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

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