src/Controller/Webservice/WebserviceController.php line 9251

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Webservice;
  3. use App\Entity\User;
  4. use App\Entity\Slider;
  5. use App\Entity\Client;
  6. use App\Entity\ExceptionAgent;
  7. use App\Entity\EmailAlert;
  8. use App\Entity\DocumentParent;
  9. use App\Entity\Document;
  10. use App\Entity\SupervisionTicket;
  11. use App\Entity\AssetLocation;
  12. use App\Entity\Asset;
  13. use App\Entity\Ticket;
  14. use App\Entity\TicketMessage;
  15. use App\Entity\TicketPicture;
  16. use App\Entity\TicketCategory;
  17. use App\Entity\TicketStatus;
  18. use App\Entity\DocumentTemplate;
  19. use App\Entity\DocumentTemplateGroup;
  20. use App\Entity\DocumentTemplateField;
  21. use App\Entity\DocumentTemplateFieldValue;
  22. use App\Entity\Employee;
  23. use App\Entity\EmployeeTime;
  24. use App\Entity\EmployeeTimeStatus;
  25. use App\Entity\VehicleAssignmentFail;
  26. use App\Entity\VehiclePicture;
  27. use App\Entity\EmployeeAgreement;
  28. use App\Entity\EmployeeStatusLog;
  29. use App\Entity\Help;
  30. use App\Entity\ShiftReportType;
  31. use App\Entity\Location;
  32. use App\Entity\LocationPlace;
  33. use App\Entity\LocationPosition;
  34. use App\Entity\LocationEmployee;
  35. use App\Entity\LocationService;
  36. use App\Entity\SupervisionPicture;
  37. use App\Entity\SanctionPicture;
  38. use App\Entity\SupervisionRoute;
  39. use App\Entity\SupervisionRouteLocation;
  40. use App\Entity\SupervisionRouteEmployee;
  41. use App\Entity\EmployeeShift;
  42. use App\Entity\ShiftEmployee;
  43. use App\Entity\ShiftEmployeePause;
  44. use App\Entity\ShiftEmployeePauseType;
  45. use App\Entity\RequestField;
  46. use App\Entity\RequestParent;
  47. use App\Entity\RequestAnswer;
  48. use App\Entity\RequestStatus;
  49. use App\Entity\RequestType;
  50. use App\Entity\RequestTypeApply;
  51. use App\Entity\RequestFieldValue;
  52. use App\Entity\ReactionType;
  53. use App\Entity\Reaction;
  54. use App\Entity\ReactionMap;
  55. use App\Entity\ReactionPicture;
  56. use App\Entity\Supervision;
  57. use App\Entity\SupervisionEmployee;
  58. use App\Entity\SupervisionFacility;
  59. use App\Entity\Shift;
  60. use App\Entity\ShiftEmployeeLog;
  61. use App\Entity\ShiftReport;
  62. use App\Entity\ShiftEvent;
  63. use App\Entity\ShiftEventPicture;
  64. use App\Entity\SanctionStatus;
  65. use App\Entity\Sanction;
  66. use App\Entity\SyncLog;
  67. use App\Entity\SyncControl;
  68. use App\Entity\SyncControlLog;
  69. use App\Entity\Push;
  70. use App\Entity\PushUser;
  71. use App\Entity\PushKey;
  72. use App\Entity\Project;
  73. use App\Entity\Electronic;
  74. use App\Entity\ElectronicType;
  75. use App\Entity\ElectronicEmployee;
  76. use App\Entity\ElectronicPicture;
  77. use App\Entity\PropertyReport;
  78. use App\Entity\PropertyReportDetail;
  79. use App\Entity\VehiclePanic;
  80. use App\Entity\VehicleTransfer;
  81. use App\Entity\VehicleAssignment;
  82. use App\Entity\VehicleAssignmentFuel;
  83. use App\Entity\VehicleAssignmentPicture;
  84. use App\Entity\VehicleChecklist;
  85. use App\Entity\Refuel;
  86. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  87. use Symfony\Component\HttpFoundation\Request;
  88. use Symfony\Component\HttpFoundation\Response;
  89. use Symfony\Component\Routing\Annotation\Route;
  90. use Symfony\Component\HttpFoundation\JsonResponse;
  91. use Doctrine\ORM\EntityManagerInterface;
  92. use Symfony\Component\Security\Core\User\UserInterface;
  93. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  94. use Symfony\Component\HttpKernel\KernelInterface;
  95. use Nzo\UrlEncryptorBundle\Encryptor\Encryptor;
  96. use App\Service\HelperService;
  97. use App\Service\MailHelper;
  98. /**
  99.  * @Route("ws")
  100.  */
  101. class WebserviceController extends AbstractController
  102. {
  103.     
  104.     private $environment;
  105.     private $passwordEncoder;
  106.     private $encryptor;
  107.     public function __construct(UserPasswordEncoderInterface $passwordEncoderKernelInterface $kernelEncryptor $encryptorEntityManagerInterface $entityManager)
  108.     {       
  109.         date_default_timezone_set('America/Guatemala');
  110.         $this->passwordEncoder $passwordEncoder;
  111.         $this->environment     $kernel->getEnvironment();
  112.         $this->encryptor       $encryptor;
  113.         $this->entityManager   $entityManager;
  114.     }        
  115.     
  116.     public function getProjectPaths()
  117.     {                
  118.         $paths = array();
  119.         if($this->environment == "prod"){    
  120.             $paths["public_path"] = 'https://appseguridad.org/public/';
  121.             $paths["public_link"] = 'https://appseguridad.org/signature_client/?rid=';
  122.         } else {
  123.             $paths["public_path"] = 'https://dev2.datoscontinuos.net/1618/symfony5/bts_interno/public/';
  124.             $paths["public_link"] = 'https://dev2.datoscontinuos.net/1618/symfony5/bts_interno/public/signature_client/?rid=';
  125.         }
  126.         
  127.         return $paths;        
  128.     }
  129.     public function checkCredentials($passwordUserInterface $user)
  130.     {
  131.         return $this->passwordEncoder->isPasswordValid($user$password);
  132.     }
  133.     /**
  134.      * @Route("/env-check", name="env-check", methods={"GET", "POST"})
  135.      */
  136.     public function envCheck(Request $requestEntityManagerInterface $entityManager): Response
  137.     {
  138.             
  139.         $paths $this->getProjectPaths();
  140.         return new JsonResponse(array('env' => $this->environment'path' => $paths["public_path"]));
  141.     
  142.     }
  143.     /**
  144.      * @Route("/validate-dpi", name="validate-dpi", methods={"GET", "POST"})
  145.      */
  146.     public function validateDpi(Request $requestEntityManagerInterface $entityManager): Response
  147.     {
  148.         
  149.         $data json_decode(file_get_contents("php://input"));             
  150.         if($data)
  151.         {   
  152.             $dpi  $data->identification;   
  153.             $type $data->type;        
  154.             if($type == 'supervisor')
  155.             {
  156.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  157.                     'citizenId'      => $dpi,
  158.                     'employeeStatus' => 1,
  159.                     'jobPosition'    => [2,11,16,5]
  160.                 ]);    
  161.                 if($employeeObj)
  162.                 {              
  163.                     $data $this->sessionEmployee($employeeObj);                         
  164.                     return new JsonResponse(array('status' => 'success''data' => $data'message' => 'Bienvenido '.$employeeObj->getName()));                    
  165.                 }
  166.             } elseif($type == 'patrolman') {
  167.                 $token $data->token;
  168.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  169.                     'citizenId'      => $dpi,
  170.                     'employeeStatus' => 1,
  171.                     'jobPosition'    => 3
  172.                 ]);    
  173.                 if($employeeObj)
  174.                 {    
  175.                     
  176.                     $employeeObj->setToken($token);
  177.                     $entityManager->persist($employeeObj);
  178.                     $entityManager->flush();
  179.                     $data $this->sessionEmployee($employeeObj);                         
  180.                     return new JsonResponse(array('status' => 'success''data' => $data'message' => 'Bienvenido '.$employeeObj->getName()));                    
  181.                     
  182.                 }
  183.             } elseif($type == 'electronic') {
  184.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  185.                     'citizenId'      => $dpi,
  186.                     'employeeStatus' => 1,
  187.                     'jobPosition'    => [4,5]
  188.                 ]);    
  189.                 if($employeeObj)
  190.                 {              
  191.                     $data $this->sessionEmployee($employeeObj);                         
  192.                     return new JsonResponse(array('status' => 'success''data' => $data'message' => 'Bienvenido '.$employeeObj->getName()));                    
  193.                 }
  194.             } elseif($type == 'overtime') {
  195.                     $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  196.                         'citizenId'      => $dpi,
  197.                         'employeeStatus' => 1,
  198.                         'jobPosition'    => [2,5,16,22,11]
  199.                     ]);    
  200.                     if($employeeObj)
  201.                     {              
  202.                         $data $this->sessionEmployee($employeeObj);                         
  203.                         return new JsonResponse(array('status' => 'success''data' => $data'message' => 'Bienvenido '.$employeeObj->getName()));                    
  204.                     }
  205.                                 
  206.             }  elseif($type == 'administrative') {
  207.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  208.                     'citizenId'      => $dpi,
  209.                     'employeeStatus' => 1,
  210.                     'jobPosition'    => [1652222412,13]
  211.                 ]);    
  212.                 if($employeeObj)
  213.                 {              
  214.                     $data $this->sessionEmployee($employeeObj);                         
  215.                     return new JsonResponse(array('status' => 'success''data' => $data'message' => 'Bienvenido '.$employeeObj->getName()));                    
  216.                 }
  217.                             
  218.             } elseif($type == 'vehicle' || $type == 'refueling') {
  219.                 //TODOS LOS EMPLEADOS PUEDEN USAR ESTE MODULO
  220.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  221.                     'citizenId'      => $dpi,
  222.                     'employeeStatus' => 1                    
  223.                 ]);    
  224.                 if($employeeObj)
  225.                 {              
  226.                     $data $this->sessionEmployee($employeeObj);                         
  227.                     return new JsonResponse(array('status' => 'success''data' => $data'message' => 'Bienvenido '.$employeeObj->getName()));                    
  228.                 }
  229.             
  230.             } else {
  231.                 //Si se trata de agente, ya no habrá restricción de roles. Esto fue aplicado porque indicaron los usuarios
  232.                 //del app, que la app no "Servia" porque no podian ingresar (Con roles que aca abajo no estaban especificados)
  233.                 //Este cambio se hizo el 28 de abril del 2025
  234.                 /*$employeeObj = $entityManager->getRepository(Employee::class)->findOneBy([
  235.                     'citizenId'      => $dpi,
  236.                     'employeeStatus' => 1,
  237.                     'jobPosition'    => [1,11,2,16,7,21,5]
  238.                 ]);*/
  239.                 
  240.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  241.                     'citizenId'      => $dpi,
  242.                     'employeeStatus' => 1                    
  243.                 ]); 
  244.                                 
  245.                 
  246.                 if($employeeObj)
  247.                 {
  248.                     
  249.                     //Esto fue comentado el 3 de marzo del 2023, porque ahora ya no se necesita que el empleado tenga turno asignado para poder iniciar sesión
  250.                     /*$currentShiftObj = $entityManager->getRepository(ShiftEmployee::class)->findOneBy([
  251.                         'Employee'  => $employeeObj->getEmployeeId(),                    
  252.                         'is_done'    => 0
  253.                     ]);
  254.                     if($currentShiftObj)
  255.                     {*/
  256.                         $data $this->sessionEmployee($employeeObj);
  257.                         return new JsonResponse(array('status' => 'success''data' => $data'message' => 'Bienvenido '.$employeeObj->getName()));
  258.                     /*} else {
  259.                         return new JsonResponse(array('status' => 'error', 'message' => 'El empleado no tiene turno asignado'));
  260.                     }*/
  261.                 }
  262.             } 
  263.             
  264.         }
  265.         return new JsonResponse(array('status' => 'error''message' => 'Identificación Invalida'));
  266.     }    
  267.     public function sessionEmployee($employeeObj$locationObj false$employeeShiftObj false)
  268.     {
  269.         $path $this->getProjectPaths();
  270.         if($employeeObj->getAvatarPath())
  271.         {
  272.             $avatar $path['public_path'].'uploads/'.$employeeObj->getAvatarPath();
  273.         } else {
  274.             $avatar $path['public_path'].'assets/img/empty_user.png';
  275.         }
  276.         if(!$locationObj)
  277.         {
  278.             $data = [
  279.                 'employee_id' => $employeeObj->getEmployeeId(),
  280.                 'citizen_id'  => $employeeObj->getCitizenId(),
  281.                 'name'        => $employeeObj->getName(),
  282.                 'alias'       => $employeeObj->getAlias(),
  283.                 'position'    => $employeeObj->getJobPosition()->getName(),
  284.                 'position_id' => $employeeObj->getJobPosition()->getJobPositionId(),
  285.                 'avatar'      => $avatar,
  286.                 'client_name'       => '',
  287.                 'project_name'      => '',
  288.                 'location_id'       => '',
  289.                 'location_name'     => '',
  290.                 'location_polygon_list'     => array(),
  291.                 'location_address'  => '',
  292.                 'shift_employee_id' => '',
  293.                 'shift_start'       => ''
  294.             ];
  295.         } else {
  296.             $data = [
  297.                 'employee_id' => $employeeObj->getEmployeeId(),
  298.                 'citizen_id'  => $employeeObj->getCitizenId(),
  299.                 'name'        => $employeeObj->getName(),
  300.                 'alias'       => $employeeObj->getAlias(),
  301.                 'position'    => $employeeObj->getJobPosition()->getName(),
  302.                 'position_id' => $employeeObj->getJobPosition()->getJobPositionId(),
  303.                 'avatar'      => $avatar,
  304.                 'client_name'       => $locationObj->getClient()->getName(),
  305.                 'project_name'      => ($locationObj->getProject() ? $locationObj->getProject()->getName() : ''),
  306.                 'location_id'       => $locationObj->getLocationId(),
  307.                 'location_name'     => $locationObj->getName(),
  308.                 'location_polygon_list'     => json_decode($locationObj->getPolygonList(), true),
  309.                 'location_address'  => $locationObj->getAddress(),
  310.                 'shift_employee_id' => $employeeShiftObj->getShiftEmployeeId(),
  311.                 'shift_start'       => $employeeShiftObj->getOpenedAt(),
  312.                 'shift_end'         => ''                
  313.             ];
  314.         }
  315.         return $data;
  316.     }
  317.     /**
  318.      * @Route("/return-vehicle", name="return-vehicle", methods={"GET", "POST"})
  319.      */
  320.     public function returnVehicle(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  321.     {
  322.         
  323.         $data json_decode(file_get_contents("php://input"));             
  324.         if($data)
  325.         {   
  326.             $array = [];
  327.             $employeeId $data->eid;
  328.             $vaid       $data->vaid;
  329.             $currentKm  $data->currentKm;
  330.                        
  331.             $vehicleAssignmentObj $entityManager->getRepository(VehicleAssignment::class)->findOneBy([
  332.                 'vehicleAssignmentId' => $vaid                
  333.             ]);                            
  334.             if($vehicleAssignmentObj)
  335.             {
  336.                 if($currentKm $vehicleAssignmentObj->getMileage())
  337.                 {
  338.                     return new JsonResponse(array('status' => 'error''message' => 'El kilometraje final no puede ser menor al inicial'));
  339.                 }
  340.                 $vehicleAssignmentObj->setMileageFinal($currentKm);
  341.                 $vehicleAssignmentObj->setIsReturned(1);
  342.                 $vehicleAssignmentObj->setReturnedAt(new \DateTime());   
  343.                 $entityManager->persist($vehicleAssignmentObj);
  344.                 $entityManager->flush();
  345.                 $calculated $currentKm $vehicleAssignmentObj->getMileage();
  346.                 
  347.                 if($helperService->externalDb_setOldVehicleAssignmentsAndStatus($vehicleAssignmentObj->getExternalId(), $currentKm$calculated))
  348.                 {
  349.                     return new JsonResponse(array('status' => 'success''message' => 'Vehículo entregado correctamente'));
  350.                 }
  351.                 return new JsonResponse(array('status' => 'error''message' => 'No se pudo entregar el vehiculo en este momento, por favor reporte este mensaje al administrador del sistema: V34421'));
  352.                       
  353.             }            
  354.             
  355.         }   
  356.         
  357.         return new JsonResponse(array('status' => 'error''message' => 'No se puede entregar el vehículo en este momento, reporte este código a su administrador: V3442'));
  358.     }      
  359.     /**
  360.      * @Route("/remove-form", name="remove-form", methods={"GET", "POST"})
  361.      */
  362.     public function removeForm(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  363.     {
  364.         $data json_decode(file_get_contents("php://input"));             
  365.         if($data)
  366.         {               
  367.             $employeeId $data->eid;
  368.             $parentId   $data->parentId;
  369.             
  370.             $parentObj $entityManager->getRepository(DocumentParent::class)->findOneBy([
  371.                 'documentParentId' => $parentId,                
  372.             ]); 
  373.             if($parentObj)
  374.             {
  375.                 $parentObj->setIsActive(0);
  376.                 $entityManager->persist($parentObj);
  377.                 $entityManager->flush();
  378.             }
  379.             return new JsonResponse(array('status' => 'success'));
  380.         }
  381.         return new JsonResponse(array('status' => 'error'));
  382.     }
  383.   
  384.     /**
  385.      * @Route("/get-my-forms", name="get-my-forms", methods={"GET", "POST"})
  386.      */
  387.     public function getMyForms(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  388.     {
  389.         $data json_decode(file_get_contents("php://input"));             
  390.         if($data)
  391.         {               
  392.             $employeeId $data->eid;
  393.             $templateId $data->templateId;
  394.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  395.                 'employeeId' => $employeeId
  396.             ]); 
  397.             
  398.             $templateObj $entityManager->getRepository(DocumentTemplate::class)->findOneBy([
  399.                 'documentTemplateId' => $templateId
  400.             ]); 
  401.             $parentObj $entityManager->getRepository(DocumentParent::class)->findBy([
  402.                 'DocumentTemplate'       => $templateId,
  403.                 'created_by_employee_id' => $employeeId,
  404.                 'is_active' => 1
  405.             ]); 
  406.             $form = [];
  407.             foreach($parentObj as $parent)
  408.             {
  409.                 $documentList $entityManager->getRepository(Document::class)->findBy([
  410.                     'DocumentParent' => $parentObj                   
  411.                 ]); 
  412.                 
  413.                 $fields = [];
  414.                 $main   = [];
  415.                 $num    0;
  416.                 foreach($documentList as $item)
  417.                 {
  418.                     $fieldObj $entityManager->getRepository(DocumentTemplateField::class)->findOneBy([
  419.                         'documentTemplateFieldId' => $item->getDocumentTemplateField()->getDocumentTemplateFieldId()                   
  420.                     ]); 
  421.                     $fields[] = [
  422.                         'document_id' => $item->getDocumentId(),
  423.                         'label'       => $item->getLabel(),
  424.                         'value'       => $item->getInputValue(),
  425.                         'field_id'    => $item->getDocumentTemplateField()->getDocumentTemplateFieldId(),
  426.                         'field_type'  => $fieldObj->getFieldType()  
  427.                     ];
  428.                     
  429.                     if($num 2)
  430.                     {
  431.                         $main[] = [
  432.                             'name'  => $item->getLabel(),
  433.                             'value' => $item->getInputValue()
  434.                         ];
  435.                     }
  436.                     $num++;
  437.                 }               
  438.                 $form[] = [
  439.                     'parent_id'  => $parent->getDocumentParentId(),
  440.                     'created_at' => $parent->getCreatedAt()->format("Y-m-d"),
  441.                     'fields'     => $fields,
  442.                     'main'       => $main
  443.                 ];
  444.                 
  445.             }
  446.             
  447.             return new JsonResponse(array('status' => 'success''form' => $form));
  448.         }
  449.         return new JsonResponse(array('status' => 'error'));
  450.     }
  451.     /**
  452.      * @Route("/get-form", name="get-form", methods={"GET", "POST"})
  453.      */
  454.     public function getForm(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  455.     {
  456.         
  457.         $data json_decode(file_get_contents("php://input"));             
  458.         if($data)
  459.         {   
  460.             $array = [];
  461.             $employeeId $data->eid;
  462.             $form       $data->form;
  463.             
  464.             //Template ID
  465.             if($form == 'vehicle-supervision')
  466.             {
  467.                 $template = [];
  468.                         
  469.                 $documentTemplateObj $entityManager->getRepository(DocumentTemplate::class)->findOneBy([
  470.                     'documentTemplateId' => 1
  471.                 ]);                            
  472.                 if($documentTemplateObj)
  473.                 {
  474.                     $documentTemplateGroupList $entityManager->getRepository(DocumentTemplateGroup::class)->findBy([
  475.                         'DocumentTemplate' => $documentTemplateObj,
  476.                         'is_active' => 1
  477.                     ]);                            
  478.                     
  479.                     
  480.                     foreach($documentTemplateGroupList as $documentTemplateGroup)
  481.                     {
  482.                         $documentTemplateFieldList $entityManager->getRepository(DocumentTemplateField::class)->findBy([
  483.                             'DocumentTemplateGroup' => $documentTemplateGroup,
  484.                             'is_active' => 1
  485.                         ]);   
  486.                         
  487.                         $fields = [];
  488.                         foreach($documentTemplateFieldList as $documentTemplateField)
  489.                         {
  490.                             $documentTemplateFieldValueList $entityManager->getRepository(DocumentTemplateFieldValue::class)->findBy([
  491.                                 'DocumentTemplateField' => $documentTemplateField,
  492.                                 'is_active' => 1
  493.                             ]);
  494.                             $choices = [];
  495.                             foreach($documentTemplateFieldValueList as $documentTemplateFieldValue)
  496.                             {
  497.                                 $choices[] = [
  498.                                     'id'   => $documentTemplateFieldValue->getDocumentTemplateFieldValueId(),
  499.                                     'name' => $documentTemplateFieldValue->getValueName()
  500.                                 ];
  501.                             }
  502.                             $default '';
  503.                             if($documentTemplateField->getFieldType() == 'opcion_multiple')
  504.                             {
  505.                                 $valueObj $entityManager->getRepository(DocumentTemplateFieldValue::class)->findOneBy([
  506.                                     'DocumentTemplateField' => $documentTemplateField,
  507.                                     'is_active'  => 1,
  508.                                     'is_default' => 1
  509.                                 ]);
  510.                                 if($valueObj)
  511.                                 {
  512.                                     $default $valueObj->getDocumentTemplateFieldValueId();
  513.                                 }                                     
  514.                             } else {
  515.                                 $default $documentTemplateField->getDefaultValue();                           
  516.                             }                            
  517.                             $fields[] = [
  518.                                 'template_field_id' => $documentTemplateField->getDocumentTemplateFieldId(),
  519.                                 'name'          => $documentTemplateField->getName(),
  520.                                 'field_type'    => $documentTemplateField->getFieldType(),
  521.                                 'help_text'     => $documentTemplateField->getHelpText(),
  522.                                 'default_value' => $default,
  523.                                 'date_validation' => $documentTemplateField->getDateValidationType(),
  524.                                 'is_required'   => $documentTemplateField->getIsRequired(),
  525.                                 'size'          => $documentTemplateField->getSize(),
  526.                                 'weight'        => $documentTemplateField->getWeight(),
  527.                                 'choices'       => $choices
  528.                             ];
  529.                         }
  530.                         $template[] = [
  531.                             'template_id' => $documentTemplateObj->getDocumentTemplateId(),
  532.                             'name'        => $documentTemplateGroup->getName(),
  533.                             'description' => $documentTemplateGroup->getDescription(),
  534.                             'fields'      => $fields
  535.                         ];
  536.                     }
  537.                                                             
  538.                         
  539.                 }                  
  540.             }      
  541.             
  542.             return new JsonResponse(array('status' => 'success''template' => $template));
  543.             
  544.         }   
  545.         
  546.         return new JsonResponse(array('status' => 'error''message' => 'No se puede entregar el vehículo en este momento, reporte este código a su administrador: V3442'));
  547.     }      
  548.     /**
  549.      * @Route("/get-current-vehicle", name="get-current-vehicle", methods={"GET", "POST"})
  550.      */
  551.     public function getCurrentVehicle(Request $requestEntityManagerInterface $entityManager): Response
  552.     {
  553.         
  554.         $data json_decode(file_get_contents("php://input"));             
  555.         if($data)
  556.         {   
  557.             $array = [];
  558.             $employeeId $data->eid;
  559.                        
  560.             $vehicleAssignmentObj $entityManager->getRepository(VehicleAssignment::class)->findOneBy([
  561.                 'created_by_employee_id' => $employeeId,
  562.                 'is_done'     => 1,
  563.                 'is_active'   => 1,
  564.                 'is_returned' => 0
  565.             ]);                            
  566.             if($vehicleAssignmentObj)
  567.             {
  568.                 $array = [
  569.                     'vehicle_assignment_id' => $vehicleAssignmentObj->getVehicleAssignmentId(),
  570.                     'plate_number'          => $vehicleAssignmentObj->getPlateNumber(),
  571.                     'process_end'           => $vehicleAssignmentObj->getProcessEnd(),
  572.                     'external_id'           => $vehicleAssignmentObj->getExternalId()
  573.                 ];                                
  574.                       
  575.             }            
  576.             return new JsonResponse(array('status' => 'success''data' => $array));    
  577.         }        
  578.     }    
  579.     
  580.     
  581.    /**
  582.      * @Route("/get-vehicle-panics", name="get-vehicle-panics", methods={"GET", "POST"})
  583.      */
  584.     public function getVehiclePanics(Request $requestEntityManagerInterface $entityManager): Response
  585.     {
  586.         
  587.         $data json_decode(file_get_contents("php://input"));             
  588.         if($data)
  589.         {   
  590.             $array = [];
  591.             $employeeId $data->eid;
  592.             $vaid $data->vaid;
  593.                        
  594.             $vehicleAssignmentFailList $entityManager->getRepository(VehiclePanic::class)->findBy([                
  595.                 'VehicleAssignment'      => $vaid                
  596.             ]);                            
  597.             foreach($vehicleAssignmentFailList as $vehicleAssignmentObj)
  598.             {
  599.                 $array[] = [
  600.                     'vehicle_panic_id' => $vehicleAssignmentObj->getVehiclePanicId(),
  601.                     'plate_number'     => $vehicleAssignmentObj->getPlateNumber(),
  602.                     'description'      => $vehicleAssignmentObj->getDescription(),
  603.                     'reason'           => $vehicleAssignmentObj->getReason(),
  604.                     'created_at'       => $vehicleAssignmentObj->getCreatedAt()->format("Y-m-d H:i:s")
  605.                 ];                                
  606.                       
  607.             }            
  608.             return new JsonResponse(array('status' => 'success''data' => $array));    
  609.         }        
  610.         return new JsonResponse(array('status' => 'error'));    
  611.     }          
  612.     /**
  613.      * @Route("/get-vehicle-fails", name="get-vehicle-fails", methods={"GET", "POST"})
  614.      */
  615.     public function getVehicleFails(Request $requestEntityManagerInterface $entityManager): Response
  616.     {
  617.         
  618.         $data json_decode(file_get_contents("php://input"));             
  619.         if($data)
  620.         {   
  621.             $array = [];
  622.             $employeeId $data->eid;
  623.             $vaid $data->vaid;
  624.                        
  625.             $vehicleAssignmentFailList $entityManager->getRepository(VehicleAssignmentFail::class)->findBy([
  626.                 'created_by_employee_id' => $employeeId,
  627.                 'VehicleAssignment'      => $vaid,
  628.                 'is_active'              => 1               
  629.             ]);                            
  630.             foreach($vehicleAssignmentFailList as $vehicleAssignmentObj)
  631.             {
  632.                 $array[] = [
  633.                     'vehicle_assignment_fail_id' => $vehicleAssignmentObj->getVehicleAssignmentFailId(),
  634.                     'plate_number'               => $vehicleAssignmentObj->getPlateNumber(),
  635.                     'description'                => $vehicleAssignmentObj->getDescription(),
  636.                     'created_at'                 => $vehicleAssignmentObj->getCreatedAt()->format("Y-m-d H:i:s")
  637.                 ];                                
  638.                       
  639.             }            
  640.             return new JsonResponse(array('status' => 'success''data' => $array));    
  641.         }        
  642.         return new JsonResponse(array('status' => 'error'));    
  643.     }          
  644.    /**
  645.      * @Route("/vehicle-assignment-complete", name="vehicle-assignment-complete", methods={"GET", "POST"})
  646.      */
  647.     public function vehicleAssignmentComplete(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  648.     {
  649.         
  650.         $data json_decode(file_get_contents("php://input"));             
  651.         if($data)
  652.         {   
  653.             $comments     $data->comments;
  654.             $currentKm    $data->currentKm;
  655.             $currentFuel  $data->currentFuel;
  656.             $pictures     $data->pictures;            
  657.             $assignmentId $data->assignmentId;
  658.             $currentLat   $data->currentLat;
  659.             $currentLng   $data->currentLng;
  660.             $base64OutgoingSignature  $data->outgoingSignature;
  661.             $base64IncomingSignature  $data->incomingSignature;
  662.             
  663.             $vehicleAssignmentObj $entityManager->getRepository(VehicleAssignment::class)->findOneBy([
  664.                 'vehicleAssignmentId' => $assignmentId
  665.             ]);                            
  666.             if($vehicleAssignmentObj)
  667.             {
  668.                 
  669.                 // ----------------------------- MILEAGE CHECK ----------------------------
  670.                 // ------------------------------------------------------------------------
  671.                 $arrayInfo    $this->getLatestMileage($helperService$entityManager$vehicleAssignmentObj->getPlateNumber());
  672.                 $mileageCheck $arrayInfo['mileageCheck'];
  673.                 $checked      $arrayInfo['checked'];
  674.                 // ------------------------------------------------------------------------
  675.                 // ----------------------------- MILEAGE CHECK ----------------------------
  676.                 if($mileageCheck $currentKm)
  677.                 {
  678.                     return new JsonResponse(array('status' => 'checked''message' => "El kilometraje actual es menor al Ãºltimo registrado ($mileageCheck) en $checked, por favor verifique y vuelva a intentar"));
  679.                 }
  680.                 $outgoingSignature $this->saveSignature($base64OutgoingSignature);
  681.                 $incomingSignature $this->saveSignature($base64IncomingSignature);
  682.                 
  683.                 $vehicleAssignmentObj->setProcessEnd(date("Y-m-d H:i:s"));
  684.                 $vehicleAssignmentObj->setMileage($currentKm);
  685.                 $vehicleAssignmentObj->setFuel($currentFuel);
  686.                 $vehicleAssignmentObj->setComments($comments);
  687.                 $vehicleAssignmentObj->setOutgoingSignature($outgoingSignature);
  688.                 $vehicleAssignmentObj->setIncomingSignature($incomingSignature);
  689.                 $vehicleAssignmentObj->setLat($currentLat);
  690.                 $vehicleAssignmentObj->setLng($currentLng);  
  691.                 $vehicleAssignmentObj->setIsDone(1);     
  692.                 $entityManager->persist($vehicleAssignmentObj);
  693.                 $entityManager->flush();    
  694.                 
  695.                 //return new JsonResponse(array('status' => 'success'));
  696.                 $step 0;
  697.                 $receiverName $vehicleAssignmentObj->getCreatedByEmployeeId()->getName();
  698.                 if(true)
  699.                 {
  700.                     $step 1;
  701.                     $newAssignment $helperService->externalDb_getVehicleAssignmentsById($vehicleAssignmentObj->getExternalId());
  702.                     if($newAssignment)
  703.                     {
  704.                         $step 2;
  705.                         $oldAssignment $newAssignment['Id_ant'];                        
  706.                         $referencedAssignment $helperService->externalDb_getVehicleAssignmentsById($newAssignment['Id_ant']);                        
  707.                         if($referencedAssignment)
  708.                         {
  709.                             $step "3a";
  710.                             $oldInitial    $referencedAssignment['KmInicial'];
  711.                             
  712.                         } else {
  713.                             $step "3b";
  714.                             $oldInitial    0;
  715.                         }
  716.                         
  717.                         $oldFinal      $currentKm;
  718.                         $calculated    $oldFinal $oldInitial;
  719.                         
  720.                         
  721.                         if($currentKm $oldInitial)
  722.                         {
  723.                             return new JsonResponse(array('status' => 'error''message' => 'El kilometraje actual no puede ser menor al kilometraje inicial del vehículo'));
  724.                         }
  725.                         if($helperService->externalDb_setVehicleAssignments($vehicleAssignmentObj->getExternalId(), $currentKm))
  726.                         {
  727.                             if($oldAssignment)
  728.                             {
  729.                                 $step 4;
  730.                                 $updateOldAssignment $helperService->externalDb_setOldVehicleAssignments($oldAssignment$currentKm$receiverName$calculated);
  731.                                 if($updateOldAssignment)
  732.                                 {
  733.                                     return new JsonResponse(array('status' => 'success''msg'=>"old_assignment"));
  734.                                 }
  735.                             }  else {
  736.                                 return new JsonResponse(array('status' => 'success''msg'=>"no_old_assignment"));
  737.                             }
  738.                         }
  739.                     
  740.                     }
  741.                     
  742.                 }
  743.                       
  744.             }            
  745.         }
  746.         $message "No se puede realizar esta acción en este momento, el proceso se quedo en el paso: ".$step;
  747.         return new JsonResponse(array('status' => 'error''message' => $message));
  748.     }      
  749.    /**
  750.      * @Route("/get-my-push", name="get-my-push", methods={"GET", "POST"})
  751.      */
  752.     public function getMyPush(Request $requestEntityManagerInterface $entityManager): Response
  753.     {
  754.         
  755.         $data json_decode(file_get_contents("php://input"));             
  756.         if($data)
  757.         {   
  758.             $token $data->token;           
  759.             $pushObj $entityManager->getRepository(PushUser::class)->findBy([
  760.                 'user'     => $token->id,                
  761.             ],['createdAt' => 'DESC']);    
  762.             
  763.             $data = [];
  764.             if($pushObj)
  765.             {
  766.                 
  767.                 foreach($pushObj as $item)
  768.                 {      
  769.                     
  770.                     $pushMain $entityManager->getRepository(Push::class)->findOneBy([
  771.                         'pushId' => $item->getPush()->getPushId()   
  772.                     ]); 
  773.                     $path $this->getProjectPaths();
  774.                     $image "";
  775.                     if($pushMain->getImagePath())
  776.                     {
  777.                         $image $path['public_path'].'uploads/'.$pushMain->getImagePath();
  778.                     } 
  779.                     $data[] = [
  780.                         'content'   => $pushMain->getTextContent(),
  781.                         'push_type' => $pushMain->getPushType(),
  782.                         'created_at'=> $pushMain->getCreatedAt()->format("Y-m-d H:i:s"),
  783.                         'image'     => $image                    
  784.                     ];
  785.                 }                              
  786.             }
  787.             return new JsonResponse(array('status' => 'success''data' => $data));
  788.         }
  789.         return new JsonResponse(array('status' => 'error''data' => $data));
  790.     }  
  791.     
  792.     
  793.     /**
  794.      * @Route("/complete-supervision", name="complete-supervision", methods={"GET", "POST"})
  795.      */
  796.     public function completeSupervision(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  797.     {
  798.         
  799.         $data json_decode(file_get_contents("php://input"));             
  800.         if($data)
  801.         {   
  802.             $supervisorId  $data->eid;           
  803.             $supervisionId $data->supervision_id;
  804.             $locationId    $data->location_id;
  805.             $agents        0;
  806.             $supervisionObj $entityManager->getRepository(Supervision::class)->findOneBy([
  807.                 'supervisionId' => $supervisionId   
  808.             ]);
  809.             if($supervisionObj)
  810.             {
  811.                 $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([
  812.                     'employeeId' => $supervisorId   
  813.                 ]); 
  814.                 $locationObj $entityManager->getRepository(Location::class)->findOneBy([
  815.                     'locationId' => $locationId   
  816.                 ]); 
  817.                 $cleanEmployees $entityManager->getRepository(Employee::class)->findBy([
  818.                     'assignedLocation' => $locationId
  819.                 ]); 
  820.                 foreach($cleanEmployees as $clean)
  821.                 {
  822.                     $clean->setAssignedLocation(null);
  823.                     $clean->setAssignedAt(null);
  824.                     $clean->setAssignedByEmployeeId(null);
  825.                     $clean->setAssignedLocationPositionId(null);
  826.                     $clean->setAssignedSupervisionId(null);
  827.                     $entityManager->persist($clean);
  828.                     $entityManager->flush();
  829.                 }
  830.                 $supervisionEmployee $entityManager->getRepository(SupervisionEmployee::class)->findBy([
  831.                     'Supervision' => $supervisionId   
  832.                 ]);
  833.                 
  834.                 foreach($supervisionEmployee as $item)
  835.                 {
  836.                     /// BRIAN ACA NUEVA VALIDACION ARMA
  837.                     /*$serial_number = $item->getInventoryWeapon();
  838.                     if( strlen($serial_number)>0 ){
  839.                     
  840.                         $idEstadoDeFuerza = $item->getEmployee()->getAlias();
  841.                         $idPuesto = $item->getSupervision()->getLocation()->getIdPuesto();
  842.                         $weapon_location_is_correct  = $helperService->externalDb_validateWeaponAssign($idEstadoDeFuerza,$idPuesto,$serial_number,$item,$supervisorObj);
  843.                     }*/
  844.                     /* TERMINA Nueva validación brian */
  845.                     
  846.                     //PARCHE PARA GUARDAR EL LOCATION_PLACE_ID EN LA SUPERVISION --------------------------------------------
  847.                     $locationEmployeeObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([
  848.                         'Employee'  => $item->getEmployee()->getEmployeeId(),
  849.                         'Location'  => $locationId,
  850.                         'is_active' => 1
  851.                     ]); 
  852.                     if($locationEmployeeObj)
  853.                     {
  854.                         //Si existe el registro de location_employee, entonces continuamos
  855.                         if($locationEmployeeObj->getLocationPlace() && $item->getLocationPlace())
  856.                         {
  857.                             //Solo actualizamos si el registro que guardo el supervisor ES diferente al que esta actualmente en location_employee
  858.                             if($locationEmployeeObj->getLocationPlace()->getLocationPlaceId() != $item->getLocationPlace()->getLocationPlaceId())
  859.                             {
  860.                                                                              
  861.                                 //Si lo encuentra, entonces vamos a dar de baja el registro, para ingresar uno nuevo
  862.                                 //para que quede la Bitacora
  863.                                 $locationEmployeeObj->setIsActive(0);   
  864.                                 $locationEmployeeObj->setUpdatedByEmployeeId($supervisorObj);
  865.                                 $locationEmployeeObj->setUpdatedAt(new \DateTime());
  866.                                 $entityManager->persist($locationEmployeeObj);
  867.                                 $entityManager->flush();
  868.                                 $newLocationPlaceObj = new LocationEmployee();
  869.                                 $newLocationPlaceObj->setEmployee($item->getEmployee());
  870.                                 $newLocationPlaceObj->setLocation($locationObj);                        
  871.                                 $newLocationPlaceObj->setLocationPlace($item->getLocationPlace());
  872.                                 $newLocationPlaceObj->setLocationPosition($item->getLocationPosition());
  873.                                 $newLocationPlaceObj->setIsActive(1);
  874.                                 $newLocationPlaceObj->setCreatedByEmployeeId($supervisorObj);
  875.                                 $newLocationPlaceObj->setCreatedAt(new \DateTime());
  876.                                 $entityManager->persist($newLocationPlaceObj);
  877.                                 $entityManager->flush();
  878.                             }
  879.                         } else {
  880.                             //Si no hay registro de Location_Place en el location_employee, entonces igual inactivamos el existente
  881.                             //Y creamos uno nuevo
  882.                             $locationEmployeeObj->setIsActive(0);   
  883.                             $locationEmployeeObj->setUpdatedByEmployeeId($supervisorObj);
  884.                             $locationEmployeeObj->setUpdatedAt(new \DateTime());
  885.                             $entityManager->persist($locationEmployeeObj);
  886.                             $entityManager->flush();
  887.                             $newLocationPlaceObj = new LocationEmployee();
  888.                             $newLocationPlaceObj->setEmployee($item->getEmployee());
  889.                             $newLocationPlaceObj->setLocation($locationObj);                        
  890.                             $newLocationPlaceObj->setLocationPlace($item->getLocationPlace());
  891.                             $newLocationPlaceObj->setLocationPosition($item->getLocationPosition());
  892.                             $newLocationPlaceObj->setIsActive(1);
  893.                             $newLocationPlaceObj->setCreatedByEmployeeId($supervisorObj);
  894.                             $newLocationPlaceObj->setCreatedAt(new \DateTime());
  895.                             $entityManager->persist($newLocationPlaceObj);
  896.                             $entityManager->flush();
  897.                             
  898.                         }
  899.                     }
  900.                     //-----------------------------------------------------------------------------------------------
  901.                     $agentObjList $entityManager->getRepository(Employee::class)->findBy([
  902.                         'employeeId' => $item->getEmployee()->getEmployeeId()   
  903.                     ]); 
  904.                     foreach($agentObjList as $agentObj)
  905.                     {
  906.                         $agentObj->setAssignedLocation($locationObj);
  907.                         $agentObj->setAssignedAt(date("Y-m-d H:i:s"));
  908.                         $agentObj->setAssignedByEmployeeId($supervisorObj);
  909.                         $agentObj->setAssignedLocationPositionId($item->getLocationPosition());
  910.                         $agentObj->setAssignedSupervisionId($supervisionObj);
  911.                         $entityManager->persist($agentObj);
  912.                         $entityManager->flush();
  913.                         $agents++;
  914.                     }
  915.                 }
  916.                 $supervisionObj->setClosedAt(date("Y-m-d H:i:s"));
  917.                 $supervisionObj->setIsCompleted(1);
  918.                 $entityManager->persist($supervisionObj);
  919.                 $entityManager->flush();
  920.             }            
  921.             return new JsonResponse(array('status' => 'success''employees' => $agents));
  922.         }
  923.         return new JsonResponse(array('status' => 'error''data' => $data));
  924.     }      
  925.     /**
  926.      * @Route("/check_supervisor_qr", name="check_supervisor_qr", methods={"GET", "POST"})
  927.      */
  928.     public function checkSupervisorQr(Request $requestEntityManagerInterface $entityManager): Response
  929.     {
  930.         
  931.         $data json_decode(file_get_contents("php://input"));             
  932.         if($data)
  933.         {   
  934.             $token $data->token;
  935.             $qr    $data->qr;  
  936.             $type  $data->type;       
  937.             
  938.             $array explode("_"$qr);
  939.             
  940.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  941.                 'citizenId'  => $array[0]
  942.             ]);
  943.             $employeeInfo = [];
  944.             if($employeeObj)
  945.             {                
  946.                 $locationEmployeeObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([
  947.                     'Employee'  => $employeeObj->getEmployeeId(),
  948.                     'is_active' => 1
  949.                 ]); 
  950.                 if($locationEmployeeObj)
  951.                 {
  952.                     $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([
  953.                         'employeeId'  => $token->employee_id                        
  954.                     ]); 
  955.                     if($supervisorObj)
  956.                     {
  957.                         $supervisionId 0;
  958.                         if($type == 'create')
  959.                         {
  960.                             $projectObj null;
  961.                             if($locationEmployeeObj->getLocation()->getProject())
  962.                             {
  963.                                 $projectObj $locationEmployeeObj->getLocation()->getProject();
  964.                             }
  965.                             $supervision = new Supervision();                    
  966.                             $supervision->setProject($projectObj);
  967.                             $supervision->setLocation($locationEmployeeObj->getLocation());                
  968.                             $supervision->setIsActive(1);
  969.                             $supervision->setCreatedAt(new \DateTime());
  970.                             $supervision->setCreatedByEmployeeId($supervisorObj);
  971.                             $entityManager->persist($supervision);
  972.                             $entityManager->flush();
  973.                             $supervisionId $supervision->getSupervisionId();
  974.                         }
  975.                         if($locationEmployeeObj->getLocation()->getProject())
  976.                         {
  977.                             $projectName $locationEmployeeObj->getLocation()->getProject()->getName();
  978.                             $projectId   $locationEmployeeObj->getLocation()->getProject()->getProjectId();
  979.                         } else {
  980.                             $projectName '-';
  981.                             $projectId   '0';
  982.                         }
  983.                         
  984.                         $employees = [];
  985.                         $data = [                        
  986.                             'supervision_id' => $supervisionId,
  987.                             'project_id'     => $projectId,
  988.                             'project_name'   => $projectName,
  989.                             'location_id'    => $locationEmployeeObj->getLocation()->getLocationId(),
  990.                             'location_name'  => $locationEmployeeObj->getLocation()->getName(),                        
  991.                             'employees'      => $employees
  992.                         ];
  993.                         return new JsonResponse(array('status' => 'success''data' => $data));
  994.                     }
  995.                 } else {
  996.                     return new JsonResponse(array('status' => 'error''msg' => 'No se encuentra un puesto asignado a este empleado'));
  997.                 }
  998.             } else {
  999.                 return new JsonResponse(array('status' => 'error''msg' => 'No se encuentra el empleado asignado a este QR'));
  1000.             }                                            
  1001.         }
  1002.         return new JsonResponse(array('status' => 'error''msg' => 'La solicitud es invalida'));
  1003.     }
  1004.     /**
  1005.      * @Route("/account-selector", name="account-selector", methods={"GET", "POST"})
  1006.      */
  1007.     public function accountSelector(Request $requestEntityManagerInterface $entityManager): Response
  1008.     {
  1009.         
  1010.         $data json_decode(file_get_contents("php://input"));             
  1011.         if($data)
  1012.         {   
  1013.             $requestType $data->request_type;
  1014.             $employeeId  $data->employee_id;           
  1015.             $accounts    = [];
  1016.             $userObj $entityManager->getRepository(Employee::class)->findOneBy([
  1017.                 'employeeId'  => $employeeId
  1018.             ]);    
  1019.             if($userObj)
  1020.             {
  1021.                 /*$clients = $entityManager->getRepository(Client::class)->findBy([
  1022.                     'isActive'  => 1
  1023.                 ]);*/ 
  1024.                   
  1025.                 //foreach($clients as $client) 
  1026.                 //{
  1027.                     $projects = [];
  1028.                     $projectsObj $entityManager->getRepository(Project::class)->findBy([
  1029.                         //'client'     => $client->getClientId(),
  1030.                         'isActive'  => 1
  1031.                     ], ['name' => 'ASC']);                     
  1032.                     foreach($projectsObj as $project)
  1033.                     {
  1034.                         $locations = [];
  1035.                         $locationsObj $entityManager->getRepository(Location::class)->findBy([
  1036.                             'project'     => $project->getProjectId(),
  1037.                             'isActive'  => 1
  1038.                         ]); 
  1039.                         foreach($locationsObj as $location)
  1040.                         {
  1041.                             if($requestType == 'electronic')
  1042.                             {
  1043.                                 $checkService $entityManager->getRepository(LocationService::class)->findOneBy([
  1044.                                     'Location'  => $location->getLocationId(),
  1045.                                     'Service'   => 2,
  1046.                                     'is_active'  => 1
  1047.                                 ]);
  1048.                                 if(!$checkService)
  1049.                                 {
  1050.                                     continue;
  1051.                                 }
  1052.                             }
  1053.                             if($requestType == 'reaction')
  1054.                             {
  1055.                                 $checkService $entityManager->getRepository(LocationService::class)->findOneBy([
  1056.                                     'Location'  => $location->getLocationId(),
  1057.                                     /*'Service'   => 1, Por solicitud de Douglas el 8 de junio se quito esta condición */
  1058.                                     'is_active'  => 1
  1059.                                 ]);
  1060.                                 if(!$checkService)
  1061.                                 {
  1062.                                     continue;
  1063.                                 }
  1064.                             }
  1065.                             $locations[] = [
  1066.                                 'location_id' => $location->getLocationId(),
  1067.                                 'name'        => $location->getName(),
  1068.                                 'address'     => $location->getAddress()
  1069.                             ];
  1070.                         }
  1071.                         $projects[] = [
  1072.                             'project_id' => $project->getProjectId(),
  1073.                             'name'       => $project->getName(),
  1074.                             'locations'  => $locations
  1075.                         ];
  1076.                     }
  1077.                     /*$accounts[] = [
  1078.                         'client_id' => $client->getClientId(),
  1079.                         'name'      => $client->getName(),
  1080.                         'projects'  => $projects
  1081.                     ];*/
  1082.                     $accounts $projects;
  1083.                 //}
  1084.                                                   
  1085.                 return new JsonResponse(array('status' => 'success''accounts' => $accounts));
  1086.                
  1087.             }
  1088.         }
  1089.         return new JsonResponse(array('status' => 'error'));
  1090.     }   
  1091.   
  1092.     
  1093.     /**
  1094.      * @Route("/reaction-create", name="reaction-create", methods={"GET", "POST"})
  1095.      */
  1096.     public function reactionCreate(Request $requestEntityManagerInterface $entityManager): Response
  1097.     {
  1098.         
  1099.         $data json_decode(file_get_contents("php://input"));             
  1100.         if($data)
  1101.         {   
  1102.             $employeeId     $data->employeeId;
  1103.             $reactionId     $data->reactionId;
  1104.             $timeArrival    $data->timeArrival;
  1105.             $timeExit       $data->timeExit;            
  1106.             $contact        $data->contact;
  1107.             $comments       $data->comments;            
  1108.             $base64SignaturePatrolman $data->signaturePatrolman;
  1109.             $base64SignatureClient    $data->signatureClient;
  1110.             $lat false;
  1111.             if($data->lat)
  1112.             {
  1113.                 $lat $data->lat;
  1114.             }
  1115.             $lng false;
  1116.             if($data->lng)
  1117.             {
  1118.                 $lng  $data->lng;
  1119.             }
  1120.             if($employeeId && $timeArrival && $contact)
  1121.             {
  1122.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  1123.                     'employeeId'  => $employeeId
  1124.                 ]);  
  1125.                 
  1126.                 if($employeeObj)
  1127.                 {
  1128.                     
  1129.                     //--------------------------------
  1130.                     $employeeObj->setAppStatus('ACTIVO');
  1131.                     $employeeObj->setAppStatusUpdatedAt(new \DateTime());
  1132.                     $entityManager->persist($employeeObj);
  1133.                     $entityManager->flush();
  1134.                     //Se guarda el registro en el log
  1135.                     $statusLog = new EmployeeStatusLog();
  1136.                     $statusLog->setEmployee($employeeObj);
  1137.                     $statusLog->setNewStatus('ACTIVO');
  1138.                     $statusLog->setCreatedAt(new \DateTime());                
  1139.                     $entityManager->persist($statusLog);
  1140.                     $entityManager->flush();
  1141.                     //--------------------------------
  1142.                     $signaturePatrolman $this->saveSignature($base64SignaturePatrolman);
  1143.                     if($base64SignatureClient)
  1144.                     {
  1145.                         $signatureClient    $this->saveSignature($base64SignatureClient);
  1146.                     }
  1147.                     $latLng "";
  1148.                     if($lat && $lng)
  1149.                     {
  1150.                         $latLng $lat.",".$lng;
  1151.                     }
  1152.                     $reactionObj $entityManager->getRepository(Reaction::class)->findOneBy([
  1153.                         'reactionId'  => $reactionId     
  1154.                     ]);  
  1155.                     if($reactionObj)
  1156.                     {                                                         
  1157.                         $reactionObj->setTimeArrival($timeArrival);
  1158.                         $reactionObj->setTimeExit(date("H:i"));
  1159.                         $reactionObj->setContact($contact);
  1160.                         $reactionObj->setComments($comments);
  1161.                         $reactionObj->setLatLng($latLng);
  1162.                         $reactionObj->setSignaturePatrolman($signaturePatrolman);
  1163.                         if($base64SignatureClient)
  1164.                         {
  1165.                             $reactionObj->setSignatureClient($signatureClient);
  1166.                         }
  1167.                         $reactionObj->setUpdatedAt(new \DateTime());
  1168.                         $reactionObj->setCreatedByEmployeeId($employeeObj);
  1169.                         $reactionObj->setIsActive(1);
  1170.                         $reactionObj->setIsDone(1);
  1171.                         $entityManager->persist($reactionObj);
  1172.                         $entityManager->flush();
  1173.                         return new JsonResponse(array('status' => 'success''data' => $reactionObj->getReactionId()));
  1174.                     }
  1175.                     return new JsonResponse(array('status' => 'invalid'));
  1176.                 }
  1177.             }           
  1178.         }
  1179.         return new JsonResponse(array('status' => 'error'));
  1180.     } 
  1181.     /**
  1182.      * @Route("/get-techs", name="get-techs", methods={"GET", "POST"})
  1183.      */
  1184.     public function getTechs(Request $requestEntityManagerInterface $entityManager): Response
  1185.     {
  1186.         
  1187.         $data json_decode(file_get_contents("php://input"));             
  1188.         if($data)
  1189.         {   
  1190.             $employeeObj $entityManager->getRepository(Employee::class)->findBy([
  1191.                 'jobPosition'    => 4,
  1192.                 'employeeStatus' => 1
  1193.             ]); 
  1194.             $list = [];
  1195.             foreach($employeeObj as $item)
  1196.             {
  1197.                 $list[] = [
  1198.                     'employee_id' => $item->getEmployeeId(),
  1199.                     'name'        => $item->getName()  
  1200.                 ];
  1201.             }
  1202.             return new JsonResponse(array('status' => 'success''data' => $list));            
  1203.         }
  1204.         return new JsonResponse(array('status' => 'error'));
  1205.     }
  1206.     /**
  1207.      * @Route("/get-employees", name="get-employees", methods={"GET", "POST"})
  1208.      */
  1209.     public function getEmployees(Request $requestEntityManagerInterface $entityManager): Response
  1210.     {
  1211.         
  1212.         $data json_decode(file_get_contents("php://input"));             
  1213.         if($data)
  1214.         {   
  1215.             $employeeObj $entityManager->getRepository(Employee::class)->findBy([                
  1216.                 'employeeStatus' => 1
  1217.             ], ['name' => 'ASC']); 
  1218.             $list = [];
  1219.             foreach($employeeObj as $item)
  1220.             {
  1221.                 $list[] = [
  1222.                     'employee_id' => $item->getEmployeeId(),
  1223.                     'name'        => $item->getName()  
  1224.                 ];
  1225.             }
  1226.             return new JsonResponse(array('status' => 'success''data' => $list));            
  1227.         }
  1228.         return new JsonResponse(array('status' => 'error'));
  1229.     }
  1230.     /**
  1231.      * @Route("/external-vehicle-assignments", name="external-vehicle-assignments", methods={"GET", "POST"})
  1232.      */
  1233.     public function externalVehicleAssignments(Request $requestHelperService $helperServiceEntityManagerInterface $entityManager): Response
  1234.     {
  1235.         
  1236.         $data json_decode(file_get_contents("php://input"));             
  1237.         if($data)
  1238.         {   
  1239.             $list       = [];
  1240.             $employeeId $data->eid;
  1241.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  1242.                 'employeeId' => $employeeId
  1243.             ]); 
  1244.             if($employeeObj)
  1245.             {
  1246.                 $list $helperService->externalDb_getVehicleAssignments($employeeObj->getName());                                    
  1247.             }
  1248.                                   
  1249.         }
  1250.         return new JsonResponse(array('status' => 'success''data' => $list));
  1251.     }   
  1252.     
  1253.     
  1254.     /**
  1255.      * @Route("/external-vehicle-confirm-manage", name="external-vehicle-confirm-manage", methods={"GET", "POST"})
  1256.      */
  1257.     public function externalVehicleConfirmManage(Request $requestHelperService $helperServiceEntityManagerInterface $entityManager): Response
  1258.     {
  1259.         
  1260.         $data json_decode(file_get_contents("php://input"));             
  1261.         if($data)
  1262.         {   
  1263.             $list       = [];
  1264.             $employeeId   $data->eid;
  1265.             $assignmentId $data->assignment_id;
  1266.             $vehicleAssignmentObj $entityManager->getRepository(VehicleAssignment::class)->findOneBy([
  1267.                 'vehicleAssignmentId' => $assignmentId
  1268.             ]); 
  1269.             if($vehicleAssignmentObj)
  1270.             {
  1271.                 
  1272.                 $checklistArray $entityManager->getRepository(VehicleChecklist::class)->findBy([
  1273.                     'is_active' => 1
  1274.                 ]); 
  1275.                 $checklist = [];
  1276.                 foreach($checklistArray as $item)
  1277.                 {
  1278.                     $checklist[] = [
  1279.                         'vehicle_checklist_id' => $item->getVehicleChecklistId(),
  1280.                         'name'                 => $item->getName(),
  1281.                         'isChecked'            => 0                        
  1282.                     ];                    
  1283.                 }
  1284.                 $pictures $this->getVehicleFiles($entityManager$assignmentId);
  1285.                 $list = [
  1286.                     'checklist' => $checklist,
  1287.                     'pictures'  => $pictures
  1288.                 ];
  1289.                 
  1290.                 return new JsonResponse(array('status' => 'success''data' => $list));
  1291.             }
  1292.                                   
  1293.         }
  1294.         return new JsonResponse(array('status' => 'error'));
  1295.     }       
  1296.     /**
  1297.      * @Route("/external-vehicle-manage-assignment", name="external-vehicle-manage-assignment", methods={"GET", "POST"})
  1298.      */
  1299.     public function externalVehicleManageAssignments(Request $requestHelperService $helperServiceEntityManagerInterface $entityManager): Response
  1300.     {
  1301.         
  1302.         $data json_decode(file_get_contents("php://input"));             
  1303.         if($data)
  1304.         {   
  1305.             $list       = [];
  1306.             $employeeId $data->eid;
  1307.             $externalId $data->external_id;
  1308.             $plate      $data->plate;
  1309.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  1310.                 'employeeId' => $employeeId
  1311.             ]); 
  1312.             if($employeeObj)
  1313.             {
  1314.                 
  1315.                 $vehicleAssignmentObj $entityManager->getRepository(VehicleAssignment::class)->findOneBy([
  1316.                     'created_by_employee_id' => $employeeId,
  1317.                     'plate_number'           => $plate,
  1318.                     'external_id'            => $externalId
  1319.                 ]); 
  1320.                 if(!$vehicleAssignmentObj)
  1321.                 {
  1322.                     $vehicleAssignmentObj = new VehicleAssignment();                    
  1323.                     $vehicleAssignmentObj->setPlateNumber($plate);
  1324.                     $vehicleAssignmentObj->setExternalId($externalId);
  1325.                     $vehicleAssignmentObj->setIsActive(1);                    
  1326.                     $vehicleAssignmentObj->setIsDone(0);
  1327.                     $vehicleAssignmentObj->setIsReturned(0);
  1328.                     $vehicleAssignmentObj->setProcessStart(date("Y-m-d H:i:s"));
  1329.                     $vehicleAssignmentObj->setCreatedAt(new \DateTime());
  1330.                     $vehicleAssignmentObj->setCreatedByEmployeeId($employeeObj);
  1331.                     $entityManager->persist($vehicleAssignmentObj);
  1332.                     $entityManager->flush();
  1333.                     return new JsonResponse(array('status' => 'success''id' => $vehicleAssignmentObj->getVehicleAssignmentId()));
  1334.                 } else {
  1335.                     return new JsonResponse(array('status' => 'exists''id' => $vehicleAssignmentObj->getVehicleAssignmentId()));
  1336.                 }
  1337.             }
  1338.                                   
  1339.         }
  1340.         return new JsonResponse(array('status' => 'success''data' => $list));
  1341.     }    
  1342.     /**
  1343.      * @Route("/update-employee-status", name="update-employee-status", methods={"GET", "POST"})
  1344.      */
  1345.     public function updateEmployeeStatus(Request $requestEntityManagerInterface $entityManager): Response
  1346.     {
  1347.         
  1348.         $data json_decode(file_get_contents("php://input"));             
  1349.         if($data)
  1350.         {   
  1351.             $employeeId  $data->employee_id;
  1352.             $newStatus   $data->new_status;
  1353.             $description $data->description;
  1354.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  1355.                 'employeeId' => $employeeId                
  1356.             ]); 
  1357.             
  1358.             if($employeeObj)
  1359.             {
  1360.                 if($newStatus == true)
  1361.                 {
  1362.                     $status 'ACTIVO';
  1363.                 } else {
  1364.                     $status 'INACTIVO';
  1365.                 }
  1366.                 $employeeObj->setAppStatus($status);
  1367.                 $employeeObj->setAppStatusDescription($description);
  1368.                 $employeeObj->setAppStatusUpdatedAt(new \DateTime());
  1369.                 $entityManager->persist($employeeObj);
  1370.                 $entityManager->flush();
  1371.                 //Se guarda el registro en el log
  1372.                 $statusLog = new EmployeeStatusLog();
  1373.                 $statusLog->setEmployee($employeeObj);
  1374.                 $statusLog->setNewStatus($status);
  1375.                 if($status == 'INACTIVO')
  1376.                 {
  1377.                     $statusLog->setDescription($description);
  1378.                 }
  1379.                 $statusLog->setCreatedAt(new \DateTime());                
  1380.                 $entityManager->persist($statusLog);
  1381.                 $entityManager->flush();
  1382.                 return new JsonResponse(array('status' => 'success'));
  1383.             }
  1384.         }
  1385.         return new JsonResponse(array('status' => 'error'));
  1386.     }    
  1387.     /**
  1388.      * @Route("/get-locations", name="get-locations", methods={"GET", "POST"})
  1389.      */
  1390.     public function getLocations(Request $requestEntityManagerInterface $entityManager): Response
  1391.     {
  1392.         
  1393.         $data json_decode(file_get_contents("php://input"));             
  1394.         if($data)
  1395.         {   
  1396.             $clientId $data->client_id;
  1397.             if($clientId == 0)
  1398.             {
  1399.                 $locationList $entityManager->getRepository(Location::class)->findBy([                    
  1400.                     'isActive' => 1                
  1401.                 ],['name' => 'ASC']); 
  1402.             } else {
  1403.                 $locationList $entityManager->getRepository(Location::class)->findBy([
  1404.                     'client'    => $clientId,
  1405.                     'isActive' => 1                
  1406.                 ],['name' => 'ASC']); 
  1407.             }
  1408.             $list = [];
  1409.             foreach($locationList as $item)
  1410.             {
  1411.                 $placeList $entityManager->getRepository(LocationPlace::class)->findBy([
  1412.                     'Location'  => $item->getLocationId(),
  1413.                     'is_active' => 1                
  1414.                 ],['name' => 'ASC']); 
  1415.                 $places = [];
  1416.                 foreach($placeList as $subitem)
  1417.                 {
  1418.                     $places[] = [
  1419.                         'location_place_id' => $subitem->getLocationPlaceId(),
  1420.                         'name' => $subitem->getName()
  1421.                     ];
  1422.                 }
  1423.                 $list[] = [
  1424.                     'location_id'    => $item->getLocationId(),
  1425.                     'name'           => $item->getName(),
  1426.                     'places'         => $places                    
  1427.                 ];
  1428.             }
  1429.             return new JsonResponse(array('status' => 'success''data' => $list));            
  1430.         }
  1431.         return new JsonResponse(array('status' => 'error'));
  1432.     }    
  1433.    /**
  1434.      * @Route("/property-report-update", name="get-property-report-update", methods={"GET", "POST"})
  1435.      */
  1436.     public function propertyReportUpdate(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  1437.     {
  1438.         
  1439.         $data json_decode(file_get_contents("php://input"));             
  1440.         if($data)
  1441.         {   
  1442.             $detailId $data->property_report_detail_id;
  1443.             $token    $data->token;
  1444.             $employeeId      $data->employee_id;
  1445.             $locationId      $data->location_id;
  1446.             $locationPlaceId $data->location_place_id;
  1447.             $comments        $data->comments;
  1448.             $remove          $data->remove;
  1449.             $propertyReportDetailObj $entityManager->getRepository(PropertyReportDetail::class)->findOneBy([
  1450.                 'propertyReportDetailId' => $detailId              
  1451.             ]);             
  1452.             if($propertyReportDetailObj)
  1453.             {
  1454.                 $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([
  1455.                     'employeeId' => $token->employee_id              
  1456.                 ]); 
  1457.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  1458.                     'employeeId' => $employeeId              
  1459.                 ]); 
  1460.                 if($remove == 0)
  1461.                 {
  1462.                     $locationObj $entityManager->getRepository(Location::class)->findOneBy([
  1463.                         'locationId' => $locationId              
  1464.                     ]); 
  1465.                     $locationPlaceObj $entityManager->getRepository(LocationPlace::class)->findOneBy([
  1466.                         'locationPlaceId' => $locationPlaceId              
  1467.                     ]); 
  1468.                     $propertyReportDetailObj->setLocation($locationObj);
  1469.                     $propertyReportDetailObj->setLocationPlace($locationPlaceObj);
  1470.                     $systemComments "El supervisor ".$supervisorObj->getName()." asigno como REFUERZO a ".$employeeObj->getName()." en el puesto ".$locationObj->getName()." y en la ubicación ".$locationPlaceObj->getName();
  1471.                 } else {
  1472.                     $systemComments "El supervisor ".$supervisorObj->getName()." QUITO a ".$employeeObj->getName()." como REFUERZO";
  1473.                     $propertyReportDetailObj->setLocation(null);
  1474.                     $propertyReportDetailObj->setLocationPlace(null);
  1475.                 }
  1476.                 $propertyReportDetailObj->setSupervisorComments($comments);
  1477.                 $propertyReportDetailObj->setUpdatedAt(new \DateTime());
  1478.                 $propertyReportDetailObj->setUpdatedBy(null);
  1479.                 $propertyReportDetailObj->setUpdatedByEmployeeId($supervisorObj);
  1480.                 $entityManager->persist($propertyReportDetailObj);
  1481.                 $entityManager->flush();
  1482.                 
  1483.                 $helperService->registerPropertyReportLog($propertyReportDetailObj->getPropertyReportDetailId(), $systemComments$supervisorObjtrue);
  1484.                 
  1485.                 return new JsonResponse(array('status' => 'success'));            
  1486.                 
  1487.             }            
  1488.         }
  1489.         return new JsonResponse(array('status' => 'error'));
  1490.     }    
  1491.     /**
  1492.      * @Route("/get-property-reports", name="get-property-reports", methods={"GET", "POST"})
  1493.      */
  1494.     public function getPropertyReports(Request $requestEntityManagerInterface $entityManager): Response
  1495.     {
  1496.         
  1497.         $data json_decode(file_get_contents("php://input"));             
  1498.         if($data)
  1499.         {   
  1500.             $propertyReportList $entityManager->getRepository(PropertyReport::class)->findBy([
  1501.                 'is_close'  => 0,
  1502.                 'is_active' => 1                
  1503.             ]); 
  1504.             $list = [];
  1505.             foreach($propertyReportList as $item)
  1506.             {
  1507.                 $list[] = [
  1508.                     'property_report_id'  => $item->getPropertyReportId(),
  1509.                     'name'                => strtoupper($item->getName()),
  1510.                     'comments'            => $item->getComments(),                    
  1511.                     'total_strength'      => $item->getTotalStrength(),
  1512.                     'report_date'         => $item->getReportDate(),
  1513.                     'client_id'           => $item->getClient()->getClientId(),
  1514.                     'client_name'         => $item->getClient()->getName(),
  1515.                     'created_at'          => $item->getCreatedAt()->format("Y-m-d H:i:s"),
  1516.                     'created_by'          => $item->getCreatedBy()->getFirstName()." ".$item->getCreatedBy()->getLastName()
  1517.                 ];
  1518.             }
  1519.             return new JsonResponse(array('status' => 'success''data' => $list));            
  1520.         }
  1521.         return new JsonResponse(array('status' => 'error'));
  1522.     }
  1523.     /**
  1524.      * @Route("/get-property-report-detail", name="get-property-report-detail", methods={"GET", "POST"})
  1525.      */
  1526.     public function getPropertyReportDetail(Request $requestEntityManagerInterface $entityManager): Response
  1527.     {
  1528.         
  1529.         $data json_decode(file_get_contents("php://input"));             
  1530.         if($data)
  1531.         {   
  1532.             $propertyReportId $data->property_report_id;
  1533.             $list $entityManager->getRepository(PropertyReportDetail::class)->findBy([
  1534.                 'PropertyReport'  => $propertyReportId,
  1535.                 'PropertyReportAction' => 2,
  1536.                 'is_active' => 1                
  1537.             ]); 
  1538.             $assigned  = [];
  1539.             $available = [];
  1540.             foreach($list as $item)
  1541.             {
  1542.                 //Si el empleado ya esta asignado
  1543.                 if($item->getEmployee())
  1544.                 {
  1545.                     $path $this->getProjectPaths();
  1546.                     if($item->getEmployee()->getAvatarPath())
  1547.                     {
  1548.                         $avatar $path['public_path'].'uploads/'.$item->getEmployee()->getAvatarPath();
  1549.                     } else {
  1550.                         $avatar $path['public_path'].'assets/img/empty_user.png';
  1551.                     }
  1552.                     
  1553.                     //Si ya esta como asignado
  1554.                     if($item->getLocation())
  1555.                     {
  1556.                         $search $item->getEmployee()->getName();
  1557.                         
  1558.                         $assigned[] = [
  1559.                             'property_report_detail_id'   => $item->getPropertyReportDetailId(),
  1560.                             'property_report_action_id'   => $item->getPropertyReportAction()->getPropertyReportActionId(),
  1561.                             'property_report_action_name' => $item->getPropertyReportAction()->getName(),
  1562.                             'property_report_id'          => $item->getPropertyReport()->getPropertyReportId(),
  1563.                             'client_id'                   => $item->getPropertyReport()->getClient()->getClientId(),
  1564.                             'employee_id'                 => $item->getEmployee()->getEmployeeId(),
  1565.                             'employee_name'               => $item->getEmployee()->getName(),
  1566.                             'position'                    => $item->getEmployee()->getJobPosition()->getName(),
  1567.                             'avatar'                      => $avatar,
  1568.                             'company_id'                  => ($item->getCompany() ? $item->getCompany()->getCompanyId() : null),
  1569.                             'company_name'                => ($item->getCompany() ? $item->getCompany()->getName() : null),
  1570.                             'location_id'                 => ($item->getLocation() ? $item->getLocation()->getLocationId() : null),
  1571.                             'location_name'               => ($item->getLocation() ? $item->getLocation()->getName() : null),
  1572.                             'location_place_id'           => ($item->getLocationPlace() ? $item->getLocationPlace()->getLocationPlaceId() : null),
  1573.                             'location_place_name'         => ($item->getLocationPlace() ? $item->getLocationPlace()->getName() : null),   
  1574.                             'supervisor_comments'         => $item->getSupervisorComments(),
  1575.                             'comments'                    => $item->getComments(),    
  1576.                             'service'                     => $item->getService(),    
  1577.                             'takeover'                    => $item->getTakeover(),    
  1578.                             'assigned_group'              => $item->getAssignedGroup(),
  1579.                             'visible'                     => 1,
  1580.                             'search'                      => $search
  1581.                         ];
  1582.                     } else {
  1583.                     //Si NO tiene asignacion
  1584.                         $search $item->getEmployee()->getName();
  1585.                         $available[] = [
  1586.                             'property_report_detail_id'   => $item->getPropertyReportDetailId(),
  1587.                             'property_report_action_id'   => $item->getPropertyReportAction()->getPropertyReportActionId(),
  1588.                             'property_report_action_name' => $item->getPropertyReportAction()->getName(),
  1589.                             'property_report_id'          => $item->getPropertyReport()->getPropertyReportId(),
  1590.                             'client_id'                   => $item->getPropertyReport()->getClient()->getClientId(),
  1591.                             'employee_id'                 => $item->getEmployee()->getEmployeeId(),
  1592.                             'employee_name'               => $item->getEmployee()->getName(),
  1593.                             'position'                    => $item->getEmployee()->getJobPosition()->getName(),
  1594.                             'avatar'                      => $avatar,
  1595.                             'company_id'                  => ($item->getCompany() ? $item->getCompany()->getCompanyId() : null),
  1596.                             'company_name'                => ($item->getCompany() ? $item->getCompany()->getName() : null),
  1597.                             'location_id'                 => null,
  1598.                             'location_name'               => null,
  1599.                             'location_place_id'           => null,
  1600.                             'location_place_name'         => null,   
  1601.                             'supervisor_comments'         => null,
  1602.                             'comments'                    => $item->getComments(),    
  1603.                             'service'                     => $item->getService(),    
  1604.                             'takeover'                    => $item->getTakeover(),    
  1605.                             'assigned_group'              => $item->getAssignedGroup(),
  1606.                             'visible'                     => 1,
  1607.                             'search'                      => $search
  1608.                         ];
  1609.                     }
  1610.                 }
  1611.             }
  1612.             return new JsonResponse(array('status' => 'success''available' => $available'assigned' => $assigned));            
  1613.         }
  1614.         return new JsonResponse(array('status' => 'error'));
  1615.     }    
  1616.     /**   
  1617.      * @Route("/set-location-place-old", name="ws_set_location_place_old", methods={"GET", "POST"})
  1618.      */
  1619.     public function setLocationPlaceOld(Request $requestEntityManagerInterface $entityManager): Response
  1620.     {
  1621.         
  1622.         $data json_decode(file_get_contents("php://input"));             
  1623.         if($data)
  1624.         {   
  1625.             
  1626.             $employeeId      $data->employeeId;
  1627.             $locationId      $data->locationId;
  1628.             $locationPlaceId $data->locationPlaceId;
  1629.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  1630.                 'employeeId' => $employeeId
  1631.             ]); 
  1632.             $locationEmployeeObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([
  1633.                 'Location' => $locationId,
  1634.                 'Employee' => $employeeId
  1635.             ]);     
  1636.             
  1637.             if($locationEmployeeObj)
  1638.             {
  1639.                 //EXISTE la asignacion de location_place???
  1640.                 if($locationEmployeeObj->getLocationPlace())
  1641.                 {
  1642.                     //Si ya existe, solo debe actualizar en caso lo que el supervisor reporta sea DIFERENTE a lo que ya existe
  1643.                     if($locationEmployeeObj->getLocationPlace()->getLocationPlaceId() <> $locationPlaceId)
  1644.                     {                        
  1645.                         $locationEmployeeObj->setIsActive(0);
  1646.                         $locationEmployeeObj->setUpdatedByEmployeeId($employeeObj);
  1647.                         $locationEmployeeObj->setUpdatedAt(new \DateTime());
  1648.                         $entityManager->persist($locationEmployeeObj);
  1649.                         $entityManager->flush();
  1650.                         $locationPlaceObj $entityManager->getRepository(LocationPlace::class)->findOneBy([
  1651.                             'locationPlaceId' => $locationPlaceId                    
  1652.                         ]);
  1653.                         $newLocationEmployee = new LocationEmployee();
  1654.                         $newLocationEmployee->setLocation($locationEmployeeObj->getLocation());
  1655.                         $newLocationEmployee->setEmployee($locationEmployeeObj->getEmployee());
  1656.                         $newLocationEmployee->setLocationPosition($locationEmployeeObj->getLocationPosition());
  1657.                         $newLocationEmployee->setLocationPlace($locationPlaceObj);
  1658.                         $newLocationEmployee->setIsActive(1);
  1659.                         $newLocationEmployee->setCreatedByEmployeeId($employeeObj);
  1660.                         $newLocationEmployee->setCreatedAt(new \DateTime());
  1661.                         $entityManager->persist($newLocationEmployee);
  1662.                         $entityManager->flush();
  1663.                     }
  1664.                 } else {
  1665.                     //Si no existe la asignacion de location_place, es poqrue no le han asignado nada asi que igual tenemos que crear nuevo registro para llevar bitacora
  1666.                     
  1667.                     $locationEmployeeObj->setIsActive(0);
  1668.                     $locationEmployeeObj->setUpdatedByEmployeeId($employeeObj);
  1669.                     $locationEmployeeObj->setUpdatedAt(new \DateTime());
  1670.                     $entityManager->persist($locationEmployeeObj);
  1671.                     $entityManager->flush();
  1672.                     $locationPlaceObj $entityManager->getRepository(LocationPlace::class)->findOneBy([
  1673.                         'locationPlaceId' => $locationPlaceId                    
  1674.                     ]);
  1675.                     $newLocationEmployee = new LocationEmployee();
  1676.                     $newLocationEmployee->setLocation($locationEmployeeObj->getLocation());
  1677.                     $newLocationEmployee->setEmployee($locationEmployeeObj->getEmployee());
  1678.                     $newLocationEmployee->setLocationPosition($locationEmployeeObj->getLocationPosition());
  1679.                     $newLocationEmployee->setLocationPlace($locationPlaceObj);
  1680.                     $newLocationEmployee->setIsActive(1);
  1681.                     $newLocationEmployee->setCreatedByEmployeeId($employeeObj);
  1682.                     $newLocationEmployee->setCreatedAt(new \DateTime());
  1683.                     $entityManager->persist($newLocationEmployee);
  1684.                     $entityManager->flush();
  1685.                     
  1686.                 }
  1687.                 return new JsonResponse(array('status' => 'success'));
  1688.             }
  1689.                         
  1690.         }                                     
  1691.         return new JsonResponse(array('status' => 'error'));
  1692.     }
  1693.     /**
  1694.      * @Route("/set-location-position", name="ws_set_location_position", methods={"GET", "POST"})
  1695.      */
  1696.     public function setLocationPosition(Request $requestEntityManagerInterface $entityManager): Response
  1697.     {
  1698.         
  1699.         $data json_decode(file_get_contents("php://input"));             
  1700.         if($data)
  1701.         {   
  1702.             $supervisor    $data->supervisor;
  1703.             $supervisionId $data->supervisionId;
  1704.             $employeeId    $data->employeeId;
  1705.             $locationPositionId $data->locationPositionId;
  1706.             $locationEmployeeId $data->locationEmployeeId;
  1707.             $supervisionEmployeeObj $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  1708.                 'Supervision' => $supervisionId,
  1709.                 'Employee'    => $employeeId
  1710.             ]);     
  1711.             
  1712.             $locationPositionObj $entityManager->getRepository(LocationPosition::class)->findOneBy([
  1713.                 'locationPositionId' => $locationPositionId
  1714.             ]);     
  1715.             $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  1716.                 'employeeId'    => $supervisor->employee_id
  1717.             ]);
  1718.             $supervisionObj $entityManager->getRepository(Supervision::class)->findOneBy([                        
  1719.                 'supervisionId'    => $supervisionId
  1720.             ]);
  1721.             $agentObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  1722.                 'employeeId'    => $employeeId
  1723.             ]);
  1724.             //Esto es por los cambios que se hicieron en conexión con el sistema externo
  1725.             $locationEmployeeObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([                        
  1726.                 'locationEmployeeId'    => $locationEmployeeId
  1727.             ]);
  1728.             if($locationEmployeeObj)
  1729.             {
  1730.                 $locationPositionObj $entityManager->getRepository(LocationPosition::class)->findOneBy([                        
  1731.                     'locationPositionId' => $locationPositionId
  1732.                 ]);
  1733.                 $locationEmployeeObj->setLocationPosition($locationPositionObj);
  1734.                 $entityManager->persist($locationEmployeeObj);
  1735.                 $entityManager->flush();
  1736.             }
  1737.             if($supervisionEmployeeObj)
  1738.             {       
  1739.                 $supervisionEmployeeObj->setSupervision($supervisionObj);
  1740.                 $supervisionEmployeeObj->setEmployee($agentObj);
  1741.                 $supervisionEmployeeObj->setLocationPosition($locationPositionObj);
  1742.                 $supervisionEmployeeObj->setIsActive(1);            
  1743.                 $supervisionEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  1744.                 $entityManager->persist($supervisionEmployeeObj);
  1745.                 $entityManager->flush();
  1746.             } else {                                                                
  1747.                 $supervisionEmployeeObj = new SupervisionEmployee();
  1748.                 $supervisionEmployeeObj->setSupervision($supervisionObj);
  1749.                 $supervisionEmployeeObj->setEmployee($agentObj);
  1750.                 $supervisionEmployeeObj->setLocationPosition($locationPositionObj);                
  1751.                 $supervisionEmployeeObj->setIsActive(1);
  1752.                 $supervisionEmployeeObj->setCreatedAt(new \DateTime());
  1753.                 $supervisionEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  1754.                 $entityManager->persist($supervisionEmployeeObj);
  1755.                 $entityManager->flush();
  1756.             }
  1757.             return new JsonResponse(array('status' => 'success'));
  1758.         }     
  1759.                             
  1760.     
  1761.         return new JsonResponse(array('status' => 'error'));
  1762.     }
  1763.     /**
  1764.      * @Route("/set-location-place", name="ws_set_location_place", methods={"GET", "POST"})
  1765.      */
  1766.     public function setLocationPlace(Request $requestEntityManagerInterface $entityManager): Response
  1767.     {
  1768.         
  1769.         $data json_decode(file_get_contents("php://input"));             
  1770.         if($data)
  1771.         {   
  1772.             $supervisor      $data->supervisor;
  1773.             $supervisionId   $data->supervisionId;
  1774.             $employeeId      $data->employeeId;
  1775.             $locationPlaceId $data->locationPlaceId;     
  1776.             $locationEmployeeId $data->locationEmployeeId;       
  1777.             $supervisionEmployeeObj $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  1778.                 'Supervision' => $supervisionId,
  1779.                 'Employee'    => $employeeId
  1780.             ]);     
  1781.             
  1782.             $locationPlaceObj $entityManager->getRepository(LocationPlace::class)->findOneBy([
  1783.                 'locationPlaceId' => $locationPlaceId
  1784.             ]);     
  1785.             $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  1786.                 'employeeId'    => $supervisor->employee_id
  1787.             ]);
  1788.             $supervisionObj $entityManager->getRepository(Supervision::class)->findOneBy([                        
  1789.                 'supervisionId'    => $supervisionId
  1790.             ]);
  1791.             $agentObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  1792.                 'employeeId'    => $employeeId
  1793.             ]);
  1794.             //Esto es por los cambios que se hicieron en conexión con el sistema externo
  1795.             $locationEmployeeObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([                        
  1796.                 'locationEmployeeId'    => $locationEmployeeId
  1797.             ]);
  1798.             if($locationEmployeeObj)
  1799.             {
  1800.                 $locationPlaceObj $entityManager->getRepository(LocationPlace::class)->findOneBy([                        
  1801.                     'locationPlaceId' => $locationPlaceId
  1802.                 ]);
  1803.                 $locationEmployeeObj->setLocationPlace($locationPlaceObj);
  1804.                 $entityManager->persist($locationEmployeeObj);
  1805.                 $entityManager->flush();
  1806.             }
  1807.             
  1808.             if($supervisionEmployeeObj)
  1809.             {       
  1810.                 $supervisionEmployeeObj->setSupervision($supervisionObj);
  1811.                 $supervisionEmployeeObj->setEmployee($agentObj);
  1812.                 $supervisionEmployeeObj->setLocationPlace($locationPlaceObj);
  1813.                 $supervisionEmployeeObj->setIsActive(1);            
  1814.                 $supervisionEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  1815.                 $entityManager->persist($supervisionEmployeeObj);
  1816.                 $entityManager->flush();
  1817.             } else {                                                                
  1818.                 $supervisionEmployeeObj = new SupervisionEmployee();
  1819.                 $supervisionEmployeeObj->setSupervision($supervisionObj);
  1820.                 $supervisionEmployeeObj->setEmployee($agentObj);
  1821.                 $supervisionEmployeeObj->setLocationPlace($locationPlaceObj);                
  1822.                 $supervisionEmployeeObj->setIsActive(1);
  1823.                 $supervisionEmployeeObj->setCreatedAt(new \DateTime());
  1824.                 $supervisionEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  1825.                 $entityManager->persist($supervisionEmployeeObj);
  1826.                 $entityManager->flush();
  1827.             }
  1828.             return new JsonResponse(array('status' => 'success'));
  1829.         }     
  1830.                             
  1831.     
  1832.         return new JsonResponse(array('status' => 'error'));
  1833.     }    
  1834.     /**
  1835.      * @Route("/electronic-create", name="electronic-create", methods={"GET", "POST"})
  1836.      */
  1837.     public function electronicCreate(Request $requestEntityManagerInterface $entityManager): Response
  1838.     {
  1839.         
  1840.         $data json_decode(file_get_contents("php://input"));             
  1841.         if($data)
  1842.         {   
  1843.             $employeeId     $data->employeeId;
  1844.             $clientId       $data->clientId;
  1845.             $projectId      $data->projectId;
  1846.             $locationId     $data->locationId;            
  1847.             $electronicId   $data->electronicId;     
  1848.             $timeArrival    $data->timeArrival;
  1849.             $timeExit       $data->timeExit;
  1850.             $electronicTypeId $data->electronicTypeId;
  1851.             $description      $data->description;
  1852.             $comments         $data->comments;
  1853.             $clientComments   $data->clientComments;
  1854.             $instalationDate  $data->instalationDate;
  1855.             $survey           $data->survey;          
  1856.             $customClientName $data->customClientName;       
  1857.             $extraEmployees   = ($data->extraEmployees $data->extraEmployees : []);     
  1858.             $base64SignatureTech      $data->signatureTech;
  1859.             $base64SignatureClient    $data->signatureClient;            
  1860.             
  1861.             $lat false;
  1862.             if($data->lat)
  1863.             {
  1864.                 $lat $data->lat;
  1865.             }
  1866.             $lng false;
  1867.             if($data->lng)
  1868.             {
  1869.                 $lng  $data->lng;
  1870.             }
  1871.             $electronicObj $entityManager->getRepository(Electronic::class)->findOneBy([
  1872.                 'electronicId'  => $electronicId
  1873.             ]);   
  1874.             
  1875.             //if($employeeId && $timeArrival && $timeExit && $electronicTypeId && $description)
  1876.             if(true)
  1877.             {
  1878.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  1879.                     'employeeId'  => $employeeId
  1880.                 ]);   
  1881.                 $signatureTech      $this->saveSignature($base64SignatureTech);
  1882.                 $signatureClient    $this->saveSignature($base64SignatureClient);
  1883.                 
  1884.                 $electronicObj->setComments($comments);
  1885.                 $electronicObj->setSignatureTech($signatureTech);
  1886.                 $electronicObj->setSignatureClient($signatureClient);
  1887.                 $electronicObj->setTimeExit(date("H:i:s"));                
  1888.                 $electronicObj->setStep(3);
  1889.                 $electronicObj->setLatLng($lat.','.$lng);
  1890.                 $electronicObj->setSurveyResult($survey);
  1891.                 $electronicObj->setClientComments($clientComments);
  1892.                 $entityManager->persist($electronicObj);
  1893.                 $entityManager->flush();
  1894.                 //Si NO es de tipo EVALUACION (1) entonces se trata de un cliente existente
  1895.                 /*if($electronicTypeId > 1)
  1896.                 {                    
  1897.                     $projectObj = $entityManager->getRepository(Project::class)->findOneBy([
  1898.                         'projectId'  => $projectId
  1899.                     ]);    
  1900.                     $locationObj = $entityManager->getRepository(Location::class)->findOneBy([
  1901.                         'locationId'  => $locationId
  1902.                     ]);   
  1903.                     $clientObj = $entityManager->getRepository(Client::class)->findOneBy([
  1904.                         'clientId'  => $locationObj->getClient()
  1905.                     ]);    
  1906.                 } 
  1907.                 $electronicTypeObj = $entityManager->getRepository(ElectronicType::class)->findOneBy([
  1908.                     'electronicTypeId'  => $electronicTypeId
  1909.                 ]);    
  1910.                 if($employeeObj && $electronicTypeObj)
  1911.                 {
  1912.                     $signatureTech      = $this->saveSignature($base64SignatureTech);
  1913.                     $signatureClient    = $this->saveSignature($base64SignatureClient);
  1914.                     $latLng = "";
  1915.                     if($lat && $lng)
  1916.                     {
  1917.                         $latLng = $lat.",".$lng;
  1918.                     }
  1919.                     
  1920.                     $reactionObj = new Electronic();        
  1921.                     if($electronicTypeId > 1)
  1922.                     {            
  1923.                         $reactionObj->setClient($clientObj);
  1924.                         $reactionObj->setProject($projectObj);
  1925.                         $reactionObj->setLocation($locationObj);
  1926.                         $reactionObj->setIsCustom(0);
  1927.                     } else {
  1928.                         $reactionObj->setCustomClientName($customClientName);
  1929.                         $reactionObj->setIsCustom(1);
  1930.                     }    
  1931.                     $reactionObj->setElectronicType($electronicTypeObj);                    
  1932.                     $reactionObj->setTimeArrival($timeArrival);
  1933.                     $reactionObj->setTimeExit($timeExit);
  1934.                     $reactionObj->setDescription($description);
  1935.                     $reactionObj->setComments($comments);
  1936.                     $reactionObj->setClientComments($clientComments);
  1937.                     $reactionObj->setInstalationDate($instalationDate);
  1938.                     $reactionObj->setSurveyResult($survey);
  1939.                     $reactionObj->setLatLng($latLng);
  1940.                     $reactionObj->setSignatureTech($signatureTech);
  1941.                     $reactionObj->setSignatureClient($signatureClient);
  1942.                     $reactionObj->setCreatedAt(new \DateTime());
  1943.                     $reactionObj->setCreatedByEmployeeId($employeeObj);
  1944.                     $reactionObj->setIsActive(1);
  1945.                     $entityManager->persist($reactionObj);
  1946.                     $entityManager->flush();
  1947.                     if($extraEmployees)
  1948.                     {
  1949.                         foreach($extraEmployees as $extraEmployee)
  1950.                         {
  1951.                             $employeeObj = $entityManager->getRepository(Employee::class)->findOneBy([
  1952.                                 'employeeId'  => $extraEmployee->employee_id
  1953.                             ]);    
  1954.                             if($employeeObj)
  1955.                             {
  1956.                                 $electronicEmployeeObj = new ElectronicEmployee();
  1957.                                 $electronicEmployeeObj->setEmployee($employeeObj);
  1958.                                 $electronicEmployeeObj->setElectronic($reactionObj);
  1959.                                 $electronicEmployeeObj->setIsActive(1);
  1960.                                 $electronicEmployeeObj->setCreatedAt(new \DateTime());
  1961.                                 $entityManager->persist($electronicEmployeeObj);
  1962.                                 $entityManager->flush();
  1963.                             }
  1964.                         }
  1965.                     }
  1966.                     return new JsonResponse(array('status' => 'success', 'data' => $reactionObj->getElectronicId()));
  1967.                 }*/
  1968.                 return new JsonResponse(array('status' => 'success''data' => $electronicObj->getElectronicId()));
  1969.             }           
  1970.         }
  1971.         return new JsonResponse(array('status' => 'error'));
  1972.     }     
  1973.     
  1974.     
  1975.     public function saveSignature($base64)
  1976.     {
  1977.                 
  1978.         $ext "png";                
  1979.         if($base64)
  1980.         {
  1981.             $base64 substr($base64,strrpos($base64",")+1);
  1982.         } 
  1983.         $dir_path "uploads/sign/";
  1984.         if(!is_dir($dir_path))
  1985.         {
  1986.             mkdir($dir_path0777true);
  1987.         }
  1988.         $fileName md5(date("YmdHis")).rand(0,1000).rand(1001,2000).".".$ext;
  1989.         $new $dir_path.$fileName;
  1990.         
  1991.         $paths $this->getProjectPaths();            
  1992.         $newPath $paths["public_path"].$new;
  1993.         
  1994.         $decoded base64_decode($base64);
  1995.         file_put_contents($new$decoded);
  1996.         return $fileName;
  1997.     }
  1998.    /**
  1999.      * @Route("/get-time-status", name="get-time-status", methods={"GET", "POST"})
  2000.      */
  2001.     public function getTimeStatus(Request $requestEntityManagerInterface $entityManager): Response
  2002.     {
  2003.         
  2004.         $data json_decode(file_get_contents("php://input"));             
  2005.         if($data)
  2006.         {   
  2007.             $token  $data->token;           
  2008.             $employeeTimeStatusList $entityManager->getRepository(EmployeeTimeStatus::class)->findBy([                
  2009.                 'is_active' => 1
  2010.             ]);
  2011.             
  2012.             $result = [];
  2013.             foreach($employeeTimeStatusList as $item)
  2014.             {                                                           
  2015.                 
  2016.                 $result[] = array(
  2017.                     'status_id'   => $item->getEmployeeTimeStatusId(),
  2018.                     'description' => $item->getDescription(),
  2019.                     'status_name' => $item->getName()
  2020.                 );
  2021.             }
  2022.             return new JsonResponse(array('status' => 'success''data' => $result));
  2023.         }    
  2024.     }    
  2025.     /**
  2026.      * @Route("/get-ticket-options", name="get-ticket-options", methods={"GET", "POST"})
  2027.      */
  2028.     public function getTicketOptions(Request $requestEntityManagerInterface $entityManager): Response
  2029.     {
  2030.         
  2031.         $data json_decode(file_get_contents("php://input"));             
  2032.         if($data)
  2033.         {   
  2034.             $token  $data->token;           
  2035.             $employeeTimeObj $entityManager->getRepository(Employee::class)->findOneBy([
  2036.                 'employeeId'  => $token->employee_id,                
  2037.             ]);                        
  2038.             if($employeeTimeObj)
  2039.             {                                           
  2040.                 
  2041.                 $ticketCategoryList $entityManager->getRepository(TicketCategory::class)->findBy([
  2042.                     'is_active' => 1
  2043.                 ]);           
  2044.                 
  2045.                 $categories = [];
  2046.                 foreach($ticketCategoryList as $item)
  2047.                 {                                                                           
  2048.                     $categories[] = array(
  2049.                         'category_id'   => $item->getTicketCategoryId(),
  2050.                         'description'   => $item->getDescription(),
  2051.                         'category_name' => $item->getName()
  2052.                     );
  2053.                 }
  2054.                 $ticketStatusList $entityManager->getRepository(TicketStatus::class)->findBy([
  2055.                     'is_active' => 1
  2056.                 ]);           
  2057.                 
  2058.                 $statuses = [];
  2059.                 foreach($ticketStatusList as $item)
  2060.                 {                                                                           
  2061.                     $statuses[] = array(
  2062.                         'status_id'   => $item->getTicketStatusId(),
  2063.                         'description' => $item->getDescription(),
  2064.                         'status_name' => $item->getName()
  2065.                     );
  2066.                 }
  2067.                 
  2068.             }
  2069.             return new JsonResponse(array('status' => 'success''categories' => $categories'statuses' => $statuses));
  2070.         }        
  2071.     }
  2072.    /**
  2073.      * @Route("/save-chats", name="save-chats", methods={"GET", "POST"})
  2074.      */
  2075.     public function saveChats(Request $requestEntityManagerInterface $entityManager): Response
  2076.     {
  2077.         
  2078.         $data json_decode(file_get_contents("php://input"));             
  2079.         if($data)
  2080.         {   
  2081.             $token  $data->token;    
  2082.             $input  $data->message;
  2083.             $ticket $data->ticket;
  2084.             $employeeTimeObj $entityManager->getRepository(Employee::class)->findOneBy([
  2085.                 'employeeId'  => $token->employee_id,                
  2086.             ]);                        
  2087.             if($employeeTimeObj)
  2088.             {     
  2089.                 
  2090.                 $ticketObj $entityManager->getRepository(Ticket::class)->findOneBy([
  2091.                     'ticketId'  => $ticket
  2092.                 ]); 
  2093.                 
  2094.                 $messageObj = new TicketMessage();
  2095.                 $messageObj->setEmployee($employeeTimeObj);
  2096.                 $messageObj->setTicket($ticketObj);
  2097.                 $messageObj->setDescription($input);                
  2098.                 $messageObj->setCreatedAt(new \DateTime());
  2099.                 $messageObj->setIsActive(1);
  2100.                 $entityManager->persist($messageObj);
  2101.                 $entityManager->flush();
  2102.                 return new JsonResponse(array('status' => 'success'));
  2103.             }
  2104.             return new JsonResponse(array('status' => 'error'));
  2105.         }        
  2106.     }    
  2107.     /**
  2108.      * @Route("/get-chats", name="get-chats", methods={"GET", "POST"})
  2109.      */
  2110.     public function getChats(Request $requestEntityManagerInterface $entityManager): Response
  2111.     {
  2112.         
  2113.         $data json_decode(file_get_contents("php://input"));             
  2114.         if($data)
  2115.         {   
  2116.             $token  $data->token
  2117.             $ticket $data->ticket;   
  2118.             $employeeTimeObj $entityManager->getRepository(Employee::class)->findOneBy([
  2119.                 'employeeId'  => $token->employee_id,                
  2120.             ]);                        
  2121.             if($employeeTimeObj)
  2122.             {                                           
  2123.                 
  2124.                 $chatList $entityManager->getRepository(TicketMessage::class)->findBy([
  2125.                     'Ticket' => $ticket
  2126.                 ],['created_at' => 'ASC']);
  2127.                 
  2128.                 $ticketData = [];
  2129.                 foreach($chatList as $ticket)
  2130.                 {
  2131.                     $ticketData[] = array(
  2132.                         'ticket_message_id'  => $ticket->getTicketMessageId(),   
  2133.                         'created_by_name'    => ($ticket->getCreatedBy() ? $ticket->getCreatedBy()->getFirstName().' '.$ticket->getCreatedBy()->getLastName() : ''),                                            
  2134.                         'comment'            => $ticket->getDescription(),
  2135.                         'visible'            => 1,
  2136.                         'created_at'         => $ticket->getCreatedAt()->format('Y-m-d H:i:s'),                        
  2137.                         'time_ago'           => $this->timeAgo($ticket->getCreatedAt()),                     
  2138.                         'created_by_employee_name' => ($ticket->getEmployee() ? $ticket->getEmployee()->getName() : '')                    
  2139.                     );
  2140.                 }
  2141.                             
  2142.                 return new JsonResponse(array('status' => 'success''chats' => $ticketData));
  2143.             }
  2144.             return new JsonResponse(array('status' => 'error'));
  2145.         }        
  2146.     }    
  2147.    /**
  2148.      * @Route("/get-my-tickets", name="get-my-tickets", methods={"GET", "POST"})
  2149.      */
  2150.     public function getMyTickets(Request $requestEntityManagerInterface $entityManager): Response
  2151.     {
  2152.         
  2153.         $data json_decode(file_get_contents("php://input"));             
  2154.         if($data)
  2155.         {   
  2156.             $token $data->token;    
  2157.             $employeeTimeObj $entityManager->getRepository(Employee::class)->findOneBy([
  2158.                 'employeeId'  => $token->employee_id,                
  2159.             ]);                        
  2160.             if($employeeTimeObj)
  2161.             {                                           
  2162.                 
  2163.                 $ticketList $entityManager->getRepository(Ticket::class)->findBy([
  2164.                     'is_active'  => 1,
  2165.                     'Employee'   => $employeeTimeObj
  2166.                 ],['created_at' => 'DESC']);
  2167.                 
  2168.                 $ticketData = [];
  2169.                 foreach($ticketList as $ticket)
  2170.                 {
  2171.                     $messagesList $entityManager->getRepository(TicketMessage::class)->findBy([
  2172.                         'is_active'  => 1,
  2173.                         'Employee'   => $employeeTimeObj,
  2174.                         'Ticket'     => $ticket
  2175.                     ]);
  2176.                     $picturesList $entityManager->getRepository(TicketPicture::class)->findBy([                        
  2177.                         'Ticket'   => $ticket
  2178.                     ]);
  2179.                     $ticketData[] = array(
  2180.                         'ticket_id'      => $ticket->getTicketId(),
  2181.                         'class'          => $ticket->getTicketStatus()->getClass(),
  2182.                         'name'           => $ticket->getName(),
  2183.                         'creator'        => $ticket->getEmployee()->getName(),
  2184.                         'category_id'    => $ticket->getTicketCategory()->getTicketCategoryId(),
  2185.                         'category_name'  => $ticket->getTicketCategory()->getName(),
  2186.                         'status_id'      => $ticket->getTicketStatus()->getTicketStatusId(),
  2187.                         'status_name'    => $ticket->getTicketStatus()->getName(),
  2188.                         'description'    => $ticket->getDescription(),
  2189.                         'created_at'     => $ticket->getCreatedAt()->format('Y-m-d H:i:s'),
  2190.                         'time_ago'       => $this->timeAgo($ticket->getCreatedAt()),
  2191.                         'total_chat'     => count($messagesList),
  2192.                         'total_pictures' => count($picturesList)                   
  2193.                     );
  2194.                 }
  2195.                             
  2196.                 //$ticketData = [];
  2197.                 return new JsonResponse(array('status' => 'success''tickets' => $ticketData));
  2198.             }
  2199.             return new JsonResponse(array('status' => 'error'));
  2200.         }        
  2201.     }    
  2202.     public function timeAgo(\DateTime $datetime$full false): string
  2203.     {
  2204.         $now = new \DateTime;
  2205.         $diff $now->diff($datetime);
  2206.         $diff->floor($diff->7);
  2207.         $diff->-= $diff->7;
  2208.         $string = [
  2209.             'y' => 'año',
  2210.             'm' => 'mes',
  2211.             'w' => 'semana',
  2212.             'd' => 'día',
  2213.             'h' => 'hora',
  2214.             'i' => 'minuto',
  2215.             's' => 'segundo',
  2216.         ];
  2217.         foreach ($string as $k => &$v) {
  2218.             if ($diff->$k) {
  2219.                 $v $diff->$k ' ' $v . ($diff->$k 's' '');
  2220.             } else {
  2221.                 unset($string[$k]);
  2222.             }
  2223.         }
  2224.         if (!$full$string array_slice($string01);
  2225.         return $string 'Hace ' implode(', '$string) : 'Justo ahora';
  2226.     }
  2227.     /**
  2228.      * @Route("/create-ticket", name="create-ticket", methods={"GET", "POST"})
  2229.      */
  2230.     public function createTicket(Request $requestEntityManagerInterface $entityManager): Response
  2231.     {
  2232.         
  2233.         $data json_decode(file_get_contents("php://input"));             
  2234.         if($data)
  2235.         {   
  2236.             $token $data->token;    
  2237.             $form  $data->form;
  2238.             
  2239.             $employeeTimeObj $entityManager->getRepository(Employee::class)->findOneBy([
  2240.                 'employeeId'  => $token->employee_id,                
  2241.             ]);                        
  2242.             if($employeeTimeObj)
  2243.             {                                           
  2244.                 
  2245.                 $categoryObj $entityManager->getRepository(TicketCategory::class)->findOneBy([
  2246.                     'ticketCategoryId'  => $form->category
  2247.                 ]); 
  2248.                 
  2249.                 $ticket = new Ticket();
  2250.                 $ticket->setEmployee($employeeTimeObj);
  2251.                 $ticket->setTicketCategory($categoryObj);
  2252.                 $ticket->setTicketStatus($entityManager->getRepository(TicketStatus::class)->findOneBy(['ticketStatusId' => 1]));
  2253.                 $ticket->setName($form->name);
  2254.                 $ticket->setPhone($form->phone);
  2255.                 $ticket->setDescription($form->description);
  2256.                 $ticket->setCreatedAt(new \DateTime());
  2257.                 $ticket->setIsActive(1);
  2258.                 $entityManager->persist($ticket);
  2259.                 $entityManager->flush();
  2260.                 return new JsonResponse(array('status' => 'success'));
  2261.             }
  2262.             return new JsonResponse(array('status' => 'error'));
  2263.         }        
  2264.     }    
  2265.    /**
  2266.      * @Route("/get-record-time", name="get-record-time", methods={"GET", "POST"})
  2267.      */
  2268.     public function getRecordTime(Request $requestEntityManagerInterface $entityManager): Response
  2269.     {
  2270.         
  2271.         $data json_decode(file_get_contents("php://input"));             
  2272.         if($data)
  2273.         {   
  2274.             $token  $data->token;           
  2275.             $employeeTimeObj $entityManager->getRepository(EmployeeTime::class)->findOneBy([
  2276.                 'Employee'  => $token->employee_id,
  2277.                 'year'      => date('Y'),
  2278.                 'month'     => date('m'),
  2279.                 'day'       => date("d"),
  2280.                 'is_active' => 1
  2281.             ], ['employeeTimeId' => 'DESC']);
  2282.             
  2283.             $result = [
  2284.                 'status_id'   => "null",
  2285.                 'status_name' => "null"
  2286.             ];
  2287.             if($employeeTimeObj)
  2288.             {                                           
  2289.                 if($employeeTimeObj->getEmployeeTimeStatus())
  2290.                 {
  2291.                     $statusId   $employeeTimeObj->getEmployeeTimeStatus()->getEmployeeTimeStatusId();
  2292.                     $statusName $employeeTimeObj->getEmployeeTimeStatus()->getName();
  2293.                     $result = [
  2294.                         'status_id'   => $statusId,
  2295.                         'status_name' => $statusName
  2296.                     ];
  2297.                     
  2298.                 }
  2299.                 
  2300.             }
  2301.             return new JsonResponse(array('status' => 'success''data' => $result));
  2302.         }        
  2303.     }
  2304.    /**
  2305.      * @Route("/record-time", name="record-time", methods={"GET", "POST"})
  2306.      */
  2307.     public function recordTime(Request $requestEntityManagerInterface $entityManager): Response
  2308.     {
  2309.         
  2310.         $data json_decode(file_get_contents("php://input"));             
  2311.         if($data)
  2312.         {   
  2313.             $token  $data->token;           
  2314.             $status $data->status;
  2315.             //$shift_employee_id = $data->shift_employee_id;
  2316.             
  2317.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  2318.                 'employeeId'  => $token->employee_id
  2319.             ]);    
  2320.             if($employeeObj)
  2321.             {
  2322.                 $year  date("Y");
  2323.                 $month date("m");
  2324.                 $day   date("d");
  2325.                 /*$statusId = 0;
  2326.                 if($status == 'open')
  2327.                 {
  2328.                     //2 es igual a "Dia iniciado"
  2329.                     $statusId = 2;
  2330.                 }*/
  2331.                 $statusId $status;
  2332.                 $employeeTimeStatusObj $entityManager->getRepository(EmployeeTimeStatus::class)->findOneBy([
  2333.                     'employeeTimeStatusId'  => $statusId
  2334.                 ]);
  2335.                 if($employeeTimeStatusObj)
  2336.                 {
  2337.                     //Cerramos todo registro anterior con fecha de finalización
  2338.                     $employeeTimeObj $entityManager->getRepository(EmployeeTime::class)->findOneBy([
  2339.                         'year'  => $year,
  2340.                         'month' => $month,
  2341.                         'day'   => $day,
  2342.                         'end_at'    => null,
  2343.                         'Employee'  => $token->employee_id,                        
  2344.                         'is_active' => 1
  2345.                     ]);
  2346.                     if($employeeTimeObj)
  2347.                     {
  2348.                       
  2349.                         $employeeTimeObj->setIsActive(0);
  2350.                         $employeeTimeObj->setEndAt(date("Y-m-d H:i:s"));
  2351.                         $entityManager->persist($employeeTimeObj);
  2352.                         $entityManager->flush();
  2353.                     }
  2354.                     
  2355.                     //e insertamos uno nuevo a menos que no sea "Dia terminado"
  2356.                     if($statusId 1)
  2357.                     {
  2358.                         $employeeTime = new EmployeeTime();
  2359.                         $employeeTime->setEmployee($employeeObj);
  2360.                         $employeeTime->setStartAt(date("Y-m-d H:i:s"));
  2361.                         $employeeTime->setYear(date("Y"));
  2362.                         $employeeTime->setMonth(date("m"));
  2363.                         $employeeTime->setDay(date("d"));
  2364.                         $employeeTime->setEmployeeTimeStatus($employeeTimeStatusObj);
  2365.                         $employeeTime->setIsActive(1);
  2366.                         $employeeTime->setCreatedAt(new \DateTime());
  2367.                         $entityManager->persist($employeeTime);
  2368.                         $entityManager->flush();                    
  2369.                     }
  2370.                     return new JsonResponse(array('status' => 'success'));
  2371.                 }
  2372.                
  2373.             }
  2374.         }
  2375.         return new JsonResponse(array('status' => 'error'));
  2376.     }      
  2377.     /**
  2378.      * @Route("/validate-nit", name="validate-nit", methods={"GET", "POST"})
  2379.      */
  2380.     public function validateNit(Request $requestEntityManagerInterface $entityManager): Response
  2381.     {
  2382.         
  2383.         $data json_decode(file_get_contents("php://input"));             
  2384.         if($data)
  2385.         {   
  2386.             $nit $data->identification;           
  2387.             $clientObj $entityManager->getRepository(Client::class)->findOneBy([
  2388.                 'tax_identifier'  => $nit                
  2389.             ]);    
  2390.             if($clientObj)
  2391.             {
  2392.                                                   
  2393.                 $data = [
  2394.                     'client_id' => $clientObj->getClientId(),
  2395.                     'name'      => $clientObj->getName()                    
  2396.                 ];
  2397.                 return new JsonResponse(array('status' => 'success''data' => $data));
  2398.                
  2399.             }
  2400.         }
  2401.         return new JsonResponse(array('status' => 'error''message' => 'NIT Invalido'));
  2402.     }   
  2403.      /**
  2404.      * @Route("/start-electronics", name="start-electronics", methods={"GET", "POST"})
  2405.      */
  2406.     public function startElectronics(Request $requestEntityManagerInterface $entityManager): Response
  2407.     {
  2408.         
  2409.         $data json_decode(file_get_contents("php://input"));             
  2410.         if($data)
  2411.         {   
  2412.             
  2413.             $electronicId $data->id;           
  2414.             $electronicObj $entityManager->getRepository(Electronic::class)->findOneBy([
  2415.                 'electronicId' => $electronicId                
  2416.             ]);
  2417.             if($electronicObj)           
  2418.             {                                                 
  2419.                 $electronicObj->setStep(2); 
  2420.                 $electronicObj->setTimeArrival(date("H:i:s"));                
  2421.                 $entityManager->persist($electronicObj);
  2422.                 $entityManager->flush();
  2423.                 return new JsonResponse(array('status' => 'success'));
  2424.             }            
  2425.         }
  2426.         return new JsonResponse(array('status' => 'error'));
  2427.     }   
  2428.     /**
  2429.      * @Route("/location-search", name="location-search", methods={"GET", "POST"})
  2430.      */
  2431.     public function locationSearch(Request $requestEntityManagerInterface $entityManager): Response
  2432.     {
  2433.         
  2434.         $data json_decode(file_get_contents("php://input"));             
  2435.         if($data)
  2436.         {   
  2437.             $array = [];
  2438.             $search $data->search;           
  2439.             //$results = $entityManager->getRepository(Location::class)->searchLocation($search);
  2440.             $results $entityManager->getRepository(Location::class)->searchLocationSimple($search);
  2441.             foreach($results as $location)
  2442.             {               
  2443.               
  2444.                 $name  =  $location['name'];
  2445.                 /*if(strlen($location["location_place"]) > 0)
  2446.                 {
  2447.                     $name  .=  " - ".$location['location_place'];
  2448.                 }*/
  2449.                 $array[] = [
  2450.                     'location_id'       => $location['location_id'],
  2451.                     'location_place_id' => '',//=> $location['location_place_id'],
  2452.                     'name'              => $name
  2453.                 ];                               
  2454.             }
  2455.             return new JsonResponse(array('status' => 'success''data' => $array));
  2456.         }
  2457.         return new JsonResponse(array('status' => 'error'));
  2458.     }   
  2459.     /**
  2460.      * @Route("/get-reaction-location", name="get-reaction-location", methods={"GET", "POST"})
  2461.      */
  2462.     public function getReactionLocation(Request $requestEntityManagerInterface $entityManager): Response
  2463.     {
  2464.         
  2465.         $data json_decode(file_get_contents("php://input"));             
  2466.         if($data)
  2467.         {   
  2468.             $rid $data->rid;           
  2469.             
  2470.             $reactionMainObj $entityManager->getRepository(Reaction::class)->findOneBy([                    
  2471.                 'reactionId' => $rid
  2472.             ]); 
  2473.             if($reactionMainObj)
  2474.             {
  2475.                 $locationObj $entityManager->getRepository(Location::class)->findOneBy([                    
  2476.                     'locationId' => $reactionMainObj->getLocation()->getLocationId()
  2477.                 ]);
  2478.                 if($locationObj->getLocationType() == 'Movil')
  2479.                 {
  2480.                     $reactionObj $entityManager->getRepository(ReactionMap::class)->findOneBy([                    
  2481.                         'Reaction' => $rid
  2482.                     ], ['reactionMapId' => 'DESC']);
  2483.                     
  2484.                     if($reactionObj)   
  2485.                     {
  2486.                             $googleLink "https://www.google.com/maps?q=loc:".$reactionObj->getLat().",".$reactionObj->getLng();
  2487.                             $wazeLink   "https://www.waze.com/live-map/directions?to=ll.".$reactionObj->getLat().",".$reactionObj->getLng();
  2488.                             return new JsonResponse(array(
  2489.                                 'status'   => 'success'
  2490.                                 'google'   => $googleLink,
  2491.                                 'wazeLink' => $wazeLink,
  2492.                                 'lat'      => $reactionObj->getLat(), 
  2493.                                 'lng'      => $reactionObj->getLng(), 
  2494.                                 'created_at' => $reactionObj->getCreatedAt()->format("Y-m-d H:i:s")
  2495.                             ));
  2496.                     }    
  2497.                     
  2498.                 } else {
  2499.                     $googleLink "https://www.google.com/maps?q=loc:".$locationObj->getLat().",".$locationObj->getLng();
  2500.                     $wazeLink   "https://www.waze.com/live-map/directions?to=ll.".$locationObj->getLat().",".$locationObj->getLng();
  2501.                     return new JsonResponse(array(
  2502.                         'status'   => 'success'
  2503.                         'google'   => $googleLink,
  2504.                         'wazeLink' => $wazeLink,
  2505.                         'lat'      => $locationObj->getLat(), 
  2506.                         'lng'      => $locationObj->getLng(), 
  2507.                         'created_at' => date("Y-m-d H:i:s")
  2508.                     ));
  2509.                     
  2510.                 }
  2511.                     
  2512.            }
  2513.         }
  2514.         return new JsonResponse(array('status' => 'error'));
  2515.     }   
  2516.    
  2517.     /**
  2518.      * @Route("/get-electronic-types", name="get-electronic-types", methods={"GET", "POST"})
  2519.      */
  2520.     public function getElectronicTypes(Request $requestEntityManagerInterface $entityManager): Response
  2521.     {
  2522.         
  2523.         $data json_decode(file_get_contents("php://input"));             
  2524.         if($data)
  2525.         {   
  2526.             $token $data->token;           
  2527.             
  2528.             $values $entityManager->getRepository(ElectronicType::class)->findBy([                    
  2529.                 'is_active' => 1
  2530.             ]);   
  2531.             
  2532.             $options = [];
  2533.             foreach($values as $value)
  2534.             {
  2535.                 $options[] = [                        
  2536.                     'value' => $value->getElectronicTypeId(),
  2537.                     'name'  => $value->getName()
  2538.                 ];
  2539.             }             
  2540.                         
  2541.             return new JsonResponse(array('status' => 'success''data' => $options));
  2542.                     
  2543.         }
  2544.         return new JsonResponse(array('status' => 'error'));
  2545.     }   
  2546.     /**
  2547.      * @Route("/get-my-electronics", name="get-my-electronics", methods={"GET", "POST"})
  2548.      */
  2549.     public function getMyElectronics(Request $requestEntityManagerInterface $entityManager): Response
  2550.     {
  2551.         
  2552.         $data json_decode(file_get_contents("php://input"));             
  2553.         if($data)
  2554.         {   
  2555.             $eid $data->eid;                       
  2556.             
  2557.             $myElectronics $entityManager->getRepository(Electronic::class)->findBy([                    
  2558.                 'is_active' => 1,
  2559.                 'Employee'  => $eid
  2560.             ], ['created_at' => 'DESC']);                           
  2561.             $array = [];
  2562.             foreach($myElectronics as $item)
  2563.             {
  2564.                 if($item->getIsCustom() == 1)
  2565.                 {
  2566.                     $name $item->getCustomClientName();
  2567.                     $address "";
  2568.                 } else {
  2569.                     if($item->getLocation())
  2570.                     {
  2571.                         $name $item->getLocation()->getName();
  2572.                         $address $item->getLocation()->getAddress();
  2573.                     } else {
  2574.                         $name "Desconocido";
  2575.                         $address "";
  2576.                     }
  2577.                 }
  2578.                 $array[] = [                        
  2579.                     'electronic_id' => $item->getElectronicId(),
  2580.                     'name'          => $name,
  2581.                     'address'       => $address,
  2582.                     'step'          => $item->getStep(),
  2583.                     'type'          => $item->getElectronicType()->getName(),
  2584.                     'scheduled_at'  => $item->getInstalationDate(),
  2585.                     'created_at'    => $item->getCreatedAt()->format("Y-m-d H:i:s"),
  2586.                     'created_by'    => $item->getCreatedBy()->getFirstName()." ".$item->getCreatedBy()->getlastName()
  2587.                 ];
  2588.             }             
  2589.                         
  2590.             return new JsonResponse(array('status' => 'success''data' => $array));
  2591.                     
  2592.         }
  2593.         return new JsonResponse(array('status' => 'error'));
  2594.     }       
  2595.      /**
  2596.      * @Route("/get-reaction-types", name="get-reaction-types", methods={"GET", "POST"})
  2597.      */
  2598.     public function getReactionTypes(Request $requestEntityManagerInterface $entityManager): Response
  2599.     {
  2600.         
  2601.         $data json_decode(file_get_contents("php://input"));             
  2602.         if($data)
  2603.         {   
  2604.             $token $data->token;           
  2605.             
  2606.             $values $entityManager->getRepository(ReactionType::class)->findBy([                    
  2607.                 'is_active' => 1
  2608.             ]);   
  2609.             
  2610.             $options = [];
  2611.             foreach($values as $value)
  2612.             {
  2613.                 $options[] = [                        
  2614.                     'value' => $value->getReactionTypeId(),
  2615.                     'name'  => $value->getName()
  2616.                 ];
  2617.             }             
  2618.                         
  2619.             return new JsonResponse(array('status' => 'success''data' => $options));
  2620.                     
  2621.         }
  2622.         return new JsonResponse(array('status' => 'error'));
  2623.     }       
  2624.     
  2625.     /**
  2626.      * @Route("/get-fields", name="get-fields", methods={"GET", "POST"})
  2627.      */
  2628.     public function getFields(Request $requestEntityManagerInterface $entityManager): Response
  2629.     {
  2630.         
  2631.         $data json_decode(file_get_contents("php://input"));             
  2632.         if($data)
  2633.         {   
  2634.             $typeId $data->type_id;           
  2635.             $fields $entityManager->getRepository(RequestField::class)->findBy([
  2636.                 'requestType'  => $typeId,
  2637.                 'isActive' => 1          
  2638.             ], ['weight' => 'ASC']);    
  2639.             if($fields)
  2640.             {
  2641.                     
  2642.                 $list = [];
  2643.                 foreach($fields as $field)
  2644.                 {
  2645.                     $values $entityManager->getRepository(RequestFieldValue::class)->findBy([
  2646.                         'requestField'  => $field->getRequestFieldId(),
  2647.                         'isActive' => 1
  2648.                     ]);   
  2649.                     
  2650.                     $options = [];
  2651.                     foreach($values as $value)
  2652.                     {
  2653.                         $options[] = [
  2654.                             'request_field_value_id' => $value->getRequestFieldValueId(),
  2655.                             'value' => $value->getValue(),
  2656.                             'name' => $value->getName()
  2657.                         ];
  2658.                     }
  2659.                     $list[] = [       
  2660.                         'request_type_id'  => $field->getRequestType()->getRequestTypeId(),   
  2661.                         'request_field_id' => $field->getRequestFieldId(),              
  2662.                         'name'             => $field->getName(),
  2663.                         'input_id'         => $field->getRequestInput()->getRequestInputId(),
  2664.                         'is_required'      => $field->getIsRequired(),
  2665.                         'options'          => $options,
  2666.                         'value'            => ''
  2667.                     ];
  2668.                 }
  2669.                 
  2670.                 return new JsonResponse(array('status' => 'success''data' => $list));
  2671.                
  2672.             }
  2673.         }
  2674.         return new JsonResponse(array('status' => 'error'));
  2675.     }       
  2676.     /**
  2677.      * @Route("/create-agent-report", name="create-agent-report", methods={"GET", "POST"})
  2678.      */
  2679.     public function createAgentReport(Request $requestMailHelper $mailHelperEntityManagerInterface $entityManager): Response
  2680.     {
  2681.         
  2682.         $data json_decode(file_get_contents("php://input"));             
  2683.         if($data)
  2684.         {             
  2685.             $seid     $data->seid;            
  2686.             $rtid     $data->rtid;
  2687.             $comments $data->comments;
  2688.             
  2689.             $employeeShiftObj $entityManager->getRepository(ShiftEmployee::class)->findOneBy([                
  2690.                 'shiftEmployeeId' => $seid         
  2691.             ]);
  2692.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  2693.                 'employeeId' => $employeeShiftObj->getEmployee()->getEmployeeId()         
  2694.             ]);    
  2695.             $locationObj $entityManager->getRepository(Location::class)->findOneBy([                
  2696.                 'locationId' => $employeeShiftObj->getLocation()->getLocationId()        
  2697.             ]);
  2698.             
  2699.             $reportType $entityManager->getRepository(ShiftReportType::class)->findOneBy([                
  2700.                 'shiftReportTypeId' => $rtid
  2701.             ]);
  2702.             if($employeeShiftObj && $employeeObj && $locationObj && $reportType)
  2703.             {                    
  2704.                       
  2705.                 $event = new ShiftEvent();
  2706.                 $event->setEmployee($employeeObj);
  2707.                 $event->setLocation($locationObj);
  2708.                 $event->setShiftEmployee($employeeShiftObj);
  2709.                 $event->setShiftReportType($reportType);
  2710.                 $event->setIsEmptyEvent(0);
  2711.                 $event->setIsActive(1);
  2712.                 $event->setIsPanic(0);
  2713.                 $event->setComments($comments);
  2714.                 $event->setCreatedAt(new \DateTime());
  2715.                 $entityManager->persist($event);
  2716.                 $entityManager->flush();
  2717.                 //--------------- ALERTA DE EMAILS ---------------//
  2718.                 $emailAlertObj $entityManager->getRepository(EmailAlert::class)->findOneBy([                
  2719.                     'emailAlertId' => 2
  2720.                 ]);
  2721.                 if($emailAlertObj->getEmail())
  2722.                 {
  2723.                     $content "<p>El agente ".$employeeObj->getName()." ha reportado novedades en su turno.</p>";                        
  2724.                     $content .= "<p><b>Ubicación:</b> ".$locationObj->getName()."</p>";
  2725.                     $content .= "<p><b>Fecha:</b> ".date('Y-m-d H:i:s')."</p>";
  2726.                     $content .= "<p><b>ID de reporte:</b> #".$event->getShiftEventId()."</p>";
  2727.                     $content .= "<p><b>Tipo:</b> ".$reportType->getName()."</p>";
  2728.                     $content .= "<p><b>Comments:</b> ".$comments."</p>";
  2729.                     $mailHelper::sendEmail($emailAlertObj->getEmail(), "Novedades - ".$employeeObj->getName(), $content);
  2730.                 };
  2731.                 //--------------- ALERTA DE EMAILS ---------------//
  2732.                 return new JsonResponse(array('status' => 'success''eventId' => $event->getShiftEventId()));
  2733.                
  2734.             }
  2735.         }
  2736.         return new JsonResponse(array('status' => 'error'));
  2737.     }           
  2738.     
  2739.     /**
  2740.      * @Route("/get-report-files", name="get-report-files", methods={"GET", "POST"})
  2741.      */
  2742.     public function getReportFilesAction(Request $requestEntityManagerInterface $entityManager): Response
  2743.     {
  2744.         
  2745.         $data json_decode(file_get_contents("php://input"));             
  2746.         if($data)
  2747.         {             
  2748.             
  2749.             $seid $data->seid;
  2750.             $pictures $this->getReportFiles($entityManager$seid);      
  2751.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));                           
  2752.         }
  2753.         return new JsonResponse(array('status' => 'error'));
  2754.     }  
  2755.     /**
  2756.      * @Route("/get-electronic-files", name="get-electronic-files", methods={"GET", "POST"})
  2757.      */
  2758.     public function getElectronicFilesAction(Request $requestEntityManagerInterface $entityManager): Response
  2759.     {
  2760.         
  2761.         $data json_decode(file_get_contents("php://input"));             
  2762.         if($data)
  2763.         {             
  2764.             
  2765.             $eid $data->eid;
  2766.             $pictures $this->getElectronicFiles($entityManager$eid);
  2767.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));                           
  2768.         }
  2769.         return new JsonResponse(array('status' => 'error'));
  2770.     }   
  2771.     
  2772.     
  2773.     /**
  2774.      * @Route("/get-ticket-files", name="get-ticket-files", methods={"GET", "POST"})
  2775.      */
  2776.     public function getTicketFilesAction(Request $requestEntityManagerInterface $entityManager): Response
  2777.     {
  2778.         
  2779.         $data json_decode(file_get_contents("php://input"));             
  2780.         if($data)
  2781.         {             
  2782.             
  2783.             $tid $data->tid;
  2784.             $pictures $this->getTicketFiles($entityManager$tid);
  2785.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));                           
  2786.         }
  2787.         return new JsonResponse(array('status' => 'error'));
  2788.     }       
  2789.     /**
  2790.      * @Route("/get-sanction-files", name="get-sanction-files", methods={"GET", "POST"})
  2791.      */
  2792.     public function getSanctionFilesAction(Request $requestEntityManagerInterface $entityManager): Response
  2793.     {
  2794.         
  2795.         $data json_decode(file_get_contents("php://input"));             
  2796.         if($data)
  2797.         {             
  2798.             
  2799.             $sid $data->sid;
  2800.             $pictures $this->getSanctionFiles($entityManager$sid);
  2801.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));                           
  2802.         }
  2803.         return new JsonResponse(array('status' => 'error'));
  2804.     }  
  2805.     /**
  2806.      * @Route("/get-reaction-files", name="get-reaction-files", methods={"GET", "POST"})
  2807.      */
  2808.     public function getReactionFilesAction(Request $requestEntityManagerInterface $entityManager): Response
  2809.     {
  2810.         
  2811.         $data json_decode(file_get_contents("php://input"));             
  2812.         if($data)
  2813.         {             
  2814.             
  2815.             $rid $data->rid;
  2816.             $pictures $this->getReactionFiles($entityManager$rid);
  2817.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));                           
  2818.         }
  2819.         return new JsonResponse(array('status' => 'error'));
  2820.     }      
  2821.     /**
  2822.      * @Route("/get-vassignment-files", name="get-vassignment-files", methods={"GET", "POST"})
  2823.      */
  2824.     public function getVassignmentFilesAction(Request $requestEntityManagerInterface $entityManager): Response
  2825.     {
  2826.         
  2827.         $data json_decode(file_get_contents("php://input"));             
  2828.         if($data)
  2829.         {             
  2830.             
  2831.             $vaid $data->vaid;
  2832.             $type $data->type;
  2833.             $pictures $this->getVehicleAssignmentFiles($entityManager$vaid$type);
  2834.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));                           
  2835.         }
  2836.         return new JsonResponse(array('status' => 'error'));
  2837.     }      
  2838.     /**
  2839.      * @Route("/get-electronic-list", name="get-electronic-list", methods={"GET", "POST"})
  2840.      */
  2841.     public function getElectronicList(Request $requestEntityManagerInterface $entityManager): Response
  2842.     {
  2843.         
  2844.         $data json_decode(file_get_contents("php://input"));             
  2845.         if($data)
  2846.         {             
  2847.             
  2848.             $eid $data->eid;
  2849.             $objs $entityManager->getRepository(Electronic::class)->findBy([
  2850.                 'is_active' => 1,
  2851.                 'created_by_employee_id' => $eid
  2852.             ], ['created_at' => 'DESC'], 3);
  2853.             $list = [];
  2854.             foreach($objs as $item)
  2855.             {
  2856.                 $pictures $this->getElectronicFiles($entityManager$item->getElectronicId());
  2857.                 if($item->getClient())
  2858.                 {
  2859.                     $client   $item->getClient()->getName();
  2860.                     $project  $item->getProject()->getName();
  2861.                     $location $item->getLocation()->getName();
  2862.                     $address  $item->getLocation()->getAddress();
  2863.                 } else {
  2864.                     $client   $item->getCustomClientName();
  2865.                     $project  "";
  2866.                     $location "";
  2867.                     $address  "";
  2868.                 }
  2869.                 $list[] = [
  2870.                     'electronic_id'  => $item->getElectronicId(),  
  2871.                     'client'         => $client,
  2872.                     'project'        => $project,
  2873.                     'location'       => $location,
  2874.                     'address'        => $address,
  2875.                     'type'           => $item->getElectronicType()->getName(),                    
  2876.                     'created_at'     => $item->getCreatedAt()->format("Y-m-d H:i:s"),   
  2877.                     'pictures'       => $pictures
  2878.                 ];
  2879.             }
  2880.             
  2881.             return new JsonResponse(array('status' => 'success''data' => $list));
  2882.         }
  2883.         return new JsonResponse(array('status' => 'error'));
  2884.     }      
  2885.     
  2886.     /**
  2887.      * @Route("/remove-agent-from-supervision", name="remove-agent-from-supervision", methods={"GET", "POST"})
  2888.      */
  2889.     public function removeAgentFromSupervision(Request $requestEntityManagerInterface $entityManager): Response
  2890.     {
  2891.         
  2892.         $data json_decode(file_get_contents("php://input"));             
  2893.         if($data)
  2894.         {             
  2895.             
  2896.             $employeeId     $data->employeeId;
  2897.             $supervisionId $data->supervisionId;
  2898.             $supervisionEmployee $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  2899.                 "Employee"    => $employeeId,
  2900.                 "Supervision" => $supervisionId
  2901.             ]);
  2902.             if($supervisionEmployee)
  2903.             {
  2904.                 $entityManager->remove($supervisionEmployee);
  2905.                 $entityManager->flush();
  2906.             }
  2907.             
  2908.             return new JsonResponse(array('status' => 'success'));
  2909.         }
  2910.         return new JsonResponse(array('status' => 'error'));
  2911.     }    
  2912.     
  2913.     
  2914.     /**
  2915.      * @Route("/remove-refueling", name="remove-refueling", methods={"GET", "POST"})
  2916.      */
  2917.     public function removeRefueling(Request $requestEntityManagerInterface $entityManager): Response
  2918.     {
  2919.         
  2920.         $data json_decode(file_get_contents("php://input"));             
  2921.         if($data)
  2922.         {             
  2923.             
  2924.             $refuelId $data->rid;            
  2925.             $refuelObj $entityManager->getRepository(Refuel::class)->findOneBy([
  2926.                 "refuelId"    => $refuelId                
  2927.             ]);
  2928.             if($refuelObj)
  2929.             {                
  2930.                 @unlink("uploads/vehicle/".$refuelObj->getPicturePath());
  2931.                 $entityManager->remove($refuelObj);
  2932.                 $entityManager->flush();
  2933.             }
  2934.             
  2935.             return new JsonResponse(array('status' => 'success'));
  2936.         }
  2937.         return new JsonResponse(array('status' => 'error'));
  2938.     }        
  2939.     /**
  2940.      * @Route("/remove-fail", name="remove-fail", methods={"GET", "POST"})
  2941.      */
  2942.     public function removeFail(Request $requestEntityManagerInterface $entityManager): Response
  2943.     {
  2944.         
  2945.         $data json_decode(file_get_contents("php://input"));             
  2946.         if($data)
  2947.         {             
  2948.             
  2949.             $vaid $data->vaid;            
  2950.             $vehicleAssignmentFailObj $entityManager->getRepository(VehicleAssignmentFail::class)->findOneBy([
  2951.                 "vehicleAssignmentFailId" => $vaid                
  2952.             ]);
  2953.             if($vehicleAssignmentFailObj)
  2954.             {                
  2955.                 //@unlink("uploads/vehicle/".$vehicleAssignmentFailObj->getPicturePath());
  2956.                 $vehicleAssignmentFailObj->setIsActive(0);
  2957.                 $entityManager->persist($vehicleAssignmentFailObj);
  2958.                 $entityManager->flush();
  2959.             }
  2960.             
  2961.             return new JsonResponse(array('status' => 'success'));
  2962.         }
  2963.         return new JsonResponse(array('status' => 'error'));
  2964.     }            
  2965.     
  2966.     
  2967.     /**
  2968.      * @Route("/get-reaction-list", name="get-reaction-list", methods={"GET", "POST"})
  2969.      */
  2970.     public function getReactionList(Request $requestEntityManagerInterface $entityManager): Response
  2971.     {
  2972.         
  2973.         $data json_decode(file_get_contents("php://input"));             
  2974.         if($data)
  2975.         {             
  2976.             
  2977.             $paths $this->getProjectPaths();
  2978.             $eid   $data->eid;
  2979.             $reaction $entityManager->getRepository(Reaction::class)->getMyReactions($eid);
  2980.             $list = [];
  2981.             foreach($reaction as $item)
  2982.             {
  2983.                 $pictures $this->getReactionFiles($entityManager$item['reaction_id']);
  2984.                 $signatureStatus false;
  2985.                 if($item['signature_client'])
  2986.                 {
  2987.                     $signatureStatus true;
  2988.                 }
  2989.                 $encrypted $this->encryptor->encrypt($item['reaction_id']);
  2990.                 $link      $paths['public_link'].$encrypted;
  2991.                 $updatedBy "";
  2992.                 $updatedByObj $entityManager->getRepository(User::class)->findOneBy([
  2993.                     'id' => $item['updated_by']                
  2994.                 ]);
  2995.                 if($updatedByObj)
  2996.                 {
  2997.                     $updatedBy $updatedByObj->getFirstName()." ".$updatedByObj->getLastName();
  2998.                 }
  2999.                 $list[] = [
  3000.                     'reaction_id' => $item['reaction_id'],  
  3001.                     'client'      => $item['client'],
  3002.                     'project'     => $item['project'],
  3003.                     'location'    => $item['location'],
  3004.                     'address'     => $item['address'],
  3005.                     'activation'  => $item['time_activation'],
  3006.                     'reaction'    => $item['reaction'],                    
  3007.                     'created_at'  => $item['created_at'],
  3008.                     'comments'    => $item['creator_comments'],
  3009.                     'created_by'  => $item['created_by'],
  3010.                     'is_done'     => $item['is_done'],
  3011.                     'is_active'   => $item['is_active'],
  3012.                     'is_cancel'   => $item['is_cancel'],
  3013.                     'updated_at'  => $item['updated_at'],
  3014.                     'updated_by'  => $updatedBy,
  3015.                     'pictures'    => $pictures,
  3016.                     'link'        => $link,
  3017.                     'signature_client' => $signatureStatus
  3018.                 ];
  3019.             }
  3020.             $status      "";
  3021.             $statusDate  "";
  3022.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  3023.                 'employeeId' => $eid                
  3024.             ]); 
  3025.             $statusRaw   "";
  3026.             if($employeeObj)
  3027.             {
  3028.                 $statusRaw $employeeObj->getAppStatus();
  3029.                 $status = ($employeeObj->getAppStatus() == 'ACTIVO' true false);
  3030.                 if($status)
  3031.                 {
  3032.                     $statusDate "Disponible desde ".$employeeObj->getAppStatusUpdatedAt()->format("Y-m-d H:i:s");
  3033.                 } else {
  3034.                     $statusDate "Inactivo desde ".$employeeObj->getAppStatusUpdatedAt()->format("Y-m-d H:i:s");
  3035.                 }    
  3036.             }
  3037.             
  3038.             return new JsonResponse(array('status' => 'success''data' => $list'description' => $employeeObj->getAppStatusDescription(), 'appStatus' => $status'appStatusDate' => $statusDate'appStatusRaw' => $statusRaw));
  3039.         }
  3040.         return new JsonResponse(array('status' => 'error'));
  3041.     }      
  3042.     /**
  3043.      * @Route("/get-shift-info", name="get-shift-info", methods={"GET", "POST"})
  3044.      */
  3045.     public function getShiftInfo(Request $requestEntityManagerInterface $entityManager): Response
  3046.     {
  3047.         
  3048.         $data json_decode(file_get_contents("php://input"));             
  3049.         if($data)
  3050.         {             
  3051.             $path $this->getProjectPaths();
  3052.             $eid  $data->eid;
  3053.             $shiftEmployee $entityManager->getRepository(ShiftEmployee::class)->findOneBy([
  3054.                 'Employee' => $eid,
  3055.                 'isActive' => 1,
  3056.                 'isDone'   => null
  3057.             ], ['createdAt' => 'DESC']);
  3058.             if($shiftEmployee)
  3059.             {
  3060.                 $client_name "";
  3061.                 if($shiftEmployee->getLocation()->getClient())
  3062.                 {
  3063.                     $client_name $shiftEmployee->getLocation()->getClient()->getName();
  3064.                 }
  3065.                 $project_name "";
  3066.                 if($shiftEmployee->getLocation()->getProject())
  3067.                 {
  3068.                     $project_name $shiftEmployee->getLocation()->getProject()->getName();
  3069.                 }
  3070.                 // Check if the employee is on pause 
  3071.                 $shiftEmployeePauseObj $entityManager->getRepository(ShiftEmployeePause::class)->findOneBy([                
  3072.                     'ShiftEmployee' => $shiftEmployee,    
  3073.                     'ended_at'  => null
  3074.                 ]); 
  3075.                 if($shiftEmployeePauseObj)
  3076.                 {
  3077.                     $paused true;
  3078.                 } else {
  3079.                     $paused false;
  3080.                 }
  3081.                 $array = [
  3082.                     "client_name"       => $client_name,
  3083.                     "location_address"  => $shiftEmployee->getLocation()->getAddress(),
  3084.                     "location_id"       => $shiftEmployee->getLocation()->getLocationId(),
  3085.                     "location_name"     => $shiftEmployee->getLocation()->getName(),
  3086.                     "project_name"      => $project_name,
  3087.                     "shift_employee_id" => $shiftEmployee->getShiftEmployeeId(),
  3088.                     "shift_start"       => $shiftEmployee->getOpenedAt(),
  3089.                     "shift_end"         => $shiftEmployee->getClosedAt()                    
  3090.                 ];
  3091.                 return new JsonResponse(array('status' => 'success''data' => $array));
  3092.             } else {
  3093.                 
  3094.                 return new JsonResponse(array('status' => 'not_found'));
  3095.             }
  3096.         }
  3097.         return new JsonResponse(array('status' => 'error'));
  3098.     }
  3099.     
  3100.     /**
  3101.      * @Route("/get-supervisor-routes", name="get-supervisor-routes", methods={"GET", "POST"})
  3102.      */
  3103.     public function getSupervisorRoutesAction(Request $requestEntityManagerInterface $entityManager): Response
  3104.     {
  3105.         
  3106.         $data json_decode(file_get_contents("php://input"));             
  3107.         if($data)
  3108.         {             
  3109.             $path $this->getProjectPaths();
  3110.             $eid  $data->eid;
  3111.             $employeeMainObj $entityManager->getRepository(Employee::class)->findOneBy([                
  3112.                 'employeeId'  => $eid         
  3113.             ]);
  3114.             //SI ES UN SUPERVISOR O COORDINADOR (5) O SUB-COORDINADOR (16), PUEDE VER SOLO LAS RUTAS ASIGNADAS
  3115.             if($employeeMainObj->getJobPosition()->getJobPositionId() == || $employeeMainObj->getJobPosition()->getJobPositionId() == || $employeeMainObj->getJobPosition()->getJobPositionId() == 16)
  3116.             {
  3117.                 $routesObj $entityManager->getRepository(SupervisionRouteEmployee::class)->findBy([                
  3118.                     'Employee'  => $eid,
  3119.                     'is_active' => 1                
  3120.                 ]);
  3121.                 $routes = [];
  3122.                 foreach($routesObj as $item)
  3123.                 {
  3124.                     if($item->getSupervisionRoute()->getIsActive() == 0)
  3125.                     {
  3126.                         continue;
  3127.                     }
  3128.                     $routeLocationObj $entityManager->getRepository(SupervisionRouteLocation::class)->findBy([                
  3129.                         'SupervisionRoute'  => $item->getSupervisionRoute()->getSupervisionRouteId()                    
  3130.                     ]);
  3131.                     $locations = [];
  3132.                     foreach($routeLocationObj as $subitem)
  3133.                     {
  3134.                         //Si no esta activa la ubicación, entonces ignoramos
  3135.                         if($subitem->getLocation()->getIsActive() == 0)
  3136.                         {
  3137.                             continue;
  3138.                         }
  3139.                         //Obtener el listado de empleados que deberian estar en el TURNO en este momento
  3140.                         $activeShift $entityManager->getRepository(Shift::class)->getActiveShifts($subitem->getLocation()->getLocationId());                    
  3141.                         $employees_list = [];
  3142.                         if($activeShift)
  3143.                         {                  
  3144.                             $shiftEmployees $entityManager->getRepository(ShiftEmployee::class)->findBy([
  3145.                                 'Shift' => $activeShift['shift_id']
  3146.                             ]);
  3147.                             foreach($shiftEmployees as $employee)
  3148.                             {
  3149.                                 if($employee->getEmployee()->getAvatarPath())
  3150.                                 {
  3151.                                     $avatar $path['public_path'].'uploads/'.$employee->getEmployee()->getAvatarPath();
  3152.                                 } else {
  3153.                                     $avatar $path['public_path'].'assets/img/empty_user.png';
  3154.                                 }                   
  3155.                                 
  3156.                                 $employees_list[] = [
  3157.                                     "shift_id"    => $activeShift['shift_id'],
  3158.                                     "employee_id" => $employee->getEmployee()->getEmployeeId(),
  3159.                                     "citizen_id"  => $employee->getEmployee()->getCitizenId(),
  3160.                                     "name"        => $employee->getEmployee()->getName(),
  3161.                                     "alias"       => $employee->getEmployee()->getAlias(),
  3162.                                     "avatar"      => $avatar,
  3163.                                     "position"    => $employee->getEmployee()->getJobPosition()->getName(),
  3164.                                     "location_position" => $employee->getLocationPosition()->getName()
  3165.                                 ];
  3166.                             }
  3167.                         }
  3168.                         if($subitem->getProject())
  3169.                         {
  3170.                             $projectName $subitem->getProject()->getName();
  3171.                             $projectId   $subitem->getProject()->getProjectId();
  3172.                         } else {
  3173.                             $projectName "";
  3174.                             $projectId   "";
  3175.                         }
  3176.                         $search_string $subitem->getLocation()->getName().", ".$projectName.", ".$subitem->getLocation()->getAddress();
  3177.                     
  3178.                         $locationEmployees $this->getLocationEmployeesList($subitem->getLocation()->getLocationId(), $entityManager);
  3179.                         $arr   = [];
  3180.                         $arr[] = ['val' => 'Limpieza en Puesto''isChecked' => false];
  3181.                         $arr[] = ['val' => 'Estado de Mobiliario''isChecked' => false];
  3182.                         $arr[] = ['val' => 'No cuenta con Procedimiento''isChecked' => false];
  3183.                         $arr[] = ['val' => 'No cuenta con Sanitario''isChecked' => false];
  3184.                         $arr[] = ['val' => 'No cuenta con Ventilación''isChecked' => false];   
  3185.                                 
  3186.                         $facilitySync = [
  3187.                             'facility_status'           => "",   
  3188.                             'facility_requires_change'  => json_encode($arr)
  3189.                         ];
  3190.                         $locations[] = [
  3191.                             'location_name'    => $subitem->getLocation()->getName(),
  3192.                             'location_address' => $subitem->getLocation()->getAddress(),
  3193.                             'location_id'      => $subitem->getLocation()->getLocationId(),
  3194.                             'project_name'     => $projectName,
  3195.                             'project_id'       => $projectId,
  3196.                             'client_name'      => ($subitem->getClient() ? $subitem->getClient()->getName() : ''),
  3197.                             'client_id'        => ($subitem->getClient() ? $subitem->getClient()->getClientId() : ''),
  3198.                             'visible'          => 1,
  3199.                             'search'           => $search_string,
  3200.                             'supervision_route_id' => $item->getSupervisionRoute()->getSupervisionRouteId(),
  3201.                             "route_name"           => $item->getSupervisionRoute()->getName(),
  3202.                             'agents'               => $employees_list
  3203.                             
  3204.                             //OFFLINE SYNC
  3205.                             'location_employees'   => $locationEmployees,
  3206.                             'max_agents'           => $subitem->getLocation()->getContractedAgents(),
  3207.                             'facility_sync'        => $facilitySync                                     
  3208.                         ];             
  3209.                     }                
  3210.                     
  3211.                     $location_count count($locations);
  3212.                     $routes[] = [
  3213.                         'supervision_route_id' => $item->getSupervisionRoute()->getSupervisionRouteId(),
  3214.                         "route_name"           => $item->getSupervisionRoute()->getName(),
  3215.                         'count'                => $location_count,
  3216.                         'locations'            => $locations
  3217.                     ];
  3218.                 }
  3219.                 
  3220.                 return new JsonResponse(array('status' => 'success''routes' => $routes));                           
  3221.             //SI ES UN ESCOLTA, PUEDE VER TODAS LAS UBICACIONES DE UNA VEZ   
  3222.             } else if($employeeMainObj->getJobPosition()->getJobPositionId() == 11) {
  3223.                 $routesList $entityManager->getRepository(SupervisionRouteLocation::class)->getActiveSupervisionRoutes();
  3224.                 foreach($routesList as $route)
  3225.                 {
  3226.                     $routeObj $entityManager->getRepository(SupervisionRoute::class)->findOneBy([                                        
  3227.                         'supervisionRouteId' => $route['supervision_route_id']
  3228.                     ]);
  3229.                     $locationObj $entityManager->getRepository(SupervisionRouteLocation::class)->findBy([                                    
  3230.                         'SupervisionRoute' => $routeObj
  3231.                     ]);
  3232.                     $locations = [];
  3233.                     foreach($locationObj as $subitem)
  3234.                     {
  3235.                         $search_string  $subitem->getLocation()->getName().", ".($subitem->getLocation()->getProject() ? $subitem->getLocation()->getProject()->getName().", " '').$subitem->getLocation()->getAddress();
  3236.                         $employees_list = [];
  3237.                         $locationEmployees $this->getLocationEmployeesList($subitem->getLocation()->getLocationId(), $entityManager);
  3238.                         $arr   = [];
  3239.                         $arr[] = ['val' => 'Limpieza en Puesto''isChecked' => false];
  3240.                         $arr[] = ['val' => 'Estado de Mobiliario''isChecked' => false];
  3241.                         $arr[] = ['val' => 'No cuenta con Procedimiento''isChecked' => false];
  3242.                         $arr[] = ['val' => 'No cuenta con Sanitario''isChecked' => false];
  3243.                         $arr[] = ['val' => 'No cuenta con Ventilación''isChecked' => false];   
  3244.                                 
  3245.                         $facilitySync = [
  3246.                             'facility_status'           => "",   
  3247.                             'facility_requires_change'  => json_encode($arr)
  3248.                         ];
  3249.                         $locations[] = [
  3250.                                 'location_name'    => $subitem->getLocation()->getName(),
  3251.                                 'location_address' => $subitem->getLocation()->getAddress(),
  3252.                                 'location_id'      => $subitem->getLocation()->getLocationId(),
  3253.                                 'project_name'     => ($subitem->getLocation()->getProject() ? $subitem->getLocation()->getProject()->getName() : ''),
  3254.                                 'project_id'       => ($subitem->getLocation()->getProject() ? $subitem->getLocation()->getProject()->getProjectId() : ''),
  3255.                                 'client_name'      => ($subitem->getLocation()->getClient() ? $subitem->getLocation()->getClient()->getName() : ''),
  3256.                                 'client_id'        => ($subitem->getLocation()->getClient() ? $subitem->getLocation()->getClient()->getClientId() : ''),
  3257.                                 'visible'          => 1,
  3258.                                 'search'           => $search_string,
  3259.                                 'supervision_route_id' => 0,
  3260.                                 "route_name"           => $route['name'], //"Todas las Ubicaciones",
  3261.                                 'agents'               => $employees_list,  
  3262.                                 
  3263.                                 //OFFLINE SYNC
  3264.                                 'location_employees'   => $locationEmployees,
  3265.                                 'max_agents'           => $subitem->getLocation()->getContractedAgents(),
  3266.                                 'facility_sync'        => $facilitySync    
  3267.                         ];
  3268.                     }
  3269.                     $routes[] = [
  3270.                         'supervision_route_id' => 0,
  3271.                         "route_name"           => $route['name'],
  3272.                         'count'                => count($locations),
  3273.                         'locations'            => $locations
  3274.                     ];
  3275.                 }
  3276.                 return new JsonResponse(array('status' => 'success''routes' => $routes));                           
  3277.             }
  3278.         }
  3279.         return new JsonResponse(array('status' => 'error'));
  3280.     } 
  3281.     /**
  3282.      * @Route("/remove-agent", name="remove-agent", methods={"GET", "POST"})
  3283.      */
  3284.     public function removeAgentAction(Request $requestEntityManagerInterface $entityManager): Response
  3285.     {
  3286.             
  3287.         $data json_decode(file_get_contents("php://input"));             
  3288.         if($data)
  3289.         {                         
  3290.             
  3291.             $supervisionId $data->supervisionId;
  3292.             $leid  $data->location_employee_id;  
  3293.             $token $data->token;            
  3294.             $locationEmployeeObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([                
  3295.                 'locationEmployeeId'  => $leid,                
  3296.             ]);
  3297.             if($locationEmployeeObj)
  3298.             {
  3299.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  3300.                     'employeeId'  => $token->employee_id
  3301.                 ]);
  3302.                 $locationEmployeeObj->setIsActive(0);
  3303.                 $locationEmployeeObj->setSyncPending(1);
  3304.                 $locationEmployeeObj->setUpdatedAt(new \Datetime());
  3305.                 $locationEmployeeObj->setUpdatedByEmployeeId($employeeObj);
  3306.                 $entityManager->persist($locationEmployeeObj);
  3307.                 $entityManager->flush();
  3308.     
  3309.                 //Unificacion de actividades
  3310.                 $supervisionEmployee $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  3311.                     "Employee"    => $locationEmployeeObj->getEmployee(),
  3312.                     "Supervision" => $supervisionId
  3313.                 ]);    
  3314.                 if($supervisionEmployee)
  3315.                 {
  3316.                     $entityManager->remove($supervisionEmployee);
  3317.                     $entityManager->flush();
  3318.                 }
  3319.             
  3320.                 
  3321.                 return new JsonResponse(array('status' => 'success'));                           
  3322.             }
  3323.         }
  3324.         return new JsonResponse(array('status' => 'error'));
  3325.     }  
  3326.     /**
  3327.      * @Route("/remove-agent-extra", name="remove-agent-extra", methods={"GET", "POST"})
  3328.      */
  3329.     public function removeAgentExtraAction(Request $requestEntityManagerInterface $entityManager): Response
  3330.     {
  3331.             
  3332.         $data json_decode(file_get_contents("php://input"));             
  3333.         if($data)
  3334.         {                         
  3335.             
  3336.             $supervisionId $data->supervisionId;
  3337.             $seid  $data->supervision_employee_id;  
  3338.             $token $data->token;            
  3339.             $supervisionObj $entityManager->getRepository(Supervision::class)->findOneBy([                
  3340.                 'supervisionId'  => $supervisionId
  3341.             ]);
  3342.             if($supervisionObj)
  3343.             {
  3344.                 /*$employeeObj = $entityManager->getRepository(Employee::class)->findOneBy([                
  3345.                     'employeeId'  => $token->employee_id
  3346.                 ]);*/                                  
  3347.                 $supervisionEmployee $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  3348.                     "supervisionEmployeeId" => $seid,                    
  3349.                     "is_extra"    => 1
  3350.                 ]);    
  3351.                 if($supervisionEmployee)
  3352.                 {
  3353.                     $entityManager->remove($supervisionEmployee);
  3354.                     $entityManager->flush();
  3355.                 }
  3356.             
  3357.                 
  3358.                 return new JsonResponse(array('status' => 'success'));                           
  3359.             }
  3360.         }
  3361.         return new JsonResponse(array('status' => 'error'));
  3362.     }  
  3363.     
  3364.     
  3365.     /**
  3366.      * @Route("/check-agent", name="check-agent", methods={"GET", "POST"})
  3367.      */
  3368.     public function checkAgentAction(Request $requestEntityManagerInterface $entityManager): Response
  3369.     {
  3370.         $data json_decode(file_get_contents("php://input"));             
  3371.         if($data)
  3372.         {                                     
  3373.             $lid      $data->location_id;              
  3374.             $employee $data->employee;          
  3375.             $locationEmployeeObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([                         
  3376.                 'Employee'  => $employee->employee_id,
  3377.                 'is_active' => 1
  3378.             ]);
  3379.             if($locationEmployeeObj)
  3380.             {                
  3381.                 if($locationEmployeeObj->getLocation()->getLocationId() == $lid)
  3382.                 {
  3383.                     $message "No se puede asignar al agente porque ya se encuentra asignado en esta ubicación";
  3384.                     return new JsonResponse(array('status' => 'duplicated''message' => $message));    
  3385.                 }
  3386.                 $locationId   $locationEmployeeObj->getLocation()->getLocationId();
  3387.                 $locationName $locationEmployeeObj->getLocation()->getName(); 
  3388.                 
  3389.                 $message "El agente ya se encuentra asignado en otra ubicación ".$locationName." (".$locationId."). Desea darle de baja en la otra ubicación y asignarlo a esta?";
  3390.                 return new JsonResponse(array('status' => 'duplicated''message' => $message));
  3391.             }
  3392.         }
  3393.             
  3394.         return new JsonResponse(array('status' => 'success'));
  3395.     }
  3396.     // Esta funcion debe estar siempre parecida a la original add-agent 
  3397.     /**
  3398.      * @Route("/add-agent-extra", name="add-agent-extra", methods={"GET", "POST"})
  3399.      */
  3400.     public function addAgentExtraAction(Request $requestEntityManagerInterface $entityManager): Response
  3401.     {
  3402.             
  3403.         $data json_decode(file_get_contents("php://input"));             
  3404.         if($data)
  3405.         {                         
  3406.             
  3407.             $supervisionData $data->supervisionData;
  3408.             $lid             $data->location_id;  
  3409.             $token           $data->token;  
  3410.             $employee        $data->employee;    
  3411.             $type            $data->type;          
  3412.             $supervisionObj $entityManager->getRepository(Supervision::class)->findOneBy([                
  3413.                 'supervisionId'  => $supervisionData->supervision_id,                
  3414.             ]);
  3415.             if($supervisionObj)
  3416.             {
  3417.                 $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([                
  3418.                     'employeeId'  => $token->employee_id
  3419.                 ]);
  3420.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  3421.                     'employeeId'  => $employee->employee_id
  3422.                 ]);
  3423.                 $locationPositionObj $entityManager->getRepository(LocationPosition::class)->findOneBy([                
  3424.                     'locationPositionId'  => 1
  3425.                 ]);
  3426.             
  3427.                 $supervisionEmployeeObj = new SupervisionEmployee();
  3428.                 $supervisionEmployeeObj->setSupervision($supervisionObj);                
  3429.                 $supervisionEmployeeObj->setEmployee($employeeObj);
  3430.                 $supervisionEmployeeObj->setLocationPosition($locationPositionObj);
  3431.                 $supervisionEmployeeObj->setIsExtra(1);
  3432.                 $supervisionEmployeeObj->setExtraType($type);
  3433.                 $supervisionEmployeeObj->setIsActive(1);                 
  3434.                 $supervisionEmployeeObj->setCreatedAt(new \Datetime());
  3435.                 $supervisionEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  3436.                 $entityManager->persist($supervisionEmployeeObj);
  3437.                 $entityManager->flush();
  3438.                 return new JsonResponse(array('status' => 'success'));                           
  3439.             }
  3440.         }
  3441.         return new JsonResponse(array('status' => 'error'));
  3442.     }      
  3443.     
  3444.     /**
  3445.      * @Route("/add-agent", name="add-agent", methods={"GET", "POST"})
  3446.      */
  3447.     public function addAgentAction(Request $requestEntityManagerInterface $entityManager): Response
  3448.     {
  3449.             
  3450.         $data json_decode(file_get_contents("php://input"));             
  3451.         if($data)
  3452.         {                         
  3453.             
  3454.             $lid      $data->location_id;  
  3455.             $token    $data->token;  
  3456.             $employee $data->employee;          
  3457.             $locationObj $entityManager->getRepository(Location::class)->findOneBy([                
  3458.                 'locationId'  => $lid,                
  3459.             ]);
  3460.             if($locationObj)
  3461.             {
  3462.                 $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([                
  3463.                     'employeeId'  => $token->employee_id
  3464.                 ]);
  3465.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  3466.                     'employeeId'  => $employee->employee_id
  3467.                 ]);
  3468.                 $locationPositionObj $entityManager->getRepository(LocationPosition::class)->findOneBy([                
  3469.                     'locationPositionId'  => 1
  3470.                 ]);
  3471.                 //Revison para no duplicar las asignaciones
  3472.                 $locationEmployeeCheckObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([                
  3473.                     'Employee'  => $employee->employee_id,     
  3474.                     'is_active' => 1
  3475.                 ]);
  3476.                 if($locationEmployeeCheckObj)
  3477.                 {
  3478.                     //Si hay una asignación activa, entonces se desactiva y se ordena para su actualización
  3479.                     if($locationEmployeeCheckObj->getLocation()->getLocationId() <> $lid)
  3480.                     {
  3481.                         $locationEmployeeCheckObj->setIsActive(0);
  3482.                         $locationEmployeeCheckObj->setSyncPending(1);
  3483.                         $locationEmployeeCheckObj->setUpdatedAt(new \Datetime());
  3484.                         $locationEmployeeCheckObj->setUpdatedByEmployeeId($supervisorObj);
  3485.                         $entityManager->persist($locationEmployeeCheckObj);
  3486.                         $entityManager->flush();                    
  3487.                     }    
  3488.                 }
  3489.                 $locationEmployeeObj = new LocationEmployee();
  3490.                 $locationEmployeeObj->setLocation($locationObj);
  3491.                 $locationEmployeeObj->setEmployee($employeeObj);
  3492.                 $locationEmployeeObj->setLocationPosition($locationPositionObj);
  3493.                 $locationEmployeeObj->setIsActive(1);
  3494.                 $locationEmployeeObj->setSyncPending(1);
  3495.                 $locationEmployeeObj->setCreatedAt(new \Datetime());
  3496.                 $locationEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  3497.                 $entityManager->persist($locationEmployeeObj);
  3498.                 $entityManager->flush();
  3499.                 return new JsonResponse(array('status' => 'success'));                           
  3500.             }
  3501.         }
  3502.         return new JsonResponse(array('status' => 'error'));
  3503.     }      
  3504.     /**
  3505.      * @Route("/get-extra-employees", name="get-extra-employees", methods={"GET", "POST"})
  3506.      */
  3507.     public function getExtraEmployees(Request $requestEntityManagerInterface $entityManager): Response
  3508.     {
  3509.         
  3510.         $data json_decode(file_get_contents("php://input"));             
  3511.         if($data)
  3512.         {                         
  3513.             $supervision $data->supervision;
  3514.             $supervisionObj $entityManager->getRepository(Supervision::class)->findOneBy([                
  3515.                 'supervisionId' => $supervision->supervision_id
  3516.             ]);
  3517.             $supervisionEmployeeList $entityManager->getRepository(SupervisionEmployee::class)->findBy([                
  3518.                 'Supervision'  => $supervision->supervision_id,
  3519.                 'is_active'    => 1,
  3520.                 'is_extra'     => 1
  3521.             ]);
  3522.             $employees = [];
  3523.             foreach($supervisionEmployeeList as $item)
  3524.             {
  3525.                 $path  $this->getProjectPaths();    
  3526.                 if($item->getEmployee()->getAvatarPath())
  3527.                 {
  3528.                     $avatar $path['public_path'].'uploads/'.$item->getEmployee()->getAvatarPath();
  3529.                 } else {
  3530.                     $avatar $path['public_path'].'assets/img/empty_user.png';
  3531.                 }
  3532.                 $location_position "";
  3533.                 if($item->getLocationPosition())
  3534.                 {
  3535.                     $location_position $item->getLocationPosition()->getName();
  3536.                 }
  3537.                 $employees[] = [
  3538.                     'supervision_employee_id' => $item->getSupervisionEmployeeId(),
  3539.                     'employee_id' => $item->getEmployee()->getEmployeeId(),
  3540.                     'citizen_id'  => $item->getEmployee()->getCitizenId(),
  3541.                     'name'        => ucwords($item->getEmployee()->getName()),
  3542.                     'alias'       => $item->getEmployee()->getAlias(),
  3543.                     'avatar'      => $avatar,
  3544.                     'position'    => $item->getEmployee()->getJobPosition()->getName(),
  3545.                     'type'        => ucwords($item->getExtraType()),
  3546.                     'location_position' => $location_position,
  3547.                     'created_at'  => $item->getCreatedAt()->format('Y-m-d H:i:s')
  3548.                 ];
  3549.             }
  3550.             
  3551.             return new JsonResponse(array('status' => 'success''employees' => $employees));                           
  3552.         }
  3553.         return new JsonResponse(array('status' => 'error'));
  3554.     }  
  3555.     /**
  3556.      * @Route("/get-employees-sync", name="get-employees-sync", methods={"GET", "POST"})
  3557.      */
  3558.     public function getEmployeesSync(Request $requestEntityManagerInterface $entityManager): Response
  3559.     {
  3560.         
  3561.         $data json_decode(file_get_contents("php://input"));             
  3562.         if($data)
  3563.         {                         
  3564.             
  3565.             $employeesList $entityManager->getRepository(Employee::class)->findBy([                
  3566.                 'employeeStatus' => 1,
  3567.                 'jobPosition'    => 1
  3568.             ]);
  3569.             $employees = [];
  3570.             foreach($employeesList as $item)
  3571.             {
  3572.                 $employeesLocationObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([                
  3573.                     'is_active' => 1,
  3574.                     'Employee'  => $item->getEmployeeId()
  3575.                 ]);
  3576.                 $locationName "";
  3577.                 $locationId   "";
  3578.                 $locationEmployeeId "";
  3579.                 if($employeesLocationObj)
  3580.                 {
  3581.                     $locationName $employeesLocationObj->getLocation()->getName();
  3582.                     $locationId   $employeesLocationObj->getLocation()->getLocationId();
  3583.                     $locationEmploeyeId $employeesLocationObj->getLocationEmployeeId();
  3584.                 }
  3585.                 /*$path  = $this->getProjectPaths();    
  3586.                 if($item->getAvatarPath())
  3587.                 {
  3588.                     $avatar = $path['public_path'].'uploads/'.$item->getAvatarPath();
  3589.                 } else {
  3590.                     $avatar = $path['public_path'].'assets/img/empty_user.png';
  3591.                 }*/
  3592.                 $employees[] = [                    
  3593.                     'employee_id' => $item->getEmployeeId(),
  3594.                     'citizen_id'  => $item->getCitizenId(),
  3595.                     'name'        => ucwords($item->getName()),
  3596.                     'alias'       => $item->getAlias(),
  3597.                     //'avatar'      => $avatar,
  3598.                     'position'    => $item->getJobPosition()->getName(),                    
  3599.                     'created_at'  => $item->getCreatedAt()->format('Y-m-d H:i:s'),
  3600.                     'assigned_location'    => $locationName,
  3601.                     'assigned_location_id' => $locationId,
  3602.                     'assigned_location_employee_id' => $locationEmployeeId
  3603.                 ];
  3604.             }
  3605.             
  3606.             return new JsonResponse(array('status' => 'success''employees' => $employees));                           
  3607.         }
  3608.         return new JsonResponse(array('status' => 'error'));
  3609.     }      
  3610.     
  3611.     /**
  3612.      * @Route("/get-location-employees", name="get-location-employees", methods={"GET", "POST"})
  3613.      */
  3614.     public function getLocationEmployees(Request $requestEntityManagerInterface $entityManager): Response
  3615.     {
  3616.         
  3617.         $data json_decode(file_get_contents("php://input"));             
  3618.         if($data)
  3619.         {                         
  3620.             $location_id $data->location_id;
  3621.             $locationObj $entityManager->getRepository(Location::class)->findOneBy([                
  3622.                 'locationId' => $location_id                
  3623.             ]);
  3624.             $employees $this->getLocationEmployeesList($location_id$entityManager);
  3625.             
  3626.             return new JsonResponse(array('status' => 'success''employees' => $employees'max_agents' => $locationObj->getContractedAgents()));                           
  3627.         }
  3628.         return new JsonResponse(array('status' => 'error'));
  3629.     }  
  3630.     
  3631.     public function getLocationEmployeesList($location_id$entityManager)
  3632.     {
  3633.         $locationEmployeeList $entityManager->getRepository(LocationEmployee::class)->findBy([                
  3634.             'Location'  => $location_id,
  3635.             'is_active' => 1
  3636.         ]);
  3637.         $employees = [];
  3638.         foreach($locationEmployeeList as $item)
  3639.         {
  3640.             $path  $this->getProjectPaths();    
  3641.             if($item->getEmployee()->getAvatarPath())
  3642.             {
  3643.                 $avatar $path['public_path'].'uploads/'.$item->getEmployee()->getAvatarPath();
  3644.             } else {
  3645.                 $avatar $path['public_path'].'assets/img/empty_user.png';
  3646.             }
  3647.             $location_position "";
  3648.             if($item->getLocationPosition())
  3649.             {
  3650.                 $location_position $item->getLocationPosition()->getName();
  3651.             }
  3652.             $employees[] = [
  3653.                 'location_employee_id' => $item->getLocationEmployeeId(),
  3654.                 'employee_id' => $item->getEmployee()->getEmployeeId(),
  3655.                 'citizen_id'  => $item->getEmployee()->getCitizenId(),
  3656.                 'name'        => ucwords($item->getEmployee()->getName()),
  3657.                 'alias'       => $item->getEmployee()->getAlias(),
  3658.                 'avatar'      => $avatar,
  3659.                 'position'    => $item->getEmployee()->getJobPosition()->getName(),
  3660.                 'location_position' => $location_position,
  3661.                 'created_at'  => $item->getCreatedAt()->format('Y-m-d H:i:s')
  3662.             ];
  3663.         }
  3664.         return $employees;
  3665.     }
  3666.     /**
  3667.      * @Route("/get-supervision-files", name="get-supervision-files", methods={"GET", "POST"})
  3668.      */
  3669.     public function getSupervisionFilesAction(Request $requestEntityManagerInterface $entityManager): Response
  3670.     {
  3671.         
  3672.         $data json_decode(file_get_contents("php://input"));             
  3673.         if($data)
  3674.         {             
  3675.             
  3676.             $supervision_id $data->supervision_id;
  3677.             $comment_type   $data->comment_type;
  3678.             $pictures $this->getSupervisionFiles($entityManager$supervision_id$comment_type);      
  3679.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));                           
  3680.         }
  3681.         return new JsonResponse(array('status' => 'error'));
  3682.     }  
  3683.     public function getSupervisionFiles($entityManager$supervisionId$type)
  3684.     {
  3685.         $path  $this->getProjectPaths();    
  3686.         $array = [];
  3687.         $pictures $entityManager->getRepository(SupervisionPicture::class)->findBy([
  3688.             "Supervision"  => $supervisionId,
  3689.             "picture_type" => $type
  3690.         ]);
  3691.         foreach($pictures as $picture)
  3692.         {
  3693.             $picturePath $path['public_path']."uploads/reports/s_".$supervisionId."/".$picture->getPicturePath();                                                                            
  3694.             $array[] = array(
  3695.                 'picture_id'   => $picture->getSupervisionPictureId(),                        
  3696.                 'picture_path' => $picturePath
  3697.             );
  3698.         }
  3699.         return $array;
  3700.     }    
  3701.         
  3702.     /**
  3703.      * @Route("/get-vehicle-fuel", name="get-vehicle-fuel", methods={"GET", "POST"})
  3704.      */
  3705.     public function getVehicleFuel(Request $requestEntityManagerInterface $entityManager): Response
  3706.     {
  3707.         
  3708.         $data json_decode(file_get_contents("php://input"));             
  3709.         if($data)
  3710.         {             
  3711.             $array = [];
  3712.             $aid   $data->aid;
  3713.             $list $entityManager->getRepository(VehicleAssignmentFuel::class)->findBy([                
  3714.                 'VehicleAssignment' => $aid         
  3715.             ]);                                   
  3716.             
  3717.             $total 0;
  3718.             foreach($list as $item)
  3719.             {                       
  3720.                 $total $total $item->getQuantity();               
  3721.                 $array[] = [
  3722.                     "quantity"   => $item->getQuantity(),                    
  3723.                     "id"         => $item->getVehicleAssignmentFuelId(),
  3724.                     "created_at" => $item->getCreatedAt()->format("Y-m-d H:i:s")
  3725.                 ];
  3726.             }
  3727.             
  3728.             return new JsonResponse(array('status' => 'success''data' => $array'total' => $total));
  3729.             
  3730.         }
  3731.         return new JsonResponse(array('status' => 'error'));
  3732.     }  
  3733.     /**
  3734.      * @Route("/get-agent-report-types", name="get-agent-report-types", methods={"GET", "POST"})
  3735.      */
  3736.     public function getReportTypes(Request $requestEntityManagerInterface $entityManager): Response
  3737.     {
  3738.         
  3739.         $data json_decode(file_get_contents("php://input"));             
  3740.         if($data)
  3741.         {             
  3742.             $objs $entityManager->getRepository(ShiftReportType::class)->findBy([                
  3743.                 'is_active' => 1          
  3744.             ]);    
  3745.             if($objs)
  3746.             {                    
  3747.                 $list = [];
  3748.                 foreach($objs as $item)
  3749.                 {                                      
  3750.                     $list[] = [
  3751.                         "name" => $item->getName(),
  3752.                         "id" => $item->getShiftReportTypeId()
  3753.                     ];
  3754.                 }
  3755.                 
  3756.                 return new JsonResponse(array('status' => 'success''data' => $list));
  3757.                
  3758.             }
  3759.         }
  3760.         return new JsonResponse(array('status' => 'error'));
  3761.     }  
  3762.     /**
  3763.      * @Route("/get-request-list", name="get-request-list", methods={"GET", "POST"})
  3764.      */
  3765.     public function getRequestList(Request $requestEntityManagerInterface $entityManager): Response
  3766.     {
  3767.         
  3768.         $data json_decode(file_get_contents("php://input"));             
  3769.         if($data)
  3770.         {           
  3771.             
  3772.             $eid $data->eid;  
  3773.             $objs $entityManager->getRepository(RequestParent::class)->findBy([                
  3774.                 'is_active' => 1,
  3775.                 'Employee'  => $eid           
  3776.             ], ['created_at' => 'DESC']);    
  3777.             if($objs)
  3778.             {                    
  3779.                 $list = [];
  3780.                 foreach($objs as $item)
  3781.                 {                 
  3782.                     
  3783.                     $color 'primary';
  3784.                     if($item->getRequestStatus()->getRequestStatusId() == 1)
  3785.                     {
  3786.                         $color 'primary';
  3787.                     } else if($item->getRequestStatus()->getRequestStatusId() == 2)
  3788.                     {
  3789.                         $color 'success';
  3790.                     } else if($item->getRequestStatus()->getRequestStatusId() == 3)
  3791.                     {
  3792.                         $color 'danger';
  3793.                     }
  3794.                     $list[] = [
  3795.                         "request_parent_id"  => $item->getRequestParentId(),
  3796.                         "request_type"       => $item->getRequestType()->getName(),
  3797.                         "request_status"     => $item->getRequestStatus()->getName(),
  3798.                         "comments"           => $item->getComments(),
  3799.                         "color"              => $color,
  3800.                         "created_at"         => $item->getCreatedAt()->format("Y-m-d H:i:s")
  3801.                     ];
  3802.                 }
  3803.                 
  3804.                 return new JsonResponse(array('status' => 'success''data' => $list));
  3805.                
  3806.             }
  3807.         }
  3808.         return new JsonResponse(array('status' => 'error'));
  3809.     }      
  3810.     /**
  3811.      * @Route("/agent-request-submit", name="ws_agent_request_submit", methods={"GET", "POST"})
  3812.      */
  3813.     public function agentRequestSubmit(Request $requestMailHelper $mailHelperEntityManagerInterface $entityManager): Response
  3814.     {
  3815.         
  3816.         $data json_decode(file_get_contents("php://input"));             
  3817.         if($data)
  3818.         {             
  3819.             $eid    $data->eid;
  3820.             $fields $data->fields;
  3821.             $rtid   $data->request_type_id;
  3822.             $requestTypeObj $entityManager->getRepository(RequestType::class)->findOneBy([                
  3823.                 'requestTypeId' => $rtid
  3824.             ]);
  3825.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  3826.                 'employeeId' => $eid
  3827.             ]);
  3828.             $requestStatusObj $entityManager->getRepository(RequestStatus::class)->findOneBy([                
  3829.                 'requestStatusId' => 1
  3830.             ]);
  3831.             //Si ya envio una solicitud igual y esta aún se encuentra pendiente, entonces se le debe indicar que no puede enviar otra
  3832.             $checkRequest $entityManager->getRepository(RequestParent::class)->findOneBy([
  3833.                 'requestType'   => $rtid,
  3834.                 'Employee'      => $eid,
  3835.                 'requestStatus' => 1,
  3836.                 'is_active'     => 1
  3837.             ]);            
  3838.             if($checkRequest)
  3839.             {
  3840.                 return new JsonResponse(array('status' => 'error''message' => "Ya tienes una solicitud pendiente de este tipo, no puedes enviar otra mientras la primera siga en proceso"));                                                
  3841.             }    
  3842.             $parent = new RequestParent();
  3843.             $parent->setRequestType($requestTypeObj);
  3844.             $parent->setEmployee($employeeObj);
  3845.             $parent->setRequestStatus($requestStatusObj);
  3846.             $parent->setRequestedFrom('bts_interno');
  3847.             $parent->setIsActive(1);                        
  3848.             $parent->setCreatedAt(new \DateTime());
  3849.             $entityManager->persist($parent);
  3850.             $entityManager->flush();
  3851.             
  3852.             if($parent)
  3853.             {                    
  3854.                 
  3855.                 $content "<p>El agente ".$employeeObj->getName()." ha realizado una solicitud.</p>";                                            
  3856.                 $content .= "<p><b>Fecha:</b> ".date('Y-m-d H:i:s')."</p>";
  3857.                 $content .= "<p><b>ID de solicitud:</b> #".$parent->getRequestParentId()."</p>";
  3858.                 $content .= "<p><b>Tipo:</b> ".$requestTypeObj->getName()."</p>";               
  3859.                 foreach($fields as $item)
  3860.                 {
  3861.                     $requestFieldObj $entityManager->getRepository(RequestField::class)->findOneBy([                
  3862.                         'requestFieldId' => $item->request_field_id
  3863.                     ]);
  3864.                     $answer = new RequestAnswer();
  3865.                     $answer->setRequestParent($parent);
  3866.                     $answer->setRequestType($requestTypeObj);
  3867.                     $answer->setEmployee($employeeObj);
  3868.                     $answer->setRequestField($requestFieldObj);
  3869.                     
  3870.                     $value "";
  3871.                     if($item->input_id == 4)
  3872.                     {
  3873.                         $requestFieldValueObj $entityManager->getRepository(RequestFieldValue::class)->findOneBy([                
  3874.                             'requestFieldValueId' => $item->value
  3875.                         ]);
  3876.                         $answer->setRequestFieldValue($requestFieldValueObj);
  3877.                         $answer->setValue($requestFieldValueObj->getValue());
  3878.                         $value $requestFieldValueObj->getValue();
  3879.                     } else {
  3880.                         $answer->setValue($item->value);
  3881.                         $value $item->value;
  3882.                     }
  3883.                     $content .= "<p><b>".$requestFieldObj->getName().":</b> ".$value."</p>";  
  3884.                     $answer->setRequestedFrom("bts_interno");
  3885.                     $answer->setEmployee($employeeObj);
  3886.                     $entityManager->persist($answer);
  3887.                     $entityManager->flush();
  3888.                 }
  3889.                  //--------------- ALERTA DE EMAILS ---------------//
  3890.                  $emailAlertObj $entityManager->getRepository(EmailAlert::class)->findOneBy([                
  3891.                     'emailAlertId' => 3
  3892.                 ]);
  3893.                 if($emailAlertObj->getEmail())
  3894.                 {
  3895.                         
  3896.                     $mailHelper::sendEmail($emailAlertObj->getEmail(), "Solicitud de agente: - ".$employeeObj->getName(), $content);
  3897.                 };
  3898.                 //--------------- ALERTA DE EMAILS ---------------//
  3899.                 
  3900.                 return new JsonResponse(array('status' => 'success''request_parent_id' => $parent->getRequestParentId()));                                                
  3901.                
  3902.             }
  3903.         }
  3904.         return new JsonResponse(array('status' => 'error'));
  3905.     }  
  3906.     
  3907.     
  3908.     
  3909.     
  3910.     /**     
  3911.      * @Route("/delete-report-file", name="/ws/delete-report-file"), methods={"GET", "POST"}) 
  3912.      */
  3913.     public function deleteReportFileAction(Request $requestEntityManagerInterface $entityManager) {
  3914.         $pictures = [];        
  3915.         $data json_decode(file_get_contents("php://input"));    
  3916.         if($data)
  3917.         {
  3918.             $fid   $data->fid;
  3919.             $seid  $data->seid;                                
  3920.             
  3921.         
  3922.             $picture $entityManager->getRepository(ShiftEventPicture::class)->findOneBy(array("shiftEventPictureId" => $fid));            
  3923.             @unlink("uploads/reports/".$seid."/".$picture->getPicturePath());
  3924.             
  3925.             $entityManager->remove($picture);
  3926.             $entityManager->flush();
  3927.                                     
  3928.             $pictures $this->getReportFiles($entityManager$seid);            
  3929.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));
  3930.         }    
  3931.         
  3932.         return new JsonResponse(array('status' => 'error' ));
  3933.     }      
  3934.     /**     
  3935.      * @Route("/delete-sanction-file", name="/ws/delete-sanction-file"), methods={"GET", "POST"}) 
  3936.      */
  3937.     public function deleteSanctionFileAction(Request $requestEntityManagerInterface $entityManager) {
  3938.         $pictures = [];        
  3939.         $data json_decode(file_get_contents("php://input"));    
  3940.         if($data)
  3941.         {
  3942.             $fid  $data->fid;
  3943.             $sid  $data->sid;                                
  3944.             
  3945.         
  3946.             $picture $entityManager->getRepository(SanctionPicture::class)->findOneBy(array("sanctionPictureId" => $fid));            
  3947.             @unlink("uploads/sanctions/".$sid."/".$picture->getPicturePath());
  3948.             
  3949.             $entityManager->remove($picture);
  3950.             $entityManager->flush();
  3951.                                     
  3952.             $pictures $this->getSanctionFiles($entityManager$sid);            
  3953.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));
  3954.         }    
  3955.         
  3956.         return new JsonResponse(array('status' => 'error' ));
  3957.     }      
  3958.     /**     
  3959.      * @Route("/delete-reaction-file", name="/ws/delete-reaction-file"), methods={"GET", "POST"}) 
  3960.      */
  3961.     public function deleteReactionFileAction(Request $requestEntityManagerInterface $entityManager) {
  3962.         $pictures = [];        
  3963.         $data json_decode(file_get_contents("php://input"));    
  3964.         if($data)
  3965.         {
  3966.             $fid  $data->fid;
  3967.             $rid  $data->rid;                                
  3968.             
  3969.         
  3970.             $picture $entityManager->getRepository(ReactionPicture::class)->findOneBy(array("reactionPictureId" => $fid));            
  3971.             @unlink("uploads/reactions/".$rid."/".$picture->getPicturePath());
  3972.             
  3973.             $entityManager->remove($picture);
  3974.             $entityManager->flush();
  3975.                                     
  3976.             $pictures $this->getReactionFiles($entityManager$rid);            
  3977.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));
  3978.         }    
  3979.         
  3980.         return new JsonResponse(array('status' => 'error' ));
  3981.     }    
  3982.     
  3983.     /**     
  3984.      * @Route("/delete-vassignment-file", name="/ws/delete-vassignment-file"), methods={"GET", "POST"}) 
  3985.      */
  3986.     public function deleteVassignmentFileAction(Request $requestEntityManagerInterface $entityManager) {
  3987.         $pictures = [];        
  3988.         $data json_decode(file_get_contents("php://input"));    
  3989.         if($data)
  3990.         {
  3991.             $fid  $data->fid;
  3992.             $vaid $data->vaid;    
  3993.             $type $data->type;                                        
  3994.         
  3995.             $picture $entityManager->getRepository(VehiclePicture::class)->findOneBy(array("vehiclePictureId" => $fid));            
  3996.             if($picture)
  3997.             {
  3998.                 @unlink("uploads/vehicle/".$picture->getPicturePath());
  3999.                 
  4000.                 $entityManager->remove($picture);
  4001.                 $entityManager->flush();
  4002.                                         
  4003.                 $pictures $this->getVehicleAssignmentFiles($entityManager$vaid$type);
  4004.                 return new JsonResponse(array('status' => 'success''pictures' => $pictures));
  4005.             }
  4006.         }    
  4007.         
  4008.         return new JsonResponse(array('status' => 'error' ));
  4009.     }        
  4010.     /**     
  4011.      * @Route("/delete-electronic-file", name="/ws/delete-electronic-file"), methods={"GET", "POST"}) 
  4012.      */
  4013.     public function deleteElectronicFileAction(Request $requestEntityManagerInterface $entityManager) {
  4014.         $pictures = [];        
  4015.         $data json_decode(file_get_contents("php://input"));    
  4016.         if($data)
  4017.         {
  4018.             $fid  $data->fid;
  4019.             $eid  $data->eid;                                
  4020.             
  4021.         
  4022.             $picture $entityManager->getRepository(ElectronicPicture::class)->findOneBy(array("electronicPictureId" => $fid));            
  4023.             @unlink("uploads/electronic/".$eid."/".$picture->getPicturePath());
  4024.             
  4025.             $entityManager->remove($picture);
  4026.             $entityManager->flush();
  4027.                                     
  4028.             $pictures $this->getElectronicFiles($entityManager$eid);            
  4029.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));
  4030.         }    
  4031.         
  4032.         return new JsonResponse(array('status' => 'error' ));
  4033.     }      
  4034.     /**     
  4035.      * @Route("/delete-ticket-file", name="/ws/delete-ticket-file"), methods={"GET", "POST"}) 
  4036.      */
  4037.     public function deleteTicketFileAction(Request $requestEntityManagerInterface $entityManager) {
  4038.         $pictures = [];        
  4039.         $data json_decode(file_get_contents("php://input"));    
  4040.         if($data)
  4041.         {
  4042.             $fid  $data->fid;
  4043.             $tid  $data->tid;                                
  4044.             
  4045.         
  4046.             $picture $entityManager->getRepository(TicketPicture::class)->findOneBy(array("ticketPictureId" => $fid));            
  4047.             @unlink("uploads/ticket/".$tid."/".$picture->getPicturePath());
  4048.             
  4049.             $entityManager->remove($picture);
  4050.             $entityManager->flush();
  4051.                                     
  4052.             $pictures $this->getTicketFiles($entityManager$tid);            
  4053.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));
  4054.         }    
  4055.         
  4056.         return new JsonResponse(array('status' => 'error' ));
  4057.     }          
  4058.     /**     
  4059.      * @Route("/delete-supervision-file", name="/ws/delete-supervision-file"), methods={"GET", "POST"}) 
  4060.      */
  4061.     public function deleteSupervisionFileAction(Request $requestEntityManagerInterface $entityManager) {
  4062.         $pictures = [];        
  4063.         $data json_decode(file_get_contents("php://input"));    
  4064.         if($data)
  4065.         {
  4066.             $fid     $data->fid;
  4067.             $supervision_id  $data->supervision_id;        
  4068.             $type    $data->comment_type;                        
  4069.             
  4070.         
  4071.             $picture $entityManager->getRepository(SupervisionPicture::class)->findOneBy(array("supervisionPictureId" => $fid));            
  4072.             @unlink("uploads/reports/s_".$supervision_id."/".$picture->getPicturePath());
  4073.             
  4074.             $entityManager->remove($picture);
  4075.             $entityManager->flush();
  4076.                                     
  4077.             $pictures $this->getSupervisionFiles($entityManager$supervision_id$type);            
  4078.             return new JsonResponse(array('status' => 'success''pictures' => $pictures));
  4079.         }    
  4080.         
  4081.         return new JsonResponse(array('status' => 'error' ));
  4082.     }   
  4083.     /**
  4084.      * @Route("/upload-file-sanction-app", name="/ws/upload-file-sanction-app"), methods={"GET", "POST"}) 
  4085.      */
  4086.     public function uploadFileSanctionAppAction(Request $requestEntityManagerInterface $entityManager) {
  4087.         $em $this->getDoctrine()->getManager();
  4088.         $data json_decode(file_get_contents("php://input"));
  4089.         $paths $this->getProjectPaths();
  4090.          
  4091.         if($data)
  4092.         {
  4093.             
  4094.             $ext    $data->ext;
  4095.             $base64 $data->hash;            
  4096.             $sid    $data->sid;            
  4097.                              
  4098.             $fileName md5(date("YmdHis")).".".$ext;
  4099.             $dir_path "uploads/sanctions/".$sid."/";
  4100.             $new      $dir_path.$fileName;
  4101.             //$newPath  = $paths["uploads_path"].$fileName;
  4102.             
  4103.             $obj $entityManager->getRepository(Sanction::class)->findOneBy(array("sanctionId" => $sid));                                                
  4104.             if($obj)
  4105.             {
  4106.                 if(!is_dir($dir_path))
  4107.                 {
  4108.                     mkdir($dir_path0777true);
  4109.                 }            
  4110.                 $decoded base64_decode($base64);
  4111.                 file_put_contents($new$decoded);                                    
  4112.                 
  4113.                 $newObj = new SanctionPicture();
  4114.                 $newObj->setSanction($obj);                     
  4115.                 $newObj->setPicturePath($fileName);
  4116.                 $newObj->setCreatedAt(new \DateTime());
  4117.                 $entityManager->persist($newObj);
  4118.                 $entityManager->flush();
  4119.                 $pictures $this->getSanctionFiles($entityManager$sid);        
  4120.                 
  4121.                            
  4122.                 return new JsonResponse(array('status' => 'success''pictures' => $pictures));                
  4123.             } 
  4124.             
  4125.     
  4126.         } else {
  4127.             return new JsonResponse(array('status' => 'error'));           
  4128.         }
  4129.  
  4130.          
  4131.     }
  4132.     /**
  4133.      * @Route("/upload-file-vapicture-app", name="/ws/upload-file-vapicture-app"), methods={"GET", "POST"}) 
  4134.      */
  4135.     public function uploadFileVapictureAppAction(Request $requestEntityManagerInterface $entityManager) {
  4136.         $em $this->getDoctrine()->getManager();
  4137.         $data json_decode(file_get_contents("php://input"));
  4138.         $paths $this->getProjectPaths();
  4139.          
  4140.         if($data)
  4141.         {
  4142.             
  4143.             $ext    $data->ext;
  4144.             $base64 $data->hash;            
  4145.             $vaid   $data->vaid;            
  4146.             $type   $data->type;
  4147.             $fileName md5(date("YmdHis")).".".$ext;
  4148.             $dir_path "uploads/vehicle/";
  4149.             $new      $dir_path.$fileName;
  4150.             if(!is_dir($dir_path))
  4151.             {
  4152.                 mkdir($dir_path0777true);
  4153.             }            
  4154.             $decoded base64_decode($base64);
  4155.             file_put_contents($new$decoded);      
  4156.             
  4157.             //FAIL TYPE --
  4158.             if($type == 'fail')
  4159.             {
  4160.                 $obj $entityManager->getRepository(VehicleAssignmentFail::class)->findOneBy(array(
  4161.                     "vehicleAssignmentFailId" => $vaid
  4162.                 ));                                                
  4163.                 if($obj)
  4164.                 {
  4165.                                 
  4166.                     $objPicture = new VehiclePicture();
  4167.                     $objPicture->setVehicleAssignmentFail($obj);                     
  4168.                     $objPicture->setPicturePath($fileName);
  4169.                     $objPicture->setType($type);
  4170.                     $objPicture->setCreatedAt(new \DateTime());
  4171.                     $entityManager->persist($objPicture);
  4172.                     $entityManager->flush();
  4173.                     $pictures $this->getVehicleAssignmentFiles($entityManager$vaid$type);
  4174.                                                             
  4175.                     return new JsonResponse(array('status' => 'success','pictures' => $pictures));                
  4176.                 } 
  4177.             } else {
  4178.                 
  4179.                     $obj $entityManager->getRepository(VehiclePanic::class)->findOneBy(array(
  4180.                         "vehiclePanicId" => $vaid
  4181.                     ));                                                
  4182.                 
  4183.                     if($obj)
  4184.                     {
  4185.                                     
  4186.                         $objPicture = new VehiclePicture();
  4187.                         $objPicture->setVehiclePanic($obj);                     
  4188.                         $objPicture->setPicturePath($fileName);
  4189.                         $objPicture->setType($type);
  4190.                         $objPicture->setCreatedAt(new \DateTime());
  4191.                         $entityManager->persist($objPicture);
  4192.                         $entityManager->flush();
  4193.                         $pictures $this->getVehicleAssignmentFiles($entityManager$vaid$type);
  4194.                                                                 
  4195.                         return new JsonResponse(array('status' => 'success','pictures' => $pictures));                
  4196.                     } 
  4197.                 
  4198.             }
  4199.             
  4200.     
  4201.         } else {
  4202.             return new JsonResponse(array('status' => 'error'));           
  4203.         }
  4204.  
  4205.          
  4206.     }
  4207.     /**
  4208.      * @Route("/upload-file-electronic-app", name="/ws/upload-file-electronic-app"), methods={"GET", "POST"}) 
  4209.      */
  4210.     public function uploadFileElectronicAppAction(Request $requestEntityManagerInterface $entityManager) {
  4211.         $em $this->getDoctrine()->getManager();
  4212.         $data json_decode(file_get_contents("php://input"));
  4213.         $paths $this->getProjectPaths();
  4214.          
  4215.         if($data)
  4216.         {
  4217.             
  4218.             $ext    $data->ext;
  4219.             $base64 $data->hash;            
  4220.             $eid    $data->eid;            
  4221.                              
  4222.             $fileName md5(date("YmdHis")).".".$ext;
  4223.             $dir_path "uploads/electronic/".$eid."/";
  4224.             $new      $dir_path.$fileName;
  4225.             //$newPath  = $paths["uploads_path"].$fileName;
  4226.             
  4227.             $obj $entityManager->getRepository(Electronic::class)->findOneBy(array("electronicId" => $eid));                                                
  4228.             if($obj)
  4229.             {
  4230.                 if(!is_dir($dir_path))
  4231.                 {
  4232.                     mkdir($dir_path0777true);
  4233.                 }            
  4234.                 $decoded base64_decode($base64);
  4235.                 file_put_contents($new$decoded);                                    
  4236.                 
  4237.                 $newObj = new ElectronicPicture();
  4238.                 $newObj->setElectronic($obj);                     
  4239.                 $newObj->setPicturePath($fileName);
  4240.                 $newObj->setCreatedAt(new \DateTime());
  4241.                 $entityManager->persist($newObj);
  4242.                 $entityManager->flush();
  4243.                 $pictures $this->getElectronicFiles($entityManager$eid);        
  4244.                 
  4245.                            
  4246.                 return new JsonResponse(array('status' => 'success''pictures' => $pictures));                
  4247.             } 
  4248.             
  4249.     
  4250.         } else {
  4251.             return new JsonResponse(array('status' => 'error'));           
  4252.         }
  4253.  
  4254.          
  4255.     }
  4256.     /**
  4257.      * @Route("/upload-file-ticket-app", name="/ws/upload-file-ticket-app"), methods={"GET", "POST"}) 
  4258.      */
  4259.     public function uploadFileTicketAppAction(Request $requestEntityManagerInterface $entityManager) {
  4260.         $em    $this->getDoctrine()->getManager();
  4261.         $data  json_decode(file_get_contents("php://input"));
  4262.         $paths $this->getProjectPaths();
  4263.          
  4264.         if($data)
  4265.         {
  4266.             
  4267.             $ext    $data->ext;
  4268.             $base64 $data->hash;            
  4269.             $tid    $data->tid;            
  4270.                              
  4271.             $fileName md5(date("YmdHis")).".".$ext;
  4272.             $dir_path "uploads/ticket/".$tid."/";
  4273.             $new      $dir_path.$fileName;
  4274.             //$newPath  = $paths["uploads_path"].$fileName;
  4275.             
  4276.             $obj $entityManager->getRepository(Ticket::class)->findOneBy(array("ticketId" => $tid));                                                
  4277.             if($obj)
  4278.             {
  4279.                 if(!is_dir($dir_path))
  4280.                 {
  4281.                     mkdir($dir_path0777true);
  4282.                 }            
  4283.                 $decoded base64_decode($base64);
  4284.                 file_put_contents($new$decoded);                                    
  4285.                 
  4286.                 $newObj = new TicketPicture();
  4287.                 $newObj->setTicket($obj);                     
  4288.                 $newObj->setPicturePath($fileName);
  4289.                 $newObj->setCreatedAt(new \DateTime());
  4290.                 $entityManager->persist($newObj);
  4291.                 $entityManager->flush();
  4292.                 $pictures $this->getTicketFiles($entityManager$tid);        
  4293.                 
  4294.                            
  4295.                 return new JsonResponse(array('status' => 'success''pictures' => $pictures));                
  4296.             } 
  4297.             
  4298.     
  4299.         } else {
  4300.             return new JsonResponse(array('status' => 'error'));           
  4301.         }
  4302.  
  4303.          
  4304.     }
  4305.     /**
  4306.      * @Route("/upload-file-reaction-app", name="/ws/upload-file-reaction-app"), methods={"GET", "POST"}) 
  4307.      */
  4308.     public function uploadFileReactionAppAction(Request $requestEntityManagerInterface $entityManager) {
  4309.         $em $this->getDoctrine()->getManager();
  4310.         $data json_decode(file_get_contents("php://input"));
  4311.         $paths $this->getProjectPaths();
  4312.          
  4313.         if($data)
  4314.         {
  4315.             
  4316.             $ext    $data->ext;
  4317.             $base64 $data->hash;            
  4318.             $rid    $data->rid;            
  4319.                              
  4320.             $fileName md5(date("YmdHis")).".".$ext;
  4321.             $dir_path "uploads/reactions/".$rid."/";
  4322.             $new      $dir_path.$fileName;
  4323.             //$newPath  = $paths["uploads_path"].$fileName;
  4324.             
  4325.             $obj $entityManager->getRepository(Reaction::class)->findOneBy(array("reactionId" => $rid));                                                
  4326.             if($obj)
  4327.             {
  4328.                 if(!is_dir($dir_path))
  4329.                 {
  4330.                     mkdir($dir_path0777true);
  4331.                 }            
  4332.                 $decoded base64_decode($base64);
  4333.                 file_put_contents($new$decoded);                                    
  4334.                 
  4335.                 $newObj = new ReactionPicture();
  4336.                 $newObj->setReaction($obj);                     
  4337.                 $newObj->setPicturePath($fileName);
  4338.                 $newObj->setCreatedAt(new \DateTime());
  4339.                 $entityManager->persist($newObj);
  4340.                 $entityManager->flush();
  4341.                 $pictures $this->getReactionFiles($entityManager$rid);        
  4342.                 
  4343.                            
  4344.                 return new JsonResponse(array('status' => 'success''pictures' => $pictures));                
  4345.             } 
  4346.             
  4347.     
  4348.         } else {
  4349.             return new JsonResponse(array('status' => 'error'));           
  4350.         }
  4351.  
  4352.          
  4353.     }
  4354.     /**
  4355.      * @Route("/upload-file-vehicle-app", name="/ws/upload-file-vehicle-app"), methods={"GET", "POST"}) 
  4356.      */
  4357.     public function uploadFileVehicleAppAction(Request $requestEntityManagerInterface $entityManager) {
  4358.        
  4359.         $em $this->getDoctrine()->getManager();
  4360.         $data json_decode(file_get_contents("php://input"));
  4361.         $paths $this->getProjectPaths();
  4362.          
  4363.         if($data)
  4364.         {
  4365.             
  4366.             $ext    $data->ext;
  4367.             $base64 $data->hash;            
  4368.             $aid    $data->assignment_id;    
  4369.             $number $data->number;        
  4370.                              
  4371.             $fileName md5(date("YmdHis")).".".$ext;
  4372.             $dir_path "uploads/vehicle/".$aid."/";
  4373.             $new      $dir_path.$fileName;
  4374.             //$newPath  = $paths["uploads_path"].$fileName;
  4375.             
  4376.             $obj $entityManager->getRepository(VehicleAssignment::class)->findOneBy(array("vehicleAssignmentId" => $aid));                                                
  4377.             if($obj)
  4378.             {
  4379.                 if(!is_dir($dir_path))
  4380.                 {
  4381.                     mkdir($dir_path0777true);
  4382.                 }            
  4383.                 $decoded base64_decode($base64);
  4384.                 file_put_contents($new$decoded);                                    
  4385.                 
  4386.                  //Si ya existe que elimine la foto que habia
  4387.                  $checkObj $entityManager->getRepository(VehicleAssignmentPicture::class)->findOneBy([
  4388.                     "VehicleAssignment" => $aid,
  4389.                     "picture_number"    => $number
  4390.                 ]);
  4391.                 if($checkObj)
  4392.                 {
  4393.                     //unlink picture
  4394.                     $file "uploads/vehicle/".$aid."/".$checkObj->getPicturePath();
  4395.                     if(file_exists($file))
  4396.                     {
  4397.                         unlink($file);
  4398.                     }
  4399.                     $entityManager->remove($checkObj);
  4400.                     $entityManager->flush();
  4401.                 }                                                
  4402.                              
  4403.                 $objPicture = new VehicleAssignmentPicture();
  4404.                 $objPicture->setVehicleAssignment($obj);                     
  4405.                 $objPicture->setPicturePath($fileName);
  4406.                 $objPicture->setPictureNumber($number);
  4407.                 $objPicture->setCreatedAt(new \DateTime());
  4408.                 $entityManager->persist($objPicture);
  4409.                 $entityManager->flush();
  4410.                 $pictures $this->getVehicleFiles($entityManager$aid);
  4411.                                       
  4412.                 return new JsonResponse(array('status' => 'success''pictures' => $pictures));    
  4413.             }             
  4414.     
  4415.         } 
  4416.         
  4417.         return new JsonResponse(array('status' => 'error'));                   
  4418.          
  4419.     }    
  4420.     /**
  4421.      * @Route("/upload-file-report-app", name="/ws/upload-file-report-app"), methods={"GET", "POST"}) 
  4422.      */
  4423.     public function uploadFileReportAppAction(Request $requestEntityManagerInterface $entityManager) {
  4424.         $em $this->getDoctrine()->getManager();
  4425.         $data json_decode(file_get_contents("php://input"));
  4426.         $paths $this->getProjectPaths();
  4427.          
  4428.         if($data)
  4429.         {
  4430.             
  4431.             $ext    $data->ext;
  4432.             $base64 $data->hash;            
  4433.             $seid   $data->seid;            
  4434.                              
  4435.             $fileName md5(date("YmdHis")).".".$ext;
  4436.             $dir_path "uploads/reports/".$seid."/";
  4437.             $new      $dir_path.$fileName;
  4438.             //$newPath  = $paths["uploads_path"].$fileName;
  4439.             
  4440.             $shiftEventObj $entityManager->getRepository(ShiftEvent::class)->findOneBy(array("shiftEventId" => $seid));                                                
  4441.             if($shiftEventObj)
  4442.             {
  4443.                 if(!is_dir($dir_path))
  4444.                 {
  4445.                     mkdir($dir_path0777true);
  4446.                 }            
  4447.                 $decoded base64_decode($base64);
  4448.                 file_put_contents($new$decoded);                                    
  4449.                 
  4450.                 $obj = new ShiftEventPicture();
  4451.                 $obj->setShiftEvent($shiftEventObj);                     
  4452.                 $obj->setPicturePath($fileName);
  4453.                 $obj->setCreatedAt(new \DateTime());
  4454.                 $entityManager->persist($obj);
  4455.                 $entityManager->flush();
  4456.                 $pictures $this->getReportFiles($entityManager$seid);        
  4457.                 
  4458.                            
  4459.                 return new JsonResponse(array('status' => 'success''pictures' => $pictures));                
  4460.             } 
  4461.             
  4462.     
  4463.         } else {
  4464.             return new JsonResponse(array('status' => 'error'));           
  4465.         }
  4466.  
  4467.          
  4468.     }
  4469.     /**
  4470.      * @Route("/upload-file-supervision-app", name="/ws/upload-file-supervision-app"), methods={"GET", "POST"}) 
  4471.      */
  4472.     public function uploadFileSupervisionAppAction(Request $requestEntityManagerInterface $entityManager) {
  4473.         $em $this->getDoctrine()->getManager();
  4474.         $data json_decode(file_get_contents("php://input"));
  4475.         $paths $this->getProjectPaths();
  4476.          
  4477.         if($data)
  4478.         {
  4479.             
  4480.             $ext    $data->ext;
  4481.             $base64 $data->hash;            
  4482.             $supervision_id   $data->supervision_id;       
  4483.             $commentType      $data->comment_type;     
  4484.                              
  4485.             $fileName md5(date("YmdHis")).".".$ext;
  4486.             $dir_path "uploads/reports/s_".$supervision_id."/";
  4487.             $new      $dir_path.$fileName;
  4488.             //$newPath  = $paths["uploads_path"].$fileName;
  4489.             
  4490.             $mainObj $entityManager->getRepository(Supervision::class)->findOneBy(array("supervisionId" => $supervision_id));                                                
  4491.             if($mainObj)
  4492.             {
  4493.                 if(!is_dir($dir_path))
  4494.                 {
  4495.                     mkdir($dir_path0777true);
  4496.                 }            
  4497.                 $decoded base64_decode($base64);
  4498.                 file_put_contents($new$decoded);                                    
  4499.                 
  4500.                 $obj = new SupervisionPicture();
  4501.                 $obj->setSupervision($mainObj);                     
  4502.                 $obj->setPicturePath($fileName);
  4503.                 $obj->setPictureType($commentType);
  4504.                 $obj->setCreatedAt(new \DateTime());
  4505.                 $entityManager->persist($obj);
  4506.                 $entityManager->flush();
  4507.                 $pictures $this->getSupervisionFiles($entityManager$supervision_id$commentType);        
  4508.                 
  4509.                            
  4510.                 return new JsonResponse(array('status' => 'success''pictures' => $pictures));                
  4511.             } 
  4512.             
  4513.     
  4514.         } else {
  4515.             return new JsonResponse(array('status' => 'error'));           
  4516.         }
  4517.  
  4518.          
  4519.     }    
  4520.     /**
  4521.      * @Route("/upload-file-report-browser", name="/ws/upload-file-report-browser"), methods={"GET", "POST"}) 
  4522.      */
  4523.     public function uploadFileReportBrowserAction(Request $requestEntityManagerInterface $entityManager)
  4524.     {
  4525.                         
  4526.         $uploadfile     $_FILES['file']['name'];
  4527.         $uploadfilename $_FILES['file']['tmp_name'];
  4528.         $array          = array();
  4529.        
  4530.         if($uploadfile)
  4531.         {
  4532.             
  4533.              $ext   $_POST['ext'];
  4534.              $seid  $_POST['seid'];            
  4535.              
  4536.              $fileName md5(date("YmdHis")).".".$ext;
  4537.              $dir_path "uploads/reports/".$seid."/";
  4538.              $new      $dir_path.$fileName;             
  4539.             if(!is_dir($dir_path))
  4540.             {
  4541.                 mkdir($dir_path0777true);
  4542.             }
  4543.             
  4544.             if(move_uploaded_file($uploadfilename$new))
  4545.             {
  4546.                 $shiftEventObj $entityManager->getRepository(ShiftEvent::class)->findOneBy(array("shiftEventId" => $seid));                                                
  4547.                 if($shiftEventObj)
  4548.                 {
  4549.                                  
  4550.                     $obj = new ShiftEventPicture();
  4551.                     $obj->setShiftEvent($shiftEventObj);                     
  4552.                     $obj->setPicturePath($fileName);
  4553.                     $obj->setCreatedAt(new \DateTime());
  4554.                     $entityManager->persist($obj);
  4555.                     $entityManager->flush();
  4556.                     $pictures $this->getReportFiles($entityManager$seid);
  4557.                                                             
  4558.                     return new JsonResponse(array('status' => 'success','pictures' => $pictures));                
  4559.                 } 
  4560.                          
  4561.             }
  4562.          
  4563.             return new JsonResponse(array('status' => 'error'));        
  4564.         }  
  4565.     }
  4566.     /**
  4567.      * @Route("/upload-file-electronic-browser", name="/ws/upload-file-electronic-browser"), methods={"GET", "POST"}) 
  4568.      */
  4569.     public function uploadFileElectronicBrowserAction(Request $requestEntityManagerInterface $entityManager)
  4570.     {
  4571.                         
  4572.         $uploadfile     $_FILES['file']['name'];
  4573.         $uploadfilename $_FILES['file']['tmp_name'];
  4574.         $array          = array();
  4575.        
  4576.         if($uploadfile)
  4577.         {
  4578.             
  4579.              $ext   $_POST['ext'];
  4580.              $eid   $_POST['eid'];            
  4581.              
  4582.              $fileName md5(date("YmdHis")).".".$ext;
  4583.              $dir_path "uploads/electronic/".$eid."/";
  4584.              $new      $dir_path.$fileName;             
  4585.             if(!is_dir($dir_path))
  4586.             {
  4587.                 mkdir($dir_path0777true);
  4588.             }
  4589.             
  4590.             if(move_uploaded_file($uploadfilename$new))
  4591.             {
  4592.                 $obj $entityManager->getRepository(Electronic::class)->findOneBy(array("electronicId" => $eid));                                                
  4593.                 if($obj)
  4594.                 {
  4595.                                  
  4596.                     $objPicture = new ElectronicPicture();
  4597.                     $objPicture->setElectronic($obj);                     
  4598.                     $objPicture->setPicturePath($fileName);
  4599.                     $objPicture->setCreatedAt(new \DateTime());
  4600.                     $entityManager->persist($objPicture);
  4601.                     $entityManager->flush();
  4602.                     $pictures $this->getElectronicFiles($entityManager$eid);
  4603.                                                             
  4604.                     return new JsonResponse(array('status' => 'success','pictures' => $pictures));                
  4605.                 } 
  4606.                          
  4607.             }
  4608.          
  4609.             return new JsonResponse(array('status' => 'error'));        
  4610.         }  
  4611.     }    
  4612.     /**
  4613.      * @Route("/upload-file-ticket-browser", name="/ws/upload-file-ticket-browser"), methods={"GET", "POST"}) 
  4614.      */
  4615.     public function uploadFileTicketBrowserAction(Request $requestEntityManagerInterface $entityManager)
  4616.     {
  4617.                         
  4618.         $uploadfile     $_FILES['file']['name'];
  4619.         $uploadfilename $_FILES['file']['tmp_name'];
  4620.         $array          = array();
  4621.        
  4622.         if($uploadfile)
  4623.         {
  4624.             
  4625.              $ext   $_POST['ext'];
  4626.              $tid   $_POST['tid'];            
  4627.              
  4628.              $fileName md5(date("YmdHis")).".".$ext;
  4629.              $dir_path "uploads/ticket/".$tid."/";
  4630.              $new      $dir_path.$fileName;             
  4631.             if(!is_dir($dir_path))
  4632.             {
  4633.                 mkdir($dir_path0777true);
  4634.             }
  4635.             
  4636.             if(move_uploaded_file($uploadfilename$new))
  4637.             {
  4638.                 $obj $entityManager->getRepository(Ticket::class)->findOneBy(array("ticketId" => $tid));                                                
  4639.                 if($obj)
  4640.                 {
  4641.                                  
  4642.                     $objPicture = new TicketPicture();
  4643.                     $objPicture->setTicket($obj);                     
  4644.                     $objPicture->setPicturePath($fileName);
  4645.                     $objPicture->setCreatedAt(new \DateTime());
  4646.                     $entityManager->persist($objPicture);
  4647.                     $entityManager->flush();
  4648.                     $pictures $this->getTicketFiles($entityManager$tid);
  4649.                                                             
  4650.                     return new JsonResponse(array('status' => 'success','pictures' => $pictures));                
  4651.                 } 
  4652.                          
  4653.             }
  4654.          
  4655.             return new JsonResponse(array('status' => 'error'));        
  4656.         }  
  4657.     }        
  4658.     /**
  4659.      * @Route("/upload-file-vehicle-browser", name="/ws/upload-file-vehicle-browser"), methods={"GET", "POST"}) 
  4660.      */
  4661.     public function uploadFileVehicleBrowserAction(Request $requestEntityManagerInterface $entityManager)
  4662.     {
  4663.                         
  4664.         $uploadfile     $_FILES['file']['name'];
  4665.         $uploadfilename $_FILES['file']['tmp_name'];
  4666.         $array          = array();
  4667.        
  4668.         if($uploadfile)
  4669.         {
  4670.             
  4671.              $ext    $_POST['ext'];
  4672.              $aid    $_POST['aid']; //Assignment Id
  4673.              $number $_POST['number'];
  4674.              
  4675.              $fileName md5(date("YmdHis")).".".$ext;
  4676.              $dir_path "uploads/vehicle/".$aid."/";
  4677.              $new      $dir_path.$fileName;             
  4678.             if(!is_dir($dir_path))
  4679.             {
  4680.                 mkdir($dir_path0777true);
  4681.             }
  4682.             
  4683.             if(move_uploaded_file($uploadfilename$new))
  4684.             {
  4685.                 $obj $entityManager->getRepository(VehicleAssignment::class)->findOneBy(array("vehicleAssignmentId" => $aid));                                                
  4686.                 if($obj)
  4687.                 {
  4688.                     //Si ya existe que elimine la foto que habia
  4689.                     $checkObj $entityManager->getRepository(VehicleAssignmentPicture::class)->findOneBy([
  4690.                         "VehicleAssignment" => $aid,
  4691.                         "picture_number"    => $number
  4692.                     ]);
  4693.                     if($checkObj)
  4694.                     {
  4695.                         //unlink picture
  4696.                         $file "uploads/vehicle/".$aid."/".$checkObj->getPicturePath();
  4697.                         if(file_exists($file))
  4698.                         {
  4699.                             unlink($file);
  4700.                         }
  4701.                         $entityManager->remove($checkObj);
  4702.                         $entityManager->flush();
  4703.                     }                                                
  4704.                                  
  4705.                     $objPicture = new VehicleAssignmentPicture();
  4706.                     $objPicture->setVehicleAssignment($obj);                     
  4707.                     $objPicture->setPicturePath($fileName);
  4708.                     $objPicture->setPictureNumber($number);
  4709.                     $objPicture->setCreatedAt(new \DateTime());
  4710.                     $entityManager->persist($objPicture);
  4711.                     $entityManager->flush();
  4712.                     $pictures $this->getVehicleFiles($entityManager$aid);
  4713.                                           
  4714.                     return new JsonResponse(array('status' => 'success''pictures' => $pictures));                
  4715.                 } 
  4716.                          
  4717.             }
  4718.          
  4719.             return new JsonResponse(array('status' => 'error'));        
  4720.         }  
  4721.     }   
  4722.     /**
  4723.      * @Route("/upload-file-vehicle-fuel-browser", name="/ws/upload-file-vehicle-fuel-browser"), methods={"GET", "POST"}) 
  4724.      */
  4725.     public function uploadFileVehicleFuelBrowserAction(Request $requestEntityManagerInterface $entityManager)
  4726.     {
  4727.                         
  4728.         $uploadfile      $_FILES['file']['name'];
  4729.         $uploadfilename  $_FILES['file']['tmp_name'];
  4730.         $uploadfile2     $_FILES['file2']['name'];
  4731.         $uploadfilename2 $_FILES['file2']['tmp_name'];
  4732.         $array          = array();                           
  4733.         if($uploadfile)
  4734.         {
  4735.             
  4736.              $ext      $_POST['ext'];
  4737.              $extTwo   $_POST['extTwo'];
  4738.              $aid      $_POST['aid']; //Assignment Id             
  4739.              $quantity $_POST['quantity'];
  4740.              $mileage  $_POST['mileage'];
  4741.              $type     $_POST['type'];
  4742.              $fileName md5(date("YmdHis"))."_fuel.".$ext;
  4743.              $dir_path "uploads/vehicle/".$aid."/";
  4744.              $new      $dir_path.$fileName;             
  4745.             if(!is_dir($dir_path))
  4746.             {
  4747.                 mkdir($dir_path0777true);
  4748.             }
  4749.             $fileName2 md5(date("YmdHis"))."_fuel_2.".$extTwo;            
  4750.             $newTwo    $dir_path.$fileName2;             
  4751.             if(!is_dir($dir_path))
  4752.             {
  4753.                 mkdir($dir_path0777true);
  4754.             }
  4755.             
  4756.             if(move_uploaded_file($uploadfilename$new))
  4757.             {
  4758.                 if(move_uploaded_file($uploadfilename2$newTwo))
  4759.                 {
  4760.                     $obj $entityManager->getRepository(VehicleAssignment::class)->findOneBy(array("vehicleAssignmentId" => $aid));                                                
  4761.                     if($obj)
  4762.                     {
  4763.                         //Si ya existe que elimine la foto que habia
  4764.                         /*$checkObj = $entityManager->getRepository(VehicleAssignmentFuel::class)->findOneBy([
  4765.                             "VehicleAssignment" => $aid                        
  4766.                         ]);
  4767.                         if($checkObj)
  4768.                         {
  4769.                             //unlink picture
  4770.                             $file = "uploads/vehicle/".$aid."/".$checkObj->getPicturePath();
  4771.                             if(file_exists($file))
  4772.                             {
  4773.                                 unlink($file);
  4774.                             }
  4775.                             $entityManager->remove($checkObj);
  4776.                             $entityManager->flush();
  4777.                         }*/                                            
  4778.                                                        
  4779.                         $objPicture = new VehicleAssignmentFuel();
  4780.                         $objPicture->setVehicleAssignment($obj);                     
  4781.                         $objPicture->setPicturePath($fileName);
  4782.                         $objPicture->setOdometerPath($fileName2);
  4783.                         $objPicture->setQuantity($quantity);
  4784.                         $objPicture->setMileage($mileage);
  4785.                         $objPicture->setRecordType($type);
  4786.                         $objPicture->setCreatedAt(new \DateTime());
  4787.                         $entityManager->persist($objPicture);
  4788.                         $entityManager->flush();
  4789.                         $pictures $this->getVehicleFilesFuel($entityManager$aid);
  4790.                                             
  4791.                         return new JsonResponse(array('status' => 'success''pictures' => $pictures));                
  4792.                     } 
  4793.                 }
  4794.                          
  4795.             }
  4796.          
  4797.             return new JsonResponse(array('status' => 'error'));        
  4798.         }  
  4799.     }  
  4800.     /**
  4801.      * @Route("/upload-file-vehicle-supervision-browser", name="/ws/upload-file-vehicle-supervision-browser"), methods={"GET", "POST"}) 
  4802.      */
  4803.     public function uploadFileVehicleSupervisionBrowserAction(Request $requestEntityManagerInterface $entityManager)
  4804.     {
  4805.         //return new JsonResponse(array('status' => 'success', 'POST' => $_POST, 'FILES' => $_FILES));                
  4806.         if(isset($_POST) or isset($_FILES))
  4807.         {
  4808.             $templateId  $_POST['templateId'];
  4809.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  4810.                 "employeeId" => $_POST['eid']
  4811.             ]);
  4812.             $templateObj $entityManager->getRepository(DocumentTemplate::class)->findOneBy([
  4813.                 "documentTemplateId" => $templateId
  4814.             ]);
  4815.             $documentParent = new DocumentParent();
  4816.             $documentParent->setDocumentTemplate($templateObj);
  4817.             $documentParent->setIsActive(1);
  4818.             $documentParent->setCreatedAt(new \DateTime());
  4819.             $documentParent->setCreatedByEmployeeId($employeeObj);
  4820.             $entityManager->persist($documentParent);
  4821.             $entityManager->flush();
  4822.             if($templateObj)
  4823.             {              
  4824.                 foreach($_POST as $key => $post)
  4825.                 {                     
  4826.                     $fieldObj $entityManager->getRepository(DocumentTemplateField::class)->findOneBy([
  4827.                         "documentTemplateFieldId" => $key
  4828.                     ]);   
  4829.                     if($fieldObj)
  4830.                     {
  4831.                         
  4832.                         $document = new Document();
  4833.                         $document->setDocumentParent($documentParent);
  4834.                         $document->setDocumentTemplateGroup($fieldObj->getDocumentTemplateGroup());
  4835.                         $document->setDocumentTemplateField($fieldObj);
  4836.                         $document->setLabel($fieldObj->getName());
  4837.                         
  4838.                         if($fieldObj->getFieldType() == 'opcion_multiple')
  4839.                         {
  4840.                             $fieldValueObj $entityManager->getRepository(DocumentTemplateFieldValue::class)->findOneBy([
  4841.                                 "documentTemplateFieldValueId" => $post
  4842.                             ]); 
  4843.                             if($fieldValueObj)
  4844.                             {
  4845.                                 $document->setInputValue($fieldValueObj->getValueName());                            
  4846.                             }
  4847.                         } else {
  4848.                             if($fieldObj->getFieldType() == 'fecha')
  4849.                             {
  4850.                                 $document->setInputValue(substr($post,0,10));
  4851.                             } else {
  4852.                                 $document->setInputValue($post);
  4853.                             }                            
  4854.                         }
  4855.                         $document->setCreatedAt(new \DateTime());
  4856.                         $document->setCreatedByEmployeeId($employeeObj);
  4857.                         $entityManager->persist($document);
  4858.                         $entityManager->flush();
  4859.                     }
  4860.                 }
  4861.                 foreach($_FILES as $key => $file)
  4862.                 {
  4863.                     
  4864.                     $fieldObj $entityManager->getRepository(DocumentTemplateField::class)->findOneBy([
  4865.                         "documentTemplateFieldId" => $key
  4866.                     ]);   
  4867.                     if($fieldObj)
  4868.                     {
  4869.                         
  4870.                         $arr      explode(".",$file['name']);
  4871.                         $fileName md5(date("YmdHis"))."_supervision.".$arr[1];
  4872.                         $dir_path "uploads/vehicle/supervision/";
  4873.                         $new      $dir_path.$fileName;             
  4874.                               
  4875.                         if(!is_dir($dir_path))
  4876.                         {
  4877.                             mkdir($dir_path0777true);
  4878.                         }
  4879.                         if(move_uploaded_file($file['tmp_name'], $new))
  4880.                         {
  4881.                             
  4882.                             $document = new Document();
  4883.                             $document->setDocumentParent($documentParent);
  4884.                             $document->setDocumentTemplateGroup($fieldObj->getDocumentTemplateGroup());
  4885.                             $document->setDocumentTemplateField($fieldObj);
  4886.                             $document->setLabel($fieldObj->getName());
  4887.                             $document->setInputValue($new);
  4888.                             $document->setCreatedAt(new \DateTime());
  4889.                             $entityManager->persist($document);
  4890.                             $entityManager->flush();
  4891.                         }
  4892.                     }
  4893.                 }
  4894.                 return new JsonResponse(array('status' => 'success'));
  4895.             }
  4896.         }
  4897.             
  4898.                                     
  4899.         return new JsonResponse(array('status' => 'error'));
  4900.     }      
  4901.     
  4902.     
  4903.     /**
  4904.      * @Route("/upload-file-refuel-app", name="/ws/upload-file-refuel-app"), methods={"GET", "POST"}) 
  4905.      */
  4906.     public function uploadFileRefuelAppAction(Request $requestHelperService $helperServiceEntityManagerInterface $entityManager) {
  4907.         $em $this->getDoctrine()->getManager();
  4908.         $data json_decode(file_get_contents("php://input"));
  4909.         $paths $this->getProjectPaths();
  4910.          
  4911.         if($data)
  4912.         {
  4913.             
  4914.             $file     $data->file;            
  4915.             $ext      $data->ext;                        
  4916.             $file2    $data->file2;            
  4917.             $ext2     $data->ext2;            
  4918.             $quantity $data->quantity;
  4919.             $plate    $data->plate;
  4920.             $mileage  $data->mileage;
  4921.             $eid      $data->eid;
  4922.             $externalId $data->external_id;
  4923.             $dir_path "uploads/vehicle/";
  4924.             $fileName md5(date("YmdHis"))."_refuel.".$ext;            
  4925.             $new      $dir_path.$fileName;             
  4926.             $fileName2 md5(date("YmdHis"))."_2_refuel.".$ext2;            
  4927.             $new2      $dir_path.$fileName2;             
  4928.             //$newPath  = $paths["uploads_path"].$fileName;
  4929.             
  4930.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  4931.                 "employeeId" => $eid
  4932.             ]);
  4933.            
  4934.             if($employeeObj)
  4935.             {
  4936.                  // ----------------------------- MILEAGE CHECK ----------------------------
  4937.                 // ------------------------------------------------------------------------
  4938.                 $arrayInfo    $this->getLatestMileage($helperService$entityManager$plate);
  4939.                 $mileageCheck $arrayInfo['mileageCheck'];
  4940.                 $checked      $arrayInfo['checked'];
  4941.                 // ------------------------------------------------------------------------
  4942.                 // ----------------------------- MILEAGE CHECK ----------------------------
  4943.                 
  4944.                 if($mileage $mileageCheck)
  4945.                 {
  4946.                     if(!is_dir($dir_path))
  4947.                     {
  4948.                         mkdir($dir_path0777true);
  4949.                     }            
  4950.     
  4951.                     $decoded base64_decode($file);
  4952.                     file_put_contents($new$decoded);                                    
  4953.     
  4954.                     $decoded2 base64_decode($file2);
  4955.                     file_put_contents($new2$decoded2);                                                                            
  4956.                 
  4957.                     $objPicture = new Refuel();
  4958.                     $objPicture->setExternalVehicleId($externalId);                     
  4959.                     $objPicture->setPicturePath($fileName);
  4960.                     $objPicture->setFuelPicturePath($fileName2);
  4961.                     $objPicture->setPlateNumber($plate);
  4962.                     $objPicture->setMileage($mileage);
  4963.                     $objPicture->setQuantity($quantity);
  4964.                     $objPicture->setCreatedAt(new \DateTime());
  4965.                     $objPicture->setCreatedByEmployeeId($employeeObj);
  4966.                     $entityManager->persist($objPicture);
  4967.                     $entityManager->flush();                
  4968.                                             
  4969.                     return new JsonResponse(array('status' => 'success'));        
  4970.                 
  4971.                 }
  4972.                 return new JsonResponse(array('status' => 'error''message' => "El kilometraje ingresado es menor al Ãºltimo registrado ($mileageCheck) en $checked. Por favor verifique e intente nuevamente."));
  4973.                        
  4974.             } 
  4975.             
  4976.     
  4977.         } else {
  4978.             return new JsonResponse(array('status' => 'error'));           
  4979.         }
  4980.  
  4981.          
  4982.     }
  4983.     /**
  4984.      * @Route("/upload-file-fail-app", name="/ws/upload-file-fail-app"), methods={"GET", "POST"}) 
  4985.      */
  4986.     public function uploadFileFailAppAction(Request $requestHelperService $helperServiceEntityManagerInterface $entityManager) {
  4987.         $em $this->getDoctrine()->getManager();
  4988.         $data json_decode(file_get_contents("php://input"));
  4989.         $paths $this->getProjectPaths();
  4990.          
  4991.         if($data)
  4992.         {
  4993.             
  4994.             $file     $data->file;            
  4995.             $ext      $data->ext;                                          
  4996.             $description $data->description;
  4997.             $plate       $data->plate;
  4998.             $vaid        $data->vaid;
  4999.             $eid         $data->eid;
  5000.             $externalId  $data->external_id;
  5001.             $dir_path "uploads/vehicle/";
  5002.             $fileName md5(date("YmdHis"))."_refuel.".$ext;            
  5003.             $new      $dir_path.$fileName;             
  5004.             
  5005.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  5006.                 "employeeId" => $eid
  5007.             ]);
  5008.            
  5009.             if($employeeObj)
  5010.             {
  5011.                     if(!is_dir($dir_path))
  5012.                     {
  5013.                         mkdir($dir_path0777true);
  5014.                     }            
  5015.     
  5016.                     $decoded base64_decode($file);
  5017.                     file_put_contents($new$decoded);                                    
  5018.     
  5019.                   
  5020.                     $assignmentObj $entityManager->getRepository(VehicleAssignment::class)->findOneBy([
  5021.                         "vehicleAssignmentId" => $vaid
  5022.                     ]);
  5023.                                                                             
  5024.                     $objPicture = new VehicleAssignmentFail();
  5025.                     $objPicture->setExternalId($externalId);                     
  5026.                     $objPicture->setPicturePath($fileName);                    
  5027.                     $objPicture->setPlateNumber($plate);
  5028.                     $objPicture->setDescription($description);
  5029.                     $objPicture->setVehicleAssignment($assignmentObj);
  5030.                     $objPicture->setCreatedAt(new \DateTime());
  5031.                     $objPicture->setCreatedByEmployeeId($employeeObj);
  5032.                     $entityManager->persist($objPicture);
  5033.                     $entityManager->flush();                                                                                                        
  5034.                     
  5035.                                             
  5036.                     return new JsonResponse(array('status' => 'success'));                                                
  5037.                        
  5038.             } 
  5039.                 
  5040.         } 
  5041.         return new JsonResponse(array('status' => 'error'));            
  5042.          
  5043.     }    
  5044.     /**
  5045.      * @Route("/upload-file-refuel-browser", name="/ws/upload-file-refuel-browser"), methods={"GET", "POST"}) 
  5046.      */
  5047.     public function uploadFileRefuelBrowserAction(Request $requestEntityManagerInterface $entityManagerHelperService $helperService)
  5048.     {
  5049.         $uploadfile     $_FILES['file']['name'];
  5050.         $uploadfilename $_FILES['file']['tmp_name'];
  5051.         $uploadfileTwo     $_FILES['file2']['name'];
  5052.         $uploadfilenameTwo $_FILES['file2']['tmp_name'];
  5053.         $array          = array();
  5054.        
  5055.         if($uploadfile && $uploadfilenameTwo)
  5056.         {
  5057.             
  5058.              $ext        $_POST['ext'];
  5059.              $ext2       $_POST['ext2'];
  5060.              $externalId $_POST['external_id']; //Assignment Id             
  5061.              $quantity   $_POST['quantity'];
  5062.              $plate      $_POST['plate'];
  5063.              $mileage    $_POST['mileage'];
  5064.              $eid        $_POST['eid'];
  5065.              $lat        $_POST['lat'];
  5066.              $lng        $_POST['lng'];
  5067.              $dir_path "uploads/vehicle/";
  5068.              $fileName md5(date("YmdHis"))."_refuel.".$ext;            
  5069.              $new      $dir_path.$fileName;             
  5070.              $fileName2 md5(date("YmdHis"))."_2_refuel.".$ext2;            
  5071.              $new2      $dir_path.$fileName2;             
  5072.             if(!is_dir($dir_path))
  5073.             {
  5074.                 mkdir($dir_path0777true);
  5075.             }
  5076.             
  5077.             if(move_uploaded_file($uploadfilename$new))
  5078.             {
  5079.                 if(move_uploaded_file($uploadfilenameTwo$new2))
  5080.                 {
  5081.                 
  5082.                     //Si ya existe que elimine la foto que habia
  5083.                     /*$checkObj = $entityManager->getRepository(VehicleAssignmentFuel::class)->findOneBy([
  5084.                         "VehicleAssignment" => $aid                        
  5085.                     ]);
  5086.                     if($checkObj)
  5087.                     {
  5088.                         //unlink picture
  5089.                         $file = "uploads/vehicle/".$aid."/".$checkObj->getPicturePath();
  5090.                         if(file_exists($file))
  5091.                         {
  5092.                             unlink($file);
  5093.                         }
  5094.                         $entityManager->remove($checkObj);
  5095.                         $entityManager->flush();
  5096.                     }*/                                            
  5097.                                 
  5098.                     $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  5099.                         "employeeId" => $eid
  5100.                     ]);
  5101.                     // ----------------------------- MILEAGE CHECK ----------------------------
  5102.                     // ------------------------------------------------------------------------
  5103.                     $arrayInfo    $this->getLatestMileage($helperService$entityManager$plate);
  5104.                     $mileageCheck $arrayInfo['mileageCheck'];
  5105.                     $checked      $arrayInfo['checked'];
  5106.                     // ------------------------------------------------------------------------
  5107.                     // ----------------------------- MILEAGE CHECK ----------------------------
  5108.                     if($mileage $mileageCheck)
  5109.                     {
  5110.                     
  5111.                         $objPicture = new Refuel();
  5112.                         $objPicture->setExternalVehicleId($externalId);                     
  5113.                         $objPicture->setPicturePath($fileName);
  5114.                         $objPicture->setFuelPicturePath($fileName2);
  5115.                         $objPicture->setPlateNumber($plate);
  5116.                         $objPicture->setMileage($mileage);
  5117.                         $objPicture->setQuantity($quantity);
  5118.                         $objPicture->setLat($lat);
  5119.                         $objPicture->setLng($lng);
  5120.                         $objPicture->setCreatedAt(new \DateTime());
  5121.                         $objPicture->setCreatedByEmployeeId($employeeObj);
  5122.                         $entityManager->persist($objPicture);
  5123.                         $entityManager->flush();                
  5124.                                                 
  5125.                         return new JsonResponse(array('status' => 'success'));        
  5126.                     
  5127.                     }
  5128.                     return new JsonResponse(array('status' => 'error''message' => "El kilometraje ingresado es menor al Ãºltimo registrado ($mileageCheck) en $checked. Por favor verifique e intente nuevamente."));
  5129.                 }         
  5130.             }
  5131.          
  5132.             return new JsonResponse(array('status' => 'error''message' => 'No se puede realizar la operación en este momento, por favor intente más tarde.'));        
  5133.         }  
  5134.     }   
  5135.     
  5136.     
  5137.     /**
  5138.      * @Route("/upload-file-fail-browser", name="/ws/upload-file-fail-browser"), methods={"GET", "POST"}) 
  5139.      */
  5140.     public function uploadFileFailBrowserAction(Request $requestEntityManagerInterface $entityManagerHelperService $helperService)
  5141.     {
  5142.         $uploadfile     $_FILES['file']['name'];
  5143.         $uploadfilename $_FILES['file']['tmp_name'];        
  5144.         $array          = array();
  5145.        
  5146.         if($uploadfile)
  5147.         {
  5148.             
  5149.              $ext         $_POST['ext'];             
  5150.              $externalId  $_POST['external_id'];             
  5151.              $description $_POST['description'];
  5152.              $plate       $_POST['plate'];
  5153.              $vaid        $_POST['vaid'];
  5154.              $eid         $_POST['eid'];
  5155.              $dir_path "uploads/vehicle/";
  5156.              $fileName md5(date("YmdHis"))."_refuel.".$ext;            
  5157.              $new      $dir_path.$fileName;                          
  5158.             if(!is_dir($dir_path))
  5159.             {
  5160.                 mkdir($dir_path0777true);
  5161.             }
  5162.             
  5163.             if(move_uploaded_file($uploadfilename$new))
  5164.             {
  5165.                 $assignmentObj $entityManager->getRepository(VehicleAssignment::class)->findOneBy([
  5166.                     "vehicleAssignmentId" => $vaid
  5167.                 ]);
  5168.                                                         
  5169.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  5170.                     "employeeId" => $eid
  5171.                 ]);
  5172.                 if($employeeObj)
  5173.                 {
  5174.                 
  5175.                     $objPicture = new VehicleAssignmentFail();
  5176.                     $objPicture->setExternalId($externalId);                     
  5177.                     $objPicture->setPicturePath($fileName);                    
  5178.                     $objPicture->setPlateNumber($plate);
  5179.                     $objPicture->setDescription($description);
  5180.                     $objPicture->setVehicleAssignment($assignmentObj);
  5181.                     $objPicture->setCreatedAt(new \DateTime());
  5182.                     $objPicture->setCreatedByEmployeeId($employeeObj);
  5183.                     $entityManager->persist($objPicture);
  5184.                     $entityManager->flush();                
  5185.                                             
  5186.                     return new JsonResponse(array('status' => 'success'));        
  5187.                 
  5188.                 }                
  5189.                     
  5190.             }
  5191.          
  5192.             return new JsonResponse(array('status' => 'error''message' => 'No se puede realizar la operación en este momento, por favor intente más tarde.'));        
  5193.         }  
  5194.     }   
  5195.     
  5196.     
  5197.     /**
  5198.      * @Route("/vehicle-panic-create", name="/ws/vehicle-panic-create"), methods={"GET", "POST"}) 
  5199.      */
  5200.     public function vehiclePanicCreateAction(Request $requestEntityManagerInterface $entityManagerHelperService $helperService)
  5201.     {
  5202.         $pictures = [];        
  5203.         $data json_decode(file_get_contents("php://input"));    
  5204.         if($data)
  5205.         {
  5206.             $description  $data->description;
  5207.             $reason       $data->reason;    
  5208.             //$externalId   = $data->external_id;                                        
  5209.             $plate        $data->plate;
  5210.             $eid          $data->eid;
  5211.             $vaid         $data->vaid;
  5212.             $lat          $data->lat;
  5213.             $lng          $data->lng;
  5214.         
  5215.             $assignmentObj $entityManager->getRepository(VehicleAssignment::class)->findOneBy(array("vehicleAssignmentId" => $vaid));            
  5216.             if($assignmentObj)
  5217.             {
  5218.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy(array("employeeId" => $eid));            
  5219.                 if($employeeObj)
  5220.                 {
  5221.                     $vehiclePanic = new VehiclePanic();
  5222.                     $vehiclePanic->setVehicleAssignment($assignmentObj);
  5223.                     $vehiclePanic->setExternalId($assignmentObj->getExternalId());
  5224.                     $vehiclePanic->setDescription($description);
  5225.                     $vehiclePanic->setReason($reason);
  5226.                     $vehiclePanic->setPlateNumber($plate);
  5227.                     $vehiclePanic->setLng($lng);
  5228.                     $vehiclePanic->setLat($lat);
  5229.                     $vehiclePanic->setIsActive(1);
  5230.                     $vehiclePanic->setCreatedAt(new \DateTime());
  5231.                     $vehiclePanic->setCreatedByEmployeeId($employeeObj);
  5232.                     $entityManager->persist($vehiclePanic);
  5233.                     $entityManager->flush();                                        
  5234.                     
  5235.                     return new JsonResponse(array('status' => 'success'));
  5236.                 }
  5237.             }
  5238.         }    
  5239.         
  5240.         return new JsonResponse(array('status' => 'error'));
  5241.     }
  5242.     /**
  5243.      * @Route("/vehicle-fuel-create", name="/ws/vehicle-fuel-create"), methods={"GET", "POST"}) 
  5244.      */
  5245.     public function vehicleFuelCreateAction(Request $requestEntityManagerInterface $entityManagerHelperService $helperService)
  5246.     {
  5247.         $pictures = [];        
  5248.         $data json_decode(file_get_contents("php://input"));    
  5249.         if($data)
  5250.         {
  5251.             
  5252.             $mileage  $data->mileage;
  5253.             $quantity $data->quantity;                                                    
  5254.             $type     $data->type;
  5255.             $eid      $data->eid;
  5256.             $aid      $data->aid;
  5257.             $lat      $data->lat;
  5258.             $lng      $data->lng;
  5259.     
  5260.             $ext2    $data->ext2;
  5261.             $base642 $data->file2;            
  5262.             $ext     $data->ext;
  5263.             $base64  $data->file;            
  5264.             $dir_path "uploads/vehicle/".$aid."/";
  5265.             $obj $entityManager->getRepository(VehicleAssignment::class)->findOneBy(array("vehicleAssignmentId" => $aid));                                                
  5266.             if($obj)
  5267.             {
  5268.                 if(!is_dir($dir_path))
  5269.                 {
  5270.                     mkdir($dir_path0777true);
  5271.                 }
  5272.                 $fileName  md5(date("YmdHis"))."_fuel.".$ext;               
  5273.                 $new       $dir_path.$fileName;                            
  5274.                 $fileName2 md5(date("YmdHis"))."_fuel_2.".$ext2;            
  5275.                 $newTwo    $dir_path.$fileName2;             
  5276.                   
  5277.                 $decoded base64_decode($base64);
  5278.                 file_put_contents($new$decoded);                                    
  5279.                 $decoded2 base64_decode($base642);
  5280.                 file_put_contents($newTwo$decoded2);                                    
  5281.                 $objPicture = new VehicleAssignmentFuel();
  5282.                 $objPicture->setVehicleAssignment($obj);                     
  5283.                 $objPicture->setPicturePath($fileName);
  5284.                 $objPicture->setOdometerPath($fileName2);
  5285.                 $objPicture->setQuantity($quantity);
  5286.                 $objPicture->setMileage($mileage);
  5287.                 $objPicture->setRecordType($type);
  5288.                 $objPicture->setCreatedAt(new \DateTime());
  5289.                 $entityManager->persist($objPicture);
  5290.                 $entityManager->flush();
  5291.                 $pictures $this->getVehicleFilesFuel($entityManager$aid);
  5292.                                     
  5293.                 return new JsonResponse(array('status' => 'success''pictures' => $pictures));                
  5294.             } 
  5295.         }    
  5296.         
  5297.         return new JsonResponse(array('status' => 'error'));
  5298.     }    
  5299.     /**
  5300.      * @Route("/vehicle-fails-create", name="/ws/vehicle-fails-create"), methods={"GET", "POST"}) 
  5301.      */
  5302.     public function vehicleFailsCreateAction(Request $requestEntityManagerInterface $entityManagerHelperService $helperService)
  5303.     {
  5304.         $pictures = [];        
  5305.         $data json_decode(file_get_contents("php://input"));    
  5306.         if($data)
  5307.         {
  5308.             $description  $data->description;            
  5309.             //$externalId   = $data->external_id;                                        
  5310.             $plate        $data->plate;
  5311.             $eid          $data->eid;
  5312.             $vaid         $data->vaid;
  5313.             $lat          $data->lat;
  5314.             $lng          $data->lng;
  5315.         
  5316.             $assignmentObj $entityManager->getRepository(VehicleAssignment::class)->findOneBy(array("vehicleAssignmentId" => $vaid));            
  5317.             if($assignmentObj)
  5318.             {
  5319.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy(array("employeeId" => $eid));            
  5320.                 if($employeeObj)
  5321.                 {
  5322.                     $vehiclePanic = new VehicleAssignmentFail();
  5323.                     $vehiclePanic->setVehicleAssignment($assignmentObj);
  5324.                     $vehiclePanic->setExternalId($assignmentObj->getExternalId());
  5325.                     $vehiclePanic->setDescription($description);                    
  5326.                     $vehiclePanic->setPlateNumber($plate);
  5327.                     $vehiclePanic->setLat($lat);
  5328.                     $vehiclePanic->setLng($lng);
  5329.                     $vehiclePanic->setIsActive(1);
  5330.                     $vehiclePanic->setCreatedAt(new \DateTime());
  5331.                     $vehiclePanic->setCreatedByEmployeeId($employeeObj);
  5332.                     $entityManager->persist($vehiclePanic);
  5333.                     $entityManager->flush();                                        
  5334.                     
  5335.                     return new JsonResponse(array('status' => 'success'));
  5336.                 }
  5337.             }
  5338.         }    
  5339.         
  5340.         return new JsonResponse(array('status' => 'error'));
  5341.     }    
  5342.     
  5343.     
  5344.     public function getLatestMileage($helperService$entityManager$plate)
  5345.     {
  5346.         $checked           ".";
  5347.         $mileageCheckInfo  0;
  5348.         $mileageRefuelInfo 0;
  5349.         $mileageInfo  $helperService->externalDb_getLatestMileage($plate);
  5350.         if($mileageInfo)
  5351.         {                         
  5352.             $kmInicial $mileageInfo['KmInicial'];
  5353.             $kmFinal   $mileageInfo['KmFinal'];
  5354.             
  5355.             if($kmFinal 0)
  5356.             {
  5357.                 $mileageCheckInfo $kmFinal;
  5358.             } else {
  5359.                 $mileageCheckInfo $kmInicial;
  5360.             }
  5361.         } 
  5362.         $vehicleAssignmentFuelObj $entityManager->getRepository(Refuel::class)->findOneBy([
  5363.             "plate_number" => $plate                        
  5364.         ], ['created_at' => 'DESC']);
  5365.         if($vehicleAssignmentFuelObj)
  5366.         {                    
  5367.             $mileageRefuelInfo $vehicleAssignmentFuelObj->getMileage();
  5368.         }
  5369.         //Se obtiene el mayor de los dos
  5370.         if($mileageCheckInfo $mileageRefuelInfo)
  5371.         {
  5372.             $mileageCheck $mileageCheckInfo;
  5373.             $checked      'el registro de asignaciones';
  5374.         } else {
  5375.             $mileageCheck $mileageRefuelInfo;
  5376.             $checked      'el registro de reabastecimiento anterior';
  5377.         }
  5378.         $array = ['mileageCheck' => $mileageCheck'checked' => $checked];
  5379.         return $array;
  5380.     }
  5381.     
  5382.     
  5383.     /**
  5384.      * @Route("/upload-file-reaction-browser", name="/ws/upload-file-reaction-browser"), methods={"GET", "POST"}) 
  5385.      */
  5386.     public function uploadFileReactionBrowserAction(Request $requestEntityManagerInterface $entityManager)
  5387.     {
  5388.                         
  5389.         $uploadfile     $_FILES['file']['name'];
  5390.         $uploadfilename $_FILES['file']['tmp_name'];
  5391.         $array          = array();
  5392.        
  5393.         if($uploadfile)
  5394.         {
  5395.             
  5396.              $ext   $_POST['ext'];
  5397.              $rid   $_POST['rid'];            
  5398.              
  5399.              $fileName md5(date("YmdHis")).".".$ext;
  5400.              $dir_path "uploads/reactions/".$rid."/";
  5401.              $new      $dir_path.$fileName;             
  5402.             if(!is_dir($dir_path))
  5403.             {
  5404.                 mkdir($dir_path0777true);
  5405.             }
  5406.             
  5407.             if(move_uploaded_file($uploadfilename$new))
  5408.             {
  5409.                 $obj $entityManager->getRepository(Reaction::class)->findOneBy(array("reactionId" => $rid));                                                
  5410.                 if($obj)
  5411.                 {
  5412.                                  
  5413.                     $objPicture = new ReactionPicture();
  5414.                     $objPicture->setReaction($obj);                     
  5415.                     $objPicture->setPicturePath($fileName);
  5416.                     $objPicture->setCreatedAt(new \DateTime());
  5417.                     $entityManager->persist($objPicture);
  5418.                     $entityManager->flush();
  5419.                     $pictures $this->getReactionFiles($entityManager$rid);
  5420.                                                             
  5421.                     return new JsonResponse(array('status' => 'success','pictures' => $pictures));                
  5422.                 } 
  5423.                          
  5424.             }
  5425.          
  5426.             return new JsonResponse(array('status' => 'error'));        
  5427.         }  
  5428.     }   
  5429.     
  5430.     
  5431.     /**
  5432.      * @Route("/upload-file-vapicture-browser", name="/ws/upload-file-vapicture-browser"), methods={"GET", "POST"}) 
  5433.      */
  5434.     public function uploadFileVapictureBrowserAction(Request $requestEntityManagerInterface $entityManager)
  5435.     {
  5436.                         
  5437.         $uploadfile     $_FILES['file']['name'];
  5438.         $uploadfilename $_FILES['file']['tmp_name'];
  5439.         $array          = array();
  5440.        
  5441.         if($uploadfile)
  5442.         {
  5443.             
  5444.              $ext    $_POST['ext'];
  5445.              $vaid   $_POST['vaid'];            
  5446.              $type   $_POST['type'];            
  5447.              
  5448.              $fileName md5(date("YmdHis")).".".$ext;
  5449.              $dir_path "uploads/vehicle/";
  5450.              $new      $dir_path.$fileName;             
  5451.             if(!is_dir($dir_path))
  5452.             {
  5453.                 mkdir($dir_path0777true);
  5454.             }
  5455.             
  5456.             if(move_uploaded_file($uploadfilename$new))
  5457.             {
  5458.                 //FAIL TYPE --
  5459.                 if($type == 'fail')
  5460.                 {
  5461.                     $obj $entityManager->getRepository(VehicleAssignmentFail::class)->findOneBy(array(
  5462.                         "vehicleAssignmentFailId" => $vaid
  5463.                     ));                                                
  5464.                 
  5465.                     if($obj)
  5466.                     {
  5467.                                     
  5468.                         $objPicture = new VehiclePicture();
  5469.                         $objPicture->setVehicleAssignmentFail($obj);                     
  5470.                         $objPicture->setPicturePath($fileName);
  5471.                         $objPicture->setType($type);
  5472.                         $objPicture->setCreatedAt(new \DateTime());
  5473.                         $entityManager->persist($objPicture);
  5474.                         $entityManager->flush();
  5475.                         $pictures $this->getVehicleAssignmentFiles($entityManager$vaid$type);
  5476.                                                                 
  5477.                         return new JsonResponse(array('status' => 'success','pictures' => $pictures));                
  5478.                     } 
  5479.                 } else {
  5480.                     
  5481.                         $obj $entityManager->getRepository(VehiclePanic::class)->findOneBy(array(
  5482.                             "vehiclePanicId" => $vaid
  5483.                         ));                                                
  5484.                     
  5485.                         if($obj)
  5486.                         {
  5487.                                         
  5488.                             $objPicture = new VehiclePicture();
  5489.                             $objPicture->setVehiclePanic($obj);                     
  5490.                             $objPicture->setPicturePath($fileName);
  5491.                             $objPicture->setType($type);
  5492.                             $objPicture->setCreatedAt(new \DateTime());
  5493.                             $entityManager->persist($objPicture);
  5494.                             $entityManager->flush();
  5495.     
  5496.                             $pictures $this->getVehicleAssignmentFiles($entityManager$vaid$type);
  5497.                                                                     
  5498.                             return new JsonResponse(array('status' => 'success','pictures' => $pictures));                
  5499.     
  5500.                         } 
  5501.                     
  5502.                 }
  5503.                          
  5504.             }
  5505.          
  5506.             return new JsonResponse(array('status' => 'error'));        
  5507.         }  
  5508.     }       
  5509.     /**
  5510.      * @Route("/upload-file-sanction-browser", name="/ws/upload-file-sanction-browser"), methods={"GET", "POST"}) 
  5511.      */
  5512.     public function uploadFileSanctionBrowserAction(Request $requestEntityManagerInterface $entityManager)
  5513.     {
  5514.                         
  5515.         $uploadfile     $_FILES['file']['name'];
  5516.         $uploadfilename $_FILES['file']['tmp_name'];
  5517.         $array          = array();
  5518.        
  5519.         if($uploadfile)
  5520.         {
  5521.             
  5522.              $ext   $_POST['ext'];
  5523.              $sid   $_POST['sid']; //sanction Id
  5524.              
  5525.              $fileName md5(date("YmdHis")).".".$ext;
  5526.              $dir_path "uploads/sanctions/".$sid."/";
  5527.              $new      $dir_path.$fileName;             
  5528.             if(!is_dir($dir_path))
  5529.             {
  5530.                 mkdir($dir_path0777true);
  5531.             }
  5532.             
  5533.             if(move_uploaded_file($uploadfilename$new))
  5534.             {
  5535.                 $obj $entityManager->getRepository(Sanction::class)->findOneBy(array("sanctionId" => $sid));                                                
  5536.                 if($obj)
  5537.                 {
  5538.                                  
  5539.                     $objPicture = new SanctionPicture();
  5540.                     $objPicture->setSanction($obj);                     
  5541.                     $objPicture->setPicturePath($fileName);
  5542.                     $objPicture->setCreatedAt(new \DateTime());
  5543.                     $entityManager->persist($objPicture);
  5544.                     $entityManager->flush();
  5545.                     $pictures $this->getSanctionFiles($entityManager$sid);
  5546.                                                             
  5547.                     return new JsonResponse(array('status' => 'success','pictures' => $pictures));                
  5548.                 } 
  5549.                          
  5550.             }
  5551.          
  5552.             return new JsonResponse(array('status' => 'error'));        
  5553.         }  
  5554.     }        
  5555.     /**
  5556.      * @Route("/upload-file-supervision-browser", name="/ws/upload-file-supervision-browser"), methods={"GET", "POST"}) 
  5557.      */
  5558.     public function uploadFileSupervisionBrowserAction(Request $requestEntityManagerInterface $entityManager)
  5559.     {
  5560.                         
  5561.         $uploadfile     $_FILES['file']['name'];
  5562.         $uploadfilename $_FILES['file']['tmp_name'];
  5563.         $array          = array();
  5564.        
  5565.         if($uploadfile)
  5566.         {
  5567.             
  5568.              $ext   $_POST['ext'];
  5569.              $supervisionId  $_POST['supervision_id'];            
  5570.              $commentTypeId  $_POST['comment_type'];            
  5571.              
  5572.              $fileName md5(date("YmdHis")).".".$ext;
  5573.              $dir_path "uploads/reports/s_".$supervisionId."/";
  5574.              $new      $dir_path.$fileName;             
  5575.             /*$t1 = "Ruta relativa: " . $dir_path . "<br>";
  5576.             $t2 = "Ruta absoluta: " . realpath($dir_path) . "<br>";
  5577.             $t3 = "cwd (current working directory): " . getcwd() . "<br>";
  5578.             return new JsonResponse(array('status' => 'success','INFO' => $t1." -- ".$t2." ---".$t3));*/
  5579.             if(!is_dir($dir_path))
  5580.             {
  5581.                 mkdir($dir_path0777true);
  5582.             }
  5583.             
  5584.             if(move_uploaded_file($uploadfilename$new))
  5585.             {
  5586.                 $mainObj $entityManager->getRepository(Supervision::class)->findOneBy(array("supervisionId" => $supervisionId));                                                
  5587.                 if($mainObj)
  5588.                 {
  5589.                                  
  5590.                     $obj = new SupervisionPicture();
  5591.                     $obj->setSupervision($mainObj);                     
  5592.                     $obj->setPicturePath($fileName);
  5593.                     $obj->setPictureType($commentTypeId);
  5594.                     $obj->setCreatedAt(new \DateTime());
  5595.                     $entityManager->persist($obj);
  5596.                     $entityManager->flush();
  5597.                     $pictures $this->getSupervisionFiles($entityManager$supervisionId$commentTypeId);
  5598.                                                             
  5599.                     return new JsonResponse(array('status' => 'success','pictures' => $pictures));                
  5600.                 } 
  5601.                          
  5602.             }
  5603.          
  5604.             return new JsonResponse(array('status' => 'error'));        
  5605.         }  
  5606.     }    
  5607.     public function getTicketFiles($entityManager$tid)
  5608.     {
  5609.         $path  $this->getProjectPaths();    
  5610.         $array = [];
  5611.         $pictures $entityManager->getRepository(TicketPicture::class)->findBy(array("Ticket" => $tid));
  5612.         foreach($pictures as $picture)
  5613.         {
  5614.             $picturePath $path['public_path']."uploads/ticket/".$tid."/".$picture->getPicturePath();                                                                            
  5615.             $array[] = array(
  5616.                 'picture_id'   => $picture->getTicketPictureId(),                        
  5617.                 'picture_path' => $picturePath
  5618.             );
  5619.         }
  5620.         return $array;
  5621.     }
  5622.     public function getElectronicFiles($entityManager$eid)
  5623.     {
  5624.         $path  $this->getProjectPaths();    
  5625.         $array = [];
  5626.         $pictures $entityManager->getRepository(ElectronicPicture::class)->findBy(array("Electronic" => $eid));
  5627.         foreach($pictures as $picture)
  5628.         {
  5629.             $picturePath $path['public_path']."uploads/electronic/".$eid."/".$picture->getPicturePath();                                                                            
  5630.             $array[] = array(
  5631.                 'picture_id'   => $picture->getElectronicPictureId(),                        
  5632.                 'picture_path' => $picturePath
  5633.             );
  5634.         }
  5635.         return $array;
  5636.     }
  5637.     public function getSanctionFiles($entityManager$sid)
  5638.     {
  5639.         $path  $this->getProjectPaths();    
  5640.         $array = [];
  5641.         $pictures $entityManager->getRepository(SanctionPicture::class)->findBy(array("Sanction" => $sid));
  5642.         foreach($pictures as $picture)
  5643.         {
  5644.             $picturePath $path['public_path']."uploads/sanctions/".$sid."/".$picture->getPicturePath();                                                                            
  5645.             $array[] = array(
  5646.                 'picture_id'   => $picture->getSanctionPictureId(),                        
  5647.                 'picture_path' => $picturePath
  5648.             );
  5649.         }
  5650.         return $array;
  5651.     }
  5652.     public function getVehicleFiles($entityManager$aid)
  5653.     {
  5654.         $path  $this->getProjectPaths();    
  5655.         $array = [];
  5656.         $pictures $entityManager->getRepository(VehicleAssignmentPicture::class)->findBy(array("VehicleAssignment" => $aid));
  5657.         foreach($pictures as $picture)
  5658.         {
  5659.             $picturePath $path['public_path']."uploads/vehicle/".$aid."/".$picture->getPicturePath();                                                                            
  5660.             $array[] = array(
  5661.                 'picture_id'   => $picture->getVehicleAssignmentPictureId(),                        
  5662.                 'picture_path' => $picturePath,
  5663.                 'number'       => $picture->getPictureNumber()
  5664.             );
  5665.         }
  5666.         return $array;
  5667.     }
  5668.     public function getVehicleFilesFuel($entityManager$aid)
  5669.     {
  5670.         $path  $this->getProjectPaths();    
  5671.         $array = [];
  5672.         $pictures $entityManager->getRepository(VehicleAssignmentFuel::class)->findBy(array("VehicleAssignment" => $aid));
  5673.         foreach($pictures as $picture)
  5674.         {
  5675.             $picturePath $path['public_path']."uploads/vehicle/".$aid."/".$picture->getPicturePath();                                                                            
  5676.             $array[] = array(
  5677.                 'picture_id'   => $picture->getVehicleAssignmentFuelId(),                        
  5678.                 'picture_path' => $picturePath,
  5679.                 'quantity'     => $picture->getQuantity()
  5680.             );
  5681.         }
  5682.         return $array;
  5683.     }
  5684.     public function getReactionFiles($entityManager$rid)
  5685.     {
  5686.         $path  $this->getProjectPaths();    
  5687.         $array = [];
  5688.         $pictures $entityManager->getRepository(ReactionPicture::class)->findBy(array("Reaction" => $rid));
  5689.         foreach($pictures as $picture)
  5690.         {
  5691.             $picturePath $path['public_path']."uploads/reactions/".$rid."/".$picture->getPicturePath();                                                                            
  5692.             $array[] = array(
  5693.                 'picture_id'   => $picture->getReactionPictureId(),                        
  5694.                 'picture_path' => $picturePath
  5695.             );
  5696.         }
  5697.         return $array;
  5698.     }
  5699.     public function getVehicleAssignmentFiles($entityManager$vaid$type)
  5700.     {
  5701.         $path  $this->getProjectPaths();    
  5702.         $array = [];
  5703.         $pictures = [];
  5704.         if($type == 'fail')
  5705.         {
  5706.             $pictures $entityManager->getRepository(VehiclePicture::class)->findBy(array(
  5707.                 "VehicleAssignmentFail" => $vaid,
  5708.                 "type" => $type
  5709.             ));
  5710.         }
  5711.         if($type == 'panic')
  5712.         {
  5713.             $pictures $entityManager->getRepository(VehiclePicture::class)->findBy(array(
  5714.                 "VehiclePanic" => $vaid,
  5715.                 "type" => $type
  5716.             ));
  5717.         }
  5718.         foreach($pictures as $picture)
  5719.         {
  5720.             $picturePath $path['public_path']."uploads/vehicle/".$picture->getPicturePath();                                                                            
  5721.             $array[] = array(
  5722.                 'picture_id'   => $picture->getVehiclePictureId(),                        
  5723.                 'picture_path' => $picturePath
  5724.             );
  5725.         }
  5726.         return $array;
  5727.     }    
  5728.     public function getReportFiles($entityManager$seid)
  5729.     {
  5730.         $path  $this->getProjectPaths();    
  5731.         $array = [];
  5732.         $pictures $entityManager->getRepository(ShiftEventPicture::class)->findBy(array("ShiftEvent" => $seid));
  5733.         foreach($pictures as $picture)
  5734.         {
  5735.             $picturePath $path['public_path']."uploads/reports/".$seid."/".$picture->getPicturePath();                                                                            
  5736.             $array[] = array(
  5737.                 'picture_id'   => $picture->getShiftEventPictureId(),                        
  5738.                 'picture_path' => $picturePath
  5739.             );
  5740.         }
  5741.         return $array;
  5742.     }
  5743.     
  5744.     /**
  5745.      * @Route("/get-agent-reports", name="get-agent-reports", methods={"GET", "POST"})
  5746.      */
  5747.     public function getAgentReports(Request $requestEntityManagerInterface $entityManager): Response
  5748.     {
  5749.         
  5750.         $data json_decode(file_get_contents("php://input"));             
  5751.         if($data)
  5752.         {             
  5753.             $seid $data->seid;
  5754.             $hash $data->hash;
  5755.             if($hash != "HASHBLACKTHORNESECURITY2023**")
  5756.             {
  5757.                 return new JsonResponse(array('status' => 'error'));
  5758.             }
  5759.             $objs $entityManager->getRepository(ShiftEvent::class)->findBy([                
  5760.                 'is_active'      => 1,
  5761.                 'is_empty_event' => 0,
  5762.                 'ShiftEmployee'  => $seid,
  5763.                 'is_panic'       => 0
  5764.             ]);    
  5765.             if($objs)
  5766.             {                    
  5767.                 $list = [];
  5768.                 foreach($objs as $item)
  5769.                 {           
  5770.                     $pictures $entityManager->getRepository(ShiftEventPicture::class)->findBy([                
  5771.                         'ShiftEvent' => $item->getShiftEventId()                        
  5772.                     ]);   
  5773.                     $list[] = [
  5774.                         "shiftEventId"   => $item->getShiftEventId(),
  5775.                         "employeeId"     => $item->getEmployee()->getEmployeeId(),
  5776.                         "comments"       => $item->getComments(),
  5777.                         "locationId"     => $item->getLocation()->getLocationId(),
  5778.                         "locationName"   => $item->getLocation()->getName(),
  5779.                         "reportTypeId"   => $item->getShiftReportType()->getShiftReportTypeId(),
  5780.                         "reportTypeName" => $item->getShiftReportType()->getName(),
  5781.                         "createdAt"      => $item->getCreatedAt()->format("Y-m-d H:i:s"),
  5782.                         'pictures'       => count($pictures)
  5783.                     ];
  5784.                 }
  5785.                 
  5786.                 return new JsonResponse(array('status' => 'success''data' => $list));
  5787.                
  5788.             } else {
  5789.                 return new JsonResponse(array('status' => 'success''data' => []));
  5790.             }
  5791.         }
  5792.         return new JsonResponse(array('status' => 'error'));
  5793.     }    
  5794.     /**
  5795.      * @Route("/save-employee-terms", name="save-employee-terms", methods={"GET", "POST"})
  5796.      */
  5797.     public function saveEmployeeTerms(Request $requestEntityManagerInterface $entityManager): Response
  5798.     {
  5799.         
  5800.         $data json_decode(file_get_contents("php://input"));             
  5801.         if($data)
  5802.         {             
  5803.             $eid       $data->eid;
  5804.             $signature $data->signature;
  5805.             $terms     $data->terms;
  5806.             $signaturePath $this->saveSignature($signature);
  5807.             if($signaturePath)
  5808.             {
  5809.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  5810.                     'employeeId'    => $eid
  5811.                 ]);
  5812.                 $agreement = new EmployeeAgreement();
  5813.                 $agreement->setEmployee($employeeObj);
  5814.                 $agreement->setSignaturePath($signaturePath);
  5815.                 $agreement->setTermsContent($terms->body);
  5816.                 $agreement->setCreatedAt(new \DateTime());                
  5817.                 $entityManager->persist($agreement);
  5818.                 $entityManager->flush();
  5819.             }
  5820.             return new JsonResponse(array('status' => 'success''data' => $agreement->getEmployeeAgreementId()));
  5821.         }
  5822.         return new JsonResponse(array('status' => 'error'));        
  5823.     }      
  5824.     /**
  5825.      * @Route("/get-vehicle-terms", name="get-vehicle-terms", methods={"GET", "POST"})
  5826.      */
  5827.     public function getVehicleTerms(Request $requestEntityManagerInterface $entityManager): Response
  5828.     {
  5829.         
  5830.         $data json_decode(file_get_contents("php://input"));             
  5831.         if($data)
  5832.         {             
  5833.             $eid  $data->eid;
  5834.             $list = [];
  5835.             $objs $entityManager->getRepository(Help::class)->findOneBy(['helpId' => 2]); 
  5836.             if($objs)
  5837.             {                    
  5838.                 
  5839.                 $list = [
  5840.                     "title" => $objs->getName(),
  5841.                     "body"  => $objs->getContent()
  5842.                 ];
  5843.                            
  5844.             }
  5845.             return new JsonResponse(array('status' => 'success''data' => $list));
  5846.         }
  5847.         return new JsonResponse(array('status' => 'error'));        
  5848.     }        
  5849.     /**
  5850.      * @Route("/get-refueling", name="get-refueling", methods={"GET", "POST"})
  5851.      */
  5852.     public function getRefueling(Request $requestEntityManagerInterface $entityManager): Response
  5853.     {
  5854.         
  5855.         $data json_decode(file_get_contents("php://input"));             
  5856.         if($data)
  5857.         {             
  5858.             $eid  $data->eid;
  5859.             $list = [];
  5860.             $objs $entityManager->getRepository(Refuel::class)->getRefueling($eid); 
  5861.             if($objs)
  5862.             {                    
  5863.                 
  5864.                 foreach($objs as $item)
  5865.                 {            
  5866.                     
  5867.                     $paths $this->getProjectPaths();
  5868.                     $image $paths['public_path'].'uploads/vehicle/'.$item['picture_path'];
  5869.                     $list[] = [
  5870.                         "refuel_id"    => $item['refuel_id'],
  5871.                         "quantity"     => $item['quantity'],
  5872.                         "mileage"      => $item['mileage'],
  5873.                         "plate"        => $item['plate_number'],
  5874.                         "picture_path" => $image,
  5875.                         "external_id"  => $item['external_vehicle_id'],                        
  5876.                         "created_at"   => $item['created_at']
  5877.                     ];
  5878.                 }                                
  5879.                            
  5880.             }
  5881.             return new JsonResponse(array('status' => 'success''data' => $list));
  5882.         }
  5883.         return new JsonResponse(array('status' => 'error'));        
  5884.     }        
  5885.   /**
  5886.      * @Route("/get-sliders", name="get-sliders", methods={"GET", "POST"})
  5887.      */
  5888.     public function getSliders(Request $requestEntityManagerInterface $entityManager): Response
  5889.     {
  5890.         
  5891.         $data json_decode(file_get_contents("php://input"));             
  5892.         if($data)
  5893.         {             
  5894.             $sliders $entityManager->getRepository(Slider::class)->findBy([                
  5895.                 'is_active' => 1          
  5896.             ], ['sliderId' => 'ASC']);    
  5897.             if($sliders)
  5898.             {                    
  5899.                 $list = [];
  5900.                 foreach($sliders as $item)
  5901.                 {                  
  5902.                     $paths $this->getProjectPaths();
  5903.                     $image $paths['public_path'].'uploads/'.$item->getImagePath();
  5904.                     $list[] = $image;                    
  5905.                 }
  5906.                 
  5907.                 return new JsonResponse(array('status' => 'success''data' => $list));
  5908.                
  5909.             }
  5910.         }
  5911.         return new JsonResponse(array('status' => 'error'));
  5912.     }           
  5913.     
  5914.     
  5915.     public function getLastReport($entityManager$eid$lid)
  5916.     {
  5917.         $shiftEvent $entityManager->getRepository(ShiftEvent::class)->findOneBy([                
  5918.             'Employee'  => $eid,
  5919.             'Location'  => $lid,
  5920.             'is_active' => 1
  5921.          ], ['shiftEventId' => 'DESC']); 
  5922.          
  5923.          $lastReport "";
  5924.          if($shiftEvent)
  5925.          {
  5926.             $lastReport $shiftEvent->getCreatedAt()->format("Y-m-d H:i:s");
  5927.          }
  5928.          return $lastReport;
  5929.     }
  5930.     public function getPanicStatus($entityManager$eid$lid)
  5931.     {
  5932.         $shiftEvent $entityManager->getRepository(ShiftEvent::class)->findOneBy([                
  5933.             'Employee'  => $eid,
  5934.             'Location'  => $lid,
  5935.             'is_active' => 1,
  5936.             'is_panic'  => 1,
  5937.             'is_panic_active' => 1
  5938.          ], ['shiftEventId' => 'DESC']); 
  5939.          
  5940.          $lastReport false;
  5941.          if($shiftEvent)
  5942.          {
  5943.             $lastReport true;
  5944.          }
  5945.          return $lastReport;
  5946.     }
  5947.     /**
  5948.      * @Route("/get-shifts-available", name="get-shifts-available", methods={"GET", "POST"})
  5949.      */
  5950.     public function shiftsAvailable(Request $requestEntityManagerInterface $entityManager): Response
  5951.     {
  5952.         
  5953.         $data json_decode(file_get_contents("php://input"));             
  5954.         if($data)
  5955.         {   
  5956.             $eid  $data->eid;  
  5957.             $shiftsAvailable $entityManager->getRepository(ShiftEmployee::class)->getShiftsAvailable($eid);
  5958.             $arr = [];
  5959.             foreach($shiftsAvailable as $shift)
  5960.             {
  5961.                 if($shift['first_name'])
  5962.                 {
  5963.                     $creatorName $shift['first_name']." ".$shift['last_name'];
  5964.                 } else {
  5965.                     $creatorName $shift['creator_name'];
  5966.                 }
  5967.                 $arr[] = [
  5968.                     "project_name"              => $shift['project_name'],
  5969.                     "client_name"               => $shift['client_name'],
  5970.                     "location_id"               => $shift['location_id'],
  5971.                     "location_name"             => $shift['location_name'],
  5972.                     'location_polygon_list'     => json_decode($shift["polygon_list"], true),
  5973.                     "location_address"          => $shift['address'],
  5974.                     "location_employee_id"      => $shift['location_employee_id'],
  5975.                     "assigned_by"               => $creatorName,
  5976.                     "date_from"                 => $shift['date_from'],
  5977.                     "date_to"                   => $shift['date_to'],
  5978.                     "already_started"           => $shift['already_started']
  5979.                 ];
  5980.             }
  5981.             return new JsonResponse(array('status' => 'success''data' => $arr));
  5982.         }
  5983.         return new JsonResponse(array('status' => 'error'));
  5984.     }
  5985.     /**
  5986.      * @Route("/search-external-vehicle", name="search-external-vehicle", methods={"GET", "POST"})
  5987.      */
  5988.     public function searchExternalVehicle(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  5989.     {
  5990.         
  5991.         $data json_decode(file_get_contents("php://input"));             
  5992.         if($data)
  5993.         {   
  5994.             $plate  $data->plate;  
  5995.             $result $helperService->externalDb_searchVehicleByPlate($plate);
  5996.             return new JsonResponse(array('status' => 'success''data' => $result));
  5997.         }
  5998.         return new JsonResponse(array('status' => 'error'));
  5999.     }
  6000.     /**
  6001.      * @Route("/search-overtime-cut", name="search-overtime-cut", methods={"GET", "POST"})
  6002.      */
  6003.     public function searchOvertimeCut(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  6004.     {
  6005.         
  6006.         $data json_decode(file_get_contents("php://input"));             
  6007.         if($data)
  6008.         {   
  6009.             $cutId  $data->cutId;  
  6010.             $result $helperService->externalDb_searchOvertimeCut($cutId);
  6011.             if($result)
  6012.             {
  6013.                 return new JsonResponse(array('status' => 'success''data' => $result));
  6014.             } 
  6015.             return new JsonResponse(array('status' => 'error''message' => "No se encontró un registro vigente con el ID proporcionado."));
  6016.         }
  6017.         return new JsonResponse(array('status' => 'error''message' => "No se pudo realizar la consulta en este momento, intente de nuevo más tarde."));
  6018.     }   
  6019.     
  6020.     
  6021.     /**
  6022.      * @Route("/external-get-absences", name="external-get-absences", methods={"GET", "POST"})
  6023.      */
  6024.     public function getGetAbsences(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  6025.     {
  6026.         
  6027.         $data json_decode(file_get_contents("php://input"));             
  6028.         if($data)
  6029.         {   
  6030.             $locationId $data->location_id;  
  6031.             $locationObj $entityManager->getRepository(Location::class)->findOneBy([
  6032.                 'locationId' => $locationId
  6033.             ]);
  6034.             if($locationObj && $locationObj->getIdPuesto())
  6035.             {
  6036.                 $result   $helperService->externalDb_getAusencias($locationObj->getIdPuesto());
  6037.                 if($result)
  6038.                 {
  6039.                     return new JsonResponse(array('status' => 'success''data' => $result));
  6040.                 } 
  6041.                 return new JsonResponse(array('status' => 'error''message' => "No hay un registro de ausencía que coincida con el criterio de búsqueda."));
  6042.             }
  6043.             return new JsonResponse(array('status' => 'error''message' => "El ID del puesto es incorrecto."));
  6044.         }
  6045.         return new JsonResponse(array('status' => 'error''message' => "No se pudo realizar la consulta en este momento, intente de nuevo más tarde."));
  6046.     }   
  6047.     /**
  6048.      * @Route("/external-save-asignacion", name="external-save-asignacion", methods={"GET", "POST"})
  6049.      */
  6050.     public function setAsignacion(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  6051.     {
  6052.         
  6053.         $data json_decode(file_get_contents("php://input"));             
  6054.         if($data)
  6055.         {   
  6056.             $form $data->form;  
  6057.             $info $data->info;
  6058.  
  6059.             $IdCorte               $info->IdCorte;
  6060.             $employeeId            $form->agente;
  6061.             $locationId            $form->puesto;
  6062.             $DescripcionAsignacion $form->descripcion;
  6063.             $IdTipo                $form->tipo;
  6064.             $IdTipoAsignacion      $form->tipoAsignacion;
  6065.             $IdMotivo              $form->motivo;
  6066.             $Cantidad              1;
  6067.             $IdUsuario             101;
  6068.             $Fecha                 date('Y-m-d');
  6069.             $Estado                "O";
  6070.             $Activo                1;            
  6071.             $IdAusencia            $form->ausencia;
  6072.             $Turno     "";
  6073.             $Actividad "";
  6074.             $IdEstadodeFuerza 0;
  6075.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  6076.                 'employeeId' => $employeeId
  6077.             ]);
  6078.             if($employeeObj && $employeeObj->getAlias())
  6079.             {
  6080.                 $IdEstadodeFuerza $employeeObj->getAlias();
  6081.             }
  6082.             if($IdEstadodeFuerza == 0)
  6083.             {
  6084.                 return new JsonResponse(array('status' => 'error''message' => "No se encontro un ID Estado de fuerza valido en la base local. Reporte este error al administrador del sistema"));
  6085.             }
  6086.             $IdPuesto 0;
  6087.             $locationObj $entityManager->getRepository(Location::class)->findOneBy([
  6088.                 'locationId' => $locationId
  6089.             ]);
  6090.             if($locationObj && $locationObj->getIdPuesto())
  6091.             {
  6092.                 $IdPuesto $locationObj->getIdPuesto();
  6093.             }
  6094.             if($IdPuesto == 0)
  6095.             {
  6096.                 return new JsonResponse(array('status' => 'error''message' => "No se encontro un ID de puesto en la base local. Reporte este error al administrador del sistema"));
  6097.             }
  6098.                                    
  6099.             $hexTipoAsignacionArray $helperService->externalDb_getHexTipoById($IdTipoAsignacion);            
  6100.             if($hexTipoAsignacionArray)
  6101.             {                      
  6102.                 $Turno     $hexTipoAsignacionArray['Cantidad'];
  6103.                 $Actividad $hexTipoAsignacionArray['Actividad'];
  6104.                 // Primera validación --> El agente puede hacer más turnos extras?
  6105.                 $checkOne $helperService->externalDb_getHexAsignacionByEstadoFuerzaId($IdEstadodeFuerza$Fecha);                
  6106.                 if($checkOne)
  6107.                 {                    
  6108.                     //foreach($checkOne as $check)
  6109.                     //{
  6110.                         if($checkOne['Turno'] == '24')
  6111.                         {
  6112.                             return new JsonResponse(array('status' => 'error''message' => "No se puede crear un registro para este agente, ya cuenta con un turno extra que colisiona con el registro actual (24 horas)."));
  6113.                         } else {
  6114.                             if($checkOne['Actividad'] == $Actividad)
  6115.                             {
  6116.                                 return new JsonResponse(array('status' => 'error''message' => "No se puede crear un registro para este agente, ya cuenta con un turno extra que colisiona con el registro actual ($Actividad)."));
  6117.                             }
  6118.                         }                            
  6119.                     //}                    
  6120.                 }
  6121.                 // Segunda validación --> El puesto permite que alguien mas este cubriendo?
  6122.                 $checkTwo $helperService->externalDb_getBiSemanalByIdPuesto($IdPuesto);
  6123.                 if($checkTwo)
  6124.                 {         
  6125.                     //Solo en estos IDs se tomará en cuenta esta validación           
  6126.                     if($IdMotivo == || $IdMotivo == || $IdMotivo == 9)
  6127.                     {
  6128.                         //Todas las vacantes naturales se toman como suma
  6129.                         $sum 0;
  6130.                         foreach($checkTwo as $check)
  6131.                         {
  6132.                             $IdEstadoDeFuerza $check['IdEstadodefuerza'];
  6133.                             if($IdEstadoDeFuerza == 0)
  6134.                             {
  6135.                                 $sum++;
  6136.                             }
  6137.                         }
  6138.                         
  6139.                         //Todas las asuencias reportadas se suman
  6140.                         if($IdAusencia 0)
  6141.                         {
  6142.                             $absencesCheck $helperService->externalDb_getBiAusenciasByIdPuesto($IdPuesto$Fecha);
  6143.                             foreach($absencesCheck as $absence)
  6144.                             {                        
  6145.                                 $sum++;                        
  6146.                             }
  6147.                         }
  6148.                         //Todos los turnos extra reportados se restan
  6149.                         $absencesCheck $helperService->externalDb_getHexAsignacionByIdPuesto($IdPuesto$Fecha);
  6150.                         foreach($absencesCheck as $absence)
  6151.                         {                        
  6152.                             $sum--;                        
  6153.                         }
  6154.                         
  6155.                         //Si ya no hay disponibilidad
  6156.                         if($sum 1)
  6157.                         {
  6158.                             return new JsonResponse(array('status' => 'error''message' => "No se puede crear un nuevo registro porque el puesto no tiene vacantes. ($sum)"));
  6159.                         }
  6160.                     }
  6161.                 } else {
  6162.                     return new JsonResponse(array('status' => 'error''message' => "No se puede crear un nuevo registro porque no hay vacantes (L:6164)"));
  6163.                 }
  6164.                 $form = [
  6165.                     'IdCorte'               => $IdCorte,
  6166.                     'IdEstadodeFuerza'      => $IdEstadodeFuerza,
  6167.                     'IdPuesto'              => $IdPuesto,
  6168.                     'IdTipoAsignacion'      => $IdTipoAsignacion,
  6169.                     'DescripcionAsignacion' => $DescripcionAsignacion,
  6170.                     'IdMotivo'              => $IdMotivo,
  6171.                     'Cantidad'              => $Cantidad,
  6172.                     'IdUsuario'             => $IdUsuario,
  6173.                     'Fecha'                 => $Fecha,
  6174.                     'Estado'                => $Estado,
  6175.                     'Activo'                => 1,
  6176.                     'IdAusencia'            => $IdAusencia,
  6177.                     'Turno'                 => $Turno,
  6178.                     'Actividad'             => $Actividad
  6179.                 ];
  6180.                 
  6181.                 //Insertar en HEX_ASIGNACION
  6182.                 if($helperService->externalDb_setHexAsignacion($form))
  6183.                 {
  6184.                     //Registrar en la ausencia, quien va a cubrir
  6185.                     if($helperService->externalDb_updateBiAusencia($IdEstadodeFuerza$IdCorte$IdAusencia))
  6186.                     {
  6187.                         
  6188.                     }   
  6189.                     return new JsonResponse(array('status' => 'success'));                 
  6190.                 }                
  6191.             }  
  6192.         }
  6193.         return new JsonResponse(array('status' => 'error''message' => "No se pudo realizar la consulta en este momento, intente de nuevo más tarde."));
  6194.     }  
  6195.     /**
  6196.      * @Route("/overtime-get-tipos-asignaciones", name="overtime-get-tipos-asignaciones", methods={"GET", "POST"})
  6197.      */
  6198.     public function getTiposAsignaciones(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  6199.     {
  6200.         
  6201.         $data json_decode(file_get_contents("php://input"));             
  6202.         if($data)
  6203.         {               
  6204.             $result $helperService->externalDb_getHexTipoAsignacionYAsignaciones();
  6205.             if($result)
  6206.             {
  6207.                 return new JsonResponse(array('status' => 'success''data' => $result));
  6208.             } 
  6209.             return new JsonResponse(array('status' => 'error''message' => "No se pudo realizar la consulta en este momento, intente de nuevo más tarde."));
  6210.         }
  6211.         return new JsonResponse(array('status' => 'error''message' => "No se pudo realizar la consulta en este momento, intente de nuevo más tarde."));
  6212.     }  
  6213.     
  6214.     /**
  6215.      * @Route("/overtime-get-asignaciones-validate", name="overtime-get-asignaciones-validate", methods={"GET", "POST"})
  6216.      */
  6217.     public function getAsignacionesForValidate(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  6218.     {
  6219.         
  6220.         $data json_decode(file_get_contents("php://input"));             
  6221.         if($data)
  6222.         {               
  6223.             $result $helperService->externalDb_getHexAsignacionesForValidate();
  6224.             if($result)
  6225.             {
  6226.                 return new JsonResponse(array('status' => 'success''data' => $result));
  6227.             } 
  6228.             return new JsonResponse(array('status' => 'error''message' => "No se pudo realizar la consulta en este momento, intente de nuevo más tarde."));
  6229.         }
  6230.         return new JsonResponse(array('status' => 'error''message' => "No se pudo realizar la consulta en este momento, intente de nuevo más tarde."));
  6231.     }  
  6232.     
  6233.        
  6234.     
  6235.     /**
  6236.      * @Route("/overtime-update-asignaciones-validate", name="overtime-update-asignaciones-validate", methods={"GET", "POST"})
  6237.      */
  6238.     public function updateAsignacionesForValidate(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  6239.     {
  6240.         
  6241.         $data json_decode(file_get_contents("php://input"));             
  6242.         if($data)
  6243.         {              
  6244.             $assignmentId $data->IdAsignacion;
  6245.             $idValidador  $data->userInfo->alias;
  6246.             if($helperService->externalDb_checkIdEstadoDeFuerza($idValidador))
  6247.             {
  6248.                 $result $helperService->externalDb_updateHexAsignacionValidate($assignmentId$idValidador);
  6249.                 if($result)
  6250.                 {
  6251.                     return new JsonResponse(array('status' => 'success''data' => $result));
  6252.                 }
  6253.                 
  6254.                 return new JsonResponse(array('status' => 'error''message' => "No se pudo realizar la consulta en este momento, intente de nuevo más tarde."));
  6255.             } else {
  6256.                 return new JsonResponse(array('status' => 'error''message' => "No existe este ID en el estado de fuerza, consulte con el administrador del sistema."));  
  6257.             }            
  6258.         }
  6259.         return new JsonResponse(array('status' => 'error''message' => "No se pudo realizar la consulta en este momento, intente de nuevo más tarde."));
  6260.     }  
  6261.     
  6262.            
  6263.     /**
  6264.      * @Route("/overtime-get-motivos", name="overtime-get-motivos", methods={"GET", "POST"})
  6265.      */
  6266.     public function getMotivos(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  6267.     {
  6268.         
  6269.         $data json_decode(file_get_contents("php://input"));             
  6270.         if($data)
  6271.         {               
  6272.             $result $helperService->externalDb_getHexMotivos();
  6273.             if($result)
  6274.             {
  6275.                 return new JsonResponse(array('status' => 'success''data' => $result));
  6276.             } 
  6277.             return new JsonResponse(array('status' => 'error''message' => "No se pudo realizar la consulta en este momento, intente de nuevo más tarde."));
  6278.         }
  6279.         return new JsonResponse(array('status' => 'error''message' => "No se pudo realizar la consulta en este momento, intente de nuevo más tarde."));
  6280.     }  
  6281.     /**
  6282.      * @Route("/get-shifts-available-supervisor", name="get-shifts-available-supervisor", methods={"GET", "POST"})
  6283.      */
  6284.     public function shiftsAvailableSupervisor(Request $requestEntityManagerInterface $entityManager): Response
  6285.     {
  6286.         
  6287.         $data json_decode(file_get_contents("php://input"));             
  6288.         if($data)
  6289.         {   
  6290.             $eid  $data->eid;  
  6291.             $shiftsAvailable $entityManager->getRepository(Shift::class)->getShiftsAvailableSupervisor($eid);
  6292.             $arr = [];
  6293.             foreach($shiftsAvailable as $shift)
  6294.             {
  6295.                 $arr[] = [
  6296.                     "shift_id"          => $shift['shift_id'],
  6297.                     "location_id"       => $shift['location_id'],
  6298.                     "project_id"        => $shift['project_id'],
  6299.                     "location_name"     => $shift['location_name'], 
  6300.                     "project_name"      => $shift['project_name'],                    
  6301.                     "date_from"         => $shift['date_from'],
  6302.                     "date_to"           => $shift['date_to']                    
  6303.                 ];
  6304.             }
  6305.             return new JsonResponse(array('status' => 'success''data' => $arr));
  6306.         }
  6307.         return new JsonResponse(array('status' => 'error'));
  6308.     }
  6309.    /**
  6310.      * @Route("/supervisor-agent-set-get", name="supervisor-agent-set-get", methods={"GET", "POST"})
  6311.      */
  6312.     public function supervisorAgentSetGet(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  6313.     {
  6314.         
  6315.         $tracking "";
  6316.         $data json_decode(file_get_contents("php://input"));             
  6317.         if($data)
  6318.         {   
  6319.                         
  6320.             $type $data->type;
  6321.             if($type == 'get')
  6322.             {
  6323.                 $employeeId        $data->employee_id;
  6324.                 $supervisionId     $data->supervision_id;
  6325.                 $supervisionEmployeeObj $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  6326.                     'Supervision' => $supervisionId,
  6327.                     'Employee'    => $employeeId
  6328.                 ]);
  6329.                 
  6330.                 $data = [
  6331.                     'is_present'           => '',
  6332.                     'coverage_employee_id' => '',
  6333.                     'absence_reason'       => '',
  6334.                     'asu_absence'          => '',
  6335.                     'absence_description'  => '',
  6336.                     'is_present_comment'   => ''
  6337.                 ];
  6338.                 
  6339.                 if($supervisionEmployeeObj)
  6340.                 {
  6341.                     $coverageEmployee '';
  6342.                     $isPresent '';                    
  6343.                     if($supervisionEmployeeObj->getIsPresent() == "1")
  6344.                     {
  6345.                         $isPresent 'yes';                        
  6346.                     } 
  6347.                     if($supervisionEmployeeObj->getIsPresent() == "0")
  6348.                     {
  6349.                         $isPresent 'no';
  6350.                         $coverageEmployee = ($supervisionEmployeeObj->getCoverageEmployeeId() ? $supervisionEmployeeObj->getCoverageEmployeeId()->getEmployeeId() : '');
  6351.                     }
  6352.                     
  6353.                     
  6354.                     $data = [
  6355.                         'is_present'           => $isPresent,
  6356.                         'coverage_employee_id' => $coverageEmployee,
  6357.                         'absence_reason'       => $supervisionEmployeeObj->getAbsenceReason(),
  6358.                         'absence_description'  => $supervisionEmployeeObj->getAbsenceDescription(),
  6359.                         'asu_absence'          => $supervisionEmployeeObj->getAsuAbsence(),
  6360.                         'is_present_comment'   => $supervisionEmployeeObj->getIsPresentComment()
  6361.                    ];
  6362.                 }
  6363.                 return new JsonResponse(array('status' => 'success''data' => $data));                
  6364.             } else {
  6365.                 $tracking .= "1";
  6366.                 $isPresent          $data->is_present;  
  6367.                 $absenceReason      $data->absence_reason;
  6368.                 $absenceDescription $data->absence_description;
  6369.                 $asuAbsence         $data->asu_absence;
  6370.                 $employeeId         $data->employee_id;
  6371.                 $supervisionId      $data->supervision_id;
  6372.                 $creatorEmployeeId  $data->creator_employee_id;
  6373.                 $selectedEmployee   $data->selected_employee;
  6374.                 $is_present_comment $data->is_present_comment;
  6375.                 if($isPresent == 'yes')
  6376.                 {
  6377.                     $isPresent 1;
  6378.                 } else {
  6379.                     $isPresent 0;                                        
  6380.                 }
  6381.                 $supervisionObj $entityManager->getRepository(Supervision::class)->findOneBy([
  6382.                     'supervisionId' => $supervisionId
  6383.                 ]);
  6384.                 if($supervisionObj)
  6385.                 {
  6386.                     $tracking .= "2";
  6387.                     $supervisionEmployeeObj $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  6388.                         'Supervision' => $supervisionId,
  6389.                         'Employee'    => $employeeId
  6390.                     ]);                     
  6391.                     $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  6392.                         'employeeId'    => $creatorEmployeeId
  6393.                     ]);
  6394.                     if($supervisionEmployeeObj)
  6395.                     {       
  6396.                         $tracking .= "3";
  6397.                         $selectedEmployeeObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  6398.                             'employeeId'    => $selectedEmployee
  6399.                         ]);
  6400.                         
  6401.                         $supervisionEmployeeObj->setIsPresentComment($is_present_comment);
  6402.                         $supervisionEmployeeObj->setIsPresent($isPresent);
  6403.                         $supervisionEmployeeObj->setCoverageEmployeeId($selectedEmployeeObj);
  6404.                         $supervisionEmployeeObj->setAbsenceReason($absenceReason);
  6405.                         $supervisionEmployeeObj->setAbsenceDescription($absenceDescription);
  6406.                         $supervisionEmployeeObj->setAsuAbsence($asuAbsence);
  6407.                         $supervisionEmployeeObj->setIsActive(1);            
  6408.                         $supervisionEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  6409.                         $entityManager->persist($supervisionEmployeeObj);
  6410.                         $entityManager->flush();
  6411.                     } else {
  6412.                         $tracking .= "4";
  6413.                         $selectedEmployeeObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  6414.                             'employeeId'    => $selectedEmployee
  6415.                         ]);
  6416.                         
  6417.                         $agentObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  6418.                             'employeeId'    => $employeeId
  6419.                         ]);                                                
  6420.                         $supervisionEmployeeObj = new SupervisionEmployee();
  6421.                         if($selectedEmployeeObj)
  6422.                         {
  6423.                             $supervisionEmployeeObj->setCoverageEmployee($selectedEmployeeObj);
  6424.                         }
  6425.                         $supervisionEmployeeObj->setSupervision($supervisionObj);
  6426.                         $supervisionEmployeeObj->setEmployee($agentObj);
  6427.                         $supervisionEmployeeObj->setIsPresentComment($is_present_comment);
  6428.                         $supervisionEmployeeObj->setIsPresent($isPresent);
  6429.                         $supervisionEmployeeObj->setAbsenceReason($absenceReason);
  6430.                         $supervisionEmployeeObj->setAbsenceDescription($absenceDescription);
  6431.                         $supervisionEmployeeObj->setAsuAbsence($asuAbsence);
  6432.                         $supervisionEmployeeObj->setIsActive(1);
  6433.                         $supervisionEmployeeObj->setCreatedAt(new \DateTime());
  6434.                         $supervisionEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  6435.                         $entityManager->persist($supervisionEmployeeObj);
  6436.                         $entityManager->flush();
  6437.                         $tracking .= "5";
  6438.                     }
  6439.                     // ------------------------------------------------------------------------------------ 
  6440.                     // ------  SI NO ESTA PRESENTE, SE DEBE DE CREAR UNA AUSENCIA EN EL SISTEMA EXTERNO
  6441.                     // ------ 
  6442.                     if($isPresent == 0)
  6443.                     {
  6444.                         if($supervisionEmployeeObj->getEmployee()->getAlias())
  6445.                         {
  6446.                             $idEstadoDeFuerza $supervisionEmployeeObj->getEmployee()->getAlias();
  6447.                             if($helperService->externalDb_checkIdEstadoDeFuerza($idEstadoDeFuerza))
  6448.                             {
  6449.                                 $idPuesto $supervisionEmployeeObj->getSupervision()->getLocation()->getIdPuesto();
  6450.                                 if($idPuesto)
  6451.                                 {
  6452.                                     if($helperService->externalDb_checkIdPuesto($idPuesto))
  6453.                                     {
  6454.                                         $supervisorName $supervisorObj->getName();
  6455.                                         if($helperService->externalDb_insertBiAusencias($idEstadoDeFuerza$idPuesto$asuAbsence$absenceReason$absenceDescription$supervisionEmployeeObj->getSupervisionEmployeeId(), $supervisorName))
  6456.                                         {
  6457.                                             $msg 'OK: Se guardo en BI_AUSENCIAS: '.$supervisionEmployeeObj->getSupervisionEmployeeId();
  6458.                                             $this->saveSyncLog('supervisor-agent-set-get'$msg);
  6459.                                         } else {
  6460.                                             $locationId $supervisionEmployeeObj->getSupervision()->getLocation()->getLocationId();
  6461.                                             $msg 'No se pudo guardar en BI_AUSENCIAS: '.$supervisionEmployeeObj->getSupervisionEmployeeId()." ($idEstadoDeFuerza$idPuesto -".$locationId."-, $asuAbsence$absenceReason$absenceDescription, ".$supervisionEmployeeObj->getSupervisionEmployeeId().", $supervisorName)";
  6462.                                             $this->saveSyncLog('supervisor-agent-set-get'$msg);
  6463.                                         };
  6464.                                     } else{
  6465.                                         $msg 'No se encontro el IdPuesto '.$idPuesto.' (Location Id: '.$supervisionEmployeeObj->getSupervision()->getLocation()->getLocationId().') en el sistema externo';
  6466.                                         $this->saveSyncLog('supervisor-agent-set-get'$msg);
  6467.                                     };
  6468.                                 } else {
  6469.                                     $msg 'No hay IdPuesto (Location Id: '.$supervisionEmployeeObj->getSupervision()->getLocation()->getLocationId().') en el sistema externo';
  6470.                                     $this->saveSyncLog('supervisor-agent-set-get'$msg);
  6471.                                 }
  6472.                             } else {
  6473.                                 $msg 'No se encontro el IdEstadoDeFuerza '.$idEstadoDeFuerza.' ('.$supervisionEmployeeObj->getEmployee()->getName().') en el sistema externo';
  6474.                                 $this->saveSyncLog('supervisor-agent-set-get'$msg);
  6475.                             }
  6476.                         } else {
  6477.                             $this->saveSyncLog('supervisor-agent-set-get''No existe el campo ALIAS');
  6478.                         }
  6479.                     } 
  6480.                     // ------------------------------------------------------------------------------------
  6481.                 
  6482.                     $tracking .= "6";
  6483.                     return new JsonResponse(array('status' => 'success'));
  6484.                 }        
  6485.             }    
  6486.             
  6487.         }
  6488.         return new JsonResponse(array('status' => 'error''tracking' => $tracking));
  6489.     }
  6490.     public function saveSyncLog($name$detail)
  6491.     {
  6492.         $entityManager $this->getDoctrine()->getManager();
  6493.         $syncLog = new SyncLog();
  6494.         $syncLog->setName($name);
  6495.         $syncLog->setDetail($detail);
  6496.         $syncLog->setCreatedAt(new \DateTime());
  6497.         $entityManager->persist($syncLog);
  6498.         $entityManager->flush();
  6499.         return true;
  6500.     }
  6501.     /**
  6502.      * @Route("/supervisor-agent-inventory-set-get", name="supervisor-agent-inventory-set-get", methods={"GET", "POST"})
  6503.      */
  6504.     public function supervisorInventoryAgentSetGet(Request $requestEntityManagerInterface $entityManager): Response
  6505.     {
  6506.         
  6507.         $data json_decode(file_get_contents("php://input"));             
  6508.         if($data)
  6509.         {   
  6510.             
  6511.             $type $data->type;
  6512.             if($type == 'get')
  6513.             {
  6514.                 $employeeId        $data->employee_id;
  6515.                 $supervisionId     $data->supervision_id;
  6516.                 $supervisionEmployeeObj $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  6517.                     'Supervision' => $supervisionId,
  6518.                     'Employee'    => $employeeId
  6519.                 ]);
  6520.                 
  6521.                 $data = [
  6522.                     'inventory_weapon' => '',
  6523.                     'inventory_phone'  => '',
  6524.                     'inventory_radio'  => ''
  6525.                 ];
  6526.                 
  6527.                 /*$supervisionEmployeeObj->setInventoryWeaponServer($weapon_serial_server);
  6528.                 $supervisionEmployeeObj->setWeaponMismatch($serial_mismatch);
  6529.                 $supervisionEmployeeObj->setWeaponMismatchComment($weapon_mismatch_comment*/
  6530.                 if($supervisionEmployeeObj)
  6531.                 {                                       
  6532.                     $data = [
  6533.                         'weapon_mismatch'          => $supervisionEmployeeObj->getWeaponMismatch(),
  6534.                         'weapon_mismatch_comment'  => $supervisionEmployeeObj->getWeaponMismatchComment(),
  6535.                         'inventory_weapon'         => $supervisionEmployeeObj->getInventoryWeapon(),
  6536.                         'inventory_phone'          => $supervisionEmployeeObj->getInventoryPhone(),
  6537.                         'inventory_radio'          => $supervisionEmployeeObj->getInventoryRadio()
  6538.                     ];
  6539.                 }
  6540.                 return new JsonResponse(array('status' => 'success''data' => $data));                
  6541.             } else {
  6542.                 $weaponSerial                 $data->weapon_serial
  6543.                 $weapon_serial_server         $data->weapon_serial_server;   
  6544.                 $phoneNumber                  $data->phone_number;
  6545.                 $radioSerial                  $data->radio_serial;
  6546.                 $employeeId                   $data->employee_id;
  6547.                 $supervisionId                $data->supervision_id;
  6548.                 $creatorEmployeeId            $data->creator_employee_id;
  6549.                 
  6550.                 $serial_mismatch false;
  6551.                 if(isset($data->serial_mismatch)){
  6552.                   $serial_mismatch              $data->serial_mismatch;  
  6553.                 }
  6554.                 $weapon_mismatch_comment "";
  6555.                 if(isset($data->mismatch_comment)){
  6556.                     $weapon_mismatch_comment      $data->mismatch_comment;  
  6557.                 }
  6558.                 
  6559.                 $supervisionObj $entityManager->getRepository(Supervision::class)->findOneBy([
  6560.                     'supervisionId' => $supervisionId
  6561.                 ]);
  6562.                 if($supervisionObj)
  6563.                 {
  6564.                     $supervisionEmployeeObj $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  6565.                         'Supervision' => $supervisionId,
  6566.                         'Employee'    => $employeeId
  6567.                     ]);                     
  6568.                     $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  6569.                         'employeeId'    => $creatorEmployeeId
  6570.                     ]);
  6571.                     if($supervisionEmployeeObj)
  6572.                     {       
  6573.                         $supervisionEmployeeObj->setInventoryWeapon($weaponSerial);
  6574.                         $supervisionEmployeeObj->setInventoryWeaponServer($weapon_serial_server);
  6575.                         $supervisionEmployeeObj->setWeaponMismatch($serial_mismatch);
  6576.                         $supervisionEmployeeObj->setWeaponMismatchComment($weapon_mismatch_comment);
  6577.                         $supervisionEmployeeObj->setInventoryRadio($radioSerial);
  6578.                         $supervisionEmployeeObj->setInventoryPhone($phoneNumber);                                                          
  6579.                         $entityManager->persist($supervisionEmployeeObj);
  6580.                         $entityManager->flush();
  6581.                     } else {
  6582.                         $agentObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  6583.                             'employeeId'    => $employeeId
  6584.                         ]);                                                
  6585.                         $supervisionEmployeeObj = new SupervisionEmployee();
  6586.                         $supervisionEmployeeObj->setSupervision($supervisionObj);
  6587.                         $supervisionEmployeeObj->setEmployee($agentObj);
  6588.                         $supervisionEmployeeObj->setInventoryWeapon($weaponSerial);
  6589.                         $supervisionEmployeeObj->setInventoryRadio($radioSerial);
  6590.                         $supervisionEmployeeObj->setInventoryWeaponServer($weapon_serial_server);
  6591.                         $supervisionEmployeeObj->setWeaponMismatch($serial_mismatch);
  6592.                         $supervisionEmployeeObj->setWeaponMismatchComment($weapon_mismatch_comment);
  6593.                         $supervisionEmployeeObj->setInventoryPhone($phoneNumber);
  6594.                         $supervisionEmployeeObj->setIsActive(1);
  6595.                         $supervisionEmployeeObj->setCreatedAt(new \DateTime());
  6596.                         $supervisionEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  6597.                         $entityManager->persist($supervisionEmployeeObj);
  6598.                         $entityManager->flush();
  6599.                     }
  6600.                     
  6601.                     if($serial_mismatch === true   ){
  6602.                       $this->createSupervisionTicket($supervisionEmployeeObj,   "ERROR ASIGNACIÓN" ,  "WEAPON" $weaponSerial ,  array(),  array(),  "Supervisor indico que existen datos incorrectos, Arma asignada no corresponde. Arma reportada $weaponSerial ($weapon_serial_server Externo)."$supervisorObj  );
  6603.                     }else if( $weaponSerial != $weapon_serial_server  ){
  6604.                       $this->createSupervisionTicket($supervisionEmployeeObj,   "ERROR ASIGNACIÓN" ,  "WEAPON" $weaponSerial ,  array(),  array(),  "Arma asignada no corresponde. Arma reportada $weaponSerial ($weapon_serial_server Externo)."$supervisorObj  );
  6605.                     }
  6606.                     
  6607.                     
  6608.                     
  6609.                     
  6610.                     return new JsonResponse(array('status' => 'success'));
  6611.                 }        
  6612.             }    
  6613.             
  6614.         }
  6615.         return new JsonResponse(array('status' => 'error'));
  6616.     }
  6617.     function createSupervisionTicket($supervisionEmployee = array(), $ticketType "" $supervisionType "" $control_number "" $correctEmployee = array(), $correctLocation = array(), $error_description ""$createdBy = array() ){
  6618.         
  6619.         
  6620.         $supervisionTicket = new SupervisionTicket();
  6621.         $supervisionTicket->setSupervision($supervisionEmployee->getSupervision());
  6622.         $supervisionTicket->setSupervisionEmployee($supervisionEmployee);
  6623.         $supervisionTicket->setTicketType($ticketType);
  6624.         $supervisionTicket->setSupervisionType($supervisionType);
  6625.         $supervisionTicket->setControlNumber($control_number);
  6626.         if($correctEmployee){
  6627.             $supervisionTicket->setCorrectEmployee($correctEmployee);
  6628.         }
  6629.         if($correctLocation){
  6630.             $supervisionTicket->setCorrectLocation($correctLocation);
  6631.         }
  6632.         $supervisionTicket->setErrorDescription($error_description);
  6633.         $supervisionTicket->setIsActive(1);
  6634.         $supervisionTicket->setCreatedAt(new \DateTime());
  6635.         if($createdBy){
  6636.             $supervisionTicket->setCreatedByEmployee($createdBy);
  6637.         }
  6638.         $this->entityManager->persist($supervisionTicket);
  6639.         $this->entityManager->flush();
  6640.     
  6641.         
  6642.     }
  6643.     
  6644.     
  6645.     /**
  6646.      * @Route("/supervisor-presentation-set-get", name="supervisor-presentation-set-get", methods={"GET", "POST"})
  6647.      */
  6648.     public function supervisorPresentationSetGet(Request $requestEntityManagerInterface $entityManager): Response
  6649.     {
  6650.         
  6651.         $data json_decode(file_get_contents("php://input"));             
  6652.         if($data)
  6653.         {   
  6654.             
  6655.             $type $data->type;
  6656.             if($type == 'get')
  6657.             {
  6658.                 $employeeId        $data->employee_id;
  6659.                 $supervisionId     $data->supervision_id;
  6660.                 $supervisionEmployeeObj $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  6661.                     'Supervision' => $supervisionId,
  6662.                     'Employee'    => $employeeId
  6663.                 ]);
  6664.                 
  6665.                 $arr   = [];
  6666.                 $arr[] = ['val' => 'Botas''isChecked' => false];
  6667.                 $arr[] = ['val' => 'Camisa''isChecked' => false];
  6668.                 $arr[] = ['val' => 'Pantalon''isChecked' => false];
  6669.                 $arr[] = ['val' => 'Gorra''isChecked' => false];
  6670.                 $arr[] = ['val' => 'Implementos''isChecked' => false];   
  6671.                 
  6672.                 $data = [
  6673.                     'is_presentable'      => '',
  6674.                     'presentation_aspect' => '',
  6675.                     'requires_change'     => json_encode($arr)
  6676.                 ];
  6677.                 
  6678.                 if($supervisionEmployeeObj)
  6679.                 {                                     
  6680.                     $newArr = [];
  6681.                     $changeList explode(",",$supervisionEmployeeObj->getRequiresChange());
  6682.                     foreach($arr as $uniformCheck)
  6683.                     {
  6684.                         if(in_array($uniformCheck['val'], $changeList))
  6685.                         {
  6686.                             $newArr[] = ['val' => $uniformCheck['val'], 'isChecked' => true];                            
  6687.                         } else {
  6688.                             $newArr[] = ['val' => $uniformCheck['val'], 'isChecked' => false];
  6689.                         }
  6690.                     }
  6691.                     
  6692.                     $isPresentable "";
  6693.                     if($supervisionEmployeeObj->getIsPresentable() == "1")
  6694.                     {
  6695.                         $isPresentable 'correct';
  6696.                     }
  6697.                     if($supervisionEmployeeObj->getIsPresentable() == "0")
  6698.                     {
  6699.                         $isPresentable 'incorrect';
  6700.                     }
  6701.                     
  6702.                     $data = [
  6703.                         'is_presentable'      => $isPresentable,
  6704.                         'presentation_aspect' => $supervisionEmployeeObj->getPresentationAspect(),
  6705.                         'requires_change'     => json_encode($newArr)
  6706.                     ];
  6707.                 }
  6708.                 return new JsonResponse(array('status' => 'success''data' => $data));                
  6709.             } else {
  6710.                 $isPresentable       $data->is_presentable;  
  6711.                 $presentationAspect  $data->presentation_aspect;
  6712.                 $requires_change     $data->requires_change;
  6713.                 $employeeId          $data->employee_id;
  6714.                 $supervisionId       $data->supervision_id;
  6715.                 $creatorEmployeeId   $data->creator_employee_id;
  6716.                 
  6717.                 if($isPresentable == 'correct')
  6718.                 {
  6719.                     $isPresentable 1;
  6720.                 } else {
  6721.                     $isPresentable 0;
  6722.                 }
  6723.                 $supervisionObj $entityManager->getRepository(Supervision::class)->findOneBy([
  6724.                     'supervisionId' => $supervisionId
  6725.                 ]);
  6726.                 if($supervisionObj)
  6727.                 {
  6728.                     $supervisionEmployeeObj $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  6729.                         'Supervision' => $supervisionId,
  6730.                         'Employee'    => $employeeId
  6731.                     ]);                     
  6732.                     $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  6733.                         'employeeId'    => $creatorEmployeeId
  6734.                     ]);
  6735.                     $requires_change_final = [];
  6736.                     foreach($requires_change as $uniform)
  6737.                     {
  6738.                         if($uniform->isChecked)
  6739.                         {
  6740.                            $requires_change_final[] = $uniform->val;     
  6741.                         }
  6742.                     }
  6743.                     if($supervisionEmployeeObj)
  6744.                     {       
  6745.                         $supervisionEmployeeObj->setIsPresentable($isPresentable);
  6746.                         $supervisionEmployeeObj->setPresentationAspect($presentationAspect); 
  6747.                         $supervisionEmployeeObj->setRequiresChange(implode(","$requires_change_final));                                        
  6748.                         $supervisionEmployeeObj->setIsActive(1);            
  6749.                         $supervisionEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  6750.                         $entityManager->persist($supervisionEmployeeObj);
  6751.                         $entityManager->flush();
  6752.                     } else {
  6753.                         $agentObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  6754.                             'employeeId'    => $employeeId
  6755.                         ]);                                                
  6756.                         $supervisionEmployeeObj = new SupervisionEmployee();
  6757.                         $supervisionEmployeeObj->setSupervision($supervisionObj);
  6758.                         $supervisionEmployeeObj->setEmployee($agentObj);
  6759.                         $supervisionEmployeeObj->setIsPresentable($isPresentable);
  6760.                         $supervisionEmployeeObj->setPresentationAspect($presentationAspect); 
  6761.                         $supervisionEmployeeObj->setRequiresChange(implode(","$requires_change_final));
  6762.                         $supervisionEmployeeObj->setIsActive(1);
  6763.                         $supervisionEmployeeObj->setCreatedAt(new \DateTime());
  6764.                         $supervisionEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  6765.                         $entityManager->persist($supervisionEmployeeObj);
  6766.                         $entityManager->flush();
  6767.                     }
  6768.                     return new JsonResponse(array('status' => 'success'));
  6769.                 }        
  6770.             }    
  6771.             
  6772.         }
  6773.         return new JsonResponse(array('status' => 'error'));
  6774.     }    
  6775.     /**
  6776.      * @Route("/supervisor-facility-set-get", name="supervisor-facility-set-get", methods={"GET", "POST"})
  6777.      */
  6778.     public function supervisorFacilitySetGet(Request $requestEntityManagerInterface $entityManager): Response
  6779.     {
  6780.         
  6781.         $data json_decode(file_get_contents("php://input"));             
  6782.         if($data)
  6783.         {   
  6784.             
  6785.             $type $data->type;
  6786.             if($type == 'get')
  6787.             {
  6788.                 $locationId       $data->location_id;
  6789.                 $supervisionId    $data->supervision_id;                
  6790.                 $supervisionFacilityObj $entityManager->getRepository(SupervisionFacility::class)->findOneBy([
  6791.                     'Supervision' => $supervisionId,
  6792.                     'Location'    => $locationId
  6793.                 ]);
  6794.                 
  6795.                 $arr   = [];
  6796.                 $arr[] = ['val' => 'Limpieza en Puesto''isChecked' => false];
  6797.                 $arr[] = ['val' => 'Estado de Mobiliario''isChecked' => false];
  6798.                 $arr[] = ['val' => 'No cuenta con Procedimiento''isChecked' => false];
  6799.                 $arr[] = ['val' => 'No cuenta con Sanitario''isChecked' => false];
  6800.                 $arr[] = ['val' => 'No cuenta con Ventilación''isChecked' => false];   
  6801.                 
  6802.                 $data = [
  6803.                     'facility_status'           => '',                    
  6804.                     'facility_requires_change'  => json_encode($arr)
  6805.                 ];
  6806.                 
  6807.                 if($supervisionFacilityObj)
  6808.                 {                                     
  6809.                     $newArr = [];
  6810.                     $changeList explode(",",$supervisionFacilityObj->getFacilityRequiresChange());
  6811.                     foreach($arr as $uniformCheck)
  6812.                     {
  6813.                         if(in_array($uniformCheck['val'], $changeList))
  6814.                         {
  6815.                             $newArr[] = ['val' => $uniformCheck['val'], 'isChecked' => true];                            
  6816.                         } else {
  6817.                             $newArr[] = ['val' => $uniformCheck['val'], 'isChecked' => false];
  6818.                         }
  6819.                     }
  6820.                     $facilityStatus '';
  6821.                     if($supervisionFacilityObj->getFacilityStatus() == "1")
  6822.                     {
  6823.                         $facilityStatus 'correct';
  6824.                     }
  6825.                     if($supervisionFacilityObj->getFacilityStatus() == "0")
  6826.                     {
  6827.                         $facilityStatus 'incorrect';
  6828.                     }
  6829.                     $data = [
  6830.                         'facility_status'           => $facilityStatus,   
  6831.                         'facility_requires_change'  => json_encode($newArr)
  6832.                     ];
  6833.                 }
  6834.                 return new JsonResponse(array('status' => 'success''data' => $data));                
  6835.             } else {
  6836.                 $facilityStatus           $data->facility_status;                  
  6837.                 $facility_requires_change $data->facility_requires_change;
  6838.                 $locationId               $data->location_id;
  6839.                 $supervisionId            $data->supervision_id;
  6840.                 $creatorEmployeeId        $data->creator_employee_id;
  6841.                 //$shiftId                = $data->shift_id;
  6842.                 
  6843.                 if($facilityStatus == 'correct')
  6844.                 {
  6845.                     $facilityStatus 1;
  6846.                 } else {
  6847.                     $facilityStatus 0;
  6848.                 }
  6849.                 /*$shiftObj = $entityManager->getRepository(Shift::class)->findOneBy([
  6850.                     'shiftId' => $shiftId
  6851.                 ]);*/
  6852.                 
  6853.                 $supervisionObj $entityManager->getRepository(Supervision::class)->findOneBy([
  6854.                     'supervisionId' => $supervisionId
  6855.                 ]);
  6856.                 if($supervisionObj)
  6857.                 {
  6858.                     $supervisionFacilityObj $entityManager->getRepository(SupervisionFacility::class)->findOneBy([
  6859.                         'Supervision' => $supervisionId,
  6860.                         'Location'    => $locationId
  6861.                     ]);    
  6862.                     
  6863.                     $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  6864.                         'employeeId'    => $creatorEmployeeId
  6865.                     ]);
  6866.                     
  6867.                     $requires_change_final = [];
  6868.                     foreach($facility_requires_change as $uniform)
  6869.                     {
  6870.                         if($uniform->isChecked)
  6871.                         {
  6872.                            $requires_change_final[] = $uniform->val;     
  6873.                         }
  6874.                     }
  6875.                     if($supervisionFacilityObj)
  6876.                     {       
  6877.                         $supervisionFacilityObj->setFacilityStatus($facilityStatus);                        
  6878.                         $supervisionFacilityObj->setFacilityRequiresChange(implode(","$requires_change_final));                                        
  6879.                         $supervisionFacilityObj->setIsActive(1);       
  6880.                         //$supervisionFacilityObj->setShift($shiftObj); 
  6881.                         $supervisionFacilityObj->setCreatedByEmployeeId($supervisorObj);
  6882.                         $entityManager->persist($supervisionFacilityObj);
  6883.                         $entityManager->flush();
  6884.                     } else {
  6885.                         $supervisionFacilityObj = new SupervisionFacility();
  6886.                         $supervisionFacilityObj->setSupervision($supervisionObj);
  6887.                         $supervisionFacilityObj->setLocation($supervisionObj->getLocation());                                                
  6888.                         $supervisionFacilityObj->setFacilityStatus($facilityStatus);                                                
  6889.                         $supervisionFacilityObj->setFacilityRequiresChange(implode(","$requires_change_final));
  6890.                         $supervisionFacilityObj->setIsActive(1);
  6891.                         //$supervisionFacilityObj->setShift($shiftObj);
  6892.                         $supervisionFacilityObj->setCreatedAt(new \DateTime());
  6893.                         $supervisionFacilityObj->setCreatedByEmployeeId($supervisorObj);
  6894.                         $entityManager->persist($supervisionFacilityObj);
  6895.                         $entityManager->flush();
  6896.                     }
  6897.                     return new JsonResponse(array('status' => 'success'));
  6898.                 }        
  6899.             }    
  6900.             
  6901.         }
  6902.         return new JsonResponse(array('status' => 'error'));
  6903.     } 
  6904.   
  6905.     /**
  6906.      * @Route("/supervision-comments-set-get", name="supervision-comments-set-get", methods={"GET", "POST"})
  6907.      */
  6908.     public function supervisionCommentsSetGet(Request $requestEntityManagerInterface $entityManager): Response
  6909.     {
  6910.         
  6911.         $data json_decode(file_get_contents("php://input"));             
  6912.         if($data)
  6913.         {   
  6914.             
  6915.             $type          $data->type;
  6916.             $commentType   $data->comment_type;
  6917.             $comments      $data->comments;
  6918.             $supervisionId $data->supervision_id;
  6919.             $supervisionObj $entityManager->getRepository(Supervision::class)->findOneBy([
  6920.                 'supervisionId' => $supervisionId
  6921.             ]);
  6922.             if($supervisionObj)
  6923.             {
  6924.                 if($type == 'set')
  6925.                 {
  6926.                     if($commentType == 1)
  6927.                     {
  6928.                         $supervisionObj->setClientComments($comments);
  6929.                     } else {
  6930.                         $supervisionObj->setEventComments($comments);
  6931.                     }
  6932.                     $entityManager->persist($supervisionObj);
  6933.                     $entityManager->flush();
  6934.                     return new JsonResponse(array('status' => 'success''message' => 'Se guardo el comentario correctamente'));
  6935.                 } else {
  6936.                     $commentInfo = [
  6937.                         'client' => $supervisionObj->getClientComments(),
  6938.                         'event'  => $supervisionObj->getEventComments()
  6939.                     ];
  6940.                     return new JsonResponse(array('status' => 'success''data' => $commentInfo));
  6941.                 }    
  6942.             } 
  6943.         }
  6944.         return new JsonResponse(array('status' => 'error''message' => 'No se pueden guardar los comentarios'));
  6945.     }
  6946.     /**
  6947.      * @Route("/upload-json", name="upload-json", methods={"GET", "POST"})
  6948.      */
  6949.     public function uploadJson(Request $requestEntityManagerInterface $entityManager): Response
  6950.     {
  6951.                
  6952.         if ($_SERVER['REQUEST_METHOD'] === 'POST')
  6953.         {
  6954.             // Asegurarse de que el archivo ha sido enviado
  6955.             if (isset($_FILES['fileContent']) && isset($_POST['fileName'])) {
  6956.                 // Obtener el nombre del archivo
  6957.                 $fileName $_POST['fileName'];
  6958.                 $token    json_decode($_POST['data']);
  6959.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([
  6960.                     'employeeId' => $token->employee_id
  6961.                 ]);
  6962.         
  6963.                 // Obtener la ruta temporal del archivo subido
  6964.                 $tempFilePath $_FILES['fileContent']['tmp_name'];
  6965.         
  6966.                 // Leer el contenido del archivo
  6967.                 $fileContent file_get_contents($tempFilePath);
  6968.         
  6969.                 // Decodificar el JSON
  6970.                 $jsonData json_decode($fileContenttrue);
  6971.         
  6972.                 if (json_last_error() === JSON_ERROR_NONE) {
  6973.                     
  6974.                     // Directory where the files will be uploaded
  6975.                     $uploadDirectory 'uploads/json/';
  6976.                     // Check if the directory exists, if not create it
  6977.                     if(!is_dir($uploadDirectory))
  6978.                     {
  6979.                         if(!mkdir($uploadDirectory0777true))
  6980.                         {                            
  6981.                             return new JsonResponse(array('status' => 'error''message' => 'Failed to create upload directory'));
  6982.                         }
  6983.                     }
  6984.                     
  6985.                     $destinationPath $uploadDirectory basename($fileName);    
  6986.                     if(move_uploaded_file($tempFilePath$destinationPath))
  6987.                     {                        
  6988.                         $locationArr explode("_",$fileName);
  6989.                         if($locationArr 0)
  6990.                         {
  6991.                             $locationObj $entityManager->getRepository(Location::class)->findOneBy([
  6992.                                 'locationId' => $locationArr[1]
  6993.                             ]);
  6994.                             $syncControl = new SyncControl();
  6995.                             $syncControl->setName($fileName);
  6996.                             $syncControl->setLocation($locationObj);
  6997.                             $syncControl->setStepNumber(1);
  6998.                             $syncControl->setIsDone(0);
  6999.                             $syncControl->setCreatedAt(new \DateTime());
  7000.                             $syncControl->setCreatedByEmployeeId($employeeObj);
  7001.                             $entityManager->persist($syncControl);
  7002.                             $entityManager->flush();
  7003.                             //$return = $this->startSync($syncControl->getSyncControlId(), $entityManager);
  7004.                             //return new JsonResponse(array('status' => 'error', 'data' => $return));
  7005.                             if($this->startSync($syncControl->getSyncControlId(), $entityManager))
  7006.                             {
  7007.                                 return new JsonResponse(array('status' => 'success''message' => 'File processed successfully'));
  7008.                             } else {
  7009.                                 return new JsonResponse(array('status' => 'error''message' => 'File could not be processed'));
  7010.                             }
  7011.                             
  7012.                         } else {                          
  7013.                             return new JsonResponse(array('status' => 'error''message' => 'Failed to move uploaded file'));
  7014.                             
  7015.                         }
  7016.                         
  7017.                     } else {                        
  7018.                         return new JsonResponse(array('status' => 'error''message' => 'Failed to move uploaded file'));                        
  7019.                     }
  7020.                 } else {
  7021.                     
  7022.                     return new JsonResponse(array('status' => 'error''message' => 'Invalid JSON data'));
  7023.                 }
  7024.             } else {
  7025.                 
  7026.                 return new JsonResponse(array('status' => 'error''message' => 'No file or file name provided'));
  7027.             }
  7028.         } else {            
  7029.             return new JsonResponse(array('status' => 'error''message' => 'Invalid request method'));
  7030.         }
  7031.         
  7032.     }    
  7033.     public function startSync($syncId$entityManager)
  7034.     {
  7035.         $syncObj $entityManager->getRepository(SyncControl::class)->findOneBy([
  7036.             'syncControlId' => $syncId
  7037.         ]);
  7038.         $syncObj->setStepNumber(2);
  7039.         $entityManager->persist($syncObj);
  7040.         $entityManager->flush();
  7041.         //Se abre el archivo para leer el resultado
  7042.         $path 'uploads/json/'.$syncObj->getName();
  7043.         
  7044.         if(!file_exists($path))
  7045.         {
  7046.             throw $this->createNotFoundException('El archivo '.$path.' JSON no existe.');
  7047.         }
  7048.         $jsonContent file_get_contents($path);
  7049.         $data        json_decode($jsonContenttrue);
  7050.         
  7051.         if(json_last_error() !== JSON_ERROR_NONE)
  7052.         {
  7053.             throw new \Exception('Error al decodificar el JSON: ' json_last_error_msg());
  7054.         }
  7055.         $facility false;
  7056.         if(isset($data["facility"]))
  7057.         {
  7058.             $facility $data["facility"];
  7059.         }
  7060.         $comments null;
  7061.         if(isset($data["comments"]))
  7062.         {
  7063.             $comments $data["comments"];
  7064.         }
  7065.         $observations null;
  7066.         if(isset($data["observations"]))
  7067.         {
  7068.             $observations $data["observations"];
  7069.         }
  7070.         //Primer paso, se crea una supervisión        
  7071.         $supervision = new Supervision();        
  7072.         $supervision->setProject($syncObj->getLocation()->getProject());
  7073.         $supervision->setLocation($syncObj->getLocation());  
  7074.         $supervision->setClientComments($comments);                
  7075.         $supervision->setEventComments($observations);
  7076.         $supervision->setSyncControl($syncObj);
  7077.         $supervision->setIsActive(1);
  7078.         $supervision->setIsCompleted(1);
  7079.         $supervision->setCreatedAt(new \DateTime());
  7080.         $supervision->setClosedAt(date("Y-m-d H:i:s"));
  7081.         $supervision->setCreatedByEmployeeId($syncObj->getCreatedByEmployeeId());
  7082.         $entityManager->persist($supervision);
  7083.         $entityManager->flush();
  7084.         //Segundo paso, se almacenan los datos de la supervisión para la ubicación
  7085.         $syncObj->setStepNumber(3);
  7086.         $entityManager->persist($syncObj);
  7087.         $entityManager->flush();
  7088.         
  7089.         if($facility)
  7090.         {            
  7091.             $requires_change_final = [];
  7092.             foreach($facility["facility_requires_change"] as $item)
  7093.             {
  7094.                 if($item["isChecked"])
  7095.                 {
  7096.                     $requires_change_final[] = $item["val"];     
  7097.                 }
  7098.             }
  7099.             $supervisionFacilityObj = new SupervisionFacility();
  7100.             $supervisionFacilityObj->setSupervision($supervision);
  7101.             $supervisionFacilityObj->setLocation($syncObj->getLocation());              
  7102.             $supervisionFacilityObj->setFacilityStatus($facility["facility_status"]);                                                
  7103.             $supervisionFacilityObj->setFacilityRequiresChange(implode(","$requires_change_final));
  7104.             $supervisionFacilityObj->setIsActive(1);        
  7105.             $supervisionFacilityObj->setCreatedAt(new \DateTime());
  7106.             $supervisionFacilityObj->setCreatedByEmployeeId($syncObj->getCreatedByEmployeeId());
  7107.             $entityManager->persist($supervisionFacilityObj);
  7108.             $entityManager->flush();
  7109.         }
  7110.         //Cuarto paso, se desactivan de location_employee los empleados que no deberian estar
  7111.         $syncObj->setStepNumber(4);
  7112.         $entityManager->persist($syncObj);
  7113.         $entityManager->flush();
  7114.         $employees = [];
  7115.         if(isset($data["employees"]))
  7116.         {
  7117.             $employees $data["employees"];
  7118.         }
  7119.         $extraEmployees = [];
  7120.         if(isset($data["extra_employees"]))
  7121.         {
  7122.             $extraEmployees $data["extra_employees"];
  7123.         }
  7124.         $employeeIds array_map(function ($employee)
  7125.         {
  7126.             return $employee["employee_id"];
  7127.         }, $employees);
  7128.         // Obtener todos los LocationEmployee
  7129.         $locationEmployees $entityManager->getRepository(LocationEmployee::class)->findBy([
  7130.             'Location'  => $syncObj->getLocation(),
  7131.             'is_active' => 1
  7132.         ]);
  7133.         // Filtrar los empleados que están en LocationEmployee pero no en el listado de employees
  7134.         $employeesNotInList array_filter($locationEmployees, function ($locationEmployee) use ($employeeIds) {            
  7135.                 return !in_array($locationEmployee->getEmployee()->getEmployeeId(), $employeeIds);            
  7136.         });
  7137.         $notInListIds array_map(function ($locationEmployee) {
  7138.             return $locationEmployee->getEmployee()->getEmployeeId();
  7139.         }, $employeesNotInList);
  7140.         foreach($notInListIds as $notInList)
  7141.         {
  7142.             $locationEmployeeCheckObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([                
  7143.                 'Employee'  => $notInList,   
  7144.                 'Location'  => $syncObj->getLocation(),
  7145.                 'is_active' => 1
  7146.             ]);
  7147.             if($locationEmployeeCheckObj)
  7148.             {
  7149.                 //Si no esta en la lista de empleados, se desactiva
  7150.                 $locationEmployeeCheckObj->setIsActive(0);
  7151.                 $locationEmployeeCheckObj->setSyncPending(1);
  7152.                 $locationEmployeeCheckObj->setSyncControl($syncObj);
  7153.                 $locationEmployeeCheckObj->setUpdatedAt(new \Datetime());
  7154.                 $locationEmployeeCheckObj->setUpdatedByEmployeeId($syncObj->getCreatedByEmployeeId());
  7155.                 $entityManager->persist($locationEmployeeCheckObj);
  7156.                 $entityManager->flush();                                    
  7157.             }            
  7158.         }
  7159.         //Quinto paso, se dan de alta / o se actualiza la fecha de los que existen
  7160.         $syncObj->setStepNumber(5);
  7161.         $entityManager->persist($syncObj);
  7162.         $entityManager->flush();
  7163.         $locationPositionObj $entityManager->getRepository(LocationPosition::class)->findOneBy([                
  7164.             'locationPositionId'  => 1            
  7165.         ]);
  7166.         foreach($employees as $employee)
  7167.         {
  7168.             $locationEmployeeCheckObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([                
  7169.                 'Employee'  => $employee["employee_id"], 
  7170.                 "Location"  => $syncObj->getLocation(),    
  7171.                 'is_active' => 1
  7172.             ]);
  7173.             if(!$locationEmployeeCheckObj)
  7174.             {
  7175.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  7176.                     'employeeId'  => $employee["employee_id"]                    
  7177.                 ]);
  7178.                 //Si no esta en la lista de empleados, se agrega
  7179.                 $locationEmployeeCheck = new LocationEmployee();                
  7180.                 $locationEmployeeCheck->setIsActive(1);
  7181.                 $locationEmployeeCheck->setLocationPosition($locationPositionObj);
  7182.                 $locationEmployeeCheck->setLocation($syncObj->getLocation());
  7183.                 $locationEmployeeCheck->setEmployee($employeeObj);
  7184.                 $locationEmployeeCheck->setSyncPending(1);
  7185.                 $locationEmployeeCheck->setSyncControl($syncObj);
  7186.                 $locationEmployeeCheck->setLocation($syncObj->getLocation());
  7187.                 $locationEmployeeCheck->setCreatedAt(new \Datetime());
  7188.                 $locationEmployeeCheck->setCreatedByEmployeeId($syncObj->getCreatedByEmployeeId());
  7189.                 $entityManager->persist($locationEmployeeCheck);
  7190.                 $entityManager->flush();                                    
  7191.             } else {
  7192.                 //Si si existe el registro, se actualiza la fecha para saber que la supervisión confirmo a este empleado
  7193.                 $locationEmployeeCheckObj->setSyncControl($syncObj);
  7194.                 $locationEmployeeCheckObj->setUpdatedAt(new \Datetime());
  7195.                 $locationEmployeeCheckObj->setUpdatedByEmployeeId($syncObj->getCreatedByEmployeeId());
  7196.                 $entityManager->persist($locationEmployeeCheckObj);
  7197.                 $entityManager->flush();      
  7198.             }          
  7199.         }
  7200.         //Paso seis, se ingresa la supervisión de los empleados
  7201.         $syncObj->setStepNumber(6);
  7202.         $syncObj->setIsDone(0);
  7203.         $entityManager->persist($syncObj);
  7204.         $entityManager->flush();
  7205.         foreach($employees as $employee)
  7206.         {
  7207.             $supervisionEmployeeObj $this->processEmployeesSync($employee$entityManager$supervision);
  7208.             //Grabación final            
  7209.             $supervisionEmployeeObj->setIsActive(1);
  7210.             $supervisionEmployeeObj->setCreatedAt(new \DateTime());
  7211.             $supervisionEmployeeObj->setCreatedByEmployeeId($syncObj->getCreatedByEmployeeId());
  7212.             $entityManager->persist($supervisionEmployeeObj);
  7213.             $entityManager->flush();
  7214.         }
  7215.         //Paso siete, se ingresa la supervisión de los empleados extras (Extrero / descansero)
  7216.         $syncObj->setStepNumber(7);
  7217.         $syncObj->setIsDone(1);
  7218.         $entityManager->persist($syncObj);
  7219.         $entityManager->flush();
  7220.         foreach($extraEmployees as $employee)
  7221.         {
  7222.             $supervisionEmployeeObj $this->processEmployeesSync($employee$entityManager$supervision);
  7223.             //Grabación final            
  7224.             $supervisionEmployeeObj->setIsExtra(1);
  7225.             $supervisionEmployeeObj->setExtraType($employee["type"]);
  7226.             $supervisionEmployeeObj->setIsActive(1);
  7227.             $supervisionEmployeeObj->setCreatedAt(new \DateTime());
  7228.             $supervisionEmployeeObj->setCreatedByEmployeeId($syncObj->getCreatedByEmployeeId());
  7229.             $entityManager->persist($supervisionEmployeeObj);
  7230.             $entityManager->flush();
  7231.             // ----------------------------------------------------------------------------------------
  7232.             // Sección de BI_Ausencias
  7233.             // 
  7234.             if($employee["is_present"] == 'yes')
  7235.             {
  7236.                 if($supervisionEmployeeObj->getEmployee()->getAlias())
  7237.                 {
  7238.                     $idEstadoDeFuerza $supervisionEmployeeObj->getEmployee()->getAlias();
  7239.                     if($helperService->externalDb_checkIdEstadoDeFuerza($idEstadoDeFuerza))
  7240.                     {
  7241.                         $idPuesto $supervisionEmployeeObj->getSupervision()->getLocation()->getIdPuesto();
  7242.                         if($idPuesto)
  7243.                         {
  7244.                             if($helperService->externalDb_checkIdPuesto($idPuesto))
  7245.                             {
  7246.                                 $supervisorName $syncObj->getCreatedByEmployeeId()->getName();
  7247.                                 if($helperService->externalDb_insertBiAusencias($idEstadoDeFuerza$idPuesto$employee["asu_absence"], $employee["absence_reason"], $employee["absence_description"], $supervisionEmployeeObj->getSupervisionEmployeeId(), $supervisorName))
  7248.                                 {
  7249.                                     $msg 'OK: Se guardo en BI_AUSENCIAS: '.$supervisionEmployeeObj->getSupervisionEmployeeId();
  7250.                                     $this->saveSyncLog('supervisor-agent-set-get'$msg);
  7251.                                 } else {
  7252.                                     $locationId $supervisionEmployeeObj->getSupervision()->getLocation()->getLocationId();
  7253.                                     $msg 'No se pudo guardar en BI_AUSENCIAS: '.$supervisionEmployeeObj->getSupervisionEmployeeId()." ($idEstadoDeFuerza$idPuesto -".$locationId."-, $asuAbsence$absenceReason$absenceDescription, ".$supervisionEmployeeObj->getSupervisionEmployeeId().", $supervisorName)";
  7254.                                     $this->saveSyncLog('supervisor-agent-set-get'$msg);
  7255.                                 };
  7256.                             } else{
  7257.                                 $msg 'No se encontro el IdPuesto '.$idPuesto.' (Location Id: '.$supervisionEmployeeObj->getSupervision()->getLocation()->getLocationId().') en el sistema externo';
  7258.                                 $this->saveSyncLog('supervisor-agent-set-get'$msg);
  7259.                             };
  7260.                         } else {
  7261.                             $msg 'No hay IdPuesto (Location Id: '.$supervisionEmployeeObj->getSupervision()->getLocation()->getLocationId().') en el sistema externo';
  7262.                             $this->saveSyncLog('supervisor-agent-set-get'$msg);
  7263.                         }
  7264.                     } else {
  7265.                         $msg 'No se encontro el IdEstadoDeFuerza '.$idEstadoDeFuerza.' ('.$supervisionEmployeeObj->getEmployee()->getName().') en el sistema externo';
  7266.                         $this->saveSyncLog('supervisor-agent-set-get'$msg);
  7267.                     }
  7268.                 } else {
  7269.                     $this->saveSyncLog('supervisor-agent-set-get''No existe el campo ALIAS');
  7270.                 }
  7271.             }
  7272.             // ----------------------------------------------------------------------------------------
  7273.         }
  7274.         return true;
  7275.     }
  7276.     public function processEmployeesSync($employee$entityManager$supervision)
  7277.     {
  7278.         $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  7279.             'employeeId'  => $employee["employee_id"]                
  7280.         ]);
  7281.         $supervisionEmployeeObj = new SupervisionEmployee();
  7282.         $supervisionEmployeeObj->setSupervision($supervision);
  7283.         $supervisionEmployeeObj->setEmployee($employeeObj);
  7284.         //Puesto        
  7285.         if(isset($employee["is_present"]) && isset($employee["absence_reason"]) && isset($employee["asu_absence"]) && isset($employee["absence_description"]))
  7286.         {
  7287.             if($employee["is_present"] == 'yes')
  7288.             {
  7289.                 $isPresent 1;
  7290.             } else {
  7291.                 $isPresent 0;                
  7292.             }
  7293.             $supervisionEmployeeObj->setIsPresent($isPresent);
  7294.             $supervisionEmployeeObj->setAbsenceReason($employee["absence_reason"]);
  7295.             $supervisionEmployeeObj->setAbsenceDescription($employee["absence_description"]);
  7296.             $supervisionEmployeeObj->setAsuAbsence($employee["asu_absence"]);
  7297.         }
  7298.         //Presentacion
  7299.         if(isset($employee["is_presentable"]))
  7300.         {
  7301.             if($employee["is_presentable"] == 'correct')
  7302.             {
  7303.                 $isPresentable 1;
  7304.             } else {
  7305.                 $isPresentable 0;
  7306.             }
  7307.             $requires_change_final = [];
  7308.             if(isset($employee["requires_change"]) && isset($employee["presentation_aspect"]))
  7309.             {
  7310.                 foreach($employee["requires_change"] as $uniform)
  7311.                 {
  7312.                     if($uniform["isChecked"])
  7313.                     {
  7314.                         $requires_change_final[] = $uniform["val"];     
  7315.                     }
  7316.                 }
  7317.                 $supervisionEmployeeObj->setRequiresChange(implode(","$requires_change_final));
  7318.             }
  7319.             $supervisionEmployeeObj->setIsPresentable($isPresentable);
  7320.             $supervisionEmployeeObj->setPresentationAspect($employee["presentation_aspect"]); 
  7321.             
  7322.         }
  7323.         //Armamento
  7324.         if(isset($employee["armory_status"]))
  7325.         {
  7326.             if($employee["armory_status"] == 'working')
  7327.             {
  7328.                 $armoryStatus 1;
  7329.             } else {
  7330.                 $armoryStatus 0;
  7331.             }
  7332.             $requires_armory_change_final = [];
  7333.             if(isset($employee["armory_requires_change"]))
  7334.             {
  7335.                 foreach($employee["armory_requires_change"] as $uniform)
  7336.                 {
  7337.                     if($uniform["isChecked"])
  7338.                     {
  7339.                         $requires_armory_change_final[] = $uniform["val"];     
  7340.                     }
  7341.                 }
  7342.                 $supervisionEmployeeObj->setArmoryRequiresChange(implode(","$requires_armory_change_final));
  7343.             }
  7344.             $supervisionEmployeeObj->setArmoryStatus($armoryStatus);                                                                  
  7345.         }
  7346.         //Inventario
  7347.         if(isset($employee["inventory_weapon"]) || isset($employee["inventory_phone"]) || isset($employee["inventory_radio"]))
  7348.         {
  7349.             $weapon "";
  7350.             if($employee["inventory_phone"])
  7351.             {
  7352.                 $weapon $employee["inventory_weapon"];
  7353.             }
  7354.             $phone "";
  7355.             if($employee["inventory_weapon"])
  7356.             {
  7357.                 $phone $employee["inventory_phone"];
  7358.             }
  7359.             $radio "";
  7360.             if($employee["inventory_radio"])
  7361.             {
  7362.                 $radio $employee["inventory_radio"];
  7363.             }
  7364.             $supervisionEmployeeObj->setInventoryWeapon($weapon);
  7365.             $supervisionEmployeeObj->setInventoryPhone($phone);
  7366.             $supervisionEmployeeObj->setInventoryRadio($radio);
  7367.                                                                      
  7368.         }
  7369.         return $supervisionEmployeeObj;
  7370.     }
  7371.     
  7372.     /**
  7373.      * @Route("/supervisor-armory-set-get", name="supervisor-armory-set-get", methods={"GET", "POST"})
  7374.      */
  7375.     public function supervisorArmorySetGet(Request $requestEntityManagerInterface $entityManager): Response
  7376.     {
  7377.         
  7378.         $data json_decode(file_get_contents("php://input"));             
  7379.         if($data)
  7380.         {   
  7381.             
  7382.             $type $data->type;
  7383.             if($type == 'get')
  7384.             {
  7385.                 $employeeId        $data->employee_id;
  7386.                 $supervisionId     $data->supervision_id;
  7387.                 $supervisionEmployeeObj $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  7388.                     'Supervision' => $supervisionId,
  7389.                     'Employee'    => $employeeId
  7390.                 ]);
  7391.                 $arr   = [];
  7392.                 $arr[] = ['val' => 'Reparación Arma''isChecked' => false];
  7393.                 $arr[] = ['val' => 'Reparación Radio''isChecked' => false];
  7394.                 $arr[] = ['val' => 'Reparación Celular''isChecked' => false];
  7395.                 $arr[] = ['val' => 'Estado Sintético''isChecked' => false];
  7396.                 $arr[] = ['val' => 'Portación Vencida''isChecked' => false];   
  7397.                 $arr[] = ['val' => 'No Tiene Portación''isChecked' => false];   
  7398.                 
  7399.                 $data = [
  7400.                     'armory_status'           => '',                    
  7401.                     'armory_requires_change'  => json_encode($arr)
  7402.                 ];
  7403.                 
  7404.                 if($supervisionEmployeeObj)
  7405.                 {                                     
  7406.                     $newArr = [];
  7407.                     $changeList explode(",",$supervisionEmployeeObj->getArmoryRequiresChange());
  7408.                     foreach($arr as $uniformCheck)
  7409.                     {
  7410.                         if(in_array($uniformCheck['val'], $changeList))
  7411.                         {
  7412.                             $newArr[] = ['val' => $uniformCheck['val'], 'isChecked' => true];                            
  7413.                         } else {
  7414.                             $newArr[] = ['val' => $uniformCheck['val'], 'isChecked' => false];
  7415.                         }
  7416.                     }
  7417.                     $armoryStatus "";
  7418.                     if($supervisionEmployeeObj->getArmoryStatus() == "1")
  7419.                     {
  7420.                         $armoryStatus "working";
  7421.                     }
  7422.                     if($supervisionEmployeeObj->getArmoryStatus() == "0")
  7423.                     {
  7424.                         $armoryStatus "fix";
  7425.                     }
  7426.                     $data = [
  7427.                         'armory_status'           => $armoryStatus,   
  7428.                         'armory_requires_change'  => json_encode($newArr)
  7429.                     ];
  7430.                 }
  7431.                 return new JsonResponse(array('status' => 'success''data' => $data));                
  7432.             } else {
  7433.                 $armoryStatus           $data->armory_status;                  
  7434.                 $armory_requires_change $data->armory_requires_change;
  7435.                 $employeeId             $data->employee_id;
  7436.                 $supervisionId          $data->supervision_id;
  7437.                 $creatorEmployeeId      $data->creator_employee_id;
  7438.                 
  7439.                 if($armoryStatus == 'working')
  7440.                 {
  7441.                     $armoryStatus 1;
  7442.                 } else {
  7443.                     $armoryStatus 0;
  7444.                 }
  7445.                 $supervisionObj $entityManager->getRepository(Supervision::class)->findOneBy([
  7446.                     'supervisionId' => $supervisionId
  7447.                 ]);
  7448.                 if($supervisionObj)
  7449.                 {
  7450.                     $supervisionEmployeeObj $entityManager->getRepository(SupervisionEmployee::class)->findOneBy([
  7451.                         'Supervision' => $supervisionId,
  7452.                         'Employee'    => $employeeId
  7453.                     ]);                     
  7454.                     $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  7455.                         'employeeId'    => $creatorEmployeeId
  7456.                     ]);
  7457.                     $requires_change_final = [];
  7458.                     foreach($armory_requires_change as $uniform)
  7459.                     {
  7460.                         if($uniform->isChecked)
  7461.                         {
  7462.                            $requires_change_final[] = $uniform->val;     
  7463.                         }
  7464.                     }
  7465.                     if($supervisionEmployeeObj)
  7466.                     {       
  7467.                         $supervisionEmployeeObj->setArmoryStatus($armoryStatus);                        
  7468.                         $supervisionEmployeeObj->setArmoryRequiresChange(implode(","$requires_change_final));                                        
  7469.                         $supervisionEmployeeObj->setIsActive(1);            
  7470.                         $supervisionEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  7471.                         $entityManager->persist($supervisionEmployeeObj);
  7472.                         $entityManager->flush();
  7473.                     } else {
  7474.                         $agentObj $entityManager->getRepository(Employee::class)->findOneBy([                        
  7475.                             'employeeId'    => $employeeId
  7476.                         ]);                                                
  7477.                         $supervisionEmployeeObj = new SupervisionEmployee();
  7478.                         $supervisionEmployeeObj->setSupervision($supervisionObj);
  7479.                         $supervisionEmployeeObj->setEmployee($agentObj);
  7480.                         $supervisionEmployeeObj->setArmoryStatus($armoryStatus);                                                  
  7481.                         $supervisionEmployeeObj->setArmoryRequiresChange(implode(","$requires_change_final));
  7482.                         $supervisionEmployeeObj->setIsActive(1);
  7483.                         $supervisionEmployeeObj->setCreatedAt(new \DateTime());
  7484.                         $supervisionEmployeeObj->setCreatedByEmployeeId($supervisorObj);
  7485.                         $entityManager->persist($supervisionEmployeeObj);
  7486.                         $entityManager->flush();
  7487.                     }
  7488.                     return new JsonResponse(array('status' => 'success'));
  7489.                 }        
  7490.             }    
  7491.             
  7492.         }
  7493.         return new JsonResponse(array('status' => 'error'));
  7494.     }     
  7495.     /**
  7496.      * @Route("/start-supervision", name="start-supervision", methods={"GET", "POST"})
  7497.      */
  7498.     public function startSupervision(Request $requestEntityManagerInterface $entityManager): Response
  7499.     {
  7500.         
  7501.         $data json_decode(file_get_contents("php://input"));             
  7502.         if($data)
  7503.         {   
  7504.             $eid      $data->eid;              
  7505.             $location_id $data->location_id;
  7506.             $lat      $data->lat;
  7507.             $lng      $data->lng;
  7508.             
  7509.             $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([                
  7510.                 'employeeId'  => $eid
  7511.             ]);  
  7512.             if($supervisorObj)
  7513.             {
  7514.                 $locationObj $entityManager->getRepository(Location::class)->findOneBy([                
  7515.                     'locationId'  => $location_id
  7516.                 ]);    
  7517.                 $array json_decode($locationObj->getPolygonList());
  7518.                 $polygonList = [];
  7519.                 //
  7520.                 // 17 de enero 2024: 
  7521.                 // Si no hay poligono, se ignora todo esto, para impedir que este causando problema
  7522.                 //
  7523.                 if(isset($array->coordinates[0]))
  7524.                 {
  7525.                     foreach($array->coordinates[0] as $item)
  7526.                     {
  7527.                         if(isset($item[0]) && isset($item[1]))
  7528.                         {
  7529.                             $polygonList[] = ['lat' => $item[1], 'lng' => $item[0]];
  7530.                         }
  7531.                     }
  7532.                             
  7533.                     $point = ['lat' => $lat'lng' => $lng];        
  7534.                     $res $this->isInsidePolygon($point$polygonList);
  7535.                     if(!$res)
  7536.                     {
  7537.                         $shiftLog = new ShiftEmployeeLog();                        
  7538.                         $shiftLog->setLocation($locationObj);
  7539.                         $shiftLog->setLat($lat);
  7540.                         $shiftLog->setLng($lng);
  7541.                         $shiftLog->setCreatedAt(new \DateTime());
  7542.                         $shiftLog->setCreatedByEmployeeId($supervisorObj);
  7543.                         $entityManager->persist($shiftLog);
  7544.                         $entityManager->flush(); 
  7545.                         
  7546.                         return new JsonResponse(array('status' => 'error''message' => 'No se puede iniciar el proceso de supervisión porque no se encuentra dentro de la ubicación autorizada para el puesto seleccionado. Si considera que se trata de un error, por favor verifique la conexión a Internet y la función de Geolocalización del dispositivo | '.$shiftLog->getShiftEmployeeLogId()));
  7547.                     }   
  7548.                 }   
  7549.                       
  7550.                 //Parche para ubicar el shift actual
  7551.                 $path $this->getProjectPaths();
  7552.                 $employees = [];
  7553.                 $shiftArray $entityManager->getRepository(Shift::class)->getActiveShifts($location_id);                                
  7554.                 if($shiftArray)
  7555.                 {
  7556.                     $employeesObj $entityManager->getRepository(ShiftEmployee::class)->findBy([                
  7557.                         'Shift'  => $shiftArray['shift_id'],                    
  7558.                         'is_active' => 1
  7559.                     ]);  
  7560.                     $shiftObj $entityManager->getRepository(Shift::class)->findOneBy([                
  7561.                         'shiftId'  => $shiftArray['shift_id']                        
  7562.                     ]);  
  7563.                     
  7564.                     foreach($employeesObj as $item)
  7565.                     {                    
  7566.                         if($item->getEmployee()->getAvatarPath())
  7567.                         {
  7568.                             $avatar $path['public_path'].'uploads/'.$item->getEmployee()->getAvatarPath();
  7569.                         } else {
  7570.                             $avatar $path['public_path'].'assets/img/empty_user.png';
  7571.                         }
  7572.                         $employees[] = [
  7573.                             'employee_id' => $item->getEmployee()->getEmployeeId(),
  7574.                             'name'        => $item->getEmployee()->getName(),
  7575.                             'position'    => $item->getEmployee()->getJobPosition()->getName(),
  7576.                             'avatar'      => $avatar,
  7577.                             'location_position'  => $item->getLocationPosition()->getName(),
  7578.                             'citizen_id'         => $item->getEmployee()->getCitizenId(),
  7579.                             'firearm_credential' => $item->getEmployee()->getFirearmCredential(),
  7580.                             'firearm_expiration' => $item->getEmployee()->getFirearmExpiration()                                                
  7581.                         ];
  7582.                     }
  7583.                 }
  7584.                 //24 DE AGOSTO
  7585.                 //SE SEPARO TOTALMENTE EL PROCESO DE CREACION DE SUPERVISION DE LA SUPERVISION DEL TURNO
  7586.                 //
  7587.                 /*$supervisionObj = $entityManager->getRepository(Supervision::class)->findOneBy([                
  7588.                     'Shift'     => $shiftObj->getShiftId(),
  7589.                     'is_active' => 1
  7590.                 ]);
  7591.                 if($supervisionObj)
  7592.                 {
  7593.                     $supervisionId = $supervisionObj->getSupervisionId();
  7594.                 } else {*/
  7595.                     $supervision = new Supervision();
  7596.                     //$supervision->setShift($shiftObj);
  7597.                     $supervision->setProject($locationObj->getProject());
  7598.                     $supervision->setLocation($locationObj);                
  7599.                     $supervision->setIsActive(1);
  7600.                     $supervision->setCreatedAt(new \DateTime());
  7601.                     $supervision->setCreatedByEmployeeId($supervisorObj);
  7602.                     $entityManager->persist($supervision);
  7603.                     $entityManager->flush();
  7604.                     $supervisionId $supervision->getSupervisionId();
  7605.                 //}
  7606.                 if($locationObj->getProject())
  7607.                 {
  7608.                     $projectName $locationObj->getProject()->getName();
  7609.                     $projectId   $locationObj->getProject()->getProjectId();
  7610.                 } else {
  7611.                     $projectName '-';
  7612.                     $projectId   '0';
  7613.                 }
  7614.                 //QUITAR ESTO PARA RETORNAR A LA LISTA DE EMPLEADOS AUTOMATICA
  7615.                 $employees = [];
  7616.                 $data = [
  7617.                     //'shift_id'       => $shiftObj->getShiftId(),
  7618.                     'supervision_id' => $supervisionId,
  7619.                     'project_id'     => $projectId,
  7620.                     'project_name'   => $projectName,
  7621.                     'location_id'    => $locationObj->getLocationId(),
  7622.                     'location_name'  => $locationObj->getName(),
  7623.                     //'date_from'      => $shiftObj->getDateFrom(),
  7624.                     //'date_to'        => $shiftObj->getDateTo(),
  7625.                     'employees'      => $employees
  7626.                 ];
  7627.                 return new JsonResponse(array('status' => 'success''data' => $data));
  7628.                 
  7629.             }
  7630.         }
  7631.         return new JsonResponse(array('status' => 'error'));
  7632.     }
  7633.     /**
  7634.      * @Route("/search_agent_bulk", name="ws_search_agent_bulk", methods={"GET", "POST"})
  7635.      */
  7636.     public function searchAgentBulk(Request $requestEntityManagerInterface $entityManager): Response
  7637.     {
  7638.         
  7639.         $data json_decode(file_get_contents("php://input"));             
  7640.         if($data)
  7641.         {   
  7642.             //$eid         = $data->eid;              
  7643.             $location_id   $data->location_id;
  7644.             $citizen_idRaw $data->citizen_id;  
  7645.             
  7646.             //Limpiamos espacios en blanco para los DPIs que vienen desde el QR con espacio en blanco
  7647.             $citizen_id preg_replace('/\s+/'''$citizen_idRaw);            
  7648.                  
  7649.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  7650.                 'citizenId'      => $citizen_id//,  
  7651.                 //'employeeStatus' => 1
  7652.             ]);  
  7653.             $employees = [];
  7654.             if($employeeObj)
  7655.             {            
  7656.                 if($employeeObj->getEmployeeStatus()->getEmployeeStatusId() != 1)
  7657.                 {
  7658.                     return new JsonResponse(array('status' => 'error''message' => 'Este colaborador no se encuentra activo. Por favor, verifique que no se encuentre de baja, ausente, suspendido o de vacaciones.'));
  7659.                 }
  7660.                 $path $this->getProjectPaths();
  7661.                 if($employeeObj->getAvatarPath())
  7662.                 {
  7663.                     $avatar $path['public_path'].'uploads/'.$employeeObj->getAvatarPath();
  7664.                 } else {
  7665.                     $avatar $path['public_path'].'assets/img/empty_user.png';
  7666.                 }
  7667.                 $type "extra";
  7668.                 $locationEmployeeObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([                
  7669.                     'Employee' => $employeeObj->getEmployeeId(),
  7670.                     'Location' => $location_id
  7671.                 ]); 
  7672.                 if($locationEmployeeObj)
  7673.                 {
  7674.                     $type 'asignado';
  7675.                 }
  7676.                 $openedAt "";
  7677.                 $shiftEmployeeObj $entityManager->getRepository(ShiftEmployee::class)->findOneBy([                
  7678.                     'Employee' => $employeeObj->getEmployeeId(),
  7679.                     'Location' => $location_id,
  7680.                     'is_done'  => 0
  7681.                 ]); 
  7682.                 if($shiftEmployeeObj)
  7683.                 {
  7684.                     $openedAt $shiftEmployeeObj->getOpenedAt();
  7685.                 }
  7686.                 $employees = [
  7687.                     'employee_id' => $employeeObj->getEmployeeId(),
  7688.                     'name'        => $employeeObj->getName(),
  7689.                     'position'    => $employeeObj->getJobPosition()->getName(),
  7690.                     'avatar'      => $avatar,                    
  7691.                     'citizen_id'  => $employeeObj->getCitizenId(),
  7692.                     'type'        => $type,
  7693.                     'opened_at'   => $openedAt                    
  7694.                 ];
  7695.                 return new JsonResponse(array('status' => 'success''data' => $employees));
  7696.             } else {
  7697.                 return new JsonResponse(array('status' => 'error''message' => 'No se encontro al colaborador con este DPI'));
  7698.                 
  7699.             }
  7700.         }
  7701.         return new JsonResponse(array('status' => 'error'));
  7702.     }
  7703.         
  7704.  
  7705.  
  7706.     /**
  7707.      * @Route("/search_agent", name="ws_search_agent", methods={"GET", "POST"})
  7708.      */
  7709.     public function searchAgent(Request $requestEntityManagerInterface $entityManager): Response
  7710.     {
  7711.         
  7712.         $data json_decode(file_get_contents("php://input"));             
  7713.         if($data)
  7714.         {   
  7715.             $eid         $data->eid;              
  7716.             //$location_id = $data->location_id;
  7717.             $citizen_id  $data->citizen_id;
  7718.             //$supervision_id = $data->supervision_id;            
  7719.             //$locationObj = $entityManager->getRepository(Location::class)->findOneBy([                
  7720.             //    'locationId'  => $location_id                
  7721.             //]);  
  7722.                  
  7723.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  7724.                 'citizenId'      => $citizen_id,  
  7725.                 'employeeStatus' => 1
  7726.             ]);  
  7727.             $employees = [];
  7728.             if($employeeObj)
  7729.             {            
  7730.                 $path $this->getProjectPaths();
  7731.                 if($employeeObj->getAvatarPath())
  7732.                 {
  7733.                     $avatar $path['public_path'].'uploads/'.$employeeObj->getAvatarPath();
  7734.                 } else {
  7735.                     $avatar $path['public_path'].'assets/img/empty_user.png';
  7736.                 }
  7737.                 $employees = [
  7738.                     'employee_id' => $employeeObj->getEmployeeId(),
  7739.                     'name'        => $employeeObj->getName(),
  7740.                     'position'    => $employeeObj->getJobPosition()->getName(),
  7741.                     'avatar'      => $avatar,
  7742.                     'location_position'  => '',
  7743.                     'location_place'     => '',
  7744.                     'citizen_id'         => $employeeObj->getCitizenId(),
  7745.                     'firearm_credential' => $employeeObj->getFirearmCredential(),
  7746.                     'firearm_expiration' => $employeeObj->getFirearmExpiration()                        
  7747.                 ];
  7748.                 return new JsonResponse(array('status' => 'success''data' => $employees));
  7749.             } else {
  7750.                 return new JsonResponse(array('status' => 'error''message' => 'No se encontro al colaborador con este DPI'));
  7751.                 
  7752.             }
  7753.         
  7754.             //Todo cambio que se haga aca, tambien debe hacerse en "start_supervision"
  7755.             /*$data = [
  7756.                 //'shift_id'       => $shiftObj->getShiftId(),
  7757.                 'supervision_id' => $supervision_id,
  7758.                 'project_id'     => $locationObj->getProject()->getProjectId(),
  7759.                 'project_name'   => $locationObj->getProject()->getName(),
  7760.                 'location_id'    => $locationObj->getLocationId(),
  7761.                 'location_name'  => $locationObj->getName(),
  7762.                 //'date_from'      => $shiftObj->getDateFrom(),
  7763.                 //'date_to'        => $shiftObj->getDateTo(),
  7764.                 'employees'      => $employee
  7765.             ];*/
  7766.             //return new JsonResponse(array('status' => 'success', 'data' => $employee));
  7767.             
  7768.         }
  7769.         return new JsonResponse(array('status' => 'error'));
  7770.     }
  7771.     /**
  7772.      * @Route("/search_agent_vehicle", name="ws_search_agent_vehicle", methods={"GET", "POST"})
  7773.      */
  7774.     public function searchAgentVehicle(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  7775.     {
  7776.         
  7777.         $data json_decode(file_get_contents("php://input"));             
  7778.         $debug 0;
  7779.         if($data)
  7780.         {   
  7781.             $eid          $data->eid;                          
  7782.             $citizen_id   $data->citizen_id;
  7783.             $vehicle_info $data->current_vehicle;
  7784.             $mileage      $data->mileage;
  7785.             
  7786.             $vehicleAssignmentObj $entityManager->getRepository(VehicleAssignment::class)->findOneBy([                
  7787.                 'vehicleAssignmentId' => $vehicle_info->vehicle_assignment_id                            
  7788.             ]);  
  7789.             if($mileage $vehicleAssignmentObj->getMileage())
  7790.             {
  7791.                 return new JsonResponse(array('status' => 'error''message' => 'El kilometraje final no puede ser menor al inicial ('.$vehicleAssignmentObj->getMileage().')'));
  7792.             }
  7793.             $debug 1;
  7794.             $employeeFromObj $entityManager->getRepository(Employee::class)->findOneBy([                
  7795.                 'employeeId'      => $eid                
  7796.             ]);  
  7797.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  7798.                 'citizenId'      => $citizen_id,  
  7799.                 'employeeStatus' => 1
  7800.             ]);  
  7801.             $employees = [];
  7802.             if($employeeObj)
  7803.             {                                      
  7804.                 
  7805.                 $debug 2;
  7806.                 $path $this->getProjectPaths();
  7807.                 if($employeeObj->getAvatarPath())
  7808.                 {
  7809.                     $avatar $path['public_path'].'uploads/'.$employeeObj->getAvatarPath();
  7810.                 } else {
  7811.                     $avatar $path['public_path'].'assets/img/empty_user.png';
  7812.                 }
  7813.                 $employees = [
  7814.                     'employee_id' => $employeeObj->getEmployeeId(),
  7815.                     'name'        => $employeeObj->getName(),
  7816.                     'position'    => $employeeObj->getJobPosition()->getName(),
  7817.                     'avatar'      => $avatar,
  7818.                     'location_position'  => '',
  7819.                     'location_place'     => '',
  7820.                     'citizen_id'         => $employeeObj->getCitizenId(),
  7821.                     'firearm_credential' => $employeeObj->getFirearmCredential(),
  7822.                     'firearm_expiration' => $employeeObj->getFirearmExpiration()                        
  7823.                 ];
  7824.                 if($vehicle_info->external_id)
  7825.                 {
  7826.                     $debug 3;
  7827.                     $externalId $vehicle_info->external_id;
  7828.                     if($positionFound $helperService->externalDb_checkVehicleAssignments($externalId$employeeObj->getName()))
  7829.                     {
  7830.                         $debug 4;
  7831.                         
  7832.                         $transferFrom $employeeFromObj->getName();
  7833.                         $transferTo   $employeeObj->getName();
  7834.                         $transfer = new VehicleTransfer();
  7835.                         $transfer->setMileage($mileage);
  7836.                         $transfer->setTransferedFrom($transferFrom);
  7837.                         $transfer->setTransferedTo($transferTo);
  7838.                         $transfer->setEmployeeIdFrom($employeeFromObj);
  7839.                         $transfer->setEmployeeIdTo($employeeObj);
  7840.                         $transfer->setVehicleAssignment($vehicleAssignmentObj);
  7841.                         $transfer->setIsActive(1);
  7842.                         $transfer->setCreatedAt(new \DateTime());
  7843.                         $transfer->setCreatedByEmployeeId($employeeFromObj);
  7844.                         $entityManager->persist($transfer);
  7845.                         $entityManager->flush();
  7846.                         //Para registrar la transferencia efectiva del vehiculo, vamos a cambiar el valor de
  7847.                         //Asignado y Asignado2, para intercambiar.                                                
  7848.                         if($helperService->externalDb_transferVehicleAssignments($externalId$transferFrom$transferTo$positionFound$employeeFromObj->getAlias(), $employeeObj->getAlias()))
  7849.                         {
  7850.                             $debug 5;
  7851.                             $vehicleAssignmentObj->setMileageFinal($mileage);
  7852.                             $vehicleAssignmentObj->setIsReturned(1);
  7853.                             $vehicleAssignmentObj->setReturnedAt(new \DateTime());   
  7854.                             $entityManager->persist($vehicleAssignmentObj);
  7855.                             $entityManager->flush();
  7856.                             return new JsonResponse(array('status' => 'success''data' => $employees'message' => "La transferencia ha sido completada exitosamente"'found' => $positionFound));
  7857.                         };                        
  7858.                     }  else {
  7859.                         return new JsonResponse(array('status' => 'error''message' => 'El colaborador que recibirá el vehículo no se encuentra autorizado''debug' => $debug));
  7860.                     }                   
  7861.                 }                
  7862.             } else {
  7863.                 return new JsonResponse(array('status' => 'error''message' => 'No se encontro al colaborador con este DPI'));
  7864.                 
  7865.             }
  7866.         
  7867.         }
  7868.         return new JsonResponse(array('status' => 'error''message' => 'No se puede realizar la transferencia en este momento, por favor comunicarse con soporte tecnico (Error 21)''debug' => $debug));
  7869.     }
  7870.         
  7871.     /**
  7872.      * @Route("/check_pause", name="check_pause", methods={"GET", "POST"})
  7873.      */
  7874.     public function checkPause(Request $requestEntityManagerInterface $entityManager): Response
  7875.     {
  7876.             
  7877.             $data json_decode(file_get_contents("php://input"));             
  7878.             if($data)
  7879.             {   
  7880.                 $seid         $data->seid;                              
  7881.                 
  7882.                 $shiftEmployeeObj $entityManager->getRepository(ShiftEmployeePause::class)->findOneBy([                
  7883.                     'ShiftEmployee' => $seid,                    
  7884.                     'ended_at'  => null
  7885.                 ]); 
  7886.     
  7887.                 if($shiftEmployeeObj)
  7888.                 {                   
  7889.                     return new JsonResponse(array('status' => 'success''data' => '1'));    
  7890.                 } else {    
  7891.                     return new JsonResponse(array('status' => 'success''data' => '0'));                    
  7892.                 }
  7893.             }
  7894.     
  7895.             return new JsonResponse(array('status' => 'error'));
  7896.     }
  7897.     /**
  7898.      * @Route("/send_bulk", name="send_bulk", methods={"GET", "POST"})
  7899.      */
  7900.     public function sendBulk(Request $requestEntityManagerInterface $entityManager): Response
  7901.     {
  7902.         
  7903.         $data json_decode(file_get_contents("php://input"));             
  7904.         if($data)
  7905.         {   
  7906.             $eid         $data->eid;              
  7907.             $location_id $data->location_id;
  7908.             $employees   $data->employees;    
  7909.             $control     date("YmdHis");
  7910.             
  7911.             foreach($employees as $employee)
  7912.             {
  7913.                 $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([                
  7914.                     'employeeId' => $eid
  7915.                 ]);
  7916.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  7917.                     'employeeId' => $employee->employee_id
  7918.                 ]);  
  7919.                 $locationObj $entityManager->getRepository(Location::class)->findOneBy([                
  7920.                     'locationId' => $location_id
  7921.                 ]);  
  7922.                 $locationEmployeeObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([                
  7923.                     'Location'  => $location_id,
  7924.                     'Employee'  => $employee->employee_id,
  7925.                     'is_active' => 1
  7926.                 ]);  
  7927.                 $shiftEmployeeObj $entityManager->getRepository(ShiftEmployee::class)->findOneBy([                
  7928.                     'Location'  => $location_id,
  7929.                     'Employee'  => $employee->employee_id,
  7930.                     'is_done'   => 0
  7931.                 ]);  
  7932.                 if($shiftEmployeeObj)
  7933.                 {
  7934.                     $shift $shiftEmployeeObj;
  7935.                 } else {
  7936.                     $shift = new ShiftEmployee();
  7937.                 }
  7938.                 $shift->setEmployee($employeeObj);
  7939.                 $shift->setLocation($locationObj);
  7940.                 $shift->setIsActive(1);
  7941.                                              
  7942.                 if($locationEmployeeObj)
  7943.                 {
  7944.                     $shift->setLocationEmployee($locationEmployeeObj);
  7945.                 }
  7946.                 if($employee->type != 'asignado')
  7947.                 {
  7948.                     $shift->setIsExtra(1);
  7949.                     $shift->setExtraType($employee->type);
  7950.                 }
  7951.                 //Si ya existia
  7952.                 if($shiftEmployeeObj)
  7953.                 {   
  7954.                     //si no esta ni abierto ni cerrado el turno
  7955.                     if(!$shiftEmployeeObj->getOpenedAt() && !$shiftEmployeeObj->getClosedAt())
  7956.                     {
  7957.                         $shift->setBulkControl($control);   
  7958.                         $shift->setCreatedByEmployeeId($supervisorObj);
  7959.                         $shift->setCreatedAt(new \DateTime());
  7960.                         $shift->setOpenedAt(date("Y-m-d H:i:s"));
  7961.                         $shift->setIsStarted(1);
  7962.                         $shift->setIsDone(0);
  7963.                     }
  7964.                     //Si ya aparece turno iniciado pero no cerrado
  7965.                     if($shiftEmployeeObj->getOpenedAt() && !$shiftEmployeeObj->getClosedAt())
  7966.                     {
  7967.                         $shift->setBulkControlClose($control);   
  7968.                         $shift->setUpdatedByEmployeeId($supervisorObj);
  7969.                         $shift->setUpdatedAt(new \DateTime());
  7970.                         $shift->setClosedAt(date("Y-m-d H:i:s"));
  7971.                         $shift->setIsDone(1);
  7972.                     }                    
  7973.                 } else {
  7974.                     //Si no esta creado
  7975.                     $shift->setBulkControl($control);   
  7976.                     $shift->setCreatedByEmployeeId($supervisorObj);
  7977.                     $shift->setOpenedAt(date("Y-m-d H:i:s"));
  7978.                     $shift->setIsStarted(1);
  7979.                     $shift->setIsDone(0);
  7980.                 }
  7981.                 $entityManager->persist($shift);
  7982.                 $entityManager->flush();
  7983.             }
  7984.                             
  7985.             return new JsonResponse(array('status' => 'success'));
  7986.         }
  7987.         return new JsonResponse(array('status' => 'error'));
  7988.     }
  7989.             
  7990.     /**
  7991.      * @Route("/shift-report", name="shift-report", methods={"GET", "POST"})
  7992.      */
  7993.     public function shiftReport(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  7994.     {
  7995.         
  7996.         $data json_decode(file_get_contents("php://input"));             
  7997.         if($data)
  7998.         {   
  7999.             $eid  $data->eid;            
  8000.             $type $data->type;     
  8001.             $lat  $data->lat;
  8002.             $lng  $data->lng;
  8003.             $seid $data->seid;  
  8004.             $leid $data->leid;  //Eso es location_employee_Id o solo location_id para extrero o descansero
  8005.             $isExtra   $data->isExtra;  
  8006.             $inventory $data->inventory;  
  8007.             
  8008.             $pauseType "";
  8009.             if(isset($data->selectedPauseType))
  8010.             {
  8011.                 $pauseType $data->selectedPauseType
  8012.             }
  8013.             $sharedCode false;
  8014.             
  8015.             $administrative_job_position = array("2","3","24","11","21","5","26","16","22","30","34","36","35","20","37","40","42","43","47");//los job position administrativos BRIAN
  8016.             
  8017.             
  8018.             //En cualquier escenario si viene INVENTORY:
  8019.             if($inventory)
  8020.             {
  8021.                 if(strlen($inventory->weapon)>0)
  8022.                 {
  8023.                     //Estos campos ahora ya no son requeridos, solo se almacenarán como INFORMACIÓN pero ya no
  8024.                     //habrá validación con la base de datos de ellos
  8025.                     //Esto se hizo el 28 de abril de 2025
  8026.                     /*if(!$helperService->externalDb_checkArmTenencia($inventory->weapon))
  8027.                     {
  8028.                         return new JsonResponse(array('status' => 'error', 'message' => 'El número de serie del arma es invalido. Ingrese un número de serie valido del arma.'));             
  8029.                     }*/
  8030.                 }
  8031.             }
  8032.             //Nueva dinamica de PAUSA
  8033.             if($type == 'pause_open')
  8034.             {
  8035.                 $shiftEmployeeObj $entityManager->getRepository(ShiftEmployee::class)->findOneBy([                
  8036.                     'shiftEmployeeId' => $seid
  8037.                 ]);  
  8038.                 if($shiftEmployeeObj)
  8039.                 {
  8040.                     $pauseTypeObj $entityManager->getRepository(ShiftEmployeePauseType::class)->findOneBy([                
  8041.                         'shiftEmployeePauseTypeId' => $pauseType
  8042.                     ]); 
  8043.                     $shiftPause = new ShiftEmployeePause();
  8044.                     $shiftPause->setEmployee($shiftEmployeeObj->getEmployee());
  8045.                     $shiftPause->setLocation($shiftEmployeeObj->getLocation());
  8046.                     $shiftPause->setShiftEmployee($shiftEmployeeObj);
  8047.                     $shiftPause->setShiftEmployeePauseType($pauseTypeObj);
  8048.                     $shiftPause->setStartedAt(date("Y-m-d H:i:s"));                    
  8049.                     $entityManager->persist($shiftPause);
  8050.                     $entityManager->flush();
  8051.                     return new JsonResponse(array('status' => 'success''shift_employee_id' => $shiftEmployeeObj->getShiftEmployeeId()));
  8052.                 } else {
  8053.                     return new JsonResponse(array('status' => 'error''message' => 'No se encontro el turno para pausar.'));             
  8054.                 }
  8055.             }
  8056.             if($type == 'pause_close')
  8057.             {
  8058.                 $shiftEmployeeObj $entityManager->getRepository(ShiftEmployeePause::class)->findOneBy([                
  8059.                     'ShiftEmployee' => $seid,
  8060.                     'ended_at' => null
  8061.                 ]);  
  8062.                 if($shiftEmployeeObj)
  8063.                 {                    
  8064.                     $shiftEmployeeObj->setEndedAt(date("Y-m-d H:i:s"));                    
  8065.                     $entityManager->persist($shiftEmployeeObj);
  8066.                     $entityManager->flush();
  8067.                     return new JsonResponse(array('status' => 'success''shift_employee_id' => $shiftEmployeeObj->getShiftEmployee()->getShiftEmployeeId()));
  8068.                 } else {
  8069.                     return new JsonResponse(array('status' => 'error''message' => 'No se encontro el turno para pausar.'));             
  8070.                 }
  8071.             }
  8072.             //Revisamos si ya existio un reporte de APERTURA para este empleado hoy
  8073.             if($type == 'open')
  8074.             {                
  8075.                 //Validacion de apertura
  8076.                 $inventoryObj false;
  8077.                 if(strlen($inventory->code)>0)
  8078.                 {
  8079.                     $inventoryObj $entityManager->getRepository(ShiftEmployee::class)->findOneBy([                
  8080.                         'inventory_code' => $inventory->code
  8081.                     ]);  
  8082.                     if(!$inventoryObj)
  8083.                     {
  8084.                         return new JsonResponse(array('status' => 'error''message' => 'El código de entrega de inventario no existe o ya no es valido. No se puede aperturar el turno.'));             
  8085.                     } else {
  8086.                         $checkShiftEmployeeId $inventoryObj->getShiftEmployeeId();
  8087.                         $checkInventoryObj $entityManager->getRepository(ShiftEmployee::class)->findOneBy([                
  8088.                             'inventory_shift_employee_id' => $checkShiftEmployeeId
  8089.                         ]);  
  8090.                         if($checkInventoryObj)
  8091.                         {
  8092.                             return new JsonResponse(array('status' => 'error''message' => 'El código de entrega ya fue utilizado.'));             
  8093.                         }
  8094.                     }
  8095.                 }
  8096.                     
  8097.                 $shiftEmployeeCheck $entityManager->getRepository(ShiftEmployee::class)->checkForShiftsOpenedToday($eid);
  8098.                 if($shiftEmployeeCheck)
  8099.                 {
  8100.                     $controlNumbers = [];
  8101.                     foreach($shiftEmployeeCheck as $checkItem)
  8102.                     {
  8103.                         if($checkItem['hours_elapsed'] < 18)
  8104.                         {
  8105.                             $controlNumbers[] = '#'.$checkItem['shift_employee_id'];
  8106.                         }
  8107.                     }
  8108.                     if(count($controlNumbers)>0)
  8109.                     {
  8110.                         //return new JsonResponse(array('status' => 'error', 'message' => 'Ya existe un reporte de apertura para un turno el dia de hoy. Si considera que se trata de un error, por favor solicite al administrador del sistema borrar el registro de apertura con el número de control: '.implode(', ', $controlNumbers)));
  8111.                     }
  8112.                 }
  8113.             }
  8114.             
  8115.             //Buscamos sesiones activas (Que aún no se han completado)      
  8116.             $checkIfHasActiveShift false;      
  8117.             if(strlen($seid) > 0)
  8118.             {
  8119.                 $shiftObj $entityManager->getRepository(ShiftEmployee::class)->findOneBy([                
  8120.                     'shiftEmployeeId' => $seid             
  8121.                 ]);
  8122.             } else {
  8123.                 $checkIfHasActiveShift true;
  8124.                 $shiftObj $entityManager->getRepository(ShiftEmployee::class)->findOneBy([                
  8125.                     'Employee'   => $eid,
  8126.                     'is_active'  => 1,
  8127.                     'is_started' => 1,
  8128.                     'is_done'    => 0
  8129.                 ], ['created_at' => 'DESC']);
  8130.             }               
  8131.             //Si encontramos sesiones activas entonces informamos según el tipo de solicitud
  8132.             if($shiftObj)
  8133.             {
  8134.               
  8135.                 if($type == 'check')
  8136.                 {
  8137.                 
  8138.                     $resetSession $this->sessionEmployee($shiftObj->getEmployee(), $shiftObj->getLocation(), $shiftObj);
  8139.                     return new JsonResponse(array('status' => 'success''reset_session' => $resetSession));
  8140.                 }    
  8141.                 
  8142.             } else {
  8143.                 if($type == 'check')
  8144.                 {
  8145.                     return new JsonResponse(array('status' => 'ignore''message' => 'No hay sesiones activas, ignorando.'));         
  8146.                 }
  8147.                 if(!$isExtra)
  8148.                 {
  8149.                     $locationEmployeeObj $entityManager->getRepository(LocationEmployee::class)->findOneBy([                
  8150.                         'locationEmployeeId' => $leid
  8151.                     ]);
  8152.                 }
  8153.                 //Si no existe, es porque no hay ningun registro de apertura de sesion activa                                                
  8154.                 //return new JsonResponse(array('status' => 'ignore', 'message' => 'No hay turnos asignados disponibles. Consulte con su supervisor.'));         
  8155.                 if(!$isExtra && $locationEmployeeObj)
  8156.                 {
  8157.                     $shiftObj = new ShiftEmployee();
  8158.                     $shiftObj->setLocationEmployee($locationEmployeeObj);
  8159.                     $shiftObj->setEmployee($locationEmployeeObj->getEmployee());
  8160.                     $shiftObj->setLocation($locationEmployeeObj->getLocation());
  8161.                     $shiftObj->setLocationPosition($locationEmployeeObj->getLocationPosition());
  8162.                     $shiftObj->setOpenedAt(date("Y-m-d H:i:s"));
  8163.                     $shiftObj->setIsActive(1);
  8164.                     $shiftObj->setIsStarted(1);
  8165.                     $shiftObj->setIsDone(0);
  8166.                     $shiftObj->setCreatedAt(new \DateTime());
  8167.                     $entityManager->persist($shiftObj);
  8168.                     $entityManager->flush();
  8169.                     
  8170.                 } else {
  8171.                     
  8172.                     //Si no es extrero o descansero, aplica esta validacion
  8173.                     if($isExtra)
  8174.                     {
  8175.                         //Si es extrero o descansero, entonces se crea sin location_employee_id
  8176.                         $employeeExtraObj $entityManager->getRepository(Employee::class)->findOneBy([                
  8177.                             'employeeId' => $eid
  8178.                         ]);
  8179.                         $locationExtraObj $entityManager->getRepository(Location::class)->findOneBy([                
  8180.                             'locationId' => $leid
  8181.                         ]);
  8182.                         $lpid $data->lpid;  //Eso es location_place_Id  para extrero o descansero
  8183.                         $locationPlaceObj $entityManager->getRepository(LocationPlace::class)->findOneBy([
  8184.                             'locationPlaceId' => $lpid
  8185.                         ]);
  8186.                         $shiftObj = new ShiftEmployee();
  8187.                         $shiftObj->setLocationEmployee(null);
  8188.                         $shiftObj->setEmployee($employeeExtraObj);
  8189.                         $shiftObj->setLocation($locationExtraObj);
  8190.                         if($locationPlaceObj){
  8191.                           $shiftObj->setLocationPlace($locationPlaceObj);
  8192.                         }else{
  8193.                           $shiftObj->setLocationPlace(null);
  8194.                         }
  8195.                         $shiftObj->setLocationPosition(null);
  8196.                         $shiftObj->setOpenedAt(date("Y-m-d H:i:s"));
  8197.                         $shiftObj->setIsExtra(1);
  8198.                         $shiftObj->setExtraType($isExtra);
  8199.                         $shiftObj->setIsActive(1);
  8200.                         $shiftObj->setIsStarted(1);
  8201.                         $shiftObj->setIsDone(0);
  8202.                         $shiftObj->setCreatedAt(new \DateTime());
  8203.                         $entityManager->persist($shiftObj);
  8204.                         $entityManager->flush();                        
  8205.                     } else {
  8206.                         return new JsonResponse(array('status' => 'error''message' => 'No hay puesto asignado para este agente. El número de control es: '.$leid));         
  8207.                     }
  8208.                 }
  8209.                 
  8210.             }    
  8211.             //revisamos si se encuentra dentro de un poligono, a la hora de abrir o cerrar
  8212.             if($type == 'open' || $type == 'close')
  8213.             {
  8214.                 if($isExtra)
  8215.                 {
  8216.                     $locationObj $entityManager->getRepository(Location::class)->findOneBy([                
  8217.                         'locationId'  => $leid
  8218.                     ]);    
  8219.                 } else {
  8220.                     $locationObj $entityManager->getRepository(Location::class)->findOneBy([                
  8221.                         'locationId'  => $shiftObj->getLocation()->getLocationId()
  8222.                     ]);    
  8223.                 }
  8224.                 if($locationObj->getPolygonList())
  8225.                 {
  8226.                     $array json_decode($locationObj->getPolygonList());
  8227.                     $polygonList = [];
  8228.                     foreach($array->coordinates[0] as $item)
  8229.                     {
  8230.                         if(isset($item[0]) && isset($item[1]))
  8231.                         {
  8232.                             $polygonList[] = ['lat' => $item[1], 'lng' => $item[0]];
  8233.                         }
  8234.                     }
  8235.                             
  8236.                     $point = ['lat' => $lat'lng' => $lng];        
  8237.                     $res $this->isInsidePolygon($point$polygonList);
  8238.                     if(!$res)
  8239.                     {     
  8240.                         $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  8241.                             'employeeId' => $eid
  8242.                         ]);  
  8243.                         
  8244.                         
  8245.                         $job_position_id $employeeObj->getJobPosition()->getJobPositionId();
  8246.                         $exceptionCode $data->exceptionCode;
  8247.                         $exceptionMessage $data->exceptionMessage;
  8248.                         if(strlen($exceptionCode)>0){
  8249.                           $exceptionValid $this->validateExceptionCode($entityManager,$employeeObj$shiftObj$exceptionCode$locationObj ); 
  8250.                           if($exceptionValid){
  8251.                             
  8252.                           }else{
  8253.                               if($shiftObj && $type == 'open'){
  8254.                                 $entityManager->remove($shiftObj);
  8255.                                 $entityManager->flush();
  8256.                               }
  8257.                               
  8258.                                 $shiftLog = new ShiftEmployeeLog();
  8259.                                 $shiftLog->setShiftEmployee($shiftObj);
  8260.                                 $shiftLog->setLocation($locationObj);
  8261.                                 $shiftLog->setLat($lat);
  8262.                                 $shiftLog->setLng($lng);
  8263.                                 $shiftLog->setCreatedAt(new \DateTime());
  8264.                                 $shiftLog->setCreatedByEmployeeId($employeeObj);
  8265.                                 $entityManager->persist($shiftLog);
  8266.                                 $entityManager->flush(); 
  8267.                               return new JsonResponse(array('status' => 'error2''message' => '<h4>Código de excepción invalido.</h4>No se puede actualizar porque no se encuentra dentro de la ubicación autorizada para el turno asignado. Puede continuar solicitando un codigo de excepción a la administración e ingresandolo abajo. | '.$shiftLog->getShiftEmployeeLogId()));
  8268.                           }
  8269.                           
  8270.                         }elseif(strlen($exceptionMessage)>&& in_array($job_position_id$administrative_job_position)){                     
  8271.                             if($type == 'close'){
  8272.                                 $shiftObj->setCloseDescription($exceptionMessage);
  8273.                             }else{
  8274.                                 $shiftObj->setOpenDescription($exceptionMessage);
  8275.                             }
  8276.                           
  8277.                           
  8278.                         } else{
  8279.                         
  8280.                             $shiftLog = new ShiftEmployeeLog();
  8281.                             $shiftLog->setShiftEmployee($shiftObj);
  8282.                             $shiftLog->setLocation($locationObj);
  8283.                             $shiftLog->setLat($lat);
  8284.                             $shiftLog->setLng($lng);
  8285.                             $shiftLog->setCreatedAt(new \DateTime());
  8286.                             $shiftLog->setCreatedByEmployeeId($employeeObj);
  8287.                             $entityManager->persist($shiftLog);
  8288.                             $entityManager->flush();   
  8289.                             
  8290.                             //ACA los job position administrativos
  8291.                             if(in_array($job_position_id$administrative_job_position ) ){
  8292.                                 if($shiftObj && $type == 'open'){
  8293.                                   $entityManager->remove($shiftObj);
  8294.                                   $entityManager->flush();
  8295.                                 }
  8296.                                 return new JsonResponse(array('status' => 'error3''message' => '<h4>Fuera de ubicación</h4>No se puede actualizar porque no se encuentra dentro de la ubicación autorizada para el turno asignado. Debe ingresarse un comentario justificativo, ya que la geolocalización registrada se encuentra fuera del rango permitido.'));
  8297.                                 exit;
  8298.                             }else{
  8299.                                 if($type == 'close'){
  8300.                                   if($shiftObj && $type == 'open'){
  8301.                                     $entityManager->remove($shiftObj);
  8302.                                     $entityManager->flush();
  8303.                                   }
  8304.                                   return new JsonResponse(array('status' => 'error2''message' => '<h4>Fuera de ubicación</h4>No se puede actualizar porque no se encuentra dentro de la ubicación autorizada para el turno asignado. Puede continuar solicitando un codigo de excepción a la administración e ingresandolo abajo. '.$shiftLog->getShiftEmployeeLogId()));
  8305.                                   exit;
  8306.                                 }else{
  8307.                                   if($shiftObj && $type == 'open'){
  8308.                                     $entityManager->remove($shiftObj);
  8309.                                     $entityManager->flush();
  8310.                                   }
  8311.                                   return new JsonResponse(array('status' => 'error''message' => '<h4>Fuera de ubicación</h4>No se puede completar la actualización de turno porque según las coordenadas de su GPS, usted no se encuentra dentro de la ubicación autorizada para el turno que tiene asignado. Si considera que se trata de un error, por favor verifique la conexión a Internet y la función de Geolocalización del dispositivo ('.$shiftLog->getShiftEmployeeLogId().')'));
  8312.                                   exit;
  8313.                                 }
  8314.                                 
  8315.                             }
  8316.                         }
  8317.                     }     
  8318.                 
  8319.                 } else {
  8320.                     if($shiftObj && $type == 'open'){
  8321.                       $entityManager->remove($shiftObj);
  8322.                       $entityManager->flush();
  8323.                     }
  8324.                     return new JsonResponse(array('status' => 'error''message' => 'No se puede continuar, se requiere un poligono en el puesto'));
  8325.                 }
  8326.             }
  8327.             if($type == 'check')
  8328.             {              
  8329.                 $resetSession false;           
  8330.                 if($checkIfHasActiveShift)
  8331.                 {
  8332.                     $resetSession $this->sessionEmployee($shiftObj->getEmployee(), $shiftObj->getLocation(), $shiftObj);
  8333.                 }
  8334.                 $checkPanic $this->getPanicStatus($entityManager$eid$shiftObj->getLocation()->getLocationId());
  8335.                 return new JsonResponse(array('status' => 'success''type' => 'check''shift_employee_id' => $shiftObj->getShiftEmployeeId(), 'has_panic' => $checkPanic'reset_session' => $resetSession));
  8336.             }
  8337.             if($type == 'close')
  8338.             {
  8339.                 // ------------------------------------------------------------------------
  8340.                 // Validacion de inventario
  8341.                 // ------------------------------------------------------------------------
  8342.                 if($inventory)
  8343.                 {                    
  8344.                     if(strlen($inventory->weapon)>&& strlen($inventory->ammunition)>0)
  8345.                     {
  8346.                         $sharedCode $this->generateInventoryCode();                        
  8347.                         $shiftObj->setInventoryCode($sharedCode);
  8348.                         $shiftObj->setInventoryWeaponSn($inventory->weapon);
  8349.                         $shiftObj->setInventoryAmmunitionClose($inventory->ammunition);
  8350.                     }                    
  8351.                 }
  8352.                 // ------------------------------------------------------------------------
  8353.                 $shiftObj->setIsDone(1);
  8354.                 $shiftObj->setClosedAt(date("Y-m-d H:i:s"));
  8355.                 //28 de abril del 2025 - se agregaron Lat y Lng para ser guardados
  8356.                 $shiftObj->setLat($lat);
  8357.                 $shiftObj->setLng($lng);
  8358.                 $entityManager->persist($shiftObj);
  8359.                 $entityManager->flush();
  8360.                 $data $this->sessionEmployee($shiftObj->getEmployee());
  8361.                 
  8362.                 return new JsonResponse(array('status' => 'success''type' => 'close''shift_employee_id' => 0'data' => $data'sharedCode' => $sharedCode));
  8363.             }     
  8364.             if($type == 'open')
  8365.             {
  8366.                                 
  8367.                 //creamos un registro de turno nuevo
  8368.                 //$employeeObj = $entityManager->getRepository(Employee::class)->findOneBy([                
  8369.                 //   'employeeId'  => $eid                    
  8370.                 //]);    
  8371.                 //$locationObj = $entityManager->getRepository(Location::class)->findOneBy([                
  8372.                 //    'locationId'  => $lid
  8373.                 //]);                      
  8374.                 // ------------------------------------------------------------------------
  8375.                 // Validacion de inventario
  8376.                 // ------------------------------------------------------------------------
  8377.                 if($inventory)
  8378.                 {                                                            
  8379.                     if($inventoryObj)
  8380.                     {
  8381.                         $shiftObj->setInventoryShiftEmployeeId($inventoryObj);
  8382.                         $shiftObj->setInventoryWeaponSn($inventoryObj->getInventoryWeaponSn());
  8383.                         $shiftObj->setInventoryAmmunition($inventoryObj->getInventoryAmmunitionClose());
  8384.                     } else {
  8385.                         if(strlen($inventory->weapon)>&& strlen($inventory->ammunition)>0)
  8386.                         {
  8387.                             $shiftObj->setInventoryWeaponSn($inventory->weapon);
  8388.                             $shiftObj->setInventoryAmmunition($inventory->ammunition);
  8389.                         }
  8390.                     }                                                                               
  8391.                 }
  8392.                 // ------------------------------------------------------------------------
  8393.                 //$shiftObjN = new ShiftReport();
  8394.                 //$shiftObjN->setEmployee($employeeObj);
  8395.                 //$shiftObjN->setLocation($locationObj);
  8396.                 $shiftObj->setOpenedAt(date("Y-m-d H:i:s"));
  8397.                 $shiftObj->setIsStarted(1);  
  8398.                 $shiftObj->setIsDone(0);    
  8399.                 
  8400.                 //28 de abril del 2025 - se agregaron Lat y Lng para ser guardados
  8401.                 $shiftObj->setLat($lat);
  8402.                 $shiftObj->setLng($lng);
  8403.                 $entityManager->persist($shiftObj);
  8404.                 $entityManager->flush();
  8405.                 $data $this->sessionEmployee($shiftObj->getEmployee(), $shiftObj->getLocation(), $shiftObj);
  8406.                 return new JsonResponse(array('status' => 'success''type' => 'open''shift_employee_id' => $shiftObj->getShiftEmployeeId(), 'data' => $data));
  8407.             }          
  8408.             
  8409.         }
  8410.         return new JsonResponse(array('status' => 'error'));
  8411.     }    
  8412.     
  8413.     public function validateExceptionCode$entityManager,$employeeObj$shiftEmployeeObj$exceptionCode$locationObj){
  8414.       $exceptionAgent $entityManager->getRepository(ExceptionAgent::class)->findOneBy([                
  8415.           'exception_code' => $exceptionCode'is_available' => 1'is_active' => 1
  8416.       ]); 
  8417.       if($exceptionAgent){
  8418.         $exceptionAgent->setLocation($locationObj);
  8419.         $exceptionAgent->setEmployee($shiftEmployeeObj->getEmployee());
  8420.         $exceptionAgent->setShiftEmployee($shiftEmployeeObj);
  8421.         $exceptionAgent->setIsAvailable(0);
  8422.         $exceptionAgent->setUpdatedAt(new \DateTime());
  8423.         $exceptionAgent->setUpdatedEmployee($employeeObj);
  8424.         $entityManager->persist($exceptionAgent);
  8425.         $entityManager->flush();
  8426.         
  8427.         $shiftEmployeeObj->setExceptionAgent($exceptionAgent);
  8428.         $entityManager->persist($shiftEmployeeObj);
  8429.         $entityManager->flush();
  8430.         
  8431.         return true;
  8432.       }else{
  8433.         return false;
  8434.       }
  8435.       return false;
  8436.       
  8437.     }
  8438.     
  8439.     public function generateInventoryCode() {
  8440.         $caracteres 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  8441.         $codigo '';
  8442.         $longitud 6;
  8443.     
  8444.         for ($i 0$i $longitud$i++) {
  8445.             $indice rand(0strlen($caracteres) - 1);
  8446.             $codigo .= $caracteres[$indice];
  8447.         }
  8448.     
  8449.         return $codigo;
  8450.     }
  8451.     
  8452.     
  8453.     
  8454.     /**
  8455.      * @Route("/get-location-position", name="ws_get_location_position", methods={"GET", "POST"})
  8456.      */
  8457.     public function getLocationPositions(Request $requestEntityManagerInterface $entityManager): Response
  8458.     {
  8459.         
  8460.         $data json_decode(file_get_contents("php://input"));             
  8461.         if($data)
  8462.         {     
  8463.             
  8464.             $locationId $data->locationId;
  8465.             $employeeId $data->employeeId;
  8466.             $forms = [];
  8467.             $formList $entityManager->getRepository(LocationPosition::class)->findBy([
  8468.                 'isActive' => 1
  8469.             ]); 
  8470.             foreach($formList as $form)
  8471.             {              
  8472.                 $forms[] = [
  8473.                     'location_position_id' => $form->getLocationPositionId(),
  8474.                     'name'                 => $form->getName()                    
  8475.                 ];
  8476.             }
  8477.             $places = [];
  8478.             $placesList $entityManager->getRepository(LocationPlace::class)->findBy([
  8479.                 'is_active' => 1,
  8480.                 'Location' => $locationId
  8481.             ]); 
  8482.             foreach($placesList as $item)
  8483.             {              
  8484.                 $places[] = [
  8485.                     'location_place_id' => $item->getLocationPlaceId(),
  8486.                     'name'              => $item->getName()                    
  8487.                 ];
  8488.             }
  8489.             $assignedPlace    0;
  8490.             $assignedPosition 0;
  8491.             $locationEmployee $entityManager->getRepository(LocationEmployee::class)->findOneBy([
  8492.                 'Location' => $locationId,
  8493.                 'Employee' => $employeeId,
  8494.                 'is_active' => 1
  8495.             ]); 
  8496.             if($locationEmployee)
  8497.             {
  8498.                 if($locationEmployee->getLocationPlace())
  8499.                 {
  8500.                     $assignedPlace $locationEmployee->getLocationPlace()->getLocationPlaceId();
  8501.                 }
  8502.                 if($locationEmployee->getLocationPosition())
  8503.                 {
  8504.                     $assignedPosition $locationEmployee->getLocationPosition()->getLocationPositionId();
  8505.                 }
  8506.             }
  8507.             return new JsonResponse(array('status' => 'success''data' => $forms'places' => $places'assigned_place' => $assignedPlace'assigned_position' => $assignedPosition));
  8508.         }
  8509.         return new JsonResponse(array('status' => 'error'));
  8510.     }
  8511.    /**
  8512.      * @Route("/get-pause-types", name="ws_get_pause_types", methods={"GET", "POST"})
  8513.      */
  8514.     public function getPauseTypes(Request $requestEntityManagerInterface $entityManager): Response
  8515.     {
  8516.         
  8517.         $data json_decode(file_get_contents("php://input"));             
  8518.         if($data)
  8519.         {     
  8520.             
  8521.          
  8522.             $formList $entityManager->getRepository(ShiftEmployeePauseType::class)->findBy([
  8523.                 'is_active' => 1,                
  8524.             ]); 
  8525.             foreach($formList as $form)
  8526.             {              
  8527.                 $forms[] = [
  8528.                     'id'   => $form->getShiftEmployeePauseTypeId(),
  8529.                     'name' => $form->getName()                    
  8530.                 ];
  8531.             }           
  8532.             return new JsonResponse(array('status' => 'success''data' => $forms));
  8533.         }
  8534.         return new JsonResponse(array('status' => 'error''data' => []));
  8535.     }    
  8536.     
  8537.     /**
  8538.      * @Route("/get-location-assets", name="ws_get_location_assets", methods={"GET", "POST"})
  8539.      */
  8540.     public function getLocationAssets(Request $requestEntityManagerInterface $entityManager): Response
  8541.     {
  8542.         
  8543.         $data json_decode(file_get_contents("php://input"));             
  8544.         if($data)
  8545.         {     
  8546.             
  8547.             $locationId $data->locationId;
  8548.             $employeeId $data->employeeId;
  8549.             $forms = [];
  8550.             $formList $entityManager->getRepository(AssetLocation::class)->findBy([
  8551.                 'is_active' => 1,
  8552.                 'Location'  => $locationId
  8553.             ]); 
  8554.             foreach($formList as $form)
  8555.             {              
  8556.                 $forms[] = [
  8557.                     'location_asset_id' => $form->getAssetLocationId(),
  8558.                     'location_id'       => $form->getLocation()->getLocationId(),  
  8559.                     'asset_name'        => $form->getAsset()->getName(),
  8560.                     'asset_id'          => $form->getAsset()->getAssetId(),
  8561.                     'asset_control'     => $form->getAsset()->getIdControl(),
  8562.                     'asset_plate'       => $form->getAsset()->getPlate(),
  8563.                     'asset_description' => $form->getAsset()->getDescription()
  8564.                 ];
  8565.             }           
  8566.             return new JsonResponse(array('status' => 'success''data' => $forms));
  8567.         }
  8568.         return new JsonResponse(array('status' => 'error'));
  8569.     }    
  8570.     
  8571.     /**
  8572.      * @Route("/create-sanction", name="ws_create_sanction", methods={"GET", "POST"})
  8573.      */
  8574.     public function createSanctionReequest(Request $requestEntityManagerInterface $entityManager): Response
  8575.     {
  8576.         
  8577.         $data json_decode(file_get_contents("php://input"));             
  8578.         if($data)
  8579.         {   
  8580.             $supervisorId  $data->supervisor_id;
  8581.             $employeeId    $data->employee_id;
  8582.             $locationId    $data->location_id;
  8583.             $type           $data->type;
  8584.             $amount         $data->amount;
  8585.             $supSignature   $data->sup_signature;
  8586.             $agentSignature $data->agent_signature;
  8587.             $description    $data->description;
  8588.             $sanction_data  $data->sanction_date;
  8589.             $supSignaturePath   "";
  8590.             $agentSignaturePath "";
  8591.             if($supSignature)
  8592.             {
  8593.                 $supSignaturePath $this->saveSignature($supSignature);
  8594.             }
  8595.             if($agentSignature)
  8596.             {
  8597.                 $agentSignaturePath $this->saveSignature($agentSignature);
  8598.             }
  8599.                         
  8600.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  8601.                 'employeeId'  => $employeeId                    
  8602.             ]);
  8603.             $locationObj $entityManager->getRepository(Location::class)->findOneBy([                
  8604.                 'locationId'  => $locationId
  8605.             ]);
  8606.             $supervisorObj $entityManager->getRepository(Employee::class)->findOneBy([                
  8607.                 'employeeId'  => $supervisorId                    
  8608.             ]);
  8609.             //Si es administrativa, se le asigna el status uno
  8610.             $statusObj $entityManager->getRepository(SanctionStatus::class)->findOneBy([                
  8611.                 'sanctionStatusId'  => 1
  8612.             ]);
  8613.             if($type == 'monetaria')
  8614.             {
  8615.                 //Si es monetaria, de una vez se pasa al estatus final
  8616.                 $statusObj $entityManager->getRepository(SanctionStatus::class)->findOneBy([                
  8617.                     'is_final'  => 1
  8618.                 ]);               
  8619.             }
  8620.             $sanctionObj = new Sanction();
  8621.             $sanctionObj->setEmployee($employeeObj);
  8622.             $sanctionObj->setLocation($locationObj);
  8623.             $sanctionObj->setCreatedByEmployee($supervisorObj);
  8624.             $sanctionObj->setDescription($description);
  8625.             $sanctionObj->setIsActive(1);
  8626.             $sanctionObj->setSanctionDate($sanction_data);
  8627.             $sanctionObj->setSanctionType($type);
  8628.             $sanctionObj->setAmount($amount);
  8629.             $sanctionObj->setSignatureSupervisor($supSignaturePath);
  8630.             $sanctionObj->setSignatureSanctioned($agentSignaturePath);
  8631.             $sanctionObj->setSanctionStatus($statusObj);
  8632.             $sanctionObj->setCreatedAt(new \DateTime());            
  8633.             $entityManager->persist($sanctionObj);
  8634.             $entityManager->flush();
  8635.             return new JsonResponse(array('status' => 'success'));
  8636.         }
  8637.         return new JsonResponse(array('status' => 'error'));
  8638.     }
  8639.     /**
  8640.      * @Route("/get-sanctions", name="ws_get_sanctions_list", methods={"GET", "POST"})
  8641.      */
  8642.     public function getSanctionsRequest(Request $requestEntityManagerInterface $entityManager): Response
  8643.     {
  8644.         
  8645.         $data json_decode(file_get_contents("php://input"));             
  8646.         if($data)
  8647.         {   
  8648.             $employeeId   $data->employee_id;
  8649.             $supervisorId $data->supervisor_id;
  8650.             $locationId   $data->location_id;
  8651.             
  8652.             $arr = [];
  8653.             if($locationId 0)
  8654.             {
  8655.                 $list $entityManager->getRepository(Sanction::class)->findBy([
  8656.                     'Employee'          => $employeeId,
  8657.                     'Created_by_employee' => $supervisorId,
  8658.                     'Location'          => $locationId
  8659.                 ],[
  8660.                     'sanctionId' => 'DESC'
  8661.                 ]);
  8662.             } else {
  8663.                 $list $entityManager->getRepository(Sanction::class)->findBy([
  8664.                     'Employee'          => $employeeId,
  8665.                     'Created_by_employee' => $supervisorId                    
  8666.                 ],[
  8667.                     'sanctionId' => 'DESC'
  8668.                 ]);
  8669.             }  
  8670.             foreach($list as $item)
  8671.             {   
  8672.                 $pictures $entityManager->getRepository(SanctionPicture::class)->findBy([
  8673.                     'Sanction' => $item->getSanctionId(),                    
  8674.                 ]);              
  8675.                 $arr[] = [
  8676.                     'name'            => $item->getEmployee()->getName(),
  8677.                     'location_name'   => ($item->getLocation() ? $item->getLocation()->getName() : ''),
  8678.                     'sanction_id'     => $item->getSanctionId(),
  8679.                     'description'     => $item->getDescription(),
  8680.                     'sanction_date'   => $item->getSanctionDate(),
  8681.                     'sanction_status' => $item->getSanctionStatus()->getName(),
  8682.                     'pictures'        => count($pictures)
  8683.                 ];
  8684.             }
  8685.             return new JsonResponse(array('status' => 'success''data' => $arr));
  8686.         }
  8687.         return new JsonResponse(array('status' => 'error'));
  8688.     }    
  8689.     /**
  8690.      * @Route("/get-agent-request-list", name="ws_get_agent_request_list", methods={"GET", "POST"})
  8691.      */
  8692.     public function getAgentReequest(Request $requestEntityManagerInterface $entityManager): Response
  8693.     {
  8694.         
  8695.         $data json_decode(file_get_contents("php://input"));             
  8696.         if($data)
  8697.         {   
  8698.             $eid $data->eid;
  8699.             
  8700.             $forms = [];
  8701.             $formList $entityManager->getRepository(RequestTypeApply::class)->getAgentForms(); 
  8702.             foreach($formList as $form)
  8703.             {
  8704.                 $path $this->getProjectPaths();
  8705.                 if($form['img_path'])
  8706.                 {
  8707.                     $image $path['public_path'].'uploads/'.$form['img_path'];
  8708.                 } else {
  8709.                     $image '';//$path['public_path'].'assets/img/empty_user.png';
  8710.                 }
  8711.                 $forms[] = [
  8712.                     'request_type_id' => $form['request_type_id'],
  8713.                     'name'            => $form['name'],
  8714.                     'description'     => $form['description'],
  8715.                     'img_path'        => $image
  8716.                 ];
  8717.             }
  8718.             return new JsonResponse(array('status' => 'success''data' => $forms));
  8719.         }
  8720.         return new JsonResponse(array('status' => 'error'));
  8721.     }
  8722.     /**
  8723.      * @Route("/send-email-test", name="ws_send_email_test", methods={"GET", "POST"})
  8724.      */
  8725.     public function sendEmailTest(MailHelper $mailHelper): Response
  8726.     {
  8727.         exit;
  8728.         $content "<p><b>Fecha:</b> ".date('Y-m-d H:i:s')."</p>";
  8729.         $result $mailHelper::sendEmail("servicio@aguilalibreweb.com""Prueba de email"$content);
  8730.         return new JsonResponse(array('status' => 'success''msg' => $result));
  8731.     }
  8732.     
  8733.     /**
  8734.      * @Route("/shift-event", name="ws_shift_event", methods={"GET", "POST"})
  8735.      */
  8736.     public function shiftEvent(Request $requestMailHelper $mailHelperEntityManagerInterface $entityManager): Response
  8737.     {
  8738.         
  8739.         $data json_decode(file_get_contents("php://input"));             
  8740.         if($data)
  8741.         {   
  8742.             $seid  $data->seid;               
  8743.             $type $data->type
  8744.             $shiftEmployeeObj $entityManager->getRepository(ShiftEmployee::class)->findOneBy([                
  8745.                 'shiftEmployeeId'  => $seid                    
  8746.             ]);
  8747.             if($shiftEmployeeObj)
  8748.             {
  8749.                 $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  8750.                     'employeeId'  => $shiftEmployeeObj->getEmployee()->getEmployeeId()                    
  8751.                 ]);    
  8752.                 $locationObj $entityManager->getRepository(Location::class)->findOneBy([                
  8753.                     'locationId'  => $shiftEmployeeObj->getLocation()->getLocationId()
  8754.                 ]); 
  8755.                 if($type == 'empty')
  8756.                 {
  8757.                     $shiftEventObj = new ShiftEvent();
  8758.                     $shiftEventObj->setShiftEmployee($shiftEmployeeObj);
  8759.                     $shiftEventObj->setEmployee($employeeObj);
  8760.                     $shiftEventObj->setLocation($locationObj);
  8761.                     $shiftEventObj->setIsEmptyEvent(1);
  8762.                     $shiftEventObj->setIsActive(1);
  8763.                     $shiftEventObj->setIsPanic(0);
  8764.                     $shiftEventObj->setCreatedAt(new \DateTime());                    
  8765.                     $entityManager->persist($shiftEventObj);
  8766.                     $entityManager->flush();
  8767.                     $lastReport "";//$this->getLastReport($entityManager, $eid, $lid);
  8768.                     //--------------- ALERTA DE EMAILS ---------------//
  8769.                     $emailAlertObj $entityManager->getRepository(EmailAlert::class)->findOneBy([                
  8770.                         'emailAlertId' => 1
  8771.                     ]);
  8772.                     if($emailAlertObj->getEmail())
  8773.                     {
  8774.                         $content "<p>El agente ".$employeeObj->getName()." ha reportado que no ha tenido novedades en su turno.</p>";                        
  8775.                         $content .= "<p><b>Ubicación:</b> ".$locationObj->getName()."</p>";
  8776.                         $content .= "<p><b>Fecha:</b> ".date('Y-m-d H:i:s')."</p>";
  8777.                         $mailHelper::sendEmail($emailAlertObj->getEmail(), "Reporte sin novedad - ".$employeeObj->getName(), $content);
  8778.                     };
  8779.                     //--------------- ALERTA DE EMAILS ---------------//
  8780.                     
  8781.                     return new JsonResponse(array('status' => 'success''last_report' => $lastReport));
  8782.                 }
  8783.                 if($type == 'panic')
  8784.                 {
  8785.                     $shiftEventObj = new ShiftEvent();
  8786.                     $shiftEventObj->setShiftEmployee($shiftEmployeeObj);
  8787.                     $shiftEventObj->setEmployee($employeeObj);
  8788.                     $shiftEventObj->setLocation($locationObj);
  8789.                     $shiftEventObj->setIsEmptyEvent(0);
  8790.                     $shiftEventObj->setIsActive(1);
  8791.                     $shiftEventObj->setIsPanic(1);
  8792.                     $shiftEventObj->setIsPanicActive(1);
  8793.                     $shiftEventObj->setCreatedAt(new \DateTime());                    
  8794.                     $entityManager->persist($shiftEventObj);
  8795.                     $entityManager->flush();
  8796.                     $lastReport $this->getLastReport($entityManager$shiftEmployeeObj->getEmployee()->getEmployeeId(), $shiftEmployeeObj->getLocation()->getLocationId());
  8797.                     return new JsonResponse(array('status' => 'success''last_report' => $lastReport));
  8798.                 }
  8799.                 /*if($employeeObj)
  8800.                 {                
  8801.                     $currentShiftObj = $entityManager->getRepository(EmployeeShift::class)->getCurrentShift($employeeObj->getEmployeeId());
  8802.                     if($currentShiftObj)
  8803.                     {
  8804.                         $data = [
  8805.                             'employee_id' => $employeeObj->getEmployeeId(),
  8806.                             'name'        => $employeeObj->getName(),
  8807.                             'alias'       => $employeeObj->getAlias(),
  8808.                             'position'    => $employeeObj->getJobPosition()->getName(),
  8809.                             'current_shift_id'    => $currentShiftObj['employee_shift_id'],
  8810.                             'current_location_id' => $currentShiftObj['location_id']
  8811.                         ];
  8812.                         return new JsonResponse(array('status' => 'success', 'data' => $data, 'message' => 'Bienvenido '.$employeeObj->getName()));
  8813.                     } else {
  8814.                         return new JsonResponse(array('status' => 'error', 'message' => 'El empleado no tiene turno asignado'));
  8815.                     }
  8816.                 }*/
  8817.             }
  8818.         }
  8819.         return new JsonResponse(array('status' => 'error'));
  8820.     }   
  8821.     
  8822.     
  8823.     /**
  8824.      * @Route("/vehicle-panic", name="ws_vehicle_panic", methods={"GET", "POST"})
  8825.      */
  8826.     public function vehiclePanic(Request $requestEntityManagerInterface $entityManager): Response
  8827.     {
  8828.         
  8829.         $data json_decode(file_get_contents("php://input"));             
  8830.         if($data)
  8831.         {   
  8832.             $eid   $data->eid;               
  8833.             $plate $data->plate
  8834.             $employeeObj $entityManager->getRepository(Employee::class)->findOneBy([                
  8835.                 'employeeId'  => $eid                    
  8836.             ]);
  8837.             if($employeeObj)
  8838.             {
  8839.             
  8840.                 $vehiclePanicObj $entityManager->getRepository(VehiclePanic::class)->findOneBy([                
  8841.                     'created_by_employee_id'  => $eid,
  8842.                     'is_active' => 1                                        
  8843.                 ]);
  8844.                 if($vehiclePanicObj)
  8845.                 {
  8846.                     return new JsonResponse(array('status' => 'error''message' => 'Ya existe una alerta activa'));
  8847.                 } else {
  8848.                     $shiftEventObj = new VehiclePanic();
  8849.                     $shiftEventObj->setPlateNumber($plate);
  8850.                     $shiftEventObj->setCreatedByEmployeeId($employeeObj);
  8851.                     $shiftEventObj->setIsActive(1);                
  8852.                     $shiftEventObj->setCreatedAt(new \DateTime());                    
  8853.                     $entityManager->persist($shiftEventObj);
  8854.                     $entityManager->flush();
  8855.                     //$lastReport = $this->getLastReport($entityManager, $shiftEmployeeObj->getEmployee()->getEmployeeId(), $shiftEmployeeObj->getLocation()->getLocationId());
  8856.                     $lastReport "";
  8857.                     return new JsonResponse(array('status' => 'success''last_report' => $lastReport));
  8858.                 }
  8859.             }
  8860.         }
  8861.         return new JsonResponse(array('status' => 'error''No se puede generar la alerta en este momento'));
  8862.     }       
  8863.     /**
  8864.      * @Route("/check_user", name="ws_index", methods={"GET", "POST", "OPTIONS"})
  8865.      */
  8866.     public function checkUserAction(Request $requestEntityManagerInterface $entityManager): Response
  8867.     {
  8868.      
  8869.             $paths $this->getProjectPaths();          
  8870.             $data json_decode(file_get_contents("php://input"));
  8871.         
  8872.            if($data)
  8873.            {
  8874.                $user  $data->user;
  8875.                $pwd   $data->pwd;
  8876.                $token $data->token;
  8877.                
  8878.                $em $this->getDoctrine()->getManager();
  8879.                $user $em->getRepository(User::class)->findOneBy(array(
  8880.                    "email" => $user,
  8881.                    'status' => 'ACTIVO',
  8882.                    'UserRole' => ['1','3']
  8883.                ));
  8884.                
  8885.                if($user)
  8886.                {
  8887.                    
  8888.                     if($this->checkCredentials($pwd$user))
  8889.                     {                                                                                                
  8890.                         
  8891.                         $data = [
  8892.                             'id'         => $user->getId(),
  8893.                             'name'       => $user->getFirstName()." ".$user->getLastName(),
  8894.                             'first_name' => $user->getFirstName(),
  8895.                             'last_name'  => $user->getLastName(),                     
  8896.                             'email'      => $user->getEmail(),
  8897.                             'role_id'    => $user->getUserRole()->getId(),
  8898.                             'token'      => md5($user->getId()),                                                                                     
  8899.                         ];
  8900.                         $user->setToken($token);
  8901.                         $em->persist($user);
  8902.                         $em->flush();
  8903.                         return new JsonResponse(array('status' => 'success''data' => $data ));    
  8904.                     } else {
  8905.                         return new JsonResponse(array('status' => 'invalid'));
  8906.                     }
  8907.                    
  8908.                } else {
  8909.                    return new JsonResponse(array('status' => 'invalid'));           
  8910.                }
  8911.            } else {
  8912.                return new JsonResponse(array('status' => 'error'));           
  8913.            }
  8914.     }
  8915.     
  8916.     
  8917.      /**
  8918.      * @Route("/app-push/send", name="ws_app_push_send", methods={"GET", "POST"})
  8919.      */
  8920.     public function appPushSendRequest $requestEntityManagerInterface $entityManager): Response
  8921.     {
  8922.         //TODOS
  8923.         //https://dev2.datoscontinuos.net/1618/symfony5/bts_interno/public/index.php/ws/app-push/send?content=Prueba&key=8er9euj2tYigKq12iiMBRIXAOpl8Ok&type=1&sendType=1
  8924.         //Usuario
  8925.         //https://dev2.datoscontinuos.net/1618/symfony5/bts_interno/public/ws/app-push/send?content=Prueba&key=8er9euj2tYigKq12iiMBRIXAOpl8Ok&type=1&to=2&id=231
  8926.         $apiKey  $request->get('key');
  8927.         $content $request->get('content');
  8928.         //1 = Alerta, 2 = Info
  8929.         $type     $request->get('type');
  8930.         if($type == || $type == 2)
  8931.         {
  8932.             //1 = Todos, 2 = Usuario
  8933.             $sendType $request->get('to');        
  8934.             if($sendType == || $sendType == 2)
  8935.             {
  8936.                 $pushKeyObj $entityManager->getRepository(PushKey::class)->findOneBy([                
  8937.                     'api_key'  => $apiKey
  8938.                 ]);   
  8939.                 if($pushKeyObj)
  8940.                 {
  8941.                     if($type == 1)
  8942.                     {
  8943.                         $type 'Alerta';
  8944.                     } else {
  8945.                         $type 'Info';
  8946.                     }
  8947.                     
  8948.                     if(strlen($content) == 0)
  8949.                     {
  8950.                         return new JsonResponse(array('status' => 'error''message' => 'Content is required'));
  8951.                     }
  8952.                     $pushObj = new Push();
  8953.                     $pushObj->setPushKey($pushKeyObj);
  8954.                     $pushObj->setPushType($type);
  8955.                     if($sendType == 1)
  8956.                     {
  8957.                         $pushObj->setSendType('Todos');
  8958.                     } else {                
  8959.                         $pushObj->setSendType('Usuario');
  8960.                         //ID solo es requerido si TO, aca viene el user_id
  8961.                         $userId $request->get('id');
  8962.                         $userObj $entityManager->getRepository(User::class)->findOneBy([                
  8963.                             'id'  => $userId
  8964.                         ]);   
  8965.                         $pushObj->setUser($userObj);
  8966.                     }
  8967.                     
  8968.                     $pushObj->setTextContent($content);
  8969.                     $pushObj->setIsActive(1);
  8970.                     $pushObj->setIsFired(0);
  8971.                     $pushObj->setCreatedAt(new \DateTime());
  8972.                     $entityManager->persist($pushObj);
  8973.                     $entityManager->flush();
  8974.                     //---
  8975.                     if($pushObj->getSendType() == 'Todos')
  8976.                     {
  8977.                         $userRepository $entityManager->getRepository(\App\Entity\User::class);
  8978.                         $queryBuilder $userRepository->createQueryBuilder('u')->where('u.token IS NOT NULL');
  8979.                         $users $queryBuilder->getQuery()->getResult();
  8980.                         foreach($users as $value)
  8981.                         {
  8982.                             $pushUser = new \App\Entity\PushUser();
  8983.                             $pushUser->setUser($value);
  8984.                             $pushUser->setPush($pushObj);
  8985.                             $pushUser->setIsFired(0);                        
  8986.                             $pushUser->setCreatedAt(new \DateTime());
  8987.                             $entityManager->persist($pushUser);
  8988.                         }
  8989.                     }
  8990.                     if($pushObj->getSendType() == 'Usuario')
  8991.                     {
  8992.                         $userSelected $entityManager->getRepository(\App\Entity\User::class)->findOneBy(['id' => $pushObj->getUser()->getId()]);
  8993.                         if(strlen($userSelected->getToken())>0)
  8994.                         {
  8995.                             $pushUser = new \App\Entity\PushUser();
  8996.                             $pushUser->setUser($userSelected);
  8997.                             $pushUser->setPush($pushObj);
  8998.                             $pushUser->setIsFired(0);                    
  8999.                             $pushUser->setCreatedAt(new \DateTime());
  9000.                             $entityManager->persist($pushUser);
  9001.                         } else {
  9002.                             return new JsonResponse(array('status' => 'error''message' => 'This user does not have a delivery token'));
  9003.                         }
  9004.                     }
  9005.                     $entityManager->flush();
  9006.                     return new JsonResponse(array('status' => 'success''message' => $pushObj->getPushId()));
  9007.                 }
  9008.             } 
  9009.         }
  9010.         return new JsonResponse(array('status' => 'error''message' => 'Invalid API Key or parameters'));
  9011.     }
  9012.     /**
  9013.      * @Route("/playground", name="ws_playground", methods={"GET", "POST"})
  9014.      */
  9015.     public function playgroundRequest $requestEntityManagerInterface $entityManager): Response
  9016.     {
  9017.         $locationObj $entityManager->getRepository(Location::class)->findOneBy([                
  9018.             'locationId'  => 1
  9019.         ]);    
  9020.         $array json_decode($locationObj->getPolygonList());
  9021.         $polygonList = [];
  9022.         foreach($array->coordinates[0] as $item)
  9023.         {
  9024.             $polygonList[] = ['lat' => $item[1], 'lng' => $item[0]];
  9025.         }
  9026.         //$fenceArea = json_encode($polygonList);
  9027.         $point = ['lat' => 14.509689173106889'lng' => -90.57686018592483];
  9028.         $res $this->isInsidePolygon($point$polygonList);
  9029.         return new JsonResponse(array('result' => $res));
  9030.     }
  9031.     public function isInsidePolygon($point$fenceArea)
  9032.     {
  9033.         $x $point['lat']; $y $point['lng'];
  9034.         
  9035.         $inside false;
  9036.         for ($i 0$j count($fenceArea) - 1$i <  count($fenceArea); $j $i++) {
  9037.             $xi $fenceArea[$i]['lat']; $yi $fenceArea[$i]['lng'];
  9038.             $xj $fenceArea[$j]['lat']; $yj $fenceArea[$j]['lng'];
  9039.         
  9040.             $intersect = (($yi $y) != ($yj $y))
  9041.                 && ($x < ($xj $xi) * ($y $yi) / ($yj $yi) + $xi);
  9042.             if ($intersect$inside = !$inside;
  9043.         }
  9044.         
  9045.         return $inside;
  9046.     
  9047.     }
  9048.      
  9049.     /**
  9050.      * @Route("/get-terms", name="get-terms", methods={"GET", "POST"})
  9051.      */
  9052.     public function getTerms(Request $requestEntityManagerInterface $entityManager): Response
  9053.     {
  9054.         
  9055.         $data json_decode(file_get_contents("php://input"));             
  9056.         if($data)
  9057.         {               
  9058.             $helpObj $entityManager->getRepository(Help::class)->findOneBy([
  9059.                 'helpId' => 1   
  9060.             ]);    
  9061.             if($helpObj)
  9062.             {                              
  9063.                 return new JsonResponse(array('status' => 'success''content' => $helpObj->getContent(), 'name' => $helpObj->getName()));                
  9064.             }
  9065.         }
  9066.         return new JsonResponse(array('status' => 'error'));
  9067.     }  
  9068.     
  9069.     /* DE ACA PARA ABAJO NO CREO QUE SE USE */
  9070.     
  9071.     /**
  9072.      * @Route("/sendCommand", name="ws_send_command", methods={"GET", "POST"})
  9073.      */
  9074.     public function sendCommandRequest $requestEntityManagerInterface $entityManagerSmsHistory $smsHistory): Response
  9075.     {
  9076.         
  9077.         $array_test = array("to"=>"345901013148857""message" => "(P02)") ;     
  9078.         $postdata json_encode($array_test);
  9079.         
  9080.         
  9081.         
  9082.         
  9083.         $url "https://aithera.api-01.dev.pentcloud.com/api/v1/sms";
  9084.         
  9085.         
  9086.         $ch curl_init($url);
  9087.         curl_setopt($chCURLOPT_POST1);
  9088.         curl_setopt($chCURLOPT_POSTFIELDS$postdata);
  9089.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  9090.         curl_setopt($chCURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  9091.         $result curl_exec($ch);
  9092.         curl_close($ch);
  9093.         print_r ($result);
  9094.         
  9095.         $result_arr json_decode($result);
  9096.         
  9097.         /*print_r($result_arr);
  9098.             
  9099.         exit;*/
  9100.         return $result_arr;
  9101.         
  9102.     }
  9103.  
  9104.     /**
  9105.      * @Route("/getMessagesCommand", name="ws_get_messages_command", methods={"GET", "POST"})
  9106.      */
  9107.     public function getMessagesCommandRequest $requestEntityManagerInterface $entityManagerSmsHistoryRepository $smsHistoryRepository SmsStatusRepository $smsStatusRepository): Response
  9108.     {
  9109.         
  9110.         
  9111.         $array_test = array("to"=>"345901013148857""message" => "(P02)") ;
  9112.         $postdata json_encode($array_test);
  9113.         
  9114.         
  9115.         $phones = array();
  9116.         $smsStatusUpdate $smsStatusRepository->findOneBySmsStatusId(2);
  9117.         
  9118.         $smsStatus $smsStatusRepository->findOneBy( ['smsStatusId'=> '1'] );
  9119.         $smsHistory $smsHistoryRepository->findBy( ['SmsStatus' => $smsStatus'is_active' => '1'] , ["created_at" => "asc"]);
  9120.         $first_date "";
  9121.         foreach($smsHistory as $info){
  9122.             if(strlen($first_date) <= 0){
  9123.                 $first_date $info->getCreatedAt()->format("d-m-Y"); 
  9124.             }
  9125.             $phones[$info->getPhone()][$info->getSmsHistoryId()]["sms"] = $info->getSms();
  9126.             $phones[$info->getPhone()][$info->getSmsHistoryId()]["petition_response"] = $info->getPetitionResponse();
  9127.             $phones[$info->getPhone()][$info->getSmsHistoryId()]["created_at"] = $info->getCreatedAt()->format("d-m-Y");            
  9128.         }
  9129.         
  9130.         foreach($phones as $phone => $info2 ){
  9131.             $url "https://aithera.api-01.dev.pentcloud.com/api/v1/sms/".$phone;
  9132.             
  9133.             
  9134.             $ch curl_init();
  9135.             curl_setopt($chCURLOPT_URL$url);
  9136.             curl_setopt($chCURLOPT_RETURNTRANSFER1);
  9137.             $result curl_exec($ch);
  9138.             curl_close($ch);
  9139.             $result_arr json_decode($result);
  9140.             $compare = array();
  9141.             
  9142.             foreach($result_arr as $info3){
  9143.                 $compare[$info3->timestamp][$info3->from] = $info3;
  9144.             }
  9145.             
  9146.             foreach($info2 as $smsHistoryId => $details){
  9147.                 $petition_arr json_decode($details["petition_response"]);
  9148.                 
  9149.                 if(isset($petition_arr->response->timestamp)) {
  9150.                     $timeStamp $petition_arr->response->timestamp;
  9151.                     if(isset($compare[$timeStamp][$petition_arr->phone] ) ){
  9152.                         $response_encode json_encode($compare[$timeStamp][$petition_arr->phone]);
  9153.                         
  9154.                         $smsHistoryUpdate $smsHistoryRepository->findOneBy( ['smsHistoryId'=> $smsHistoryId] );
  9155.                         
  9156.                         $smsHistoryUpdate->setResponse($response_encode);
  9157.                         $smsHistoryUpdate->setUpdatedAt( new \Datetime() );
  9158.                         $smsHistoryUpdate->setSmsStatus$smsStatusUpdate );
  9159.                         $entityManager->persist($smsHistoryUpdate);
  9160.                         $entityManager->flush(); 
  9161.                         
  9162.                         
  9163.                         echo "<br><br>";
  9164.                     }else{
  9165.                         echo "no esta seteado el valor";
  9166.                     }
  9167.                 }else{
  9168.                     
  9169.                 }
  9170.                 
  9171.             }
  9172.             
  9173.         }
  9174.         exit;
  9175.         
  9176.        
  9177.         
  9178.     }
  9179.     
  9180.     /**
  9181.      * @Route("/getAllMessagesCommand", name="ws_get_all_messages_command", methods={"GET", "POST"})
  9182.      */
  9183.     public function getAllMessagesCommandRequest $requestEntityManagerInterface $entityManagerSmsHistoryRepository $smsHistoryRepository SmsStatusRepository $smsStatusRepository): Response
  9184.     {
  9185.         
  9186.         
  9187.         $phone "345901013149211";
  9188.         $url "https://aithera.api-01.dev.pentcloud.com/api/v1/sms/".$phone;
  9189.         
  9190.         
  9191.         $ch curl_init();
  9192.         curl_setopt($chCURLOPT_URL$url);
  9193.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  9194.         $result curl_exec($ch);
  9195.         curl_close($ch);
  9196.         $result_arr json_decode($result);
  9197.         
  9198.         var_dump($result_arr);
  9199.         
  9200.         exit;
  9201.     }
  9202.     
  9203.     /**
  9204.      * @Route("/supervisor-agent-inventory-server-values", name="supervisor-agent-inventory-server-values", methods={"GET", "POST"})
  9205.      */
  9206.     public function supervisorInventoryAgentServerValues(Request $requestEntityManagerInterface $entityManagerHelperService $helperService): Response
  9207.     {
  9208.       
  9209.         $data json_decode(file_get_contents("php://input"));             
  9210.         if($data)
  9211.         {   
  9212.               $employeeId        $data->employee_id;
  9213.               $employee $entityManager->getRepository(Employee::class)->findOneBy([
  9214.                   'employeeId'    => $employeeId
  9215.               ]);
  9216.               $idEstadoDeFuerza $employee->getAlias();
  9217.               $inventory_weapon  $helperService->externalDb_getWeaponAssignInfo($idEstadoDeFuerza);
  9218.               $data = [
  9219.                   'inventory_weapon' => $inventory_weapon,
  9220.                   'inventory_phone'  => '',
  9221.                   'inventory_radio'  => ''
  9222.               ];
  9223.               return new JsonResponse(array('status' => 'success''data' => $data));                
  9224.             
  9225.         }
  9226.     
  9227.         return new JsonResponse(array('status' => 'error'));
  9228.     
  9229.     }
  9230.     
  9231.     
  9232. }