src/Controller/higotrigo/HtFileController.php line 196

Open in your IDE?
  1. <?php
  2. namespace App\Controller\higotrigo;
  3. use App\Entity\HtExtra;
  4. use App\Entity\HtFile;
  5. use App\Entity\HtFileDeposit;
  6. use App\Entity\HtInvoice;
  7. use App\Entity\HtProforma;
  8. use App\Form\HtFileDepositType;
  9. use App\Form\HtFileType;
  10. use App\MDS\VenuesBundle\Entity\Reservation;
  11. use App\MDS\VenuesBundle\Entity\ReservationLoungeSimple;
  12. use App\Repository\HtFileRepository;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use App\Entity\User;
  17. use App\Helper\StatusHelper;
  18. use App\MDS\AvexpressBundle\Entity\AveFiles;
  19. use App\Service\HtService;
  20. use Doctrine\ORM\EntityManagerInterface;
  21. use Psr\Log\LoggerInterface;
  22. use Symfony\Component\HttpFoundation\JsonResponse;
  23. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  24. use Symfony\Component\Routing\Annotation\Route;
  25. /**
  26.  * @Route("/higotrigo/ht/file")
  27.  */
  28. class HtFileController extends AbstractController
  29. {
  30.     private HtFileRepository $htFileRepository;
  31.     private EntityManagerInterface $em;
  32.     private LoggerInterface $htLogger;
  33.     private SessionInterface $session;
  34.     public function __construct(HtFileRepository $htFileRepositoryLoggerInterface $htLoggerSessionInterface $sessionEntityManagerInterface $em) {
  35.         $this->htFileRepository $htFileRepository;
  36.         $this->htLogger $htLogger;
  37.         $this->session $session;
  38.         $this->em $em;
  39.     }
  40.     /**
  41.      * @Route("/", name="app_ht_file_index", methods={"GET"})
  42.      */
  43.     public function index(): Response
  44.     {
  45.         $htFile $this->htFileRepository->findAll();
  46.         
  47.         return $this->render('higotrigo/ht_file/index.html.twig', [
  48.             'ht_files' => $htFile,
  49.         ]);
  50.     }
  51.     /**
  52.      * @Route("/new", name="app_ht_file_new", methods={"GET", "POST"})
  53.      */
  54.     public function new(Request $request): Response
  55.     {
  56.         $htFile = new HtFile();
  57.         $form $this->createForm(HtFileType::class, $htFile);
  58.         $form->handleRequest($request);
  59.         if ($form->isSubmitted() && $form->isValid()) {
  60.             $user $this->getUser();
  61.             $htFile->setCreatedId($user);
  62.             $htFile->setUpdatedId($user);
  63.             $htFile $this->_addUserToExtras($htFile$user);
  64.             $this->htFileRepository->add($htFiletrue);
  65.             return $this->redirectToRoute('app_ht_file_edit', ['id' => $htFile->getId()], Response::HTTP_SEE_OTHER);
  66.         }
  67.         return $this->renderForm('higotrigo/ht_file/new.html.twig', [
  68.             'ht_file' => $htFile,
  69.             'invoices' => null,
  70.             'form' => $form,
  71.         ]);
  72.     }
  73.     /**
  74.      * @Route("/{id}", name="app_ht_file_show", methods={"GET"})
  75.      */
  76.     public function show(HtFile $htFile): Response
  77.     {
  78.         return $this->render('higotrigo/ht_file/show.html.twig', [
  79.             'ht_file' => $htFile,
  80.         ]);
  81.     }
  82.     /**
  83.      * @Route("/{id}/edit", name="app_ht_file_edit", methods={"GET", "POST"})
  84.      */
  85.     public function edit(Request $requestHtFile $htFileHtService $htService): Response
  86.     {
  87.         // 1. Extraemos la reserva vinculada de Venues
  88.         $reservation $htFile->getReservation();
  89. //        dd($reservation->getId());
  90.         // 2. Pasamos la reserva como opción al formulario
  91.         $form $this->createForm(HtFileType::class, $htFile, [
  92.             'reservation' => $reservation
  93.         ]);
  94.         $form->handleRequest($request);
  95.         // ... (resto del código del depósito)
  96.         $deposit = new HtFileDeposit();
  97.         $deposit->setFileId($htFile->getId());
  98.         $depositForm $this->createForm(HtFileDepositType::class, $deposit, [
  99.             'user' => $this->getUser(),
  100.             'action' => $this->generateUrl('ht_deposit_save', ['fileId' => $htFile->getId()]),
  101.             'method' => 'POST',
  102.         ]);
  103.         $invoices $this->em->getRepository(HtInvoice::class)->findByHtFile($htFile);
  104.         $proformas $this->em->getRepository(HtProforma::class)->findByHtFile($htFile->getId());
  105.         $deposits $this->em->getRepository(HtFileDeposit::class)->findByFileId($htFile->getId());
  106.         $gpFile = !empty($reservation) && $this->session->get('_modules')->mvenues $reservation null;
  107.         $aveFile = !empty($gpFile) && $this->session->get('_modules')->mav $this->em->getRepository(AveFiles::class)->findOneByReservation($gpFile) : null;
  108.         return $this->renderForm('higotrigo/ht_file/edit.html.twig', [
  109.             'ht_file' => $htFile,
  110.             'invoices' => $invoices,
  111.             'proformas' => $proformas,
  112.             'deposits' => $deposits,
  113.             'gpFile' => $gpFile,
  114.             'aveFile' => $aveFile,
  115.             'form' => $form,
  116.             'depositForm' => $depositForm,
  117.             'isNew' => true,
  118.             'totalData' => $htService->CalcTotals($htFile),
  119.         ]);
  120.     }
  121.     /**
  122.      * @Route("/{id}/edit/ajax", name="app_ht_file_edit_ajax", methods={"POST"})
  123.      */
  124.     public function editAjax(Request $requestHtFile $htFile): JsonResponse
  125.     {
  126.         $originalStatus $htFile->getStatus();
  127.         $originalClient $htFile->getClient();
  128.         $form $this->createForm(HtFileType::class, $htFile);
  129.         $form->handleRequest($request);
  130.         if ($form->isSubmitted() && $form->isValid()) {
  131.             try {
  132.                 $this->_processFileUpdate($htFile$originalStatus$originalClient);
  133.                 return $this->json([
  134.                     'msg' => 'Datos guardados correctamente',
  135.                     'data' => []
  136.                 ], JsonResponse::HTTP_OK);
  137.             } catch (\Throwable $th) {
  138.                 return $this->json([
  139.                     'title' => 'Ha ocurrido un error al guardar los datos',
  140.                     'msg' => $th->getMessage(),
  141.                     'data' => []
  142.                 ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
  143.                 
  144.                 $this->htLogger->error(sprintf(
  145.                     'Expediente %d: %s',
  146.                     $htFile->getId(),
  147.                     $th->getMessage()
  148.                 ));
  149.             }
  150.         }
  151.         
  152.         return $this->json([
  153.             'title' => 'Error al enviar los datos',
  154.             'msg' => 'Revisa el formulario',
  155.             'data' => $this->_getFormErrorsAsArray($form)
  156.         ], JsonResponse::HTTP_BAD_REQUEST);
  157.     }
  158.     /**
  159.      * @Route("/{id}", name="app_ht_file_delete", methods={"POST"})
  160.      */
  161.     public function delete(Request $requestHtFile $htFile): Response
  162.     {
  163.         if ($this->isCsrfTokenValid('delete'.$htFile->getId(), $request->request->get('_token'))) {
  164.             $this->htFileRepository->remove($htFiletrue);
  165.         }
  166.         return $this->redirectToRoute('app_ht_file_index', [], Response::HTTP_SEE_OTHER);
  167.     }
  168.     /**
  169.      * @Route("/htexternal/{id}/summary", name="app_ht_file_summary", methods={"GET", "POST"})
  170.      */
  171.     public function summary(HtFile $htFile): Response
  172.     {
  173.         $arrayElem = array();
  174.         $htItems $htFile->getHtItems();
  175.         if(!empty($htItems)) {
  176.             foreach ($htItems as $htItem) {
  177.                 $arrayEscandallos = [];
  178.                 $arrayMenus = [];
  179.                 $lounge = empty($htItem->getLoungeGp()) ? $htItem->getLoungeOther() : $htItem->getLoungeGp()->getName();
  180.                 $lounge = empty($lounge) ? 'No se ha indicado la sala' $lounge;
  181.                 if (!empty($htItem->getHtMenus())) {
  182.                     foreach (($htItem->getHtMenus()) as $htMenu){
  183.                         foreach (($htMenu->getEscandallo()) as $escan){
  184.                             $arrayEscandallos[] = array('escandallo' => $escan'nota' => $escan->getHtNotes()[0],);
  185.                         }
  186.                         $arrayMenus[] = array('htMenu' => $htMenu'arrayEscandallos' => $arrayEscandallos,);
  187.                     }
  188.                 }
  189.                 $arrayElem[$htItem->getDateStart()->format('YmdHi').str_pad($htItem->getId(), 6"0"STR_PAD_LEFT)] = array(
  190.                     'htItem'=>$htItem,
  191.                     'htMenus'=> $arrayMenus,
  192.                     'lounge'=>$lounge,
  193.                 );
  194.             }
  195.         }
  196.         ksort($arrayElem);
  197.         $reserva null$lngMont null$lngDesMont null;
  198.         $reservaIdNotLinked $htFile->getReservation();
  199.         if (!empty($reservaIdNotLinked)){ $reserva $this->em->getRepository(Reservation::class)->findOneById($reservaIdNotLinked->getId()); }
  200.         if (!empty($reserva)){
  201.             $lngMont $this->em->getRepository(ReservationLoungeSimple::class)->findOneBy( array( 'idReservation' => $reserva->getId(), 'type' => 'Montaje', ) );
  202.             $lngDesMont $this->em->getRepository(ReservationLoungeSimple::class)->findOneBy( array( 'idReservation' => $reserva->getId(), 'type' => 'Desmontaje', ) );
  203.         }
  204.         return $this->renderForm('higotrigo/ht_file/summary-htfile-pdf.html.twig', [
  205.             'ht_file' => $htFile,
  206.             'arrayElem' => $arrayElem,
  207.             'reserva' => $reserva,
  208.             'montaje' => $lngMont,
  209.             'desmontaje' => $lngDesMont,
  210.         ]);
  211.     }
  212.     /**
  213.      * Recorremos los extras para añadirle el usuario que los crea y edita
  214.      */
  215.     private function _addUserToExtras(HtFile $htFileUser $user) : HtFile {
  216.         $htItems $htFile->getHtItems();
  217.         foreach ($htItems as $htItem) {
  218.             $htFile->removeHtItem($htItem); // Borrar el item para volverlo a insertar al final con los cambios de extras
  219.             $htExtras $htItem->getHtExtras();
  220.             foreach ($htExtras as $htExtra) {
  221.                 $htItem->removeHtExtra($htExtra);
  222.                 if($htExtra->getCreatedId() == NULL){
  223.                     $htExtra->setCreatedId($user);
  224.                 }
  225.                 $htExtra->setUpdatedId($user);
  226.                 $htItem->addHtExtra($htExtra);
  227.             }
  228.             $htFile->addHtItem($htItem);
  229.         }
  230.         return $htFile;
  231.     }
  232.     /**
  233.      * Comprobar si el htFile tiene htItems y si estos tienen htExtras para añadirselos para que la vista funcione bien.
  234.      */
  235.     private function _addHtItemAndHtExtra(HtFile $htFile) : HtFile {
  236.         $htItems $htFile->getHtItems();
  237.         if($htItems){
  238.             foreach ($htItems as $htItem) {
  239.                 $htExtras $htItem->getHtExtras();
  240.                 if($htExtras === null || $htExtras->isEmpty()){
  241.                     $htFile->removeHtItem($htItem);
  242.                     $htExtra = new HtExtra();
  243.                     $htItem->addHtExtra($htExtra);
  244.                     $htFile->addHtItem($htItem);
  245.                 }
  246.             }
  247.         }
  248.         return $htFile;
  249.     }
  250.     /**
  251.      * Procesa la actualización de la entidad HtFile (Auditoría, Asignación de usuario y Persistencia).
  252.      */
  253.     private function _processFileUpdate(HtFile $htFilestring $originalStatus, ?object $originalClient): void
  254.     {
  255.         // Si el estado es facturado pero no tiene factura, no se permite guardar
  256.         $invoices $this->em->getRepository(HtInvoice::class)->findByHtFile($htFile);
  257.         if ($htFile->getStatus() === StatusHelper::STATUS_HT['Facturado'] && !$invoices) {
  258.             throw new \Exception('No se puede establecer el estado "Facturado" sin tener al menos una factura asociada');
  259.         }
  260.         // Controlar que las fechas de inicio es menor que la de fin
  261.         // if ($htFile->getDateStart() && $htFile->getDateEnd() && $htFile->getDateStart() > $htFile->getDateEnd()) {
  262.         //     throw new \Exception('La fecha de inicio no puede ser mayor que la fecha de fin');
  263.         // }
  264.         
  265.         if ($originalStatus !== $htFile->getStatus()) {
  266.             $this->htLogger->info(sprintf(
  267.                 'Expediente %d: status cambiado de "%s" a "%s"',
  268.                 $htFile->getId(),
  269.                 $originalStatus,
  270.                 $htFile->getStatus()
  271.             ));
  272.         }
  273.         if ($originalClient !== $htFile->getClient()) {
  274.             $this->htLogger->info(sprintf(
  275.                 'Expediente %d: cliente cambiado de "%s" a "%s". El usuario que realiza el cambio es %s',
  276.                 $htFile->getId(),
  277.                 $originalClient $originalClient->getName() : 'N/A',
  278.                 $htFile->getClient() ? $htFile->getClient()->getName() : 'N/A',
  279.                 $this->getUser() ? $this->getUser()->getEmail() : 'unknown'
  280.             ));
  281.         }
  282.         $user $this->getUser();
  283.         $htFile->setUpdatedId($user);
  284.         $htFile $this->_addUserToExtras($htFile$user);
  285.         $this->htFileRepository->add($htFiletrue);
  286.     }
  287.     private function _getFormErrorsAsArray(\Symfony\Component\Form\FormInterface $form): array
  288.     {
  289.         $errors = [];
  290.         // Errores globales del formulario (como el Callback que pusimos en la entidad)
  291.         foreach ($form->getErrors() as $error) {
  292.             $errors[] = $error->getMessage();
  293.         }
  294.         // Errores específicos de cada campo
  295.         foreach ($form->all() as $child) {
  296.             if (!$child->isValid()) {
  297.                 foreach ($child->getErrors(true) as $error) {
  298.                     // Guardamos el error con el nombre del campo para identificarlo en el JS
  299.                     $errors[$child->getName()] = $error->getMessage();
  300.                 }
  301.             }
  302.         }
  303.         return $errors;
  304.     }
  305. }