<?php
namespace App\Controller;
use App\Entity\Documentation;
use App\Entity\DocumentType;
use App\Entity\EventLog;
use App\Entity\File;
use App\Entity\Plant;
use App\Entity\StatusType;
use App\Entity\Supplier;
use App\Entity\SupplierStatus;
use App\Entity\Tender;
use App\Entity\TenderStatus;
use App\Entity\User;
use App\Entity\UserSupervisor;
use App\Repository\DocumentTypeRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class DashController extends AbstractController
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* @Route("/", name="app_dash")
*/
public function dash(Request $request): Response
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$em = $this->entityManager;
$user = $this->getUser();
if ($user->isActive() == 0) {
$this->addFlash(
'error',
'Su cuenta fue desactivada'
);
return $this->redirectToRoute('app_login');
}
//$url = 'app_start';
//$url = 'app_dash_supplier';
if ($this->isGranted('ROLE_SUPPLIER')) {
$supplierExist = $em->getRepository(Supplier::class)->findOneBy(['active' => 1, 'user' => $user]);
if (!$supplierExist) {
$this->addFlash('error', 'El usuario no es válido.');
return new RedirectResponse($request->headers->get('referer') ?? $this->urlGenerator->generate('app_login'));
}
$situationTypeUserCurrent = $em->getRepository(SupplierStatus::class)->findOneBy(['endDate' => null, 'supplier' => $supplierExist]);
}
$rut = $request->get('rut');
if ($this->isGranted('ROLE_SUPPLIER')) {
if ($situationTypeUserCurrent->getSituationType()->getId() != 2) {
return $this->redirectToRoute('view_supplier', ['id' => $supplierExist->getId()]);
} else {
return $this->redirectToRoute('app_supplier_tender');
}
} elseif ($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_SUPER_ADMIN')) {
return $this->redirectToRoute('app_start');
} elseif ($this->isGranted('ROLE_TENDERER')) {
return $this->redirectToRoute('app_tenderer_dash');
} elseif ($this->isGranted('ROLE_AUDITOR')) {
return $this->redirectToRoute('app_document_index');
} elseif ($this->isGranted('ROLE_SUPERVISOR_TENDER')) {
return $this->redirectToRoute('app_tenderer_dash');
} elseif ($this->isGranted('ROLE_AUDITORIA_INTERNA')) {
return $this->redirectToRoute('app_supplier_interno_index');
} else {
return $this->redirectToRoute('app_supplier_index');
}
}
/**
* @Route("/tenderer/dash", name="app_tenderer_dash")
*/
public function auditorDash(Request $request): Response
{
$em = $this->entityManager;
$active = true;
$role = 'ROLE_TENDERER';
$tenderer = $em->getRepository(User::class)->findAllTendered($active, $role);
$eventLog = $em->getRepository(EventLog::class)->findBy(
['indView' => 1],
['createdAt' => 'DESC'],
8,
);
return $this->render('dash/indexTenderer.html.twig', [
'tendered' => $tenderer,
'eventLogs' => $eventLog,
]);
}
/**
* @Route("/start", name="app_start")
*/
public function index(Request $request): Response
{
$em = $this->entityManager;
$active = true;
$role = 'ROLE_TENDERER';
$tenderer = $em->getRepository(User::class)->findAllTendered($active, $role);
$eventLog = $em->getRepository(EventLog::class)->findBy(
['indView' => 1],
['createdAt' => 'DESC'],
8,
);
return $this->render('dash/index.html.twig', [
'tendered' => $tenderer,
'eventLogs' => $eventLog,
]);
}
/**
* @Route("/get-items-tender", name="get_items_tender", methods={"GET"})
*/
public function getItemsTender(Request $request): JsonResponse
{
$em = $this->entityManager;
$user = $this->getUser();
$roles = $user ? $user->getRoles() : [];
$isSupervisorTender = in_array('ROLE_SUPERVISOR_TENDER', $roles);
$isRoleAdmin = !empty(array_intersect(['ROLE_ADMIN', 'ROLE_SUPER_ADMIN'], $roles));
$isTenderer = in_array('ROLE_TENDERER', $roles);
$startDate = $request->get('dateStart') ? new \DateTime($request->get('dateStart')) : null;
$endDate = $request->get('dateEnd') ? new \DateTime($request->get('dateEnd')) : null;
$tendered = $request->get('tendered');
// Si el usuario es un tenderer y no se ha especificado $tendered, se asigna su ID
if ($isTenderer) {
$tendered = $user->getId();
}
$countTenderForStatus = $em->getRepository(StatusType::class)->countTenderForStatus($isRoleAdmin, $user, $isSupervisorTender, $startDate, $endDate, $tendered);
$tendersForStatus = $em->getRepository(Tender::class)->getTendersForStatus($isRoleAdmin, $user, $isSupervisorTender, $startDate, $endDate, $tendered);
return $this->json(['countTenderForStatus' => $countTenderForStatus, 'tendersForStatus' => $tendersForStatus]);
}
/**
* @Route("/get-items-timeline", name="get_items_timeline", methods={"GET"})
*/
public function getItemsTimeline(): JsonResponse
{
$em = $this->entityManager;
$eventLog = $em->getRepository(EventLog::class)->eventLogToday();
$itemsTimeline = [];
foreach ($eventLog as $item) {
$itemsTimeline[] = [
'time' => $item->getCreatedAt()->format('H:i'),
'badgeClass' => $item->getTypeEventLog()->getCssColor(),
'content' => $item->getDescription()
];
}
usort($itemsTimeline, function ($a, $b) {
return strtotime($b['time']) - strtotime($a['time']);
});
return $this->json($itemsTimeline);
}
/**
* @Route("/ajax/getdata", name="ajax_get_data")
*/
public function getData(): JsonResponse
{
$em = $this->entityManager;
$progressData = [];
// Función de comparación para ordenar por la fecha más cercana
usort($progressData, function ($a, $b) {
return strtotime($a['targetDate']) - strtotime($b['targetDate']);
});
return new JsonResponse($progressData);
}
/**
* @Route("/certificationsChart", name="certifications_chart", methods={"GET"})
*/
public function certificationsChart(): JsonResponse
{
$em = $this->entityManager;
$allPlants = $em->getRepository(Plant::class)->findBy(['active' => 1]);
$categories = [];
foreach ($allPlants as $plant) {
$categories[] = $plant->getName();
}
$data = [
'categories' => $categories,
];
return new JsonResponse($data);
}
/**
* @Route("/document", name="app_document_index", methods={"GET"})
*/
public function document(DocumentTypeRepository $docRepo, Request $request): Response
{
$em = $this->entityManager;
$user = $this->getUser();
$userId = $user->getUserIdentifier();
$type = $request->get('type');
if (
$this->isGranted('ROLE_ADMIN') ||
$this->isGranted('ROLE_SUPER_ADMIN')
) {
$qualityUserId = null;
} else {
$qualityUserId = $userId;
}
$documentTypes = $em->getRepository(DocumentType::class)->getDocumentTypesByUser($qualityUserId);
$papaMapping = $em->getRepository(UserSupervisor::class)
->findOneBy(['supervisor' => $user]);
if ($papaMapping) {
$papaId = $papaMapping->getUser()->getId();
$documentTypesPapa = $docRepo->getDocumentTypesByUser($papaId);
$allById = [];
foreach ($documentTypes as $dt) {
$allById[$dt->getId()] = $dt;
}
foreach ($documentTypesPapa as $dt) {
$allById[$dt->getId()] = $dt;
}
$documentTypes = array_values($allById);
}
$documents = [];
foreach ($documentTypes as $documentType) {
if ($type == null) {
$documentations = $em->getRepository(Documentation::class)->findBy([
'documentType' => $documentType,
'approvedInd' => $type
],['id' => 'DESC']);
} else {
$documentations = $em->getRepository(Documentation::class)->findBy([
'documentType' => $documentType,
'entityUser' => $this->getUser()->getUserIdentifier(),
'approvedInd' => $type
],['id' => 'DESC']);
}
if ($documentations) {
foreach ($documentations as $documentation) {
if (!$documentType->getQualityUser() && $documentation && $documentation->isApprovedInd() === null) {
$documentation->setApprovedInd(true);
$em->persist($documentation);
$em->flush();
}
$documentData = $this->formatDocument($documentType, $documentation);
$qualityUser = $documentType->getQualityUser();
$supervisorId = null;
if ($qualityUser) {
$supervisor = $em->getRepository(UserSupervisor::class)->findOneBy(['user' => $qualityUser]);
if ($supervisor && $supervisor->getSupervisor()) {
$supervisorId = $supervisor->getSupervisor()->getId();
}
}
$canApproveReject = false;
if ($documentation && $documentation->isApprovedInd() == null) {
if ($userId == ($qualityUser ? $qualityUser->getId() : null) || $userId == $supervisorId) {
$canApproveReject = true;
} elseif ($qualityUserId == null) {
$canApproveReject = true;
}
}
$documentData['canApproveReject'] = $canApproveReject;
if ($documentation->getSupplier()) {
$documentData['supplierName'] = $documentation->getSupplier()->getSupplierName();
$documents[] = $documentData;
}
}
}
}
if ($type == null) {
$type = -1;
}
return $this->render('document/index.html.twig', [
'documents' => $documents,
'type' => $type,
]
);
}
/**
* Formatea los datos del documento para la respuesta JSON
*/
private function formatDocument(DocumentType $documentType, ?Documentation $documentation): array
{
return [
'id' => $documentation->getId(),
'name' => $documentType->getName(),
'isUploaded' => (bool)$documentation,
'documentationId' => $documentation ? $documentation->getId() : null,
'endValidityDate' => $documentation && $documentation->getEndValidityDate()
? $documentation->getEndValidityDate()->format('Y-m-d\TH:i')
: null,
'filePath' => $documentation && $documentation->getFile() ? $this->generateUrl('document_file', ['id' => $documentation->getFile()->getId()]) : null,
'fileType' => $documentation && $documentation->getFile() ? $documentation->getFile()->getType() : null,
'approvedInd' => $documentation ? $documentation->isApprovedInd() : null,
'isApproved' => $documentation ? ($documentation->isApprovedInd() === true) : false,
'isRejected' => $documentation ? ($documentation->isApprovedInd() === false) : false,
'rejectedReason' => $documentation ? $documentation->getObservationTxt() : null,
'newFileUploaded' => false,
'qualityUserId' => $documentType->getQualityUser() ? $documentType->getQualityUser()->getId() : null,
'fileId' => $documentation && $documentation->getFile() ? $documentation->getFile()->getId() : null,
];
}
/**
* @Route("/check-email-exists", name="check_email_exists", methods={"POST"})
*/
public function checkEmailExists(Request $request): JsonResponse
{
$email = $request->request->get('email');
$entityManager = $this->getDoctrine()->getManager();
$userRepository = $entityManager->getRepository(User::class);
$user = $userRepository->findOneBy(['email' => $email]);
if ($user) {
return new JsonResponse(['status' => 'exists']);
} else {
return new JsonResponse(['status' => 'not_exists']);
}
}
/**
* @Route("/search/dni", name="search_dni", methods={"GET"})
*/
public function searchDni(Request $request, EntityManagerInterface $em): JsonResponse
{
$dni = $request->get('dni');
$supplier = $em->getRepository(Supplier::class)->findOneBy(['supplierDni' => $dni]);
return new JsonResponse(['exists' => $supplier !== null]);
}
}