src/MDS/AvexpressBundle/Controller/FilesController.php line 744

Open in your IDE?
  1. <?php
  2. namespace App\MDS\AvexpressBundle\Controller;
  3. use App\Entity\Cities;
  4. use App\Entity\Client;
  5. use App\Entity\Configuration;
  6. use App\Entity\Country;
  7. use App\Entity\Destination;
  8. use App\Entity\Regions;
  9. use App\Entity\SettingsCompany;
  10. use App\Entity\User;
  11. use App\Entity\HtFile;
  12. use App\MDS\AvexpressBundle\Entity\AveBenefitsSupplier;
  13. use App\MDS\AvexpressBundle\Entity\AveBriefings;
  14. use App\MDS\AvexpressBundle\Entity\AveBudgetPending;
  15. use App\MDS\GreenPatioBundle\Entity\Reservation;
  16. use Doctrine\ORM\EntityManagerInterface;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use DateTime;
  21. use App\MDS\AvexpressBundle\Entity\AveFiles;
  22. use App\MDS\AvexpressBundle\Entity\AveBudgetToProforma;
  23. use App\MDS\AvexpressBundle\Entity\AveDocInvoice;
  24. use App\MDS\AvexpressBundle\Entity\AveDocInvoiceItems;
  25. use App\MDS\AvexpressBundle\Entity\AveDocInvoiceRec;
  26. use App\MDS\AvexpressBundle\Entity\AveDocInvoiceRecItems;
  27. use App\MDS\AvexpressBundle\Entity\AveDocProforma;
  28. use App\MDS\AvexpressBundle\Entity\AveDocProformaItems;
  29. use App\MDS\AvexpressBundle\Entity\AvePaymentsClient;
  30. use App\MDS\AvexpressBundle\Entity\AveProduct;
  31. use App\MDS\AvexpressBundle\Entity\AveProductFile;
  32. use App\MDS\AvexpressBundle\Entity\AveServices;
  33. use App\MDS\DevelupBundle\Entity\MdvTelegramUser;
  34. use App\MDS\EventsBundle\Entity\Proposal;
  35. use App\MDS\EventsBundle\Entity\ProposalAgents;
  36. use App\MDS\EventsBundle\Entity\ProposalInvoice;
  37. use App\MDS\EventsBundle\Entity\ProposalSupplierControl;
  38. use App\MDS\EventsBundle\Entity\ProposalSupplierServices;
  39. use Swift_Mailer;
  40. use Swift_Message;
  41. use Swift_SmtpTransport;
  42. use Symfony\Contracts\Translation\TranslatorInterface;
  43. class FilesController extends AbstractController
  44. {
  45.     private $translator;
  46.     public function __construct(TranslatorInterface $translator) {
  47.         $this->translator $translator;
  48.     }
  49.     
  50.     /**
  51.      * @Route("/fileadd/",  name="ave_add_file")
  52.      * Agregar un expediente
  53.      */
  54.     public function addFileActionRequest $request)
  55.     {
  56.         $em $this->getDoctrine()->getManager();
  57.         $clients $em->getRepository(Client::class)->findAll();
  58.         $destinations $em->getRepository(Destination::class)->findAll();
  59.         $aveFiles $em->getRepository(AveFiles::class)->findAll();
  60.         $id =0;
  61.         if (empty($aveFiles)){
  62.             $id ++;
  63.         } else {
  64.             $lastElem end($aveFiles);
  65.             $id $lastElem->getId() + 1;
  66.         }
  67.         return $this->render('MDS/AvexpressBundle/Avexpress/add-files.html.twig',
  68.             array(
  69.                 'id' => $id,
  70.                 'clients' => $clients,
  71.                 'destinations' => $destinations,
  72.                 'clientId' => 0,
  73.             ));
  74.     }
  75.     /**
  76.      * @Route("/filelist/",  name="ave_list_file")
  77.      * Listar expedientes
  78.      */
  79.     public function listFileActionRequest $requestEntityManagerInterface $em)
  80.     {
  81.         $idgroup null;
  82. //        $parameters = array( 'status' => 'Deleted' );
  83. //
  84. //        $dql = 'SELECT i
  85. //                FROM AvexpressBundle:AveFiles i
  86. //                WHERE i.status != :status
  87. //                ORDER BY i.dateStart DESC ';
  88. //        $query = $em->createQuery($dql)->setParameters($parameters);
  89.         $ref = [];
  90. //
  91. //        $reservas = $query->getResult();
  92.         $dql 'SELECT i.id, i.title, i.client, i.status, i.idProposal, i.dateStart, i.dateEnd, i.createdId,        
  93.                      r.id AS reservation_id
  94.                     FROM AvexpressBundle:AveFiles i
  95.                     LEFT JOIN i.reservation r
  96.                     WHERE i.status != :status
  97.                     ORDER BY i.dateStart DESC
  98.                 ';
  99.         $query $em->createQuery($dql)->setParameter('status''Deleted');
  100.         $reservas $query->getArrayResult();
  101.         foreach ($reservas as $key => $res) {
  102.             $client $em->getRepository(Client::class)->findOneById($res['client']);
  103.             $reservas[$key]['client'] = (!empty($client)) ? $client->getName() : null;
  104.             if (!empty($res['dateStart']) and !empty($res['dateEnd'])) {
  105.                 $ref[$res['id']] = '#' . ($res['dateStart'])->format('ymd') . ($res['dateEnd'])->format('ymd');
  106.             } else {
  107.                 $ref[$res->getId()] = '#' '000000' '000000';
  108.             }
  109.         }
  110.         $reservasZero = array();
  111.         foreach ($reservas as $res) {
  112.             $reservasZero[] = array(
  113.                 'dateStart' => $res['dateStart'],
  114.                 'dateEnd' => $res['dateEnd'],
  115.                 'id' => $res['id'],
  116.                 'title' => $res['title'],
  117.                 'client' => $res['client'],
  118.                 'createdId' => $res['createdId'],
  119.                 'ref' => $ref[$res['id']],
  120.                 'reservation' => $res['reservation_id'],
  121.             );
  122.         }
  123.         $reservas $reservasZero;
  124.         return $this->render('MDS/AvexpressBundle/Avexpress/list-files.html.twig',
  125.             array(
  126.                 'groups' => null,
  127.                 'listofdeletedfiles' => false,
  128.                 'reservations' => $reservas
  129.             )
  130.         );
  131.     }
  132.     /**
  133.      * @Route("/filesave/",  name="ave_save_file")
  134.      * Guardar un expediente nuevo
  135.      */
  136.     public function saveFileActionRequest $request)
  137.     {
  138.         $em $this->getDoctrine()->getManager();
  139.         $newRequest $request->request->get('avexpress');
  140.         if (empty($newRequest['title'])){ return $this->redirectToRoute('ave_add_file'); }
  141.         /* Obtengo usuario logueado */
  142.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  143.         $user_id $user_logueado->getId();
  144.         $newFile = new AveFiles();
  145.         $newFile->setTitle($newRequest['title']);
  146.         $newFile->setClient($newRequest['client']);
  147.         if (!empty($newRequest['idProposal'])){
  148.             $newFile->setIdProposal($newRequest['idProposal']);
  149.         } else {
  150.             $newFile->setIdProposal(null);
  151.         }
  152.         $newFile->setStatus($newRequest['status']);
  153.         $newFile->setAdvancePayment($newRequest['advancePayment']);
  154.         $newFile->setDescription($newRequest['description']);
  155.         if (empty($newRequest['dateStart'])){
  156.             $newFile->setDateStart(new \DateTime("now"));
  157.         } else {
  158.             $newFile->setDateStart(new \DateTime($newRequest['dateStart']));}
  159.         if (empty($newRequest['dateEnd'])){
  160.             $newFile->setDateEnd(new \DateTime("now"));
  161.         } else {
  162.             $newFile->setDateEnd(new \DateTime($newRequest['dateEnd']));}
  163.         if (!empty($newRequest['destination'])){
  164.             $newFile->setDestinoId($newRequest['destination']);
  165.         }
  166.         $newFile->setCreatedId($user_id);
  167.         $newFile->setUpdatedId($user_id);
  168.         $newFile->setCreatedAt(new \DateTime("now"));
  169.         $newFile->setUpdatedAt(new \DateTime("now"));
  170.         $em->persist($newFile);
  171.         $em->flush();
  172.         $clients $em->getRepository(Client::class)->findAll();
  173.         $products $em->getRepository(AveProduct::class)->findAll();
  174.         $data $this->calculosFile($newFile->getId(), null0'File');
  175.         $sumatoriaTotalNet 0;
  176.         $sumatoriaTotalVat 0;
  177.         $sumatoriaTotal 0;
  178.         $resultados = array(
  179.             'totalNeto' => $sumatoriaTotalNet,
  180.             'vat' => $sumatoriaTotalVat,
  181.             'total' => $sumatoriaTotal,
  182.         );
  183.         $productInFile $em->getRepository(AveProductFile::class)->findByFileId($newFile->getId());
  184.         $numeroItems sizeof($productInFile);
  185.         return $this->redirectToRoute('ave_edit_file', array( 'id' => $newFile->getId() ));
  186.     }
  187.     /**
  188.      * @Route("/fileupdate/{id}",  name="ave_update_file")
  189.      * Actualizar un expediente
  190.      */
  191.     public function updateFileAction($idRequest $request)
  192.     {
  193.         $logTelegram false;
  194.         $numberToPrefix 0;
  195.         $em $this->getDoctrine()->getManager();
  196.         $newFile $em->getRepository(AveFiles::class)->findOneById($id);
  197.         $newRequest $request->request->get('avexpress');
  198.         $srvInconsistentes '';                    // Mensaje de alerta por inconsistencia en los servicios
  199.         // INICIO: Si existe un documento creado no se puede cambiar el cliente
  200.         $oldDoc $em->getRepository(AveDocInvoice::class)->findOneByFileId($id);
  201.         $noexistefactura = empty($oldDoc);
  202.         // FIN: Si existe un documento creado no se puede cambiar el cliente
  203.         /* Obtengo usuario logueado */
  204.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  205.         $user_id $user_logueado->getId();
  206.         if (!empty($newRequest['title'])){$newFile->setTitle($newRequest['title']);}
  207.         if ($noexistefactura)
  208.             {
  209.                 $newFile->setClient($newRequest['client']);
  210.                 $msjErrorClt '';
  211.             }
  212.         else
  213.             { /* Hay una factura, no se debe cambiar el cliente */
  214.                 // Verificamos si intenta cambiar el cliente para informar que no es posible hacerlo
  215.                 if (!($newFile->getClient() == $newRequest['client'])){
  216.                     $msjErrorClt 'El cliente no puede ser modificado, ya existe una factura previa';
  217.                 } else {
  218.                     $msjErrorClt '';
  219.                 }
  220.             }
  221.         if (!empty($newRequest['idProposal'])){$newFile->setIdProposal($newRequest['idProposal']);} else {$newFile->setIdProposal(null);}
  222.         $newFile->setStatus($newRequest['status']);
  223.         $newFile->setDescription($newRequest['description']);
  224.         $newFile->setUpdatedId($user_id);
  225.         $newFile->setUpdatedAt(new \DateTime("now"));
  226.         if (!empty($newRequest['destination'])){$newFile->setDestinoId($newRequest['destination']);}
  227.         if (!empty($newRequest['dateStart'])){$newFile->setDateStart(new DateTime($newRequest['dateStart']));}
  228.         if (!empty($newRequest['dateEnd'])){$newFile->setDateEnd(new DateTime($newRequest['dateEnd']));}
  229.         if (!empty($newRequest['xtraFieldOne'])){$newFile->setXtraFieldOne($newRequest['xtraFieldOne']);}
  230.         try{
  231.             $em->persist($newFile);
  232.             $em->flush();
  233.             $event 'El expediente ha sido actualizado. ';
  234.             if (!empty($msjErrorClt)){ $event $event.$msjErrorClt; }
  235.             $successMessage $this->translator->trans($event);
  236.             $this->addFlash('mensajeav'$successMessage);
  237.         } catch (\Exception $e){
  238.             $event 'An error occurred: '.$e->getMessage();
  239.             /* Para el usuario */
  240.             $errorMessage $this->translator->trans($event);
  241.             $this->addFlash('mensajeaverror'$errorMessage);
  242.         }
  243.         $productInFile $em->getRepository(AveProductFile::class)->findByFileId($newFile->getId());
  244.         $txtWarning '';
  245.         if(!empty($newFile->getIdProposal())){
  246.             // El expediente se ha relacionado con un proposal, se debe actualizar en eventos
  247.             $file $newFile;
  248.             // Si hay proposal se debe actualizar en el expediente de Eventos
  249.             if (!empty($file->getIdProposal()) and is_numeric($file->getIdProposal())){
  250.                 // Buscamos el destino donde se encuentre Avexpress y ahi agregamos el servicio, si no se encuentra no se agregara el servicio
  251.                 $control $em->getRepository(ProposalSupplierControl::class)->findOneBy(
  252.                     array(
  253.                         'supplierId' => 80,                                          // El supplier 80 es Avexpress
  254.                         'proposalId' => $file->getIdProposal(),
  255.                     )
  256.                 );
  257.                 // INICIO: Buscamos la info del lado de eventos (SINCRONIZACION)
  258.                 $txtOfChanges ''//Mensaje para el agente de cambios en los servicios hechos desde AvExpress
  259.                 $proposal $em->getRepository(Proposal::class)->findOneById($file->getIdProposal());
  260.                 $agent $em->getRepository(User::class)->findOneById($proposal->getAgentId());
  261.                 $agentFullName $agent->getName().' '.$agent->getLastName();
  262.                 $proposalTitle $proposal->getId().' - '.$proposal->getTitle();
  263.                 // FIN: Buscamos la info del lado de eventos
  264.                 foreach ($productInFile as $item){
  265.                     //Si las fechas de inicio y fin no coinciden con el campo dias se debe enviar alerta
  266.                     $txtWarning = ($item->getDateOutAt()->diff($item->getDateInAt()))->days <> $item->getDays() ? '<br>'.$item->getProductName() : '';
  267.                     if (!empty($txtWarning)){
  268.                         if (empty($srvInconsistentes)){ $srvInconsistentes 'Hay inconsistencias en: '.'<br>'.$txtWarning; } else { $srvInconsistentes $srvInconsistentes.'<br>'.$txtWarning; }
  269.                     }
  270.                     if (!empty($control)){
  271.                         // Existe un destino con AvExpress como proveedor, ahĆ­ se agregara el servicio
  272.                         $yaexistiaunservicio false$proposalServicex null;
  273.                         // Se verifica que no el productfile Av no tenga imagen en Eventos
  274.                         if (!empty($item->getOriginId())){
  275.                             // Se verifica que aun exista en Eventos  el servicio
  276.                             $proposalServicex $em->getRepository(ProposalSupplierServices::class)->findOneById($item->getOriginId());
  277.                             if (!empty($proposalServicex)){ $yaexistiaunservicio true; } else { $yaexistiaunservicio false; }
  278.                         } else {
  279.                             // no estaba relacionado con nada en eventos, se crea uno nuevo
  280.                             $yaexistiaunservicio false;
  281.                         }
  282.                         if ($yaexistiaunservicio){
  283.                             $prpInv $em->getRepository(ProposalInvoice::class)->findOneByProposalId($file->getIdProposal());
  284.                             if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
  285.                                 $service $proposalServicex;
  286.                                 $oldServiceEvent = array(
  287.                                     'activityId' => $service->getActivityId(),
  288.                                     'assistantId' => $service->getAssistantId(),
  289.                                     'breakdown' => $service->getBreakdown(),
  290.                                     'commission' => $service->getCommission(),
  291.                                     'controlId' => $service->getControlId(),
  292.                                     'currency' => $service->getCurrency(),
  293.                                     'dateBlockLimit' => $service->getDateBlockLimit(),
  294.                                     'dateInAt' => $service->getDateInAt(),
  295.                                     'dateOutAt' => $service->getDateOutAt(),
  296.                                     'destinationId' => $service->getDestinationId(),
  297.                                     'directPayment' => $service->getDirectPayment(),
  298.                                     'hour' => $service->getHour(),
  299.                                     'ideaId' => $service->getIdeaId(),
  300.                                     'isFather' => $service->getIsFather(),
  301.                                     'iva' => $service->getIva(),
  302.                                     'name' => $service->getName(),
  303.                                     'opCommission' => $service->getOpCommission(),
  304.                                     'opIva' => $service->getOpIva(),
  305.                                     'opOver' => $service->getOpOver(),
  306.                                     'originalIva' => $service->getOriginalIva(),
  307.                                     'originalPrice' => $service->getOriginalPrice(),
  308.                                     'originalopIva' => $service->getOriginalopIva(),
  309.                                     'over' => $service->getOver(),
  310.                                     'pax' => $service->getPax(),
  311.                                     'preCommission' => $service->getPreCommission(),
  312.                                     'preIva' => $service->getPreIva(),
  313.                                     'price' => $service->getPrice(),
  314.                                     'proposalId' => $service->getProposalId(),
  315.                                     'rank' => $service->getRank(),
  316.                                     'serviceCatId' => $service->getServiceCatId(),
  317.                                     'serviceCatName' => $service->getServiceCatName(),
  318.                                     'serviceId' => $service->getServiceId(),
  319.                                     'serviceIdFather' => $service->getServiceIdFather(),
  320.                                     'status' => $service->getStatus(),
  321.                                     'statusRec' => $service->getStatusRec(),
  322.                                     'statusinternal' => $service->getStatusinternal(),
  323.                                     'supplierId' => $service->getSupplierId(),
  324.                                     'units' => $service->getUnits(),
  325.                                 );
  326.                                 $service->setName($item->getProductName());
  327.                                 // Se verifican los precios en ambas partes (AV Express e InOut)
  328.                                 if (!($service->getPrice() == $item->getServicePrice())) {
  329.                                     // Si ambos precios unitarios son distintos se ha modificado el numero de dĆ­as en Av Express
  330.                                     $newPriceInOut $this->precioPorVariacionDeDias($service$item);
  331.                                     $service->setPrice($newPriceInOut);
  332.                                 } else {
  333.                                     // si son iguales tambien se deben verificar el numero de dias
  334.                                     if (!(($service->getDateOutAt()->diff($service->getDateInAt())->days 1) == $item->getDays())) {
  335.                                         $newPriceInOut $this->precioPorVariacionDeDias($service$item);
  336.                                         $service->setPrice($newPriceInOut);
  337.                                     }
  338.                                 }
  339.                                 $service->setCurrency($item->getCurrency());
  340.                                 $service->setUnits($item->getUnits());
  341. //                            $service->setCommission(0);                                       // InOut puede haber metido una Comision y no se le debe modificar
  342. //                            $service->setOver(0);                                             // InOut puede haber metido un Over y no se le debe modificar
  343.                                 $service->setIva(21);
  344.                                 if (empty($item->getPax())) {
  345.                                     $service->setPax(1);
  346.                                 } else {
  347.                                     $service->setPax($item->getPax());
  348.                                 }
  349.                                 $service->setHour(null);
  350.                                 $service->setDateInAt($item->getDateInAt());
  351.                                 $service->setDateOutAt($item->getDateOutAt());
  352.                                 $service->setDirectPayment(0);
  353. //                            $service->setStatus('Pending');                                   // InOut puede haber Confirmado y no se le debe modificar
  354.                                 $service->setStatusinternal('Additional');
  355.                                 $service->setPreCommission(null);
  356.                                 $service->setPreIva(null);
  357.                                 $service->setDateBlockLimit(null);
  358. //                            $service->setOpCommission(1);                                     // InOut puede haber metido una Op Comision y no se le debe modificar
  359. //                            $service->setOpOver(1);                                           // InOut puede haber metido una Op Over y no se le debe modificar
  360. //                            $service->setOpIva(1);                                            // InOut puede haber metido una Op Iva y no se le debe modificar
  361.                                 $service->setBreakdown(0);
  362.                                 $service->setIsFather(0);
  363.                                 $service->setRank($this->rankAvParaInOutService($item->getId()));
  364.                                 $service->setOriginalopIva(1);
  365.                                 $service->setStatusRec('normal');
  366.                                 $service->setCreatedId($user_id);
  367.                                 $service->setUpdatedId($user_id);
  368.                                 $em->persist($service);
  369.                                 $em->flush();
  370.                                 // Se debe notificar por Telegram al agente de eventos
  371.                                 $logTelegram true;
  372.                                 //Verificamos cambios e informamos al agente del proposal
  373.                                 $boolChanges false;
  374.                                 if (!($service->getRank() == $oldServiceEvent['rank'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Orden</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['rank'].', su nuevo valor es: '.$service->getRank().'<br>'$boolChanges true; }
  375.                                 if (!($service->getName() == $oldServiceEvent['name'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Nombre</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['name'].', su nuevo valor es: '.$service->getName().'<br>'$boolChanges true; }
  376.                                 if (!($service->getPrice() == $oldServiceEvent['price'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Precio</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['price'].', su nuevo valor es: '.$service->getPrice().'<br>'$boolChanges true; }
  377.                                 if (!($service->getCurrency() == $oldServiceEvent['currency'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Moneda</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['currency'].', su nuevo valor es: '.$service->getCurrency().'<br>'$boolChanges true; }
  378.                                 if (!($service->getUnits() == $oldServiceEvent['units'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Cantidad</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['units'].', su nuevo valor es: '.$service->getUnits().'<br>'$boolChanges true; }
  379.                                 if (!($service->getPax() == $oldServiceEvent['pax'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Personas</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['pax'].', su nuevo valor es: '.$service->getPax().'<br>'$boolChanges true; }
  380.                                 if (!($service->getOpOver() == $oldServiceEvent['opOver'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Opción (-/+) del Over</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['opOver'].', su nuevo valor es: '.$service->getOpOver().'<br>'$boolChanges true; }
  381.                                 if (!($service->getOver() == $oldServiceEvent['over'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Over</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['over'].', su nuevo valor es: '.$service->getOver().'<br>'$boolChanges true; }
  382.                                 if (!($service->getOpCommission() == $oldServiceEvent['opCommission'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Opción (-/+) de la Comisión</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['opCommission'].', su nuevo valor es: '.$service->getOpCommission().'<br>'$boolChanges true; }
  383.                                 if (!($service->getCommission() == $oldServiceEvent['commission'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Comisión" ha sido modificado. Su valor era: '.$oldServiceEvent['commission'].', su nuevo valor es: '.$service->getCommission().'<br>'$boolChanges true; }
  384.                                 if (!($service->getOpIva() == $oldServiceEvent['opIva'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Opción (-/+) del Iva</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['opIva'].', su nuevo valor es: '.$service->getOpIva().'<br>'$boolChanges true; }
  385.                                 if (!($service->getIva() == $oldServiceEvent['iva'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Iva</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['iva'].', su nuevo valor es: '.$service->getIva().'<br>'$boolChanges true; }
  386.                                 if (!($service->getDateInAt()->format('H:i') == $oldServiceEvent['dateInAt']->format('H:i'))){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Hora inicio</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['dateInAt']->format('H:i').', su nuevo valor es: '.$service->getDateInAt()->format('H:i').'<br>'$boolChanges true; }
  387.                                 if (!($service->getDateInAt()->format('Ymd') == $oldServiceEvent['dateInAt']->format('Ymd'))){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Fecha inicio</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['dateInAt']->format('d/m/Y').', su nuevo valor es: '.$service->getDateInAt()->format('d/m/Y').'<br>'$boolChanges true; }
  388.                                 if (!($service->getDateOutAt()->format('H:i') == $oldServiceEvent['dateOutAt']->format('H:i'))){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Hora fin</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['dateOutAt']->format('H:i').', su nuevo valor es: '.$service->getDateOutAt()->format('H:i').'<br>'$boolChanges true; }
  389.                                 if (!($service->getDateOutAt()->format('Ymd') == $oldServiceEvent['dateOutAt']->format('Ymd'))){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Fecha fin</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['dateOutAt']->format('d/m/Y').', su nuevo valor es: '.$service->getDateOutAt()->format('d/m/Y').'<br>'$boolChanges true; }
  390.                             } else {
  391.                                 $srvAlreadyInvoiced 'Error al sincronizar. <br><br> InOut ya ha facturado.';
  392.                                 $this->addFlash('mensajeaverror'$srvAlreadyInvoiced);
  393.                             }
  394.                         } else{
  395.                             $prpInv $em->getRepository(ProposalInvoice::class)->findOneByProposalId($file->getIdProposal());
  396.                             if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
  397.                                 $service = new ProposalSupplierServices();
  398.                                 $service->setServiceIdFather(0);
  399.                                 $service->setControlId($control->getId());
  400.                                 $service->setProposalId($file->getIdProposal());
  401.                                 $service->setDestinationId($control->getDestinoId());
  402.                                 $service->setSupplierId(80);                                    // 80 es AvExpress
  403.                                 $service->setIdeaId(null);
  404.                                 $service->setServiceId($item->getProductId());
  405.                                 $service->setServiceCatName('Av');
  406.                                 $service->setServiceCatId(3);
  407.                                 $service->setName($item->getProductName());
  408.                                 $priceInOut $item->getSubTotalPrice();
  409.                                 if (!($item->getPax() == 0)) {
  410.                                     $priceInOut $priceInOut $item->getPax();                    // Se devuelve el calculo dividiendo entre personas
  411.                                 }
  412.                                 if (!($item->getUnits() == 0)) {
  413.                                     $priceInOut $priceInOut $item->getUnits();                  // Se devuelve el calculo dividiendo entre cantidades
  414.                                 }
  415.                                 if (!($item->getDays() == 0)) {
  416.                                     $priceInOut $priceInOut round($item->getDays());            // Se devuelve el calculo dividiendo entre dias, se redondea por si es 1.5
  417.                                 }
  418.                                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  419.                                 $priceInOut round($priceInOut2PHP_ROUND_HALF_UP);
  420.                                 $service->setPrice($priceInOut);
  421.                                 $service->setCurrency($item->getCurrency());
  422.                                 $service->setUnits($item->getUnits());
  423.                                 $service->setCommission(0);
  424.                                 $service->setOver(0);
  425.                                 $service->setIva(21);
  426.                                 if (empty($item->getPax())) { $service->setPax(1); } else { $service->setPax($item->getPax()); }
  427.                                 $service->setHour(null);
  428.                                 $service->setDateInAt($item->getDateInAt());
  429.                                 $service->setDateOutAt($item->getDateOutAt());
  430.                                 $service->setDirectPayment(0);
  431.                                 $service->setStatus('Pending');
  432.                                 $service->setStatusinternal('Additional');
  433.                                 $service->setPreCommission(null);
  434.                                 $service->setPreIva(null);
  435.                                 $service->setDateBlockLimit(null);
  436.                                 $service->setOpCommission(1);
  437.                                 $service->setOpOver(1);
  438.                                 $service->setOpIva(1);
  439.                                 $service->setBreakdown(0);
  440.                                 $service->setIsFather(0);
  441.                                 $service->setRank($this->rankAvParaInOutService($item->getId()));
  442.                                 $service->setOriginalopIva(1);
  443.                                 $service->setOriginalIva(null);
  444.                                 $service->setOriginalPrice(null);
  445.                                 $service->setStatusRec('normal');
  446.                                 $service->setAssistantId(null);
  447.                                 $service->setCreatedId($user_id);
  448.                                 $service->setUpdatedId($user_id);
  449.                                 $service->setCreatedAt(new \DateTime("now"));
  450.                                 $service->setUpdatedAt(new \DateTime("now"));
  451.                                 $em->persist($service);
  452.                                 $em->flush();
  453.                                 // Se relaciona el nuevo Servicio InOut con el Servicio AV
  454.                                 $item->setOriginId($service->getId());
  455.                                 $em->persist($item);
  456.                                 $em->flush();
  457.                                 // Se debe notificar por Telegram al agente de eventos
  458.                                 $logTelegram true;
  459.                             } else {
  460.                                 $srvAlreadyInvoiced 'Error al sincronizar. <br><br> InOut ya ha facturado.';
  461.                                 $this->addFlash('mensajeaverror'$srvAlreadyInvoiced);
  462.                             }
  463.                         }
  464.                     }
  465.                     // Notificamos al agente de InOut si se hicieron actualizaciones en los servicios desde AvExpress
  466.                     if (!empty($txtOfChanges)) { $this->messageOfChangesToAgent($txtOfChanges$proposal->getId()); }
  467.                     //INICIO: Creamos una orden de hacer proforma
  468.                     //INICIO: Calculamos el ID de la proforma
  469.                     $numberToPrefix $em->getRepository(AveDocProforma::class)->findAll();
  470.                     if (empty($numberToPrefix)){
  471.                         $numberToPrefix 0;
  472.                     } else {
  473.                         $numberToPrefix end($numberToPrefix)->getId();
  474.                     }
  475.                     $numberToPrefix++;
  476.                     //FIN: Calculamos el ID de la proforma
  477.                     $order = new AveBudgetToProforma();
  478.                     $order->setStatus('Pending');
  479.                     $order->setFileId($file->getId());
  480.                     $order->setProductFileId($item->getId());
  481.                     $order->setUserConfirmedId($proposal->getAgentId());
  482.                     $order->setUserConfirmedFullName($agentFullName);
  483.                     $order->setProposalTitle($proposalTitle);
  484.                     $order->setProformaId($numberToPrefix);
  485.                     $em->persist($order);
  486.                     $em->flush();
  487.                     //FIN: Creamos una orden de hacer proforma
  488.                 }
  489.                 $event 'Expediente guardado correctamente.';
  490.                 $successMessage $this->translator->trans($event);
  491.                 $this->addFlash('mensajeav'$successMessage);
  492.                 if (!empty($srvInconsistentes) and !empty($newFile->getIdProposal())){ $this->addFlash('mensajeaverror'$srvInconsistentes); }
  493.                 //INICIO: Notificamos al agente por Telegram
  494.                 if ($logTelegram){
  495.                     //Buscamos todos los agentes del proposal
  496.                     $proposalAgents $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposal->getId());
  497.                     //Buscamos el Destino
  498.                     $proposalDestino $em->getRepository(Destination::class)->findOneById($control->getDestinoId());
  499.                     //Buscamos el agente de Avexpress
  500.                     $userData $em->getRepository(User::class)->findOneById($user_id);
  501.                     if (!empty($proposalAgents) and !($user_id == 22)){
  502.                         if ((!empty($proposalAgents->getAgOne())) and (!($proposalAgents->getAgOne() == 0))){
  503.                             $this->sendTelegram($proposalAgents->getAgOne(),'1. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$proposal->getId().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  504.                         }
  505.                         if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
  506.                             $this->sendTelegram($proposalAgents->getAgTwo(),'2. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$proposal->getId().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  507.                         }
  508.                         if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
  509.                             $this->sendTelegram($proposalAgents->getAgThree(),'3. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$proposal->getId().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  510.                         }
  511.                         if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
  512.                             $this->sendTelegram($proposalAgents->getAgFour(),'4. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$proposal->getId().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  513.                         }
  514.                     }
  515.                 }
  516.                 //FIN: Notificamos al agente por Telegram
  517.                 //INICIO: Creamos el presupuesto (proforma)
  518.                 $budToPro $em->getRepository(AveBudgetToProforma::class)->findByProformaId($numberToPrefix);
  519.                 //INICIO: Se agrupan por expediente (fileId)
  520.                 $proformas = array();
  521.                 foreach ($budToPro as $item){
  522.                     $proformas[$item->getFileId()][] = $item;
  523.                 }
  524.                 //FIN: Se agrupan por expediente (fileId)
  525.                 if (!empty($budToPro)){
  526.                     foreach ($proformas as $key => $elemento){
  527.                         //INICIO: Creamos las proformas
  528.                         $newProforma = new AveDocProforma();
  529.                         $newProforma->setPrefix('AVE-' . (new DateTime('now'))->format('dmy') . '-' $numberToPrefix '-' $key);
  530.                         $newProforma->setDateAt(new DateTime('now'));
  531.                         $newProforma->setFileId($key);
  532.                         $newProforma->setCreatedId($user_id);
  533.                         $newProforma->setUpdatedId($user_id);
  534.                         $newProforma->setCreatedAt(new DateTime('now'));
  535.                         $newProforma->setUpdatedAt(new DateTime('now'));
  536. //                        $em->persist($newProforma);
  537.                         $em->flush();
  538.                         //FIN: Creamos las proformas
  539.                         foreach ($elemento as $item) {
  540.                             //$key es el id del expediente
  541.                             // $arrayIdPro['X'] = 'Y'; al agente 'Y' se le informa del presupuesto 'X'
  542.                             //INICIO: Creamos los elemento que iran dentro de las proformas
  543.                             $itemProforma = new AveDocProformaItems();
  544.                             $itemProforma->setType('PRODUCT');
  545.                             $itemProforma->setFileId($key);
  546.                             $itemProforma->setProformaId($newProforma->getId());
  547.                             $itemProforma->setControlId($item->getProductFileId());
  548. //                            $em->persist($itemProforma);
  549.                             $em->flush();
  550.                             //INICIO: Confirmamos el BudToProforma
  551. //                            $item->setStatus('Tosend');              // El elemento se ha pasado a la proforma, solo falta enviar
  552.                             $item->setProformaId($newProforma->getId());
  553. //                            $em->persist($item);
  554.                             $em->flush();
  555.                             //FIN: Confirmamos el BudToProforma
  556.                             //FIN: Creamos los elemento que iran dentro de las proformas
  557.                         }
  558.                     }
  559.                 }
  560.                 //FIN: Creamos el presupuesto (proforma)
  561.                 // INICIO: Se envia al agente el presupuesto
  562.                 $budToPro $em->getRepository(AveBudgetToProforma::class)->findByStatus('Tosend');
  563.                 /* Obtengo usuario logueado */
  564.                 $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  565.                 $user_id $user_logueado->getId();
  566.                 $arrayIdPro = array();          // $arrayIdPro['X'] = 'Y'; al agente 'Y' se le informa del presupuesto 'X'
  567.                 //INICIO: Se agrupan por expediente (fileId)
  568.                 $proformas = array();
  569.                 foreach ($budToPro as $item){
  570.                     $proformas[$item->getFileId()][] = $item;
  571.                 }
  572.                 //FIN: Se agrupan por expediente (fileId)
  573.                 if (!empty($budToPro)){
  574.                     foreach ($proformas as $key => $elemento){
  575.                         //INICIO: Creamos las proformas
  576.                         foreach ($elemento as $item) {
  577.                             //$key es el id del expediente
  578.                             if (!empty($item->getProformaId())) {
  579.                                 $arrayIdPro[$item->getProformaId()] = $item->getUserConfirmedId();             // $arrayIdPro['X'] = 'Y'; al agente 'Y' se le informa del presupuesto 'X'
  580.                             }
  581.                             //INICIO: Confirmamos el BudToProforma
  582.                             $item->setStatus('Confirmed');              // El elemento se ha pasado a confirmado porque se enviara por correo
  583.                             $em->persist($item);
  584.                             $em->flush();
  585.                             //FIN: Confirmamos el BudToProforma
  586.                             //FIN: Creamos los elemento que iran dentro de las proformas
  587.                         }
  588.                     }
  589.                 }
  590.                 //INICIO: Notificamos de todos los presupuestos (proformas) que se han creado
  591.                 foreach ($arrayIdPro as $key => $item){
  592.                     //Buscamos la info del proposal
  593.                     $xprof $em->getRepository(AveDocProforma::class)->findOneById($key);
  594.                     if (!empty($xprof)){
  595.                         $xfile $em->getRepository(AveFiles::class)->findOneById($xprof->getFileId());
  596.                         $xprop $em->getRepository(Proposal::class)->findOneById($xfile->getIdProposal());
  597.                         $xcli $em->getRepository(Client::class)->findOneById($xprop->getClientId());
  598.                         $xbody 'Proposal #'.$xprop->getId().' - '.$xprop->getName().
  599.                             '<br><a href="http://' $request->server->get('HTTP_HOST') . '/events/proposal/edit/' $xprop->getId() . '">Ver el Proposal</a>'.
  600.                             '<br>Cliente: '.$xcli->getName().
  601.                             '<br><br>' .'Presupuesto AvExpress #' $key  ', ' '<br><a href="http://' $request->server->get('HTTP_HOST') . '/pdf/avexpressproforma/' $key '">Ver el PDF del presupuesto</a><br><br>Notificación de nuevo presupuesto: Este presupuesto ha sido creado de forma automĆ”tica.' .
  602.                             '<br>Si el enlace al presupuesto no funciona correctamente, se debe a que desde AV lo han modificado o descartado.'.
  603.                             '<br><br>';
  604.                     } else {
  605.                         $xbody 'Presupuesto AvExpress #' $key  ', ' '<br><a href="http://' $request->server->get('HTTP_HOST') . '/pdf/avexpressproforma/' $key '">Ver el PDF del presupuesto</a><br><br>Notificación de nuevo presupuesto: Este presupuesto ha sido creado de forma automĆ”tica.' '<br><br>';
  606.                     }
  607.                     //Buscamos los agentes a notificar
  608.                     // $arrayIdPro['X'] = 'Y'; al agente 'Y' se le informa del presupuesto 'X'
  609.                     $agent $em->getRepository(User::class)->findOneById($item);
  610.                     $agentMail $agent->getEmail();
  611.                     $mailAgent $agentMail;
  612.                     //Se prepara el correo con los agentes a notificar
  613.                     $firmGmail $agent->getFirmGmail();
  614.                     $data = array(
  615.                         'body' => $xbody,
  616.                         'firm' => $firmGmail,
  617.                     );
  618.                     // EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
  619.                     $transporter = new Swift_SmtpTransport();
  620.                         $transporter->setHost('smtp.gmail.com')
  621.                         ->setEncryption('ssl')//ssl / tls
  622.                         ->setPort(465)// 465 / 587
  623.                         ->setUsername('desarrollo@develup.solutions')
  624.                         ->setPassword('utvh hzoi wfdo ztjs');
  625.                     $mailer = new Swift_Mailer($transporter);
  626.                     $message = new Swift_Message();
  627.                         $message->setSubject('Presupuesto #' $key ', Notificación de nuevo presupuesto')
  628.                         ->setSender($agentMail)
  629.                         ->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
  630.                         ->setReplyTo($agentMail)
  631.                         ->setTo($mailAgent)
  632.                         ->setBody(
  633.                             $this->renderView(
  634.                                 'mail/structure-mail.html.twig',
  635.                                 array('data' => $data)
  636.                             ),
  637.                             'text/html'
  638.                         );
  639.                     $mailer->send($message);
  640.                 }
  641.                 //FIN: Notificamos de todos los presupuestos (proformas) que se han creado
  642.                 // FIN: Se envia al agente el presupuesto
  643.             }
  644.         }
  645.         if(!empty($msjErrorClt)){
  646.             $errorMessage $this->translator->trans('Error, el cliente no puede ser modificado, ya existe una factura previa');
  647.             $this->addFlash('mensajeaverror'$errorMessage);
  648.             return $this->redirectToRoute('ave_edit_file', array('id' => $newFile->getId()));
  649.         }
  650.         return $this->redirectToRoute('ave_edit_file', array('id' => $newFile->getId()));
  651.     }
  652.     /**
  653.      * @Route("/fileedit/{id}",  name="ave_edit_file")
  654.      * Editar un expediente
  655.      */
  656.     public function editFileAction$idRequest $request)
  657.     {
  658.         $em $this->getDoctrine()->getManager();
  659.         $editFile $em->getRepository(AveFiles::class)->findOneById($id);
  660.         $clients $em->getRepository(Client::class)->findAll();
  661.         $clientSelected $em->getRepository(Client::class)->findOneById($editFile->getClient());
  662.         $products $em->getRepository(AveProduct::class)->findAll();
  663.         $destinations $em->getRepository(Destination::class)->findAll();
  664.         /* Obtengo usuario logueado */
  665.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  666.         $data $this->calculosFile($idnull0'File');
  667.         $sumatoriaTotalNet 0;
  668.         $sumatoriaTotalVat 0;
  669.         $sumatoriaTotal 0;
  670.         $resultados = array(
  671.             'totalNeto' => $sumatoriaTotalNet,
  672.             'vat' => $sumatoriaTotalVat,
  673.             'total' => $sumatoriaTotal,
  674.         );
  675.         $productInFile $em->getRepository(AveProductFile::class)->findByFileId($id);
  676.         $numeroItems sizeof($productInFile);
  677.         $facturas $em->getRepository(AveDocInvoice::class)->findByFileId($id);
  678.         $facturasRec $em->getRepository(AveDocInvoiceRec::class)->findByFileId($id);
  679.         foreach ($facturasRec as $item){ array_push($facturas,$item); }
  680.         $proformas = array();
  681.         $allProformas $em->getRepository(AveDocProforma::class)->findByFileId($id);
  682.         foreach ($allProformas as $item) {
  683.             $dataTwo $this->baseInvoiceDoneFileTwo($id$item->getId(), 'P');
  684.             $bases 0;
  685.             if (is_numeric($dataTwo['totales']) and is_numeric($dataTwo['totales_neto'])) {
  686.                 $bases $dataTwo['totales'] - $dataTwo['totales_neto'];
  687.             }
  688.             $itemsInProforma = array();
  689.             if (array_key_exists('product'$dataTwo['datasupplier'])) {
  690.                 foreach ($dataTwo['datasupplier']['product'] as $elem) {
  691.                     $itemsInProforma[] = $em->getRepository(AveProductFile::class)->findOneById($elem['id']);
  692.                 }
  693.                 $proformas[] = array(
  694.                     'id' => $dataTwo['number'],
  695.                     'itemsInProforma' => $itemsInProforma,
  696.                     'date' => $dataTwo['date'],
  697.                     'neto' => $dataTwo['totales_neto'],
  698.                     'bases_imponibles' => $bases,
  699.                     'total' => $dataTwo['totales'],
  700.                 );
  701.             }
  702.         }
  703.         // Calculamos el beneficio
  704.         $dataThree $this->baseBenefits($id);
  705.         // Buscamos los serviicos pendientes
  706.         $pendingBuds $em->getRepository(AveBudgetPending::class)->findByProposalId($editFile->getIdProposal());
  707.         $pBuds = array();
  708.         // Creamos la agrupacion por proposal
  709.         foreach ($pendingBuds as $item){
  710.             if (!(array_key_exists($item->getProposalId(),$pBuds))){
  711.                 if (!empty($item->getOriginId())){    // Los vacios solo contienen briefings
  712.                     $pBuds[$item->getProposalId()] = null;
  713.                 }
  714.             }
  715.         }
  716.         // Metemos los items en el arreglo clasificado por proposal
  717.         foreach ($pendingBuds as $item){
  718.             if (!empty($item->getOriginId())) {    // Los vacios solo contienen briefings
  719.                 $pBuds[$item->getProposalId()][] = $item;
  720.             }
  721.         }
  722.         ksort($pBuds);
  723.         $keysPbuds array_keys($pBuds);
  724.         $gpFile $em->getRepository(Reservation::class)->findOneById($editFile->getReservation());
  725.         $htFile = !(empty($gpFile)) ? (in_array($user_logueado->getUserrol(),[9,23,24,37,47,53]) ? $em->getRepository(HtFile::class)->findOneByReservation($gpFile) : null ) : null;
  726.         $gpFile in_array($user_logueado->getUserrol(),[9,23,24,37,47,53]) ? $gpFile null ;
  727.         return $this->render('MDS/AvexpressBundle/Avexpress/edit-files.html.twig',
  728.             array(
  729.                 'id' => $id,
  730.                 'clients' => $clients,
  731.                 'clientId' => $editFile->getClient(),
  732.                 'clientSelected' => $clientSelected,
  733.                 'file' => $editFile,
  734.                 'numeroItems' => $numeroItems,
  735.                 'arrayProductFile' => $data['datasupplier']['product'],
  736.                 'products' => $products,
  737.                 'services' => null,
  738.                 'facturas' => $facturas,
  739.                 'proformas' => $proformas,
  740.                 'paymentNotIvoiced' => null,
  741.                 'paymentsAll' => null,
  742.                 'resultados' => $resultados,
  743.                 'totales_global_con_iva' => $data['totales'], //$data['totales_global_con_iva'],
  744.                 'totales_global_iva' => $data['bases_imponibles']['ivaMontoVeintiUno'], //$data['totales_global_iva'],
  745.                 'totales_global_neto' => $data['totales_neto'], //$data['totales_global_neto'],
  746.                 'totales_global_servicios_con_iva' => 0//$data['totales_global_servicios_con_iva'],
  747.                 'totales_global_servicios_neto' => 0//$data['totales_global_servicios_neto'],
  748.                 'totales_global_servicios_iva' => 0//$data['totales_global_servicios_iva'],
  749.                 'sumatoria_totales_global_con_iva' => 0//$data['sumatoria_totales_global_con_iva'],
  750.                 'sumatoria_totales_global_neto' => 0//$data['sumatoria_totales_global_neto'],
  751.                 'sumatoria_totales_global_iva' => 0//$data['sumatoria_totales_global_iva'],
  752.                 'benefitEuro' => $dataThree['benefitEuro'],
  753.                 'benefitPerc' => $dataThree['benefitPerc'],
  754.                 'pendingBudgets' => $pBuds,
  755.                 'keysPendingBudgets' => $keysPbuds,
  756.                 'destinations' => $destinations,
  757.                 'htFile' => $htFile,
  758.                 'gpFile' => $gpFile,
  759.             ));
  760.     }
  761.     /**
  762.      * @Route("/filedelete/{id}",  name="ave_delete_file")
  763.      * Actualizar un expediente
  764.      */
  765.     public function deleteFileAction($idRequest $request)
  766.     {
  767.         $em $this->getDoctrine()->getManager();
  768.         $newFile $em->getRepository(AveFiles::class)->findOneById($id);
  769.         /* Obtengo usuario logueado */
  770.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  771.         $user_id $user_logueado->getId();
  772.         $newFile->setStatus('Deleted');
  773.         $newFile->setUpdatedId($user_id);
  774.         $newFile->setUpdatedAt(new \DateTime("now"));
  775.         $em->persist($newFile);
  776.         $em->flush();
  777.         return $this->redirectToRoute('ave_edit_file', array( 'id' => $id ));
  778.     }
  779.     /**
  780.      * @Route("/filefrombudget/{id}",  name="ave_add_file_from_budget")
  781.      * Agregar un expediente desde un presupuesto
  782.      */
  783.     public function addFileFromBudgetAction$idRequest $request)
  784.     {
  785.         $em $this->getDoctrine()->getManager();
  786.         $budget $em->getRepository(AveBudgetPending::class)->findOneById($id);
  787.         $proposal $em->getRepository(Proposal::class)->findOneById($budget->getProposalId());
  788.         $newFile $em->getRepository(AveFiles::class)->findOneByIdProposal($proposal->getId());
  789.         /* Obtengo usuario logueado */
  790.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  791.         $user_id $user_logueado->getId();
  792.         if (empty($newFile)){
  793.             // No hay un File asociado a ese proposal, se debe crear uno nuevo
  794.             $newFile = new AveFiles();
  795.             $newFile->setTitle($proposal->getId().' - ' .$budget->getProposalTitle());
  796.             $newFile->setClient(262);                           // In Out es el cliente
  797.             $newFile->setIdProposal($proposal->getId());
  798.             $newFile->setStatus('Pending');
  799.             $newFile->setAdvancePayment(null);
  800.             if (!empty($budget->getBriefing())){
  801.                 $newFile->setDescription('<p> *********  MENSAJE DEL AGENTE  ********* </p>' $budget->getBriefing());
  802.             }
  803.             $newFile->setDateStart(new \DateTime("now"));
  804.             $newFile->setDateEnd(new \DateTime("now"));
  805.             $newFile->setCreatedId($user_id);
  806.             $newFile->setUpdatedId($user_id);
  807.             $newFile->setCreatedAt(new \DateTime("now"));
  808.             $newFile->setUpdatedAt(new \DateTime("now"));
  809.         } else {
  810.             // Ya existe un File asociado a ese proposal
  811.             $newFile->setClient(262);                           // In Out es el cliente
  812.             $newFile->setStatus('Pending');
  813.             if (!empty($budget->getBriefing())) {
  814.                 $newFile->setDescription($newFile->getDescription() . '<p> *********  MENSAJE DEL AGENTE  ********* </p>' $budget->getBriefing());
  815.             }
  816.             $newFile->setUpdatedId($user_id);
  817.             $newFile->setUpdatedAt(new \DateTime("now"));
  818.         }
  819.         $em->persist($newFile);
  820.         $em->flush();
  821.         $em->remove($budget);
  822.         $em->flush();
  823.         //Actualizamos los Briefings que esten en FileId null con el recien generado fileId en base al proposalId
  824.         $allBriefings $em->getRepository(AveBriefings::class)->findByProposalId($proposal->getId());
  825.         foreach ($allBriefings as $item){
  826.             if (empty($item->getFileId())) {
  827.                 $item->setFileId($newFile->getId());
  828.                 $em->persist($item);
  829.                 $em->flush();
  830.             }
  831.         }
  832.         return $this->redirectToRoute('ave_edit_file', array( 'id' => $newFile->getId() ));
  833.     }
  834.     /**
  835.      * @Route("/filelistbriefings/{id}",  name="ave_list_file_briefings")
  836.      * Listar briefings del expediente
  837.      */
  838.     public function listFileBriefingsAction($idRequest $request){
  839.         $em $this->getDoctrine()->getManager();
  840.         $briefings $em->getRepository(AveBriefings::class)->findByFileId($id);
  841.         return $this->render('MDS/AvexpressBundle/Avexpress/list-briefings.html.twig',
  842.             array(
  843.                 'id' => $id,
  844.                 'briefings' => $briefings,
  845.             )
  846.         );
  847.     }
  848.     /**
  849.      * @Route("/briefingadd/{id}",  name="ave_add_file_briefings")
  850.      * Agregar briefing al expediente
  851.      */
  852.     public function addFileBriefingsAction($idRequest $request){
  853.         $brif $request->request->get('newbriefing');
  854.         $em $this->getDoctrine()->getManager();
  855.         $file $em->getRepository(AveFiles::class)->findOneById($id);
  856.         $proposalId $file->getIdProposal();
  857.         /* Obtengo usuario logueado */
  858.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  859.         $user_id $user_logueado->getId();
  860.         $userConfirmedFullName $user_logueado->getName().' '.$user_logueado->getLastName();
  861.         $briefing = new AveBriefings();
  862.         $briefing->setProposalId($proposalId);
  863.         $briefing->setBriefing($brif);
  864.         $briefing->setBudgetPendingId(null);
  865.         $briefing->setFileId($id);
  866.         $briefing->setUserConfirmedFullName($userConfirmedFullName);
  867.         $briefing->setUserConfirmedId($user_id);
  868.         $briefing->setCreatedAt(new \DateTime("now"));
  869.         $em->persist($briefing);
  870.         $em->flush();
  871.         $briefings $em->getRepository(AveBriefings::class)->findByFileId($id);
  872.         return $this->render('MDS/AvexpressBundle/Avexpress/list-briefings.html.twig',
  873.             array(
  874.                 'id' => $id,
  875.                 'briefings' => $briefings,
  876.             )
  877.         );
  878.     }
  879.     /**
  880.      * @Route("/filedeletedlist/",  name="ave_list_file_deleted")
  881.      * Listar expedientes cancelados
  882.      */
  883.     public function listFileDeletedActionRequest $request)
  884.     {
  885.         $em $this->getDoctrine()->getManager();
  886.         $idgroup null$ref = array();
  887.         $reservas $em->getRepository(AveFiles::class)->findByStatus('Deleted');
  888.         foreach ($reservas as $res) {
  889.             $client $em->getRepository(Client::class)->findOneById($res->getClient());
  890.             if (!empty($client)) { $res->setClient($client->getName()); } else { $res->setClient(null); }
  891.             if (!empty($res->getDateStart()) and !empty($res->getDateEnd())) {
  892.                 $ref[$res->getId()] = '#' . ($res->getDateStart())->format('ymd') . ($res->getDateEnd())->format('ymd');
  893.             } else {
  894.                 $ref[$res->getId()] = '#' '000000' '000000';
  895.             }
  896.         }
  897.         $reservasZero = array();
  898.         foreach ($reservas as $res) {
  899.             $reservasZero[] = array(
  900.                 'dateStart' => $res->getDateStart(),
  901.                 'dateEnd' => $res->getDateEnd(),
  902.                 'id' => $res->getId(),
  903.                 'title' => $res->getTitle(),
  904.                 'client' => $res->getClient(),
  905.                 'createdId' => $res->getCreatedId(),
  906.                 'ref' => $ref[$res->getId()],
  907.                 'reservation' => $res->getReservation(),
  908.             );
  909.         }
  910.         $reservas $reservasZero;
  911.         return $this->render('MDS/AvexpressBundle/Avexpress/list-files.html.twig',
  912.             array(
  913.                 'groups' => null,
  914.                 'listofdeletedfiles' => true,
  915.                 'reservations' => $reservas
  916.             )
  917.         );
  918.     }
  919.     /**
  920.      * @Route("/updatefilecomments/{id}",  name="ave_update_file_comments")
  921.      * Actualizar Comentarios y booleanos del expediente
  922.      */
  923.     public function updateFileCommentsAction($idRequest $request){
  924.         $em $this->getDoctrine()->getManager();
  925.         $file $em->getRepository(AveFiles::class)->findOneById($id);
  926.         $newComments $request->request->get('comments');
  927.         $chkCommentsToPro $request->request->get('chkCommentsToPro');
  928.         $chkCommentsToInv $request->request->get('chkCommentsToInv');
  929.         if ($chkCommentsToInv == 'on'){ $chkCommentsToInv true; } else { $chkCommentsToInv false; }
  930.         if ($chkCommentsToPro == 'on'){ $chkCommentsToPro true; } else { $chkCommentsToPro false; }
  931.         $file->setComments($newComments);
  932.         $file->setCommentsInInv($chkCommentsToInv);
  933.         $file->setCommentsInPro($chkCommentsToPro);
  934.         $em->persist($file);
  935.         $em->flush();
  936.         return $this->redirectToRoute('ave_edit_file', array( 'id' => $id ));
  937.     }
  938.     private function baseInvoiceDoneFileTwo($fileId$invoiceId$typeBase)
  939.     {
  940.         $em $this->getDoctrine()->getManager();
  941.         $file $em->getRepository(AveFiles::class)->findOneById($fileId);
  942.         $dateDocument null;                                                                           //Fecha final del documento
  943.         $subneto 0;
  944.         if (($typeBase == 'I') or ($typeBase == 'P')) {
  945.             if ($typeBase == 'I') {
  946.                 $items $em->getRepository(AveDocInvoiceItems::class)->findBy(array('fileId' => $fileId'invoiceId' => $invoiceId));
  947.             } else {
  948.                 // Es proforma
  949. //                $items = $em->getRepository(AveDocProformaItems::class)->findBy(array('fileId' => $fileId, 'proformaId' => $invoiceId));
  950. //                $items = $em->getRepository(AveDocProformaItems::class)->findBy(array('fileId' => $fileId, 'proformaId' => $invoiceId));
  951.                 $parameters = array(
  952.                     'fileId' => $fileId,
  953.                     'proformaId' => $invoiceId,
  954.                 );
  955.                 $dql 'SELECT i
  956.                         FROM AvexpressBundle:AveProductFile i
  957.                         INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  958.                         WHERE i.fileId = :fileId AND c.proformaId =:proformaId
  959.                         ORDER BY i.rankAv ASC';
  960.                 $query $em->createQuery($dql)->setParameters($parameters);
  961.                 $items $query->getResult();
  962.                 $arrayLocation = array();
  963.                 $arrayLocationWithNull false;
  964.                 foreach ($items as $item){
  965.                     if (!empty($item->getLocation())){
  966.                         $arrayLocation[$item->getLocation()] = $item->getLocation();
  967.                     } else {
  968.                         $arrayLocationWithNull true;
  969.                     }
  970.                 }
  971.                 if ($arrayLocationWithNull){ $arrayLocation['null'] = 'null'; }
  972.                 $productsInFile = array();
  973.                 foreach ($arrayLocation as $item){
  974.                     // VIDEO
  975.                     $parameters = array(
  976.                         'fileId' => $fileId,
  977.                         'type' => 'VĆ­deo',
  978.                         'location' => $item,
  979.                         'proformaId' => $invoiceId,
  980.                     );
  981.                     $dql 'SELECT i                            
  982.                             FROM AvexpressBundle:AveProductFile i
  983.                             INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  984.                             WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location AND c.proformaId =:proformaId
  985.                             ORDER BY i.rankAv ASC';
  986.                     $query $em->createQuery($dql)->setParameters($parameters);
  987.                     $productsInFileVid $query->getResult();
  988.                     // SONIDO
  989.                     $parameters = array(
  990.                         'fileId' => $fileId,
  991.                         'type' => 'Sonido',
  992.                         'location' => $item,
  993.                         'proformaId' => $invoiceId,
  994.                     );
  995.                     $dql 'SELECT i
  996.                             FROM AvexpressBundle:AveProductFile i
  997.                             INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  998.                             WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location AND c.proformaId =:proformaId
  999.                             ORDER BY i.rankAv ASC';
  1000.                     $query $em->createQuery($dql)->setParameters($parameters);
  1001.                     $productsInFileSound $query->getResult();
  1002.                     // ILUMINACION
  1003.                     $parameters = array(
  1004.                         'fileId' => $fileId,
  1005.                         'type' => 'Iluminación',
  1006.                         'location' => $item,
  1007.                         'proformaId' => $invoiceId,
  1008.                     );
  1009.                     $dql 'SELECT i
  1010.                             FROM AvexpressBundle:AveProductFile i
  1011.                             INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1012.                             WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location AND c.proformaId =:proformaId
  1013.                             ORDER BY i.rankAv ASC';
  1014.                     $query $em->createQuery($dql)->setParameters($parameters);
  1015.                     $productsInFileLights $query->getResult();
  1016.                     // OTROS
  1017.                     $parameters = array(
  1018.                         'fileId' => $fileId,
  1019.                         'typeV' => 'VĆ­deo',
  1020.                         'typeS' => 'Sonido',
  1021.                         'typeI' => 'Iluminación',
  1022.                         'location' => $item,
  1023.                         'proformaId' => $invoiceId,
  1024.                     );
  1025.                     $dql 'SELECT i
  1026.                             FROM AvexpressBundle:AveProductFile i
  1027.                             INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1028.                             WHERE (i.fileId = :fileId AND i.type != :typeV AND i.type != :typeS AND i.type != :typeI AND i.location = :location AND c.proformaId =:proformaId)
  1029.                             ORDER BY i.rankAv ASC';
  1030.                     $query $em->createQuery($dql)->setParameters($parameters);
  1031.                     $productsInFileOther $query->getResult();
  1032.                     // CASO NULL (Los casos EMPTY estan considerados en las consultas previas)
  1033.                     $parameters = array(
  1034.                         'fileId' => $fileId,
  1035.                         'location' => $item,
  1036.                         'proformaId' => $invoiceId,
  1037.                     );
  1038.                     $dql 'SELECT i
  1039.                             FROM AvexpressBundle:AveProductFile i
  1040.                             INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1041.                             WHERE (i.fileId = :fileId AND i.type IS NULL AND i.location = :location AND c.proformaId =:proformaId)
  1042.                             ORDER BY i.rankAv ASC';
  1043.                     $query $em->createQuery($dql)->setParameters($parameters);
  1044.                     $productsInFileNull $query->getResult();
  1045.                     // Para el location en NULL el SQL tiene que ser diferente por eso el siguiente condicional
  1046.                     if ($item == 'null'){
  1047.                         // VIDEO
  1048.                         $parameters = array(
  1049.                             'fileId' => $fileId,
  1050.                             'type' => 'VĆ­deo',
  1051.                             'proformaId' => $invoiceId,
  1052. //                    'location' => $item,
  1053.                         );
  1054.                         $dql 'SELECT i
  1055.                                 FROM AvexpressBundle:AveProductFile i
  1056.                                 INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1057.                                 WHERE i.fileId = :fileId AND i.type = :type AND i.location IS NULL AND c.proformaId =:proformaId
  1058.                                 ORDER BY i.rankAv ASC';
  1059.                         $query $em->createQuery($dql)->setParameters($parameters);
  1060.                         $productsInFileVid $query->getResult();
  1061.                         // SONIDO
  1062.                         $parameters = array(
  1063.                             'fileId' => $fileId,
  1064.                             'type' => 'Sonido',
  1065.                             'proformaId' => $invoiceId,
  1066. //                    'location' => $item,
  1067.                         );
  1068.                         $dql 'SELECT i
  1069.                                 FROM AvexpressBundle:AveProductFile i
  1070.                                 INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1071.                                 WHERE i.fileId = :fileId AND i.type = :type AND i.location IS NULL AND c.proformaId =:proformaId
  1072.                                 ORDER BY i.rankAv ASC';
  1073.                         $query $em->createQuery($dql)->setParameters($parameters);
  1074.                         $productsInFileSound $query->getResult();
  1075.                         // ILUMINACION
  1076.                         $parameters = array(
  1077.                             'fileId' => $fileId,
  1078.                             'type' => 'Iluminación',
  1079.                             'proformaId' => $invoiceId,
  1080. //                    'location' => $item,
  1081.                         );
  1082.                         $dql 'SELECT i
  1083.                                 FROM AvexpressBundle:AveProductFile i
  1084.                                 INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1085.                                 WHERE i.fileId = :fileId AND i.type = :type AND i.location IS NULL AND c.proformaId =:proformaId
  1086.                                 ORDER BY i.rankAv ASC';
  1087.                         $query $em->createQuery($dql)->setParameters($parameters);
  1088.                         $productsInFileLights $query->getResult();
  1089.                         // OTROS
  1090.                         $parameters = array(
  1091.                             'fileId' => $fileId,
  1092.                             'typeV' => 'VĆ­deo',
  1093.                             'typeS' => 'Sonido',
  1094.                             'typeI' => 'Iluminación',
  1095.                             'proformaId' => $invoiceId,
  1096. //                    'location' => $item,
  1097.                         );
  1098.                         $dql 'SELECT i
  1099.                                 FROM AvexpressBundle:AveProductFile i
  1100.                                 INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1101.                                 WHERE (i.fileId = :fileId AND i.type != :typeV AND i.type != :typeS AND i.type != :typeI AND i.location IS NULL AND c.proformaId =:proformaId)
  1102.                                 ORDER BY i.rankAv ASC';
  1103.                         $query $em->createQuery($dql)->setParameters($parameters);
  1104.                         $productsInFileOther $query->getResult();
  1105.                         // CASO NULL (Los casos EMPTY estan considerados en las consultas previas)
  1106.                         $parameters = array(
  1107.                             'fileId' => $fileId,
  1108.                             'proformaId' => $invoiceId,
  1109. //                    'location' => $item,
  1110.                         );
  1111.                         $dql 'SELECT i
  1112.                                 FROM AvexpressBundle:AveProductFile i
  1113.                                 INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1114.                                 WHERE (i.fileId = :fileId AND i.type IS NULL AND i.location IS NULL AND c.proformaId =:proformaId)
  1115.                                 ORDER BY i.rankAv ASC';
  1116.                         $query $em->createQuery($dql)->setParameters($parameters);
  1117.                         $productsInFileNull $query->getResult();
  1118.                     }
  1119.                     $productsInFile array_merge($productsInFile$productsInFileVid$productsInFileSound$productsInFileLights$productsInFileOther$productsInFileNull);
  1120.                 }
  1121.                 $items $productsInFile;       // En Items estaban todos pero sin ordenamiento, ahora estan organizados por location y tipo
  1122.             }
  1123.         } else {
  1124.             // No es factura ni proforma, es una rectificativa
  1125.             $items $em->getRepository(AveDocInvoiceRecItems::class)->findBy(array('fileId' => $fileId'invoiceRecId' => $invoiceId));
  1126.         }
  1127.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('4');
  1128.         $client $em->getRepository(Client::class)->findById($file->getClient());
  1129.         if (empty($client)){
  1130.             $client[0] = new Client();
  1131.             $client[0]->setName('');
  1132.             $client[0]->setTitle('');
  1133.             $client[0]->setIdDocument('');
  1134.             $client[0]->setPopulation('');
  1135.             $client[0]->setRegion('');
  1136.             $client[0]->setCountry('');
  1137.         } else {
  1138.             if (is_numeric($client[0]->getPopulation())){
  1139.                 $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  1140.                 $client[0]->setPopulation($city->getCity());
  1141.             }
  1142.             if (is_numeric($client[0]->getRegion())){
  1143.                 $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  1144.                 $client[0]->setRegion($region->getRegion());
  1145.             }
  1146.             if (is_numeric($client[0]->getCountry())){
  1147.                 $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  1148.                 $client[0]->setCountry($country->getCountry());
  1149.             }
  1150.         }
  1151.         // Acumuladores de los calculos
  1152.         $totales_neto_all 0;
  1153.         $data_iva = array(
  1154.             'iva' => 21,
  1155.             'ivaMontoVeintiUno' => 0,
  1156.             'ivaMontoDiez' => 0,
  1157.             'ivaMontoCero' => 0,
  1158.         );
  1159.         //INICIO: Determinamos el numero de factura o proforma
  1160.         if ($typeBase == 'I'){
  1161.             // Es una Factura
  1162.             $number $em->getRepository(AveDocInvoice::class)->findOneById($invoiceId);
  1163.             $dateDocument $number->getDateAt();
  1164.             $number $number->getNumber();
  1165.             $type 'Invoice';
  1166.         } else {
  1167.             if ($typeBase == 'R'){
  1168.                 // Es una factura rectificativa
  1169.                 $number $em->getRepository(AveDocInvoiceRec::class)->findOneById($invoiceId);
  1170.                 $dateDocument $number->getDateAt();
  1171.                 $type 'Invoice Rec';
  1172.             } else {
  1173.                 // Es una Proforma
  1174.                 $number $invoiceId;
  1175.                 $type 'Proforma';
  1176.             }
  1177.         }
  1178.         //FIN: Determinamos el numero de factura o proforma
  1179.         // Buscamos los productos, pagos y servicios
  1180.         $arrayItems = array();
  1181.         $fileProducts = array();
  1182.         $payments = array();
  1183.         $services = array();
  1184.         if (!empty($items)) {
  1185.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  1186.                 foreach ($items as $item) {
  1187.                     switch ($item->getItemType()) {
  1188.                         case 'PRODUCT'// Producto
  1189.                             $fileProducts[] = $item;
  1190.                             break;
  1191.                         case 'PAYMENT'// Pago
  1192.                             $payments[] = $item;
  1193.                             break;
  1194.                         case 'SERVICE'// Servicio
  1195.                             $services[] = $item;
  1196.                             break;
  1197.                         default:
  1198.                             break;
  1199.                     }
  1200.                 }
  1201.             } else {
  1202.                 // Es una proforma
  1203.                 foreach ($items as $item) {
  1204.                     switch ($item->getType()) {
  1205.                         case 'PRODUCT'// Producto
  1206.                             $productPro $em->getRepository(AveProductFile::class)->findOneById($item->getControlId());
  1207.                             if (!empty($productPro)) {
  1208.                                 $fileProducts[] = $productPro;
  1209.                             }
  1210.                             break;
  1211.                         case 'PAYMENT'// Pago
  1212.                             $paymentPro $em->getRepository(AvePaymentsClient::class)->findOneById($item->getControlId());
  1213.                             if (!empty($paymentPro)) {
  1214.                                 $payments[] = $paymentPro;
  1215.                             }
  1216.                             break;
  1217.                         case 'SERVICE'// Servicio
  1218.                             $servicePro $em->getRepository(AveServices::class)->findOneById($item->getControlId());
  1219.                             if (!empty($servicePro)) {
  1220.                                 $services[] = $servicePro;
  1221.                             }
  1222.                             break;
  1223.                         default:
  1224.                             // Producto  (Video, Iluminacion, Sonido, Otros)
  1225.                             if (!empty($item)) {
  1226.                                 $fileProducts[] = $item;
  1227.                             }
  1228.                         break;
  1229.                     }
  1230.                 }
  1231.             }
  1232.         }
  1233.         $data_supplier = array();
  1234.         $i 0;
  1235.         $iva '21';            // Esteban Rincon: "Por Ley de localización del impuesto, siempre serĆ” un 21%"
  1236.         $pax '1';
  1237.         $qty '1';
  1238.         $product = array(
  1239.             'neto' => 0,
  1240.             'sumSubT' => 0,
  1241.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  1242.         $service = array(
  1243.             'neto' => 0,
  1244.             'sumSubT' => 0,
  1245.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  1246.         foreach ($fileProducts as $item){
  1247.             if (!is_null($item->getUnits()) or !empty($item->getUnits())){
  1248.                 $qty $item->getUnits();
  1249.             }
  1250.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  1251.                 if (is_null($item->getPrdServicePrice()) or empty($item->getPrdServicePrice())){
  1252.                     $subtotal 0;
  1253.                     $neto 0;
  1254.                     $subtotalProduct 0;
  1255.                 } else {
  1256. //                    $subtotalProduct = $item->getPrdServicePrice() * 1.21;
  1257.                     $subtotalProduct $item->getPrdSubTotalPrice() * 1.21;
  1258. //                    $subneto = $item->getPrdServicePrice();
  1259.                     $subneto $item->getPrdSubTotalPrice();
  1260.                     $subtotal =  $subtotalProduct;
  1261.                     $neto =  $subneto;
  1262.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  1263.                     $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  1264.                     $neto round($neto,2,PHP_ROUND_HALF_UP);
  1265.                     $arrayItems[] = array(
  1266.                         'type' => 'Product',
  1267.                         'name' => $item->getPrdName(),
  1268.                         'amount' => $neto,
  1269.                         'iva' => '21',
  1270.                         'total' => $subtotal,
  1271.                     );
  1272.                 }
  1273.             } else {
  1274.                 // Es proforma
  1275.                 if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
  1276.                     $subtotal 0;
  1277.                     $neto 0;
  1278.                     $subtotalProduct 0;
  1279.                 } else {
  1280. //                    $subtotalProduct = $item->getServicePrice() * 1.21;
  1281.                     $subtotalProduct $item->getSubTotalPrice() * 1.21;
  1282. //                    $subneto = $item->getServicePrice();
  1283.                     $subneto $item->getSubTotalPrice();
  1284.                     $subtotal =  $subtotalProduct;
  1285.                     $neto =  $subneto;
  1286.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  1287.                     $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  1288.                     $neto round($neto,2,PHP_ROUND_HALF_UP);
  1289.                     $arrayItems[] = array(
  1290.                         'type' => 'Product',
  1291.                         'name' => $item->getProductName(),
  1292.                         'amount' => $neto,
  1293.                         'iva' => '21',
  1294.                         'total' => $subtotal,
  1295.                     );
  1296.                 }
  1297.             }
  1298.             // Acumula netos totales e IVA
  1299.             $totales_neto_all $totales_neto_all $neto;
  1300.             $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto 0.21);
  1301.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  1302.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  1303.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  1304.             // Acumula netos totales e IVA
  1305.             $product['neto'] = $product['neto'] + $neto;
  1306.             $product['sumSubT'] = $product['sumSubT'] + $subtotal;
  1307.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  1308.             $product['neto'] = round($product['neto'],2,PHP_ROUND_HALF_UP);
  1309.             $product['sumSubT'] = round($product['sumSubT'],2,PHP_ROUND_HALF_UP);
  1310.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  1311.                 $data_supplier['product'][$i] = array(
  1312.                     'id' => $item->getId(),
  1313.                     'productName' => $item->getPrdName(),
  1314.                     'productId' => $item->getPrdProductId(),
  1315.                     'dateStart' => $item->getPrdDateStart(),
  1316.                     'dateEnd' => $item->getPrdDateEnd(),
  1317.                     'servicePrice' => $item->getPrdServicePrice(),
  1318.                     'serviceSubTotalPrice' => $subneto,     //antes de IVA
  1319.                     'subtotalProduct' => $subtotalProduct,
  1320.                     'iva' => $iva,
  1321.                     'pax' => $pax,
  1322.                     'qty' => $qty,
  1323.                     'type' => $item->getPrdType(),
  1324.                     'subtotal' => $subtotal,
  1325.                 );
  1326.             } else {
  1327.                 // Es proforma
  1328.                 $data_supplier['product'][$i] = array(
  1329.                     'id' => $item->getId(),
  1330.                     'productName' => $item->getProductName(),
  1331.                     'productId' => $item->getProductId(),
  1332.                     'dateStart' => $item->getDateStart(),
  1333.                     'dateEnd' => $item->getDateEnd(),
  1334.                     'servicePrice' => $item->getServicePrice(),
  1335.                     'subtotalProduct' => $subtotalProduct,
  1336.                     'iva' => $iva,
  1337.                     'pax' => $pax,
  1338.                     'qty' => $qty,
  1339.                     'type' => $item->getType(),
  1340.                     'subtotal' => $subtotal,
  1341.                 );
  1342.             }
  1343.             $i++;
  1344.         }
  1345.         $data_supplier['productSubTotal'] = array(
  1346.             'neto' => $product['neto'],
  1347.             'sumSubT' => $product['sumSubT'],
  1348.         );
  1349.         $payment = array(
  1350.             'sumSubT' => 0,
  1351.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  1352.         $i 0;
  1353.         foreach ($payments as $item){
  1354.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  1355.                 $payment['sumSubT'] = $payment['sumSubT'] + $item->getPayAmountTotal();
  1356.                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  1357.                 $payment['sumSubT'] = round($payment['sumSubT'], 2PHP_ROUND_HALF_UP);
  1358.                 $data_supplier['payment'][$i] = array(
  1359.                     'id' => $item->getId(),
  1360.                     'amount' => $item->getPayAmount(),
  1361.                     'amountTotal' => $item->getPayAmountTotal(),
  1362.                     'vat' => $item->getPayVat(),
  1363.                     'datePayAt' => $item->getPayDatePayAt(),
  1364.                     'wayToPay' => $item->getPayWayToPay(),
  1365.                 );
  1366.                 $arrayItems[] = array(
  1367.                     'type' => 'Payment',
  1368.                     'name' => $item->getPayWayToPay(),
  1369.                     'amount' => $item->getPayAmount(),
  1370.                     'total' => $item->getPayAmountTotal(),
  1371.                     'iva' => $item->getPayVat(),
  1372.                 );
  1373.             } else {
  1374.                 // Es una proforma
  1375.                 $payment['sumSubT'] = $payment['sumSubT'] + $item->getAmountTotal();
  1376.                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  1377.                 $payment['sumSubT'] = round($payment['sumSubT'], 2PHP_ROUND_HALF_UP);
  1378.                 $data_supplier['payment'][$i] = array(
  1379.                     'id' => $item->getId(),
  1380.                     'amount' => $item->getAmount(),
  1381.                     'amountTotal' => $item->getAmountTotal(),
  1382.                     'vat' => $item->getVat(),
  1383.                     'datePayAt' => $item->getDatePayAt(),
  1384.                     'wayToPay' => $item->getWayToPay(),
  1385.                 );
  1386.                 $arrayItems[] = array(
  1387.                     'type' => 'Payment',
  1388.                     'name' => $item->getWayToPay(),
  1389.                     'amount' => $item->getAmount(),
  1390.                     'total' => $item->getAmountTotal(),
  1391.                     'iva' => $item->getVat(),
  1392.                 );
  1393.             }
  1394.             $i++;
  1395.         }
  1396.         if (!empty($payments)) {
  1397.             $data_supplier['paymentSubTotal'] = array(
  1398.                 'sumSubT' => $payment['sumSubT'],
  1399.             );
  1400.         }
  1401.         foreach ($services as $item){
  1402.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  1403.                 if (is_null($item->getSrvPrice()) or empty($item->getSrvPrice())) {
  1404.                     $subtotal 0;
  1405.                     $neto 0;
  1406.                     $subtotalService 0;
  1407.                 } else {
  1408.                     $subtotalService $item->getSrvPrice();
  1409.                     $subneto $item->getSrvPrice();
  1410.                     // Commission
  1411.                     if ($item->getSrvOpCommission() == '1') {
  1412.                         $subtotalService $subtotalService * (+ ($item->getSrvCommission() / 100));
  1413.                         $subneto $subneto * (+ ($item->getSrvCommission() / 100));
  1414.                     } else {
  1415.                         $subtotalService $subtotalService * (- ($item->getSrvCommission() / 100));
  1416.                         $subneto $subneto * (- ($item->getSrvCommission() / 100));
  1417.                     }
  1418.                     // Over
  1419.                     if ($item->getSrvOpOver() == '1') {
  1420.                         $subtotalService $subtotalService $item->getSrvOver();
  1421.                         $subneto $subneto $item->getSrvOver();
  1422.                     } else {
  1423.                         $subtotalService $subtotalService $item->getSrvOver();
  1424.                         $subneto $subneto $item->getSrvOver();
  1425.                     }
  1426.                     // IVA
  1427.                     if ($item->getSrvOpIva() == '1') {
  1428.                         $subtotalService $subtotalService * (+ ($item->getSrvIva() / 100));
  1429.                     } else {
  1430.                         $subtotalService $item->getSrvPrice();
  1431.                         $subneto = ($subneto 100) / (100 $item->getSrvIva());
  1432.                     }
  1433.                     switch ($item->getSrvServiceCatId()) {
  1434.                         case 1// Alojamiento
  1435.                             // el numero de noches $numNoches; precio unitario $subneto
  1436.                             $numNoches = (($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days;
  1437.                             // La personas no afectan este calculo
  1438.                             $subtotal $subtotalService $numNoches $item->getSrvUnits();
  1439.                             $subnetoUnit $subneto;
  1440.                             $subneto $subneto $numNoches $item->getSrvUnits();
  1441.                             $data_supplier['service'][$i] = array(
  1442.                                 'id' => $item->getId(),
  1443.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1444.                                 'serviceName' => $item->getSrvName(),
  1445.                                 'serviceType' => 'Hotel',
  1446.                                 'date' => ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y'),
  1447.                                 'qty' => $item->getSrvUnits(),
  1448.                                 'iva' => $item->getSrvIva(),
  1449.                                 'pax' => '-',
  1450.                                 'precioUnit' => $subnetoUnit,
  1451.                                 'subneto' => $subneto,
  1452.                                 'subtotal' => $subtotal,
  1453.                             );
  1454.                             break;
  1455.                         case 2//Actividades
  1456.                             // El nĆŗmero de personas es considerado en el calculo
  1457.                             $pax $item->getSrvPax();
  1458.                             if (empty($pax) or $pax == "0") {
  1459.                                 $pax 1;
  1460.                             }
  1461.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1462.                             if ($days 1) {
  1463.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1464.                             } else {
  1465.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1466.                             }
  1467.                             $subtotal $subtotalService $days $item->getSrvUnits();
  1468.                             $subnetoUnit $subneto;
  1469.                             $subneto $subneto $days $item->getSrvUnits();
  1470.                             $data_supplier['service'][$i] = array(
  1471.                                 'id' => $item->getId(),
  1472.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1473.                                 'serviceName' => $item->getSrvName(),
  1474.                                 'serviceType' => 'Actividad',
  1475.                                 'date' => $dateServ,
  1476.                                 'qty' => $item->getSrvUnits(),
  1477.                                 'iva' => $item->getSrvIva(),
  1478.                                 'pax' => $item->getSrvPax(),
  1479.                                 'precioUnit' => $subnetoUnit,
  1480.                                 'subneto' => $subneto,
  1481.                                 'subtotal' => $subtotal,
  1482.                             );
  1483.                             break;
  1484.                         case 3// AV
  1485.                             $pax $item->getSrvPax();
  1486.                             if (empty($pax) or $pax == "0") {
  1487.                                 $pax 1;
  1488.                             }
  1489.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1490.                             if ($days 1) {
  1491.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1492.                             } else {
  1493.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1494.                             }
  1495.                             $unitsServ $item->getSrvUnits();
  1496.                             if (empty($unitsServ) or $unitsServ == "0") {
  1497.                                 $unitsServ 1;
  1498.                             }
  1499.                             $subtotal $subtotalService $days $unitsServ $pax;
  1500.                             $subnetoUnit $subneto;
  1501.                             $subneto $subneto $days $unitsServ $pax;
  1502.                             $data_supplier['service'][$i] = array(
  1503.                                 'id' => $item->getId(),
  1504.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1505.                                 'serviceName' => $item->getSrvName(),
  1506.                                 'serviceType' => 'AV',
  1507.                                 'date' => $dateServ,
  1508.                                 'qty' => $unitsServ,
  1509.                                 'iva' => $item->getSrvIva(),
  1510.                                 'pax' => $item->getSrvPax(),
  1511.                                 'precioUnit' => $subnetoUnit,
  1512.                                 'subneto' => $subneto,
  1513.                                 'subtotal' => $subtotal,
  1514.                             );
  1515.                             break;
  1516.                         case 4//Creative
  1517.                             $pax $item->getSrvPax();
  1518.                             if (empty($pax) or $pax == "0") {
  1519.                                 $pax 1;
  1520.                             }
  1521.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1522.                             if ($days 1) {
  1523.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1524.                             } else {
  1525.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1526.                             }
  1527.                             $unitsServ $item->getSrvUnits();
  1528.                             if (empty($unitsServ) or $unitsServ == "0") {
  1529.                                 $unitsServ 1;
  1530.                             }
  1531.                             $subtotal $subtotalService $days $unitsServ $pax;
  1532.                             $subnetoUnit $subneto;
  1533.                             $subneto $subneto $days $unitsServ $pax;
  1534.                             $data_supplier['service'][$i] = array(
  1535.                                 'id' => $item->getId(),
  1536.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1537.                                 'serviceName' => $item->getSrvName(),
  1538.                                 'serviceType' => 'Creativo',
  1539.                                 'date' => $dateServ,
  1540.                                 'qty' => $unitsServ,
  1541.                                 'iva' => $item->getSrvIva(),
  1542.                                 'pax' => $item->getSrvPax(),
  1543.                                 'precioUnit' => $subnetoUnit,
  1544.                                 'subneto' => $subneto,
  1545.                                 'subtotal' => $subtotal,
  1546.                             );
  1547.                             break;
  1548.                         case 5//Cruise
  1549.                             $pax $item->getSrvPax();
  1550.                             if (empty($pax) or $pax == "0") {
  1551.                                 $pax 1;
  1552.                             }
  1553.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days);
  1554.                             if ($days 1) {
  1555.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1556.                             } else {
  1557.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1558.                             }
  1559.                             $unitsServ $item->getSrvUnits();
  1560.                             if (empty($unitsServ) or $unitsServ == "0") {
  1561.                                 $unitsServ 1;
  1562.                             }
  1563.                             $subtotal $subtotalService $days $unitsServ $pax;
  1564.                             $subnetoUnit $subneto;
  1565.                             $subneto $subneto $days $unitsServ $pax;
  1566.                             $data_supplier['service'][$i] = array(
  1567.                                 'id' => $item->getId(),
  1568.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1569.                                 'serviceName' => $item->getSrvName(),
  1570.                                 'serviceType' => 'Crucero',
  1571.                                 'date' => $dateServ,
  1572.                                 'qty' => $unitsServ,
  1573.                                 'iva' => $item->getSrvIva(),
  1574.                                 'pax' => $item->getSrvPax(),
  1575.                                 'precioUnit' => $subnetoUnit,
  1576.                                 'subneto' => $subneto,
  1577.                                 'subtotal' => $subtotal,
  1578.                             );
  1579.                             break;
  1580.                         case 6//Entertaiment
  1581.                             $pax $item->getSrvPax();
  1582.                             if (empty($pax) or $pax == "0") {
  1583.                                 $pax 1;
  1584.                             }
  1585.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1586.                             if ($days 1) {
  1587.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1588.                             } else {
  1589.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1590.                             }
  1591.                             $unitsServ $item->getSrvUnits();
  1592.                             if (empty($unitsServ) or $unitsServ == "0") {
  1593.                                 $unitsServ 1;
  1594.                             }
  1595.                             $subtotal $subtotalService $days $unitsServ $pax;
  1596.                             $subnetoUnit $subneto;
  1597.                             $subneto $subneto $days $unitsServ $pax;
  1598.                             $data_supplier['service'][$i] = array(
  1599.                                 'id' => $item->getId(),
  1600.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1601.                                 'serviceName' => $item->getSrvName(),
  1602.                                 'serviceType' => 'Entretenimiento',
  1603.                                 'date' => $dateServ,
  1604.                                 'qty' => $unitsServ,
  1605.                                 'iva' => $item->getSrvIva(),
  1606.                                 'pax' => $item->getSrvPax(),
  1607.                                 'precioUnit' => $subnetoUnit,
  1608.                                 'subneto' => $subneto,
  1609.                                 'subtotal' => $subtotal,
  1610.                             );
  1611.                             break;
  1612.                         case 7// Gifts
  1613.                             $pax $item->getSrvPax();
  1614.                             if (empty($pax) or $pax == "0") {
  1615.                                 $pax 1;
  1616.                             }
  1617. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  1618.                             $days 1;
  1619.                             if ($days 1) {
  1620.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1621.                             } else {
  1622.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1623.                             }
  1624.                             $unitsServ $item->getSrvUnits();
  1625.                             if (empty($unitsServ) or $unitsServ == "0") {
  1626.                                 $unitsServ 1;
  1627.                             }
  1628.                             $subtotal $subtotalService $days $unitsServ $pax;
  1629.                             $subnetoUnit $subneto;
  1630.                             $subneto $subneto $days $unitsServ $pax;
  1631.                             $data_supplier['service'][$i] = array(
  1632.                                 'id' => $item->getId(),
  1633.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1634.                                 'serviceName' => $item->getSrvName(),
  1635.                                 'serviceType' => 'Regalos',
  1636.                                 'date' => $dateServ,
  1637.                                 'qty' => $unitsServ,
  1638.                                 'iva' => $item->getSrvIva(),
  1639.                                 'pax' => $item->getSrvPax(),
  1640.                                 'precioUnit' => $subnetoUnit,
  1641.                                 'subneto' => $subneto,
  1642.                                 'subtotal' => $subtotal,
  1643.                             );
  1644.                             break;
  1645.                         case 8//Guide
  1646.                             $pax $item->getSrvPax();
  1647.                             if (empty($pax) or $pax == "0") {
  1648.                                 $pax 1;
  1649.                             }
  1650.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1651.                             if ($days 1) {
  1652.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1653.                             } else {
  1654.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1655.                             }
  1656.                             $unitsServ $item->getSrvUnits();
  1657.                             if (empty($unitsServ) or $unitsServ == "0") {
  1658.                                 $unitsServ 1;
  1659.                             }
  1660.                             $subtotal $subtotalService $days $unitsServ $pax;
  1661.                             $subnetoUnit $subneto;
  1662.                             $subneto $subneto $days $unitsServ $pax;
  1663.                             $data_supplier['service'][$i] = array(
  1664.                                 'id' => $item->getId(),
  1665.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1666.                                 'serviceName' => $item->getSrvName(),
  1667.                                 'serviceType' => 'Regalos',
  1668.                                 'date' => $dateServ,
  1669.                                 'qty' => $unitsServ,
  1670.                                 'iva' => $item->getSrvIva(),
  1671.                                 'pax' => $item->getSrvPax(),
  1672.                                 'precioUnit' => $subnetoUnit,
  1673.                                 'subneto' => $subneto,
  1674.                                 'subtotal' => $subtotal,
  1675.                             );
  1676.                             break;
  1677.                         case 9//Itineraries
  1678.                             $pax $item->getSrvPax();
  1679.                             if (empty($pax) or $pax == "0") {
  1680.                                 $pax 1;
  1681.                             }
  1682.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1683.                             if ($days 1) {
  1684.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1685.                             } else {
  1686.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1687.                             }
  1688.                             $unitsServ $item->getSrvUnits();
  1689.                             if (empty($unitsServ) or $unitsServ == "0") {
  1690.                                 $unitsServ 1;
  1691.                             }
  1692.                             $subtotal $subtotalService $days $unitsServ $pax;
  1693.                             $subnetoUnit $subneto;
  1694.                             $subneto $subneto $days $unitsServ $pax;
  1695.                             $data_supplier['service'][$i] = array(
  1696.                                 'id' => $item->getId(),
  1697.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1698.                                 'serviceName' => $item->getSrvName(),
  1699.                                 'serviceType' => 'Itinerarios',
  1700.                                 'date' => $dateServ,
  1701.                                 'qty' => $unitsServ,
  1702.                                 'iva' => $item->getSrvIva(),
  1703.                                 'pax' => $item->getSrvPax(),
  1704.                                 'precioUnit' => $subnetoUnit,
  1705.                                 'subneto' => $subneto,
  1706.                                 'subtotal' => $subtotal,
  1707.                             );
  1708.                             break;
  1709.                         case 10//Lounge  -- No Aplica
  1710. //                        $pax = $item->getPax();
  1711. //                        if (empty($pax) or $pax == "0") {
  1712. //                            $pax = 1;
  1713. //                        }
  1714. //
  1715. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  1716. //                        if ($days > 1){
  1717. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  1718. //                        } else {
  1719. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y');
  1720. //                        }
  1721. //
  1722. //                        $unitsServ = $item->getUnits();
  1723. //                        if (empty($unitsServ) or $unitsServ == "0") {
  1724. //                            $unitsServ = 1;
  1725. //                        }
  1726. //
  1727. //                        $subtotal = $subtotalService * $days * $unitsServ * $pax;
  1728. //                        $subnetoUnit = $subneto;
  1729. //                        $subneto = $subneto * $days * $unitsServ * $pax;
  1730. //
  1731. //                        $data_supplier['service'][$i] = array (
  1732. //                            'id' => $item->getId(),
  1733. //                            'serviceCatId' => $item->getServiceCatId(),
  1734. //                            'serviceName' => $item->getName(),
  1735. //                            'serviceType' => 'Itinerarios',
  1736. //                            'date' => $dateServ,
  1737. //                            'qty' => $unitsServ,
  1738. //                            'iva' => $item->getIva(),
  1739. //                            'pax' => $item->getPax(),
  1740. //                            'precioUnit' => $subnetoUnit,
  1741. //                            'subneto' => $subneto,
  1742. //                            'subtotal' => $subtotal,
  1743. //                        );
  1744.                             break;
  1745.                         case 11//Menu
  1746.                             $pax $item->getSrvPax();
  1747.                             if (empty($pax) or $pax == "0") {
  1748.                                 $pax 1;
  1749.                             }
  1750.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1751.                             if ($days 1) {
  1752.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1753.                             } else {
  1754.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1755.                             }
  1756.                             $unitsServ $item->getSrvUnits();
  1757.                             if (empty($unitsServ) or $unitsServ == "0") {
  1758.                                 $unitsServ 1;
  1759.                             }
  1760.                             $subtotal $subtotalService $days $unitsServ $pax;
  1761.                             $subnetoUnit $subneto;
  1762.                             $subneto $subneto $days $unitsServ $pax;
  1763.                             $data_supplier['service'][$i] = array(
  1764.                                 'id' => $item->getId(),
  1765.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1766.                                 'serviceName' => $item->getSrvName(),
  1767.                                 'serviceType' => 'MenĆŗ',
  1768.                                 'date' => $dateServ,
  1769.                                 'qty' => $unitsServ,
  1770.                                 'iva' => $item->getSrvIva(),
  1771.                                 'pax' => $item->getSrvPax(),
  1772.                                 'precioUnit' => $subnetoUnit,
  1773.                                 'subneto' => $subneto,
  1774.                                 'subtotal' => $subtotal,
  1775.                             );
  1776.                             break;
  1777.                         case 12//Others
  1778.                             $pax $item->getSrvPax();
  1779.                             if (empty($pax) or $pax == "0") {
  1780.                                 $pax 1;
  1781.                             }
  1782.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1783.                             if ($days 1) {
  1784.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1785.                             } else {
  1786.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1787.                             }
  1788.                             $unitsServ $item->getSrvUnits();
  1789.                             if (empty($unitsServ) or $unitsServ == "0") {
  1790.                                 $unitsServ 1;
  1791.                             }
  1792.                             $subtotal $subtotalService $days $unitsServ $pax;
  1793.                             $subnetoUnit $subneto;
  1794.                             $subneto $subneto $days $unitsServ $pax;
  1795.                             $data_supplier['service'][$i] = array(
  1796.                                 'id' => $item->getId(),
  1797.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1798.                                 'serviceName' => $item->getSrvName(),
  1799.                                 'serviceType' => 'Otros',
  1800.                                 'date' => $dateServ,
  1801.                                 'qty' => $unitsServ,
  1802.                                 'iva' => $item->getSrvIva(),
  1803.                                 'pax' => $item->getSrvPax(),
  1804.                                 'precioUnit' => $subnetoUnit,
  1805.                                 'subneto' => $subneto,
  1806.                                 'subtotal' => $subtotal,
  1807.                             );
  1808.                             break;
  1809.                         case 13//Transport
  1810.                             $pax $item->getSrvPax();
  1811.                             if (empty($pax) or $pax == "0") {
  1812.                                 $pax 1;
  1813.                             }
  1814.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1815.                             if ($days 1) {
  1816.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1817.                             } else {
  1818.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1819.                             }
  1820.                             $unitsServ $item->getSrvUnits();
  1821.                             if (empty($unitsServ) or $unitsServ == "0") {
  1822.                                 $unitsServ 1;
  1823.                             }
  1824.                             $subtotal $subtotalService $days $unitsServ $pax;
  1825.                             $subnetoUnit $subneto;
  1826.                             $subneto $subneto $days $unitsServ $pax;
  1827.                             $data_supplier['service'][$i] = array(
  1828.                                 'id' => $item->getId(),
  1829.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1830.                                 'serviceName' => $item->getSrvName(),
  1831.                                 'serviceType' => 'Transporte',
  1832.                                 'date' => $dateServ,
  1833.                                 'qty' => $unitsServ,
  1834.                                 'iva' => $item->getSrvIva(),
  1835.                                 'pax' => $item->getSrvPax(),
  1836.                                 'precioUnit' => $subnetoUnit,
  1837.                                 'subneto' => $subneto,
  1838.                                 'subtotal' => $subtotal,
  1839.                             );
  1840.                             break;
  1841.                         case 14//Technology
  1842.                             $pax $item->getSrvPax();
  1843.                             if (empty($pax) or $pax == "0") {
  1844.                                 $pax 1;
  1845.                             }
  1846. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  1847.                             $days 1;
  1848. //                        if ($days > 1){
  1849. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  1850. //                        } else {
  1851. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y');
  1852. //                        }
  1853.                             $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1854.                             $unitsServ $item->getSrvUnits();
  1855.                             if (empty($unitsServ) or $unitsServ == "0") {
  1856.                                 $unitsServ 1;
  1857.                             }
  1858.                             $subtotal $subtotalService $days $unitsServ $pax;
  1859.                             $subnetoUnit $subneto;
  1860.                             $subneto $subneto $days $unitsServ $pax;
  1861.                             $data_supplier['service'][$i] = array(
  1862.                                 'id' => $item->getId(),
  1863.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1864.                                 'serviceName' => $item->getSrvName(),
  1865.                                 'serviceType' => 'TecnologĆ­a',
  1866.                                 'date' => $dateServ,
  1867.                                 'qty' => $unitsServ,
  1868.                                 'iva' => $item->getSrvIva(),
  1869.                                 'pax' => $item->getSrvPax(),
  1870.                                 'precioUnit' => $subnetoUnit,
  1871.                                 'subneto' => $subneto,
  1872.                                 'subtotal' => $subtotal,
  1873.                             );
  1874.                             break;
  1875.                         case 15//Assisstant
  1876.                             $pax $item->getSrvPax();
  1877.                             if (empty($pax) or $pax == "0") {
  1878.                                 $pax 1;
  1879.                             }
  1880.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1881.                             if ($days 1) {
  1882.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1883.                             } else {
  1884.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1885.                             }
  1886.                             $unitsServ $item->getSrvUnits();
  1887.                             if (empty($unitsServ) or $unitsServ == "0") {
  1888.                                 $unitsServ 1;
  1889.                             }
  1890.                             $subtotal $subtotalService $days $unitsServ $pax;
  1891.                             $subnetoUnit $subneto;
  1892.                             $subneto $subneto $days $unitsServ $pax;
  1893.                             $data_supplier['service'][$i] = array(
  1894.                                 'id' => $item->getId(),
  1895.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1896.                                 'serviceName' => $item->getSrvName(),
  1897.                                 'serviceType' => 'Asistente',
  1898.                                 'date' => $dateServ,
  1899.                                 'qty' => $unitsServ,
  1900.                                 'iva' => $item->getSrvIva(),
  1901.                                 'pax' => $item->getSrvPax(),
  1902.                                 'precioUnit' => $subnetoUnit,
  1903.                                 'subneto' => $subneto,
  1904.                                 'subtotal' => $subtotal,
  1905.                             );
  1906.                             break;
  1907.                         case 16//DDR
  1908.                             $pax $item->getSrvPax();
  1909.                             if (empty($pax) or $pax == "0") {
  1910.                                 $pax 1;
  1911.                             }
  1912.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1913.                             if ($days 1) {
  1914.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1915.                             } else {
  1916.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1917.                             }
  1918.                             $unitsServ $item->getSrvUnits();
  1919.                             if (empty($unitsServ) or $unitsServ == "0") {
  1920.                                 $unitsServ 1;
  1921.                             }
  1922.                             $subtotal $subtotalService $days $unitsServ $pax;
  1923.                             $subnetoUnit $subneto;
  1924.                             $subneto $subneto $days $unitsServ $pax;
  1925.                             $data_supplier['service'][$i] = array(
  1926.                                 'id' => $item->getId(),
  1927.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1928.                                 'serviceName' => $item->getSrvName(),
  1929.                                 'serviceType' => 'DDR',
  1930.                                 'date' => $dateServ,
  1931.                                 'qty' => $unitsServ,
  1932.                                 'iva' => $item->getSrvIva(),
  1933.                                 'pax' => $item->getSrvPax(),
  1934.                                 'precioUnit' => $subnetoUnit,
  1935.                                 'subneto' => $subneto,
  1936.                                 'subtotal' => $subtotal,
  1937.                             );
  1938.                             break;
  1939.                         default:
  1940.                             break;
  1941.                     }
  1942.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  1943.                     $subtotal round($subtotal2PHP_ROUND_HALF_UP);
  1944.                     $neto round($subneto2PHP_ROUND_HALF_UP);
  1945.                     $arrayItems[] = array(
  1946.                         'type' => 'Service',
  1947.                         'name' => $item->getSrvName(),
  1948.                         'amount' => $neto,
  1949.                         'iva' => $item->getSrvIva(),
  1950.                         'total' => $subtotal,
  1951.                     );
  1952.                 }
  1953.                 switch ($item->getSrvIva()) {
  1954.                     // Acumula IVA
  1955.                     case 21:
  1956.                         $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($item->getSrvIva() / 100));
  1957.                         break;
  1958.                     case 10:
  1959.                         $data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * ($item->getSrvIva() / 100));
  1960.                         break;
  1961.                     case 0:
  1962.                         break;
  1963.                     default:
  1964.                         break;
  1965.                 }
  1966.             } else {
  1967.                 // Es una proforma
  1968.                 if (is_null($item->getPrice()) or empty($item->getPrice())) {
  1969.                     $subtotal 0;
  1970.                     $neto 0;
  1971.                     $subtotalService 0;
  1972.                 } else {
  1973.                     $subtotalService $item->getPrice();
  1974.                     $subneto $item->getPrice();
  1975.                     // Commission
  1976.                     if ($item->getOpCommission() == '1') {
  1977.                         $subtotalService $subtotalService * (+ ($item->getCommission() / 100));
  1978.                         $subneto $subneto * (+ ($item->getCommission() / 100));
  1979.                     } else {
  1980.                         $subtotalService $subtotalService * (- ($item->getCommission() / 100));
  1981.                         $subneto $subneto * (- ($item->getCommission() / 100));
  1982.                     }
  1983.                     // Over
  1984.                     if ($item->getOpOver() == '1') {
  1985.                         $subtotalService $subtotalService $item->getOver();
  1986.                         $subneto $subneto $item->getOver();
  1987.                     } else {
  1988.                         $subtotalService $subtotalService $item->getOver();
  1989.                         $subneto $subneto $item->getOver();
  1990.                     }
  1991.                     // IVA
  1992.                     if ($item->getOpIva() == '1') {
  1993.                         $subtotalService $subtotalService * (+ ($item->getIva() / 100));
  1994.                     } else {
  1995.                         $subtotalService $item->getPrice();
  1996.                         $subneto = ($subneto 100) / (100 $item->getIva());
  1997.                     }
  1998.                     switch ($item->getServiceCatId()) {
  1999.                         case 1// Alojamiento
  2000.                             // el numero de noches $numNoches; precio unitario $subneto
  2001.                             $numNoches = (($item->getDateOutAt())->diff($item->getDateInAt()))->days;
  2002.                             // La personas no afectan este calculo
  2003.                             $subtotal $subtotalService $numNoches $item->getUnits();
  2004.                             $subnetoUnit $subneto;
  2005.                             $subneto $subneto $numNoches $item->getUnits();
  2006.                             $data_supplier['service'][$i] = array(
  2007.                                 'id' => $item->getId(),
  2008.                                 'serviceCatId' => $item->getServiceCatId(),
  2009.                                 'serviceName' => $item->getName(),
  2010.                                 'serviceType' => 'Hotel',
  2011.                                 'date' => ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y'),
  2012.                                 'qty' => $item->getUnits(),
  2013.                                 'iva' => $item->getIva(),
  2014.                                 'pax' => '-',
  2015.                                 'precioUnit' => $subnetoUnit,
  2016.                                 'subneto' => $subneto,
  2017.                                 'subtotal' => $subtotal,
  2018.                             );
  2019.                             break;
  2020.                         case 2//Actividades
  2021.                             // El nĆŗmero de personas es considerado en el calculo
  2022.                             $pax $item->getPax();
  2023.                             if (empty($pax) or $pax == "0") {
  2024.                                 $pax 1;
  2025.                             }
  2026.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2027.                             if ($days 1) {
  2028.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2029.                             } else {
  2030.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2031.                             }
  2032.                             $subtotal $subtotalService $days $item->getUnits();
  2033.                             $subnetoUnit $subneto;
  2034.                             $subneto $subneto $days $item->getUnits();
  2035.                             $data_supplier['service'][$i] = array(
  2036.                                 'id' => $item->getId(),
  2037.                                 'serviceCatId' => $item->getServiceCatId(),
  2038.                                 'serviceName' => $item->getName(),
  2039.                                 'serviceType' => 'Actividad',
  2040.                                 'date' => $dateServ,
  2041.                                 'qty' => $item->getUnits(),
  2042.                                 'iva' => $item->getIva(),
  2043.                                 'pax' => $item->getPax(),
  2044.                                 'precioUnit' => $subnetoUnit,
  2045.                                 'subneto' => $subneto,
  2046.                                 'subtotal' => $subtotal,
  2047.                             );
  2048.                             break;
  2049.                         case 3// AV
  2050.                             $pax $item->getPax();
  2051.                             if (empty($pax) or $pax == "0") {
  2052.                                 $pax 1;
  2053.                             }
  2054.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2055.                             if ($days 1) {
  2056.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2057.                             } else {
  2058.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2059.                             }
  2060.                             $unitsServ $item->getUnits();
  2061.                             if (empty($unitsServ) or $unitsServ == "0") {
  2062.                                 $unitsServ 1;
  2063.                             }
  2064.                             $subtotal $subtotalService $days $unitsServ $pax;
  2065.                             $subnetoUnit $subneto;
  2066.                             $subneto $subneto $days $unitsServ $pax;
  2067.                             $data_supplier['service'][$i] = array(
  2068.                                 'id' => $item->getId(),
  2069.                                 'serviceCatId' => $item->getServiceCatId(),
  2070.                                 'serviceName' => $item->getName(),
  2071.                                 'serviceType' => 'AV',
  2072.                                 'date' => $dateServ,
  2073.                                 'qty' => $unitsServ,
  2074.                                 'iva' => $item->getIva(),
  2075.                                 'pax' => $item->getPax(),
  2076.                                 'precioUnit' => $subnetoUnit,
  2077.                                 'subneto' => $subneto,
  2078.                                 'subtotal' => $subtotal,
  2079.                             );
  2080.                             break;
  2081.                         case 4//Creative
  2082.                             $pax $item->getPax();
  2083.                             if (empty($pax) or $pax == "0") {
  2084.                                 $pax 1;
  2085.                             }
  2086.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2087.                             if ($days 1) {
  2088.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2089.                             } else {
  2090.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2091.                             }
  2092.                             $unitsServ $item->getUnits();
  2093.                             if (empty($unitsServ) or $unitsServ == "0") {
  2094.                                 $unitsServ 1;
  2095.                             }
  2096.                             $subtotal $subtotalService $days $unitsServ $pax;
  2097.                             $subnetoUnit $subneto;
  2098.                             $subneto $subneto $days $unitsServ $pax;
  2099.                             $data_supplier['service'][$i] = array(
  2100.                                 'id' => $item->getId(),
  2101.                                 'serviceCatId' => $item->getServiceCatId(),
  2102.                                 'serviceName' => $item->getName(),
  2103.                                 'serviceType' => 'Creativo',
  2104.                                 'date' => $dateServ,
  2105.                                 'qty' => $unitsServ,
  2106.                                 'iva' => $item->getIva(),
  2107.                                 'pax' => $item->getPax(),
  2108.                                 'precioUnit' => $subnetoUnit,
  2109.                                 'subneto' => $subneto,
  2110.                                 'subtotal' => $subtotal,
  2111.                             );
  2112.                             break;
  2113.                         case 5//Cruise
  2114.                             $pax $item->getPax();
  2115.                             if (empty($pax) or $pax == "0") {
  2116.                                 $pax 1;
  2117.                             }
  2118.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days);
  2119.                             if ($days 1) {
  2120.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2121.                             } else {
  2122.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2123.                             }
  2124.                             $unitsServ $item->getUnits();
  2125.                             if (empty($unitsServ) or $unitsServ == "0") {
  2126.                                 $unitsServ 1;
  2127.                             }
  2128.                             $subtotal $subtotalService $days $unitsServ $pax;
  2129.                             $subnetoUnit $subneto;
  2130.                             $subneto $subneto $days $unitsServ $pax;
  2131.                             $data_supplier['service'][$i] = array(
  2132.                                 'id' => $item->getId(),
  2133.                                 'serviceCatId' => $item->getServiceCatId(),
  2134.                                 'serviceName' => $item->getName(),
  2135.                                 'serviceType' => 'Crucero',
  2136.                                 'date' => $dateServ,
  2137.                                 'qty' => $unitsServ,
  2138.                                 'iva' => $item->getIva(),
  2139.                                 'pax' => $item->getPax(),
  2140.                                 'precioUnit' => $subnetoUnit,
  2141.                                 'subneto' => $subneto,
  2142.                                 'subtotal' => $subtotal,
  2143.                             );
  2144.                             break;
  2145.                         case 6//Entertaiment
  2146.                             $pax $item->getPax();
  2147.                             if (empty($pax) or $pax == "0") {
  2148.                                 $pax 1;
  2149.                             }
  2150.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2151.                             if ($days 1) {
  2152.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2153.                             } else {
  2154.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2155.                             }
  2156.                             $unitsServ $item->getUnits();
  2157.                             if (empty($unitsServ) or $unitsServ == "0") {
  2158.                                 $unitsServ 1;
  2159.                             }
  2160.                             $subtotal $subtotalService $days $unitsServ $pax;
  2161.                             $subnetoUnit $subneto;
  2162.                             $subneto $subneto $days $unitsServ $pax;
  2163.                             $data_supplier['service'][$i] = array(
  2164.                                 'id' => $item->getId(),
  2165.                                 'serviceCatId' => $item->getServiceCatId(),
  2166.                                 'serviceName' => $item->getName(),
  2167.                                 'serviceType' => 'Entretenimiento',
  2168.                                 'date' => $dateServ,
  2169.                                 'qty' => $unitsServ,
  2170.                                 'iva' => $item->getIva(),
  2171.                                 'pax' => $item->getPax(),
  2172.                                 'precioUnit' => $subnetoUnit,
  2173.                                 'subneto' => $subneto,
  2174.                                 'subtotal' => $subtotal,
  2175.                             );
  2176.                             break;
  2177.                         case 7// Gifts
  2178.                             $pax $item->getPax();
  2179.                             if (empty($pax) or $pax == "0") {
  2180.                                 $pax 1;
  2181.                             }
  2182. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  2183.                             $days 1;
  2184.                             if ($days 1) {
  2185.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2186.                             } else {
  2187.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2188.                             }
  2189.                             $unitsServ $item->getUnits();
  2190.                             if (empty($unitsServ) or $unitsServ == "0") {
  2191.                                 $unitsServ 1;
  2192.                             }
  2193.                             $subtotal $subtotalService $days $unitsServ $pax;
  2194.                             $subnetoUnit $subneto;
  2195.                             $subneto $subneto $days $unitsServ $pax;
  2196.                             $data_supplier['service'][$i] = array(
  2197.                                 'id' => $item->getId(),
  2198.                                 'serviceCatId' => $item->getServiceCatId(),
  2199.                                 'serviceName' => $item->getName(),
  2200.                                 'serviceType' => 'Regalos',
  2201.                                 'date' => $dateServ,
  2202.                                 'qty' => $unitsServ,
  2203.                                 'iva' => $item->getIva(),
  2204.                                 'pax' => $item->getPax(),
  2205.                                 'precioUnit' => $subnetoUnit,
  2206.                                 'subneto' => $subneto,
  2207.                                 'subtotal' => $subtotal,
  2208.                             );
  2209.                             break;
  2210.                         case 8//Guide
  2211.                             $pax $item->getPax();
  2212.                             if (empty($pax) or $pax == "0") {
  2213.                                 $pax 1;
  2214.                             }
  2215.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2216.                             if ($days 1) {
  2217.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2218.                             } else {
  2219.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2220.                             }
  2221.                             $unitsServ $item->getUnits();
  2222.                             if (empty($unitsServ) or $unitsServ == "0") {
  2223.                                 $unitsServ 1;
  2224.                             }
  2225.                             $subtotal $subtotalService $days $unitsServ $pax;
  2226.                             $subnetoUnit $subneto;
  2227.                             $subneto $subneto $days $unitsServ $pax;
  2228.                             $data_supplier['service'][$i] = array(
  2229.                                 'id' => $item->getId(),
  2230.                                 'serviceCatId' => $item->getServiceCatId(),
  2231.                                 'serviceName' => $item->getName(),
  2232.                                 'serviceType' => 'Regalos',
  2233.                                 'date' => $dateServ,
  2234.                                 'qty' => $unitsServ,
  2235.                                 'iva' => $item->getIva(),
  2236.                                 'pax' => $item->getPax(),
  2237.                                 'precioUnit' => $subnetoUnit,
  2238.                                 'subneto' => $subneto,
  2239.                                 'subtotal' => $subtotal,
  2240.                             );
  2241.                             break;
  2242.                         case 9//Itineraries
  2243.                             $pax $item->getPax();
  2244.                             if (empty($pax) or $pax == "0") {
  2245.                                 $pax 1;
  2246.                             }
  2247.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2248.                             if ($days 1) {
  2249.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2250.                             } else {
  2251.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2252.                             }
  2253.                             $unitsServ $item->getUnits();
  2254.                             if (empty($unitsServ) or $unitsServ == "0") {
  2255.                                 $unitsServ 1;
  2256.                             }
  2257.                             $subtotal $subtotalService $days $unitsServ $pax;
  2258.                             $subnetoUnit $subneto;
  2259.                             $subneto $subneto $days $unitsServ $pax;
  2260.                             $data_supplier['service'][$i] = array(
  2261.                                 'id' => $item->getId(),
  2262.                                 'serviceCatId' => $item->getServiceCatId(),
  2263.                                 'serviceName' => $item->getName(),
  2264.                                 'serviceType' => 'Itinerarios',
  2265.                                 'date' => $dateServ,
  2266.                                 'qty' => $unitsServ,
  2267.                                 'iva' => $item->getIva(),
  2268.                                 'pax' => $item->getPax(),
  2269.                                 'precioUnit' => $subnetoUnit,
  2270.                                 'subneto' => $subneto,
  2271.                                 'subtotal' => $subtotal,
  2272.                             );
  2273.                             break;
  2274.                         case 10//Lounge  -- No Aplica
  2275. //                        $pax = $item->getPax();
  2276. //                        if (empty($pax) or $pax == "0") {
  2277. //                            $pax = 1;
  2278. //                        }
  2279. //
  2280. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  2281. //                        if ($days > 1){
  2282. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2283. //                        } else {
  2284. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2285. //                        }
  2286. //
  2287. //                        $unitsServ = $item->getUnits();
  2288. //                        if (empty($unitsServ) or $unitsServ == "0") {
  2289. //                            $unitsServ = 1;
  2290. //                        }
  2291. //
  2292. //                        $subtotal = $subtotalService * $days * $unitsServ * $pax;
  2293. //                        $subnetoUnit = $subneto;
  2294. //                        $subneto = $subneto * $days * $unitsServ * $pax;
  2295. //
  2296. //                        $data_supplier['service'][$i] = array (
  2297. //                            'id' => $item->getId(),
  2298. //                            'serviceCatId' => $item->getServiceCatId(),
  2299. //                            'serviceName' => $item->getName(),
  2300. //                            'serviceType' => 'Itinerarios',
  2301. //                            'date' => $dateServ,
  2302. //                            'qty' => $unitsServ,
  2303. //                            'iva' => $item->getIva(),
  2304. //                            'pax' => $item->getPax(),
  2305. //                            'precioUnit' => $subnetoUnit,
  2306. //                            'subneto' => $subneto,
  2307. //                            'subtotal' => $subtotal,
  2308. //                        );
  2309.                             break;
  2310.                         case 11//Menu
  2311.                             $pax $item->getPax();
  2312.                             if (empty($pax) or $pax == "0") {
  2313.                                 $pax 1;
  2314.                             }
  2315.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2316.                             if ($days 1) {
  2317.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2318.                             } else {
  2319.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2320.                             }
  2321.                             $unitsServ $item->getUnits();
  2322.                             if (empty($unitsServ) or $unitsServ == "0") {
  2323.                                 $unitsServ 1;
  2324.                             }
  2325.                             $subtotal $subtotalService $days $unitsServ $pax;
  2326.                             $subnetoUnit $subneto;
  2327.                             $subneto $subneto $days $unitsServ $pax;
  2328.                             $data_supplier['service'][$i] = array(
  2329.                                 'id' => $item->getId(),
  2330.                                 'serviceCatId' => $item->getServiceCatId(),
  2331.                                 'serviceName' => $item->getName(),
  2332.                                 'serviceType' => 'MenĆŗ',
  2333.                                 'date' => $dateServ,
  2334.                                 'qty' => $unitsServ,
  2335.                                 'iva' => $item->getIva(),
  2336.                                 'pax' => $item->getPax(),
  2337.                                 'precioUnit' => $subnetoUnit,
  2338.                                 'subneto' => $subneto,
  2339.                                 'subtotal' => $subtotal,
  2340.                             );
  2341.                             break;
  2342.                         case 12//Others
  2343.                             $pax $item->getPax();
  2344.                             if (empty($pax) or $pax == "0") {
  2345.                                 $pax 1;
  2346.                             }
  2347.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2348.                             if ($days 1) {
  2349.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2350.                             } else {
  2351.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2352.                             }
  2353.                             $unitsServ $item->getUnits();
  2354.                             if (empty($unitsServ) or $unitsServ == "0") {
  2355.                                 $unitsServ 1;
  2356.                             }
  2357.                             $subtotal $subtotalService $days $unitsServ $pax;
  2358.                             $subnetoUnit $subneto;
  2359.                             $subneto $subneto $days $unitsServ $pax;
  2360.                             $data_supplier['service'][$i] = array(
  2361.                                 'id' => $item->getId(),
  2362.                                 'serviceCatId' => $item->getServiceCatId(),
  2363.                                 'serviceName' => $item->getName(),
  2364.                                 'serviceType' => 'Otros',
  2365.                                 'date' => $dateServ,
  2366.                                 'qty' => $unitsServ,
  2367.                                 'iva' => $item->getIva(),
  2368.                                 'pax' => $item->getPax(),
  2369.                                 'precioUnit' => $subnetoUnit,
  2370.                                 'subneto' => $subneto,
  2371.                                 'subtotal' => $subtotal,
  2372.                             );
  2373.                             break;
  2374.                         case 13//Transport
  2375.                             $pax $item->getPax();
  2376.                             if (empty($pax) or $pax == "0") {
  2377.                                 $pax 1;
  2378.                             }
  2379.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2380.                             if ($days 1) {
  2381.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2382.                             } else {
  2383.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2384.                             }
  2385.                             $unitsServ $item->getUnits();
  2386.                             if (empty($unitsServ) or $unitsServ == "0") {
  2387.                                 $unitsServ 1;
  2388.                             }
  2389.                             $subtotal $subtotalService $days $unitsServ $pax;
  2390.                             $subnetoUnit $subneto;
  2391.                             $subneto $subneto $days $unitsServ $pax;
  2392.                             $data_supplier['service'][$i] = array(
  2393.                                 'id' => $item->getId(),
  2394.                                 'serviceCatId' => $item->getServiceCatId(),
  2395.                                 'serviceName' => $item->getName(),
  2396.                                 'serviceType' => 'Transporte',
  2397.                                 'date' => $dateServ,
  2398.                                 'qty' => $unitsServ,
  2399.                                 'iva' => $item->getIva(),
  2400.                                 'pax' => $item->getPax(),
  2401.                                 'precioUnit' => $subnetoUnit,
  2402.                                 'subneto' => $subneto,
  2403.                                 'subtotal' => $subtotal,
  2404.                             );
  2405.                             break;
  2406.                         case 14//Technology
  2407.                             $pax $item->getPax();
  2408.                             if (empty($pax) or $pax == "0") {
  2409.                                 $pax 1;
  2410.                             }
  2411. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  2412.                             $days 1;
  2413. //                        if ($days > 1){
  2414. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2415. //                        } else {
  2416. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2417. //                        }
  2418.                             $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2419.                             $unitsServ $item->getUnits();
  2420.                             if (empty($unitsServ) or $unitsServ == "0") {
  2421.                                 $unitsServ 1;
  2422.                             }
  2423.                             $subtotal $subtotalService $days $unitsServ $pax;
  2424.                             $subnetoUnit $subneto;
  2425.                             $subneto $subneto $days $unitsServ $pax;
  2426.                             $data_supplier['service'][$i] = array(
  2427.                                 'id' => $item->getId(),
  2428.                                 'serviceCatId' => $item->getServiceCatId(),
  2429.                                 'serviceName' => $item->getName(),
  2430.                                 'serviceType' => 'TecnologĆ­a',
  2431.                                 'date' => $dateServ,
  2432.                                 'qty' => $unitsServ,
  2433.                                 'iva' => $item->getIva(),
  2434.                                 'pax' => $item->getPax(),
  2435.                                 'precioUnit' => $subnetoUnit,
  2436.                                 'subneto' => $subneto,
  2437.                                 'subtotal' => $subtotal,
  2438.                             );
  2439.                             break;
  2440.                         case 15//Assisstant
  2441.                             $pax $item->getPax();
  2442.                             if (empty($pax) or $pax == "0") {
  2443.                                 $pax 1;
  2444.                             }
  2445.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2446.                             if ($days 1) {
  2447.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2448.                             } else {
  2449.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2450.                             }
  2451.                             $unitsServ $item->getUnits();
  2452.                             if (empty($unitsServ) or $unitsServ == "0") {
  2453.                                 $unitsServ 1;
  2454.                             }
  2455.                             $subtotal $subtotalService $days $unitsServ $pax;
  2456.                             $subnetoUnit $subneto;
  2457.                             $subneto $subneto $days $unitsServ $pax;
  2458.                             $data_supplier['service'][$i] = array(
  2459.                                 'id' => $item->getId(),
  2460.                                 'serviceCatId' => $item->getServiceCatId(),
  2461.                                 'serviceName' => $item->getName(),
  2462.                                 'serviceType' => 'Asistente',
  2463.                                 'date' => $dateServ,
  2464.                                 'qty' => $unitsServ,
  2465.                                 'iva' => $item->getIva(),
  2466.                                 'pax' => $item->getPax(),
  2467.                                 'precioUnit' => $subnetoUnit,
  2468.                                 'subneto' => $subneto,
  2469.                                 'subtotal' => $subtotal,
  2470.                             );
  2471.                             break;
  2472.                         case 16//DDR
  2473.                             $pax $item->getPax();
  2474.                             if (empty($pax) or $pax == "0") {
  2475.                                 $pax 1;
  2476.                             }
  2477.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2478.                             if ($days 1) {
  2479.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2480.                             } else {
  2481.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2482.                             }
  2483.                             $unitsServ $item->getUnits();
  2484.                             if (empty($unitsServ) or $unitsServ == "0") {
  2485.                                 $unitsServ 1;
  2486.                             }
  2487.                             $subtotal $subtotalService $days $unitsServ $pax;
  2488.                             $subnetoUnit $subneto;
  2489.                             $subneto $subneto $days $unitsServ $pax;
  2490.                             $data_supplier['service'][$i] = array(
  2491.                                 'id' => $item->getId(),
  2492.                                 'serviceCatId' => $item->getServiceCatId(),
  2493.                                 'serviceName' => $item->getName(),
  2494.                                 'serviceType' => 'DDR',
  2495.                                 'date' => $dateServ,
  2496.                                 'qty' => $unitsServ,
  2497.                                 'iva' => $item->getIva(),
  2498.                                 'pax' => $item->getPax(),
  2499.                                 'precioUnit' => $subnetoUnit,
  2500.                                 'subneto' => $subneto,
  2501.                                 'subtotal' => $subtotal,
  2502.                             );
  2503.                             break;
  2504.                         default:
  2505.                             break;
  2506.                     }
  2507.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  2508.                     $subtotal round($subtotal2PHP_ROUND_HALF_UP);
  2509.                     $neto round($subneto2PHP_ROUND_HALF_UP);
  2510.                     $arrayItems[] = array(
  2511.                         'type' => 'Service',
  2512.                         'name' => $item->getName(),
  2513.                         'amount' => $neto,
  2514.                         'iva' => $item->getIva(),
  2515.                         'total' => $subtotal,
  2516.                     );
  2517.                 }
  2518.                 switch ($item->getIva()) {
  2519.                     // Acumula IVA
  2520.                     case 21:
  2521.                         $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($item->getIva() / 100));
  2522.                         break;
  2523.                     case 10:
  2524.                         $data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * ($item->getIva() / 100));
  2525.                         break;
  2526.                     case 0:
  2527.                         break;
  2528.                     default:
  2529.                         break;
  2530.                 }
  2531.             }
  2532.             $totales_neto_all $totales_neto_all $neto;
  2533.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  2534.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  2535.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  2536.             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
  2537.             // Acumula netos totales e IVA
  2538.             $service['neto'] = $service['neto'] + $neto;
  2539.             $service['sumSubT'] = $service['sumSubT'] + $subtotal;
  2540.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  2541.             $service['neto'] = round($service['neto'],2,PHP_ROUND_HALF_UP);
  2542.             $service['sumSubT'] = round($service['sumSubT'],2,PHP_ROUND_HALF_UP);
  2543.             $i++;
  2544.         }
  2545.         $data_supplier['serviceSubTotal'] = array(
  2546.             'neto' => $service['neto'],
  2547.             'sumSubT' => $service['sumSubT'],
  2548.         );
  2549.         $currency '€';
  2550.         $totales_total $totales_neto_all $data_iva['ivaMontoVeintiUno'] + $data_iva['ivaMontoDiez'];
  2551.         if (!empty($payments)) {
  2552.             $amount_pay $data_supplier['paymentSubTotal']['sumSubT'];
  2553.         } else {
  2554.             $amount_pay 0;
  2555.         }
  2556.         $totales_all $totales_total $amount_pay;
  2557.         if (empty($dateDocument)){
  2558.             $dateDocument = new DateTime('now');
  2559.         }
  2560.         $data = array(
  2561.             'id' => $fileId,
  2562.             'type' => $type,
  2563. //            'type' => '',
  2564.             'number' => $number,
  2565. //            'prefix' => $prefix,
  2566.             'prefix' => 'AVE-'.(new DateTime('now'))->format('dmy').'-'.$invoiceId,
  2567.             'date' => $dateDocument,
  2568.             'file' => $file,
  2569.             'token' => $file->getAccessKey(),
  2570.             'company' => $company,
  2571.             'clients' => $client,
  2572.             'arrayItems' => $arrayItems,
  2573.             'datasupplier' => $data_supplier,
  2574.             'currency' => $currency,
  2575.             'totales_neto' => $totales_neto_all,
  2576.             'bases_imponibles' => $data_iva,
  2577.             'totales' => $totales_total,
  2578.             'balance' => $totales_all,
  2579.             'paymentInvoice' => $amount_pay,
  2580.         );
  2581.         return $data;
  2582.     }
  2583.     // Replicar cambios entre FileController y ProductsFilesController
  2584.     private function calculosFile($id$arrayBools$number$type)
  2585.     {
  2586.         // $id Id del Expediente (File)
  2587.         // $arrayBool arreglo de logicos
  2588.         // $number  *********************
  2589.         // $type tipo de calculos a realizar (edicion de expediente, factura, factura de deposito, proforma)
  2590.         $em $this->getDoctrine()->getManager();
  2591.         $file $em->getRepository(AveFiles::class)->findOneById($id);
  2592. //        $items = $em->getRepository(AveProductFile::class)->findByFileId($file->getId());
  2593.         // Primero se agrupan por sala (Ubicacion), luego por tipo y finalmente por RankAv
  2594.         // Salvador Guerrero indico, el orden de los productos en la factura o proforma serĆ” (Video - Sonido - Iluminacion - Otros)
  2595.         $allProductFile $em->getRepository(AveProductFile::class)->findByFileId($id);
  2596.         $arrayLocation = array();
  2597.         $arrayLocationWithNull false;
  2598.         foreach ($allProductFile as $item){
  2599.             if (!empty($item->getLocation())){
  2600.                 $arrayLocation[$item->getLocation()] = $item->getLocation();
  2601.             } else {
  2602.                 $arrayLocationWithNull true;
  2603.             }
  2604.         }
  2605.         if ($arrayLocationWithNull){ $arrayLocation['null'] = 'null'; }
  2606.         $productsInFile = array();
  2607.         $items = array();
  2608.         foreach ($arrayLocation as $item){
  2609.             // VIDEO
  2610.             $parameters = array(
  2611.                 'fileId' => $id,
  2612.                 'type' => 'VĆ­deo',
  2613.                 'location' => $item,
  2614.             );
  2615.             $dql 'SELECT i
  2616.                     FROM AvexpressBundle:AveProductFile i
  2617.                     WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location
  2618.                     ORDER BY i.rankAv ASC';
  2619.             $query $em->createQuery($dql)->setParameters($parameters);
  2620.             $productsInFileVid $query->getResult();
  2621.             // SONIDO
  2622.             $parameters = array(
  2623.                 'fileId' => $id,
  2624.                 'type' => 'Sonido',
  2625.                 'location' => $item,
  2626.             );
  2627.             $dql 'SELECT i
  2628.                     FROM AvexpressBundle:AveProductFile i
  2629.                     WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location
  2630.                     ORDER BY i.rankAv ASC';
  2631.             $query $em->createQuery($dql)->setParameters($parameters);
  2632.             $productsInFileSound $query->getResult();
  2633.             // ILUMINACION
  2634.             $parameters = array(
  2635.                 'fileId' => $id,
  2636.                 'type' => 'Iluminación',
  2637.                 'location' => $item,
  2638.             );
  2639.             $dql 'SELECT i
  2640.                     FROM AvexpressBundle:AveProductFile i
  2641.                     WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location
  2642.                     ORDER BY i.rankAv ASC';
  2643.             $query $em->createQuery($dql)->setParameters($parameters);
  2644.             $productsInFileLights $query->getResult();
  2645.             // OTROS
  2646.             $parameters = array(
  2647.                 'fileId' => $id,
  2648.                 'typeV' => 'VĆ­deo',
  2649.                 'typeS' => 'Sonido',
  2650.                 'typeI' => 'Iluminación',
  2651.                 'location' => $item,
  2652.             );
  2653.             $dql 'SELECT i
  2654.                     FROM AvexpressBundle:AveProductFile i
  2655.                     WHERE (i.fileId = :fileId AND i.type != :typeV AND i.type != :typeS AND i.type != :typeI AND i.location = :location)
  2656.                     ORDER BY i.rankAv ASC';
  2657.             $query $em->createQuery($dql)->setParameters($parameters);
  2658.             $productsInFileOther $query->getResult();
  2659.             // CASO NULL (Los casos EMPTY estan considerados en las consultas previas)
  2660.             $parameters = array(
  2661.                 'fileId' => $id,
  2662.                 'location' => $item,
  2663.             );
  2664.             $dql 'SELECT i
  2665.                     FROM AvexpressBundle:AveProductFile i
  2666.                     WHERE (i.fileId = :fileId AND i.type IS NULL AND i.location = :location)
  2667.                     ORDER BY i.rankAv ASC';
  2668.             $query $em->createQuery($dql)->setParameters($parameters);
  2669.             $productsInFileNull $query->getResult();
  2670.             // Para el location en NULL el SQL tiene que ser diferente por eso el siguiente condicional
  2671.             if ($item == 'null'){
  2672.                 // VIDEO
  2673.                 $parameters = array(
  2674.                     'fileId' => $id,
  2675.                     'type' => 'VĆ­deo',
  2676.                     'location' => '',
  2677.                 );
  2678.                 $dql 'SELECT i
  2679.                         FROM AvexpressBundle:AveProductFile i
  2680.                         WHERE i.fileId = :fileId AND i.type = :type AND (i.location IS NULL OR i.location = :location)
  2681.                         ORDER BY i.rankAv ASC';
  2682.                 $query $em->createQuery($dql)->setParameters($parameters);
  2683.                 $productsInFileVid $query->getResult();
  2684.                 // SONIDO
  2685.                 $parameters = array(
  2686.                     'fileId' => $id,
  2687.                     'type' => 'Sonido',
  2688.                     'location' => '',
  2689.                 );
  2690.                 $dql 'SELECT i
  2691.                         FROM AvexpressBundle:AveProductFile i
  2692.                         WHERE i.fileId = :fileId AND i.type = :type AND (i.location IS NULL OR i.location = :location) 
  2693.                         ORDER BY i.rankAv ASC';
  2694.                 $query $em->createQuery($dql)->setParameters($parameters);
  2695.                 $productsInFileSound $query->getResult();
  2696.                 // ILUMINACION
  2697.                 $parameters = array(
  2698.                     'fileId' => $id,
  2699.                     'type' => 'Iluminación',
  2700.                     'location' => '',
  2701.                 );
  2702.                 $dql 'SELECT i
  2703.                         FROM AvexpressBundle:AveProductFile i
  2704.                         WHERE i.fileId = :fileId AND i.type = :type AND (i.location IS NULL OR i.location = :location)
  2705.                         ORDER BY i.rankAv ASC';
  2706.                 $query $em->createQuery($dql)->setParameters($parameters);
  2707.                 $productsInFileLights $query->getResult();
  2708.                 // OTROS
  2709.                 $parameters = array(
  2710.                     'fileId' => $id,
  2711.                     'typeV' => 'VĆ­deo',
  2712.                     'typeS' => 'Sonido',
  2713.                     'typeI' => 'Iluminación',
  2714.                     'location' => '',
  2715.                 );
  2716.                 $dql 'SELECT i
  2717.                         FROM AvexpressBundle:AveProductFile i
  2718.                         WHERE (i.fileId = :fileId AND i.type != :typeV AND i.type != :typeS AND i.type != :typeI AND (i.location IS NULL OR i.location = :location))
  2719.                         ORDER BY i.rankAv ASC';
  2720.                 $query $em->createQuery($dql)->setParameters($parameters);
  2721.                 $productsInFileOther $query->getResult();
  2722.                 // CASO NULL DEL TIPO (Los casos EMPTY estan considerados en las consultas previas)
  2723.                 $parameters = array(
  2724.                     'fileId' => $id,
  2725.                     'location' => '',
  2726.                 );
  2727.                 $dql 'SELECT i
  2728.                         FROM AvexpressBundle:AveProductFile i
  2729.                         WHERE (i.fileId = :fileId AND i.type IS NULL AND (i.location IS NULL OR i.location = :location))
  2730.                         ORDER BY i.rankAv ASC';
  2731.                 $query $em->createQuery($dql)->setParameters($parameters);
  2732.                 $productsInFileNull $query->getResult();
  2733.             }
  2734.             $items array_merge($items,$productsInFileVid$productsInFileSound$productsInFileLights$productsInFileOther$productsInFileNull);
  2735.         }
  2736.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('4');
  2737.         $client $em->getRepository(Client::class)->findById($file->getClient());
  2738.         if (!empty($client)){
  2739.             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  2740.             $client[0]->setPopulation($city);
  2741.             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  2742.             $client[0]->setRegion($region);
  2743.             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  2744.             $client[0]->setCountry($country);
  2745.         } else {
  2746.             $client[0] = new Client();
  2747.             $client[0]->setName('');
  2748.             $client[0]->setTitle('');
  2749.             $client[0]->setIdDocument('');
  2750.             $client[0]->setPopulation('');
  2751.             $client[0]->setRegion('');
  2752.             $client[0]->setCountry('');
  2753.         }
  2754.         // Acumuladores de los calculos
  2755.         $totales_neto_all 0;
  2756.         $data_iva = array(
  2757.             'iva' => 21,
  2758.             'ivaMontoVeintiUno' => 0,
  2759.             'ivaMontoDiez' => 0,
  2760.             'ivaMontoCero' => 0,
  2761.         );
  2762.         //INICIO: Determinamos el numero de factura o proforma
  2763.         if (substr($number,0,1) == 'I'){
  2764.             // Es una Factura
  2765.             $numberInvoiceOrProforma substr($number,1);
  2766.             $number $numberInvoiceOrProforma;
  2767.             $type 'Invoice';
  2768.         } else {
  2769.             // Es una Proforma
  2770.             $numberInvoiceOrProforma substr($number,1);
  2771.             $number $numberInvoiceOrProforma;
  2772.             $type 'Proforma';
  2773.         }
  2774.         //FIN: Determinamos el numero de factura o proforma
  2775.         // Buscamos las salas reservadas, pagos y servicios para el evento
  2776.         $arrayItems = array();
  2777.         $fileProducts = array();
  2778.         if (!empty($arrayBools['lounge'])) {
  2779.             foreach ($arrayBools['lounge'] as $key => $item) {
  2780.                 if ($item == 'true') {
  2781. //                    $fileProducts[] = $em->getRepository('DevelupBundle:ReservationLoungeSimple')->findOneById($key);
  2782.                 }
  2783.             }
  2784.         }
  2785.         $payments = array();
  2786.         if (!empty($arrayBools['payment'])) {
  2787.             foreach ($arrayBools['payment'] as $key => $item) {
  2788.                 if ($item == 'true') {
  2789. //                    $payments[] = $em->getRepository('DevelupBundle:ReservationPaymentsClient')->findOneById($key);
  2790.                 }
  2791.             }
  2792.         }
  2793.         $services = array();
  2794.         if (!empty($arrayBools['service'])) {
  2795.             foreach ($arrayBools['service'] as $key => $item) {
  2796.                 if ($item == 'true') {
  2797. //                    $services[] = $em->getRepository('DevelupBundle:ReservationService')->findOneById($key);
  2798.                 }
  2799.             }
  2800.         }
  2801.         $data_supplier = array();
  2802.         $i 0;
  2803.         $iva '21';            // Esteban Rincon: "Por Ley de localización del impuesto, siempre serĆ” un 21%"
  2804.         $pax '-';
  2805.         $qty '1';
  2806.         $product = array(
  2807.             'neto' => 0,
  2808.             'sumSubT' => 0,
  2809.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  2810.         $service = array(
  2811.             'neto' => 0,
  2812.             'sumSubT' => 0,
  2813.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  2814.         if (empty($items)){
  2815.             $data_supplier['product'][0] = null;
  2816.         }
  2817.         foreach ($items as $item){
  2818.             $days '1';
  2819.             if (!empty($item->getUnits())){
  2820.                 $qty $item->getUnits();
  2821.             }
  2822.             if (!empty($item->getDays())){
  2823.                 $days $item->getDays();
  2824.             }
  2825.             if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
  2826.                 $subtotal 0;
  2827.                 $neto 0;
  2828.                 $subtotalProduct 0;
  2829.             } else {
  2830. //                $subtotalProduct = $item->getServicePrice() * 1.21;
  2831.                 $subtotalProduct $item->getSubTotalPrice() * 1.21;
  2832. //                $subneto = $item->getServicePrice();
  2833.                 $subneto $item->getSubTotalPrice();
  2834.                 $subtotal =  $subtotalProduct;
  2835.                 $neto =  $subneto;
  2836.                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  2837.                 $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  2838.                 $neto round($neto,2,PHP_ROUND_HALF_UP);
  2839.                 $arrayItems[] = array(
  2840.                     'type' => 'Product',
  2841.                     'name' => $item->getProductName(),
  2842.                     'amount' => $neto,
  2843.                     'iva' => '21',
  2844.                     'total' => $subtotal,
  2845.                 );
  2846.             }
  2847.             // Acumula netos totales e IVA
  2848.             $totales_neto_all $totales_neto_all $neto;
  2849.             switch ($item->getIva()){
  2850.                 case 21$data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto 0.21); break;
  2851.                 case 10$data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto 0.1); break;
  2852.                 case 0$data_iva['ivaMontoCero'] = $data_iva['ivaMontoCero'] + ($neto 0); break;
  2853.                 default:  break;
  2854.             }
  2855.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  2856.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  2857.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  2858.             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
  2859.             // Acumula netos totales e IVA
  2860.             $product['neto'] = $product['neto'] + $neto;
  2861.             $product['sumSubT'] = $product['sumSubT'] + $subtotal;
  2862.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  2863.             $product['neto'] = round($product['neto'],2,PHP_ROUND_HALF_UP);
  2864.             $product['sumSubT'] = round($product['sumSubT'],2,PHP_ROUND_HALF_UP);
  2865.             $data_supplier['product'][$i] = array (
  2866.                 'id' => $item->getId(),
  2867.                 'productName' => $item->getProductName(),
  2868.                 'description' => $item->getDescription(),
  2869.                 'productId' => $item->getProductId(),
  2870.                 'dateStart' => $item->getDateStart(),
  2871.                 'dateEnd' => $item->getDateEnd(),
  2872.                 'servicePrice' => $item->getServicePrice(),
  2873.                 'subTotalPrice' => $item->getSubTotalPrice(),
  2874.                 'subtotalProduct' => $subtotalProduct,
  2875.                 'iva' => $iva,
  2876.                 'pax' => $pax,
  2877.                 'qty' => $qty,
  2878.                 'days' => $days,
  2879.                 'type' => $item->getType(),
  2880.                 'subtotal' => $subtotal,
  2881.             );
  2882.             $i++;
  2883.         }
  2884.         $data_supplier['productSubTotal'] = array(
  2885.             'neto' => $product['neto'],
  2886.             'sumSubT' => $product['sumSubT'],
  2887.         );
  2888.         $payment = array(
  2889.             'sumSubT' => 0,
  2890.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  2891.         $i 0;
  2892.         foreach ($payments as $item){
  2893.             $payment['sumSubT'] = $payment['sumSubT'] + $item->getAmountTotal();
  2894.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  2895.             $payment['sumSubT'] = round($payment['sumSubT'],2,PHP_ROUND_HALF_UP);
  2896.             $data_supplier['payment'][$i] = array (
  2897.                 'id' => $item->getId(),
  2898.                 'amount' => $item->getAmount(),
  2899.                 'amountTotal' => $item->getAmountTotal(),
  2900.                 'vat' => $item->getVat(),
  2901.                 'datePayAt' => $item->getDatePayAt(),
  2902.                 'wayToPay' => $item->getWayToPay(),
  2903.             );
  2904.             $arrayItems[] = array(
  2905.                 'type' => 'Payment',
  2906.                 'name' => $item->getWayToPay(),
  2907.                 'amount' => $item->getAmount(),
  2908.                 'total' => $item->getAmountTotal(),
  2909.                 'iva' => $item->getVat(),
  2910.             );
  2911.             $i++;
  2912.         }
  2913.         if (!empty($payments)) {
  2914.             $data_supplier['paymentSubTotal'] = array(
  2915.                 'sumSubT' => $payment['sumSubT'],
  2916.             );
  2917.         }
  2918.         foreach ($services as $item){
  2919.             if (is_null($item->getPrice()) or empty($item->getPrice())){
  2920.                 $subtotal 0;
  2921.                 $neto 0;
  2922.                 $subtotalService 0;
  2923.             } else {
  2924.                 $subtotalService $item->getPrice();
  2925.                 $subneto $item->getPrice();
  2926.                 // Commission
  2927.                 if ($item->getOpCommission()=='1'){
  2928.                     $subtotalService $subtotalService * (+ ($item->getCommission()/100));
  2929.                     $subneto $subneto  * (+ ($item->getCommission()/100));
  2930.                 } else {
  2931.                     $subtotalService $subtotalService * (- ($item->getCommission()/100));
  2932.                     $subneto $subneto * (- ($item->getCommission()/100));
  2933.                 }
  2934.                 // Over
  2935.                 if ($item->getOpOver()=='1'){
  2936.                     $subtotalService $subtotalService $item->getOver();
  2937.                     $subneto $subneto $item->getOver();
  2938.                 } else {
  2939.                     $subtotalService $subtotalService $item->getOver();
  2940.                     $subneto $subneto $item->getOver();
  2941.                 }
  2942.                 // IVA
  2943.                 if ($item->getOpIva()=='1'){
  2944.                     $subtotalService $subtotalService * (+ ($item->getIva()/100));
  2945.                 } else {
  2946.                     $subtotalService $item->getPrice();
  2947.                     $subneto = ($subneto 100) / (100 $item->getIva());
  2948.                 }
  2949.                 switch ($item->getServiceCatId()){
  2950.                     case 1// Alojamiento
  2951.                         // el numero de noches $numNoches; precio unitario $subneto
  2952.                         $numNoches = (($item->getDateOutAt())->diff($item->getDateInAt()))->days;
  2953.                         // La personas no afectan este calculo
  2954.                         $subtotal $subtotalService $numNoches $item->getUnits();
  2955.                         $subnetoUnit $subneto;
  2956.                         $subneto $subneto $numNoches $item->getUnits();
  2957.                         $data_supplier['service'][$i] = array (
  2958.                             'id' => $item->getId(),
  2959.                             'serviceCatId' => $item->getServiceCatId(),
  2960.                             'serviceName' => $item->getName(),
  2961.                             'serviceType' => 'Hotel',
  2962.                             'date' => ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y'),
  2963.                             'qty' => $item->getUnits(),
  2964.                             'iva' => $item->getIva(),
  2965.                             'pax' => '-',
  2966.                             'precioUnit' => $subnetoUnit,
  2967.                             'subneto' => $subneto,
  2968.                             'subtotal' => $subtotal,
  2969.                         );
  2970.                         break;
  2971.                     case 2//Actividades
  2972.                         // El nĆŗmero de personas es considerado en el calculo
  2973.                         $pax $item->getPax();
  2974.                         if (empty($pax) or $pax == "0") {
  2975.                             $pax 1;
  2976.                         }
  2977.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2978.                         if ($days 1){
  2979.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2980.                         } else {
  2981.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2982.                         }
  2983.                         $subtotal $subtotalService $days $item->getUnits();
  2984.                         $subnetoUnit $subneto;
  2985.                         $subneto $subneto $days $item->getUnits();
  2986.                         $data_supplier['service'][$i] = array (
  2987.                             'id' => $item->getId(),
  2988.                             'serviceCatId' => $item->getServiceCatId(),
  2989.                             'serviceName' => $item->getName(),
  2990.                             'serviceType' => 'Actividad',
  2991.                             'date' => $dateServ,
  2992.                             'qty' => $item->getUnits(),
  2993.                             'iva' => $item->getIva(),
  2994.                             'pax' => $item->getPax(),
  2995.                             'precioUnit' => $subnetoUnit,
  2996.                             'subneto' => $subneto,
  2997.                             'subtotal' => $subtotal,
  2998.                         );
  2999.                         break;
  3000.                     case 3// AV
  3001.                         $pax $item->getPax();
  3002.                         if (empty($pax) or $pax == "0") {
  3003.                             $pax 1;
  3004.                         }
  3005.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  3006.                         if ($days 1){
  3007.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3008.                         } else {
  3009.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3010.                         }
  3011.                         $unitsServ $item->getUnits();
  3012.                         if (empty($unitsServ) or $unitsServ == "0") {
  3013.                             $unitsServ 1;
  3014.                         }
  3015.                         $subtotal $subtotalService $days $unitsServ $pax;
  3016.                         $subnetoUnit $subneto;
  3017.                         $subneto $subneto $days $unitsServ $pax;
  3018.                         $data_supplier['service'][$i] = array (
  3019.                             'id' => $item->getId(),
  3020.                             'serviceCatId' => $item->getServiceCatId(),
  3021.                             'serviceName' => $item->getName(),
  3022.                             'serviceType' => 'AV',
  3023.                             'date' => $dateServ,
  3024.                             'qty' => $unitsServ,
  3025.                             'iva' => $item->getIva(),
  3026.                             'pax' => $item->getPax(),
  3027.                             'precioUnit' => $subnetoUnit,
  3028.                             'subneto' => $subneto,
  3029.                             'subtotal' => $subtotal,
  3030.                         );
  3031.                         break;
  3032.                     case 4//Creative
  3033.                         $pax $item->getPax();
  3034.                         if (empty($pax) or $pax == "0") {
  3035.                             $pax 1;
  3036.                         }
  3037.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  3038.                         if ($days 1){
  3039.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3040.                         } else {
  3041.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3042.                         }
  3043.                         $unitsServ $item->getUnits();
  3044.                         if (empty($unitsServ) or $unitsServ == "0") {
  3045.                             $unitsServ 1;
  3046.                         }
  3047.                         $subtotal $subtotalService $days $unitsServ $pax;
  3048.                         $subnetoUnit $subneto;
  3049.                         $subneto $subneto $days $unitsServ $pax;
  3050.                         $data_supplier['service'][$i] = array (
  3051.                             'id' => $item->getId(),
  3052.                             'serviceCatId' => $item->getServiceCatId(),
  3053.                             'serviceName' => $item->getName(),
  3054.                             'serviceType' => 'Creativo',
  3055.                             'date' => $dateServ,
  3056.                             'qty' => $unitsServ,
  3057.                             'iva' => $item->getIva(),
  3058.                             'pax' => $item->getPax(),
  3059.                             'precioUnit' => $subnetoUnit,
  3060.                             'subneto' => $subneto,
  3061.                             'subtotal' => $subtotal,
  3062.                         );
  3063.                         break;
  3064.                     case 5//Cruise
  3065.                         $pax $item->getPax();
  3066.                         if (empty($pax) or $pax == "0") {
  3067.                             $pax 1;
  3068.                         }
  3069.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days);
  3070.                         if ($days 1){
  3071.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3072.                         } else {
  3073.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3074.                         }
  3075.                         $unitsServ $item->getUnits();
  3076.                         if (empty($unitsServ) or $unitsServ == "0") {
  3077.                             $unitsServ 1;
  3078.                         }
  3079.                         $subtotal $subtotalService $days $unitsServ $pax;
  3080.                         $subnetoUnit $subneto;
  3081.                         $subneto $subneto $days $unitsServ $pax;
  3082.                         $data_supplier['service'][$i] = array (
  3083.                             'id' => $item->getId(),
  3084.                             'serviceCatId' => $item->getServiceCatId(),
  3085.                             'serviceName' => $item->getName(),
  3086.                             'serviceType' => 'Crucero',
  3087.                             'date' => $dateServ,
  3088.                             'qty' => $unitsServ,
  3089.                             'iva' => $item->getIva(),
  3090.                             'pax' => $item->getPax(),
  3091.                             'precioUnit' => $subnetoUnit,
  3092.                             'subneto' => $subneto,
  3093.                             'subtotal' => $subtotal,
  3094.                         );
  3095.                         break;
  3096.                     case 6//Entertaiment
  3097.                         $pax $item->getPax();
  3098.                         if (empty($pax) or $pax == "0") {
  3099.                             $pax 1;
  3100.                         }
  3101.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  3102.                         if ($days 1){
  3103.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3104.                         } else {
  3105.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3106.                         }
  3107.                         $unitsServ $item->getUnits();
  3108.                         if (empty($unitsServ) or $unitsServ == "0") {
  3109.                             $unitsServ 1;
  3110.                         }
  3111.                         $subtotal $subtotalService $days $unitsServ $pax;
  3112.                         $subnetoUnit $subneto;
  3113.                         $subneto $subneto $days $unitsServ $pax;
  3114.                         $data_supplier['service'][$i] = array (
  3115.                             'id' => $item->getId(),
  3116.                             'serviceCatId' => $item->getServiceCatId(),
  3117.                             'serviceName' => $item->getName(),
  3118.                             'serviceType' => 'Entretenimiento',
  3119.                             'date' => $dateServ,
  3120.                             'qty' => $unitsServ,
  3121.                             'iva' => $item->getIva(),
  3122.                             'pax' => $item->getPax(),
  3123.                             'precioUnit' => $subnetoUnit,
  3124.                             'subneto' => $subneto,
  3125.                             'subtotal' => $subtotal,
  3126.                         );
  3127.                         break;
  3128.                     case 7// Gifts
  3129.                         $pax $item->getPax();
  3130.                         if (empty($pax) or $pax == "0") {
  3131.                             $pax 1;
  3132.                         }
  3133. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  3134.                         $days 1;
  3135.                         if ($days 1){
  3136.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3137.                         } else {
  3138.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3139.                         }
  3140.                         $unitsServ $item->getUnits();
  3141.                         if (empty($unitsServ) or $unitsServ == "0") {
  3142.                             $unitsServ 1;
  3143.                         }
  3144.                         $subtotal $subtotalService $days $unitsServ $pax;
  3145.                         $subnetoUnit $subneto;
  3146.                         $subneto $subneto $days $unitsServ $pax;
  3147.                         $data_supplier['service'][$i] = array (
  3148.                             'id' => $item->getId(),
  3149.                             'serviceCatId' => $item->getServiceCatId(),
  3150.                             'serviceName' => $item->getName(),
  3151.                             'serviceType' => 'Regalos',
  3152.                             'date' => $dateServ,
  3153.                             'qty' => $unitsServ,
  3154.                             'iva' => $item->getIva(),
  3155.                             'pax' => $item->getPax(),
  3156.                             'precioUnit' => $subnetoUnit,
  3157.                             'subneto' => $subneto,
  3158.                             'subtotal' => $subtotal,
  3159.                         );
  3160.                         break;
  3161.                     case 8//Guide
  3162.                         $pax $item->getPax();
  3163.                         if (empty($pax) or $pax == "0") {
  3164.                             $pax 1;
  3165.                         }
  3166.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  3167.                         if ($days 1){
  3168.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3169.                         } else {
  3170.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3171.                         }
  3172.                         $unitsServ $item->getUnits();
  3173.                         if (empty($unitsServ) or $unitsServ == "0") {
  3174.                             $unitsServ 1;
  3175.                         }
  3176.                         $subtotal $subtotalService $days $unitsServ $pax;
  3177.                         $subnetoUnit $subneto;
  3178.                         $subneto $subneto $days $unitsServ $pax;
  3179.                         $data_supplier['service'][$i] = array (
  3180.                             'id' => $item->getId(),
  3181.                             'serviceCatId' => $item->getServiceCatId(),
  3182.                             'serviceName' => $item->getName(),
  3183.                             'serviceType' => 'Regalos',
  3184.                             'date' => $dateServ,
  3185.                             'qty' => $unitsServ,
  3186.                             'iva' => $item->getIva(),
  3187.                             'pax' => $item->getPax(),
  3188.                             'precioUnit' => $subnetoUnit,
  3189.                             'subneto' => $subneto,
  3190.                             'subtotal' => $subtotal,
  3191.                         );
  3192.                         break;
  3193.                     case 9//Itineraries
  3194.                         $pax $item->getPax();
  3195.                         if (empty($pax) or $pax == "0") {
  3196.                             $pax 1;
  3197.                         }
  3198.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  3199.                         if ($days 1){
  3200.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3201.                         } else {
  3202.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3203.                         }
  3204.                         $unitsServ $item->getUnits();
  3205.                         if (empty($unitsServ) or $unitsServ == "0") {
  3206.                             $unitsServ 1;
  3207.                         }
  3208.                         $subtotal $subtotalService $days $unitsServ $pax;
  3209.                         $subnetoUnit $subneto;
  3210.                         $subneto $subneto $days $unitsServ $pax;
  3211.                         $data_supplier['service'][$i] = array (
  3212.                             'id' => $item->getId(),
  3213.                             'serviceCatId' => $item->getServiceCatId(),
  3214.                             'serviceName' => $item->getName(),
  3215.                             'serviceType' => 'Itinerarios',
  3216.                             'date' => $dateServ,
  3217.                             'qty' => $unitsServ,
  3218.                             'iva' => $item->getIva(),
  3219.                             'pax' => $item->getPax(),
  3220.                             'precioUnit' => $subnetoUnit,
  3221.                             'subneto' => $subneto,
  3222.                             'subtotal' => $subtotal,
  3223.                         );
  3224.                         break;
  3225.                     case 10//Lounge  -- No Aplica
  3226. //                        $pax = $item->getPax();
  3227. //                        if (empty($pax) or $pax == "0") {
  3228. //                            $pax = 1;
  3229. //                        }
  3230. //
  3231. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  3232. //                        if ($days > 1){
  3233. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3234. //                        } else {
  3235. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3236. //                        }
  3237. //
  3238. //                        $unitsServ = $item->getUnits();
  3239. //                        if (empty($unitsServ) or $unitsServ == "0") {
  3240. //                            $unitsServ = 1;
  3241. //                        }
  3242. //
  3243. //                        $subtotal = $subtotalService * $days * $unitsServ * $pax;
  3244. //                        $subnetoUnit = $subneto;
  3245. //                        $subneto = $subneto * $days * $unitsServ * $pax;
  3246. //
  3247. //                        $data_supplier['service'][$i] = array (
  3248. //                            'id' => $item->getId(),
  3249. //                            'serviceCatId' => $item->getServiceCatId(),
  3250. //                            'serviceName' => $item->getName(),
  3251. //                            'serviceType' => 'Itinerarios',
  3252. //                            'date' => $dateServ,
  3253. //                            'qty' => $unitsServ,
  3254. //                            'iva' => $item->getIva(),
  3255. //                            'pax' => $item->getPax(),
  3256. //                            'precioUnit' => $subnetoUnit,
  3257. //                            'subneto' => $subneto,
  3258. //                            'subtotal' => $subtotal,
  3259. //                        );
  3260.                         break;
  3261.                     case 11//Menu
  3262.                         $pax $item->getPax();
  3263.                         if (empty($pax) or $pax == "0") {
  3264.                             $pax 1;
  3265.                         }
  3266.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  3267.                         if ($days 1){
  3268.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3269.                         } else {
  3270.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3271.                         }
  3272.                         $unitsServ $item->getUnits();
  3273.                         if (empty($unitsServ) or $unitsServ == "0") {
  3274.                             $unitsServ 1;
  3275.                         }
  3276.                         $subtotal $subtotalService $days $unitsServ $pax;
  3277.                         $subnetoUnit $subneto;
  3278.                         $subneto $subneto $days $unitsServ $pax;
  3279.                         $data_supplier['service'][$i] = array (
  3280.                             'id' => $item->getId(),
  3281.                             'serviceCatId' => $item->getServiceCatId(),
  3282.                             'serviceName' => $item->getName(),
  3283.                             'serviceType' => 'MenĆŗ',
  3284.                             'date' => $dateServ,
  3285.                             'qty' => $unitsServ,
  3286.                             'iva' => $item->getIva(),
  3287.                             'pax' => $item->getPax(),
  3288.                             'precioUnit' => $subnetoUnit,
  3289.                             'subneto' => $subneto,
  3290.                             'subtotal' => $subtotal,
  3291.                         );
  3292.                         break;
  3293.                     case 12//Others
  3294.                         $pax $item->getPax();
  3295.                         if (empty($pax) or $pax == "0") {
  3296.                             $pax 1;
  3297.                         }
  3298.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  3299.                         if ($days 1){
  3300.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3301.                         } else {
  3302.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3303.                         }
  3304.                         $unitsServ $item->getUnits();
  3305.                         if (empty($unitsServ) or $unitsServ == "0") {
  3306.                             $unitsServ 1;
  3307.                         }
  3308.                         $subtotal $subtotalService $days $unitsServ $pax;
  3309.                         $subnetoUnit $subneto;
  3310.                         $subneto $subneto $days $unitsServ $pax;
  3311.                         $data_supplier['service'][$i] = array (
  3312.                             'id' => $item->getId(),
  3313.                             'serviceCatId' => $item->getServiceCatId(),
  3314.                             'serviceName' => $item->getName(),
  3315.                             'serviceType' => 'Otros',
  3316.                             'date' => $dateServ,
  3317.                             'qty' => $unitsServ,
  3318.                             'iva' => $item->getIva(),
  3319.                             'pax' => $item->getPax(),
  3320.                             'precioUnit' => $subnetoUnit,
  3321.                             'subneto' => $subneto,
  3322.                             'subtotal' => $subtotal,
  3323.                         );
  3324.                         break;
  3325.                     case 13//Transport
  3326.                         $pax $item->getPax();
  3327.                         if (empty($pax) or $pax == "0") {
  3328.                             $pax 1;
  3329.                         }
  3330.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  3331.                         if ($days 1){
  3332.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3333.                         } else {
  3334.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3335.                         }
  3336.                         $unitsServ $item->getUnits();
  3337.                         if (empty($unitsServ) or $unitsServ == "0") {
  3338.                             $unitsServ 1;
  3339.                         }
  3340.                         $subtotal $subtotalService $days $unitsServ $pax;
  3341.                         $subnetoUnit $subneto;
  3342.                         $subneto $subneto $days $unitsServ $pax;
  3343.                         $data_supplier['service'][$i] = array (
  3344.                             'id' => $item->getId(),
  3345.                             'serviceCatId' => $item->getServiceCatId(),
  3346.                             'serviceName' => $item->getName(),
  3347.                             'serviceType' => 'Transporte',
  3348.                             'date' => $dateServ,
  3349.                             'qty' => $unitsServ,
  3350.                             'iva' => $item->getIva(),
  3351.                             'pax' => $item->getPax(),
  3352.                             'precioUnit' => $subnetoUnit,
  3353.                             'subneto' => $subneto,
  3354.                             'subtotal' => $subtotal,
  3355.                         );
  3356.                         break;
  3357.                     case 14//Technology
  3358.                         $pax $item->getPax();
  3359.                         if (empty($pax) or $pax == "0") {
  3360.                             $pax 1;
  3361.                         }
  3362. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  3363.                         $days 1;
  3364. //                        if ($days > 1){
  3365. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3366. //                        } else {
  3367. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3368. //                        }
  3369.                         $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3370.                         $unitsServ $item->getUnits();
  3371.                         if (empty($unitsServ) or $unitsServ == "0") {
  3372.                             $unitsServ 1;
  3373.                         }
  3374.                         $subtotal $subtotalService $days $unitsServ $pax;
  3375.                         $subnetoUnit $subneto;
  3376.                         $subneto $subneto $days $unitsServ $pax;
  3377.                         $data_supplier['service'][$i] = array (
  3378.                             'id' => $item->getId(),
  3379.                             'serviceCatId' => $item->getServiceCatId(),
  3380.                             'serviceName' => $item->getName(),
  3381.                             'serviceType' => 'TecnologĆ­a',
  3382.                             'date' => $dateServ,
  3383.                             'qty' => $unitsServ,
  3384.                             'iva' => $item->getIva(),
  3385.                             'pax' => $item->getPax(),
  3386.                             'precioUnit' => $subnetoUnit,
  3387.                             'subneto' => $subneto,
  3388.                             'subtotal' => $subtotal,
  3389.                         );
  3390.                         break;
  3391.                     case 15//Assisstant
  3392.                         $pax $item->getPax();
  3393.                         if (empty($pax) or $pax == "0") {
  3394.                             $pax 1;
  3395.                         }
  3396.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  3397.                         if ($days 1){
  3398.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3399.                         } else {
  3400.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3401.                         }
  3402.                         $unitsServ $item->getUnits();
  3403.                         if (empty($unitsServ) or $unitsServ == "0") {
  3404.                             $unitsServ 1;
  3405.                         }
  3406.                         $subtotal $subtotalService $days $unitsServ $pax;
  3407.                         $subnetoUnit $subneto;
  3408.                         $subneto $subneto $days $unitsServ $pax;
  3409.                         $data_supplier['service'][$i] = array (
  3410.                             'id' => $item->getId(),
  3411.                             'serviceCatId' => $item->getServiceCatId(),
  3412.                             'serviceName' => $item->getName(),
  3413.                             'serviceType' => 'Asistente',
  3414.                             'date' => $dateServ,
  3415.                             'qty' => $unitsServ,
  3416.                             'iva' => $item->getIva(),
  3417.                             'pax' => $item->getPax(),
  3418.                             'precioUnit' => $subnetoUnit,
  3419.                             'subneto' => $subneto,
  3420.                             'subtotal' => $subtotal,
  3421.                         );
  3422.                         break;
  3423.                     case 16//DDR
  3424.                         $pax $item->getPax();
  3425.                         if (empty($pax) or $pax == "0") {
  3426.                             $pax 1;
  3427.                         }
  3428.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  3429.                         if ($days 1){
  3430.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  3431.                         } else {
  3432.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  3433.                         }
  3434.                         $unitsServ $item->getUnits();
  3435.                         if (empty($unitsServ) or $unitsServ == "0") {
  3436.                             $unitsServ 1;
  3437.                         }
  3438.                         $subtotal $subtotalService $days $unitsServ $pax;
  3439.                         $subnetoUnit $subneto;
  3440.                         $subneto $subneto $days $unitsServ $pax;
  3441.                         $data_supplier['service'][$i] = array (
  3442.                             'id' => $item->getId(),
  3443.                             'serviceCatId' => $item->getServiceCatId(),
  3444.                             'serviceName' => $item->getName(),
  3445.                             'serviceType' => 'DDR',
  3446.                             'date' => $dateServ,
  3447.                             'qty' => $unitsServ,
  3448.                             'iva' => $item->getIva(),
  3449.                             'pax' => $item->getPax(),
  3450.                             'precioUnit' => $subnetoUnit,
  3451.                             'subneto' => $subneto,
  3452.                             'subtotal' => $subtotal,
  3453.                         );
  3454.                         break;
  3455.                     default:
  3456.                         break;
  3457.                 }
  3458.                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  3459.                 $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  3460.                 $neto round($subneto,2,PHP_ROUND_HALF_UP);
  3461.                 $arrayItems[] = array(
  3462.                     'type' => 'Service',
  3463.                     'name' => $item->getName(),
  3464.                     'amount' => $neto,
  3465.                     'iva' => $item->getIva(),
  3466.                     'total' => $subtotal,
  3467.                 );
  3468.             }
  3469.             switch ($item->getIva()){
  3470.                 // Acumula IVA
  3471.                 case 21:
  3472.                     $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($item->getIva()/100));
  3473.                     break;
  3474.                 case 10:
  3475.                     $data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * ($item->getIva()/100));
  3476.                     break;
  3477.                 case 0:
  3478.                     break;
  3479.                 default:
  3480.                     break;
  3481.             }
  3482.             $totales_neto_all $totales_neto_all $neto;
  3483.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  3484.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  3485.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  3486.             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
  3487.             // Acumula netos totales e IVA
  3488.             $service['neto'] = $service['neto'] + $neto;
  3489.             $service['sumSubT'] = $service['sumSubT'] + $subtotal;
  3490.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  3491.             $service['neto'] = round($service['neto'],2,PHP_ROUND_HALF_UP);
  3492.             $service['sumSubT'] = round($service['sumSubT'],2,PHP_ROUND_HALF_UP);
  3493.             $i++;
  3494.         }
  3495.         $data_supplier['serviceSubTotal'] = array(
  3496.             'neto' => $service['neto'],
  3497.             'sumSubT' => $service['sumSubT'],
  3498.         );
  3499.         $currency '€';
  3500.         $totales_total $totales_neto_all $data_iva['ivaMontoVeintiUno'] + $data_iva['ivaMontoDiez'];
  3501.         if (!empty($payments)) {
  3502.             $amount_pay $data_supplier['paymentSubTotal']['sumSubT'];
  3503.         } else {
  3504.             $amount_pay 0;
  3505.         }
  3506.         $totales_all $totales_total $amount_pay;
  3507.         if ($type == 'Invoice'){
  3508.             $em->clear();   // sin este clear se producia error al guardar
  3509.             $newInvoice $em->getRepository(AveDocInvoice::class)->findOneById($numberInvoiceOrProforma);
  3510.             $newInvoice->setBalance($totales_all);
  3511.             $em->persist($newInvoice);
  3512.             $em->flush();
  3513.         }
  3514.         $data = array(
  3515.             'id' => $id,
  3516.             'type' => $type,
  3517.             'number' => $number,
  3518.             'prefix' => 'AVE-'.(new DateTime('now'))->format('dmy').'-',
  3519.             'date' => new DateTime('now'),
  3520.             'file' => $file,
  3521.             'company' => $company,
  3522.             'clients' => $client,
  3523.             'arrayItems' => $arrayItems,
  3524.             'datasupplier' => $data_supplier,
  3525.             'currency' => $currency,
  3526.             'totales_neto' => $totales_neto_all,
  3527.             'bases_imponibles' => $data_iva,
  3528.             'totales' => $totales_total,
  3529.             'balance' => $totales_all,
  3530.             'paymentInvoice' => $amount_pay,
  3531.         );
  3532.         return $data;
  3533.     }
  3534.     private function sendTelegram($id$text )
  3535.     {
  3536.         $em $this->getDoctrine()->getManager();
  3537.         // No es necesario tener una tabla de TelegramUser para el modulo de AvExpress
  3538.         $telegUser $em->getRepository(MdvTelegramUser::class)->findOneByUserId($id);
  3539.         if (empty($telegUser)){return true;}
  3540.         $parameters = array(
  3541.             'chat_id' => $telegUser->getChatId(),
  3542.             'text' => $text,
  3543.         );
  3544.         $bot_token $telegUser->getBotToken();
  3545.         $url "https://api.telegram.org/bot$bot_token/sendMessage";
  3546.         if (!$curl curl_init()){
  3547.             exit();
  3548.         }
  3549.         curl_setopt($curl,CURLOPT_POST,true);
  3550.         curl_setopt($curl,CURLOPT_POSTFIELDS,$parameters);
  3551.         curl_setopt($curl,CURLOPT_URL,$url);
  3552.         curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
  3553.         $output curl_exec($curl);
  3554.         curl_close($curl);
  3555.         return true;
  3556.     }
  3557.     private function baseBenefits($fileId){
  3558.         $em $this->getDoctrine()->getManager();
  3559. //        $file = $em->getRepository(AveFiles::class)->findOneById($fileId);
  3560.         $productsInFile $em->getRepository(AveProductFile::class)->findByFileId($fileId);
  3561.         $benefitEuro 0;
  3562.         $benefitPerc 0;
  3563.         $totalSale 0;
  3564.         foreach ($productsInFile as $item){
  3565.             if(empty($item->getSupplierExt()) or ($item->getSupplierExt() == 'AV EXPRESS S.L.')){
  3566.                 // El proveedor es AV, el beneficio es 100%
  3567.                 $benefitEuro $benefitEuro $item->getSubTotalPrice();
  3568.             } else {
  3569.                 // El proveedor es externo, el beneficio lo determinan el over y la comision
  3570. //                $subTotalPriceExt = $item->getServicePrice() * $item->getUnits() * $item->getDays();        // Precio sin Over ni Comision
  3571. //                $benefitEuro = $benefitEuro + ($item->getSubTotalPrice() - $subTotalPriceExt);
  3572.                 $prdPrice $item->getServicePrice(); if (empty($prdPrice)){ $prdPrice 0; }
  3573.                 $prdUnits $item->getUnits(); if (empty($prdUnits)){ $prdUnits 1; }
  3574.                 $prdDays $item->getDays(); if (empty($prdDays)){ $prdDays 1; }
  3575.                 $prdPax $item->getPax(); if (empty($prdPax)){ $prdPax 1; }
  3576.                 $subTotalPriceExt $prdPrice $prdUnits $prdDays $prdPax;                             // Precio sin Over ni Comision
  3577.                 $benefitEuro $benefitEuro + ($item->getSubTotalPrice() - $subTotalPriceExt);
  3578.             }
  3579.             $totalSale $totalSale $item->getSubTotalPrice();
  3580.         }
  3581.         // Verificamos beneficios simplificados de proveedores
  3582.         $simplyBen $em->getRepository(AveBenefitsSupplier::class)->findByFileId($fileId);
  3583.         foreach ($simplyBen as $item){ $benefitEuro $benefitEuro $item->getBenefitSupplier(); }
  3584.         if (!($totalSale == 0)){
  3585.             $benefitPerc = ($benefitEuro 100)/$totalSale;
  3586.         }
  3587.         $data = array(
  3588.             'id' => $fileId,
  3589.             'benefitEuro' => $benefitEuro,
  3590.             'benefitPerc' => $benefitPerc,
  3591.         );
  3592.         return $data;
  3593.     }
  3594.     private function precioPorVariacionDeDias ($supplierService$productFile){
  3595.         // El precio unitario debe ser dividido en funcion de los dias que tiene InOut y no en funcion de los dias de Av Express
  3596.         $days = ($supplierService->getDateOutAt()->diff($supplierService->getDateInAt())->days)===$supplierService->getDateOutAt()->diff($supplierService->getDateInAt())->days +1;
  3597.         $newPrice $productFile->getSubTotalPrice() / ( $days );
  3598.         $newPrice $newPrice $supplierService->getUnits();
  3599.         $newPrice round($newPrice,2,PHP_ROUND_HALF_UP);
  3600.         return $newPrice;
  3601.     }
  3602.     private function rankAvParaInOutService($idProduct){
  3603.         // con el ID del product buscamos en "ave_doc_invoice_items" con prdControl($idProduct) para determinar la factura, y buscamos elementos dentro de esa factura
  3604.         // luego si es vacio repetimos para proformas en "ave_doc_proforma_items"
  3605.         // Devuelve el numero de RankAv considerando la posible asociacion por sala y ordenando segun el criterio (video, sonido, iluminacion, otros)
  3606.         $em $this->getDoctrine()->getManager();
  3607.         $rankAv 1$proformaItemsInSameProforma = array(); $boolFound false;
  3608.         $invoiceItem $em->getRepository(AveDocInvoiceItems::class)->findOneByPrdControlId($idProduct);
  3609.         $invoiceItemsInSameInvoice = (!empty($invoiceItem)) ? $em->getRepository(AveDocInvoiceItems::class)->findByInvoiceId($invoiceItem->getInvoiceId()) : array();
  3610.         if (empty($invoiceItemsInSameInvoice)){
  3611.             // No se encontraba facturado, buscamos en proforma el item y los elementos que esten en esa proforma
  3612.             $proformaItem $em->getRepository(AveDocProformaItems::class)->findOneByControlId($idProduct);
  3613.             $proformaItemsInSameProforma = (!empty($proformaItem)) ? $em->getRepository(AveDocProformaItems::class)->findByProformaId($proformaItem->getProformaId()) : array();
  3614.         }
  3615.         $arrayItems = empty($invoiceItemsInSameInvoice) ? $proformaItemsInSameProforma $invoiceItemsInSameInvoice;
  3616.         foreach ($arrayItems as $item){
  3617.             $idToCheck = empty($invoiceItemsInSameInvoice) ? $item->getControlId() : $item->getPrdControlId();
  3618.             if (!($idToCheck == $idProduct)){ if(!($boolFound)){ $rankAv++;} } else { $boolFound true; }
  3619.         }
  3620.         // 001, 002, ... 010, 011, ..., 100, 101
  3621.         $rankAv = ($rankAv 100) ? (($rankAv 10) ? '00'$rankAv '0'$rankAv) : $rankAv;
  3622.         return $rankAv;
  3623.     }
  3624.     private function messageOfChangesToAgent($message$proposalId){
  3625.         // $message mensaje a enviar a los agentes del proposal
  3626.         if ($proposalId  == 0){ return true; }
  3627.         $em $this->getDoctrine()->getManager();
  3628.         $proposal $em->getRepository(Proposal::class)->findOneById($proposalId);
  3629.         /* Obtengo usuario logueado */
  3630.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  3631.         $user_id $user_logueado->getId();
  3632.         $agent $em->getRepository(User::class)->findOneById($user_id);
  3633.         $message 'El proposal <strong>#'.$proposalId.' '.$proposal->getName().'</strong>'.' ha sido modificacdo por el agente: '.$agent->getName().' '.$agent->getLastName().'<br><br><br>'.$message;
  3634.         $proposalAgents $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposalId);
  3635.         $mailArrayTo = array();
  3636.         if (!empty($agent)){ $mailArrayTo[$agent->getEmail()] = $agent->getEmail(); }
  3637.         if (!empty($proposalAgents)){
  3638.             if (!empty($proposalAgents->getAgOne())){
  3639.                 $agent $em->getRepository(User::class)->findOneById($proposalAgents->getAgOne());
  3640.                 $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  3641.             }
  3642.             if (!empty($proposalAgents->getAgTwo())){
  3643.                 $agent $em->getRepository(User::class)->findOneById($proposalAgents->getAgTwo());
  3644.                 $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  3645.             }
  3646.             if (!empty($proposalAgents->getAgThree())){
  3647.                 $agent $em->getRepository(User::class)->findOneById($proposalAgents->getAgThree());
  3648.                 $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  3649.             }
  3650.             if (!empty($proposalAgents->getAgFour())){
  3651.                 $agent $em->getRepository(User::class)->findOneById($proposalAgents->getAgFour());
  3652.                 $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  3653.             }
  3654.         }
  3655.         if (!empty($mailArrayTo)){
  3656.             $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  3657.             $replyTo = array();
  3658.             foreach ($mailArrayTo as $item){ $replyTo[$item] = $item; }
  3659.             $agentMail $agent->getEmail();
  3660.             //Se prepara el correo con los agentes a notificar
  3661.             $firmGmail $agent->getFirmGmail();
  3662.             $data = array(
  3663.                 'body' => $message,
  3664.                 'firm' => $firmGmail,
  3665.             );
  3666.             // EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
  3667.             $transporter = new Swift_SmtpTransport();
  3668.                 $transporter->setHost('smtp.gmail.com')
  3669.                 ->setEncryption('ssl')//ssl / tls
  3670.                 ->setPort(465)// 465 / 587
  3671.                 ->setUsername('desarrollo@develup.solutions')
  3672.                 ->setPassword('utvh hzoi wfdo ztjs');
  3673.             $mailer = new Swift_Mailer($transporter);
  3674.             $message = new Swift_Message();
  3675.                 $message->setSubject('Actualización de servicios AvExpress del proposal: '$proposalId)
  3676.                 ->setSender($agentMail)
  3677.                 ->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
  3678.                 ->setReplyTo($agentMail)
  3679.                 ->setTo($replyTo)
  3680.                 ->setBody(
  3681.                     $this->renderView(
  3682.                         'mail/structure-mail.html.twig',
  3683.                         array('data' => $data)
  3684.                     ),
  3685.                     'text/html'
  3686.                 );
  3687.             $mailer->send($message);
  3688.         }
  3689.         return true;
  3690.     }
  3691. };