src/Controller/DashController.php line 43

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Documentation;
  4. use App\Entity\DocumentType;
  5. use App\Entity\EventLog;
  6. use App\Entity\File;
  7. use App\Entity\Plant;
  8. use App\Entity\StatusType;
  9. use App\Entity\Supplier;
  10. use App\Entity\SupplierStatus;
  11. use App\Entity\Tender;
  12. use App\Entity\TenderStatus;
  13. use App\Entity\User;
  14. use App\Entity\UserSupervisor;
  15. use App\Repository\DocumentTypeRepository;
  16. use Doctrine\ORM\EntityManagerInterface;
  17. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  18. use Symfony\Component\HttpFoundation\JsonResponse;
  19. use Symfony\Component\HttpFoundation\RedirectResponse;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpFoundation\Response;
  22. use Symfony\Component\Routing\Annotation\Route;
  23. class DashController extends AbstractController
  24. {
  25.     private $entityManager;
  26.     public function __construct(EntityManagerInterface $entityManager)
  27.     {
  28.         $this->entityManager $entityManager;
  29.     }
  30.     /**
  31.      * @Route("/", name="app_dash")
  32.      */
  33.     public function dash(Request $request): Response
  34.     {
  35.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  36.         $em $this->entityManager;
  37.         $user $this->getUser();
  38.         if ($user->isActive() == 0) {
  39.             $this->addFlash(
  40.                 'error',
  41.                 'Su cuenta fue desactivada'
  42.             );
  43.             return $this->redirectToRoute('app_login');
  44.         }
  45.         //$url = 'app_start';
  46.         //$url = 'app_dash_supplier';
  47.         if ($this->isGranted('ROLE_SUPPLIER')) {
  48.             $supplierExist $em->getRepository(Supplier::class)->findOneBy(['active' => 1'user' => $user]);
  49.             if (!$supplierExist) {
  50.                 $this->addFlash('error''El usuario no es válido.');
  51.                 return new RedirectResponse($request->headers->get('referer') ?? $this->urlGenerator->generate('app_login'));
  52.             }
  53.             $situationTypeUserCurrent $em->getRepository(SupplierStatus::class)->findOneBy(['endDate' => null'supplier' => $supplierExist]);
  54.         }
  55.         $rut $request->get('rut');
  56.         if ($this->isGranted('ROLE_SUPPLIER')) {
  57.             if ($situationTypeUserCurrent->getSituationType()->getId() != 2) {
  58.                 return $this->redirectToRoute('view_supplier', ['id' => $supplierExist->getId()]);
  59.             } else {
  60.                 return $this->redirectToRoute('app_supplier_tender');
  61.             }
  62.         } elseif ($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_SUPER_ADMIN')) {
  63.             return $this->redirectToRoute('app_start');
  64.         } elseif ($this->isGranted('ROLE_TENDERER')) {
  65.             return $this->redirectToRoute('app_tenderer_dash');
  66.         } elseif ($this->isGranted('ROLE_AUDITOR')) {
  67.             return $this->redirectToRoute('app_document_index');
  68.         } elseif ($this->isGranted('ROLE_SUPERVISOR_TENDER')) {
  69.             return $this->redirectToRoute('app_tenderer_dash');
  70.         } elseif ($this->isGranted('ROLE_AUDITORIA_INTERNA')) {
  71.             return $this->redirectToRoute('app_supplier_interno_index');
  72.         } else {
  73.             return $this->redirectToRoute('app_supplier_index');
  74.         }
  75.     }
  76.     /**
  77.      * @Route("/tenderer/dash", name="app_tenderer_dash")
  78.      */
  79.     public function auditorDash(Request $request): Response
  80.     {
  81.         $em $this->entityManager;
  82.         $active true;
  83.         $role 'ROLE_TENDERER';
  84.         $tenderer $em->getRepository(User::class)->findAllTendered($active$role);
  85.         $eventLog $em->getRepository(EventLog::class)->findBy(
  86.             ['indView' => 1],
  87.             ['createdAt' => 'DESC'],
  88.             8,
  89.         );
  90.         return $this->render('dash/indexTenderer.html.twig', [
  91.             'tendered' => $tenderer,
  92.             'eventLogs' => $eventLog,
  93.         ]);
  94.     }
  95.     /**
  96.      * @Route("/start", name="app_start")
  97.      */
  98.     public function index(Request $request): Response
  99.     {
  100.         $em $this->entityManager;
  101.         $active true;
  102.         $role 'ROLE_TENDERER';
  103.         $tenderer $em->getRepository(User::class)->findAllTendered($active$role);
  104.         $eventLog $em->getRepository(EventLog::class)->findBy(
  105.             ['indView' => 1],
  106.             ['createdAt' => 'DESC'],
  107.             8,
  108.         );
  109.         return $this->render('dash/index.html.twig', [
  110.             'tendered' => $tenderer,
  111.             'eventLogs' => $eventLog,
  112.         ]);
  113.     }
  114.     /**
  115.      * @Route("/get-items-tender", name="get_items_tender", methods={"GET"})
  116.      */
  117.     public function getItemsTender(Request $request): JsonResponse
  118.     {
  119.         $em $this->entityManager;
  120.         $user $this->getUser();
  121.         $roles $user $user->getRoles() : [];
  122.         $isSupervisorTender in_array('ROLE_SUPERVISOR_TENDER'$roles);
  123.         $isRoleAdmin = !empty(array_intersect(['ROLE_ADMIN''ROLE_SUPER_ADMIN'], $roles));
  124.         $isTenderer in_array('ROLE_TENDERER'$roles);
  125.         $startDate $request->get('dateStart') ? new \DateTime($request->get('dateStart')) : null;
  126.         $endDate $request->get('dateEnd') ? new \DateTime($request->get('dateEnd')) : null;
  127.         $tendered $request->get('tendered');
  128.         // Si el usuario es un tenderer y no se ha especificado $tendered, se asigna su ID
  129.         if ($isTenderer) {
  130.             $tendered $user->getId();
  131.         }
  132.         $countTenderForStatus $em->getRepository(StatusType::class)->countTenderForStatus($isRoleAdmin$user$isSupervisorTender$startDate$endDate$tendered);
  133.         $tendersForStatus $em->getRepository(Tender::class)->getTendersForStatus($isRoleAdmin$user$isSupervisorTender$startDate$endDate$tendered);
  134.         return $this->json(['countTenderForStatus' => $countTenderForStatus'tendersForStatus' => $tendersForStatus]);
  135.     }
  136.     /**
  137.      * @Route("/get-items-timeline", name="get_items_timeline", methods={"GET"})
  138.      */
  139.     public function getItemsTimeline(): JsonResponse
  140.     {
  141.         $em $this->entityManager;
  142.         $eventLog $em->getRepository(EventLog::class)->eventLogToday();
  143.         $itemsTimeline = [];
  144.         foreach ($eventLog as $item) {
  145.             $itemsTimeline[] = [
  146.                 'time' => $item->getCreatedAt()->format('H:i'),
  147.                 'badgeClass' => $item->getTypeEventLog()->getCssColor(),
  148.                 'content' => $item->getDescription()
  149.             ];
  150.         }
  151.         usort($itemsTimeline, function ($a$b) {
  152.             return strtotime($b['time']) - strtotime($a['time']);
  153.         });
  154.         return $this->json($itemsTimeline);
  155.     }
  156.     /**
  157.      * @Route("/ajax/getdata", name="ajax_get_data")
  158.      */
  159.     public function getData(): JsonResponse
  160.     {
  161.         $em $this->entityManager;
  162.         $progressData = [];
  163.         // Función de comparación para ordenar por la fecha más cercana
  164.         usort($progressData, function ($a$b) {
  165.             return strtotime($a['targetDate']) - strtotime($b['targetDate']);
  166.         });
  167.         return new JsonResponse($progressData);
  168.     }
  169.     /**
  170.      * @Route("/certificationsChart", name="certifications_chart", methods={"GET"})
  171.      */
  172.     public function certificationsChart(): JsonResponse
  173.     {
  174.         $em $this->entityManager;
  175.         $allPlants $em->getRepository(Plant::class)->findBy(['active' => 1]);
  176.         $categories = [];
  177.         foreach ($allPlants as $plant) {
  178.             $categories[] = $plant->getName();
  179.         }
  180.         $data = [
  181.             'categories' => $categories,
  182.         ];
  183.         return new JsonResponse($data);
  184.     }
  185.     /**
  186.      * @Route("/document", name="app_document_index", methods={"GET"})
  187.      */
  188.     public function document(DocumentTypeRepository $docRepoRequest $request): Response
  189.     {
  190.         $em $this->entityManager;
  191.         $user $this->getUser();
  192.         $userId $user->getUserIdentifier();
  193.         $type $request->get('type');
  194.         if (
  195.             $this->isGranted('ROLE_ADMIN') ||
  196.             $this->isGranted('ROLE_SUPER_ADMIN')
  197.         ) {
  198.             $qualityUserId null;
  199.         } else {
  200.             $qualityUserId $userId;
  201.         }
  202.         $documentTypes $em->getRepository(DocumentType::class)->getDocumentTypesByUser($qualityUserId);
  203.         $papaMapping $em->getRepository(UserSupervisor::class)
  204.             ->findOneBy(['supervisor' => $user]);
  205.         if ($papaMapping) {
  206.             $papaId $papaMapping->getUser()->getId();
  207.             $documentTypesPapa $docRepo->getDocumentTypesByUser($papaId);
  208.             $allById = [];
  209.             foreach ($documentTypes as $dt) {
  210.                 $allById[$dt->getId()] = $dt;
  211.             }
  212.             foreach ($documentTypesPapa as $dt) {
  213.                 $allById[$dt->getId()] = $dt;
  214.             }
  215.             $documentTypes array_values($allById);
  216.         }
  217.         $documents = [];
  218.         foreach ($documentTypes as $documentType) {
  219.             if ($type == null) {
  220.                 $documentations $em->getRepository(Documentation::class)->findBy([
  221.                     'documentType' => $documentType,
  222.                     'approvedInd' => $type
  223.                 ],['id' => 'DESC']);
  224.             } else {
  225.                 $documentations $em->getRepository(Documentation::class)->findBy([
  226.                     'documentType' => $documentType,
  227.                     'entityUser' => $this->getUser()->getUserIdentifier(),
  228.                     'approvedInd' => $type
  229.                 ],['id' => 'DESC']);
  230.             }
  231.             if ($documentations) {
  232.                 foreach ($documentations as $documentation) {
  233.                     if (!$documentType->getQualityUser() && $documentation && $documentation->isApprovedInd() === null) {
  234.                         $documentation->setApprovedInd(true);
  235.                         $em->persist($documentation);
  236.                         $em->flush();
  237.                     }
  238.                     $documentData $this->formatDocument($documentType$documentation);
  239.                     $qualityUser $documentType->getQualityUser();
  240.                     $supervisorId null;
  241.                     if ($qualityUser) {
  242.                         $supervisor $em->getRepository(UserSupervisor::class)->findOneBy(['user' => $qualityUser]);
  243.                         if ($supervisor && $supervisor->getSupervisor()) {
  244.                             $supervisorId $supervisor->getSupervisor()->getId();
  245.                         }
  246.                     }
  247.                     $canApproveReject false;
  248.                     if ($documentation && $documentation->isApprovedInd() == null) {
  249.                         if ($userId == ($qualityUser $qualityUser->getId() : null) || $userId == $supervisorId) {
  250.                             $canApproveReject true;
  251.                         } elseif ($qualityUserId == null) {
  252.                             $canApproveReject true;
  253.                         }
  254.                     }
  255.                     $documentData['canApproveReject'] = $canApproveReject;
  256.                     if ($documentation->getSupplier()) {
  257.                         $documentData['supplierName'] = $documentation->getSupplier()->getSupplierName();
  258.                         $documents[] = $documentData;
  259.                     }
  260.                 }
  261.             }
  262.         }
  263.         if ($type == null) {
  264.             $type = -1;
  265.         }
  266.         return $this->render('document/index.html.twig', [
  267.                 'documents' => $documents,
  268.                 'type' => $type,
  269.             ]
  270.         );
  271.     }
  272.     /**
  273.      * Formatea los datos del documento para la respuesta JSON
  274.      */
  275.     private function formatDocument(DocumentType $documentType, ?Documentation $documentation): array
  276.     {
  277.         return [
  278.             'id' => $documentation->getId(),
  279.             'name' => $documentType->getName(),
  280.             'isUploaded' => (bool)$documentation,
  281.             'documentationId' => $documentation $documentation->getId() : null,
  282.             'endValidityDate' => $documentation && $documentation->getEndValidityDate()
  283.                 ? $documentation->getEndValidityDate()->format('Y-m-d\TH:i')
  284.                 : null,
  285.             'filePath' => $documentation && $documentation->getFile() ? $this->generateUrl('document_file', ['id' => $documentation->getFile()->getId()]) : null,
  286.             'fileType' => $documentation && $documentation->getFile() ? $documentation->getFile()->getType() : null,
  287.             'approvedInd' => $documentation $documentation->isApprovedInd() : null,
  288.             'isApproved' => $documentation ? ($documentation->isApprovedInd() === true) : false,
  289.             'isRejected' => $documentation ? ($documentation->isApprovedInd() === false) : false,
  290.             'rejectedReason' => $documentation $documentation->getObservationTxt() : null,
  291.             'newFileUploaded' => false,
  292.             'qualityUserId' => $documentType->getQualityUser() ? $documentType->getQualityUser()->getId() : null,
  293.             'fileId' => $documentation && $documentation->getFile() ? $documentation->getFile()->getId() : null,
  294.         ];
  295.     }
  296.     /**
  297.      * @Route("/check-email-exists", name="check_email_exists", methods={"POST"})
  298.      */
  299.     public function checkEmailExists(Request $request): JsonResponse
  300.     {
  301.         $email $request->request->get('email');
  302.         $entityManager $this->getDoctrine()->getManager();
  303.         $userRepository $entityManager->getRepository(User::class);
  304.         $user $userRepository->findOneBy(['email' => $email]);
  305.         if ($user) {
  306.             return new JsonResponse(['status' => 'exists']);
  307.         } else {
  308.             return new JsonResponse(['status' => 'not_exists']);
  309.         }
  310.     }
  311.     /**
  312.      * @Route("/search/dni", name="search_dni", methods={"GET"})
  313.      */
  314.     public function searchDni(Request $requestEntityManagerInterface $em): JsonResponse
  315.     {
  316.         $dni $request->get('dni');
  317.         $supplier $em->getRepository(Supplier::class)->findOneBy(['supplierDni' => $dni]);
  318.         return new JsonResponse(['exists' => $supplier !== null]);
  319.     }
  320. }