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

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