src/Controller/Mantenimiento/PedidoReparacionController.php line 118

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Mantenimiento;
  3. use App\Entity\Equipos\Maquinaria;
  4. use App\Entity\Mantenimiento\Departamento;
  5. use App\Entity\Mantenimiento\PedidoReparacion;
  6. use App\Entity\Mantenimiento\SectorPlanta;
  7. use App\Form\Mantenimiento\PedidoReparacionType;
  8. use App\Repository\Mantenimiento\PedidoReparacionRepository;
  9. use Doctrine\ORM\EntityRepository;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  15. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  16. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  17. use Symfony\Component\Form\Extension\Core\Type\DateType;
  18. use Symfony\Component\Validator\Constraints\NotNull;
  19. use Knp\Snappy\Pdf;
  20. use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
  21. use Twig\Environment;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  23. use Symfony\Component\Form\FormError;
  24. use Symfony\Component\HttpFoundation\JsonResponse;
  25. /**
  26.  * @Route("/pedido/reparacion")
  27.  * @Security("is_granted('ROLE_INGRESO_ANOMALIAS') or is_granted('ROLE_CALIDAD')")
  28.  */
  29. class PedidoReparacionController extends AbstractController
  30. {
  31.     private $twig;
  32.     private $pdf;
  33.     public function __construct(Environment $twigPdf $pdf)
  34.     {
  35.         $this->twig $twig;
  36.         $this->pdf $pdf;
  37.     }
  38.     /**
  39.      * @Route("/", name="app_mantenimiento_pedido_reparacion_index", methods={"GET", "POST"})
  40.      */
  41.     public function index(Request $requestPedidoReparacionRepository $pedidoReparacionRepository): Response
  42.     {
  43.         $form $this->formFilterTreas();
  44.         if ($request->isMethod('POST')) 
  45.         {
  46.             $form->handleRequest($request);
  47.  
  48.             $data $form->getData();
  49.             return $this->render('mantenimiento/pedido_reparacion/index.html.twig', [
  50.                 'pedido_reparacions' => $pedidoReparacionRepository->pedidosReparacionUsuarioWithParameters($this->getUser(), $data),
  51.                 'form' => $form->createView()
  52.             ]);
  53.             
  54.         }
  55.         return $this->render('mantenimiento/pedido_reparacion/index.html.twig', [
  56.             'pedido_reparacions' => $pedidoReparacionRepository->pedidosReparacionUsuario($this->getUser()),
  57.             'form' => $form->createView()
  58.         ]);
  59.     }
  60.    /**
  61.      * @Route("/informe/tareas/from/{from}/to/{to}/sector/{sector}/depto/{dpto}/export", name="app_mantenimiento_pedido_reparacion_informe_tareas_export", methods={"GET", "POST"})
  62.      */
  63.     public function eportarInformeSenasa($from$to$sector$dptoRequest $requestPedidoReparacionRepository $pedidoReparacionRepository, \Doctrine\ORM\EntityManagerInterface $entityManager): Response
  64.     {
  65.         $data = [
  66.             'desde' => (new \DateTime())->setTimestamp($from),
  67.             'hasta' => (new \DateTime())->setTimestamp($to),
  68.             'sector' => $sector == 'all' null $entityManager->getRepository(SectorPlanta::class)->find($sector),
  69.             'departamento' => $dpto == 'all' null $entityManager->getRepository(Departamento::class)->find($dpto)
  70.         ];
  71.         $pendientes $pedidoReparacionRepository->pedidosReparacionUsuarioWithParametersAllPendiente($data);
  72.         $realizadosDiagramados =  $pedidoReparacionRepository->pedidosReparacionUsuarioWithParametersAll($data);
  73.         $pedido_reparacions array_merge($pendientes$realizadosDiagramados);
  74.         usort($pedido_reparacions, function($a$b) {
  75.             return $a['fechaPedido'] <=> $b['fechaPedido'];
  76.         });
  77.         $html $this->twig->render('mantenimiento/diagrama_tarea/pedidos.html.twig', [
  78.             'pedido_reparacions' => $pedido_reparacions,
  79.             'data' => $data
  80.         ]);
  81.         $filename sprintf('informe_pedidos_reparacion_%s_%s'$data['desde']->format('d_m_Y'), $data['hasta']->format('d_m_Y'));
  82.         return new PdfResponse(
  83.             $this->pdf->getOutputFromHtml($html, [
  84.                 'margin-top'    => 10,
  85.                 'margin-right'  => 10,
  86.                 'margin-bottom' => 10,
  87.                 'margin-left'   => 10,
  88.                 'encoding'      => 'utf-8',
  89.                 'page-size'     => 'A4',
  90.                 'orientation'   => 'Landscape',
  91.             ]),
  92.             $filename '.pdf'
  93.         );
  94.     }
  95.    /**
  96.      * @Route("/informe/tareas", name="app_mantenimiento_pedido_reparacion_informe_tareas", methods={"GET", "POST"})
  97.      */
  98.     public function informeSenasa(Request $requestPedidoReparacionRepository $pedidoReparacionRepository): Response
  99.     {
  100.         $form $this->formFilterInformes();
  101.         if ($request->isMethod('POST')) 
  102.         {
  103.             $form->handleRequest($request);
  104.             
  105.             if ($form->isValid()) 
  106.             {
  107.                 $data $form->getData();
  108.                 $url $this->generateUrl('app_mantenimiento_pedido_reparacion_informe_tareas_export', [
  109.                     'from' => $data['desde']->getTimestamp(),
  110.                     'to' => $data['hasta']->getTimestamp(),
  111.                     'sector' => $data['sector'] ? $data['sector']->getId() : 'all',
  112.                     'dpto' => $data['departamento'] ? $data['departamento']->getId() : 'all',
  113.                 ], 0);
  114.   
  115.                 $pendientes $pedidoReparacionRepository->pedidosReparacionUsuarioWithParametersAllPendiente($data);
  116.                 $realizadosDiagramados =  $pedidoReparacionRepository->pedidosReparacionUsuarioWithParametersAll($data);
  117.                 $pedido_reparacions array_merge($pendientes$realizadosDiagramados);
  118.                 return $this->render('mantenimiento/pedido_reparacion/informe.html.twig', [
  119.                     'pedido_reparacions' => $pedido_reparacions,
  120.                     'form' => $form->createView(), 
  121.                     'url' => $url
  122.                 ]);
  123.             }
  124.             
  125.         }
  126.         return $this->render('mantenimiento/pedido_reparacion/informe.html.twig', [
  127.             'form' => $form->createView()
  128.         ]);
  129.     }
  130.     private function formFilterInformes()
  131.     {
  132.         $user $this->getUser();
  133.         $form $this->createFormBuilder()
  134.                      ->add('sector'EntityType::class, [
  135.                                 'class' => SectorPlanta::class,
  136.                                 'required' => false,
  137.                                 'placeholder' => 'Todos',
  138.                                 'choices' => $user->getSectores()->toArray(),
  139.                                                     
  140.                             ])
  141.                      ->add('departamento'EntityType::class, [
  142.                                 'class' => Departamento::class,
  143.                                 'required' => false,
  144.                                 'placeholder' => 'Todos',
  145.                                 'choices' => $user->getDepartamentos()->toArray(),
  146.                             ])
  147.                      ->add('desde'DateType::class, [
  148.                                                         'widget' => 'single_text',
  149.                                                         'constraints' => [
  150.                                                             new NotNull(['message' => 'Este campo no puede estar vacío.']),
  151.                                                         ],
  152.                             ])
  153.                      ->add('hasta'DateType::class, [
  154.                                                         'widget' => 'single_text',
  155.                                                         'constraints' => [
  156.                                                             new NotNull(['message' => 'Este campo no puede estar vacío.']),
  157.                                                         ],
  158.                             ])
  159.                      ->getForm();
  160.         return $form;
  161.     }
  162.     private function formFilterTreas()
  163.     {
  164.         $user $this->getUser();
  165.         $form $this->createFormBuilder()
  166.                      ->add('realizado'ChoiceType::class, [
  167.                                 'choices'  => [
  168.                                     'Todas' => 'all',
  169.                                     'Si' => true,
  170.                                     'No' => false,
  171.                                 ],
  172.                                 'data' => 'all',
  173.                             ])
  174.                      ->add('diagramado'ChoiceType::class, [
  175.                                 'choices'  => [
  176.                                     'Todas' => 'all',
  177.                                     'Si' => true,
  178.                                     'No' => false,
  179.                                 ],
  180.                                 'data' => 'all',
  181.                             ])
  182.                      ->add('equipo'EntityType::class, [
  183.                                 'class' => Maquinaria::class,
  184.                                 'required' => false,
  185.                                 'placeholder' => 'Todos',
  186.                                 'query_builder' => function (EntityRepository $er) {
  187.                                                         return $er->createQueryBuilder('d')
  188.                                                                   ->andWhere('d.activo = true')
  189.                                                                   ->orderBy('d.nombre''ASC');
  190.                                                     },
  191.                                 'group_by' => function($choice$key$value) {
  192.                                                                                     if ($choice && $choice->getSector()) 
  193.                                                                                     {
  194.                                                                                         return $choice->getSector() . '';
  195.                                                                                     }
  196.                                                                                     return 'Sin sector';
  197.                                                                                 },
  198.                                                                            
  199.                             ])
  200.                      ->add('sector'EntityType::class, [
  201.                                 'class' => SectorPlanta::class,
  202.                                 'required' => false,
  203.                                 'placeholder' => 'Todos',
  204.                                 'choices' => $user->getSectores()->toArray(),
  205.                             ])
  206.                      ->add('desde'DateType::class, [
  207.                                                         'widget' => 'single_text',
  208.                                                         'data' => (new \DateTime())->modify('-1 day'),
  209.                             ])
  210.                      ->add('hasta'DateType::class, [
  211.                                                         'widget' => 'single_text',
  212.                                                         'data' => new \DateTime(),
  213.                             ])
  214.                      ->add('departamento'EntityType::class, [
  215.                                 'class' => Departamento::class,
  216.                                 'required' => false,
  217.                                 'placeholder' => 'Todos',
  218.                                 'choices' => $user->getDepartamentos()->toArray(),
  219.                             ])
  220.                      ->getForm();
  221.         return $form;
  222.     }
  223.     /**
  224.      * @Route("/new", name="app_mantenimiento_pedido_reparacion_new", methods={"GET", "POST"})
  225.      */
  226.     public function new(Request $requestPedidoReparacionRepository $pedidoReparacionRepository): Response
  227.     {
  228.         $pedidoReparacion = new PedidoReparacion();
  229.         $form $this->createForm(PedidoReparacionType::class, $pedidoReparacion, ['user' => $this->getUser()]);
  230.         $form->handleRequest($request);
  231.         if ($form->isSubmitted() && $form->isValid()) 
  232.         {
  233.             $uploadedFile $form->get('archivoImagen')->getData();
  234.             if ($uploadedFile
  235.             {
  236.                  $allowedMimeTypes = ['jpeg''JPG''JPEG''jpg''png''PNG','gif''GIF'];
  237.                  $extension $uploadedFile->getClientOriginalExtension();
  238.                 if (!in_array($extension$allowedMimeTypes)) 
  239.                 {
  240.                     $form->get('archivoImagen')->addError(new FormError('Tipo de archivo no permitido. Solo se aceptan JPEG, PNG y GIF.'));
  241.                     return $this->renderForm('mantenimiento/pedido_reparacion/new.html.twig', [
  242.                                                                                                 'pedido_reparacion' => $pedidoReparacion,
  243.                                                                                                 'form' => $form,
  244.                                                                                                 'dpto' => true
  245.                                                                                                 ]);
  246.                 }
  247.                 $originalFilename pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
  248.                 $safeFilename transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()'$originalFilename);
  249.                 $extension $uploadedFile->getClientOriginalExtension();                
  250.                 $newFilename $safeFilename.'-'.uniqid().'.'.$extension// Usamos $extension aquí
  251.                 try 
  252.                 {
  253.                     $uploadedFile->move(
  254.                         $this->getParameter('ruta_imagenes_pedidos'), 
  255.                         $newFilename
  256.                     );
  257.                 } catch (\Exception $e) {
  258.                     // ...
  259.                 }
  260.                 $pedidoReparacion->setNombreArchivoImagen($newFilename);
  261.             }
  262.             
  263.             $pedidoReparacionRepository->add($pedidoReparaciontrue);
  264.             return $this->redirectToRoute('app_mantenimiento_pedido_reparacion_index', [], Response::HTTP_SEE_OTHER);
  265.         }
  266.         return $this->renderForm('mantenimiento/pedido_reparacion/new.html.twig', [
  267.             'pedido_reparacion' => $pedidoReparacion,
  268.             'form' => $form,
  269.             'dpto' => true
  270.         ]);
  271.     }
  272.     /**
  273.      * @Route("/{id}/modificar/{dpto}/departamento", name="app_mantenimiento_pedido_reparacion_change_depto", methods={"GET", "POST"})
  274.      */
  275.     public function modificarDepartamento(PedidoReparacion $pedidoReparacionDepartamento $dptoPedidoReparacionRepository $pedidoReparacionRepository): Response
  276.     {
  277.         try
  278.         {
  279.             $pedidoReparacion->setDepartamento($dpto);
  280.             $pedidoReparacionRepository->add($pedidoReparaciontrue);
  281.             return new JsonResponse(['ok' => true]);
  282.         }
  283.         catch (\Exception $e)
  284.         {
  285.             return new JsonResponse(['ok' => false'message' => $e->getMessage()]);
  286.         }
  287.     }
  288.     /**
  289.      * @Route("/{id}", name="app_mantenimiento_pedido_reparacion_show", methods={"GET", "POST"})
  290.      */
  291.     public function show(PedidoReparacion $pedidoReparacion): Response
  292.     {
  293.         return $this->render('mantenimiento/pedido_reparacion/show.html.twig', [
  294.             'pedido_reparacion' => $pedidoReparacion,
  295.         ]);
  296.     }
  297.     /**
  298.      * @Route("/{id}/diagramar", name="app_mantenimiento_pedido_reparacion_diagramar", methods={"GET", "POST"})
  299.      */
  300.     public function diagramar(Request $requestPedidoReparacion $pedidoReparacionPedidoReparacionRepository $pedidoReparacionRepository): Response
  301.     {
  302.         if (in_array($this->getUser()->getId(), [1,11]))
  303.         {
  304.             $form $this->createForm(PedidoReparacionType::class, $pedidoReparacion, ['user' => $this->getUser(), 'depto' => true ]);
  305.         }
  306.         else
  307.         {
  308.             $form $this->createForm(PedidoReparacionType::class, $pedidoReparacion);
  309.         }
  310.      
  311.         $form->handleRequest($request);
  312.         if ($form->isSubmitted() && $form->isValid()) {
  313.             $pedidoReparacionRepository->add($pedidoReparaciontrue);
  314.             return $this->redirectToRoute('app_mantenimiento_pedido_reparacion_index', [], Response::HTTP_SEE_OTHER);
  315.         }
  316.         return $this->renderForm('mantenimiento/pedido_reparacion/edit.html.twig', [
  317.             'pedido_reparacion' => $pedidoReparacion,
  318.             'form' => $form,
  319.         ]);
  320.     }
  321.     /**
  322.      * @Route("/{id}/edit", name="app_mantenimiento_pedido_reparacion_edit", methods={"GET", "POST"})
  323.      */
  324.     public function edit(Request $requestPedidoReparacion $pedidoReparacionPedidoReparacionRepository $pedidoReparacionRepository): Response
  325.     {
  326.         $form $this->createForm(PedidoReparacionType::class, $pedidoReparacion, ['user' => $this->getUser(), 'depto' => in_array($this->getUser()->getId(), [1,11]) ]);
  327.         $form->handleRequest($request);
  328.         if ($form->isSubmitted() && $form->isValid()) 
  329.         {
  330.             $uploadedFile $form->get('archivoImagen')->getData();
  331.             if ($uploadedFile
  332.             {
  333.                  $allowedMimeTypes = ['jpeg''JPG''JPEG''jpg''png''PNG','gif''GIF'];
  334.                  $extension $uploadedFile->getClientOriginalExtension();
  335.                 if (!in_array($extension$allowedMimeTypes)) 
  336.                 {
  337.                     $form->get('archivoImagen')->addError(new FormError('Tipo de archivo no permitido. Solo se aceptan JPEG, PNG y GIF.'));
  338.                     return $this->renderForm('mantenimiento/pedido_reparacion/new.html.twig', [
  339.                                                                                                 'pedido_reparacion' => $pedidoReparacion,
  340.                                                                                                 'form' => $form,
  341.                                                                                                 'dpto' => true
  342.                                                                                                 ]);
  343.                 }
  344.                 $originalFilename pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
  345.                 $safeFilename transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()'$originalFilename);
  346.                 $extension $uploadedFile->getClientOriginalExtension();                
  347.                 $newFilename $safeFilename.'-'.uniqid().'.'.$extension// Usamos $extension aquí
  348.                 try 
  349.                 {
  350.                     $uploadedFile->move(
  351.                         $this->getParameter('ruta_imagenes_pedidos'), 
  352.                         $newFilename
  353.                     );
  354.                 } catch (\Exception $e) {
  355.                     // ...
  356.                 }
  357.                 $pedidoReparacion->setNombreArchivoImagen($newFilename);
  358.             }
  359.             $pedidoReparacionRepository->add($pedidoReparaciontrue);
  360.             return $this->redirectToRoute('app_mantenimiento_pedido_reparacion_index', [], Response::HTTP_SEE_OTHER);
  361.         }
  362.         return $this->renderForm('mantenimiento/pedido_reparacion/edit.html.twig', [
  363.             'pedido_reparacion' => $pedidoReparacion,
  364.             'form' => $form,
  365.             'dpto' => in_array($this->getUser()->getId(), [1,11]),
  366.         ]);
  367.     }
  368.     /**
  369.      * @Route("/{id}", name="app_mantenimiento_pedido_reparacion_delete", methods={"POST"})
  370.      */
  371.     public function delete(Request $requestPedidoReparacion $pedidoReparacionPedidoReparacionRepository $pedidoReparacionRepository): Response
  372.     {
  373.         if ($this->isCsrfTokenValid('delete'.$pedidoReparacion->getId(), $request->request->get('_token'))) {
  374.             $pedidoReparacionRepository->remove($pedidoReparaciontrue);
  375.         }
  376.         return $this->redirectToRoute('app_mantenimiento_pedido_reparacion_index', [], Response::HTTP_SEE_OTHER);
  377.     }
  378. }