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