src/Controller/AbsenceController.php line 68

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Interface\Services\AccountantInterface;
  4. use App\Interface\UseCase\VacationListInterface;
  5. use App\Interface\UseCase\Absence\AbsenceInterface;
  6. use Blh\Bundle\Entity\Country;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\Routing\Annotation\Route;
  10. use Blh\Bundle\Entity\EmployeeAbsenceType;
  11. use Blh\Bundle\Entity\EmployeeVacationTaken;
  12. use Blh\Bundle\Entity\Employee;
  13. use Blh\Bundle\Entity\VwEmployeeVacation;
  14. use Blh\Bundle\Entity\EntityContract;
  15. use Ramsey\Uuid\Uuid;
  16. use Doctrine\ORM\EntityManagerInterface;
  17. use Symfony\Component\HttpFoundation\RedirectResponse;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\JsonResponse;
  20. use Symfony\Component\Workflow\Registry;
  21. use Blh\Bundle\Handler\MailHandler;
  22. use Blh\Bundle\Entity\Email;
  23. use Blh\Bundle\Handler\FileHandler;
  24. use Blh\Bundle\Repository\FileCategoryRepository;
  25. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  26. use Blh\Bundle\Entity\EmployeeVacationTakenFile;
  27. use Blh\Bundle\Entity\File;
  28. use Blh\Bundle\Repository\VwEmployeeVacationRepository;
  29. use Blh\Bundle\Repository\EmployeeRepository;
  30. #[Route('/absence'name'absence_')]
  31. class AbsenceController extends AbstractController
  32. {
  33.     private  $AbsencesRequireFile = [1,2]; // estos son los ids de tipos de ausencia que requieren archivos anexos.
  34.     public function __construct(
  35.         private readonly EntityManagerInterface $entityManager,
  36.         private readonly Registry $workflow,
  37.         private readonly MailHandler $mailHandler,
  38.         private readonly ParameterBagInterface $parameters,
  39.         private readonly AccountantInterface $accountant
  40.     ) {}
  41.     #[Route('/list'name'index')]
  42.     public function index(): Response
  43.     {
  44.         
  45.         $employeeId $this->getUser()->getEmployee()->getId();
  46.         $contractType $this->entityManager->getRepository(Employee::class)->hasContractActive($employeeId)[0]->getContractType($employeeId);
  47.         return $this->render(
  48.             'absence/index.html.twig'
  49.             ['contractTypeCode' => $contractType->getCode(),
  50.                          'absenceTypes' => $this->entityManager->getRepository(EmployeeAbsenceType::class)->findBy(['isActive' => 1]),
  51.             
  52.         ]);
  53.     }
  54.     #[Route('/report'name'report')]
  55.     public function report(): Response
  56.     {
  57.         return $this->render('absence/report.html.twig');
  58.     }
  59.     #[Route('/register'name'register',  methods: ['GET''POST'])]
  60.     public function registerAction(EmployeeRepository  $employeeRepository): Response
  61.     {
  62.         //Buscamos si el usuario tiene supervisor.
  63.         $immediateBoss $this->getUser()->getEmployee()->getImmediateBoss();
  64.         
  65.         $contract null;
  66.         $whitSupervisor true;
  67.         $whitAccountant 'yes';
  68.         // Si tiene supervisor verificamos que tenga contrato activo y que no este de vacaciones.
  69.         if ($immediateBoss) {
  70.             
  71.             $supervisorId $this->getUser()->getEmployee()->getImmediateBoss()->getId();
  72.             
  73.             $contract $this->entityManager->getRepository(Employee::class)->hasContractActive($supervisorId);
  74.             $inVacation =  $this->entityManager->getRepository(Employee::class)->isInVacation($supervisorId);
  75.             // Si tiene contrato activo obtenemos los nombres.
  76.             if ($contract) {
  77.                 $supervisor $contract[0]->getEmployee();
  78.                 $supervisorName $supervisor->getFirstName() . " " $supervisor->getSurname();
  79.             }
  80.             if (!$contract) {
  81.                 $supervisorName "No Supervisor with active contract";
  82.                 $whitSupervisor false;
  83.             }
  84.             if ($inVacation) {
  85.                 $supervisorName "Supervisor is in vacation currently";
  86.                 $whitSupervisor false;
  87.             }
  88.         }
  89.         if (!$immediateBoss) {
  90.             $supervisorName "No associated supervisor";
  91.             $whitSupervisor false;
  92.         }
  93.         //Verificamos si el pais de donde es el empelado tiene contador. 
  94.         $employee =  $this->getUser()->getEmployee();
  95.         $contract $this->entityManager->getRepository(Employee::class)->hasContractActive($employee->getId());
  96.         // Esta seccion de codigo es para determinar el pais del empleado y buscar el contador correspondiente.
  97.         $contractEntity $this->entityManager->getRepository(EntityContract::class)->findBy(['contract' => $contract[0]->getId(), 'isPrincipal' => 1]);
  98.         // Buscamos quien es el accountan del pais donde tiene contrato el solicitante de ausencia.
  99.         $Accountant $this->accountant->getAccountant($contractEntity[0]);
  100.        
  101.         //En caso que no hayan contadores se coloca la condicion, para dejar un arreglo vacio.
  102.         $accountantEmployeeIds = ($Accountant) ? implode(','array_column($Accountant'employeeId')) : [];
  103.         $accountantActive $this->entityManager->getRepository(Employee::class)->hasContractActive($accountantEmployeeIds);
  104.         
  105.         $accountantInVacation $this->entityManager->getRepository(Employee::class)->isInVacation($accountantEmployeeIds);
  106.         //Se indica que no tiene contador asociado si nadie tiene la posicion correspondiente
  107.         //O (hay contador con vacaciones y la cantidad de contadores que existe para dicho pais, es igual a la cantidad de sulicitudes actuales de vacaciones)
  108.         if (!$accountantActive || ($accountantInVacation  && count($accountantInVacation) == count($Accountant))) {
  109.             $whitAccountant 'no';
  110.         }
  111.         $employeeVacations $this->entityManager->getRepository(VwEmployeeVacation::class)->find($employee->getId());
  112.         $employeeVacationTaken $employeeVacations?->getVacationTaken();
  113.         $employeeVacationDays = empty($employeeVacations) ? 100 $employeeVacations->getVacationDays();
  114.         $vacationDaysPending $employeeVacationDays $employeeVacationTaken;
  115.         if (
  116.             !empty($employee->getCity()) &&
  117.             !empty($employee->getCity()->getCountry()) &&
  118.             $employee->getCity()->getCountry()->getId() == Country::BR
  119.         ) {
  120.             $vacationDaysPending $employeeVacationDays - ($employeeVacationTaken + ($employeeVacationDays 30) );
  121.         }
  122.         return $this->render('absence/register.html.twig', [
  123.             'controller_name' => 'AbsenceController',
  124.             'supervisorName' => $supervisorName,
  125.             'absenceUuid' => Uuid::uuid4()->toString(),
  126.             'absenceTypes' => $this->entityManager->getRepository(EmployeeAbsenceType::class)->findBy(['isActive' => 1]),
  127.             'employeeVacationDays' => $employeeVacationDays,
  128.             'employeeVacationTaken' => $employeeVacationTaken,
  129.             'whitSupervisor' => $whitSupervisor,
  130.             'whitAccountant' => $whitAccountant,
  131.             'minDaysToRequestVacations' => $this->getParameter('minDaysToRequestVacations'),
  132.             'activeEmployees' => $employeeRepository->selectActiveEmployees(),
  133.             'vacationDaysPending' => $vacationDaysPending
  134.         ]);
  135.     }
  136.     #[Route('/create'name'create',  methods: ['POST'])]
  137.     public function createAction(AbsenceInterface $absenceInterfaceFileHandler $fileHandler,FileCategoryRepository $fileCategoryRepositoryRequest $request): JsonResponse
  138.     {
  139.         $parameters =  $request->request->all();
  140.         try {
  141.             $employeeReplacement $this->entityManager->getRepository(Employee::class)->find($parameters['absence-register-replace']);
  142.             $startDate = new \DateTime($parameters['absence-register-date-start'], new \DateTimeZone('UTC'));
  143.             $startEnd = new \DateTime($parameters['absence-register-date-end'], new \DateTimeZone('UTC'));
  144.             $vacationsEmployee $this->entityManager->getRepository(EmployeeVacationTaken::class)->vacationByEmployeeIdAndDates($this->getUser()->getEmployee()->getId(), $startDate$startEnd);
  145.             //Si tiene vacaciones que coinciden con las fechas que intenta registrar ahora se generara un error, para mostrar en el front.
  146.             if ($vacationsEmployee) {
  147.                 throw new \Exception('Coincidence in dates with others absence requested.');
  148.             }
  149.             //Validamos que venga el arcihvo que caso de no ser una vacacion:
  150.             $uploadedFiles $request->files->get('file-licence-absence');
  151.             // Si no se subio el archivo y el tipo de ausencia requiere archivo
  152.             if (!$uploadedFiles  && (in_array($parameters['absence-register-absence-type'], $this->AbsencesRequireFile))) {
  153.                 throw new \Exception("No file in the request, this is required");
  154.             }
  155.             // Si el tipo de ausencia requiere archivo y hay un error al cargarla.
  156.             if ( (in_array($parameters['absence-register-absence-type'], $this->AbsencesRequireFile))  && !$uploadedFiles[0]->isValid() ) {
  157.                 throw new \Exception('Error uploading file: ' $uploadedFiles[0]->getErrorMessage());
  158.             }
  159.             $arrayFiles = [];
  160.             if ($uploadedFiles) {
  161.                 $uploadDir $this->getParameter('kernel.project_dir') . '/public/assets/temp/';
  162.                 
  163.                $arrayFiles =  $absenceInterface->relocateFiles($uploadedFiles$uploadDir);
  164.                 /*$arrayFiles = [];
  165.                 foreach($uploadedFiles as $fileValue) {
  166.                     // Generar un nombre único para evitar conflictos
  167.                     $newFilename = "abs_".$fileValue->getClientOriginalName().'.' . $fileValue->guessExtension();
  168.                     $fileValue->move($uploadDir, $newFilename);   
  169.                     
  170.                     $arrayFiles[] =[
  171.                         'originFilePath' => $uploadDir.$newFilename,
  172.                         'fileName' => $fileValue->getClientOriginalName(),
  173.                     ];
  174.                 }*/
  175.             }
  176.             $employee $this->entityManager->getRepository(Employee::class)->find($this->getUser()->getEmployee()->getId());
  177.             $absence = new  EmployeeVacationTaken();
  178.             $absence->setStartDate($startDate);
  179.             $absence->setEndDate($startEnd);
  180.             $absence->setComment($parameters['absence-register-comments']);
  181.             $absence->setReplacement(trim($employeeReplacement->getFirstName()).' 'trim($employeeReplacement->getSurname()));
  182.             $absence->setEmployeeReplacement($employeeReplacement);
  183.             $absence->setEmployee($employee);
  184.             $absence->setEmployeeAbsenceType($this->entityManager->getRepository(EmployeeAbsenceType::class)->find($parameters['absence-register-absence-type']));
  185.             $absence->setDaysTaken($parameters['absence-register-days-absence']);    
  186.             $absence->setWorkflowStep('Pending_Supervisor_Approval');
  187.             $absence->setActive();
  188.             $this->entityManager->persist($absence);
  189.             $this->entityManager->flush();
  190.             //Si el empleado anexo archivo se regitra en la tabla de file
  191.             if ($arrayFiles) {
  192.                 $absenceInterface->registerAndUploadFile($fileCategoryRepository,$fileHandler$absence$this->entityManager$arrayFiles );
  193.                 /*$fileCategory = $fileCategoryRepository->getFileCategory(43);
  194.                 foreach($arrayFiles as $fileToUpload) {
  195.                     $file = $fileHandler->uploadAditionalEmployeeFile(
  196.                         $fileToUpload['originFilePath'], 
  197.                         $fileToUpload['fileName'], 
  198.                         $fileCategory,
  199.                         $employee
  200.                     );
  201.                     //Insertamos en registro en la tabla intermedia entre Ausencias y Vacaciones.
  202.                     $employeeVacationTakenFile = new EmployeeVacationTakenFile();
  203.                     $employeeVacationTakenFile->setVacation($absence);
  204.                     $employeeVacationTakenFile->setFile($file);
  205.                     $this->entityManager->persist($employeeVacationTakenFile);
  206.                     $this->entityManager->flush();
  207.                 }*/
  208.             }
  209.             // Se envia la notificacino:
  210.             $this->sendNotificationMail($absence'absence-Pending_Supervisor_Approval');
  211.             return new JsonResponse([
  212.                 'message' => 'OK'
  213.             ], 200);
  214.         } catch (\Exception $e) {
  215.             //dd($e);
  216.             return new JsonResponse([
  217.                 'message' => $e->getMessage()
  218.             ], 500);
  219.         }
  220.     }
  221.     #[Route('/edit/{absence}'name'edit'methods: ['GET''POST'])]
  222.     public function editAction(Request $requestEmployeeRepository  $employeeRepository,  VwEmployeeVacationRepository $vwEmployeeVacationRepositoryEmployeeVacationTaken $absence): Response
  223.     {
  224.         
  225.         $idCurrentEmployee $this->getUser()->getEmployee()->getId();
  226.         $rolesCurrentUser $this->getUser()->getRoles();
  227.         
  228.         $dataEmpleado $vwEmployeeVacationRepository->findEmployeeDetailsById($absence->getEmployee()->getId());
  229.         
  230.         //$employeeVacations = $this->entityManager->getRepository(VwEmployeeVacation::class)->find($this->getUser()->getEmployee()->getId());
  231.         $employeeVacationTaken $dataEmpleado['vacation_taken'];
  232.         $employeeVacationDays = empty($dataEmpleado['vacation_days']) ? 100 $dataEmpleado['vacation_days'];
  233.         $supervisorName = ($dataEmpleado['boss_id']) ?
  234.             $dataEmpleado['boss_first_name'] . ' ' $dataEmpleado['boss_surname']
  235.             : 'Not asociated supervisor';
  236.         $allowActions = [];
  237.         //Variable que nos determina si los campos estaran activos o inactivos
  238.         $fieldsDisabledEnabled 'disabled';
  239.         //Queremos saber si este usuario tendra la accion de Accountant localmente.
  240.         $contract $this->entityManager->getRepository(Employee::class)->hasContractActive($idCurrentEmployee);
  241.         $contractEntity $this->entityManager->getRepository(EntityContract::class)->findBy(['contract' => $dataEmpleado['contract_id'], 'isPrincipal' => 1]);
  242.         
  243.         $accountant $this->accountant->getAccountant($contractEntity[0]);
  244.         
  245.         //Si hay contador y es el usuario actual.                
  246.         $currentUserIsAccountant =  ($accountant && in_array($this->getUser()->getEmployee()->getId(), array_column($accountant'employeeId'))) ? 0;
  247.         date_default_timezone_set('UTC');
  248.         $currencyDate = new \DateTime();
  249.         //Si el que ingresa al registro es el solicitante
  250.         if (($dataEmpleado['employee_id'] == $idCurrentEmployee && in_array($absence->getWorkflowStep(), ['Pending_Supervisor_Approval''Approved_by_Supervisor']))
  251.             || (in_array("ROL_EMPLOYEE_ABSENCE_CANCEL"$this->getUser()->getRoles()) && $absence->getWorkflowStep() != 'canceled')
  252.         ) {
  253.             array_push($allowActions"cancel");
  254.         }
  255.         //Si tiene supervisor asociado  y Si el que ingresa es el supervisor y esta en estatus pendiente.
  256.         if ($dataEmpleado['boss_id'] && $dataEmpleado['boss_id'] == $idCurrentEmployee && $absence->getWorkflowStep() == 'Pending_Supervisor_Approval') {
  257.             array_push($allowActions"approve");
  258.             array_push($allowActions"reject");
  259.         }
  260.         // otro rol que podra editar una ausencia, solo si, tiene el rol ROL_EMPLOYEE_ABSENCE_EDIT
  261.         if (in_array("ROL_EMPLOYEE_ABSENCE_EDIT"$rolesCurrentUser)) {
  262.             $fieldsDisabledEnabled '';
  263.             array_push($allowActions"update");
  264.             array_push($allowActions"cancel");
  265.         }
  266.         if (in_array("ROL_EMPLOYEE_ABSENCE_REJECT"$rolesCurrentUser)) {
  267.             $fieldsDisabledEnabled '';
  268.             if ($absence->getWorkflowStep() == 'Pending_Supervisor_Approval') {
  269.                 array_push($allowActions"reject");
  270.             }
  271.         }
  272.         if (in_array("ROL_EMPLOYEE_ABSENCE_APPROVE"$rolesCurrentUser)) {
  273.             $fieldsDisabledEnabled '';
  274.             if ($absence->getWorkflowStep() == 'Pending_Supervisor_Approval') {
  275.                 array_push($allowActions"approve");
  276.             }
  277.         }
  278.         // Se podra ELIMINAR una ausencia, solo si, tiene el rol ROL_EMPLOYEE_ABSENCE_DELETE
  279.         // Si la fecha de inicio es mayor a la fecha actual
  280.         // Si esta pendiente.
  281.         if (
  282.             in_array("ROL_EMPLOYEE_ABSENCE_DELETE"$rolesCurrentUser) &&
  283.             ($absence->getStartDate() >= $currencyDate)
  284.         ) {
  285.             if ($absence->getWorkflowStep() == 'Pending_Supervisor_Approval') {
  286.                 $fieldsDisabledEnabled '';
  287.                 array_push($allowActions"delete");
  288.             }
  289.         }
  290.         //Buscamos el archivo en caso que tenga uno asociado.
  291.         $fileAsociatedToAbsece $absence->getFiles()->toArray();
  292.         return $this->render('absence/edit.html.twig', [
  293.             'controller_name' => 'AbsenceController',
  294.             'absence' => $absence,
  295.             'supervisorName' => $supervisorName,
  296.             'absenceTypes' => $this->entityManager->getRepository(EmployeeAbsenceType::class)->findBy(["isActive" => 1]),
  297.             'allowActions' => $allowActions,
  298.             'fieldsDisabledEnabled' => $fieldsDisabledEnabled,
  299.             'employeeVacationDays' => $employeeVacationDays,
  300.             'employeeVacationTaken' => $employeeVacationTaken,
  301.             'currentUserIsAccountant' => $currentUserIsAccountant,
  302.             'backFromAccountingRegistered' => ($request->query->get('ori') == "registerAccountant") ? 0,
  303.             'backFromUpdated' => ($request->query->get('ori') == "update") ? 0,
  304.             'activeEmployees' => $employeeRepository->selectActiveEmployees(),
  305.             'files' =>$fileAsociatedToAbsece
  306.         ]);
  307.     }
  308.     #[Route('/update/{absence}'name'update'methods: ['POST'])]
  309.     public function updateActionAbsenceInterface $absenceInterfaceFileHandler $fileHandler,FileCategoryRepository $fileCategoryRepositoryRequest $requestEmployeeVacationTaken $absence): Response
  310.     {
  311.         $parameters =  $request->request->all();
  312.         
  313.         $remplacement $this->entityManager->getRepository(Employee::class)->find((int)$request->get("absence-register-replace"));
  314.        
  315.        
  316.         //try {
  317.             //Validamos que venga el arcihvo que caso de no ser una vacacion:
  318.             $uploadedFiles $request->files->get('file-licence-absence');
  319.             $filesToDelete = (trim($parameters['absence-edit-files-to-delete'])!="")?explode(","$parameters['absence-edit-files-to-delete']):null;
  320.             
  321.             // Si no se subio el archivo y el tipo de ausencia requiere archivo
  322.             /*if (!$uploadedFiles  && (in_array($absence->getEmployeeAbsenceType()->getId(), $this->AbsencesRequireFile))) {
  323.                 throw new \Exception("No file in the request, this is required");
  324.             }
  325.             // Si el tipo de ausencia requiere archivo y hay un error al cargarla.
  326.             if ( (in_array($absence->getEmployeeAbsenceType()->getId(), $this->AbsencesRequireFile))  && !$uploadedFiles[0]->isValid() ) {
  327.                 throw new \Exception(message: 'Error uploading file: ' . $uploadedFiles[0]->getErrorMessage());
  328.             }*/
  329.             $arrayFiles = [];
  330.             if ($uploadedFiles) {
  331.                 $uploadDir $this->getParameter('kernel.project_dir') . '/public/assets/temp/';
  332.                 $arrayFiles =  $absenceInterface->relocateFiles($uploadedFiles$uploadDir);
  333.                 /*foreach($uploadedFiles as $fileValue) {
  334.                     // Generar un nombre único para evitar conflictos
  335.                     $newFilename = "abs_".$fileValue->getClientOriginalName().'.' . $fileValue->guessExtension();
  336.                     $fileValue->move($uploadDir, $newFilename);   
  337.                     $arrayFiles[] =[
  338.                         'originFilePath' => $uploadDir.$newFilename,
  339.                         'fileName' => $fileValue->getClientOriginalName(),
  340.                     ];
  341.                 }*/
  342.             }
  343.             if ($request->get("absence-edit-action") == "update") {
  344.                 date_default_timezone_set('UTC');
  345.                 $absence->setStartDate(new \DateTimeImmutable($request->get("absence-register-date-start")));
  346.                 $absence->setEndDate(new \DateTimeImmutable($request->get("absence-register-date-end")));
  347.                 $absence->setComment($request->get("absence-register-comments"));
  348.                 $absence->setReplacement(trim($remplacement->getFirstName()).' 'trim($remplacement->getSurname()));
  349.                 $absence->setEmployeeReplacement($remplacement);
  350.                 $absence->setEmployeeAbsenceType($this->entityManager->getRepository(EmployeeAbsenceType::class)->find($request->get("absence-register-absence-type")));
  351.                 $absence->setDaysTaken($request->get("absence-register-days-absence"));
  352.                 $this->entityManager->persist($absence);
  353.                 $this->sendNotificationMail($absence'absence-updated');
  354.                 $edited true;
  355.             }
  356.             if ($request->get("absence-edit-action") == "delete") {
  357.                 $this->entityManager->remove($absence);
  358.                 // $this->entityManager->persist($absence);
  359.             }
  360.             $stateMachine  $this->workflow->get($absence'absenceVacation');
  361.             if ($request->get("absence-edit-action") == "cancel") {
  362.                 
  363.                 // Se le agrega esta propiedad para ver desde el workflow, si fue RRHH que cancelo y enviar las notificaciones al Contabilidad.
  364.                 if ($absence->getWorkflowStep() != 'Pending_Supervisor_Approval') {
  365.                     $absence->cancelByHR true;
  366.                 }
  367.                 if ($stateMachine->can($absence'to_canceled')) {
  368.                     $stateMachine->apply($absence'to_canceled');
  369.                 }
  370.             }
  371.             if ($request->get("absence-edit-action") == "approve") {
  372.                 $approvedDate = new \DateTime(date('Y-m-d'), new \DateTimeZone('UTC'));
  373.                 $absence->setApprovedDate($approvedDate);
  374.                 if ($stateMachine->can($absence'to_Approved_by_Supervisor')) {
  375.                     $stateMachine->apply($absence'to_Approved_by_Supervisor');
  376.                 }
  377.                 $this->entityManager->persist($absence);
  378.             }
  379.             if ($request->get("absence-edit-action") == "reject") {
  380.                 if ($stateMachine->can($absence'to_rejected')) {
  381.                     $stateMachine->apply($absence'to_rejected');
  382.                 }
  383.             }
  384.             if ($request->get("absence-edit-action") == "registerAccountant") {
  385.                 $accountingRecordedDate = new \DateTime(date('Y-m-d'), new \DateTimeZone('UTC'));
  386.                 $absence->setAccountingRecordedDate($accountingRecordedDate);
  387.                 $absence->setAccountingRecorded(1);
  388.             }
  389.             $this->entityManager->flush();
  390.             //Si el empleado anexó archivo se regitra en la tabla de file
  391.             if ($arrayFiles) {
  392.                 $absenceInterface->registerAndUploadFile($fileCategoryRepository,$fileHandler$absence$this->entityManager$arrayFiles );
  393.                 /*$fileCategory = $fileCategoryRepository->getFileCategory(43);
  394.                 foreach($arrayFiles as $fileToUpload) {
  395.                     $file = $fileHandler->uploadAditionalEmployeeFile(
  396.                         $fileToUpload['originFilePath'], 
  397.                         $fileToUpload['fileName'], 
  398.                         $fileCategory,
  399.                         $absence->getEmployee()
  400.                     );
  401.                     //Insertamos en registro en la tabla intermedia entre Ausencias y Vacaciones.
  402.                     $employeeVacationTakenFile = new EmployeeVacationTakenFile();
  403.                     $employeeVacationTakenFile->setVacation($absence);
  404.                     $employeeVacationTakenFile->setFile($file);
  405.                     $this->entityManager->persist($employeeVacationTakenFile);
  406.                     $this->entityManager->flush();
  407.                 }*/
  408.             }
  409.             
  410.             //Si el usuario requirio eliminar archivos ya existentes
  411.             if ($filesToDelete){
  412.                 foreach ($filesToDelete as  $fileId) {
  413.                    $dataFile $this->entityManager->getRepository(File::class)->find$fileId);
  414.                    $fileHandler->simpleDeleteFile($dataFile);
  415.                    $dataEmployeeVacationTakenFile $this->entityManager->getRepository(EmployeeVacationTakenFile::class)->findBy(['file' => $fileId ] );
  416.                    //Eliminar registros de File.
  417.                    $this->entityManager->remove($dataFile);
  418.                    //Eliminamos de la tabla employee_vacation_taken_file
  419.                    $this->entityManager->remove($dataEmployeeVacationTakenFile[0]);
  420.                    $this->entityManager->flush();                
  421.                 }
  422.             }
  423.             return ($request->get("absence-edit-action") == "delete") ?
  424.                 $this->redirect($this->generateUrl('absence_index') . '?id=' $absence->getId()) :
  425.                 $this->redirect($this->generateUrl('absence_edit', ["absence" => $absence->getId()]) . "&ori=" $request->get("absence-edit-action"));
  426.         /*} catch (\Exception $e) {
  427.             //dd($e);
  428.             return new JsonResponse([
  429.                 'message' => $e->getMessage()
  430.             ], 500);
  431.         }*/    
  432.     
  433.     }
  434.     #[Route('/{isPendingAccounting}/table/{year}/{month}/{day}/{absenceType}'name'table'methods: ['GET'], defaults: ["year" => 0"month" => 0"day" => 0"isPendingAccounting" => 0"absenceType" => 0])]
  435.     public function table(
  436.         VacationListInterface $vacationList,
  437.         int $year,
  438.         int $month,
  439.         int $day,
  440.         int $isPendingAccounting,
  441.         int $absenceType
  442.     ): Response {
  443.         return $this->json($vacationList->getData($year$month$day$isPendingAccounting$absenceType));
  444.     }
  445.     public function sendNotificationMail(EmployeeVacationTaken $absence$typeNotify)
  446.     {
  447.         
  448.         $emailToSend $this->entityManager->getRepository(Email::class)->findOneBy([
  449.             'name' => $typeNotify
  450.         ]);
  451.         $employee $absence->getEmployee();
  452.         $EmployeeName $employee->getFirstName() . ' ' $employee->getSurName();
  453.         $cmEmail $this->entityManager->getRepository(Employee::class)->findEmailsByPositionInCountry($employee'CM');
  454.         $ccEmail $this->entityManager->getRepository(Employee::class)->findEmailsByPositionInCountry($employee'CC');
  455.         $cmEmail array_merge($cmEmail$ccEmail);
  456.         
  457.         if ($typeNotify == 'absence-updated') {
  458.             $contract $this->entityManager->getRepository(Employee::class)->hasContractActive($employee->getId());
  459.             $entityContract $this->entityManager->getRepository(EntityContract::class)->findOneBy(['contract' => $contract[0]->getId(), 'isPrincipal' => 1]);
  460.             $a3code $entityContract->getEntity()->getCountry()->getA3code();
  461.             $positionAccountant $this->parameters->get('absence_position_notification_by_country')[$a3code];
  462.             $employeeAccountant $this->entityManager->getRepository(Employee::class)->getEmployeeByCountryAndPosition($entityContract->getEntity()->getCountry()->getId(), $positionAccountant);
  463.             foreach ($employeeAccountant as $contract) {
  464.                 $sendTo[] = $contract->getEmployee()->getCorporateEmail();
  465.             }
  466.             //$sendTo[] = ($employeeAccountant)?$employeeAccountant[0]->getEmployee()->getCorporateEmail():"";
  467.             //$sendTo[] = 'mjordan+100@bizlatinhub.com';
  468.             
  469.             array_push($sendTo$employee->getCorporateEmail());
  470.             array_push($sendTo$employee->getImmediateBoss()->getCorporateEmail());
  471.             $sendTo array_merge($sendTo$cmEmail);
  472.         }
  473.         if ($typeNotify == 'absence-Pending_Supervisor_Approval') {
  474.             $sendTo = [$employee->getImmediateBoss()->getCorporateEmail()];
  475.         }
  476.         $emailsForNotification =
  477.             [
  478.                 MailHandler::RECEIVER_TO => $sendTo,
  479.                 MailHandler::RECEIVER_CC =>  explode(","$emailToSend->getSendCc()),
  480.                 MailHandler::RECEIVER_BCC => explode(","$emailToSend->getSendBcc())
  481.             ];
  482.         $subject str_replace('{{employeeName}}'$EmployeeName$emailToSend->getSubject());
  483.         $this->mailHandler->sendEmailByApi(
  484.             $emailToSend->setSubject($subject),
  485.             $emailsForNotification,
  486.             ['process' => $absence]
  487.         );
  488.         $this->entityManager->detach($emailToSend);
  489.     }
  490. }