src/MDS/AvexpressBundle/Controller/ProductsFilesController.php line 274

Open in your IDE?
  1. <?php
  2. namespace App\MDS\AvexpressBundle\Controller;
  3. use App\Entity\Cities;
  4. use App\Entity\Client;
  5. use App\Entity\Configuration;
  6. use App\Entity\Country;
  7. use App\Entity\Destination;
  8. use App\Entity\Regions;
  9. use App\Entity\SettingsCompany;
  10. use App\Entity\Supplier;
  11. use App\Entity\User;
  12. use App\MDS\AvexpressBundle\Entity\AveDocInvoiceItems;
  13. use App\MDS\AvexpressBundle\Entity\AveDocProforma;
  14. use App\MDS\AvexpressBundle\Entity\AveDocProformaItems;
  15. use App\MDS\AvexpressBundle\Entity\AveFiles;
  16. use App\MDS\AvexpressBundle\Entity\AveProduct;
  17. use App\MDS\AvexpressBundle\Entity\AveProductFileLocationNames;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use App\MDS\AvexpressBundle\Entity\AveProductFile;
  22. use App\MDS\AvexpressBundle\Entity\AveTemplate;
  23. use App\MDS\AvexpressBundle\Entity\AveTemplateItems;
  24. use App\MDS\DevelupBundle\Entity\MdvTelegramUser;
  25. use App\MDS\EventsBundle\Entity\Proposal;
  26. use App\MDS\EventsBundle\Entity\ProposalAgents;
  27. use App\MDS\EventsBundle\Entity\ProposalInvoice;
  28. use App\MDS\EventsBundle\Entity\ProposalSupplierControl;
  29. use App\MDS\EventsBundle\Entity\ProposalSupplierServices;
  30. use App\MDS\GreenPatioBundle\Entity\ReservationInvoice;
  31. use Swift_Mailer;
  32. use Swift_Message;
  33. use Swift_SmtpTransport;
  34. use Symfony\Contracts\Translation\TranslatorInterface;
  35. class ProductsFilesController extends AbstractController
  36. {
  37.     private $translator;
  38.     public function __construct(TranslatorInterface $translator) {
  39.         $this->translator $translator;
  40.     }
  41.     
  42.     /**
  43.      * @Route("/productfileadd/",  name="ave_add_productfile")
  44.      * Agregar un producto a un expediente
  45.      */
  46.     public function addProductFileActionRequest $request)
  47.     {
  48.         $em $this->getDoctrine()->getManager();
  49.         $clients $em->getRepository(Client::class)->findAll();
  50.         $newRequest $request->request->get('productfile');
  51.         $editFile $em->getRepository(AveFiles::class)->findOneById($newRequest['fileId']);
  52.         $mdvProductSelected $em->getRepository(AveProduct::class)->findOneById($newRequest['productId']);
  53.         $logTelegram false;
  54.         /* Obtengo usuario logueado */
  55.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  56.         $user_id $user_logueado->getId();
  57.         $newProductFile = new AveProductFile();
  58.         $newProductFile->setProductName($mdvProductSelected->getName());
  59.         $newProductFile->setProductId($mdvProductSelected->getId());
  60.         $newProductFile->setType($mdvProductSelected->getType());
  61.         if (!empty($newRequest['servicePrice'])){
  62.             $newProductFile->setServicePrice($newRequest['servicePrice']);
  63.         } else {
  64.             // Si el precio viene vacio tomamos el valor por defecto del producto
  65.             $newProductFile->setServicePrice($mdvProductSelected->getPrice());
  66.         }
  67.         $newProductFile->setDescription($mdvProductSelected->getDescription());
  68.         $newProductFile->setFileId($newRequest['fileId']);
  69.         if (!empty($newRequest['dateStart'])) { $newProductFile->setDateStart(new \DateTime($newRequest['dateStart'].' '.$newRequest['hourStart'])); }
  70.         if (!empty($newRequest['dateEnd'])) { $newProductFile->setDateEnd(new \DateTime($newRequest['dateStart'].' '.$newRequest['hourEnd'])); }
  71.         $dataDates $this->obtenerFechas($newRequest['fileId'], $newProductFile->getDateStart(), $newProductFile->getDateEnd());
  72.         $newProductFile->setDateStart($dataDates['dateStart']);
  73.         $newProductFile->setDateEnd($dataDates['dateEnd']);
  74.         $newProductFile->setDateInAt($dataDates['dateStart']);
  75.         $newProductFile->setDateOutAt($dataDates['dateEnd']);
  76.         $newProductFile->setCreatedId($user_id);
  77.         $newProductFile->setUpdatedId($user_id);
  78.         $newProductFile->setCreatedAt(new \DateTime("now"));
  79.         $newProductFile->setUpdatedAt(new \DateTime("now"));
  80.         $newProductFile->setOpIva(true);
  81.         $newProductFile->setIva('21');
  82.         if (!empty($newRequest['supplierExt'])){
  83.             $supplier $em->getRepository(Supplier::class)->findOneById($newRequest['supplierExt']);
  84.             $newProductFile->setSupplierExt($supplier->getName());
  85.             $newProductFile->setSupplierExtId($newRequest['supplierExt']);
  86.         } else {
  87.             $newProductFile->setSupplierExt(null);
  88.             $newProductFile->setSupplierExtId(null);
  89.         }
  90.         if (empty($newProductFile->getType())){ $newProductFile->setType('Otros'); }
  91.         $dataRankAv $this->obtenerRankAv($newRequest['fileId']);
  92.         $newProductFile->setRankAv($dataRankAv);
  93.         $newProductFile->setDays((($newProductFile->getDateEnd()->diff($newProductFile->getDateStart()))->days 1));
  94.         $em->persist($newProductFile);
  95.         $em->flush();
  96.         $products $em->getRepository(AveProduct::class)->findAll();
  97.         $data $this->calculosFile($newRequest['fileId'], null0'File');
  98.         $sumatoriaTotalNet 0;
  99.         $sumatoriaTotalVat 0;
  100.         $sumatoriaTotal 0;
  101.         $resultados = array(
  102.             'totalNeto' => $sumatoriaTotalNet,
  103.             'vat' => $sumatoriaTotalVat,
  104.             'total' => $sumatoriaTotal,
  105.         );
  106.         $productInFile $em->getRepository(AveProductFile::class)->findByFileId($newRequest['fileId']);
  107.         $numeroItems sizeof($productInFile);
  108.         $file $editFile;
  109.         // Si hay proposal se debe actualizar en el expediente de Eventos
  110.         if (!empty($file->getIdProposal()) and is_numeric($file->getIdProposal())){
  111.             // Buscamos el destino donde se encuentre Avexpress y ahi agregamos el servicio, si no se encuentra no se agregara el servicio
  112.             $control $em->getRepository(ProposalSupplierControl::class)->findOneBy(
  113.                 array(
  114.                     'supplierId' => 80,                                          // El supplier 80 es Avexpress
  115.                     'proposalId' => $file->getIdProposal(),
  116.                 )
  117.             );
  118.             if (!empty($control)){
  119.                 // Existe un destino con Avexpress como proveedor, hay se agregara el servicio
  120.                 $prpInv $em->getRepository(ProposalInvoice::class)->findOneByProposalId($file->getIdProposal());
  121.                 if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
  122.                     $logTelegram true;
  123.                     $service = new ProposalSupplierServices();
  124.                     $service->setServiceIdFather(0);
  125.                     $service->setControlId($control->getId());
  126.                     $service->setProposalId($file->getIdProposal());
  127.                     $service->setDestinationId($control->getDestinoId());
  128.                     $service->setSupplierId(80);
  129.                     $service->setIdeaId(null);
  130.                     $service->setServiceId($newProductFile->getProductId());
  131.                     $service->setServiceCatName('Av');
  132.                     $service->setServiceCatId(3);
  133.                     $service->setName($newProductFile->getProductName());
  134. //                $service->setPrice($mdvProductSelected->getPrice() * 1.21);
  135.                     $priceInOut $mdvProductSelected->getSubTotalPrice() / $mdvProductSelected->getPax();      // Se devuelve el calculo dividiendo entre personas
  136.                     $priceInOut $priceInOut $mdvProductSelected->getUnits();                                // Se devuelve el calculo dividiendo entre cantidades
  137.                     $priceInOut $priceInOut round($mdvProductSelected->getDays());                          // Se devuelve el calculo dividiendo entre dias, se redondea por si es 1.5
  138.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  139.                     $priceInOut round($priceInOut2PHP_ROUND_HALF_UP);
  140.                     $service->setPrice($priceInOut);
  141. //                $service->setPrice($mdvProductSelected->getPrice());
  142.                     $service->setCurrency(null);
  143.                     $service->setUnits(1);
  144.                     $service->setCommission(0);
  145.                     $service->setOver(0);
  146.                     $service->setIva(21);
  147.                     $service->setPax(0);
  148.                     $service->setHour(null);
  149.                     $service->setDateInAt(new \DateTime("now"));
  150.                     $service->setDateOutAt(new \DateTime("now"));
  151.                     $service->setDirectPayment(0);
  152.                     $service->setStatus('Pending');
  153.                     $service->setStatusinternal('Additional');
  154.                     $service->setPreCommission(null);
  155.                     $service->setPreIva(null);
  156.                     $service->setDateBlockLimit(null);
  157.                     $service->setOpCommission(1);
  158.                     $service->setOpOver(1);
  159.                     $service->setOpIva(1);
  160.                     $service->setBreakdown(0);
  161.                     $service->setIsFather(0);
  162.                     $service->setRank(1);
  163.                     $service->setOriginalopIva(1);
  164.                     $service->setOriginalIva(null);
  165.                     $service->setOriginalPrice(null);
  166.                     $service->setStatusRec('normal');
  167.                     $service->setAssistantId(null);
  168.                     $service->setCreatedId($user_id);
  169.                     $service->setUpdatedId($user_id);
  170.                     $service->setCreatedAt(new \DateTime("now"));
  171.                     $service->setUpdatedAt(new \DateTime("now"));
  172.                     $em->persist($service);
  173.                     $em->flush();
  174.                     // Guardamos el ID del servicio (Eventos) asociado al producto (AvExpress)
  175.                     $newProductFile->setOriginId($service->getId());
  176.                     $em->persist($newProductFile);
  177.                     $em->flush();
  178.                 }
  179.             }
  180.         }
  181.         //INICIO: Notificamos al agente por Telegram
  182.         if ($logTelegram){
  183.             //Buscamos todos los agentes del proposal
  184.             $proposalAgents $em->getRepository(ProposalAgents::class)->findOneByIdProp($file->getIdProposal());
  185.             //Buscamos el Destino
  186.             $proposalDestino $em->getRepository(Destination::class)->findOneById($control->getDestinoId());
  187.             //Buscamos el agente de AvExpress
  188.             $userData $em->getRepository(User::class)->findOneById($user_id);
  189.             if (!empty($proposalAgents) and !($user_id == 22)){
  190.                 if ((!empty($proposalAgents->getAgOne())) and (!($proposalAgents->getAgOne() == 0))){
  191.                     $this->sendTelegram($proposalAgents->getAgOne(),'1. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (Nuevo Servicio) __ ID: '.$file->getIdProposal().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  192.                 }
  193.                 if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
  194.                     $this->sendTelegram($proposalAgents->getAgTwo(),'2. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (Nuevo Servicio) __ ID: '.$file->getIdProposal().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  195.                 }
  196.                 if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
  197.                     $this->sendTelegram($proposalAgents->getAgThree(),'3. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (Nuevo Servicio) __ ID: '.$file->getIdProposal().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  198.                 }
  199.                 if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
  200.                     $this->sendTelegram($proposalAgents->getAgFour(),'4. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (Nuevo Servicio) __ ID: '.$file->getIdProposal().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  201.                 }
  202.             }
  203.         }
  204.         //FIN: Notificamos al agente por Telegram
  205.         return $this->render('MDS/AvexpressBundle/Avexpress/edit-files.html.twig',
  206.             array(
  207.                 'id' => $newRequest['fileId'],
  208.                 'clients' => $clients,
  209.                 'clientId' => $editFile->getClient(),
  210.                 'file' => $editFile,
  211.                 'products' => $products,
  212.                 'numeroItems' => $numeroItems,
  213.                 'arrayProductFile' => $data['datasupplier']['product'],
  214.                 'services' => null,
  215.                 'facturas' => null,
  216.                 'paymentNotIvoiced' => null,
  217.                 'paymentsAll' => null,
  218.                 'resultados' => $resultados,
  219.                 'totales_global_con_iva' => $data['totales'], //$data['totales_global_con_iva'],
  220.                 'totales_global_iva' => $data['bases_imponibles']['ivaMontoVeintiUno'], //$data['totales_global_iva'],
  221.                 'totales_global_neto' => $data['totales_neto'], //$data['totales_global_neto'],
  222.                 'totales_global_servicios_con_iva' => 0//$data['totales_global_servicios_con_iva'],
  223.                 'totales_global_servicios_neto' => 0//$data['totales_global_servicios_neto'],
  224.                 'totales_global_servicios_iva' => 0//$data['totales_global_servicios_iva'],
  225.                 'sumatoria_totales_global_con_iva' => 0//$data['sumatoria_totales_global_con_iva'],
  226.                 'sumatoria_totales_global_neto' => 0//$data['sumatoria_totales_global_neto'],
  227.                 'sumatoria_totales_global_iva' => 0//$data['sumatoria_totales_global_iva'],
  228.             ));
  229.     }
  230.     /**
  231.      * @Route("/productfiledelete/{id}",  name="ave_delete_productfile")
  232.      * Eliminar un producto de un expediente
  233.      */
  234.     public function deleteProductFileAction($idRequest $request)
  235.     {
  236.         $em $this->getDoctrine()->getManager();
  237.         $mdvProductSelected $em->getRepository(AveProductFile::class)->findOneById($id);
  238.         $id $mdvProductSelected->getFileId();
  239.         $logTelegram false;
  240.         /* Obtengo usuario logueado */
  241.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  242.         $user_id $user_logueado->getId();
  243.         //INICIO: Si hay un ID origin se debe eliminar en Eventos
  244.         if (!empty($mdvProductSelected->getOriginId())){
  245.             $logTelegram true;
  246.             $delete $em->getRepository(ProposalSupplierServices::class)->findOneById($mdvProductSelected->getOriginId());
  247.             if (!empty($delete)) {
  248.                 $destinationId $delete->getDestinationId();
  249.                 $proposalId $delete->getProposalId();
  250.                 $prpInv $em->getRepository(ProposalInvoice::class)->findOneByProposalId($delete->getProposalId());
  251.                 if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
  252.                     if (!empty($delete)) {
  253.                         $delete_sub $em->getRepository(ProposalSupplierServices::class)->findByServiceIdFather($delete->getId());
  254.                         foreach ($delete_sub as $deletesub) {
  255.                             $em->remove($deletesub);
  256.                         }
  257.                         $em->remove($delete);
  258.                         $em->flush();
  259.                     }
  260.                 }
  261.             } else {
  262.                 // El servicio origen no se encontro
  263.                 $logTelegram false;
  264.             }
  265.         }
  266.         //INICIO: Notificamos al agente por Telegram
  267.         if ($logTelegram){
  268.             //Buscamos todos los agentes del proposal
  269.             $proposalAgents $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposalId);
  270.             //Buscamos el Destino
  271.             $proposalDestino $em->getRepository(Destination::class)->findOneById($destinationId);
  272.             //Buscamos el agente de Develup
  273.             $userData $em->getRepository(User::class)->findOneById($user_id);
  274.             if (!empty($proposalAgents)){
  275.                 if ((!empty($proposalAgents->getAgOne())) and (!($proposalAgents->getAgOne() == 0))){
  276.                     $this->sendTelegram($proposalAgents->getAgOne(),'1. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  277.                 }
  278.                 if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
  279.                     $this->sendTelegram($proposalAgents->getAgTwo(),'2. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  280.                 }
  281.                 if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
  282.                     $this->sendTelegram($proposalAgents->getAgThree(),'3. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  283.                 }
  284.                 if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
  285.                     $this->sendTelegram($proposalAgents->getAgFour(),'4. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  286.                 }
  287.             }
  288.         }
  289.         //FIN: Notificamos al agente por Telegram
  290.         //FIN: Si hay un ID origin se debe eliminar en Eventos
  291.         //INICIO: Si el producto se encuentra dentro de una proforma (Ave_Doc_Proforma_Items) se elimina tambiĆ©n
  292.         $productInProforma $em->getRepository(AveDocProformaItems::class)->findByControlId($mdvProductSelected->getId());
  293.         if (!empty($productInProforma)){
  294.             foreach ($productInProforma as $item){
  295.                 $item->setFileId((-1) * $item->getFileId());      // No lo vamos a eliminar, apuntarĆ” al fileId en negativo
  296.                 $em->persist($item);
  297.                 // $em->remove($item);
  298.                 $em->flush();
  299.             }
  300.         }
  301.         //FIN: Si el producto se encuentra dentro de una proforma (Ave_Doc_Proforma_Items) se elimina tambiĆ©n
  302.         $mdvProductSelected->setFileId((-1) * $mdvProductSelected->getFileId());      // No lo vamos a eliminar, apuntarĆ” al fileId en negativo
  303.         $em->persist($mdvProductSelected);
  304.         // $em->remove($mdvProductSelected);
  305.         $em->flush();
  306.         return $this->redirectToRoute('ave_edit_file', array('id' => $id));
  307.     }
  308.     /**
  309.      * @Route("/productfileproformadelete/{id}",  name="ave_delete_productfileproforma")
  310.      * Eliminar un producto de una proforma
  311.      */
  312.     public function deleteProductFileInProformaAction($idRequest $request)
  313.     {
  314.         $em $this->getDoctrine()->getManager();
  315.         $mdvProductSelected $em->getRepository(AveDocProformaItems::class)->findOneByControlId($id);
  316.         $id $mdvProductSelected->getFileId();
  317.         $em->remove($mdvProductSelected);
  318.         $em->flush();
  319.         return $this->redirectToRoute('ave_edit_file', array('id' => $id));
  320.     }
  321.     /**
  322.      * @Route("/updateproductfilegrid/",  name="ave_updategrid_productfile")
  323.      * Actualizar grid de productos de un expediente
  324.      */
  325.     public function updategridProductFileAction(Request $request)
  326.     {
  327.         $em $this->getDoctrine()->getManager();
  328.         $newRequest $request->request->get('product');
  329.         $fileId $request->request->get('fileId');
  330.         $logTelegram false;
  331.         $srvInconsistentes '';                    // Mensaje de alerta por inconsistencia en los servicios
  332.         $txtOfChanges '';
  333.         /* Obtengo usuario logueado */
  334.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  335.         $user_id $user_logueado->getId();
  336.         foreach ($newRequest as $key => $item) {
  337.             $txtWarning '';
  338.             if (!empty($item['name'])){
  339.                 if (is_numeric($item['price'])){
  340.                     $logTelegram true;
  341.                     $productInFile $em->getRepository(AveProductFile::class)->findOneById($key);
  342.                     $productInFile->setProductName($item['name']);
  343.                     $productInFile->setServicePrice($item['price']);
  344.                     $productInFile->setUnits($item['units']);
  345.                     $productInFile->setDays($item['days']);
  346.                     $productInFile->setSubTotalPrice($item['price'] * $item['units'] *$item['days']);
  347.                     // *** Primero se debe calcular la comision y luego el over ***
  348.                     // Calculo de comision
  349.                     if ($productInFile->getOpCommission()){
  350.                         //Over positivo
  351.                         if (!($productInFile->getCommission() == 0) and is_numeric($productInFile->getCommission())){
  352.                             $suma $productInFile->getCommission()/100;
  353.                             $suma $productInFile->getSubTotalPrice() * $suma;
  354.                             $productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() + $suma);
  355.                         }
  356.                     } else {
  357.                         //Over negativo
  358.                         if (!($productInFile->getCommission() == 0) and is_numeric($productInFile->getCommission())){
  359.                             $suma $productInFile->getCommission()/100;
  360.                             $suma $productInFile->getSubTotalPrice() * $suma;
  361.                             if ($productInFile->getSubTotalPrice() > $suma){            // La comision a restar no puede ser mayor que el precio total
  362.                                 $productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() - $suma);
  363.                             }
  364.                         }
  365.                     }
  366.                     // Calculo con OVER
  367.                     if ($productInFile->getOpOver()){
  368.                         //Over positivo
  369.                         if (!($productInFile->getOver() == 0) and is_numeric($productInFile->getOver())){
  370.                             $productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() + $productInFile->getOver());
  371.                         }
  372.                     } else {
  373.                         //Over negativo
  374.                         if (!($productInFile->getOver() == 0) and is_numeric($productInFile->getOver())){
  375.                             $productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() + ((-1) * $productInFile->getOver()));
  376.                         }
  377.                     }
  378.                     // IVA
  379. //                    $productInFile->setDescription($item['description']);
  380.                     $productInFile->setUpdatedId($user_id);
  381.                     $productInFile->setUpdatedAt(new \DateTime("now"));
  382.                     //Si las fechas de inicio y fin no coinciden con el campo dias se debe enviar alerta
  383.                     $txtWarning = ($productInFile->getDateOutAt()->diff($productInFile->getDateInAt()))->days <> $productInFile->getDays() ? '<br>'.$productInFile->getProductName() : '';
  384.                     if (!empty($txtWarning)){
  385.                         if (empty($srvInconsistentes)){ $srvInconsistentes 'Hay inconsistencias en: '.'<br>'.$txtWarning; } else { $srvInconsistentes $srvInconsistentes.'<br>'.$txtWarning; }
  386.                     }
  387.                     $em->persist($productInFile);
  388.                     $em->flush();
  389.                     //INICIO: Duplicamos en Eventos
  390.                     $proposalId 0;
  391.                     if (!empty($productInFile->getOriginId())) {
  392.                         $serviceEvent $em->getRepository(ProposalSupplierServices::class)->findOneById($productInFile->getOriginId());
  393.                         $oldServiceEvent = array(
  394.                             'activityId' => $serviceEvent->getActivityId(),
  395.                             'assistantId' => $serviceEvent->getAssistantId(),
  396.                             'breakdown' => $serviceEvent->getBreakdown(),
  397.                             'commission' => $serviceEvent->getCommission(),
  398.                             'controlId' => $serviceEvent->getControlId(),
  399.                             'currency' => $serviceEvent->getCurrency(),
  400.                             'dateBlockLimit' => $serviceEvent->getDateBlockLimit(),
  401.                             'dateInAt' => $serviceEvent->getDateInAt(),
  402.                             'dateOutAt' => $serviceEvent->getDateOutAt(),
  403.                             'destinationId' => $serviceEvent->getDestinationId(),
  404.                             'directPayment' => $serviceEvent->getDirectPayment(),
  405.                             'hour' => $serviceEvent->getHour(),
  406.                             'ideaId' => $serviceEvent->getIdeaId(),
  407.                             'isFather' => $serviceEvent->getIsFather(),
  408.                             'iva' => $serviceEvent->getIva(),
  409.                             'name' => $serviceEvent->getName(),
  410.                             'opCommission' => $serviceEvent->getOpCommission(),
  411.                             'opIva' => $serviceEvent->getOpIva(),
  412.                             'opOver' => $serviceEvent->getOpOver(),
  413.                             'originalIva' => $serviceEvent->getOriginalIva(),
  414.                             'originalPrice' => $serviceEvent->getOriginalPrice(),
  415.                             'originalopIva' => $serviceEvent->getOriginalopIva(),
  416.                             'over' => $serviceEvent->getOver(),
  417.                             'pax' => $serviceEvent->getPax(),
  418.                             'preCommission' => $serviceEvent->getPreCommission(),
  419.                             'preIva' => $serviceEvent->getPreIva(),
  420.                             'price' => $serviceEvent->getPrice(),
  421.                             'proposalId' => $serviceEvent->getProposalId(),
  422.                             'rank' => $serviceEvent->getRank(),
  423.                             'serviceCatId' => $serviceEvent->getServiceCatId(),
  424.                             'serviceCatName' => $serviceEvent->getServiceCatName(),
  425.                             'serviceId' => $serviceEvent->getServiceId(),
  426.                             'serviceIdFather' => $serviceEvent->getServiceIdFather(),
  427.                             'status' => $serviceEvent->getStatus(),
  428.                             'statusRec' => $serviceEvent->getStatusRec(),
  429.                             'statusinternal' => $serviceEvent->getStatusinternal(),
  430.                             'supplierId' => $serviceEvent->getSupplierId(),
  431.                             'units' => $serviceEvent->getUnits(),
  432.                         );
  433.                         if (!empty($serviceEvent)) {
  434.                             $proposalId $serviceEvent->getProposalId();
  435.                             $prpInv $em->getRepository(ProposalInvoice::class)->findOneByProposalId($serviceEvent->getProposalId());
  436.                             if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
  437. //                            $serviceEvent->setUnits(1);                             // Las unidades no se pueden replicar o se genera un sobre calculo del lado de Evenetos
  438.                                 $serviceEvent->setName($productInFile->getProductName());
  439.                                 $priceInOut $productInFile->getSubTotalPrice();
  440.                                 if (!($productInFile->getPax() == 0)) {
  441.                                     $priceInOut $priceInOut $productInFile->getPax();                    // Se devuelve el calculo dividiendo entre personas
  442.                                 }
  443.                                 if (!($productInFile->getUnits() == 0)) {
  444.                                     $priceInOut $priceInOut $productInFile->getUnits();                  // Se devuelve el calculo dividiendo entre cantidades
  445.                                 }
  446.                                 if (!($productInFile->getDays() == 0)) {
  447.                                     $priceInOut $priceInOut round($productInFile->getDays());            // Se devuelve el calculo dividiendo entre dias, se redondea por si es 1.5
  448.                                 }
  449.                                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  450.                                 $priceInOut round($priceInOut2PHP_ROUND_HALF_UP);
  451.                                 $serviceEvent->setPrice($priceInOut);
  452.                                 // Se verifican los precios en ambas partes (AV Express e InOut)
  453.                                 if (!($serviceEvent->getPrice() == $productInFile->getServicePrice())) {
  454.                                     // Si ambos precios unitarios son distintos se ha modificado el numero de dĆ­as en Av Express
  455.                                     $newPriceInOut $this->precioPorVariacionDeDias($serviceEvent$productInFile);
  456.                                     $serviceEvent->setPrice($newPriceInOut);
  457.                                 } else {
  458.                                     // si son iguales tambien se deben verificar el numero de dias
  459.                                     if (!(($serviceEvent->getDateOutAt()->diff($serviceEvent->getDateInAt())->days 1) == $productInFile->getDays())) {
  460.                                         $newPriceInOut $this->precioPorVariacionDeDias($serviceEvent$productInFile);
  461.                                         $serviceEvent->setPrice($newPriceInOut);
  462.                                     }
  463.                                 }
  464.                                 $serviceEvent->setCurrency($productInFile->getCurrency());
  465.                                 $serviceEvent->setUnits($productInFile->getUnits());
  466. //                            $serviceEvent->setIva(21);
  467.                                 if (empty($productInFile->getPax())) {
  468.                                     $serviceEvent->setPax(1);
  469.                                 } else {
  470.                                     $serviceEvent->setPax($productInFile->getPax());
  471.                                 }
  472.                                 $serviceEvent->setDateInAt($productInFile->getDateInAt());
  473.                                 $serviceEvent->setDateOutAt($productInFile->getDateOutAt());
  474.                                 //Verificamos cambios e informamos al agente del proposal
  475.                                 $boolChanges false;
  476.                                 if (!($serviceEvent->getRank() == $oldServiceEvent['rank'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Orden</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['rank'].', su nuevo valor es: '.$serviceEvent->getRank().'<br>'$boolChanges true; }
  477.                                 if (!($serviceEvent->getName() == $oldServiceEvent['name'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Nombre</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['name'].', su nuevo valor es: '.$serviceEvent->getName().'<br>'$boolChanges true; }
  478.                                 if (!($serviceEvent->getPrice() == $oldServiceEvent['price'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Precio</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['price'].', su nuevo valor es: '.$serviceEvent->getPrice().'<br>'$boolChanges true; }
  479.                                 if (!($serviceEvent->getCurrency() == $oldServiceEvent['currency'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Moneda</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['currency'].', su nuevo valor es: '.$serviceEvent->getCurrency().'<br>'$boolChanges true; }
  480.                                 if (!($serviceEvent->getUnits() == $oldServiceEvent['units'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Cantidad</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['units'].', su nuevo valor es: '.$serviceEvent->getUnits().'<br>'$boolChanges true; }
  481.                                 if (!($serviceEvent->getPax() == $oldServiceEvent['pax'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Personas</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['pax'].', su nuevo valor es: '.$serviceEvent->getPax().'<br>'$boolChanges true; }
  482.                                 if (!($serviceEvent->getOpOver() == $oldServiceEvent['opOver'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getOpOver().'<br>'$boolChanges true; }
  483.                                 if (!($serviceEvent->getOver() == $oldServiceEvent['over'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Over</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['over'].', su nuevo valor es: '.$serviceEvent->getOver().'<br>'$boolChanges true; }
  484.                                 if (!($serviceEvent->getOpCommission() == $oldServiceEvent['opCommission'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getOpCommission().'<br>'$boolChanges true; }
  485.                                 if (!($serviceEvent->getCommission() == $oldServiceEvent['commission'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>ComisiĆ³n" ha sido modificado. Su valor era: '.$oldServiceEvent['commission'].', su nuevo valor es: '.$serviceEvent->getCommission().'<br>'$boolChanges true; }
  486.                                 if (!($serviceEvent->getOpIva() == $oldServiceEvent['opIva'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getOpIva().'<br>'$boolChanges true; }
  487.                                 if (!($serviceEvent->getIva() == $oldServiceEvent['iva'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Iva</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['iva'].', su nuevo valor es: '.$serviceEvent->getIva().'<br>'$boolChanges true; }
  488.                                 if (!($serviceEvent->getDateInAt()->format('H:i') == $oldServiceEvent['dateInAt']->format('H:i'))){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateInAt()->format('H:i').'<br>'$boolChanges true; }
  489.                                 if (!($serviceEvent->getDateInAt()->format('Ymd') == $oldServiceEvent['dateInAt']->format('Ymd'))){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateInAt()->format('d/m/Y').'<br>'$boolChanges true; }
  490.                                 if (!($serviceEvent->getDateOutAt()->format('H:i') == $oldServiceEvent['dateOutAt']->format('H:i'))){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateOutAt()->format('H:i').'<br>'$boolChanges true; }
  491.                                 if (!($serviceEvent->getDateOutAt()->format('Ymd') == $oldServiceEvent['dateOutAt']->format('Ymd'))){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateOutAt()->format('d/m/Y').'<br>'$boolChanges true; }
  492.                                 $em->persist($serviceEvent);
  493.                                 $em->flush();
  494.                             }
  495.                         }
  496.                     }
  497.                     //FIN: Duplicamos en Eventos
  498.                 }
  499.             }
  500.         }
  501.         // Notificamos al agente de InOut si se hicieron actualizaciones en los servicios desde AvExpress
  502.         if (!empty($txtOfChanges)) { $this->messageOfChangesToAgent($txtOfChanges$proposalId); }
  503.         $file $em->getRepository(AveFiles::class)->findOneById($fileId);
  504.         $event 'Servicios guardados correctamente.';
  505.         $successMessage $this->translator->trans($event);
  506.         $this->addFlash('mensajeav'$successMessage);
  507.         if (!empty($srvInconsistentes) and !empty($file->getIdProposal())){ $this->addFlash('mensajeaverror'$srvInconsistentes); }
  508.         // Si el proposalId esta vacio no se notifica a nadie por Telegram
  509.         if (empty($file->getIdProposal())){$logTelegram false;}
  510.         //INICIO: Notificamos al agente por Telegram
  511.         if ($logTelegram){
  512.             //Buscamos todos los agentes del proposal
  513.             $proposalAgents $em->getRepository(ProposalAgents::class)->findOneByIdProp($file->getIdProposal());
  514.             //Buscamos el Destino
  515. //            $proposalDestino = $em->getRepository(Destination::class)->findOneById($control->getDestinoId());
  516.             //Buscamos el agente de AVEXPRESS
  517.             $userData $em->getRepository(User::class)->findOneById($user_id);
  518.             if (!empty($proposalAgents) and !($user_id == 22)){
  519.                 if ((!empty($proposalAgents->getAgOne())) and (!($proposalAgents->getAgOne() == 0))){
  520.                     $this->sendTelegram($proposalAgents->getAgOne(),'1. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  521.                 }
  522.                 if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
  523.                     $this->sendTelegram($proposalAgents->getAgTwo(),'2. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  524.                 }
  525.                 if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
  526.                     $this->sendTelegram($proposalAgents->getAgThree(),'3. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  527.                 }
  528.                 if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
  529.                     $this->sendTelegram($proposalAgents->getAgFour(),'4. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  530.                 }
  531.             }
  532.         }
  533.         //FIN: Notificamos al agente por Telegram
  534.         return $this->redirectToRoute('ave_edit_file', array('id' => $fileId));
  535.     }
  536.     /**
  537.      * @Route("/updateproductfilegridtwo/",  name="ave_update_productfile_grid_two")
  538.      * Editar todos los producto de un expediente con todos sus campos
  539.      */
  540.     public function updateProductFileGridTwoAction(Request $request){
  541.         $em $this->getDoctrine()->getManager();
  542.         $newRequest $request->request->get('services');
  543.         $fileId $request->request->get('fileId');
  544.         $logTelegram false;
  545.         $srvInconsistentes '';                    // Mensaje de alerta por inconsistencia en los servicios
  546.         /* Obtengo usuario logueado */
  547.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  548.         $user_id $user_logueado->getId();
  549.         $txtOfChanges ''$boolNotifyOfChanges false$proposalId 0;
  550.         foreach ($newRequest as $item) {
  551.             $productInFile $em->getRepository(AveProductFile::class)->findOneById($item['productFileId']);
  552.             $logTelegram true;
  553.             $txtWarning '';
  554.             $productInFile->setProductName($item['name']);
  555.             $productInFile->setServicePrice($item['price']);
  556. //            $productInFile->setDescription($item['description']);
  557.             $productInFile->setCurrency($item['currency']);
  558.             $productInFile->setUnits($item['units']);
  559.             $productInFile->setType($item['prdType']);
  560.             $productInFile->setLocation($item['location']);
  561.             $productInFile->setRankAv(intval($item['rankAv']));
  562.             if (array_key_exists('dateInAt',$item)){
  563.                 $productInFile->setDateStart(new \DateTime($item['dateInAt']));
  564.                 $productInFile->setDateInAt(new \DateTime($item['dateInAt']));
  565.             } else {
  566.                 // No se requiere accion
  567.             }
  568.             if (array_key_exists('dateOutAt',$item)){
  569.                 $productInFile->setDateEnd(new \DateTime($item['dateOutAt']));
  570.                 $productInFile->setDateOutAt(new \DateTime($item['dateOutAt']));
  571.             } else {
  572.                 // No se requiere accion
  573.             }
  574.             if (empty($item['days'])){
  575. //                $productInFile->setDays($days = (((new \DateTime($item['dateOutAt']))->diff(new \DateTime($item['dateInAt'])))->days + 1));
  576.                 $productInFile->setDays($days = (($productInFile->getDateOutAt()->diff($productInFile->getDateInAt()))->days 1));
  577.             } else {
  578.                 $productInFile->setDays($item['days']);
  579.             }
  580.             $productInFile->setPax($item['pax']);
  581.             $productInFile->setOpCommission($item['opCommission']);
  582.             $productInFile->setCommission($item['commission']);
  583.             $productInFile->setOpOver($item['opOver']);
  584.             $productInFile->setOver($item['over']);
  585.             $productInFile->setOpIva($item['opIva']);
  586.             $productInFile->setIva($item['iva']);
  587.             if (!empty($item['supplierExt'])){
  588.                 $supplier $em->getRepository(Supplier::class)->findOneById($item['supplierExt']);
  589.                 $productInFile->setSupplierExt($supplier->getName());
  590.                 $productInFile->setSupplierExtId($item['supplierExt']);
  591.             } else {
  592.                 $productInFile->setSupplierExt(null);
  593.                 $productInFile->setSupplierExtId(null);
  594.             }
  595.             $productInFile->setHourStart(substr($item['start'],0,2));
  596.             $productInFile->setMinStart(substr($item['start'],3,2));
  597.             $productInFile->setHourEnd(substr($item['end'],0,2));
  598.             $productInFile->setMinEnd(substr($item['end'],3,2));
  599.             $productInFile->setUpdatedId($user_id);
  600.             $productInFile->setUpdatedAt(new \DateTime("now"));
  601.             $productInFile->setSubTotalPrice($productInFile->getServicePrice());
  602.             //INICIO: Validaciones para el sub total
  603.             if (is_numeric($productInFile->getUnits())){
  604.                 $productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() * $productInFile->getUnits());
  605.             }
  606.             if (is_numeric($productInFile->getPax())){
  607.                 $productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() * $productInFile->getPax());
  608.             }
  609.             $productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() * $productInFile->getDays());
  610.             // *** Primero se debe calcular la comision y luego el over ***
  611.             // Calculo de comision
  612.             if ($productInFile->getOpCommission()){
  613.                 //Over positivo
  614.                 if (!($productInFile->getCommission() == 0) and is_numeric($productInFile->getCommission())){
  615.                     $suma $productInFile->getCommission()/100;
  616.                     $suma $productInFile->getSubTotalPrice() * $suma;
  617.                     $productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() + $suma);
  618.                 }
  619.             } else {
  620.                 //Over negativo
  621.                 if (!($productInFile->getCommission() == 0) and is_numeric($productInFile->getCommission())){
  622.                     $suma $productInFile->getCommission()/100;
  623.                     $suma $productInFile->getSubTotalPrice() * $suma;
  624.                     if ($productInFile->getSubTotalPrice() > $suma){            // La comision a restar no puede ser mayor que el precio total
  625.                         $productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() - $suma);
  626.                     }
  627.                 }
  628.             }
  629.             // Calculo con OVER
  630.             if ($productInFile->getOpOver()){
  631.                 //Over positivo
  632.                 if (!($productInFile->getOver() == 0) and is_numeric($productInFile->getOver())){
  633.                     $productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() + $productInFile->getOver());
  634.                 }
  635.             } else {
  636.                 //Over negativo
  637.                 if (!($productInFile->getOver() == 0) and is_numeric($productInFile->getOver())){
  638.                     $productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() + ((-1) * $productInFile->getOver()));
  639.                 }
  640.             }
  641.             // IVA
  642.             //FIN: Validaciones para el sub total
  643.             //Si las fechas de inicio y fin no coinciden con el campo dias se debe enviar alerta
  644.             $txtWarning = ($productInFile->getDateOutAt()->diff($productInFile->getDateInAt()))->days <> $productInFile->getDays() ? '<br>'.$productInFile->getProductName() : '';
  645.             if (!empty($txtWarning)){
  646.                 if (empty($srvInconsistentes)){ $srvInconsistentes 'Hay inconsistencias en: '.'<br>'.$txtWarning; } else { $srvInconsistentes $srvInconsistentes.'<br>'.$txtWarning; }
  647.             }
  648.             $em->persist($productInFile);
  649.             $em->flush();
  650.             $em->clear();
  651.             //INICIO: Duplicamos en Eventos (SINCRONIZACION)
  652.             if (!empty($productInFile->getOriginId())){
  653.                 $serviceEvent $em->getRepository(ProposalSupplierServices::class)->findOneById($productInFile->getOriginId());
  654.                 $proposalId $serviceEvent->getProposalId();
  655.                 $oldServiceEvent = array(
  656.                     'activityId' => $serviceEvent->getActivityId(),
  657.                     'assistantId' => $serviceEvent->getAssistantId(),
  658.                     'breakdown' => $serviceEvent->getBreakdown(),
  659.                     'commission' => $serviceEvent->getCommission(),
  660.                     'controlId' => $serviceEvent->getControlId(),
  661.                     'currency' => $serviceEvent->getCurrency(),
  662.                     'dateBlockLimit' => $serviceEvent->getDateBlockLimit(),
  663.                     'dateInAt' => $serviceEvent->getDateInAt(),
  664.                     'dateOutAt' => $serviceEvent->getDateOutAt(),
  665.                     'destinationId' => $serviceEvent->getDestinationId(),
  666.                     'directPayment' => $serviceEvent->getDirectPayment(),
  667.                     'hour' => $serviceEvent->getHour(),
  668.                     'ideaId' => $serviceEvent->getIdeaId(),
  669.                     'isFather' => $serviceEvent->getIsFather(),
  670.                     'iva' => $serviceEvent->getIva(),
  671.                     'name' => $serviceEvent->getName(),
  672.                     'opCommission' => $serviceEvent->getOpCommission(),
  673.                     'opIva' => $serviceEvent->getOpIva(),
  674.                     'opOver' => $serviceEvent->getOpOver(),
  675.                     'originalIva' => $serviceEvent->getOriginalIva(),
  676.                     'originalPrice' => $serviceEvent->getOriginalPrice(),
  677.                     'originalopIva' => $serviceEvent->getOriginalopIva(),
  678.                     'over' => $serviceEvent->getOver(),
  679.                     'pax' => $serviceEvent->getPax(),
  680.                     'preCommission' => $serviceEvent->getPreCommission(),
  681.                     'preIva' => $serviceEvent->getPreIva(),
  682.                     'price' => $serviceEvent->getPrice(),
  683.                     'proposalId' => $serviceEvent->getProposalId(),
  684.                     'rank' => $serviceEvent->getRank(),
  685.                     'serviceCatId' => $serviceEvent->getServiceCatId(),
  686.                     'serviceCatName' => $serviceEvent->getServiceCatName(),
  687.                     'serviceId' => $serviceEvent->getServiceId(),
  688.                     'serviceIdFather' => $serviceEvent->getServiceIdFather(),
  689.                     'status' => $serviceEvent->getStatus(),
  690.                     'statusRec' => $serviceEvent->getStatusRec(),
  691.                     'statusinternal' => $serviceEvent->getStatusinternal(),
  692.                     'supplierId' => $serviceEvent->getSupplierId(),
  693.                     'units' => $serviceEvent->getUnits(),
  694.                 );
  695.                 if (!empty($serviceEvent)) {
  696.                     $prpInv $em->getRepository(ProposalInvoice::class)->findOneByProposalId($serviceEvent->getProposalId());
  697.                     if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
  698.                         $serviceEvent->setName($productInFile->getProductName());
  699.                         // Se verifican los precios en ambas partes (AV Express e InOut)
  700.                         if (!($serviceEvent->getPrice() == $productInFile->getServicePrice())) {
  701.                             // Si ambos precios unitarios son distintos se ha modificado el numero de dĆ­as en Av Express
  702.                             $newPriceInOut $this->precioPorVariacionDeDias($serviceEvent$productInFile);
  703.                             $serviceEvent->setPrice($newPriceInOut);
  704.                         } else {
  705.                             // si son iguales tambien se deben verificar el numero de dias
  706.                             if (!(($serviceEvent->getDateOutAt()->diff($serviceEvent->getDateInAt())->days 1) == $productInFile->getDays())) {
  707.                                 $newPriceInOut $this->precioPorVariacionDeDias($serviceEvent$item);
  708.                                 $serviceEvent->setPrice($newPriceInOut);
  709.                             }
  710.                         }
  711.                         $serviceEvent->setCurrency($productInFile->getCurrency());
  712.                         $serviceEvent->setUnits($productInFile->getUnits());
  713.                         if (empty($productInFile->getPax())) {
  714.                             $serviceEvent->setPax(1);
  715.                         } else {
  716.                             $serviceEvent->setPax($productInFile->getPax());
  717.                         }
  718.                         $serviceEvent->setDateInAt($productInFile->getDateInAt());
  719.                         $serviceEvent->setDateOutAt($productInFile->getDateOutAt());
  720.                         // Se verifican los precios en ambas partes (AV Express e InOut)
  721.                         if (!($serviceEvent->getPrice() == $productInFile->getServicePrice())) {
  722.                             // Si ambos precios unitarios son distintos se ha modificado el numero de dĆ­as en Av Express
  723.                             $newPriceInOut $this->precioPorVariacionDeDias($serviceEvent$productInFile);
  724.                             $serviceEvent->setPrice($newPriceInOut);
  725.                         } else {
  726.                             // si son iguales tambien se deben verificar el numero de dias
  727.                             if (!(($serviceEvent->getDateOutAt()->diff($serviceEvent->getDateInAt())->days 1) == $productInFile->getDays())) {
  728.                                 $newPriceInOut $this->precioPorVariacionDeDias($serviceEvent$productInFile);
  729.                                 $serviceEvent->setPrice($newPriceInOut);
  730.                             }
  731.                         }
  732.                         //Verificamos cambios e informamos al agente del proposal
  733.                         $boolChanges false;
  734.                         if (!($serviceEvent->getRank() == $oldServiceEvent['rank'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Orden</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['rank'].', su nuevo valor es: '.$serviceEvent->getRank().'<br>'$boolChanges true; }
  735.                         if (!($serviceEvent->getName() == $oldServiceEvent['name'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Nombre</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['name'].', su nuevo valor es: '.$serviceEvent->getName().'<br>'$boolChanges true; }
  736.                         if (!($serviceEvent->getPrice() == $oldServiceEvent['price'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Precio</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['price'].', su nuevo valor es: '.$serviceEvent->getPrice().'<br>'$boolChanges true; }
  737.                         if (!($serviceEvent->getCurrency() == $oldServiceEvent['currency'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Moneda</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['currency'].', su nuevo valor es: '.$serviceEvent->getCurrency().'<br>'$boolChanges true; }
  738.                         if (!($serviceEvent->getUnits() == $oldServiceEvent['units'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Cantidad</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['units'].', su nuevo valor es: '.$serviceEvent->getUnits().'<br>'$boolChanges true; }
  739.                         if (!($serviceEvent->getPax() == $oldServiceEvent['pax'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Personas</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['pax'].', su nuevo valor es: '.$serviceEvent->getPax().'<br>'$boolChanges true; }
  740.                         if (!($serviceEvent->getOpOver() == $oldServiceEvent['opOver'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getOpOver().'<br>'$boolChanges true; }
  741.                         if (!($serviceEvent->getOver() == $oldServiceEvent['over'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Over</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['over'].', su nuevo valor es: '.$serviceEvent->getOver().'<br>'$boolChanges true; }
  742.                         if (!($serviceEvent->getOpCommission() == $oldServiceEvent['opCommission'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getOpCommission().'<br>'$boolChanges true; }
  743.                         if (!($serviceEvent->getCommission() == $oldServiceEvent['commission'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>ComisiĆ³n" ha sido modificado. Su valor era: '.$oldServiceEvent['commission'].', su nuevo valor es: '.$serviceEvent->getCommission().'<br>'$boolChanges true; }
  744.                         if (!($serviceEvent->getOpIva() == $oldServiceEvent['opIva'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getOpIva().'<br>'$boolChanges true; }
  745.                         if (!($serviceEvent->getIva() == $oldServiceEvent['iva'])){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges $txtOfChanges '<br><br>El campo "<strong>Iva</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['iva'].', su nuevo valor es: '.$serviceEvent->getIva().'<br>'$boolChanges true; }
  746.                         if (!($serviceEvent->getDateInAt()->format('H:i') == $oldServiceEvent['dateInAt']->format('H:i'))){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateInAt()->format('H:i').'<br>'$boolChanges true; }
  747.                         if (!($serviceEvent->getDateInAt()->format('Ymd') == $oldServiceEvent['dateInAt']->format('Ymd'))){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateInAt()->format('d/m/Y').'<br>'$boolChanges true; }
  748.                         if (!($serviceEvent->getDateOutAt()->format('H:i') == $oldServiceEvent['dateOutAt']->format('H:i'))){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateOutAt()->format('H:i').'<br>'$boolChanges true; }
  749.                         if (!($serviceEvent->getDateOutAt()->format('Ymd') == $oldServiceEvent['dateOutAt']->format('Ymd'))){ if (!$boolChanges){ $txtOfChanges =  $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateOutAt()->format('d/m/Y').'<br>'$boolChanges true; }
  750.                         $em->persist($serviceEvent);
  751.                         $em->flush();
  752.                         $em->clear();
  753.                     }
  754.                 }
  755.             }
  756.             //FIN: Duplicamos en Eventos
  757.         }
  758.         // Notificamos al agente de InOut si se hicieron actualizaciones en los servicios desde AvExpress
  759.         if (!empty($txtOfChanges)) { $this->messageOfChangesToAgent($txtOfChanges$proposalId); }
  760.         $file $em->getRepository(AveFiles::class)->findOneById($fileId);
  761.         $event 'Servicios guardados correctamente.';
  762.         $successMessage $this->translator->trans($event);
  763.         $this->addFlash('mensajeav'$successMessage);
  764.         if (!empty($srvInconsistentes) and !empty($file->getIdProposal())){ $this->addFlash('mensajeaverror'$srvInconsistentes); }
  765.         // Si el proposalId esta vacio no se notifica a nadie por Telegram
  766.         if (empty($file->getIdProposal())){$logTelegram false;}
  767.         //INICIO: Notificamos al agente por Telegram
  768.         if ($logTelegram){
  769.             //Buscamos todos los agentes del proposal
  770.             $proposalAgents $em->getRepository(ProposalAgents::class)->findOneByIdProp($file->getIdProposal());
  771.             //Buscamos el Destino
  772. //            $proposalDestino = $em->getRepository(Destination::class)->findOneById($control->getDestinoId());
  773.             //Buscamos el agente de Develup
  774.             $userData $em->getRepository(User::class)->findOneById($user_id);
  775.             if (!empty($proposalAgents) and !($user_id == 22)){
  776.                 if ((!empty($proposalAgents->getAgOne())) and (!($proposalAgents->getAgOne() == 0))){
  777.                     $this->sendTelegram($proposalAgents->getAgOne(),'1. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID2) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  778.                 }
  779.                 if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
  780.                     $this->sendTelegram($proposalAgents->getAgTwo(),'2. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID2) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  781.                 }
  782.                 if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
  783.                     $this->sendTelegram($proposalAgents->getAgThree(),'3. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID2) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  784.                 }
  785.                 if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
  786.                     $this->sendTelegram($proposalAgents->getAgFour(),'4. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID2) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  787.                 }
  788.             }
  789.         }
  790.         //FIN: Notificamos al agente por Telegram
  791.         return $this->redirectToRoute('ave_edit_file', array('id' => $fileId));
  792.     }
  793.     /**
  794.      * @Route("/productfilelistmultiple/{id}",  name="ave_list_multiple_productfile")
  795.      * Listar multiples productos para agregar en el expediente id
  796.      */
  797.     public function listMultipleProductFileAction$idRequest $request){
  798.         $em $this->getDoctrine()->getManager();
  799. //        $avs = $em->getRepository(AveProduct::class)->findAll();
  800.         // Listamos por orden alfabetico y se deja de primero a "Otro servicio"
  801.         $parameters = array();
  802.         $dql 'SELECT i
  803.                     FROM AvexpressBundle:AveProduct i
  804.                     ORDER BY i.name ASC';
  805.         $query $em->createQuery($dql)->setParameters($parameters);
  806.         $avs $query->getResult();
  807.         $newAvs = array();
  808.         foreach ($avs as $key => $item) {
  809.             if ($item->getName() == 'Otro servicio'){
  810.                 $item->setName('0 - Otro servicio');
  811.                 $newAvs = array($item);
  812.                 unset($avs[$key]);
  813.                 foreach ($avs as $keyTwo => $elem){
  814.                     $ind $keyTwo 1;
  815.                     $elem->setName($ind.' - '.$elem->getName());
  816.                     array_push($newAvs,$elem);
  817.                 }
  818.             }
  819.         }
  820.         $avs $newAvs;
  821.         /* av Description*/
  822.         $data_av = array();
  823.         foreach($avs as $av){
  824.             $data_av[] = array(
  825.                 'id' => $av->getId(),
  826.                 'name' => $av->getName(),
  827.                 'modules' => null,
  828.                 'type' => $av->getType(),
  829.                 'currency' => 'Euro',
  830.                 'price' => $av->getPrice(),
  831.                 'commission' => 0,
  832.                 'iva' => 21,
  833.                 'controlId' => 0,
  834.                 'description' => null
  835.             );
  836.         }
  837.         // Buscamos las plantilas precargadas
  838.         $parameters = array();
  839.         $dql 'SELECT i
  840.                     FROM AvexpressBundle:AveTemplate i
  841.                     ORDER BY i.name ASC';
  842.         $query $em->createQuery($dql)->setParameters($parameters);
  843.         $aveTemplates $query->getResult();
  844.         // Buscamos las proformas
  845.         $proformas $em->getRepository(AveDocProforma::class)->findByFileId($id);
  846.         return $this->render('MDS/AvexpressBundle/Avexpress/add-services.html.twig',
  847.             array(
  848.                 'id' => $id,
  849.                 'avs' => $data_av,
  850.                 'newAvs' => $newAvs,
  851.                 'aveTemplates' => $aveTemplates,
  852.                 'proformas' => $proformas,
  853.                 'technology' => null,
  854.             ));
  855.     }
  856.     /**
  857.      * @Route("/productfilemultipleadd/",  name="ave_add_multiple_productfile")
  858.      * Agregar multiples productos a un expediente
  859.      */
  860.     public function addMultipleProductFileActionRequest $request){
  861.         $logTelegram false;
  862.         $fileId $request->request->get('fileId');
  863.         $products $request->request->get('av');
  864.         $template $request->request->get('avexpress');
  865.         $template $template['template'];
  866.         $srvDestination $request->request->get('srvDestination');
  867.         /* Obtengo usuario logueado */
  868.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  869.         $user_id $user_logueado->getId();
  870.         $em $this->getDoctrine()->getManager();
  871.         $file $em->getRepository(AveFiles::class)->findOneById($fileId);
  872.         $template $em->getRepository(AveTemplate::class)->findOneById($template);
  873.         if(!empty($products)) {
  874.             foreach ($products as $item) {
  875.                 $mdvProductSelected $em->getRepository(AveProduct::class)->findOneById($item);
  876.                 $newProductFile = new AveProductFile();
  877.                 $newProductFile->setProductName($mdvProductSelected->getName());
  878.                 $newProductFile->setProductId($mdvProductSelected->getId());
  879.                 $newProductFile->setServicePrice($mdvProductSelected->getPrice());
  880.                 $newProductFile->setDescription($mdvProductSelected->getDescription());
  881.                 $newProductFile->setType($mdvProductSelected->getType());
  882.                 $newProductFile->setFileId($fileId);
  883.                 $newProductFile->setUnits('1');
  884.                 $newProductFile->setOpIva(true);
  885.                 $newProductFile->setIva('21');
  886.                 $newProductFile->setSupplierExt($mdvProductSelected->getSupplierExt());
  887.                 $newProductFile->setSupplierExtId($mdvProductSelected->getSupplierExtId());
  888.                 $dataDates $this->obtenerFechas($newProductFile->getFileId(), $newProductFile->getDateStart(), $newProductFile->getDateEnd());
  889.                 $newProductFile->setDateStart($dataDates['dateStart']);
  890.                 $newProductFile->setDateEnd($dataDates['dateEnd']);
  891.                 $newProductFile->setDateInAt($dataDates['dateStart']);
  892.                 $newProductFile->setDateOutAt($dataDates['dateEnd']);
  893.                 $dataRankAv $this->obtenerRankAv($fileId);
  894.                 $newProductFile->setRankAv($dataRankAv);
  895.                 $newProductFile->setCreatedId($user_id);
  896.                 $newProductFile->setUpdatedId($user_id);
  897.                 $newProductFile->setCreatedAt(new \DateTime("now"));
  898.                 $newProductFile->setUpdatedAt(new \DateTime("now"));
  899.                 if (empty($newProductFile->getType())){ $newProductFile->setType('Otros'); }
  900.                 $newProductFile->setDays((($newProductFile->getDateEnd()->diff($newProductFile->getDateStart()))->days 1));
  901.                 $newProductFile->setSubTotalPrice($newProductFile->getServicePrice() * $newProductFile->getDays());
  902.                 $em->persist($newProductFile);
  903.                 $em->flush();
  904.                 if (!($srvDestination == 0)){
  905.                     //Se debe agregar el producto a una proforma
  906.                     $this->addProductFileToProforma($fileId$newProductFile->getId(), $srvDestination);
  907.                 }
  908.                 // Si hay proposal se debe actualizar en el expediente de Eventos
  909.                 if (!empty($file->getIdProposal()) and is_numeric($file->getIdProposal())) {
  910.                     // Buscamos el destino donde se encuentre Av Express y ahi agregamos el servicio, si no se encuentra no se agregara el servicio
  911.                     $control $em->getRepository(ProposalSupplierControl::class)->findOneBy(
  912.                         array(
  913.                             'supplierId' => 80,                                          // El supplier 80 es AVEXPRESS
  914.                             'proposalId' => $file->getIdProposal(),
  915.                         )
  916.                     );
  917.                     if (!empty($control)) {
  918.                         // Existe un destino con Av Express como proveedor, hay se agregara el servicio
  919.                         $prpInv $em->getRepository(ProposalInvoice::class)->findOneByProposalId($file->getIdProposal());
  920.                         if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
  921.                             $logTelegram true;
  922.                             $service = new ProposalSupplierServices();
  923.                             $service->setServiceIdFather(0);
  924.                             $service->setControlId($control->getId());
  925.                             $service->setProposalId($file->getIdProposal());
  926.                             $service->setDestinationId($control->getDestinoId());
  927.                             $service->setSupplierId(80);
  928.                             $service->setIdeaId(null);
  929.                             $service->setServiceId($newProductFile->getProductId());
  930.                             $service->setServiceCatName('Av');
  931.                             $service->setServiceCatId(3);
  932.                             $service->setName($newProductFile->getProductName());
  933.                             $service->setPrice($newProductFile->getSubTotalPrice() / $newProductFile->getDays());
  934. //                        $priceInOut = $newProductFile->getSubTotalPrice() / $newProductFile->getPax();      // Se devuelve el calculo dividiendo entre personas
  935. //                        $priceInOut = $priceInOut / $newProductFile->getUnits();                            // Se devuelve el calculo dividiendo entre cantidades
  936. //                        $priceInOut = $priceInOut / round($newProductFile->getDays());                      // Se devuelve el calculo dividiendo entre dias, se redondea por si es 1.5
  937. //                        $service->setPrice($priceInOut);
  938.                             $service->setCurrency($newProductFile->getCurrency());
  939.                             $service->setUnits($newProductFile->getUnits());
  940.                             $service->setCommission(0);
  941.                             $service->setOver(0);
  942.                             $service->setIva(21);
  943.                             $service->setPax(1);
  944.                             $service->setHour(null);
  945.                             $service->setDateInAt($newProductFile->getDateInAt());
  946.                             $service->setDateOutAt($newProductFile->getDateOutAt());
  947.                             $service->setDirectPayment(0);
  948.                             $service->setStatus('Pending');
  949.                             $service->setStatusinternal('Additional');
  950.                             $service->setPreCommission(null);
  951.                             $service->setPreIva(null);
  952.                             $service->setDateBlockLimit(null);
  953.                             $service->setOpCommission(1);
  954.                             $service->setOpOver(1);
  955.                             $service->setOpIva(1);
  956.                             $service->setBreakdown(0);
  957.                             $service->setIsFather(0);
  958.                             $service->setRank(1);
  959.                             $service->setOriginalopIva(1);
  960.                             $service->setOriginalIva(null);
  961.                             $service->setOriginalPrice(null);
  962.                             $service->setStatusRec('normal');
  963.                             $service->setAssistantId(null);
  964.                             $service->setCreatedId($user_id);
  965.                             $service->setUpdatedId($user_id);
  966.                             $service->setCreatedAt(new \DateTime("now"));
  967.                             $service->setUpdatedAt(new \DateTime("now"));
  968.                             $em->persist($service);
  969.                             $em->flush();
  970.                             // Guardamos el ID del servicio (Eventos) asociado al producto (AvExpress)
  971.                             $newProductFile->setOriginId($service->getId());
  972.                             $em->persist($newProductFile);
  973.                             $em->flush();
  974.                         }
  975.                     }
  976.                 }
  977.             }
  978.         }
  979.         // Buscamos los elementos de la plantilla seleccionada
  980.         $templateItems = array();
  981.         if(!empty($template)){
  982.             $templateItems $em->getRepository(AveTemplateItems::class)->findByTemplateId($template);
  983.         }
  984.         foreach ($templateItems as $item){
  985.             $newProductFile = new AveProductFile();
  986.             $newProductFile->setProductName($item->getProductName());
  987.             $newProductFile->setProductId($item->getProductId());
  988.             $newProductFile->setServicePrice($item->getServicePrice());
  989.             $newProductFile->setFileId($fileId);
  990.             $newProductFile->setPax($item->getPax());
  991.             $newProductFile->setType($item->getType());
  992.             $newProductFile->setHourStart($item->getHourStart());
  993.             $newProductFile->setMinStart($item->getMinStart());
  994.             $newProductFile->setHourEnd($item->getHourEnd());
  995.             $newProductFile->setMinEnd($item->getMinEnd());
  996.             $newProductFile->setDescription($item->getDescription());
  997.             $newProductFile->setSupplierExtId($item->getSupplierExtId());
  998.             $newProductFile->setSupplierExt($item->getSupplierExt());
  999.             $newProductFile->setServiceIdProposal($item->getServiceIdProposal());
  1000.             $newProductFile->setServiceIdFather($item->getServiceIdFather());
  1001.             $newProductFile->setControlId($item->getControlId());
  1002.             $newProductFile->setProposalId($item->getProposalId());
  1003.             $newProductFile->setDestinationId($item->getDestinationId());
  1004.             $newProductFile->setIdeaId($item->getIdeaId());
  1005.             $newProductFile->setActivityId($item->getActivityId());
  1006.             $newProductFile->setSupplierId($item->getSupplierId());
  1007.             $newProductFile->setAssistantId($item->getAssistantId());
  1008.             $newProductFile->setServiceId($item->getServiceId());
  1009.             $newProductFile->setServiceCatId($item->getServiceCatId());
  1010.             $newProductFile->setServiceCatName($item->getServiceCatName());
  1011.             $newProductFile->setName($item->getName());
  1012.             $newProductFile->setPrice($item->getPrice());
  1013.             $newProductFile->setCurrency($item->getCurrency());
  1014.             $newProductFile->setUnits($item->getUnits());
  1015.             $newProductFile->setOpCommission($item->getOpCommission());
  1016.             $newProductFile->setCommission($item->getCommission());
  1017.             $newProductFile->setOpOver($item->getOpOver());
  1018.             $newProductFile->setOver($item->getOver());
  1019.             $newProductFile->setOpIva($item->getOpIva());
  1020.             $newProductFile->setIva($item->getIva());
  1021.             $newProductFile->setHour($item->getHour());
  1022.             $dataDates $this->obtenerFechas($newProductFile->getFileId(), $newProductFile->getDateStart(), $newProductFile->getDateEnd());
  1023.             $newProductFile->setDateStart($dataDates['dateStart']);
  1024.             $newProductFile->setDateEnd($dataDates['dateEnd']);
  1025.             $newProductFile->setDateInAt($dataDates['dateStart']);
  1026.             $newProductFile->setDateOutAt($dataDates['dateEnd']);
  1027.             $newProductFile->setContcolor($item->getContcolor());
  1028.             $newProductFile->setRank($item->getRank());
  1029.             $dataRankAv $this->obtenerRankAv($fileId);
  1030.             $newProductFile->setRankAv($dataRankAv);
  1031.             $newProductFile->setRenovate($item->getRenovate());
  1032.             $newProductFile->setPay($item->getPay());
  1033.             $newProductFile->setDays($item->getDays());
  1034.             $newProductFile->setSubTotalPrice($item->getSubTotalPrice());
  1035.             $newProductFile->setCreatedId($user_id);
  1036.             $newProductFile->setUpdatedId($user_id);
  1037.             $newProductFile->setCreatedAt(new \DateTime("now"));
  1038.             $newProductFile->setUpdatedAt(new \DateTime("now"));
  1039.             if (empty($newProductFile->getType())){ $newProductFile->setType('Otros'); }
  1040.             $em->persist($newProductFile);
  1041.             $em->flush();
  1042.             if (!($srvDestination == 0)){
  1043.                 //Se debe agregar el producto a una proforma
  1044.                 $this->addProductFileToProforma($fileId$newProductFile->getId(), $srvDestination);
  1045.             }
  1046.             // Si hay proposal se debe actualizar en el expediente de Eventos
  1047.             if (!empty($file->getIdProposal()) and is_numeric($file->getIdProposal())){
  1048.                 // Buscamos el destino donde se encuentre Av Express y ahi agregamos el servicio, si no se encuentra no se agregara el servicio
  1049.                 $control $em->getRepository(ProposalSupplierControl::class)->findOneBy(
  1050.                     array(
  1051.                         'supplierId' => 80,                                          // El supplier 80 es AVEXPRESS
  1052.                         'proposalId' => $file->getIdProposal(),
  1053.                     )
  1054.                 );
  1055.                 if (!empty($control)){
  1056.                     // Existe un destino con Av Express como proveedor, hay se agregara el servicio
  1057.                     $prpInv $em->getRepository(ProposalInvoice::class)->findOneByProposalId($file->getIdProposal());
  1058.                     if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
  1059.                         $logTelegram true;
  1060.                         $service = new ProposalSupplierServices();
  1061.                         $service->setServiceIdFather(0);
  1062.                         $service->setControlId($control->getId());
  1063.                         $service->setProposalId($file->getIdProposal());
  1064.                         $service->setDestinationId($control->getDestinoId());
  1065.                         $service->setSupplierId(80);
  1066.                         $service->setIdeaId(null);
  1067.                         $service->setServiceId($newProductFile->getProductId());
  1068.                         $service->setServiceCatName('Av');
  1069.                         $service->setServiceCatId(3);
  1070.                         $service->setName($newProductFile->getProductName());
  1071.                         $service->setPrice($newProductFile->getSubTotalPrice());
  1072.                         $service->setCurrency(null);
  1073.                         $service->setUnits(1);
  1074.                         $service->setCommission(0);
  1075.                         $service->setOver(0);
  1076.                         $service->setIva(21);
  1077.                         $service->setPax(0);
  1078.                         $service->setHour(null);
  1079.                         $service->setDateInAt(new \DateTime("now"));
  1080.                         $service->setDateOutAt(new \DateTime("now"));
  1081.                         $service->setDirectPayment(0);
  1082.                         $service->setStatus('Pending');
  1083.                         $service->setStatusinternal('Additional');
  1084.                         $service->setPreCommission(null);
  1085.                         $service->setPreIva(null);
  1086.                         $service->setDateBlockLimit(null);
  1087.                         $service->setOpCommission(1);
  1088.                         $service->setOpOver(1);
  1089.                         $service->setOpIva(1);
  1090.                         $service->setBreakdown(0);
  1091.                         $service->setIsFather(0);
  1092.                         $service->setRank(1);
  1093.                         $service->setOriginalopIva(1);
  1094.                         $service->setOriginalIva(null);
  1095.                         $service->setOriginalPrice(null);
  1096.                         $service->setStatusRec('normal');
  1097.                         $service->setAssistantId(null);
  1098.                         $service->setCreatedId($user_id);
  1099.                         $service->setUpdatedId($user_id);
  1100.                         $service->setCreatedAt(new \DateTime("now"));
  1101.                         $service->setUpdatedAt(new \DateTime("now"));
  1102.                         $em->persist($service);
  1103.                         $em->flush();
  1104.                         // Guardamos el ID del servicio (Eventos) asociado al producto (AvExpress)
  1105.                         $newProductFile->setOriginId($service->getId());
  1106.                         $em->persist($newProductFile);
  1107.                         $em->flush();
  1108.                     }
  1109.                 }
  1110.             }
  1111.         }
  1112.         //INICIO: Notificamos al agente por Telegram
  1113.         if ($logTelegram){
  1114.             //Buscamos todos los agentes del proposal
  1115.             $proposalAgents $em->getRepository(ProposalAgents::class)->findOneByIdProp($file->getIdProposal());
  1116.             //Buscamos el Destino
  1117.             $proposalDestino $em->getRepository(Destination::class)->findOneById($control->getDestinoId());
  1118.             //Buscamos el agente de AvExpress
  1119.             $userData $em->getRepository(User::class)->findOneById($user_id);
  1120.             if (!empty($proposalAgents) and !($user_id == 22)){
  1121.                 if ((!empty($proposalAgents->getAgOne())) and (!($proposalAgents->getAgOne() == 0))){
  1122.                     $this->sendTelegram($proposalAgents->getAgOne(),'1. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$file->getIdProposal().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  1123.                 }
  1124.                 if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
  1125.                     $this->sendTelegram($proposalAgents->getAgTwo(),'2. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$file->getIdProposal().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  1126.                 }
  1127.                 if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
  1128.                     $this->sendTelegram($proposalAgents->getAgThree(),'3. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$file->getIdProposal().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  1129.                 }
  1130.                 if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
  1131.                     $this->sendTelegram($proposalAgents->getAgFour(),'4. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$file->getIdProposal().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  1132.                 }
  1133.             }
  1134.         }
  1135.         //FIN: Notificamos al agente por Telegram
  1136.         return $this->redirectToRoute('ave_edit_file',
  1137.             array(
  1138.                 'id' => $fileId
  1139.             )
  1140.         );
  1141.     }
  1142.     /**
  1143.      * @Route("/productfileedit/{id}",  name="ave_productfile_edit")
  1144.      * Editar un producto de un expediente
  1145.      */
  1146.     public function editProductFileAction($idRequest $request){
  1147.         $em $this->getDoctrine()->getManager();
  1148.         $productFile $em->getRepository(AveProductFile::class)->findOneById($id);
  1149.         $fileId $productFile->getFileId();
  1150.         // Primero se agrupan por sala (Ubicacion), luego por tipo y finalmente por RankAv
  1151.         // Salvador Guerrero indico, el orden de los productos en la factura o proforma serĆ” (Video - Sonido - Iluminacion - Otros)
  1152.         $allProductFile $em->getRepository(AveProductFile::class)->findByFileId($fileId);
  1153.         $arrayLocation = array();
  1154.         $arrayLocationWithNull false;
  1155.         foreach ($allProductFile as $item){
  1156.             if (!empty($item->getLocation())){
  1157.                 $arrayLocation[$item->getLocation()] = $item->getLocation();
  1158.             } else {
  1159.                 $arrayLocationWithNull true;
  1160.             }
  1161.         }
  1162.         if ($arrayLocationWithNull){ $arrayLocation['null'] = 'null'; }
  1163.         $productInFile = array();
  1164.         foreach ($arrayLocation as $item){
  1165.             // VIDEO
  1166.             $parameters = array(
  1167.                 'fileId' => $fileId,
  1168.                 'type' => 'VĆ­deo',
  1169.                 'location' => $item,
  1170.             );
  1171.             $dql 'SELECT i
  1172.                     FROM AvexpressBundle:AveProductFile i
  1173.                     WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location
  1174.                     ORDER BY i.rankAv ASC';
  1175.             $query $em->createQuery($dql)->setParameters($parameters);
  1176.             $productsInFileVid $query->getResult();
  1177.             // SONIDO
  1178.             $parameters = array(
  1179.                 'fileId' => $fileId,
  1180.                 'type' => 'Sonido',
  1181.                 'location' => $item,
  1182.             );
  1183.             $dql 'SELECT i
  1184.                     FROM AvexpressBundle:AveProductFile i
  1185.                     WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location
  1186.                     ORDER BY i.rankAv ASC';
  1187.             $query $em->createQuery($dql)->setParameters($parameters);
  1188.             $productsInFileSound $query->getResult();
  1189.             // ILUMINACION
  1190.             $parameters = array(
  1191.                 'fileId' => $fileId,
  1192.                 'type' => 'IluminaciĆ³n',
  1193.                 'location' => $item,
  1194.             );
  1195.             $dql 'SELECT i
  1196.                     FROM AvexpressBundle:AveProductFile i
  1197.                     WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location
  1198.                     ORDER BY i.rankAv ASC';
  1199.             $query $em->createQuery($dql)->setParameters($parameters);
  1200.             $productsInFileLights $query->getResult();
  1201.             // OTROS
  1202.             $parameters = array(
  1203.                 'fileId' => $fileId,
  1204.                 'typeV' => 'VĆ­deo',
  1205.                 'typeS' => 'Sonido',
  1206.                 'typeI' => 'IluminaciĆ³n',
  1207.                 'location' => $item,
  1208.             );
  1209.             $dql 'SELECT i
  1210.                     FROM AvexpressBundle:AveProductFile i
  1211.                     WHERE (i.fileId = :fileId AND i.type != :typeV AND i.type != :typeS AND i.type != :typeI AND i.location = :location)
  1212.                     ORDER BY i.rankAv ASC';
  1213.             $query $em->createQuery($dql)->setParameters($parameters);
  1214.             $productsInFileOther $query->getResult();
  1215.             // CASO NULL (Los casos EMPTY estan considerados en las consultas previas)
  1216.             $parameters = array(
  1217.                 'fileId' => $fileId,
  1218.                 'location' => $item,
  1219.             );
  1220.             $dql 'SELECT i
  1221.                     FROM AvexpressBundle:AveProductFile i
  1222.                     WHERE (i.fileId = :fileId AND i.type IS NULL AND i.location = :location)
  1223.                     ORDER BY i.rankAv ASC';
  1224.             $query $em->createQuery($dql)->setParameters($parameters);
  1225.             $productsInFileNull $query->getResult();
  1226.             // Para el location en NULL el SQL tiene que ser diferente por eso el siguiente condicional
  1227.             if ($item == 'null'){
  1228.                 // VIDEO
  1229.                 $parameters = array(
  1230.                     'fileId' => $fileId,
  1231.                     'type' => 'VĆ­deo',
  1232.                     'location' => '',
  1233.                 );
  1234.                 $dql 'SELECT i
  1235.                         FROM AvexpressBundle:AveProductFile i
  1236.                         WHERE i.fileId = :fileId AND i.type = :type AND (i.location IS NULL OR i.location = :location)
  1237.                         ORDER BY i.rankAv ASC';
  1238.                 $query $em->createQuery($dql)->setParameters($parameters);
  1239.                 $productsInFileVid $query->getResult();
  1240.                 // SONIDO
  1241.                 $parameters = array(
  1242.                     'fileId' => $fileId,
  1243.                     'type' => 'Sonido',
  1244.                     'location' => '',
  1245.                 );
  1246.                 $dql 'SELECT i
  1247.                         FROM AvexpressBundle:AveProductFile i
  1248.                         WHERE i.fileId = :fileId AND i.type = :type AND (i.location IS NULL OR i.location = :location) 
  1249.                         ORDER BY i.rankAv ASC';
  1250.                 $query $em->createQuery($dql)->setParameters($parameters);
  1251.                 $productsInFileSound $query->getResult();
  1252.                 // ILUMINACION
  1253.                 $parameters = array(
  1254.                     'fileId' => $fileId,
  1255.                     'type' => 'IluminaciĆ³n',
  1256.                     'location' => '',
  1257.                 );
  1258.                 $dql 'SELECT i
  1259.                         FROM AvexpressBundle:AveProductFile i
  1260.                         WHERE i.fileId = :fileId AND i.type = :type AND (i.location IS NULL OR i.location = :location)
  1261.                         ORDER BY i.rankAv ASC';
  1262.                 $query $em->createQuery($dql)->setParameters($parameters);
  1263.                 $productsInFileLights $query->getResult();
  1264.                 // OTROS
  1265.                 $parameters = array(
  1266.                     'fileId' => $fileId,
  1267.                     'typeV' => 'VĆ­deo',
  1268.                     'typeS' => 'Sonido',
  1269.                     'typeI' => 'IluminaciĆ³n',
  1270.                     'location' => '',
  1271.                 );
  1272.                 $dql 'SELECT i
  1273.                         FROM AvexpressBundle:AveProductFile i
  1274.                         WHERE (i.fileId = :fileId AND i.type != :typeV AND i.type != :typeS AND i.type != :typeI AND (i.location IS NULL OR i.location = :location))
  1275.                         ORDER BY i.rankAv ASC';
  1276.                 $query $em->createQuery($dql)->setParameters($parameters);
  1277.                 $productsInFileOther $query->getResult();
  1278.                 // CASO NULL DEL TIPO (Los casos EMPTY estan considerados en las consultas previas)
  1279.                 $parameters = array(
  1280.                     'fileId' => $fileId,
  1281.                     'location' => '',
  1282.                 );
  1283.                 $dql 'SELECT i
  1284.                         FROM AvexpressBundle:AveProductFile i
  1285.                         WHERE (i.fileId = :fileId AND i.type IS NULL AND (i.location IS NULL OR i.location = :location))
  1286.                         ORDER BY i.rankAv ASC';
  1287.                 $query $em->createQuery($dql)->setParameters($parameters);
  1288.                 $productsInFileNull $query->getResult();
  1289.             }
  1290.             $productInFile array_merge($productInFile,$productsInFileVid$productsInFileSound$productsInFileLights$productsInFileOther$productsInFileNull);
  1291.         }
  1292.         $parameters = array();
  1293.         $dql 'SELECT p.id, p.name
  1294.                 FROM App\Entity\Supplier p
  1295.                 WHERE p.isSupplierAvExpress = TRUE 
  1296.                 ORDER BY p.name ASC ';
  1297.         $query $em->createQuery($dql)->setParameters($parameters);
  1298.         $suppliers $query->getResult();
  1299.         // Quitamos el elemento seleccionado para evitar duplicaciones
  1300.         foreach ($productInFile as $key => $item) {
  1301.             if ($productFile->getId() == $item->getId()){
  1302.                 unset($productInFile[$key]);
  1303.             }
  1304.         }
  1305.         $id $productFile->getFileId();
  1306.         $numeroItems sizeof($productInFile) + 1;
  1307.         $productsLocation $em->getRepository(AveProductFileLocationNames::class)->findAll();
  1308.         return $this->render('MDS/AvexpressBundle/Avexpress/edit-productfiles.html.twig',
  1309.             array(
  1310.                 'id' => $id,
  1311.                 'numeroItems' => $numeroItems,
  1312.                 'arrayProductFile' => $productInFile,
  1313.                 'services' => $productInFile,
  1314.                 'product' => array($productFile),
  1315.                 'suppliers' => $suppliers,
  1316.                 'productsLocation' => $productsLocation,
  1317.             ));
  1318.     }
  1319.     /**
  1320.      * @Route("/cleanproductfile/{id}",  name="ave_clean_productfile")
  1321.      * Eliminar los productos (y servicios en InOut) de un expediente que no estĆ©n relacionados con una factura o una proforma
  1322.      */
  1323.     public function cleanProductFileAction($idRequest $request)
  1324.     {
  1325.         $em $this->getDoctrine()->getManager();
  1326.         /* Obtengo usuario logueado */
  1327.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1328.         $user_id $user_logueado->getId();
  1329.         $allMdvProductSelected $em->getRepository(AveProductFile::class)->findByFileId($id);
  1330.         // Si el ProductFile esta asociado a una factura o a una proforma se mantiene, de lo contrario se elimina y su evento asociado
  1331.         foreach ($allMdvProductSelected as $key => $item){
  1332.             $isInInvoice $em->getRepository(AveDocInvoiceItems::class)->findOneByPrdControlId($item->getId());
  1333.             $isInProforma $em->getRepository(AveDocProformaItems::class)->findOneByControlId($item->getId());
  1334.             if (!empty($isInInvoice) or !empty($isInProforma)){
  1335.                 //Lo sacamos de la lista de elementos a eliminar
  1336.                 unset($allMdvProductSelected[$key]);
  1337.             }
  1338.         }
  1339.         foreach ($allMdvProductSelected as $mdvProductSelected){
  1340.             $logTelegram false;
  1341.             //INICIO: Si hay un ID origin se debe eliminar en Eventos
  1342.             if (!empty($mdvProductSelected->getOriginId())){
  1343.                 $logTelegram true;
  1344.                 $delete $em->getRepository(ProposalSupplierServices::class)->findOneById($mdvProductSelected->getOriginId());
  1345.                 if (!empty($delete)) {
  1346.                     $destinationId $delete->getDestinationId();
  1347.                     $nameServEvents $delete->getName();
  1348.                     $proposalId $delete->getProposalId();
  1349.                     $prpInv $em->getRepository(ProposalInvoice::class)->findOneByProposalId($delete->getProposalId());
  1350.                     if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
  1351.                         if (!empty($delete)) {
  1352.                             $delete_sub $em->getRepository(ProposalSupplierServices::class)->findByServiceIdFather($delete->getId());
  1353.                             foreach ($delete_sub as $deletesub) {
  1354.                                 $em->remove($deletesub);
  1355.                             }
  1356.                             $em->remove($delete);
  1357.                             $em->flush();
  1358.                         }
  1359.                     }
  1360.                 } else {
  1361.                     // El servicio origen no se encontro
  1362.                     $logTelegram false;
  1363.                 }
  1364.             }
  1365.             //INICIO: Notificamos al agente por Telegram
  1366.             if ($logTelegram){
  1367.                 //Buscamos todos los agentes del proposal
  1368.                 $proposalAgents $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposalId);
  1369.                 //Buscamos el Destino
  1370.                 $proposalDestino $em->getRepository(Destination::class)->findOneById($destinationId);
  1371.                 //Buscamos el agente de Develup
  1372.                 $userData $em->getRepository(User::class)->findOneById($user_id);
  1373.                 if (!empty($proposalAgents)){
  1374.                     if ((!empty($proposalAgents->getAgOne())) and (!($proposalAgents->getAgOne() == 0))){
  1375.                         $this->sendTelegram($proposalAgents->getAgOne(),'1. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  1376.                     }
  1377.                     if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
  1378.                         $this->sendTelegram($proposalAgents->getAgTwo(),'2. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  1379.                     }
  1380.                     if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
  1381.                         $this->sendTelegram($proposalAgents->getAgThree(),'3. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  1382.                     }
  1383.                     if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
  1384.                         $this->sendTelegram($proposalAgents->getAgFour(),'4. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
  1385.                     }
  1386.                 }
  1387.             }
  1388.             //FIN: Notificamos al agente por Telegram
  1389.             //FIN: Si hay un ID origin se debe eliminar en Eventos
  1390.             //INICIO: Si el producto se encuentra dentro de una proforma (Ave_Doc_Proforma_Items) se elimina tambiĆ©n
  1391.             $productInProforma $em->getRepository(AveDocProformaItems::class)->findOneByControlId($mdvProductSelected->getId());
  1392.             if (!empty($productInProforma)){
  1393.                 $productInProforma->setFileId((-1) * $productInProforma->getFileId());      // No lo vamos a eliminar, apuntarĆ” al fileId en negativo
  1394.                 $em->persist($productInProforma);
  1395.                 // $em->remove($productInProforma);
  1396.                 $em->flush();
  1397.             }
  1398.             //FIN: Si el producto se encuentra dentro de una proforma (Ave_Doc_Proforma_Items) se elimina tambiĆ©n
  1399.             $mdvProductSelected->setFileId((-1) * $mdvProductSelected->getFileId());      // No lo vamos a eliminar, apuntarĆ” al fileId en negativo
  1400.             $em->persist($mdvProductSelected);
  1401.             // $em->remove($mdvProductSelected);
  1402.             $em->flush();
  1403.         }
  1404.         return $this->redirectToRoute('ave_edit_file', array('id' => $id));
  1405.     }
  1406.     /**
  1407.      * @Route("/overallproductfile/",  name="ave_over_all_productfile")
  1408.      * Aplicar un Over a todos los productos de un expediente
  1409.      */
  1410.     public function overAllProductFileAction(Request $request){
  1411.         $fileId $request->request->get('fileId');
  1412.         $opOverAll $request->request->get('opOverAll');
  1413.         $overAll $request->request->get('overAll');
  1414.         $em $this->getDoctrine()->getManager();
  1415.         $productInFile $em->getRepository(AveProductFile::class)->findByFileId($fileId);
  1416.         foreach ($productInFile as $item){
  1417.             $itemId $item->getId();
  1418.             $item->setOpOver($opOverAll);
  1419.             $item->setOver($overAll);
  1420.             $em->persist($item);
  1421.             $em->flush();
  1422.         }
  1423.         return $this->redirectToRoute('ave_productfile_edit', array('id' => $itemId));
  1424.     }
  1425.     /**
  1426.      * @Route("/commissionallproductfile/",  name="ave_commission_all_productfile")
  1427.      * Aplicar una Comision a todos los productos de un expediente
  1428.      */
  1429.     public function commissionAllProductFileAction(Request $request){
  1430.         $fileId $request->request->get('fileId');
  1431.         $opCommissionAll $request->request->get('opCommissionAll');
  1432.         $commissionAll $request->request->get('commissionAll');
  1433.         $em $this->getDoctrine()->getManager();
  1434.         $productInFile $em->getRepository(AveProductFile::class)->findByFileId($fileId);
  1435.         foreach ($productInFile as $item){
  1436.             $itemId $item->getId();
  1437.             $item->setOpCommission($opCommissionAll);
  1438.             $item->setCommission($commissionAll);
  1439.             $em->persist($item);
  1440.             $em->flush();
  1441.         }
  1442.         return $this->redirectToRoute('ave_productfile_edit', array('id' => $itemId));
  1443.     }
  1444.     /**
  1445.      * @Route("/ivazeroallproductfile/",  name="ave_iva_zero_all_productfile")
  1446.      * Aplicar un IVA de cero a todos los productos de un expediente
  1447.      */
  1448.     public function ivaZeroAllProductFileAction(Request $request){
  1449.         $fileId $request->request->get('fileId');
  1450. //        $opCommissionAll = $request->request->get('opCommissionAll');
  1451. //        $commissionAll = $request->request->get('commissionAll');
  1452.         $em $this->getDoctrine()->getManager();
  1453.         $productInFile $em->getRepository(AveProductFile::class)->findByFileId($fileId);
  1454.         foreach ($productInFile as $item){
  1455.             $itemId $item->getId();
  1456.             $item->setOpIva(1);
  1457.             $item->setIva(0);
  1458.             
  1459.             $em->persist($item);
  1460.             $em->flush();
  1461.         }
  1462.         return $this->redirectToRoute('ave_productfile_edit', array('id' => $itemId));
  1463.     }
  1464.     
  1465.     /**
  1466.      * @Route("/productfilelocationadd/",  name="ave_add_productfilelocation")
  1467.      * Agregar una Ubicacion. Salas en donde estara el producto
  1468.      */
  1469.     public function addProductFileLocationActionRequest $request)
  1470.     {
  1471.         $em $this->getDoctrine()->getManager();
  1472.         $newRequest $request->request->get('product');
  1473.         /* Obtengo usuario logueado */
  1474.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1475.         $user_id $user_logueado->getId();
  1476.         $newProductFile = new AveProductFileLocationNames();
  1477.         $newProductFile->setName($newRequest['name']);
  1478.         $newProductFile->setDescription($newRequest['description']);
  1479.         $newProductFile->setCreatedId($user_id);
  1480.         $newProductFile->setUpdatedId($user_id);
  1481.         $newProductFile->setCreatedAt(new \DateTime("now"));
  1482.         $newProductFile->setUpdatedAt(new \DateTime("now"));
  1483.         $em->persist($newProductFile);
  1484.         $em->flush();
  1485.         return $this->redirectToRoute('ave_list_productfilelocation');
  1486.     }
  1487.     /**
  1488.      * @Route("/productfilelocationlist/",  name="ave_list_productfilelocation")
  1489.      * Listar Ubicaciones para los productos
  1490.      */
  1491.     public function listProductFileLocationAction(Request $request){
  1492.         $em $this->getDoctrine()->getManager();
  1493.         $productsLocation $em->getRepository(AveProductFileLocationNames::class)->findAll();
  1494.         return $this->render('MDS/AvexpressBundle/Avexpress/list-productsfile-locationnames.html.twig',
  1495.             array(
  1496.                 'productsLocation' => $productsLocation,
  1497.             ));
  1498.     }
  1499.     /**
  1500.      * @Route("/productfilelocationedit/{id}",  name="ave_edit_productfilelocation")
  1501.      * Editar una Ubicacion
  1502.      */
  1503.     public function editProductFileLocationAction$idRequest $request)
  1504.     {
  1505.         $em $this->getDoctrine()->getManager();
  1506.         $editProductLocation $em->getRepository(AveProductFileLocationNames::class)->findOneById($id);
  1507.         return $this->render('MDS/AvexpressBundle/Avexpress/edit-productsfiles-location.html.twig',
  1508.             array(
  1509.                 'id' => $editProductLocation->getId(),
  1510.                 'productLocation' => $editProductLocation,
  1511.             ));
  1512.     }
  1513.     /**
  1514.      * @Route("/productfilelocationupdate/",  name="ave_update_productfilelocation")
  1515.      * Update de una Ubicacion
  1516.      */
  1517.     public function updateProductFileLocationAction(Request $request)
  1518.     {
  1519.         $em $this->getDoctrine()->getManager();
  1520.         $newRequest $request->request->get('product');
  1521.         $id $newRequest['id'];
  1522.         $newProduct $em->getRepository(AveProductFileLocationNames::class)->findOneById($id);
  1523.         /* Obtengo usuario logueado */
  1524.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1525.         $user_id $user_logueado->getId();
  1526.         if (!empty($newRequest['name'])){$newProduct->setName($newRequest['name']);}
  1527.         $newProduct->setDescription($newRequest['description']);
  1528.         $newProduct->setUpdatedId($user_id);
  1529.         $newProduct->setUpdatedAt(new \DateTime("now"));
  1530.         $em->persist($newProduct);
  1531.         $em->flush();
  1532.         return $this->redirectToRoute('ave_list_productfilelocation');
  1533.     }
  1534.     /**
  1535.      * @Route("/productfilelocationdelete/{id}",  name="ave_delete_productfilelocation")
  1536.      * Eliminar una Ubicacion
  1537.      */
  1538.     public function deleteProductAction($idRequest $request)
  1539.     {
  1540.         $em $this->getDoctrine()->getManager();
  1541.         $delProduct $em->getRepository(AveProductFileLocationNames::class)->findOneById($id);
  1542.         if (!empty($delProduct)){
  1543.             $em->remove($delProduct);
  1544.             $em->flush();
  1545.         }
  1546.         return $this->redirectToRoute('ave_list_productfilelocation');
  1547.     }
  1548.     // Replicar cambios entre FileController y ProductsFilesController
  1549.     private function calculosFile($id$arrayBools$number$type)
  1550.     {
  1551.         // $id Id del Expediente (File)
  1552.         // $arrayBool arreglo de logicos
  1553.         // $number  *********************
  1554.         // $type tipo de calculos a realizar (edicion de expediente, factura, factura de deposito, proforma)
  1555.         
  1556.         
  1557.         $em $this->getDoctrine()->getManager();
  1558.         $file $em->getRepository(AveFiles::class)->findOneById($id);
  1559.         $items $em->getRepository(AveProductFile::class)->findByFileId($file->getId());
  1560.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('3');
  1561.         $client $em->getRepository(Client::class)->findById($file->getClient());
  1562.         if (!empty($client)){
  1563.             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  1564.             $client[0]->setPopulation($city);
  1565.             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  1566.             $client[0]->setRegion($region);
  1567.             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  1568.             $client[0]->setCountry($country);
  1569.         } else {
  1570.             $client[0] = new Client();
  1571.             $client[0]->setName('');
  1572.             $client[0]->setTitle('');
  1573.             $client[0]->setIdDocument('');
  1574.             $client[0]->setPopulation('');
  1575.             $client[0]->setRegion('');
  1576.             $client[0]->setCountry('');
  1577.         }
  1578.         // Acumuladores de los calculos
  1579.         $totales_neto_all 0;
  1580.         $data_iva = array(
  1581.             'iva' => 21,
  1582.             'ivaMontoVeintiUno' => 0,
  1583.             'ivaMontoDiez' => 0,
  1584.             'ivaMontoCero' => 0,
  1585.         );
  1586.         //INICIO: Determinamos el numero de factura o proforma
  1587.         if (substr($number,0,1) == 'I'){
  1588.             // Es una Factura
  1589.             $numberInvoiceOrProforma substr($number,1);
  1590.             $number $numberInvoiceOrProforma;
  1591.             $type 'Invoice';
  1592.         } else {
  1593.             // Es una Proforma
  1594.             $numberInvoiceOrProforma substr($number,1);
  1595.             $number $numberInvoiceOrProforma;
  1596.             $type 'Proforma';
  1597.         }
  1598.         //FIN: Determinamos el numero de factura o proforma
  1599.         // Buscamos las salas reservadas, pagos y servicios para el evento
  1600.         $arrayItems = array();
  1601.         $fileProducts = array();
  1602.         if (!empty($arrayBools['lounge'])) {
  1603.             foreach ($arrayBools['lounge'] as $key => $item) {
  1604.                 if ($item == 'true') {
  1605. //                    $fileProducts[] = $em->getRepository('DevelupBundle:ReservationLoungeSimple')->findOneById($key);
  1606.                 }
  1607.             }
  1608.         }
  1609.         $payments = array();
  1610.         if (!empty($arrayBools['payment'])) {
  1611.             foreach ($arrayBools['payment'] as $key => $item) {
  1612.                 if ($item == 'true') {
  1613. //                    $payments[] = $em->getRepository('DevelupBundle:ReservationPaymentsClient')->findOneById($key);
  1614.                 }
  1615.             }
  1616.         }
  1617.         $services = array();
  1618.         if (!empty($arrayBools['service'])) {
  1619.             foreach ($arrayBools['service'] as $key => $item) {
  1620.                 if ($item == 'true') {
  1621. //                    $services[] = $em->getRepository('DevelupBundle:ReservationService')->findOneById($key);
  1622.                 }
  1623.             }
  1624.         }
  1625.         $data_supplier = array();
  1626.         $i 0;
  1627.         $iva '21';            // Esteban Rincon: "Por Ley de localizaciĆ³n del impuesto, siempre serĆ” un 21%"
  1628.         $pax '-';
  1629.         $qty '1';
  1630.         $product = array(
  1631.             'neto' => 0,
  1632.             'sumSubT' => 0,
  1633.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  1634.         $service = array(
  1635.             'neto' => 0,
  1636.             'sumSubT' => 0,
  1637.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  1638.         if (empty($items)){
  1639.             $data_supplier['product'][0] = null;
  1640.         }
  1641.         foreach ($items as $item){
  1642.             if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
  1643.                 $subtotal 0;
  1644.                 $neto 0;
  1645.                 $subtotalProduct 0;
  1646.             } else {
  1647.                 $subtotalProduct $item->getServicePrice() * 1.21;
  1648.                 $subneto $item->getServicePrice();
  1649.                 $subtotal =  $subtotalProduct;
  1650.                 $neto =  $subneto;
  1651.                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  1652.                 $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  1653.                 $neto round($neto,2,PHP_ROUND_HALF_UP);
  1654.                 $arrayItems[] = array(
  1655.                     'type' => 'Product',
  1656.                     'name' => $item->getProductName(),
  1657.                     'amount' => $neto,
  1658.                     'iva' => '21',
  1659.                     'total' => $subtotal,
  1660.                 );
  1661.             }
  1662.             // Acumula netos totales e IVA
  1663.             $totales_neto_all $totales_neto_all $neto;
  1664.             $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto 0.21);
  1665.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  1666.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  1667.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  1668.             // Acumula netos totales e IVA
  1669.             $product['neto'] = $product['neto'] + $neto;
  1670.             $product['sumSubT'] = $product['sumSubT'] + $subtotal;
  1671.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  1672.             $product['neto'] = round($product['neto'],2,PHP_ROUND_HALF_UP);
  1673.             $product['sumSubT'] = round($product['sumSubT'],2,PHP_ROUND_HALF_UP);
  1674.             $data_supplier['product'][$i] = array (
  1675.                 'id' => $item->getId(),
  1676.                 'productName' => $item->getProductName(),
  1677.                 'description' => $item->getDescription(),
  1678.                 'productId' => $item->getProductId(),
  1679.                 'dateStart' => $item->getDateStart(),
  1680.                 'dateEnd' => $item->getDateEnd(),
  1681.                 'servicePrice' => $item->getServicePrice(),
  1682.                 'subtotalProduct' => $subtotalProduct,
  1683.                 'iva' => $iva,
  1684.                 'pax' => $pax,
  1685.                 'qty' => $qty,
  1686.                 'type' => $item->getType(),
  1687.                 'subtotal' => $subtotal,
  1688.             );
  1689.             $i++;
  1690.         }
  1691.         $data_supplier['productSubTotal'] = array(
  1692.             'neto' => $product['neto'],
  1693.             'sumSubT' => $product['sumSubT'],
  1694.         );
  1695.         $payment = array(
  1696.             'sumSubT' => 0,
  1697.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  1698.         $i 0;
  1699.         foreach ($payments as $item){
  1700.             $payment['sumSubT'] = $payment['sumSubT'] + $item->getAmountTotal();
  1701.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  1702.             $payment['sumSubT'] = round($payment['sumSubT'],2,PHP_ROUND_HALF_UP);
  1703.             $data_supplier['payment'][$i] = array (
  1704.                 'id' => $item->getId(),
  1705.                 'amount' => $item->getAmount(),
  1706.                 'amountTotal' => $item->getAmountTotal(),
  1707.                 'vat' => $item->getVat(),
  1708.                 'datePayAt' => $item->getDatePayAt(),
  1709.                 'wayToPay' => $item->getWayToPay(),
  1710.             );
  1711.             $arrayItems[] = array(
  1712.                 'type' => 'Payment',
  1713.                 'name' => $item->getWayToPay(),
  1714.                 'amount' => $item->getAmount(),
  1715.                 'total' => $item->getAmountTotal(),
  1716.                 'iva' => $item->getVat(),
  1717.             );
  1718.             $i++;
  1719.         }
  1720.         if (!empty($payments)) {
  1721.             $data_supplier['paymentSubTotal'] = array(
  1722.                 'sumSubT' => $payment['sumSubT'],
  1723.             );
  1724.         }
  1725.         foreach ($services as $item){
  1726.             if (is_null($item->getPrice()) or empty($item->getPrice())){
  1727.                 $subtotal 0;
  1728.                 $neto 0;
  1729.                 $subtotalService 0;
  1730.             } else {
  1731.                 $subtotalService $item->getPrice();
  1732.                 $subneto $item->getPrice();
  1733.                 // Commission
  1734.                 if ($item->getOpCommission()=='1'){
  1735.                     $subtotalService $subtotalService * (+ ($item->getCommission()/100));
  1736.                     $subneto $subneto  * (+ ($item->getCommission()/100));
  1737.                 } else {
  1738.                     $subtotalService $subtotalService * (- ($item->getCommission()/100));
  1739.                     $subneto $subneto * (- ($item->getCommission()/100));
  1740.                 }
  1741.                 // Over
  1742.                 if ($item->getOpOver()=='1'){
  1743.                     $subtotalService $subtotalService $item->getOver();
  1744.                     $subneto $subneto $item->getOver();
  1745.                 } else {
  1746.                     $subtotalService $subtotalService $item->getOver();
  1747.                     $subneto $subneto $item->getOver();
  1748.                 }
  1749.                 // IVA
  1750.                 if ($item->getOpIva()=='1'){
  1751.                     $subtotalService $subtotalService * (+ ($item->getIva()/100));
  1752.                 } else {
  1753.                     $subtotalService $item->getPrice();
  1754.                     $subneto = ($subneto 100) / (100 $item->getIva());
  1755.                 }
  1756.                 switch ($item->getServiceCatId()){
  1757.                     case 1// Alojamiento
  1758.                         // el numero de noches $numNoches; precio unitario $subneto
  1759.                         $numNoches = (($item->getDateOutAt())->diff($item->getDateInAt()))->days;
  1760.                         // La personas no afectan este calculo
  1761.                         $subtotal $subtotalService $numNoches $item->getUnits();
  1762.                         $subnetoUnit $subneto;
  1763.                         $subneto $subneto $numNoches $item->getUnits();
  1764.                         $data_supplier['service'][$i] = array (
  1765.                             'id' => $item->getId(),
  1766.                             'serviceCatId' => $item->getServiceCatId(),
  1767.                             'serviceName' => $item->getName(),
  1768.                             'serviceType' => 'Hotel',
  1769.                             'date' => ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y'),
  1770.                             'qty' => $item->getUnits(),
  1771.                             'iva' => $item->getIva(),
  1772.                             'pax' => '-',
  1773.                             'precioUnit' => $subnetoUnit,
  1774.                             'subneto' => $subneto,
  1775.                             'subtotal' => $subtotal,
  1776.                         );
  1777.                         break;
  1778.                     case 2//Actividades
  1779.                         // El nĆŗmero de personas es considerado en el calculo
  1780.                         $pax $item->getPax();
  1781.                         if (empty($pax) or $pax == "0") {
  1782.                             $pax 1;
  1783.                         }
  1784.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  1785.                         if ($days 1){
  1786.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  1787.                         } else {
  1788.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  1789.                         }
  1790.                         $subtotal $subtotalService $days $item->getUnits();
  1791.                         $subnetoUnit $subneto;
  1792.                         $subneto $subneto $days $item->getUnits();
  1793.                         $data_supplier['service'][$i] = array (
  1794.                             'id' => $item->getId(),
  1795.                             'serviceCatId' => $item->getServiceCatId(),
  1796.                             'serviceName' => $item->getName(),
  1797.                             'serviceType' => 'Actividad',
  1798.                             'date' => $dateServ,
  1799.                             'qty' => $item->getUnits(),
  1800.                             'iva' => $item->getIva(),
  1801.                             'pax' => $item->getPax(),
  1802.                             'precioUnit' => $subnetoUnit,
  1803.                             'subneto' => $subneto,
  1804.                             'subtotal' => $subtotal,
  1805.                         );
  1806.                         break;
  1807.                     case 3// AV
  1808.                         $pax $item->getPax();
  1809.                         if (empty($pax) or $pax == "0") {
  1810.                             $pax 1;
  1811.                         }
  1812.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  1813.                         if ($days 1){
  1814.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  1815.                         } else {
  1816.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  1817.                         }
  1818.                         $unitsServ $item->getUnits();
  1819.                         if (empty($unitsServ) or $unitsServ == "0") {
  1820.                             $unitsServ 1;
  1821.                         }
  1822.                         $subtotal $subtotalService $days $unitsServ $pax;
  1823.                         $subnetoUnit $subneto;
  1824.                         $subneto $subneto $days $unitsServ $pax;
  1825.                         $data_supplier['service'][$i] = array (
  1826.                             'id' => $item->getId(),
  1827.                             'serviceCatId' => $item->getServiceCatId(),
  1828.                             'serviceName' => $item->getName(),
  1829.                             'serviceType' => 'AV',
  1830.                             'date' => $dateServ,
  1831.                             'qty' => $unitsServ,
  1832.                             'iva' => $item->getIva(),
  1833.                             'pax' => $item->getPax(),
  1834.                             'precioUnit' => $subnetoUnit,
  1835.                             'subneto' => $subneto,
  1836.                             'subtotal' => $subtotal,
  1837.                         );
  1838.                         break;
  1839.                     case 4//Creative
  1840.                         $pax $item->getPax();
  1841.                         if (empty($pax) or $pax == "0") {
  1842.                             $pax 1;
  1843.                         }
  1844.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  1845.                         if ($days 1){
  1846.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  1847.                         } else {
  1848.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  1849.                         }
  1850.                         $unitsServ $item->getUnits();
  1851.                         if (empty($unitsServ) or $unitsServ == "0") {
  1852.                             $unitsServ 1;
  1853.                         }
  1854.                         $subtotal $subtotalService $days $unitsServ $pax;
  1855.                         $subnetoUnit $subneto;
  1856.                         $subneto $subneto $days $unitsServ $pax;
  1857.                         $data_supplier['service'][$i] = array (
  1858.                             'id' => $item->getId(),
  1859.                             'serviceCatId' => $item->getServiceCatId(),
  1860.                             'serviceName' => $item->getName(),
  1861.                             'serviceType' => 'Creativo',
  1862.                             'date' => $dateServ,
  1863.                             'qty' => $unitsServ,
  1864.                             'iva' => $item->getIva(),
  1865.                             'pax' => $item->getPax(),
  1866.                             'precioUnit' => $subnetoUnit,
  1867.                             'subneto' => $subneto,
  1868.                             'subtotal' => $subtotal,
  1869.                         );
  1870.                         break;
  1871.                     case 5//Cruise
  1872.                         $pax $item->getPax();
  1873.                         if (empty($pax) or $pax == "0") {
  1874.                             $pax 1;
  1875.                         }
  1876.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days);
  1877.                         if ($days 1){
  1878.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  1879.                         } else {
  1880.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  1881.                         }
  1882.                         $unitsServ $item->getUnits();
  1883.                         if (empty($unitsServ) or $unitsServ == "0") {
  1884.                             $unitsServ 1;
  1885.                         }
  1886.                         $subtotal $subtotalService $days $unitsServ $pax;
  1887.                         $subnetoUnit $subneto;
  1888.                         $subneto $subneto $days $unitsServ $pax;
  1889.                         $data_supplier['service'][$i] = array (
  1890.                             'id' => $item->getId(),
  1891.                             'serviceCatId' => $item->getServiceCatId(),
  1892.                             'serviceName' => $item->getName(),
  1893.                             'serviceType' => 'Crucero',
  1894.                             'date' => $dateServ,
  1895.                             'qty' => $unitsServ,
  1896.                             'iva' => $item->getIva(),
  1897.                             'pax' => $item->getPax(),
  1898.                             'precioUnit' => $subnetoUnit,
  1899.                             'subneto' => $subneto,
  1900.                             'subtotal' => $subtotal,
  1901.                         );
  1902.                         break;
  1903.                     case 6//Entertaiment
  1904.                         $pax $item->getPax();
  1905.                         if (empty($pax) or $pax == "0") {
  1906.                             $pax 1;
  1907.                         }
  1908.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  1909.                         if ($days 1){
  1910.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  1911.                         } else {
  1912.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  1913.                         }
  1914.                         $unitsServ $item->getUnits();
  1915.                         if (empty($unitsServ) or $unitsServ == "0") {
  1916.                             $unitsServ 1;
  1917.                         }
  1918.                         $subtotal $subtotalService $days $unitsServ $pax;
  1919.                         $subnetoUnit $subneto;
  1920.                         $subneto $subneto $days $unitsServ $pax;
  1921.                         $data_supplier['service'][$i] = array (
  1922.                             'id' => $item->getId(),
  1923.                             'serviceCatId' => $item->getServiceCatId(),
  1924.                             'serviceName' => $item->getName(),
  1925.                             'serviceType' => 'Entretenimiento',
  1926.                             'date' => $dateServ,
  1927.                             'qty' => $unitsServ,
  1928.                             'iva' => $item->getIva(),
  1929.                             'pax' => $item->getPax(),
  1930.                             'precioUnit' => $subnetoUnit,
  1931.                             'subneto' => $subneto,
  1932.                             'subtotal' => $subtotal,
  1933.                         );
  1934.                         break;
  1935.                     case 7// Gifts
  1936.                         $pax $item->getPax();
  1937.                         if (empty($pax) or $pax == "0") {
  1938.                             $pax 1;
  1939.                         }
  1940. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  1941.                         $days 1;
  1942.                         if ($days 1){
  1943.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  1944.                         } else {
  1945.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  1946.                         }
  1947.                         $unitsServ $item->getUnits();
  1948.                         if (empty($unitsServ) or $unitsServ == "0") {
  1949.                             $unitsServ 1;
  1950.                         }
  1951.                         $subtotal $subtotalService $days $unitsServ $pax;
  1952.                         $subnetoUnit $subneto;
  1953.                         $subneto $subneto $days $unitsServ $pax;
  1954.                         $data_supplier['service'][$i] = array (
  1955.                             'id' => $item->getId(),
  1956.                             'serviceCatId' => $item->getServiceCatId(),
  1957.                             'serviceName' => $item->getName(),
  1958.                             'serviceType' => 'Regalos',
  1959.                             'date' => $dateServ,
  1960.                             'qty' => $unitsServ,
  1961.                             'iva' => $item->getIva(),
  1962.                             'pax' => $item->getPax(),
  1963.                             'precioUnit' => $subnetoUnit,
  1964.                             'subneto' => $subneto,
  1965.                             'subtotal' => $subtotal,
  1966.                         );
  1967.                         break;
  1968.                     case 8//Guide
  1969.                         $pax $item->getPax();
  1970.                         if (empty($pax) or $pax == "0") {
  1971.                             $pax 1;
  1972.                         }
  1973.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  1974.                         if ($days 1){
  1975.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  1976.                         } else {
  1977.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  1978.                         }
  1979.                         $unitsServ $item->getUnits();
  1980.                         if (empty($unitsServ) or $unitsServ == "0") {
  1981.                             $unitsServ 1;
  1982.                         }
  1983.                         $subtotal $subtotalService $days $unitsServ $pax;
  1984.                         $subnetoUnit $subneto;
  1985.                         $subneto $subneto $days $unitsServ $pax;
  1986.                         $data_supplier['service'][$i] = array (
  1987.                             'id' => $item->getId(),
  1988.                             'serviceCatId' => $item->getServiceCatId(),
  1989.                             'serviceName' => $item->getName(),
  1990.                             'serviceType' => 'Regalos',
  1991.                             'date' => $dateServ,
  1992.                             'qty' => $unitsServ,
  1993.                             'iva' => $item->getIva(),
  1994.                             'pax' => $item->getPax(),
  1995.                             'precioUnit' => $subnetoUnit,
  1996.                             'subneto' => $subneto,
  1997.                             'subtotal' => $subtotal,
  1998.                         );
  1999.                         break;
  2000.                     case 9//Itineraries
  2001.                         $pax $item->getPax();
  2002.                         if (empty($pax) or $pax == "0") {
  2003.                             $pax 1;
  2004.                         }
  2005.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2006.                         if ($days 1){
  2007.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2008.                         } else {
  2009.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2010.                         }
  2011.                         $unitsServ $item->getUnits();
  2012.                         if (empty($unitsServ) or $unitsServ == "0") {
  2013.                             $unitsServ 1;
  2014.                         }
  2015.                         $subtotal $subtotalService $days $unitsServ $pax;
  2016.                         $subnetoUnit $subneto;
  2017.                         $subneto $subneto $days $unitsServ $pax;
  2018.                         $data_supplier['service'][$i] = array (
  2019.                             'id' => $item->getId(),
  2020.                             'serviceCatId' => $item->getServiceCatId(),
  2021.                             'serviceName' => $item->getName(),
  2022.                             'serviceType' => 'Itinerarios',
  2023.                             'date' => $dateServ,
  2024.                             'qty' => $unitsServ,
  2025.                             'iva' => $item->getIva(),
  2026.                             'pax' => $item->getPax(),
  2027.                             'precioUnit' => $subnetoUnit,
  2028.                             'subneto' => $subneto,
  2029.                             'subtotal' => $subtotal,
  2030.                         );
  2031.                         break;
  2032.                     case 10//Lounge  -- No Aplica
  2033. //                        $pax = $item->getPax();
  2034. //                        if (empty($pax) or $pax == "0") {
  2035. //                            $pax = 1;
  2036. //                        }
  2037. //
  2038. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  2039. //                        if ($days > 1){
  2040. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2041. //                        } else {
  2042. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2043. //                        }
  2044. //
  2045. //                        $unitsServ = $item->getUnits();
  2046. //                        if (empty($unitsServ) or $unitsServ == "0") {
  2047. //                            $unitsServ = 1;
  2048. //                        }
  2049. //
  2050. //                        $subtotal = $subtotalService * $days * $unitsServ * $pax;
  2051. //                        $subnetoUnit = $subneto;
  2052. //                        $subneto = $subneto * $days * $unitsServ * $pax;
  2053. //
  2054. //                        $data_supplier['service'][$i] = array (
  2055. //                            'id' => $item->getId(),
  2056. //                            'serviceCatId' => $item->getServiceCatId(),
  2057. //                            'serviceName' => $item->getName(),
  2058. //                            'serviceType' => 'Itinerarios',
  2059. //                            'date' => $dateServ,
  2060. //                            'qty' => $unitsServ,
  2061. //                            'iva' => $item->getIva(),
  2062. //                            'pax' => $item->getPax(),
  2063. //                            'precioUnit' => $subnetoUnit,
  2064. //                            'subneto' => $subneto,
  2065. //                            'subtotal' => $subtotal,
  2066. //                        );
  2067.                         break;
  2068.                     case 11//Menu
  2069.                         $pax $item->getPax();
  2070.                         if (empty($pax) or $pax == "0") {
  2071.                             $pax 1;
  2072.                         }
  2073.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2074.                         if ($days 1){
  2075.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2076.                         } else {
  2077.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2078.                         }
  2079.                         $unitsServ $item->getUnits();
  2080.                         if (empty($unitsServ) or $unitsServ == "0") {
  2081.                             $unitsServ 1;
  2082.                         }
  2083.                         $subtotal $subtotalService $days $unitsServ $pax;
  2084.                         $subnetoUnit $subneto;
  2085.                         $subneto $subneto $days $unitsServ $pax;
  2086.                         $data_supplier['service'][$i] = array (
  2087.                             'id' => $item->getId(),
  2088.                             'serviceCatId' => $item->getServiceCatId(),
  2089.                             'serviceName' => $item->getName(),
  2090.                             'serviceType' => 'MenĆŗ',
  2091.                             'date' => $dateServ,
  2092.                             'qty' => $unitsServ,
  2093.                             'iva' => $item->getIva(),
  2094.                             'pax' => $item->getPax(),
  2095.                             'precioUnit' => $subnetoUnit,
  2096.                             'subneto' => $subneto,
  2097.                             'subtotal' => $subtotal,
  2098.                         );
  2099.                         break;
  2100.                     case 12//Others
  2101.                         $pax $item->getPax();
  2102.                         if (empty($pax) or $pax == "0") {
  2103.                             $pax 1;
  2104.                         }
  2105.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2106.                         if ($days 1){
  2107.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2108.                         } else {
  2109.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2110.                         }
  2111.                         $unitsServ $item->getUnits();
  2112.                         if (empty($unitsServ) or $unitsServ == "0") {
  2113.                             $unitsServ 1;
  2114.                         }
  2115.                         $subtotal $subtotalService $days $unitsServ $pax;
  2116.                         $subnetoUnit $subneto;
  2117.                         $subneto $subneto $days $unitsServ $pax;
  2118.                         $data_supplier['service'][$i] = array (
  2119.                             'id' => $item->getId(),
  2120.                             'serviceCatId' => $item->getServiceCatId(),
  2121.                             'serviceName' => $item->getName(),
  2122.                             'serviceType' => 'Otros',
  2123.                             'date' => $dateServ,
  2124.                             'qty' => $unitsServ,
  2125.                             'iva' => $item->getIva(),
  2126.                             'pax' => $item->getPax(),
  2127.                             'precioUnit' => $subnetoUnit,
  2128.                             'subneto' => $subneto,
  2129.                             'subtotal' => $subtotal,
  2130.                         );
  2131.                         break;
  2132.                     case 13//Transport
  2133.                         $pax $item->getPax();
  2134.                         if (empty($pax) or $pax == "0") {
  2135.                             $pax 1;
  2136.                         }
  2137.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2138.                         if ($days 1){
  2139.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2140.                         } else {
  2141.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2142.                         }
  2143.                         $unitsServ $item->getUnits();
  2144.                         if (empty($unitsServ) or $unitsServ == "0") {
  2145.                             $unitsServ 1;
  2146.                         }
  2147.                         $subtotal $subtotalService $days $unitsServ $pax;
  2148.                         $subnetoUnit $subneto;
  2149.                         $subneto $subneto $days $unitsServ $pax;
  2150.                         $data_supplier['service'][$i] = array (
  2151.                             'id' => $item->getId(),
  2152.                             'serviceCatId' => $item->getServiceCatId(),
  2153.                             'serviceName' => $item->getName(),
  2154.                             'serviceType' => 'Transporte',
  2155.                             'date' => $dateServ,
  2156.                             'qty' => $unitsServ,
  2157.                             'iva' => $item->getIva(),
  2158.                             'pax' => $item->getPax(),
  2159.                             'precioUnit' => $subnetoUnit,
  2160.                             'subneto' => $subneto,
  2161.                             'subtotal' => $subtotal,
  2162.                         );
  2163.                         break;
  2164.                     case 14//Technology
  2165.                         $pax $item->getPax();
  2166.                         if (empty($pax) or $pax == "0") {
  2167.                             $pax 1;
  2168.                         }
  2169. //                        $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
  2170.                         $days 1;
  2171. //                        if ($days > 1){
  2172. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2173. //                        } else {
  2174. //                            $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2175. //                        }
  2176.                         $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2177.                         $unitsServ $item->getUnits();
  2178.                         if (empty($unitsServ) or $unitsServ == "0") {
  2179.                             $unitsServ 1;
  2180.                         }
  2181.                         $subtotal $subtotalService $days $unitsServ $pax;
  2182.                         $subnetoUnit $subneto;
  2183.                         $subneto $subneto $days $unitsServ $pax;
  2184.                         $data_supplier['service'][$i] = array (
  2185.                             'id' => $item->getId(),
  2186.                             'serviceCatId' => $item->getServiceCatId(),
  2187.                             'serviceName' => $item->getName(),
  2188.                             'serviceType' => 'TecnologĆ­a',
  2189.                             'date' => $dateServ,
  2190.                             'qty' => $unitsServ,
  2191.                             'iva' => $item->getIva(),
  2192.                             'pax' => $item->getPax(),
  2193.                             'precioUnit' => $subnetoUnit,
  2194.                             'subneto' => $subneto,
  2195.                             'subtotal' => $subtotal,
  2196.                         );
  2197.                         break;
  2198.                     case 15//Assisstant
  2199.                         $pax $item->getPax();
  2200.                         if (empty($pax) or $pax == "0") {
  2201.                             $pax 1;
  2202.                         }
  2203.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2204.                         if ($days 1){
  2205.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2206.                         } else {
  2207.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2208.                         }
  2209.                         $unitsServ $item->getUnits();
  2210.                         if (empty($unitsServ) or $unitsServ == "0") {
  2211.                             $unitsServ 1;
  2212.                         }
  2213.                         $subtotal $subtotalService $days $unitsServ $pax;
  2214.                         $subnetoUnit $subneto;
  2215.                         $subneto $subneto $days $unitsServ $pax;
  2216.                         $data_supplier['service'][$i] = array (
  2217.                             'id' => $item->getId(),
  2218.                             'serviceCatId' => $item->getServiceCatId(),
  2219.                             'serviceName' => $item->getName(),
  2220.                             'serviceType' => 'Asistente',
  2221.                             'date' => $dateServ,
  2222.                             'qty' => $unitsServ,
  2223.                             'iva' => $item->getIva(),
  2224.                             'pax' => $item->getPax(),
  2225.                             'precioUnit' => $subnetoUnit,
  2226.                             'subneto' => $subneto,
  2227.                             'subtotal' => $subtotal,
  2228.                         );
  2229.                         break;
  2230.                     case 16//DDR
  2231.                         $pax $item->getPax();
  2232.                         if (empty($pax) or $pax == "0") {
  2233.                             $pax 1;
  2234.                         }
  2235.                         $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days 1);
  2236.                         if ($days 1){
  2237.                             $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
  2238.                         } else {
  2239.                             $dateServ = ($item->getDateInAt())->format('d/m/Y');
  2240.                         }
  2241.                         $unitsServ $item->getUnits();
  2242.                         if (empty($unitsServ) or $unitsServ == "0") {
  2243.                             $unitsServ 1;
  2244.                         }
  2245.                         $subtotal $subtotalService $days $unitsServ $pax;
  2246.                         $subnetoUnit $subneto;
  2247.                         $subneto $subneto $days $unitsServ $pax;
  2248.                         $data_supplier['service'][$i] = array (
  2249.                             'id' => $item->getId(),
  2250.                             'serviceCatId' => $item->getServiceCatId(),
  2251.                             'serviceName' => $item->getName(),
  2252.                             'serviceType' => 'DDR',
  2253.                             'date' => $dateServ,
  2254.                             'qty' => $unitsServ,
  2255.                             'iva' => $item->getIva(),
  2256.                             'pax' => $item->getPax(),
  2257.                             'precioUnit' => $subnetoUnit,
  2258.                             'subneto' => $subneto,
  2259.                             'subtotal' => $subtotal,
  2260.                         );
  2261.                         break;
  2262.                     default:
  2263.                         break;
  2264.                 }
  2265.                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  2266.                 $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  2267.                 $neto round($subneto,2,PHP_ROUND_HALF_UP);
  2268.                 $arrayItems[] = array(
  2269.                     'type' => 'Service',
  2270.                     'name' => $item->getName(),
  2271.                     'amount' => $neto,
  2272.                     'iva' => $item->getIva(),
  2273.                     'total' => $subtotal,
  2274.                 );
  2275.             }
  2276.             switch ($item->getIva()){
  2277.                 // Acumula IVA
  2278.                 case 21:
  2279.                     $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($item->getIva()/100));
  2280.                     break;
  2281.                 case 10:
  2282.                     $data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * ($item->getIva()/100));
  2283.                     break;
  2284.                 case 0:
  2285.                     break;
  2286.                 default:
  2287.                     break;
  2288.             }
  2289.             $totales_neto_all $totales_neto_all $neto;
  2290.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  2291.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  2292.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  2293.             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
  2294.             // Acumula netos totales e IVA
  2295.             $service['neto'] = $service['neto'] + $neto;
  2296.             $service['sumSubT'] = $service['sumSubT'] + $subtotal;
  2297.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  2298.             $service['neto'] = round($service['neto'],2,PHP_ROUND_HALF_UP);
  2299.             $service['sumSubT'] = round($service['sumSubT'],2,PHP_ROUND_HALF_UP);
  2300.             $i++;
  2301.         }
  2302.         $data_supplier['serviceSubTotal'] = array(
  2303.             'neto' => $service['neto'],
  2304.             'sumSubT' => $service['sumSubT'],
  2305.         );
  2306.         $currency 'ā‚¬';
  2307.         $totales_total $totales_neto_all $data_iva['ivaMontoVeintiUno'] + $data_iva['ivaMontoDiez'];
  2308.         if (!empty($payments)) {
  2309.             $amount_pay $data_supplier['paymentSubTotal']['sumSubT'];
  2310.         } else {
  2311.             $amount_pay 0;
  2312.         }
  2313.         $totales_all $totales_total $amount_pay;
  2314.         if ($type == 'Invoice'){
  2315.             $em->clear();   // sin este clear se producia error al guardar
  2316.             $newInvoice $em->getRepository(ReservationInvoice::class)->findOneById($numberInvoiceOrProforma);
  2317.             $newInvoice->setBalance($totales_all);
  2318.             $em->persist($newInvoice);
  2319.             $em->flush();
  2320.         }
  2321.         $data = array(
  2322.             'id' => $id,
  2323.             'type' => $type,
  2324.             'number' => $number,
  2325.             'prefix' => 'GPF-'.(new DateTime('now'))->format('dmy').'-',
  2326.             'date' => new DateTime('now'),
  2327.             'file' => $file,
  2328. //            'token' => $reservation->getAccessKey(),
  2329.             'company' => $company,
  2330.             'clients' => $client,
  2331.             'arrayItems' => $arrayItems,
  2332.             'datasupplier' => $data_supplier,
  2333.             'currency' => $currency,
  2334.             'totales_neto' => $totales_neto_all,
  2335.             'bases_imponibles' => $data_iva,
  2336.             'totales' => $totales_total,
  2337.             'balance' => $totales_all,
  2338.             'paymentInvoice' => $amount_pay,
  2339.         );
  2340.         return $data;
  2341.     }
  2342.     private function obtenerRankAv($id)
  2343.     {
  2344.         // $id Id del Expediente (File)
  2345.         $em $this->getDoctrine()->getManager();
  2346.         $items $em->getRepository(AveProductFile::class)->findByFileId($id);
  2347.         if (empty($items)){ $num 1; } else { $num sizeof($items) + 1; }
  2348.         $data $num;
  2349.         return $data;
  2350.     }
  2351.     private function obtenerFechas($id$dateStart$dateEnd)
  2352.     {
  2353.         // $id Id del Expediente (File)
  2354.         // $dateStart Fecha de inicio (Producto)
  2355.         // $dateEnd Fecha de fin (Producto)
  2356.         $em $this->getDoctrine()->getManager();
  2357.         $file $em->getRepository(AveFiles::class)->findOneById($id);
  2358.         if (empty($dateStart)){ $newDateStart $file->getDateStart(); } else { $newDateStart $dateStart; }
  2359.         if (empty($dateEnd)){ $newDateEnd $file->getDateEnd(); } else { $newDateEnd $dateEnd; }
  2360.         $data = array(
  2361.             'dateStart' => $newDateStart,
  2362.             'dateEnd' => $newDateEnd,
  2363.         );
  2364.         return $data;
  2365.     }
  2366.     private function sendTelegram$id$text )
  2367.     {
  2368.         $em $this->getDoctrine()->getManager();
  2369.         $telegUser $em->getRepository(MdvTelegramUser::class)->findOneByUserId($id);
  2370.         if (empty($telegUser)){return true;}
  2371.         $parameters = array(
  2372.             'chat_id' => $telegUser->getChatId(),
  2373.             'text' => $text,
  2374.         );
  2375.         $bot_token $telegUser->getBotToken();
  2376.         $url "https://api.telegram.org/bot$bot_token/sendMessage";
  2377.         if (!$curl curl_init()){
  2378.             exit();
  2379.         }
  2380.         curl_setopt($curl,CURLOPT_POST,true);
  2381.         curl_setopt($curl,CURLOPT_POSTFIELDS,$parameters);
  2382.         curl_setopt($curl,CURLOPT_URL,$url);
  2383.         curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
  2384.         $output curl_exec($curl);
  2385.         curl_close($curl);
  2386.         return true;
  2387.     }
  2388.     private function addProductFileToProforma$fileId$newProductId$proformaId )
  2389.     {
  2390.         $em $this->getDoctrine()->getManager();
  2391.         $file $em->getRepository(AveFiles::class)->findOneById($fileId);
  2392.         $productFile $em->getRepository(AveProductFile::class)->findOneById($newProductId);
  2393.         $proforma $em->getRepository(AveDocProforma::class)->findOneById($proformaId);
  2394.         if (!empty($file) and !empty($productFile) and !empty($proforma) ){
  2395.             $newProformaItem = new AveDocProformaItems();
  2396.             $newProformaItem->setControlId($newProductId);
  2397.             $newProformaItem->setType('PRODUCT');
  2398.             $newProformaItem->setFileId($fileId);
  2399.             $newProformaItem->setProformaId($proformaId);
  2400.             $em->persist($newProformaItem);
  2401.             $em->flush();
  2402.             return true;
  2403.         } else {
  2404.             return false;
  2405.         }
  2406.     }
  2407.     private function precioPorVariacionDeDias ($supplierService$productFile){
  2408.         $em $this->getDoctrine()->getManager();
  2409.         // El precio unitario debe ser dividido en funcion de los dias que tiene InOut y no en funcion de los dias de Av Express
  2410.         $days = ($supplierService->getDateOutAt()->diff($supplierService->getDateInAt())->days)===$supplierService->getDateOutAt()->diff($supplierService->getDateInAt())->days +1;
  2411.         if (array_key_exists('productFileId',$productFile)){
  2412.             // En el GridTwo viene es un arreglo no la entidad
  2413.             $productInFile $em->getRepository(AveProductFile::class)->findOneById($productFile['productFileId']);
  2414.             $newPrice $productInFile->getSubTotalPrice() / ( $days );
  2415.         } else {
  2416.             $newPrice $productFile->getSubTotalPrice() / ( $days );
  2417.         }
  2418.         $newPrice $newPrice $supplierService->getUnits();
  2419.         $newPrice round($newPrice,2,PHP_ROUND_HALF_UP);
  2420.         return $newPrice;
  2421.     }
  2422.     private function messageOfChangesToAgent($message$proposalId){
  2423.         // $message mensaje a enviar a los agentes del proposal
  2424.         if ($proposalId  == 0){ return true; }
  2425.         $em $this->getDoctrine()->getManager();
  2426.         $proposal $em->getRepository(Proposal::class)->findOneById($proposalId);
  2427.         /* Obtengo usuario logueado */
  2428.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2429.         $user_id $user_logueado->getId();
  2430.         $agent $em->getRepository(User::class)->findOneById($user_id);
  2431.         $message 'El proposal <strong>#'.$proposalId.' '.$proposal->getName().'</strong>'.' ha sido modificacdo por el agente: '.$agent->getName().' '.$agent->getLastName().'<br><br><br>'.$message;
  2432.         $proposalAgents $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposalId);
  2433.         $mailArrayTo = array();
  2434.         if (!empty($agent)){ $mailArrayTo[$agent->getEmail()] = $agent->getEmail(); }
  2435.         if (!empty($proposalAgents)){
  2436.             if (!empty($proposalAgents->getAgOne())){
  2437.                 $agent $em->getRepository(User::class)->findOneById($proposalAgents->getAgOne());
  2438.                 $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  2439.             }
  2440.             if (!empty($proposalAgents->getAgTwo())){
  2441.                 $agent $em->getRepository(User::class)->findOneById($proposalAgents->getAgTwo());
  2442.                 $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  2443.             }
  2444.             if (!empty($proposalAgents->getAgThree())){
  2445.                 $agent $em->getRepository(User::class)->findOneById($proposalAgents->getAgThree());
  2446.                 $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  2447.             }
  2448.             if (!empty($proposalAgents->getAgFour())){
  2449.                 $agent $em->getRepository(User::class)->findOneById($proposalAgents->getAgFour());
  2450.                 $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  2451.             }
  2452.         }
  2453.         if (!empty($mailArrayTo)){
  2454.             $mailArrayTo[$agent->getEmail()] = $agent->getEmail();
  2455.             $replyTo = array();
  2456.             foreach ($mailArrayTo as $item){ $replyTo[$item] = $item; }
  2457.             $agentMail $agent->getEmail();
  2458.             //Se prepara el correo con los agentes a notificar
  2459.             $firmGmail $agent->getFirmGmail();
  2460.             $data = array(
  2461.                 'body' => $message,
  2462.                 'firm' => $firmGmail,
  2463.             );
  2464.             // EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
  2465.             $transporter = new Swift_SmtpTransport();
  2466.             $transporter->setHost('smtp.gmail.com')
  2467.                 ->setEncryption('ssl')//ssl / tls
  2468.                 ->setPort(465)// 465 / 587
  2469.                 ->setUsername('desarrollo@develup.solutions')
  2470.                 ->setPassword('MeDITeRRANeAN_Develup30102023#');
  2471.             $mailer = new Swift_Mailer($transporter);
  2472.             $message = new Swift_Message();
  2473.             $message->setSubject('ActualizaciĆ³n de servicios AvExpress del proposal: '$proposalId)
  2474.                 ->setSender($agentMail)
  2475.                 ->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
  2476.                 ->setReplyTo($agentMail)
  2477.                 ->setTo($replyTo)
  2478.                 ->setBody(
  2479.                     $this->renderView(
  2480.                         'mail/structure-mail.html.twig',
  2481.                         array('data' => $data)
  2482.                     ),
  2483.                     'text/html'
  2484.                 );
  2485.             $mailer->send($message);
  2486.         }
  2487.         return true;
  2488.     }
  2489. };