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

Open in your IDE?
  1. <?php
  2. namespace App\MDS\AvexpressBundle\Controller;
  3. use App\Constants\BusinessTypeSettingsCompanyConstants;
  4. use App\Entity\Cities;
  5. use App\Entity\Client;
  6. use App\Entity\Configuration;
  7. use App\Entity\Country;
  8. use App\Entity\Destination;
  9. use App\Entity\Regions;
  10. use App\Entity\SettingsCompany;
  11. use App\Entity\User;
  12. use App\Entity\HtFile;
  13. use App\MDS\AvexpressBundle\Entity\AveBenefitsSupplier;
  14. use App\MDS\AvexpressBundle\Entity\AveBriefings;
  15. use App\MDS\AvexpressBundle\Entity\AveBudgetPending;
  16. use App\MDS\AvexpressBundle\Service\AvexpressCalculatorService;
  17. use App\MDS\VenuesBundle\Entity\Reservation;
  18. use App\MDS\VenuesBundle\Entity\ReservationLoungeSimple;
  19. use Doctrine\ORM\EntityManagerInterface;
  20. use Symfony\Component\Routing\Annotation\Route;
  21. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  22. use Symfony\Component\HttpFoundation\Request;
  23. use DateTime;
  24. use App\MDS\AvexpressBundle\Entity\AveFiles;
  25. use App\MDS\AvexpressBundle\Entity\AveBudgetToProforma;
  26. use App\MDS\AvexpressBundle\Entity\AveDocInvoice;
  27. use App\MDS\AvexpressBundle\Entity\AveDocInvoiceItems;
  28. use App\MDS\AvexpressBundle\Entity\AveDocInvoiceRec;
  29. use App\MDS\AvexpressBundle\Entity\AveDocInvoiceRecItems;
  30. use App\MDS\AvexpressBundle\Entity\AveDocProforma;
  31. use App\MDS\AvexpressBundle\Entity\AveDocProformaItems;
  32. use App\MDS\AvexpressBundle\Entity\AvePaymentsClient;
  33. use App\MDS\AvexpressBundle\Entity\AveProduct;
  34. use App\MDS\AvexpressBundle\Entity\AveProductFile;
  35. use App\MDS\AvexpressBundle\Entity\AveServices;
  36. use App\MDS\EventsBundle\Entity\Proposal;
  37. use App\MDS\EventsBundle\Entity\ProposalAgents;
  38. use App\MDS\EventsBundle\Entity\ProposalInvoice;
  39. use App\MDS\EventsBundle\Entity\ProposalSupplierControl;
  40. use App\MDS\EventsBundle\Entity\ProposalSupplierServices;
  41. use App\MDS\AvexpressBundle\Repository\AveProductFileRepository;
  42. use Swift_Mailer;
  43. use Swift_Message;
  44. use Swift_SmtpTransport;
  45. use Symfony\Contracts\Translation\TranslatorInterface;
  46. class FilesController extends AbstractController
  47. {
  48.     private $translator;
  49.     public function __construct(TranslatorInterface $translator) {
  50.         $this->translator $translator;
  51.     }
  52.     
  53.     /**
  54.      * @Route("/fileadd/",  name="ave_add_file")
  55.      * Agregar un expediente
  56.      */
  57.     public function addFileActionRequest $request)
  58.     {
  59.         $em $this->getDoctrine()->getManager();
  60.         $clients $em->getRepository(Client::class)->findAll();
  61.         $destinations $em->getRepository(Destination::class)->findAll();
  62.         $aveFiles $em->getRepository(AveFiles::class)->findAll();
  63.         $id =0;
  64.         if (empty($aveFiles)){
  65.             $id ++;
  66.         } else {
  67.             $lastElem end($aveFiles);
  68.             $id $lastElem->getId() + 1;
  69.         }
  70.         return $this->render('MDS/AvexpressBundle/Avexpress/add-files.html.twig',
  71.             array(
  72.                 'id' => $id,
  73.                 'clients' => $clients,
  74.                 'destinations' => $destinations,
  75.                 'clientId' => 0,
  76.             ));
  77.     }
  78.     /**
  79.      * @Route("/filelist/",  name="ave_list_file")
  80.      * Listar expedientes
  81.      */
  82.     public function listFileAction(Request $requestEntityManagerInterface $em)
  83.     {
  84.         $reservasRaw $em->getRepository(AveFiles::class)->findAllOptimizedForList();
  85.         $reservas = [];
  86.         foreach ($reservasRaw as $res) {
  87.             $ref '';
  88.             if ($res['dateStart'] instanceof \DateTimeInterface && $res['dateEnd'] instanceof \DateTimeInterface) {
  89.                 $ref '#' $res['dateStart']->format('ymd') . $res['dateEnd']->format('ymd');
  90.             } else {
  91.                 $ref '#000000000000';
  92.             }
  93.             $reservas[] = [
  94.                 'id'            => $res['id'],
  95.                 'title'         => $res['title'],
  96.                 'client'        => $res['clientName'] ?? 'N/A',
  97.                 'dateStart'     => $res['dateStart'],
  98.                 'dateEnd'       => $res['dateEnd'],
  99.                 'createdId'     => $res['createdId'],
  100.                 'ref'           => $ref,
  101.                 'reservation'   => $res['reservation_id'],
  102.             ];
  103.         }
  104.         return $this->render('MDS/AvexpressBundle/Avexpress/list-files.html.twig', [
  105.             'listofdeletedfiles' => false,
  106.             'reservations'       => $reservas
  107.         ]);
  108.     }
  109.     /**
  110.      * @Route("/filesave/",  name="ave_save_file")
  111.      * Guardar un expediente nuevo
  112.      */
  113.     public function saveFileActionRequest $request)
  114.     {
  115.         $em $this->getDoctrine()->getManager();
  116.         $newRequest $request->request->get('avexpress');
  117.         if (empty($newRequest['title'])){ return $this->redirectToRoute('ave_add_file'); }
  118.         /* Obtengo usuario logueado */
  119.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  120.         $user_id $user_logueado->getId();
  121.         $newFile = new AveFiles();
  122.         $newFile->setTitle($newRequest['title']);
  123.         $newFile->setClient($newRequest['client']);
  124.         if (!empty($newRequest['idProposal'])){
  125.             $newFile->setIdProposal($newRequest['idProposal']);
  126.         } else {
  127.             $newFile->setIdProposal(null);
  128.         }
  129.         $newFile->setStatus($newRequest['status']);
  130.         $newFile->setAdvancePayment($newRequest['advancePayment']);
  131.         $newFile->setDescription($newRequest['description']);
  132.         if (empty($newRequest['dateStart'])){
  133.             $newFile->setDateStart(new \DateTime("now"));
  134.         } else {
  135.             $newFile->setDateStart(new \DateTime($newRequest['dateStart']));}
  136.         if (empty($newRequest['dateEnd'])){
  137.             $newFile->setDateEnd(new \DateTime("now"));
  138.         } else {
  139.             $newFile->setDateEnd(new \DateTime($newRequest['dateEnd']));}
  140.         if (!empty($newRequest['destination'])){
  141.             $newFile->setDestinoId($newRequest['destination']);
  142.         }
  143.         $newFile->setCreatedId($user_id);
  144.         $newFile->setUpdatedId($user_id);
  145.         $newFile->setCreatedAt(new \DateTime("now"));
  146.         $newFile->setUpdatedAt(new \DateTime("now"));
  147.         $em->persist($newFile);
  148.         $em->flush();
  149.         $sumatoriaTotalNet 0;
  150.         $sumatoriaTotalVat 0;
  151.         $sumatoriaTotal 0;
  152.         $resultados = array(
  153.             'totalNeto' => $sumatoriaTotalNet,
  154.             'vat' => $sumatoriaTotalVat,
  155.             'total' => $sumatoriaTotal,
  156.         );
  157.         $productInFile $em->getRepository(AveProductFile::class)->findByFileId($newFile->getId());
  158.         $numeroItems sizeof($productInFile);
  159.         return $this->redirectToRoute('ave_edit_file', array( 'id' => $newFile->getId() ));
  160.     }
  161.     /**
  162.      * @Route("/fileupdate/{id}",  name="ave_update_file")
  163.      * Actualizar un expediente
  164.      */
  165.     public function updateFileAction($idRequest $request)
  166.     {
  167.         $logTelegram false;
  168.         $numberToPrefix 0;
  169.         $em $this->getDoctrine()->getManager();
  170.         $newFile $em->getRepository(AveFiles::class)->findOneById($id);
  171.         $newRequest $request->request->get('avexpress');
  172.         $srvInconsistentes '';                    // Mensaje de alerta por inconsistencia en los servicios
  173.         // INICIO: Si existe un documento creado no se puede cambiar el cliente
  174.         $oldDoc $em->getRepository(AveDocInvoice::class)->findOneByFileId($id);
  175.         $noexistefactura = empty($oldDoc);
  176.         // FIN: Si existe un documento creado no se puede cambiar el cliente
  177.         /* Obtengo usuario logueado */
  178.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  179.         $user_id $user_logueado->getId();
  180.         if (!empty($newRequest['title'])){$newFile->setTitle($newRequest['title']);}
  181.         if ($noexistefactura)
  182.             {
  183.                 $newFile->setClient($newRequest['client']);
  184.                 $msjErrorClt '';
  185.             }
  186.         else
  187.             { /* Hay una factura, no se debe cambiar el cliente */
  188.                 // Verificamos si intenta cambiar el cliente para informar que no es posible hacerlo
  189.                 if (!($newFile->getClient() == $newRequest['client'])){
  190.                     $msjErrorClt 'El cliente no puede ser modificado, ya existe una factura previa';
  191.                 } else {
  192.                     $msjErrorClt '';
  193.                 }
  194.             }
  195.         if (!empty($newRequest['idProposal'])){$newFile->setIdProposal($newRequest['idProposal']);} else {$newFile->setIdProposal(null);}
  196.         $newFile->setStatus($newRequest['status']);
  197.         $newFile->setDescription($newRequest['description']);
  198.         $newFile->setUpdatedId($user_id);
  199.         $newFile->setUpdatedAt(new \DateTime("now"));
  200.         if (!empty($newRequest['destination'])){$newFile->setDestinoId($newRequest['destination']);}
  201.         if (!empty($newRequest['dateStart'])){$newFile->setDateStart(new DateTime($newRequest['dateStart']));}
  202.         if (!empty($newRequest['dateEnd'])){$newFile->setDateEnd(new DateTime($newRequest['dateEnd']));}
  203.         if (!empty($newRequest['xtraFieldOne'])){$newFile->setXtraFieldOne($newRequest['xtraFieldOne']);}
  204.         try{
  205.             $em->persist($newFile);
  206.             $em->flush();
  207.             $event 'El expediente ha sido actualizado. ';
  208.             if (!empty($msjErrorClt)){ $event $event.$msjErrorClt; }
  209.             $successMessage $this->translator->trans($event);
  210.             $this->addFlash('mensajeav'$successMessage);
  211.         } catch (\Exception $e){
  212.             $event 'An error occurred: '.$e->getMessage();
  213.             /* Para el usuario */
  214.             $errorMessage $this->translator->trans($event);
  215.             $this->addFlash('mensajeaverror'$errorMessage);
  216.         }
  217.         $productInFile $em->getRepository(AveProductFile::class)->findByFileId($newFile->getId());
  218.         $txtWarning '';
  219.         if(!empty($newFile->getIdProposal())){
  220.             // El expediente se ha relacionado con un proposal, se debe actualizar en eventos
  221.             $file $newFile;
  222.             // Si hay proposal se debe actualizar en el expediente de Eventos
  223.             if (!empty($file->getIdProposal()) and is_numeric($file->getIdProposal())){
  224.                 // Buscamos el destino donde se encuentre Avexpress y ahi agregamos el servicio, si no se encuentra no se agregara el servicio
  225.                 $control $em->getRepository(ProposalSupplierControl::class)->findOneBy(
  226.                     array(
  227.                         'supplierId' => 80,                                          // El supplier 80 es Avexpress
  228.                         'proposalId' => $file->getIdProposal(),
  229.                     )
  230.                 );
  231.                 // INICIO: Buscamos la info del lado de eventos (SINCRONIZACION)
  232.                 $txtOfChanges ''//Mensaje para el agente de cambios en los servicios hechos desde AvExpress
  233.                 $proposal $em->getRepository(Proposal::class)->findOneById($file->getIdProposal());
  234.                 $agent $em->getRepository(User::class)->findOneById($proposal->getAgentId());
  235.                 $agentFullName $agent->getName().' '.$agent->getLastName();
  236.                 $proposalTitle $proposal->getId().' - '.$proposal->getTitle();
  237.                 // FIN: Buscamos la info del lado de eventos
  238.                 foreach ($productInFile as $item){
  239.                     //Si las fechas de inicio y fin no coinciden con el campo dias se debe enviar alerta
  240.                     $txtWarning = ($item->getDateOutAt()->diff($item->getDateInAt()))->days <> $item->getDays() ? '<br>'.$item->getProductName() : '';
  241.                     if (!empty($txtWarning)){
  242.                         if (empty($srvInconsistentes)){ $srvInconsistentes 'Hay inconsistencias en: '.'<br>'.$txtWarning; } else { $srvInconsistentes $srvInconsistentes.'<br>'.$txtWarning; }
  243.                     }
  244.                     if (!empty($control)){
  245.                         // Existe un destino con AvExpress como proveedor, ahĆ­ se agregara el servicio
  246.                         $yaexistiaunservicio false$proposalServicex null;
  247.                         // Se verifica que no el productfile Av no tenga imagen en Eventos
  248.                         if (!empty($item->getOriginId())){
  249.                             // Se verifica que aun exista en Eventos  el servicio
  250.                             $proposalServicex $em->getRepository(ProposalSupplierServices::class)->findOneById($item->getOriginId());
  251.                             if (!empty($proposalServicex)){ $yaexistiaunservicio true; } else { $yaexistiaunservicio false; }
  252.                         } else {
  253.                             // no estaba relacionado con nada en eventos, se crea uno nuevo
  254.                             $yaexistiaunservicio false;
  255.                         }
  256.                         if ($yaexistiaunservicio){
  257.                             $prpInv $em->getRepository(ProposalInvoice::class)->findOneByProposalId($file->getIdProposal());
  258.                             if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
  259.                                 $service $proposalServicex;
  260.                                 $oldServiceEvent = array(
  261.                                     'activityId' => $service->getActivityId(),
  262.                                     'assistantId' => $service->getAssistantId(),
  263.                                     'breakdown' => $service->getBreakdown(),
  264.                                     'commission' => $service->getCommission(),
  265.                                     'controlId' => $service->getControlId(),
  266.                                     'currency' => $service->getCurrency(),
  267.                                     'dateBlockLimit' => $service->getDateBlockLimit(),
  268.                                     'dateInAt' => $service->getDateInAt(),
  269.                                     'dateOutAt' => $service->getDateOutAt(),
  270.                                     'destinationId' => $service->getDestinationId(),
  271.                                     'directPayment' => $service->getDirectPayment(),
  272.                                     'hour' => $service->getHour(),
  273.                                     'ideaId' => $service->getIdeaId(),
  274.                                     'isFather' => $service->getIsFather(),
  275.                                     'iva' => $service->getIva(),
  276.                                     'name' => $service->getName(),
  277.                                     'opCommission' => $service->getOpCommission(),
  278.                                     'opIva' => $service->getOpIva(),
  279.                                     'opOver' => $service->getOpOver(),
  280.                                     'originalIva' => $service->getOriginalIva(),
  281.                                     'originalPrice' => $service->getOriginalPrice(),
  282.                                     'originalopIva' => $service->getOriginalopIva(),
  283.                                     'over' => $service->getOver(),
  284.                                     'pax' => $service->getPax(),
  285.                                     'preCommission' => $service->getPreCommission(),
  286.                                     'preIva' => $service->getPreIva(),
  287.                                     'price' => $service->getPrice(),
  288.                                     'proposalId' => $service->getProposalId(),
  289.                                     'rankquote' => $service->getRankQuote(),
  290.                                     'serviceCatId' => $service->getServiceCatId(),
  291.                                     'serviceCatName' => $service->getServiceCatName(),
  292.                                     'serviceId' => $service->getServiceId(),
  293.                                     'serviceIdFather' => $service->getServiceIdFather(),
  294.                                     'status' => $service->getStatus(),
  295.                                     'statusRec' => $service->getStatusRec(),
  296.                                     'statusinternal' => $service->getStatusinternal(),
  297.                                     'supplierId' => $service->getSupplierId(),
  298.                                     'units' => $service->getUnits(),
  299.                                 );
  300.                                 $service->setName($item->getProductName());
  301.                                 // Se verifican los precios en ambas partes (AV Express e InOut)
  302.                                 if (!($service->getPrice() == $item->getServicePrice())) {
  303.                                     // Si ambos precios unitarios son distintos se ha modificado el numero de dĆ­as en Av Express
  304.                                     $newPriceInOut $this->precioPorVariacionDeDias($service$item);
  305.                                     $service->setPrice($newPriceInOut);
  306.                                 } else {
  307.                                     // si son iguales tambien se deben verificar el numero de dias
  308.                                     if (!(($service->getDateOutAt()->diff($service->getDateInAt())->days 1) == $item->getDays())) {
  309.                                         $newPriceInOut $this->precioPorVariacionDeDias($service$item);
  310.                                         $service->setPrice($newPriceInOut);
  311.                                     }
  312.                                 }
  313.                                 $service->setCurrency($item->getCurrency());
  314.                                 $service->setUnits($item->getUnits());
  315. //                            $service->setCommission(0);                                       // InOut puede haber metido una Comision y no se le debe modificar
  316. //                            $service->setOver(0);                                             // InOut puede haber metido un Over y no se le debe modificar
  317.                                 $service->setIva(21);
  318.                                 if (empty($item->getPax())) {
  319.                                     $service->setPax(1);
  320.                                 } else {
  321.                                     $service->setPax($item->getPax());
  322.                                 }
  323.                                 $service->setHour(null);
  324.                                 $service->setDateInAt($item->getDateInAt());
  325.                                 $service->setDateOutAt($item->getDateOutAt());
  326.                                 $service->setDirectPayment(0);
  327. //                            $service->setStatus('Pending');                                   // InOut puede haber Confirmado y no se le debe modificar
  328.                                 $service->setStatusinternal('Additional');
  329.                                 $service->setPreCommission(null);
  330.                                 $service->setPreIva(null);
  331.                                 $service->setDateBlockLimit(null);
  332. //                            $service->setOpCommission(1);                                     // InOut puede haber metido una Op Comision y no se le debe modificar
  333. //                            $service->setOpOver(1);                                           // InOut puede haber metido una Op Over y no se le debe modificar
  334. //                            $service->setOpIva(1);                                            // InOut puede haber metido una Op Iva y no se le debe modificar
  335.                                 $service->setBreakdown(0);
  336.                                 $service->setIsFather(0);
  337.                                 $service->setRankQuote($this->rankquoteAvParaInOutService($item->getId()));
  338.                                 $service->setOriginalopIva(1);
  339.                                 $service->setStatusRec('normal');
  340.                                 $service->setCreatedId($user_id);
  341.                                 $service->setUpdatedId($user_id);
  342.                                 $em->persist($service);
  343.                                 $em->flush();
  344.                                 // Se debe notificar por Telegram al agente de eventos
  345.                                 $logTelegram true;
  346.                                 //Verificamos cambios e informamos al agente del proposal
  347.                                 $boolChanges false;
  348.                                 if (!($service->getRankQuote() == $oldServiceEvent['rankquote'])){ 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['rankquote'].', su nuevo valor es: '.$service->getRankQuote().'<br>'$boolChanges true; }
  349.                                 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; }
  350.                                 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; }
  351.                                 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; }
  352.                                 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; }
  353.                                 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; }
  354.                                 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; }
  355.                                 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; }
  356.                                 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; }
  357.                                 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; }
  358.                                 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; }
  359.                                 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; }
  360.                                 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; }
  361.                                 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; }
  362.                                 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; }
  363.                                 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; }
  364.                             } else {
  365.                                 $srvAlreadyInvoiced 'Error al sincronizar. <br><br> InOut ya ha facturado.';
  366.                                 $this->addFlash('mensajeaverror'$srvAlreadyInvoiced);
  367.                             }
  368.                         } else{
  369.                             $prpInv $em->getRepository(ProposalInvoice::class)->findOneByProposalId($file->getIdProposal());
  370.                             if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
  371.                                 $service = new ProposalSupplierServices();
  372.                                 $service->setServiceIdFather(0);
  373.                                 $service->setControlId($control->getId());
  374.                                 $service->setProposalId($file->getIdProposal());
  375.                                 $service->setDestinationId($control->getDestinoId());
  376.                                 $service->setSupplierId(80);                                    // 80 es AvExpress
  377.                                 $service->setIdeaId(null);
  378.                                 $service->setServiceId($item->getProductId());
  379.                                 $service->setServiceCatName('Av');
  380.                                 $service->setServiceCatId(3);
  381.                                 $service->setName($item->getProductName());
  382.                                 $priceInOut $item->getSubTotalPrice();
  383.                                 if (!($item->getPax() == 0)) {
  384.                                     $priceInOut $priceInOut $item->getPax();                    // Se devuelve el calculo dividiendo entre personas
  385.                                 }
  386.                                 if (!($item->getUnits() == 0)) {
  387.                                     $priceInOut $priceInOut $item->getUnits();                  // Se devuelve el calculo dividiendo entre cantidades
  388.                                 }
  389.                                 if (!($item->getDays() == 0)) {
  390.                                     $priceInOut $priceInOut round($item->getDays());            // Se devuelve el calculo dividiendo entre dias, se redondea por si es 1.5
  391.                                 }
  392.                                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  393.                                 $priceInOut round($priceInOut2PHP_ROUND_HALF_UP);
  394.                                 $service->setPrice($priceInOut);
  395.                                 $service->setCurrency($item->getCurrency());
  396.                                 $service->setUnits($item->getUnits());
  397.                                 $service->setCommission(0);
  398.                                 $service->setOver(0);
  399.                                 $service->setIva(21);
  400.                                 if (empty($item->getPax())) { $service->setPax(1); } else { $service->setPax($item->getPax()); }
  401.                                 $service->setHour(null);
  402.                                 $service->setDateInAt($item->getDateInAt());
  403.                                 $service->setDateOutAt($item->getDateOutAt());
  404.                                 $service->setDirectPayment(0);
  405.                                 $service->setStatus('Pending');
  406.                                 $service->setStatusinternal('Additional');
  407.                                 $service->setPreCommission(null);
  408.                                 $service->setPreIva(null);
  409.                                 $service->setDateBlockLimit(null);
  410.                                 $service->setOpCommission(1);
  411.                                 $service->setOpOver(1);
  412.                                 $service->setOpIva(1);
  413.                                 $service->setBreakdown(0);
  414.                                 $service->setIsFather(0);
  415.                                 $service->setRankQuote($this->rankquoteAvParaInOutService($item->getId()));
  416.                                 $service->setOriginalopIva(1);
  417.                                 $service->setOriginalIva(null);
  418.                                 $service->setOriginalPrice(null);
  419.                                 $service->setStatusRec('normal');
  420.                                 $service->setAssistantId(null);
  421.                                 $service->setCreatedId($user_id);
  422.                                 $service->setUpdatedId($user_id);
  423.                                 $service->setCreatedAt(new \DateTime("now"));
  424.                                 $service->setUpdatedAt(new \DateTime("now"));
  425.                                 $em->persist($service);
  426.                                 $em->flush();
  427.                                 // Se relaciona el nuevo Servicio InOut con el Servicio AV
  428.                                 $item->setOriginId($service->getId());
  429.                                 $em->persist($item);
  430.                                 $em->flush();
  431.                                 // Se debe notificar por Telegram al agente de eventos
  432.                                 $logTelegram true;
  433.                             } else {
  434.                                 $srvAlreadyInvoiced 'Error al sincronizar. <br><br> InOut ya ha facturado.';
  435.                                 $this->addFlash('mensajeaverror'$srvAlreadyInvoiced);
  436.                             }
  437.                         }
  438.                     }
  439.                     // Notificamos al agente de InOut si se hicieron actualizaciones en los servicios desde AvExpress
  440.                     if (!empty($txtOfChanges)) { $this->messageOfChangesToAgent($txtOfChanges$proposal->getId()); }
  441.                     //INICIO: Creamos una orden de hacer proforma
  442.                     //INICIO: Calculamos el ID de la proforma
  443.                     $numberToPrefix $em->getRepository(AveDocProforma::class)->findAll();
  444.                     if (empty($numberToPrefix)){
  445.                         $numberToPrefix 0;
  446.                     } else {
  447.                         $numberToPrefix end($numberToPrefix)->getId();
  448.                     }
  449.                     $numberToPrefix++;
  450.                     //FIN: Calculamos el ID de la proforma
  451.                     $order = new AveBudgetToProforma();
  452.                     $order->setStatus('Pending');
  453.                     $order->setFileId($file->getId());
  454.                     $order->setProductFileId($item->getId());
  455.                     $order->setUserConfirmedId($proposal->getAgentId());
  456.                     $order->setUserConfirmedFullName($agentFullName);
  457.                     $order->setProposalTitle($proposalTitle);
  458.                     $order->setProformaId($numberToPrefix);
  459.                     $em->persist($order);
  460.                     $em->flush();
  461.                     //FIN: Creamos una orden de hacer proforma
  462.                 }
  463.                 $event 'Expediente guardado correctamente.';
  464.                 $successMessage $this->translator->trans($event);
  465.                 $this->addFlash('mensajeav'$successMessage);
  466.                 if (!empty($srvInconsistentes) and !empty($newFile->getIdProposal())){ $this->addFlash('mensajeaverror'$srvInconsistentes); }
  467.                 //INICIO: Notificamos al agente por Telegram
  468.                 if ($logTelegram){
  469.                     //Buscamos todos los agentes del proposal
  470.                     $proposalAgents $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposal->getId());
  471.                     //Buscamos el Destino
  472.                     $proposalDestino $em->getRepository(Destination::class)->findOneById($control->getDestinoId());
  473.                     //Buscamos el agente de Avexpress
  474.                     $userData $em->getRepository(User::class)->findOneById($user_id);
  475.                     if (!empty($proposalAgents) and !($user_id == 22)){
  476.                         if ((!empty($proposalAgents->getAgOne())) and (!($proposalAgents->getAgOne() == 0))){
  477.                             $this->sendTelegram($proposalAgents->getAgOne(),'1. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$proposal->getId().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  478.                         }
  479.                         if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
  480.                             $this->sendTelegram($proposalAgents->getAgTwo(),'2. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$proposal->getId().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  481.                         }
  482.                         if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
  483.                             $this->sendTelegram($proposalAgents->getAgThree(),'3. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$proposal->getId().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  484.                         }
  485.                         if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
  486.                             $this->sendTelegram($proposalAgents->getAgFour(),'4. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$proposal->getId().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  487.                         }
  488.                     }
  489.                 }
  490.                 //FIN: Notificamos al agente por Telegram
  491.                 //INICIO: Creamos el presupuesto (proforma)
  492.                 $budToPro $em->getRepository(AveBudgetToProforma::class)->findByProformaId($numberToPrefix);
  493.                 //INICIO: Se agrupan por expediente (fileId)
  494.                 $proformas = [];
  495.                 foreach ($budToPro as $item){
  496.                     $proformas[$item->getFileId()][] = $item;
  497.                 }
  498.                 //FIN: Se agrupan por expediente (fileId)
  499.                 if (!empty($budToPro)){
  500.                     foreach ($proformas as $key => $elemento){
  501.                         //INICIO: Creamos las proformas
  502.                         $newProforma = new AveDocProforma();
  503.                         $newProforma->setPrefix('AVE-' . (new DateTime('now'))->format('dmy') . '-' $numberToPrefix '-' $key);
  504.                         $newProforma->setDateAt(new DateTime('now'));
  505.                         $newProforma->setFileId($key);
  506.                         $newProforma->setCreatedId($user_id);
  507.                         $newProforma->setUpdatedId($user_id);
  508.                         $newProforma->setCreatedAt(new DateTime('now'));
  509.                         $newProforma->setUpdatedAt(new DateTime('now'));
  510. //                        $em->persist($newProforma);
  511.                         $em->flush();
  512.                         //FIN: Creamos las proformas
  513.                         foreach ($elemento as $item) {
  514.                             //$key es el id del expediente
  515.                             // $arrayIdPro['X'] = 'Y'; al agente 'Y' se le informa del presupuesto 'X'
  516.                             //INICIO: Creamos los elemento que iran dentro de las proformas
  517.                             $itemProforma = new AveDocProformaItems();
  518.                             $itemProforma->setType('PRODUCT');
  519.                             $itemProforma->setFileId($key);
  520.                             $itemProforma->setProformaId($newProforma->getId());
  521.                             $itemProforma->setControlId($item->getProductFileId());
  522. //                            $em->persist($itemProforma);
  523.                             $em->flush();
  524.                             //INICIO: Confirmamos el BudToProforma
  525. //                            $item->setStatus('Tosend');              // El elemento se ha pasado a la proforma, solo falta enviar
  526.                             $item->setProformaId($newProforma->getId());
  527. //                            $em->persist($item);
  528.                             $em->flush();
  529.                             //FIN: Confirmamos el BudToProforma
  530.                             //FIN: Creamos los elemento que iran dentro de las proformas
  531.                         }
  532.                     }
  533.                 }
  534.                 //FIN: Creamos el presupuesto (proforma)
  535.                 // INICIO: Se envia al agente el presupuesto
  536.                 $budToPro $em->getRepository(AveBudgetToProforma::class)->findByStatus('Tosend');
  537.                 /* Obtengo usuario logueado */
  538.                 $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  539.                 $user_id $user_logueado->getId();
  540.                 $arrayIdPro = [];          // $arrayIdPro['X'] = 'Y'; al agente 'Y' se le informa del presupuesto 'X'
  541.                 //INICIO: Se agrupan por expediente (fileId)
  542.                 $proformas = [];
  543.                 foreach ($budToPro as $item){
  544.                     $proformas[$item->getFileId()][] = $item;
  545.                 }
  546.                 //FIN: Se agrupan por expediente (fileId)
  547.                 if (!empty($budToPro)){
  548.                     foreach ($proformas as $key => $elemento){
  549.                         //INICIO: Creamos las proformas
  550.                         foreach ($elemento as $item) {
  551.                             //$key es el id del expediente
  552.                             if (!empty($item->getProformaId())) {
  553.                                 $arrayIdPro[$item->getProformaId()] = $item->getUserConfirmedId();             // $arrayIdPro['X'] = 'Y'; al agente 'Y' se le informa del presupuesto 'X'
  554.                             }
  555.                             //INICIO: Confirmamos el BudToProforma
  556.                             $item->setStatus('Confirmed');              // El elemento se ha pasado a confirmado porque se enviara por correo
  557.                             $em->persist($item);
  558.                             $em->flush();
  559.                             //FIN: Confirmamos el BudToProforma
  560.                             //FIN: Creamos los elemento que iran dentro de las proformas
  561.                         }
  562.                     }
  563.                 }
  564.                 //INICIO: Notificamos de todos los presupuestos (proformas) que se han creado
  565.                 foreach ($arrayIdPro as $key => $item){
  566.                     //Buscamos la info del proposal
  567.                     $xprof $em->getRepository(AveDocProforma::class)->findOneById($key);
  568.                     if (!empty($xprof)){
  569.                         $xfile $em->getRepository(AveFiles::class)->findOneById($xprof->getFileId());
  570.                         $xprop $em->getRepository(Proposal::class)->findOneById($xfile->getIdProposal());
  571.                         $xcli $em->getRepository(Client::class)->findOneById($xprop->getClientId());
  572.                         $xbody 'Proposal #'.$xprop->getId().' - '.$xprop->getName().
  573.                             '<br><a href="http://' $request->server->get('HTTP_HOST') . '/events/proposal/edit/' $xprop->getId() . '">Ver el Proposal</a>'.
  574.                             '<br>Cliente: '.$xcli->getName().
  575.                             '<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.' .
  576.                             '<br>Si el enlace al presupuesto no funciona correctamente, se debe a que desde AV lo han modificado o descartado.'.
  577.                             '<br><br>';
  578.                     } else {
  579.                         $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>';
  580.                     }
  581.                     //Buscamos los agentes a notificar
  582.                     // $arrayIdPro['X'] = 'Y'; al agente 'Y' se le informa del presupuesto 'X'
  583.                     $agent $em->getRepository(User::class)->findOneById($item);
  584.                     $agentMail $agent->getEmail();
  585.                     $mailAgent $agentMail;
  586.                     //Se prepara el correo con los agentes a notificar
  587.                     $firmGmail $agent->getFirmGmail();
  588.                     $data = array(
  589.                         'body' => $xbody,
  590.                         'firm' => $firmGmail,
  591.                     );
  592.                     // EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
  593.                     $transporter = new Swift_SmtpTransport();
  594.                         $transporter->setHost('smtp.gmail.com')
  595.                         ->setEncryption('ssl')//ssl / tls
  596.                         ->setPort(465)// 465 / 587
  597.                         ->setUsername('desarrollo@develup.solutions')
  598.                         ->setPassword('utvh hzoi wfdo ztjs');
  599.                     $mailer = new Swift_Mailer($transporter);
  600.                     $message = new Swift_Message();
  601.                         $message->setSubject('Presupuesto #' $key ', Notificación de nuevo presupuesto')
  602.                         ->setSender($agentMail)
  603.                         ->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
  604.                         ->setReplyTo($agentMail)
  605.                         ->setTo($mailAgent)
  606.                         ->setBody(
  607.                             $this->renderView(
  608.                                 'mail/structure-mail.html.twig',
  609.                                 array('data' => $data)
  610.                             ),
  611.                             'text/html'
  612.                         );
  613.                     $mailer->send($message);
  614.                 }
  615.                 //FIN: Notificamos de todos los presupuestos (proformas) que se han creado
  616.                 // FIN: Se envia al agente el presupuesto
  617.             }
  618.         }
  619.         if(!empty($msjErrorClt)){
  620.             $errorMessage $this->translator->trans('Error, el cliente no puede ser modificado, ya existe una factura previa');
  621.             $this->addFlash('mensajeaverror'$errorMessage);
  622.             return $this->redirectToRoute('ave_edit_file', array('id' => $newFile->getId()));
  623.         }
  624.         return $this->redirectToRoute('ave_edit_file', array('id' => $newFile->getId()));
  625.     }
  626.     /**
  627.      * @Route("/fileedit/{id}",  name="ave_edit_file")
  628.      * Editar un expediente
  629.      */
  630.     public function editFileAction$idRequest $requestAvexpressCalculatorService $calculator)
  631.     {
  632.         $em $this->getDoctrine()->getManager();
  633.         $editFile $em->getRepository(AveFiles::class)->findOneById($id);
  634.         $clients $em->getRepository(Client::class)->findAll();
  635.         $clientSelected $em->getRepository(Client::class)->findOneById($editFile->getClient());
  636.         $products $em->getRepository(AveProduct::class)->findAll();
  637.         $destinations $em->getRepository(Destination::class)->findAll();
  638.         /* Obtengo usuario logueado */
  639.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  640.         $data $calculator->calculateFileTotals((int)$id);
  641.         $sumatoriaTotalNet 0;
  642.         $sumatoriaTotalVat 0;
  643.         $sumatoriaTotal 0;
  644.         $resultados = array(
  645.             'totalNeto' => $sumatoriaTotalNet,
  646.             'vat' => $sumatoriaTotalVat,
  647.             'total' => $sumatoriaTotal,
  648.         );
  649.         $productInFile $em->getRepository(AveProductFile::class)->findByFileId($id);
  650.         $numeroItems sizeof($productInFile);
  651.         $facturas $em->getRepository(AveDocInvoice::class)->findByFileId($id);
  652.         $facturasRec $em->getRepository(AveDocInvoiceRec::class)->findByFileId($id);
  653.         foreach ($facturasRec as $item){ array_push($facturas,$item); }
  654.         $proformas = [];
  655.         $allProformas $em->getRepository(AveDocProforma::class)->findByFileId($id);
  656.         foreach ($allProformas as $item) {
  657.             $dataTwo $this->baseInvoiceDoneFileTwo($id$item->getId(), 'P');
  658.             $bases 0;
  659.             if (is_numeric($dataTwo['totales']) and is_numeric($dataTwo['totales_neto'])) {
  660.                 $bases $dataTwo['totales'] - $dataTwo['totales_neto'];
  661.             }
  662.             $itemsInProforma = [];
  663.             if (array_key_exists('product'$dataTwo['datasupplier'])) {
  664.                 foreach ($dataTwo['datasupplier']['product'] as $elem) {
  665.                     $itemsInProforma[] = $em->getRepository(AveProductFile::class)->findOneById($elem['id']);
  666.                 }
  667.                 $proformas[] = array(
  668.                     'id' => $dataTwo['number'],
  669.                     'itemsInProforma' => $itemsInProforma,
  670.                     'date' => $dataTwo['date'],
  671.                     'neto' => $dataTwo['totales_neto'],
  672.                     'bases_imponibles' => $bases,
  673.                     'total' => $dataTwo['totales'],
  674.                 );
  675.             }
  676.         }
  677.         // Calculamos el beneficio
  678.         $dataThree $this->baseBenefits($id);
  679.         // Buscamos los serviicos pendientes
  680.         $pendingBuds $em->getRepository(AveBudgetPending::class)->findByProposalId($editFile->getIdProposal());
  681.         $pBuds = [];
  682.         // Creamos la agrupacion por proposal
  683.         foreach ($pendingBuds as $item){
  684.             if (!(array_key_exists($item->getProposalId(),$pBuds))){
  685.                 if (!empty($item->getOriginId())){    // Los vacios solo contienen briefings
  686.                     $pBuds[$item->getProposalId()] = null;
  687.                 }
  688.             }
  689.         }
  690.         // Metemos los items en el arreglo clasificado por proposal
  691.         foreach ($pendingBuds as $item){
  692.             if (!empty($item->getOriginId())) {    // Los vacios solo contienen briefings
  693.                 $pBuds[$item->getProposalId()][] = $item;
  694.             }
  695.         }
  696.         ksort($pBuds);
  697.         $keysPbuds array_keys($pBuds);
  698.         $productsInFile $em->getRepository(AveProductFile::class)->getSortedProductsByFile($editFile);
  699.         $arrayProductsInFile = [];
  700.         foreach ($productsInFile as $item){
  701.             $priceTotalWithOutVat $item->getServicePrice() * $item->getPax() * $item->getUnits() * $item->getDays();
  702.             $comi = empty($item->getCommission()) ? $item->getServicePrice() * $item->getPax() * $item->getUnits() * $item->getDays() * ($item->getCommission() / 100);
  703.             $comi = ($item->getOpCommission() == 0) ? ($comi * -1) : $comi;
  704.             $priceTotalWithOutVat += $comi;
  705.             $over =$item->getOver();
  706.             $over = ($item->getOpOver() == 0) ? ($over * -1) : $over;
  707.             $priceTotalWithOutVat += $over;
  708.             $priceWithVat = ($item->getOpIva() == 0) ? ($priceTotalWithOutVat - ($priceTotalWithOutVat * ($item->getIva()/100))) : ($priceTotalWithOutVat + ($priceTotalWithOutVat * ($item->getIva()/100)));
  709.             $arrayProductsInFile[] = array(
  710.                 'id' => $item->getId(),
  711.                 'productName' => $item->getProductName(),
  712.                 'description' => $item->getDescription(),
  713.                 'productId' => $item->getProductId(),
  714.                 'dateStart' => $item->getDateStart(),
  715.                 'dateEnd' => $item->getDateEnd(),
  716.                 'servicePrice' => $item->getServicePrice(),
  717.                 'subTotalPrice' => $item->getSubTotalPrice(),
  718.                 'subtotalProduct' => $priceTotalWithOutVat,
  719.                 'iva' => $item->getIva(),
  720.                 'pax' => $item->getPax(),
  721.                 'qty' => $item->getUnits(),
  722.                 'days' => $item->getDays(),
  723.                 'type' => $item->getType(),
  724.                 'subtotal' => $priceWithVat,
  725.             );
  726.         }
  727.         // Generamos un arreglo con la previsión posible de venta del espacio
  728.         $gpFile $em->getRepository(Reservation::class)->findOneById($editFile->getReservation());
  729.         $idGpFile = empty($gpFile) ? null $gpFile->getId();
  730.         $optionsGp = [];
  731.         if (!empty($idGpFile)) {
  732.             $options $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($idGpFile);
  733.             foreach ($options as $option) {
  734.                 $rankQuote $option->getRankQuote();
  735.                 if (!isset($optionsGp[$rankQuote])) {
  736.                     $optionsGp[$rankQuote] = [
  737.                         'Opcion' => $rankQuote,
  738.                         'Salas'  => [],
  739.                         'Precio' => 0
  740.                     ];
  741.                 }
  742.                 // Agregar sala si no existe
  743.                 $loungeName $option->getLoungeName();
  744.                 if (!in_array($loungeName$optionsGp[$rankQuote]['Salas'])) {
  745.                     $optionsGp[$rankQuote]['Salas'][] = $loungeName;
  746.                 }
  747.                 // Sumar precios
  748.                 $optionsGp[$rankQuote]['Precio'] += (float) $option->getServicePrice();
  749.             }
  750.             // Convertimos el array de salas a texto
  751.             foreach ($optionsGp as &$gp) {
  752.                 $gp['Sala'] = implode(', '$gp['Salas']);
  753.                 unset($gp['Salas']);
  754.             }
  755.             // Reindexar array
  756.             $optionsGp array_values($optionsGp);
  757.         }
  758.         $htFile = !(empty($gpFile)) ? (in_array($user_logueado->getUserrol()->getId(),[9,23,24,37,47,53]) ? $em->getRepository(HtFile::class)->findOneByReservation($gpFile) : null ) : null;
  759.         $gpFile in_array($user_logueado->getUserrol()->getId(),[9,23,24,37,47,53]) ? $gpFile null ;
  760.         return $this->render('MDS/AvexpressBundle/Avexpress/edit-files.html.twig',
  761.             array(
  762.                 'id' => $id,
  763.                 'clients' => $clients,
  764.                 'clientId' => $editFile->getClient(),
  765.                 'clientSelected' => $clientSelected,
  766.                 'file' => $editFile,
  767.                 'numeroItems' => $numeroItems,
  768. //                'arrayProductFile' => $data['datasupplier']['product'],
  769.                 'arrayProductFile' => $arrayProductsInFile,
  770.                 'products' => $products,
  771.                 'services' => null,
  772.                 'facturas' => $facturas,
  773.                 'proformas' => $proformas,
  774.                 'paymentNotIvoiced' => null,
  775.                 'paymentsAll' => null,
  776.                 'optionsGp' => $optionsGp,
  777.                 'resultados' => $resultados,
  778.                 'totales_global_con_iva' => $data['totales'], //$data['totales_global_con_iva'],
  779.                 'totales_global_iva' => $data['bases_imponibles']['ivaMontoVeintiUno'], //$data['totales_global_iva'],
  780.                 'totales_global_neto' => $data['totales_neto'], //$data['totales_global_neto'],
  781.                 'totales_global_servicios_con_iva' => 0//$data['totales_global_servicios_con_iva'],
  782.                 'totales_global_servicios_neto' => 0//$data['totales_global_servicios_neto'],
  783.                 'totales_global_servicios_iva' => 0//$data['totales_global_servicios_iva'],
  784.                 'sumatoria_totales_global_con_iva' => 0//$data['sumatoria_totales_global_con_iva'],
  785.                 'sumatoria_totales_global_neto' => 0//$data['sumatoria_totales_global_neto'],
  786.                 'sumatoria_totales_global_iva' => 0//$data['sumatoria_totales_global_iva'],
  787.                 'benefitEuro' => $dataThree['benefitEuro'],
  788.                 'benefitPerc' => $dataThree['benefitPerc'],
  789.                 'pendingBudgets' => $pBuds,
  790.                 'keysPendingBudgets' => $keysPbuds,
  791.                 'destinations' => $destinations,
  792.                 'htFile' => $htFile,
  793.                 'gpFile' => $gpFile,
  794.             ));
  795.     }
  796.     /**
  797.      * @Route("/filedelete/{id}",  name="ave_delete_file")
  798.      * Actualizar un expediente
  799.      */
  800.     public function deleteFileAction($idRequest $request)
  801.     {
  802.         $em $this->getDoctrine()->getManager();
  803.         $newFile $em->getRepository(AveFiles::class)->findOneById($id);
  804.         /* Obtengo usuario logueado */
  805.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  806.         $user_id $user_logueado->getId();
  807.         $newFile->setStatus('Deleted');
  808.         $newFile->setUpdatedId($user_id);
  809.         $newFile->setUpdatedAt(new \DateTime("now"));
  810.         $em->persist($newFile);
  811.         $em->flush();
  812.         return $this->redirectToRoute('ave_edit_file', array( 'id' => $id ));
  813.     }
  814.     /**
  815.      * @Route("/filefrombudget/{id}",  name="ave_add_file_from_budget")
  816.      * Agregar un expediente desde un presupuesto
  817.      */
  818.     public function addFileFromBudgetAction$idRequest $request)
  819.     {
  820.         $em $this->getDoctrine()->getManager();
  821.         $budget $em->getRepository(AveBudgetPending::class)->findOneById($id);
  822.         $proposal $em->getRepository(Proposal::class)->findOneById($budget->getProposalId());
  823.         $newFile $em->getRepository(AveFiles::class)->findOneByIdProposal($proposal->getId());
  824.         /* Obtengo usuario logueado */
  825.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  826.         $user_id $user_logueado->getId();
  827.         if (empty($newFile)){
  828.             // No hay un File asociado a ese proposal, se debe crear uno nuevo
  829.             $newFile = new AveFiles();
  830.             $newFile->setTitle($proposal->getId().' - ' .$budget->getProposalTitle());
  831.             $newFile->setClient(262);                           // In Out es el cliente
  832.             $newFile->setIdProposal($proposal->getId());
  833.             $newFile->setStatus('Pending');
  834.             $newFile->setAdvancePayment(null);
  835.             if (!empty($budget->getBriefing())){
  836.                 $newFile->setDescription('<p> *********  MENSAJE DEL AGENTE  ********* </p>' $budget->getBriefing());
  837.             }
  838.             $newFile->setDateStart(new \DateTime("now"));
  839.             $newFile->setDateEnd(new \DateTime("now"));
  840.             $newFile->setCreatedId($user_id);
  841.             $newFile->setUpdatedId($user_id);
  842.             $newFile->setCreatedAt(new \DateTime("now"));
  843.             $newFile->setUpdatedAt(new \DateTime("now"));
  844.         } else {
  845.             // Ya existe un File asociado a ese proposal
  846.             $newFile->setClient(262);                           // In Out es el cliente
  847.             $newFile->setStatus('Pending');
  848.             if (!empty($budget->getBriefing())) {
  849.                 $newFile->setDescription($newFile->getDescription() . '<p> *********  MENSAJE DEL AGENTE  ********* </p>' $budget->getBriefing());
  850.             }
  851.             $newFile->setUpdatedId($user_id);
  852.             $newFile->setUpdatedAt(new \DateTime("now"));
  853.         }
  854.         $em->persist($newFile);
  855.         $em->flush();
  856.         $em->remove($budget);
  857.         $em->flush();
  858.         //Actualizamos los Briefings que esten en FileId null con el recien generado fileId en base al proposalId
  859.         $allBriefings $em->getRepository(AveBriefings::class)->findByProposalId($proposal->getId());
  860.         foreach ($allBriefings as $item){
  861.             if (empty($item->getFileId())) {
  862.                 $item->setFileId($newFile->getId());
  863.                 $em->persist($item);
  864.                 $em->flush();
  865.             }
  866.         }
  867.         return $this->redirectToRoute('ave_edit_file', array( 'id' => $newFile->getId() ));
  868.     }
  869.     /**
  870.      * @Route("/filelistbriefings/{id}",  name="ave_list_file_briefings")
  871.      * Listar briefings del expediente
  872.      */
  873.     public function listFileBriefingsAction($idRequest $request){
  874.         $em $this->getDoctrine()->getManager();
  875.         $briefings $em->getRepository(AveBriefings::class)->findByFileId($id);
  876.         return $this->render('MDS/AvexpressBundle/Avexpress/list-briefings.html.twig',
  877.             array(
  878.                 'id' => $id,
  879.                 'briefings' => $briefings,
  880.             )
  881.         );
  882.     }
  883.     /**
  884.      * @Route("/briefingadd/{id}",  name="ave_add_file_briefings")
  885.      * Agregar briefing al expediente
  886.      */
  887.     public function addFileBriefingsAction($idRequest $request){
  888.         $brif $request->request->get('newbriefing');
  889.         $em $this->getDoctrine()->getManager();
  890.         $file $em->getRepository(AveFiles::class)->findOneById($id);
  891.         $proposalId $file->getIdProposal();
  892.         /* Obtengo usuario logueado */
  893.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  894.         $user_id $user_logueado->getId();
  895.         $userConfirmedFullName $user_logueado->getName().' '.$user_logueado->getLastName();
  896.         $briefing = new AveBriefings();
  897.         $briefing->setProposalId($proposalId);
  898.         $briefing->setBriefing($brif);
  899.         $briefing->setBudgetPendingId(null);
  900.         $briefing->setFileId($id);
  901.         $briefing->setUserConfirmedFullName($userConfirmedFullName);
  902.         $briefing->setUserConfirmedId($user_id);
  903.         $briefing->setCreatedAt(new \DateTime("now"));
  904.         $em->persist($briefing);
  905.         $em->flush();
  906.         $briefings $em->getRepository(AveBriefings::class)->findByFileId($id);
  907.         return $this->render('MDS/AvexpressBundle/Avexpress/list-briefings.html.twig',
  908.             array(
  909.                 'id' => $id,
  910.                 'briefings' => $briefings,
  911.             )
  912.         );
  913.     }
  914.     /**
  915.      * @Route("/filedeletedlist/",  name="ave_list_file_deleted")
  916.      * Listar expedientes cancelados
  917.      */
  918.     public function listFileDeletedActionRequest $request)
  919.     {
  920.         $em $this->getDoctrine()->getManager();
  921.         $idgroup null$ref = [];
  922.         $reservas $em->getRepository(AveFiles::class)->findByStatus('Deleted');
  923.         foreach ($reservas as $res) {
  924.             $client $em->getRepository(Client::class)->findOneById($res->getClient());
  925.             if (!empty($client)) { $res->setClient($client->getName()); } else { $res->setClient(null); }
  926.             if (!empty($res->getDateStart()) and !empty($res->getDateEnd())) {
  927.                 $ref[$res->getId()] = '#' . ($res->getDateStart())->format('ymd') . ($res->getDateEnd())->format('ymd');
  928.             } else {
  929.                 $ref[$res->getId()] = '#' '000000' '000000';
  930.             }
  931.         }
  932.         $reservasZero = [];
  933.         foreach ($reservas as $res) {
  934.             $reservasZero[] = array(
  935.                 'dateStart' => $res->getDateStart(),
  936.                 'dateEnd' => $res->getDateEnd(),
  937.                 'id' => $res->getId(),
  938.                 'title' => $res->getTitle(),
  939.                 'client' => $res->getClient(),
  940.                 'createdId' => $res->getCreatedId(),
  941.                 'ref' => $ref[$res->getId()],
  942.                 'reservation' => $res->getReservation(),
  943.             );
  944.         }
  945.         $reservas $reservasZero;
  946.         return $this->render('MDS/AvexpressBundle/Avexpress/list-files.html.twig',
  947.             array(
  948.                 'groups' => null,
  949.                 'listofdeletedfiles' => true,
  950.                 'reservations' => $reservas
  951.             )
  952.         );
  953.     }
  954.     /**
  955.      * @Route("/updatefilecomments/{id}",  name="ave_update_file_comments")
  956.      * Actualizar Comentarios y booleanos del expediente
  957.      */
  958.     public function updateFileCommentsAction($idRequest $request){
  959.         $em $this->getDoctrine()->getManager();
  960.         $file $em->getRepository(AveFiles::class)->findOneById($id);
  961.         $newComments $request->request->get('comments');
  962.         $chkCommentsToPro $request->request->get('chkCommentsToPro');
  963.         $chkCommentsToInv $request->request->get('chkCommentsToInv');
  964.         if ($chkCommentsToInv == 'on'){ $chkCommentsToInv true; } else { $chkCommentsToInv false; }
  965.         if ($chkCommentsToPro == 'on'){ $chkCommentsToPro true; } else { $chkCommentsToPro false; }
  966.         $file->setComments($newComments);
  967.         $file->setCommentsInInv($chkCommentsToInv);
  968.         $file->setCommentsInPro($chkCommentsToPro);
  969.         $em->persist($file);
  970.         $em->flush();
  971.         return $this->redirectToRoute('ave_edit_file', array( 'id' => $id ));
  972.     }
  973.     private function baseInvoiceDoneFileTwo($fileId$invoiceId$typeBase)
  974.     {
  975.         $em $this->getDoctrine()->getManager();
  976.         $file $em->getRepository(AveFiles::class)->findOneById($fileId);
  977.         $dateDocument null;                                                                           //Fecha final del documento
  978.         $subneto 0;
  979.         if (($typeBase == 'I') or ($typeBase == 'P')) {
  980.             if ($typeBase == 'I') {
  981.                 $items $em->getRepository(AveDocInvoiceItems::class)->findBy(array('fileId' => $fileId'invoiceId' => $invoiceId));
  982.             } else {
  983.                 $parameters = array(
  984.                     'fileId' => $fileId,
  985.                     'proformaId' => $invoiceId,
  986.                 );
  987.                 $dql 'SELECT i
  988.                         FROM AvexpressBundle:AveProductFile i
  989.                         INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  990.                         WHERE i.fileId = :fileId AND c.proformaId =:proformaId
  991.                         ORDER BY i.rankquoteAv ASC';
  992.                 $query $em->createQuery($dql)->setParameters($parameters);
  993.                 $items $query->getResult();
  994.                 $arrayLocation = [];
  995.                 $arrayLocationWithNull false;
  996.                 foreach ($items as $item){
  997.                     if (!empty($item->getLocation())){
  998.                         $arrayLocation[$item->getLocation()] = $item->getLocation();
  999.                     } else {
  1000.                         $arrayLocationWithNull true;
  1001.                     }
  1002.                 }
  1003.                 if ($arrayLocationWithNull){ $arrayLocation['null'] = 'null'; }
  1004.                 $productsInFile = [];
  1005.                 foreach ($arrayLocation as $item){
  1006.                     // VIDEO
  1007.                     $parameters = array(
  1008.                         'fileId' => $fileId,
  1009.                         'type' => 'VĆ­deo',
  1010.                         'location' => $item,
  1011.                         'proformaId' => $invoiceId,
  1012.                     );
  1013.                     $dql 'SELECT i                            
  1014.                             FROM AvexpressBundle:AveProductFile i
  1015.                             INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1016.                             WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location AND c.proformaId =:proformaId
  1017.                             ORDER BY i.rankquoteAv ASC';
  1018.                     $query $em->createQuery($dql)->setParameters($parameters);
  1019.                     $productsInFileVid $query->getResult();
  1020.                     // SONIDO
  1021.                     $parameters = array(
  1022.                         'fileId' => $fileId,
  1023.                         'type' => 'Sonido',
  1024.                         'location' => $item,
  1025.                         'proformaId' => $invoiceId,
  1026.                     );
  1027.                     $dql 'SELECT i
  1028.                             FROM AvexpressBundle:AveProductFile i
  1029.                             INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1030.                             WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location AND c.proformaId =:proformaId
  1031.                             ORDER BY i.rankquoteAv ASC';
  1032.                     $query $em->createQuery($dql)->setParameters($parameters);
  1033.                     $productsInFileSound $query->getResult();
  1034.                     // ILUMINACION
  1035.                     $parameters = array(
  1036.                         'fileId' => $fileId,
  1037.                         'type' => 'Iluminación',
  1038.                         'location' => $item,
  1039.                         'proformaId' => $invoiceId,
  1040.                     );
  1041.                     $dql 'SELECT i
  1042.                             FROM AvexpressBundle:AveProductFile i
  1043.                             INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1044.                             WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location AND c.proformaId =:proformaId
  1045.                             ORDER BY i.rankquoteAv ASC';
  1046.                     $query $em->createQuery($dql)->setParameters($parameters);
  1047.                     $productsInFileLights $query->getResult();
  1048.                     // OTROS
  1049.                     $parameters = array(
  1050.                         'fileId' => $fileId,
  1051.                         'typeV' => 'VĆ­deo',
  1052.                         'typeS' => 'Sonido',
  1053.                         'typeI' => 'Iluminación',
  1054.                         'location' => $item,
  1055.                         'proformaId' => $invoiceId,
  1056.                     );
  1057.                     $dql 'SELECT i
  1058.                             FROM AvexpressBundle:AveProductFile i
  1059.                             INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1060.                             WHERE (i.fileId = :fileId AND i.type != :typeV AND i.type != :typeS AND i.type != :typeI AND i.location = :location AND c.proformaId =:proformaId)
  1061.                             ORDER BY i.rankquoteAv ASC';
  1062.                     $query $em->createQuery($dql)->setParameters($parameters);
  1063.                     $productsInFileOther $query->getResult();
  1064.                     // CASO NULL (Los casos EMPTY estan considerados en las consultas previas)
  1065.                     $parameters = array(
  1066.                         'fileId' => $fileId,
  1067.                         'location' => $item,
  1068.                         'proformaId' => $invoiceId,
  1069.                     );
  1070.                     $dql 'SELECT i
  1071.                             FROM AvexpressBundle:AveProductFile i
  1072.                             INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1073.                             WHERE (i.fileId = :fileId AND i.type IS NULL AND i.location = :location AND c.proformaId =:proformaId)
  1074.                             ORDER BY i.rankquoteAv ASC';
  1075.                     $query $em->createQuery($dql)->setParameters($parameters);
  1076.                     $productsInFileNull $query->getResult();
  1077.                     // Para el location en NULL el SQL tiene que ser diferente por eso el siguiente condicional
  1078.                     if ($item == 'null'){
  1079.                         // VIDEO
  1080.                         $parameters = array(
  1081.                             'fileId' => $fileId,
  1082.                             'type' => 'VĆ­deo',
  1083.                             'proformaId' => $invoiceId,
  1084. //                    'location' => $item,
  1085.                         );
  1086.                         $dql 'SELECT i
  1087.                                 FROM AvexpressBundle:AveProductFile i
  1088.                                 INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1089.                                 WHERE i.fileId = :fileId AND i.type = :type AND i.location IS NULL AND c.proformaId =:proformaId
  1090.                                 ORDER BY i.rankquoteAv ASC';
  1091.                         $query $em->createQuery($dql)->setParameters($parameters);
  1092.                         $productsInFileVid $query->getResult();
  1093.                         // SONIDO
  1094.                         $parameters = array(
  1095.                             'fileId' => $fileId,
  1096.                             'type' => 'Sonido',
  1097.                             'proformaId' => $invoiceId,
  1098. //                    'location' => $item,
  1099.                         );
  1100.                         $dql 'SELECT i
  1101.                                 FROM AvexpressBundle:AveProductFile i
  1102.                                 INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1103.                                 WHERE i.fileId = :fileId AND i.type = :type AND i.location IS NULL AND c.proformaId =:proformaId
  1104.                                 ORDER BY i.rankquoteAv ASC';
  1105.                         $query $em->createQuery($dql)->setParameters($parameters);
  1106.                         $productsInFileSound $query->getResult();
  1107.                         // ILUMINACION
  1108.                         $parameters = array(
  1109.                             'fileId' => $fileId,
  1110.                             'type' => 'Iluminación',
  1111.                             'proformaId' => $invoiceId,
  1112. //                    'location' => $item,
  1113.                         );
  1114.                         $dql 'SELECT i
  1115.                                 FROM AvexpressBundle:AveProductFile i
  1116.                                 INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1117.                                 WHERE i.fileId = :fileId AND i.type = :type AND i.location IS NULL AND c.proformaId =:proformaId
  1118.                                 ORDER BY i.rankquoteAv ASC';
  1119.                         $query $em->createQuery($dql)->setParameters($parameters);
  1120.                         $productsInFileLights $query->getResult();
  1121.                         // OTROS
  1122.                         $parameters = array(
  1123.                             'fileId' => $fileId,
  1124.                             'typeV' => 'VĆ­deo',
  1125.                             'typeS' => 'Sonido',
  1126.                             'typeI' => 'Iluminación',
  1127.                             'proformaId' => $invoiceId,
  1128. //                    'location' => $item,
  1129.                         );
  1130.                         $dql 'SELECT i
  1131.                                 FROM AvexpressBundle:AveProductFile i
  1132.                                 INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1133.                                 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)
  1134.                                 ORDER BY i.rankquoteAv ASC';
  1135.                         $query $em->createQuery($dql)->setParameters($parameters);
  1136.                         $productsInFileOther $query->getResult();
  1137.                         // CASO NULL (Los casos EMPTY estan considerados en las consultas previas)
  1138.                         $parameters = array(
  1139.                             'fileId' => $fileId,
  1140.                             'proformaId' => $invoiceId,
  1141. //                    'location' => $item,
  1142.                         );
  1143.                         $dql 'SELECT i
  1144.                                 FROM AvexpressBundle:AveProductFile i
  1145.                                 INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
  1146.                                 WHERE (i.fileId = :fileId AND i.type IS NULL AND i.location IS NULL AND c.proformaId =:proformaId)
  1147.                                 ORDER BY i.rankquoteAv ASC';
  1148.                         $query $em->createQuery($dql)->setParameters($parameters);
  1149.                         $productsInFileNull $query->getResult();
  1150.                     }
  1151.                     $productsInFile array_merge($productsInFile$productsInFileVid$productsInFileSound$productsInFileLights$productsInFileOther$productsInFileNull);
  1152.                 }
  1153.                 $items $productsInFile;       // En Items estaban todos pero sin ordenamiento, ahora estan organizados por location y tipo
  1154.             }
  1155.         } else {
  1156.             // No es factura ni proforma, es una rectificativa
  1157.             $items $em->getRepository(AveDocInvoiceRecItems::class)->findBy(array('fileId' => $fileId'invoiceRecId' => $invoiceId));
  1158.         }
  1159.         $company $em->getRepository(SettingsCompany::class)->findOneBy(['businessType' => BusinessTypeSettingsCompanyConstants::AUDIOVISUAL]);
  1160.         $client $em->getRepository(Client::class)->findById($file->getClient());
  1161.         if (empty($client)){
  1162.             $client[0] = new Client();
  1163.             $client[0]->setName('');
  1164.             $client[0]->setTitle('');
  1165.             $client[0]->setIdDocument('');
  1166.             $client[0]->setPopulation('');
  1167.             $client[0]->setRegion('');
  1168.             $client[0]->setCountry('');
  1169.         } else {
  1170.             if (is_numeric($client[0]->getPopulation())){
  1171.                 $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  1172.                 $client[0]->setPopulation($city->getCity());
  1173.             }
  1174.             if (is_numeric($client[0]->getRegion())){
  1175.                 $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  1176.                 $client[0]->setRegion($region->getRegion());
  1177.             }
  1178.             if (is_numeric($client[0]->getCountry())){
  1179.                 $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  1180.                 $client[0]->setCountry($country->getCountry());
  1181.             }
  1182.         }
  1183.         // Acumuladores de los calculos
  1184.         $totales_neto_all 0;
  1185.         $data_iva = array(
  1186.             'iva' => 21,
  1187.             'ivaMontoVeintiUno' => 0,
  1188.             'ivaMontoDiez' => 0,
  1189.             'ivaMontoCero' => 0,
  1190.         );
  1191.         //INICIO: Determinamos el numero de factura o proforma
  1192.         if ($typeBase == 'I'){
  1193.             // Es una Factura
  1194.             $number $em->getRepository(AveDocInvoice::class)->findOneById($invoiceId);
  1195.             $dateDocument $number->getDateAt();
  1196.             $number $number->getNumber();
  1197.             $type 'Invoice';
  1198.         } else {
  1199.             if ($typeBase == 'R'){
  1200.                 // Es una factura rectificativa
  1201.                 $number $em->getRepository(AveDocInvoiceRec::class)->findOneById($invoiceId);
  1202.                 $dateDocument $number->getDateAt();
  1203.                 $type 'Invoice Rec';
  1204.             } else {
  1205.                 // Es una Proforma
  1206.                 $number $invoiceId;
  1207.                 $type 'Proforma';
  1208.             }
  1209.         }
  1210.         //FIN: Determinamos el numero de factura o proforma
  1211.         // Buscamos los productos, pagos y servicios
  1212.         $arrayItems = [];
  1213.         $fileProducts = [];
  1214.         $payments = [];
  1215.         $services = [];
  1216.         if (!empty($items)) {
  1217.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  1218.                 foreach ($items as $item) {
  1219.                     switch ($item->getItemType()) {
  1220.                         case 'PRODUCT'// Producto
  1221.                             $fileProducts[] = $item;
  1222.                             break;
  1223.                         case 'PAYMENT'// Pago
  1224.                             $payments[] = $item;
  1225.                             break;
  1226.                         case 'SERVICE'// Servicio
  1227.                             $services[] = $item;
  1228.                             break;
  1229.                         default:
  1230.                             break;
  1231.                     }
  1232.                 }
  1233.             } else {
  1234.                 // Es una proforma
  1235.                 foreach ($items as $item) {
  1236.                     switch ($item->getType()) {
  1237.                         case 'PRODUCT'// Producto
  1238.                             $productPro $em->getRepository(AveProductFile::class)->findOneById($item->getControlId());
  1239.                             if (!empty($productPro)) {
  1240.                                 $fileProducts[] = $productPro;
  1241.                             }
  1242.                             break;
  1243.                         case 'PAYMENT'// Pago
  1244.                             $paymentPro $em->getRepository(AvePaymentsClient::class)->findOneById($item->getControlId());
  1245.                             if (!empty($paymentPro)) {
  1246.                                 $payments[] = $paymentPro;
  1247.                             }
  1248.                             break;
  1249.                         case 'SERVICE'// Servicio
  1250.                             $servicePro $em->getRepository(AveServices::class)->findOneById($item->getControlId());
  1251.                             if (!empty($servicePro)) {
  1252.                                 $services[] = $servicePro;
  1253.                             }
  1254.                             break;
  1255.                         default:
  1256.                             // Producto  (Video, Iluminacion, Sonido, Otros)
  1257.                             if (!empty($item)) {
  1258.                                 $fileProducts[] = $item;
  1259.                             }
  1260.                         break;
  1261.                     }
  1262.                 }
  1263.             }
  1264.         }
  1265.         $data_supplier = [];
  1266.         $i 0;
  1267.         $iva '21';            // Esteban Rincon: "Por Ley de localización del impuesto, siempre serĆ” un 21%"
  1268.         $pax '1';
  1269.         $qty '1';
  1270.         $product = array(
  1271.             'neto' => 0,
  1272.             'sumSubT' => 0,
  1273.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  1274.         $service = array(
  1275.             'neto' => 0,
  1276.             'sumSubT' => 0,
  1277.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  1278.         foreach ($fileProducts as $item){
  1279.             if (!is_null($item->getUnits()) or !empty($item->getUnits())){
  1280.                 $qty $item->getUnits();
  1281.             }
  1282.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  1283.                 if (is_null($item->getPrdServicePrice()) or empty($item->getPrdServicePrice())){
  1284.                     $subtotal 0;
  1285.                     $neto 0;
  1286.                     $subtotalProduct 0;
  1287.                 } else {
  1288. //                    $subtotalProduct = $item->getPrdServicePrice() * 1.21;
  1289.                     $subtotalProduct $item->getPrdSubTotalPrice() * 1.21;
  1290. //                    $subneto = $item->getPrdServicePrice();
  1291.                     $subneto $item->getPrdSubTotalPrice();
  1292.                     $subtotal =  $subtotalProduct;
  1293.                     $neto =  $subneto;
  1294.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  1295.                     $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  1296.                     $neto round($neto,2,PHP_ROUND_HALF_UP);
  1297.                     $arrayItems[] = array(
  1298.                         'type' => 'Product',
  1299.                         'name' => $item->getPrdName(),
  1300.                         'amount' => $neto,
  1301.                         'iva' => '21',
  1302.                         'total' => $subtotal,
  1303.                     );
  1304.                 }
  1305.             } else {
  1306.                 // Es proforma
  1307.                 if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
  1308.                     $subtotal 0;
  1309.                     $neto 0;
  1310.                     $subtotalProduct 0;
  1311.                 } else {
  1312. //                    $subtotalProduct = $item->getServicePrice() * 1.21;
  1313.                     $subtotalProduct $item->getSubTotalPrice() * 1.21;
  1314. //                    $subneto = $item->getServicePrice();
  1315.                     $subneto $item->getSubTotalPrice();
  1316.                     $subtotal =  $subtotalProduct;
  1317.                     $neto =  $subneto;
  1318.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  1319.                     $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  1320.                     $neto round($neto,2,PHP_ROUND_HALF_UP);
  1321.                     $arrayItems[] = array(
  1322.                         'type' => 'Product',
  1323.                         'name' => $item->getProductName(),
  1324.                         'amount' => $neto,
  1325.                         'iva' => '21',
  1326.                         'total' => $subtotal,
  1327.                     );
  1328.                 }
  1329.             }
  1330.             // Acumula netos totales e IVA
  1331.             $totales_neto_all $totales_neto_all $neto;
  1332.             $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto 0.21);
  1333.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  1334.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  1335.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  1336.             // Acumula netos totales e IVA
  1337.             $product['neto'] = $product['neto'] + $neto;
  1338.             $product['sumSubT'] = $product['sumSubT'] + $subtotal;
  1339.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  1340.             $product['neto'] = round($product['neto'],2,PHP_ROUND_HALF_UP);
  1341.             $product['sumSubT'] = round($product['sumSubT'],2,PHP_ROUND_HALF_UP);
  1342.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  1343.                 $data_supplier['product'][$i] = array(
  1344.                     'id' => $item->getId(),
  1345.                     'productName' => $item->getPrdName(),
  1346.                     'productId' => $item->getPrdProductId(),
  1347.                     'dateStart' => $item->getPrdDateStart(),
  1348.                     'dateEnd' => $item->getPrdDateEnd(),
  1349.                     'servicePrice' => $item->getPrdServicePrice(),
  1350.                     'serviceSubTotalPrice' => $subneto,     //antes de IVA
  1351.                     'subtotalProduct' => $subtotalProduct,
  1352.                     'iva' => $iva,
  1353.                     'pax' => $pax,
  1354.                     'qty' => $qty,
  1355.                     'type' => $item->getPrdType(),
  1356.                     'subtotal' => $subtotal,
  1357.                 );
  1358.             } else {
  1359.                 // Es proforma
  1360.                 $data_supplier['product'][$i] = array(
  1361.                     'id' => $item->getId(),
  1362.                     'productName' => $item->getProductName(),
  1363.                     'productId' => $item->getProductId(),
  1364.                     'dateStart' => $item->getDateStart(),
  1365.                     'dateEnd' => $item->getDateEnd(),
  1366.                     'servicePrice' => $item->getServicePrice(),
  1367.                     'subtotalProduct' => $subtotalProduct,
  1368.                     'iva' => $iva,
  1369.                     'pax' => $pax,
  1370.                     'qty' => $qty,
  1371.                     'type' => $item->getType(),
  1372.                     'subtotal' => $subtotal,
  1373.                 );
  1374.             }
  1375.             $i++;
  1376.         }
  1377.         $data_supplier['productSubTotal'] = array(
  1378.             'neto' => $product['neto'],
  1379.             'sumSubT' => $product['sumSubT'],
  1380.         );
  1381.         $payment = array(
  1382.             'sumSubT' => 0,
  1383.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  1384.         $i 0;
  1385.         foreach ($payments as $item){
  1386.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  1387.                 $payment['sumSubT'] = $payment['sumSubT'] + $item->getPayAmountTotal();
  1388.                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  1389.                 $payment['sumSubT'] = round($payment['sumSubT'], 2PHP_ROUND_HALF_UP);
  1390.                 $data_supplier['payment'][$i] = array(
  1391.                     'id' => $item->getId(),
  1392.                     'amount' => $item->getPayAmount(),
  1393.                     'amountTotal' => $item->getPayAmountTotal(),
  1394.                     'vat' => $item->getPayVat(),
  1395.                     'datePayAt' => $item->getPayDatePayAt(),
  1396.                     'wayToPay' => $item->getPayWayToPay(),
  1397.                 );
  1398.                 $arrayItems[] = array(
  1399.                     'type' => 'Payment',
  1400.                     'name' => $item->getPayWayToPay(),
  1401.                     'amount' => $item->getPayAmount(),
  1402.                     'total' => $item->getPayAmountTotal(),
  1403.                     'iva' => $item->getPayVat(),
  1404.                 );
  1405.             } else {
  1406.                 // Es una proforma
  1407.                 $payment['sumSubT'] = $payment['sumSubT'] + $item->getAmountTotal();
  1408.                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  1409.                 $payment['sumSubT'] = round($payment['sumSubT'], 2PHP_ROUND_HALF_UP);
  1410.                 $data_supplier['payment'][$i] = array(
  1411.                     'id' => $item->getId(),
  1412.                     'amount' => $item->getAmount(),
  1413.                     'amountTotal' => $item->getAmountTotal(),
  1414.                     'vat' => $item->getVat(),
  1415.                     'datePayAt' => $item->getDatePayAt(),
  1416.                     'wayToPay' => $item->getWayToPay(),
  1417.                 );
  1418.                 $arrayItems[] = array(
  1419.                     'type' => 'Payment',
  1420.                     'name' => $item->getWayToPay(),
  1421.                     'amount' => $item->getAmount(),
  1422.                     'total' => $item->getAmountTotal(),
  1423.                     'iva' => $item->getVat(),
  1424.                 );
  1425.             }
  1426.             $i++;
  1427.         }
  1428.         if (!empty($payments)) {
  1429.             $data_supplier['paymentSubTotal'] = array(
  1430.                 'sumSubT' => $payment['sumSubT'],
  1431.             );
  1432.         }
  1433.         foreach ($services as $item){
  1434.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  1435.                 if (is_null($item->getSrvPrice()) or empty($item->getSrvPrice())) {
  1436.                     $subtotal 0;
  1437.                     $neto 0;
  1438.                     $subtotalService 0;
  1439.                 } else {
  1440.                     $subtotalService $item->getSrvPrice();
  1441.                     $subneto $item->getSrvPrice();
  1442.                     // Commission
  1443.                     if ($item->getSrvOpCommission() == '1') {
  1444.                         $subtotalService $subtotalService * (+ ($item->getSrvCommission() / 100));
  1445.                         $subneto $subneto * (+ ($item->getSrvCommission() / 100));
  1446.                     } else {
  1447.                         $subtotalService $subtotalService * (- ($item->getSrvCommission() / 100));
  1448.                         $subneto $subneto * (- ($item->getSrvCommission() / 100));
  1449.                     }
  1450.                     // Over
  1451.                     if ($item->getSrvOpOver() == '1') {
  1452.                         $subtotalService $subtotalService $item->getSrvOver();
  1453.                         $subneto $subneto $item->getSrvOver();
  1454.                     } else {
  1455.                         $subtotalService $subtotalService $item->getSrvOver();
  1456.                         $subneto $subneto $item->getSrvOver();
  1457.                     }
  1458.                     // IVA
  1459.                     if ($item->getSrvOpIva() == '1') {
  1460.                         $subtotalService $subtotalService * (+ ($item->getSrvIva() / 100));
  1461.                     } else {
  1462.                         $subtotalService $item->getSrvPrice();
  1463.                         $subneto = ($subneto 100) / (100 $item->getSrvIva());
  1464.                     }
  1465.                     switch ($item->getSrvServiceCatId()) {
  1466.                         case 1// Alojamiento
  1467.                             // el numero de noches $numNoches; precio unitario $subneto
  1468.                             $numNoches = (($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days;
  1469.                             // La personas no afectan este calculo
  1470.                             $subtotal $subtotalService $numNoches $item->getSrvUnits();
  1471.                             $subnetoUnit $subneto;
  1472.                             $subneto $subneto $numNoches $item->getSrvUnits();
  1473.                             $data_supplier['service'][$i] = array(
  1474.                                 'id' => $item->getId(),
  1475.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1476.                                 'serviceName' => $item->getSrvName(),
  1477.                                 'serviceType' => 'Hotel',
  1478.                                 'date' => ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y'),
  1479.                                 'qty' => $item->getSrvUnits(),
  1480.                                 'iva' => $item->getSrvIva(),
  1481.                                 'pax' => '-',
  1482.                                 'precioUnit' => $subnetoUnit,
  1483.                                 'subneto' => $subneto,
  1484.                                 'subtotal' => $subtotal,
  1485.                             );
  1486.                             break;
  1487.                         case 2//Actividades
  1488.                             // El nĆŗmero de personas es considerado en el calculo
  1489.                             $pax $item->getSrvPax();
  1490.                             if (empty($pax) or $pax == "0") {
  1491.                                 $pax 1;
  1492.                             }
  1493.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1494.                             if ($days 1) {
  1495.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1496.                             } else {
  1497.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1498.                             }
  1499.                             $subtotal $subtotalService $days $item->getSrvUnits();
  1500.                             $subnetoUnit $subneto;
  1501.                             $subneto $subneto $days $item->getSrvUnits();
  1502.                             $data_supplier['service'][$i] = array(
  1503.                                 'id' => $item->getId(),
  1504.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1505.                                 'serviceName' => $item->getSrvName(),
  1506.                                 'serviceType' => 'Actividad',
  1507.                                 'date' => $dateServ,
  1508.                                 'qty' => $item->getSrvUnits(),
  1509.                                 'iva' => $item->getSrvIva(),
  1510.                                 'pax' => $item->getSrvPax(),
  1511.                                 'precioUnit' => $subnetoUnit,
  1512.                                 'subneto' => $subneto,
  1513.                                 'subtotal' => $subtotal,
  1514.                             );
  1515.                             break;
  1516.                         case 3// AV
  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' => 'AV',
  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 4//Creative
  1549.                             $pax $item->getSrvPax();
  1550.                             if (empty($pax) or $pax == "0") {
  1551.                                 $pax 1;
  1552.                             }
  1553.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  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' => 'Creativo',
  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 5//Cruise
  1581.                             $pax $item->getSrvPax();
  1582.                             if (empty($pax) or $pax == "0") {
  1583.                                 $pax 1;
  1584.                             }
  1585.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days);
  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' => 'Crucero',
  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 6//Entertaiment
  1613.                             $pax $item->getSrvPax();
  1614.                             if (empty($pax) or $pax == "0") {
  1615.                                 $pax 1;
  1616.                             }
  1617.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1618.                             if ($days 1) {
  1619.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1620.                             } else {
  1621.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1622.                             }
  1623.                             $unitsServ $item->getSrvUnits();
  1624.                             if (empty($unitsServ) or $unitsServ == "0") {
  1625.                                 $unitsServ 1;
  1626.                             }
  1627.                             $subtotal $subtotalService $days $unitsServ $pax;
  1628.                             $subnetoUnit $subneto;
  1629.                             $subneto $subneto $days $unitsServ $pax;
  1630.                             $data_supplier['service'][$i] = array(
  1631.                                 'id' => $item->getId(),
  1632.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1633.                                 'serviceName' => $item->getSrvName(),
  1634.                                 'serviceType' => 'Entretenimiento',
  1635.                                 'date' => $dateServ,
  1636.                                 'qty' => $unitsServ,
  1637.                                 'iva' => $item->getSrvIva(),
  1638.                                 'pax' => $item->getSrvPax(),
  1639.                                 'precioUnit' => $subnetoUnit,
  1640.                                 'subneto' => $subneto,
  1641.                                 'subtotal' => $subtotal,
  1642.                             );
  1643.                             break;
  1644.                         case 7// Gifts
  1645.                             $pax $item->getSrvPax();
  1646.                             if (empty($pax) or $pax == "0") {
  1647.                                 $pax 1;
  1648.                             }
  1649. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  1650.                             $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 8//Guide
  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' => 'Regalos',
  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 9//Itineraries
  1710.                             $pax $item->getSrvPax();
  1711.                             if (empty($pax) or $pax == "0") {
  1712.                                 $pax 1;
  1713.                             }
  1714.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1715.                             if ($days 1) {
  1716.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1717.                             } else {
  1718.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1719.                             }
  1720.                             $unitsServ $item->getSrvUnits();
  1721.                             if (empty($unitsServ) or $unitsServ == "0") {
  1722.                                 $unitsServ 1;
  1723.                             }
  1724.                             $subtotal $subtotalService $days $unitsServ $pax;
  1725.                             $subnetoUnit $subneto;
  1726.                             $subneto $subneto $days $unitsServ $pax;
  1727.                             $data_supplier['service'][$i] = array(
  1728.                                 'id' => $item->getId(),
  1729.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1730.                                 'serviceName' => $item->getSrvName(),
  1731.                                 'serviceType' => 'Itinerarios',
  1732.                                 'date' => $dateServ,
  1733.                                 'qty' => $unitsServ,
  1734.                                 'iva' => $item->getSrvIva(),
  1735.                                 'pax' => $item->getSrvPax(),
  1736.                                 'precioUnit' => $subnetoUnit,
  1737.                                 'subneto' => $subneto,
  1738.                                 'subtotal' => $subtotal,
  1739.                             );
  1740.                             break;
  1741.                         case 10//Lounge  -- No Aplica
  1742. //                        $pax = $item->getPax();
  1743. //                        if (empty($pax) or $pax == "0") {
  1744. //                            $pax = 1;
  1745. //                        }
  1746. //
  1747. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  1748. //                        if ($days > 1){
  1749. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  1750. //                        } else {
  1751. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y');
  1752. //                        }
  1753. //
  1754. //                        $unitsServ = $item->getUnits();
  1755. //                        if (empty($unitsServ) or $unitsServ == "0") {
  1756. //                            $unitsServ = 1;
  1757. //                        }
  1758. //
  1759. //                        $subtotal = $subtotalService * $days * $unitsServ * $pax;
  1760. //                        $subnetoUnit = $subneto;
  1761. //                        $subneto = $subneto * $days * $unitsServ * $pax;
  1762. //
  1763. //                        $data_supplier['service'][$i] = array (
  1764. //                            'id' => $item->getId(),
  1765. //                            'serviceCatId' => $item->getServiceCatId(),
  1766. //                            'serviceName' => $item->getName(),
  1767. //                            'serviceType' => 'Itinerarios',
  1768. //                            'date' => $dateServ,
  1769. //                            'qty' => $unitsServ,
  1770. //                            'iva' => $item->getIva(),
  1771. //                            'pax' => $item->getPax(),
  1772. //                            'precioUnit' => $subnetoUnit,
  1773. //                            'subneto' => $subneto,
  1774. //                            'subtotal' => $subtotal,
  1775. //                        );
  1776.                             break;
  1777.                         case 11//Menu
  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' => 'MenĆŗ',
  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 12//Others
  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' => 'Otros',
  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 13//Transport
  1842.                             $pax $item->getSrvPax();
  1843.                             if (empty($pax) or $pax == "0") {
  1844.                                 $pax 1;
  1845.                             }
  1846.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1847.                             if ($days 1) {
  1848.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1849.                             } else {
  1850.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1851.                             }
  1852.                             $unitsServ $item->getSrvUnits();
  1853.                             if (empty($unitsServ) or $unitsServ == "0") {
  1854.                                 $unitsServ 1;
  1855.                             }
  1856.                             $subtotal $subtotalService $days $unitsServ $pax;
  1857.                             $subnetoUnit $subneto;
  1858.                             $subneto $subneto $days $unitsServ $pax;
  1859.                             $data_supplier['service'][$i] = array(
  1860.                                 'id' => $item->getId(),
  1861.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1862.                                 'serviceName' => $item->getSrvName(),
  1863.                                 'serviceType' => 'Transporte',
  1864.                                 'date' => $dateServ,
  1865.                                 'qty' => $unitsServ,
  1866.                                 'iva' => $item->getSrvIva(),
  1867.                                 'pax' => $item->getSrvPax(),
  1868.                                 'precioUnit' => $subnetoUnit,
  1869.                                 'subneto' => $subneto,
  1870.                                 'subtotal' => $subtotal,
  1871.                             );
  1872.                             break;
  1873.                         case 14//Technology
  1874.                             $pax $item->getSrvPax();
  1875.                             if (empty($pax) or $pax == "0") {
  1876.                                 $pax 1;
  1877.                             }
  1878. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  1879.                             $days 1;
  1880. //                        if ($days > 1){
  1881. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  1882. //                        } else {
  1883. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y');
  1884. //                        }
  1885.                             $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  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' => 'TecnologĆ­a',
  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 15//Assisstant
  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' => 'Asistente',
  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.                         case 16//DDR
  1940.                             $pax $item->getSrvPax();
  1941.                             if (empty($pax) or $pax == "0") {
  1942.                                 $pax 1;
  1943.                             }
  1944.                             $days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days 1);
  1945.                             if ($days 1) {
  1946.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
  1947.                             } else {
  1948.                                 $dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
  1949.                             }
  1950.                             $unitsServ $item->getSrvUnits();
  1951.                             if (empty($unitsServ) or $unitsServ == "0") {
  1952.                                 $unitsServ 1;
  1953.                             }
  1954.                             $subtotal $subtotalService $days $unitsServ $pax;
  1955.                             $subnetoUnit $subneto;
  1956.                             $subneto $subneto $days $unitsServ $pax;
  1957.                             $data_supplier['service'][$i] = array(
  1958.                                 'id' => $item->getId(),
  1959.                                 'serviceCatId' => $item->getSrvServiceCatId(),
  1960.                                 'serviceName' => $item->getSrvName(),
  1961.                                 'serviceType' => 'DDR',
  1962.                                 'date' => $dateServ,
  1963.                                 'qty' => $unitsServ,
  1964.                                 'iva' => $item->getSrvIva(),
  1965.                                 'pax' => $item->getSrvPax(),
  1966.                                 'precioUnit' => $subnetoUnit,
  1967.                                 'subneto' => $subneto,
  1968.                                 'subtotal' => $subtotal,
  1969.                             );
  1970.                             break;
  1971.                         default:
  1972.                             break;
  1973.                     }
  1974.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  1975.                     $subtotal round($subtotal2PHP_ROUND_HALF_UP);
  1976.                     $neto round($subneto2PHP_ROUND_HALF_UP);
  1977.                     $arrayItems[] = array(
  1978.                         'type' => 'Service',
  1979.                         'name' => $item->getSrvName(),
  1980.                         'amount' => $neto,
  1981.                         'iva' => $item->getSrvIva(),
  1982.                         'total' => $subtotal,
  1983.                     );
  1984.                 }
  1985.                 switch ($item->getSrvIva()) {
  1986.                     // Acumula IVA
  1987.                     case 21:
  1988.                         $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($item->getSrvIva() / 100));
  1989.                         break;
  1990.                     case 10:
  1991.                         $data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * ($item->getSrvIva() / 100));
  1992.                         break;
  1993.                     case 0:
  1994.                         break;
  1995.                     default:
  1996.                         break;
  1997.                 }
  1998.             } else {
  1999.                 // Es una proforma
  2000.                 if (is_null($item->getPrice()) or empty($item->getPrice())) {
  2001.                     $subtotal 0;
  2002.                     $neto 0;
  2003.                     $subtotalService 0;
  2004.                 } else {
  2005.                     $subtotalService $item->getPrice();
  2006.                     $subneto $item->getPrice();
  2007.                     // Commission
  2008.                     if ($item->getOpCommission() == '1') {
  2009.                         $subtotalService $subtotalService * (+ ($item->getCommission() / 100));
  2010.                         $subneto $subneto * (+ ($item->getCommission() / 100));
  2011.                     } else {
  2012.                         $subtotalService $subtotalService * (- ($item->getCommission() / 100));
  2013.                         $subneto $subneto * (- ($item->getCommission() / 100));
  2014.                     }
  2015.                     // Over
  2016.                     if ($item->getOpOver() == '1') {
  2017.                         $subtotalService $subtotalService $item->getOver();
  2018.                         $subneto $subneto $item->getOver();
  2019.                     } else {
  2020.                         $subtotalService $subtotalService $item->getOver();
  2021.                         $subneto $subneto $item->getOver();
  2022.                     }
  2023.                     // IVA
  2024.                     if ($item->getOpIva() == '1') {
  2025.                         $subtotalService $subtotalService * (+ ($item->getIva() / 100));
  2026.                     } else {
  2027.                         $subtotalService $item->getPrice();
  2028.                         $subneto = ($subneto 100) / (100 $item->getIva());
  2029.                     }
  2030.                     switch ($item->getServiceCatId()) {
  2031.                         case 1// Alojamiento
  2032.                             // el numero de noches $numNoches; precio unitario $subneto
  2033.                             $numNoches = (($item->getDateOutAt())->diff($item->getDateInAt()))->days;
  2034.                             // La personas no afectan este calculo
  2035.                             $subtotal $subtotalService $numNoches $item->getUnits();
  2036.                             $subnetoUnit $subneto;
  2037.                             $subneto $subneto $numNoches $item->getUnits();
  2038.                             $data_supplier['service'][$i] = array(
  2039.                                 'id' => $item->getId(),
  2040.                                 'serviceCatId' => $item->getServiceCatId(),
  2041.                                 'serviceName' => $item->getName(),
  2042.                                 'serviceType' => 'Hotel',
  2043.                                 'date' => ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y'),
  2044.                                 'qty' => $item->getUnits(),
  2045.                                 'iva' => $item->getIva(),
  2046.                                 'pax' => '-',
  2047.                                 'precioUnit' => $subnetoUnit,
  2048.                                 'subneto' => $subneto,
  2049.                                 'subtotal' => $subtotal,
  2050.                             );
  2051.                             break;
  2052.                         case 2//Actividades
  2053.                             // El nĆŗmero de personas es considerado en el calculo
  2054.                             $pax $item->getPax();
  2055.                             if (empty($pax) or $pax == "0") {
  2056.                                 $pax 1;
  2057.                             }
  2058.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2059.                             if ($days 1) {
  2060.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2061.                             } else {
  2062.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2063.                             }
  2064.                             $subtotal $subtotalService $days $item->getUnits();
  2065.                             $subnetoUnit $subneto;
  2066.                             $subneto $subneto $days $item->getUnits();
  2067.                             $data_supplier['service'][$i] = array(
  2068.                                 'id' => $item->getId(),
  2069.                                 'serviceCatId' => $item->getServiceCatId(),
  2070.                                 'serviceName' => $item->getName(),
  2071.                                 'serviceType' => 'Actividad',
  2072.                                 'date' => $dateServ,
  2073.                                 'qty' => $item->getUnits(),
  2074.                                 'iva' => $item->getIva(),
  2075.                                 'pax' => $item->getPax(),
  2076.                                 'precioUnit' => $subnetoUnit,
  2077.                                 'subneto' => $subneto,
  2078.                                 'subtotal' => $subtotal,
  2079.                             );
  2080.                             break;
  2081.                         case 3// AV
  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' => 'AV',
  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 4//Creative
  2114.                             $pax $item->getPax();
  2115.                             if (empty($pax) or $pax == "0") {
  2116.                                 $pax 1;
  2117.                             }
  2118.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  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' => 'Creativo',
  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 5//Cruise
  2146.                             $pax $item->getPax();
  2147.                             if (empty($pax) or $pax == "0") {
  2148.                                 $pax 1;
  2149.                             }
  2150.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days);
  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' => 'Crucero',
  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 6//Entertaiment
  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.                             if ($days 1) {
  2184.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2185.                             } else {
  2186.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2187.                             }
  2188.                             $unitsServ $item->getUnits();
  2189.                             if (empty($unitsServ) or $unitsServ == "0") {
  2190.                                 $unitsServ 1;
  2191.                             }
  2192.                             $subtotal $subtotalService $days $unitsServ $pax;
  2193.                             $subnetoUnit $subneto;
  2194.                             $subneto $subneto $days $unitsServ $pax;
  2195.                             $data_supplier['service'][$i] = array(
  2196.                                 'id' => $item->getId(),
  2197.                                 'serviceCatId' => $item->getServiceCatId(),
  2198.                                 'serviceName' => $item->getName(),
  2199.                                 'serviceType' => 'Entretenimiento',
  2200.                                 'date' => $dateServ,
  2201.                                 'qty' => $unitsServ,
  2202.                                 'iva' => $item->getIva(),
  2203.                                 'pax' => $item->getPax(),
  2204.                                 'precioUnit' => $subnetoUnit,
  2205.                                 'subneto' => $subneto,
  2206.                                 'subtotal' => $subtotal,
  2207.                             );
  2208.                             break;
  2209.                         case 7// Gifts
  2210.                             $pax $item->getPax();
  2211.                             if (empty($pax) or $pax == "0") {
  2212.                                 $pax 1;
  2213.                             }
  2214. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  2215.                             $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 8//Guide
  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' => 'Regalos',
  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 9//Itineraries
  2275.                             $pax $item->getPax();
  2276.                             if (empty($pax) or $pax == "0") {
  2277.                                 $pax 1;
  2278.                             }
  2279.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2280.                             if ($days 1) {
  2281.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2282.                             } else {
  2283.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2284.                             }
  2285.                             $unitsServ $item->getUnits();
  2286.                             if (empty($unitsServ) or $unitsServ == "0") {
  2287.                                 $unitsServ 1;
  2288.                             }
  2289.                             $subtotal $subtotalService $days $unitsServ $pax;
  2290.                             $subnetoUnit $subneto;
  2291.                             $subneto $subneto $days $unitsServ $pax;
  2292.                             $data_supplier['service'][$i] = array(
  2293.                                 'id' => $item->getId(),
  2294.                                 'serviceCatId' => $item->getServiceCatId(),
  2295.                                 'serviceName' => $item->getName(),
  2296.                                 'serviceType' => 'Itinerarios',
  2297.                                 'date' => $dateServ,
  2298.                                 'qty' => $unitsServ,
  2299.                                 'iva' => $item->getIva(),
  2300.                                 'pax' => $item->getPax(),
  2301.                                 'precioUnit' => $subnetoUnit,
  2302.                                 'subneto' => $subneto,
  2303.                                 'subtotal' => $subtotal,
  2304.                             );
  2305.                             break;
  2306.                         case 10//Lounge  -- No Aplica
  2307. //                        $pax = $item->getPax();
  2308. //                        if (empty($pax) or $pax == "0") {
  2309. //                            $pax = 1;
  2310. //                        }
  2311. //
  2312. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  2313. //                        if ($days > 1){
  2314. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2315. //                        } else {
  2316. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2317. //                        }
  2318. //
  2319. //                        $unitsServ = $item->getUnits();
  2320. //                        if (empty($unitsServ) or $unitsServ == "0") {
  2321. //                            $unitsServ = 1;
  2322. //                        }
  2323. //
  2324. //                        $subtotal = $subtotalService * $days * $unitsServ * $pax;
  2325. //                        $subnetoUnit = $subneto;
  2326. //                        $subneto = $subneto * $days * $unitsServ * $pax;
  2327. //
  2328. //                        $data_supplier['service'][$i] = array (
  2329. //                            'id' => $item->getId(),
  2330. //                            'serviceCatId' => $item->getServiceCatId(),
  2331. //                            'serviceName' => $item->getName(),
  2332. //                            'serviceType' => 'Itinerarios',
  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 11//Menu
  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' => 'MenĆŗ',
  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 12//Others
  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' => 'Otros',
  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 13//Transport
  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.                             if ($days 1) {
  2413.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2414.                             } else {
  2415.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2416.                             }
  2417.                             $unitsServ $item->getUnits();
  2418.                             if (empty($unitsServ) or $unitsServ == "0") {
  2419.                                 $unitsServ 1;
  2420.                             }
  2421.                             $subtotal $subtotalService $days $unitsServ $pax;
  2422.                             $subnetoUnit $subneto;
  2423.                             $subneto $subneto $days $unitsServ $pax;
  2424.                             $data_supplier['service'][$i] = array(
  2425.                                 'id' => $item->getId(),
  2426.                                 'serviceCatId' => $item->getServiceCatId(),
  2427.                                 'serviceName' => $item->getName(),
  2428.                                 'serviceType' => 'Transporte',
  2429.                                 'date' => $dateServ,
  2430.                                 'qty' => $unitsServ,
  2431.                                 'iva' => $item->getIva(),
  2432.                                 'pax' => $item->getPax(),
  2433.                                 'precioUnit' => $subnetoUnit,
  2434.                                 'subneto' => $subneto,
  2435.                                 'subtotal' => $subtotal,
  2436.                             );
  2437.                             break;
  2438.                         case 14//Technology
  2439.                             $pax $item->getPax();
  2440.                             if (empty($pax) or $pax == "0") {
  2441.                                 $pax 1;
  2442.                             }
  2443. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  2444.                             $days 1;
  2445. //                        if ($days > 1){
  2446. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2447. //                        } else {
  2448. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2449. //                        }
  2450.                             $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  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' => 'TecnologĆ­a',
  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 15//Assisstant
  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' => 'Asistente',
  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.                         case 16//DDR
  2505.                             $pax $item->getPax();
  2506.                             if (empty($pax) or $pax == "0") {
  2507.                                 $pax 1;
  2508.                             }
  2509.                             $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2510.                             if ($days 1) {
  2511.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
  2512.                             } else {
  2513.                                 $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2514.                             }
  2515.                             $unitsServ $item->getUnits();
  2516.                             if (empty($unitsServ) or $unitsServ == "0") {
  2517.                                 $unitsServ 1;
  2518.                             }
  2519.                             $subtotal $subtotalService $days $unitsServ $pax;
  2520.                             $subnetoUnit $subneto;
  2521.                             $subneto $subneto $days $unitsServ $pax;
  2522.                             $data_supplier['service'][$i] = array(
  2523.                                 'id' => $item->getId(),
  2524.                                 'serviceCatId' => $item->getServiceCatId(),
  2525.                                 'serviceName' => $item->getName(),
  2526.                                 'serviceType' => 'DDR',
  2527.                                 'date' => $dateServ,
  2528.                                 'qty' => $unitsServ,
  2529.                                 'iva' => $item->getIva(),
  2530.                                 'pax' => $item->getPax(),
  2531.                                 'precioUnit' => $subnetoUnit,
  2532.                                 'subneto' => $subneto,
  2533.                                 'subtotal' => $subtotal,
  2534.                             );
  2535.                             break;
  2536.                         default:
  2537.                             break;
  2538.                     }
  2539.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  2540.                     $subtotal round($subtotal2PHP_ROUND_HALF_UP);
  2541.                     $neto round($subneto2PHP_ROUND_HALF_UP);
  2542.                     $arrayItems[] = array(
  2543.                         'type' => 'Service',
  2544.                         'name' => $item->getName(),
  2545.                         'amount' => $neto,
  2546.                         'iva' => $item->getIva(),
  2547.                         'total' => $subtotal,
  2548.                     );
  2549.                 }
  2550.                 switch ($item->getIva()) {
  2551.                     // Acumula IVA
  2552.                     case 21:
  2553.                         $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($item->getIva() / 100));
  2554.                         break;
  2555.                     case 10:
  2556.                         $data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * ($item->getIva() / 100));
  2557.                         break;
  2558.                     case 0:
  2559.                         break;
  2560.                     default:
  2561.                         break;
  2562.                 }
  2563.             }
  2564.             $totales_neto_all $totales_neto_all $neto;
  2565.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  2566.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  2567.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  2568.             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
  2569.             // Acumula netos totales e IVA
  2570.             $service['neto'] = $service['neto'] + $neto;
  2571.             $service['sumSubT'] = $service['sumSubT'] + $subtotal;
  2572.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  2573.             $service['neto'] = round($service['neto'],2,PHP_ROUND_HALF_UP);
  2574.             $service['sumSubT'] = round($service['sumSubT'],2,PHP_ROUND_HALF_UP);
  2575.             $i++;
  2576.         }
  2577.         $data_supplier['serviceSubTotal'] = array(
  2578.             'neto' => $service['neto'],
  2579.             'sumSubT' => $service['sumSubT'],
  2580.         );
  2581.         $currency '€';
  2582.         $totales_total $totales_neto_all $data_iva['ivaMontoVeintiUno'] + $data_iva['ivaMontoDiez'];
  2583.         if (!empty($payments)) {
  2584.             $amount_pay $data_supplier['paymentSubTotal']['sumSubT'];
  2585.         } else {
  2586.             $amount_pay 0;
  2587.         }
  2588.         $totales_all $totales_total $amount_pay;
  2589.         if (empty($dateDocument)){
  2590.             $dateDocument = new DateTime('now');
  2591.         }
  2592.         $data = array(
  2593.             'id' => $fileId,
  2594.             'type' => $type,
  2595. //            'type' => '',
  2596.             'number' => $number,
  2597. //            'prefix' => $prefix,
  2598.             'prefix' => 'AVE-'.(new DateTime('now'))->format('dmy').'-'.$invoiceId,
  2599.             'date' => $dateDocument,
  2600.             'file' => $file,
  2601.             'token' => $file->getAccessKey(),
  2602.             'company' => $company,
  2603.             'clients' => $client,
  2604.             'arrayItems' => $arrayItems,
  2605.             'datasupplier' => $data_supplier,
  2606.             'currency' => $currency,
  2607.             'totales_neto' => $totales_neto_all,
  2608.             'bases_imponibles' => $data_iva,
  2609.             'totales' => $totales_total,
  2610.             'balance' => $totales_all,
  2611.             'paymentInvoice' => $amount_pay,
  2612.         );
  2613.         return $data;
  2614.     }
  2615.     private function sendTelegram($id$text )
  2616.     {
  2617.         $em $this->getDoctrine()->getManager();
  2618.         // No es necesario tener una tabla de TelegramUser para el modulo de AvExpress
  2619.         $telegUser $em->getRepository(MdvTelegramUser::class)->findOneByUserId($id);
  2620.         if (empty($telegUser)){return true;}
  2621.         $parameters = array(
  2622.             'chat_id' => $telegUser->getChatId(),
  2623.             'text' => $text,
  2624.         );
  2625.         $bot_token $telegUser->getBotToken();
  2626.         $url "https://api.telegram.org/bot$bot_token/sendMessage";
  2627.         if (!$curl curl_init()){
  2628.             exit();
  2629.         }
  2630.         curl_setopt($curl,CURLOPT_POST,true);
  2631.         curl_setopt($curl,CURLOPT_POSTFIELDS,$parameters);
  2632.         curl_setopt($curl,CURLOPT_URL,$url);
  2633.         curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
  2634.         $output curl_exec($curl);
  2635.         curl_close($curl);
  2636.         return true;
  2637.     }
  2638.     private function baseBenefits($fileId){
  2639.         $em $this->getDoctrine()->getManager();
  2640. //        $file = $em->getRepository(AveFiles::class)->findOneById($fileId);
  2641.         $productsInFile $em->getRepository(AveProductFile::class)->findByFileId($fileId);
  2642.         $benefitEuro 0;
  2643.         $benefitPerc 0;
  2644.         $totalSale 0;
  2645.         foreach ($productsInFile as $item){
  2646.             if(empty($item->getSupplierExt()) or ($item->getSupplierExt() == 'AV EXPRESS S.L.')){
  2647.                 // El proveedor es AV, el beneficio es 100%
  2648.                 $benefitEuro $benefitEuro $item->getSubTotalPrice();
  2649.             } else {
  2650.                 // El proveedor es externo, el beneficio lo determinan el over y la comision
  2651. //                $subTotalPriceExt = $item->getServicePrice() * $item->getUnits() * $item->getDays();        // Precio sin Over ni Comision
  2652. //                $benefitEuro = $benefitEuro + ($item->getSubTotalPrice() - $subTotalPriceExt);
  2653.                 $prdPrice $item->getServicePrice(); if (empty($prdPrice)){ $prdPrice 0; }
  2654.                 $prdUnits $item->getUnits(); if (empty($prdUnits)){ $prdUnits 1; }
  2655.                 $prdDays $item->getDays(); if (empty($prdDays)){ $prdDays 1; }
  2656.                 $prdPax $item->getPax(); if (empty($prdPax)){ $prdPax 1; }
  2657.                 $subTotalPriceExt $prdPrice $prdUnits $prdDays $prdPax;                             // Precio sin Over ni Comision
  2658.                 $benefitEuro $benefitEuro + ($item->getSubTotalPrice() - $subTotalPriceExt);
  2659.             }
  2660.             $totalSale $totalSale $item->getSubTotalPrice();
  2661.         }
  2662.         // Verificamos beneficios simplificados de proveedores
  2663.         $simplyBen $em->getRepository(AveBenefitsSupplier::class)->findByFileId($fileId);
  2664.         foreach ($simplyBen as $item){ $benefitEuro $benefitEuro $item->getBenefitSupplier(); }
  2665.         if (!($totalSale == 0)){
  2666.             $benefitPerc = ($benefitEuro 100)/$totalSale;
  2667.         }
  2668.         $data = array(
  2669.             'id' => $fileId,
  2670.             'benefitEuro' => $benefitEuro,
  2671.             'benefitPerc' => $benefitPerc,
  2672.         );
  2673.         return $data;
  2674.     }
  2675.     private function precioPorVariacionDeDias ($supplierService$productFile){
  2676.         // El precio unitario debe ser dividido en funcion de los dias que tiene InOut y no en funcion de los dias de Av Express
  2677.         $days = ($supplierService->getDateOutAt()->diff($supplierService->getDateInAt())->days)===$supplierService->getDateOutAt()->diff($supplierService->getDateInAt())->days +1;
  2678.         $newPrice $productFile->getSubTotalPrice() / ( $days );
  2679.         $newPrice $newPrice $supplierService->getUnits();
  2680.         $newPrice round($newPrice,2,PHP_ROUND_HALF_UP);
  2681.         return $newPrice;
  2682.     }
  2683.     private function rankquoteAvParaInOutService($idProduct){
  2684.         // 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
  2685.         // luego si es vacio repetimos para proformas en "ave_doc_proforma_items"
  2686.         // Devuelve el numero de RankQuoteAv considerando la posible asociacion por sala y ordenando segun el criterio (video, sonido, iluminacion, otros)
  2687.         $em $this->getDoctrine()->getManager();
  2688.         $rankquoteAv 1$proformaItemsInSameProforma = []; $boolFound false;
  2689.         $invoiceItem $em->getRepository(AveDocInvoiceItems::class)->findOneByPrdControlId($idProduct);
  2690.         $invoiceItemsInSameInvoice = (!empty($invoiceItem)) ? $em->getRepository(AveDocInvoiceItems::class)->findByInvoiceId($invoiceItem->getInvoiceId()) : array();
  2691.         if (empty($invoiceItemsInSameInvoice)){
  2692.             // No se encontraba facturado, buscamos en proforma el item y los elementos que esten en esa proforma
  2693.             $proformaItem $em->getRepository(AveDocProformaItems::class)->findOneByControlId($idProduct);
  2694.             $proformaItemsInSameProforma = (!empty($proformaItem)) ? $em->getRepository(AveDocProformaItems::class)->findByProformaId($proformaItem->getProformaId()) : array();
  2695.         }
  2696.         $arrayItems = empty($invoiceItemsInSameInvoice) ? $proformaItemsInSameProforma $invoiceItemsInSameInvoice;
  2697.         foreach ($arrayItems as $item){
  2698.             $idToCheck = empty($invoiceItemsInSameInvoice) ? $item->getControlId() : $item->getPrdControlId();
  2699.             if (!($idToCheck == $idProduct)){ if(!($boolFound)){ $rankquoteAv++;} } else { $boolFound true; }
  2700.         }
  2701.         // 001, 002, ... 010, 011, ..., 100, 101
  2702.         $rankquoteAv = ($rankquoteAv 100) ? (($rankquoteAv 10) ? '00'$rankquoteAv '0'$rankquoteAv) : $rankquoteAv;
  2703.         return $rankquoteAv;
  2704.     }
  2705.     private function messageOfChangesToAgent($message$proposalId){
  2706.         // $message mensaje a enviar a los agentes del proposal
  2707.         if ($proposalId  == 0){ return true; }
  2708.         $em $this->getDoctrine()->getManager();
  2709.         $proposal $em->getRepository(Proposal::class)->findOneById($proposalId);
  2710.         /* Obtengo usuario logueado */
  2711.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2712.         $user_id $user_logueado->getId();
  2713.         $agent $em->getRepository(User::class)->findOneById($user_id);
  2714.         $message 'El proposal <strong>#'.$proposalId.' '.$proposal->getName().'</strong>'.' ha sido modificacdo por el agente: '.$agent->getName().' '.$agent->getLastName().'<br><br><br>'.$message;
  2715.         $proposalAgents $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposalId);
  2716.         $mailArrayTo = [];
  2717.         if (!empty($agent)){ $mailArrayTo[$agent->getEmail()] = $agent->getEmail(); }
  2718.         if (!empty($proposalAgents)){
  2719.             if (!empty($proposalAgents->getAgOne())){
  2720.                 $agent $em->getRepository(User::class)->findOneById($proposalAgents->getAgOne());
  2721.                 $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  2722.             }
  2723.             if (!empty($proposalAgents->getAgTwo())){
  2724.                 $agent $em->getRepository(User::class)->findOneById($proposalAgents->getAgTwo());
  2725.                 $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  2726.             }
  2727.             if (!empty($proposalAgents->getAgThree())){
  2728.                 $agent $em->getRepository(User::class)->findOneById($proposalAgents->getAgThree());
  2729.                 $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  2730.             }
  2731.             if (!empty($proposalAgents->getAgFour())){
  2732.                 $agent $em->getRepository(User::class)->findOneById($proposalAgents->getAgFour());
  2733.                 $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  2734.             }
  2735.         }
  2736.         if (!empty($mailArrayTo)){
  2737.             $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  2738.             $replyTo = [];
  2739.             foreach ($mailArrayTo as $item){ $replyTo[$item] = $item; }
  2740.             $agentMail $agent->getEmail();
  2741.             //Se prepara el correo con los agentes a notificar
  2742.             $firmGmail $agent->getFirmGmail();
  2743.             $data = array(
  2744.                 'body' => $message,
  2745.                 'firm' => $firmGmail,
  2746.             );
  2747.             // EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
  2748.             $transporter = new Swift_SmtpTransport();
  2749.                 $transporter->setHost('smtp.gmail.com')
  2750.                 ->setEncryption('ssl')//ssl / tls
  2751.                 ->setPort(465)// 465 / 587
  2752.                 ->setUsername('desarrollo@develup.solutions')
  2753.                 ->setPassword('utvh hzoi wfdo ztjs');
  2754.             $mailer = new Swift_Mailer($transporter);
  2755.             $message = new Swift_Message();
  2756.                 $message->setSubject('Actualización de servicios AvExpress del proposal: '$proposalId)
  2757.                 ->setSender($agentMail)
  2758.                 ->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
  2759.                 ->setReplyTo($agentMail)
  2760.                 ->setTo($replyTo)
  2761.                 ->setBody(
  2762.                     $this->renderView(
  2763.                         'mail/structure-mail.html.twig',
  2764.                         array('data' => $data)
  2765.                     ),
  2766.                     'text/html'
  2767.                 );
  2768.             $mailer->send($message);
  2769.         }
  2770.         return true;
  2771.     }
  2772. };