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