src/MDS/GreenPatioBundle/Controller/ReservationsListingsController.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\MDS\GreenPatioBundle\Controller;
  3. use App\Entity\Client;
  4. use App\Entity\Configuration;
  5. use App\Entity\SettingsCompany;
  6. use App\Entity\User;
  7. use App\MDS\GreenPatioBundle\Entity\Reservation;
  8. use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceItems;
  9. use App\MDS\GreenPatioBundle\Entity\ReservationLoungeDetails;
  10. use App\MDS\GreenPatioBundle\Entity\ReservationLoungeSimple;
  11. use App\MDS\GreenPatioBundle\Entity\CvrReservationInvoiceItems;
  12. use App\MDS\GreenPatioBundle\Entity\BlvReservationInvoiceItems;
  13. use Google\Service\MigrationCenterAPI\DateTime;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  19. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  20. use PhpOffice\PhpSpreadsheet\Style\Fill;
  21. use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
  22. use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
  23. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  24. use Symfony\Component\HttpFoundation\StreamedResponse;
  25. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  26. class ReservationsListingsController extends AbstractController
  27. {
  28.     /**
  29.      * @Route("/liststatistics/",  name="reservations_greenpatio_list_statistics")
  30.      */
  31.     public function listStatisticsReservationAction(EntityManagerInterface $emRequest $request)
  32.     {
  33.         $clients $em->getRepository(Client::class)->findAll();
  34.         $salas $em->getRepository(ReservationLoungeDetails::class)->findAll();
  35.         return $this->render('MDS/GreenPatioBundle/reservations/list-statistics.html.twig',
  36.             array(
  37.                 'data' => null,
  38.                 'clients' => $clients,
  39.                 'clientId' => 0,
  40.                 'salas' => $salas,
  41.                 'consulta' => null,
  42.                 'dateStartReq' => null,
  43.                 'dateEndReq' => null,
  44.             ));
  45.     }
  46.     /**
  47.      * @Route("/responseliststatistics/",  name="reservations_greenpatio_response_list_statistics")
  48.      */
  49.     public function responseListStatisticsReservationAction(EntityManagerInterface $emRequest $request)
  50.     {
  51.         $salas $em->getRepository(ReservationLoungeDetails::class)->findAll();
  52.         $dateRequest $request->request->get('forecast');
  53.         $clientId $request->request->get('client');
  54.         $boolStatus $request->request->get('boolStatus');
  55.         $selectedSalasNames $request->request->get('selected_salas');
  56.         $arraySalasId = empty($request->request->get('tags')) ? null $request->request->get('tags')['tags2'];
  57.         $dateStartReq $dateRequest['date_start'];
  58.         $dateEndReq $dateRequest['date_end'];
  59.         $data = [];
  60.         $data $this->baseForecast($dateStartReq,$dateEndReq$boolStatus$clientId$arraySalasId);
  61.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  62.         $clients $em->getRepository(Client::class)->findAll();
  63.         $consulta 'Del '. (new \DateTime($dateStartReq))->format('d/m/Y').' al '.(new \DateTime($dateEndReq))->format('d/m/Y').',';
  64.         if (!empty($boolStatus['Blocked']) and
  65.             !empty($boolStatus['Confirmed']) and
  66.             !empty($boolStatus['Quoted']) and
  67.             !empty($boolStatus['Invoiced']) and
  68.             !empty($boolStatus['Cancel'])
  69.         ){
  70.             $consulta.=' todos los expedientes,';
  71.         } else {
  72.             $consulta.=' los expedientes';
  73.             if (!empty($boolStatus['Blocked'])) { $consulta .= ' Bloqueados,'; }
  74.             if (!empty($boolStatus['Confirmed'])) { $consulta .= ' Confirmados,'; }
  75.             if (!empty($boolStatus['Quoted'])) { $consulta .= ' Cotizados,'; }
  76.             if (!empty($boolStatus['Invoiced'])) { $consulta .= ' Facturados,'; }
  77.             if (!empty($boolStatus['Cancel'])) { $consulta .= ' Cancelados,'; }
  78.         }
  79.         if(empty($selectedSalasNames)) { $consulta.= ' de todas las salas.'; } else { $consulta.= ' en '.$selectedSalasNames.'.'; }
  80.         $boolBlocked = !empty($boolStatus['Blocked']) ? true false ;
  81.         $boolConfirmed = !empty($boolStatus['Confirmed']) ? true false;
  82.         $boolQuoted = !empty($boolStatus['Quoted']) ? true false;
  83.         $boolInvoiced = !empty($boolStatus['Invoiced']) ? true false;
  84.         $boolCancel = !empty($boolStatus['Cancel']) ? true false;
  85.         return $this->render('MDS/GreenPatioBundle/reservations/list-statistics.html.twig',
  86.             array(
  87.                 'data' => $data['reservations'],
  88.                 'clients' => $clients,
  89.                 'salas' => $salas,
  90.                 'consulta' => $consulta,
  91.                 'company' => $company,
  92.                 'clientId' => $clientId,
  93.                 'dateStartReq' => $dateStartReq,
  94.                 'dateEndReq' => $dateEndReq,
  95.                 'boolBlocked' => $boolBlocked,
  96.                 'boolConfirmed' => $boolConfirmed,
  97.                 'boolQuoted' => $boolQuoted,
  98.                 'boolInvoiced' => $boolInvoiced,
  99.                 'boolCancel' => $boolCancel,
  100.                 'selectedSalasNames' => $selectedSalasNames,
  101.                 'arraySalasId' => empty($arraySalasId) ? null implode(","$arraySalasId),
  102.                 'netoForeCast' => $data['netoForeCast'],
  103.                 'vatForeCast' => $data['vatForeCast'],
  104.                 'totalForeCast' => $data['totalForeCast'],
  105.             ));
  106.     }
  107.     /**
  108.      * @Route("/createforecastprint/{dateStartReq}/{dateEndReq}",  name="reservations_greenpatio_createforecastprint")
  109.      * Se genera una prevision de ventas con los datos recibidos en una pantalla para imprimir
  110.      */
  111.     public function printForecastAction($dateStartReq$dateEndReqRequest $request)
  112.     {
  113.         $em $this->getDoctrine()->getManager();
  114.         $clientId '';
  115.         $boolStatus = array(
  116.             'Confirmed' => 'on',
  117.             'Quoted' => 'on',
  118.             'Blocked' => 'on',
  119.             'Invoiced' => 'on',
  120.         );
  121.         $arraySalasId = empty($request->request->get('tags')) ? null $request->request->get('tags')['tags2'];
  122.         $data = array();
  123.         $data $this->baseForecast($dateStartReq,$dateEndReq$boolStatus$clientId$arraySalasId);
  124.         $months = array(
  125.             '01' => 'Enero',
  126.             '02' => 'Febrero',
  127.             '03' => 'Marzo',
  128.             '04' => 'Abril',
  129.             '05' => 'Mayo',
  130.             '06' => 'Junio',
  131.             '07' => 'Julio',
  132.             '08' => 'Agosto',
  133.             '09' => 'Septiembre',
  134.             '10' => 'Octubre',
  135.             '11' => 'Noviembre',
  136.             '12' => 'Diciembre',
  137.         );
  138.         $hoy = new \DateTime("now"NULL);
  139.         $yearActual $hoy->format('Y');
  140.         $monthActual $hoy->format('m');
  141.         $years = array();
  142.         $yearActual++;
  143.         for ($i 2019$i $yearActual$i++){
  144.             array_unshift($years,$i);               // Se genera el arreglo [2021,2020,2019] - En el 2019 es el inicio de las reservas
  145.         }
  146.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  147.         return $this->render('MDS/GreenPatioBundle/reservations/list-forecast-print.html.twig',
  148.             array(
  149.                 'company' => $company,
  150.                 'months' => $months,
  151.                 'monthActual' => $monthActual,
  152.                 'years' => $years,
  153.                 'yearActual' => $yearActual,
  154.                 'dateStartReq' => $dateStartReq,
  155.                 'dateEndReq' => $dateEndReq,
  156.                 'data' => $data['reservations'],
  157.                 'netoForeCast' => $data['netoForeCast'],
  158.                 'vatForeCast' => $data['vatForeCast'],
  159.                 'totalForeCast' => $data['totalForeCast'],
  160.             )
  161.         );
  162.     }
  163.     /**
  164.      * @Route("/xlsstatistics/",  name="excel_statistics")
  165.      * Estadisticas de Green Patio en xls
  166.      */
  167.     public function excelStatisticsAction(EntityManagerInterface $emRequest $request)
  168.     {
  169.         $dateStartReq $request->request->get('xls')['dateStartReq'];
  170.         $dateEndReq $request->request->get('xls')['dateEndReq'];
  171.         $clientId $request->request->get('xls')['clientId'];
  172.         $boolStatus = array();
  173.         if (!empty($request->request->get('xls')['boolBlocked'])){ $boolStatus['Blocked'] = 'on'; }
  174.         if (!empty($request->request->get('xls')['boolConfirmed'])){ $boolStatus['Confirmed'] = 'on'; }
  175.         if (!empty($request->request->get('xls')['boolQuoted'])){ $boolStatus['Quoted'] = 'on'; }
  176.         if (!empty($request->request->get('xls')['boolInvoiced'])){ $boolStatus['Invoiced'] = 'on'; }
  177.         if (!empty($request->request->get('xls')['boolCancel'])){ $boolStatus['Cancel'] = 'on'; }
  178.         $selectedSalasNames $request->request->get('xls')['selectedSalasNames'];
  179.         $arraySalasId = !empty($request->request->get('xls')['arraySalasId']) ? explode(","$request->request->get('xls')['arraySalasId']) : null ;
  180.         $data = array();
  181.         $data $this->baseForecast($dateStartReq,$dateEndReq$boolStatus$clientId$arraySalasId);
  182.         $consulta 'del '. (new \DateTime($dateStartReq))->format('d/m/Y').' al '.(new \DateTime($dateEndReq))->format('d/m/Y').',';
  183.         if (!empty($boolStatus['Blocked']) and
  184.             !empty($boolStatus['Confirmed']) and
  185.             !empty($boolStatus['Quoted']) and
  186.             !empty($boolStatus['Invoiced']) and
  187.             !empty($boolStatus['Cancel'])
  188.         ){
  189.             $consulta.=' todos los expedientes,';
  190.         } else {
  191.             $consulta.=' los expedientes';
  192.             if (!empty($boolStatus['Blocked'])) { $consulta .= ' Bloqueados,'; }
  193.             if (!empty($boolStatus['Confirmed'])) { $consulta .= ' Confirmados,'; }
  194.             if (!empty($boolStatus['Quoted'])) { $consulta .= ' Cotizados,'; }
  195.             if (!empty($boolStatus['Invoiced'])) { $consulta .= ' Facturados,'; }
  196.             if (!empty($boolStatus['Cancel'])) { $consulta .= ' Cancelados,'; }
  197.         }
  198.         if(empty($selectedSalasNames)) { $consulta.= ' de todas las salas.'; } else { $consulta.= ' en '.$selectedSalasNames.'.'; }
  199.         // Solicita el servicio de excel
  200.         $phpExcelObject = new Spreadsheet();
  201.         $phpExcelObject->getProperties()->setCreator("Grupo Green Patio")
  202.             ->setLastModifiedBy("Grupo Green Patio")
  203.             ->setTitle("Grupo Green Patio")
  204.             ->setSubject("Grupo Green Patio")
  205.             ->setDescription("Grupo Green Patio, generado usando clases de PHP")
  206.             ->setKeywords("office 2005 openxml php")
  207.             ->setCategory("Archivo de estadisticas");
  208.         $fill = new Fill();
  209.         $numberFormat = new NumberFormat();
  210.         $alignment = new Alignment();
  211.         $i 6;
  212.         $indiceInicial 7;
  213.         $indiceFinal 7;
  214.         $activesheet $phpExcelObject->getActiveSheet();
  215.         $drawingobject = new Drawing();
  216.         $drawingobject->setName('Image name');
  217.         $drawingobject->setDescription('Image description');
  218.         $drawingobject->setPath(getcwd() . '/assets/images/logo/logo_green_patio.png');
  219.         $drawingobject->setHeight(60);
  220.         $drawingobject->setOffsetY(20);
  221.         $drawingobject->setCoordinates('Q1');
  222.         $drawingobject->setWorksheet($activesheet);
  223.         $phpExcelObject
  224.             ->getActiveSheet()
  225.             ->getStyle('B3:O3')
  226.             ->getFill()
  227.             ->setFillType($fill::FILL_SOLID)
  228.             ->getStartColor()
  229.             ->setRGB('9ba67c');
  230.         $phpExcelObject->setActiveSheetIndex(0)
  231.             ->setCellValue('C3''Estadísticas ' $consulta);
  232.         $phpExcelObject
  233.             ->getActiveSheet()
  234.             ->getStyle('B' $i ':R' $i)
  235.             ->getFill()
  236.             ->setFillType($fill::FILL_SOLID)
  237.             ->getStartColor()
  238.             ->setRGB('d1d1cf');
  239.         $phpExcelObject->setActiveSheetIndex(0)
  240.             ->setCellValue('B' $i'Fecha')
  241.             ->setCellValue('D' $i'Nombre')
  242.             ->setCellValue('H' $i'Expediente')
  243.             ->setCellValue('J' $i'Cliente')
  244.             ->setCellValue('N' $i'Venta Neta')
  245.             ->setCellValue('P' $i'Iva')
  246.             ->setCellValue('R' $i'Total');
  247.         $phpExcelObject->getActiveSheet()->getStyle('N' $i)
  248.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  249.         $phpExcelObject->getActiveSheet()->getStyle('P' $i)
  250.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  251.         $phpExcelObject->getActiveSheet()->getStyle('R' $i)
  252.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  253.         foreach ($data['reservations'] as $item) {
  254.             $phpExcelObject
  255.                 ->getActiveSheet()
  256.                 ->getStyle('N' . ($i 1))
  257.                 ->getNumberFormat()
  258.                 ->setFormatCode('#,##0.00');
  259.             $phpExcelObject
  260.                 ->getActiveSheet()
  261.                 ->getStyle('P' . ($i 1))
  262.                 ->getNumberFormat()
  263.                 ->setFormatCode('#,##0.00');
  264.             $phpExcelObject
  265.                 ->getActiveSheet()
  266.                 ->getStyle('R' . ($i 1))
  267.                 ->getNumberFormat()
  268.                 ->setFormatCode('#,##0.00');
  269.             $phpExcelObject->setActiveSheetIndex(0)
  270.                 ->setCellValue('B' . ($i 1), $item['dateStart']->format('d/m/Y'))
  271.                 ->setCellValue('D' . ($i 1), $item['title'])
  272.                 ->setCellValue('H' . ($i 1), $item['reservationId'])
  273.                 ->setCellValue('J' . ($i 1), $item['clientName'])
  274.                 ->setCellValue('N' . ($i 1), $item['neto'])
  275.                 ->setCellValue('P' . ($i 1), $item['vat'])
  276.                 ->setCellValue('R' . ($i 1), $item['total']);
  277.             $i++;
  278.             $indiceFinal++;
  279.         }
  280.         $indiceFinal--;
  281.         $phpExcelObject
  282.             ->getActiveSheet()
  283.             ->getStyle('L' . ($indiceFinal 3) . ':' 'R' . ($indiceFinal 3))
  284.             ->getFill()
  285.             ->setFillType($fill::FILL_SOLID)
  286.             ->getStartColor()
  287.             ->setRGB('9ba67c');
  288.         $phpExcelObject
  289.             ->getActiveSheet()
  290.             ->getStyle('N' . ($indiceFinal 4))
  291.             ->getNumberFormat()
  292.             ->setFormatCode('#,##0.00 â‚¬');
  293.         $phpExcelObject
  294.             ->getActiveSheet()
  295.             ->getColumnDimension('N')
  296.             ->setAutoSize(true);
  297.         $phpExcelObject
  298.             ->getActiveSheet()
  299.             ->getStyle('P' . ($indiceFinal 4))
  300.             ->getNumberFormat()
  301.             ->setFormatCode('#,##0.00 â‚¬');
  302.         $phpExcelObject
  303.             ->getActiveSheet()
  304.             ->getColumnDimension('P')
  305.             ->setAutoSize(true);
  306.         $phpExcelObject
  307.             ->getActiveSheet()
  308.             ->getStyle('R' . ($indiceFinal 4))
  309.             ->getNumberFormat()
  310.             ->setFormatCode('#,##0.00 â‚¬');
  311.         $phpExcelObject
  312.             ->getActiveSheet()
  313.             ->getColumnDimension('R')
  314.             ->setAutoSize(true);
  315.         $phpExcelObject->setActiveSheetIndex(0)
  316.             ->setCellValue('N' . ($indiceFinal 3), 'Neto')
  317.             ->setCellValue('P' . ($indiceFinal 3), 'Iva')
  318.             ->setCellValue('R' . ($indiceFinal 3), 'Total');
  319.         $phpExcelObject->getActiveSheet()->getStyle('N' . ($indiceFinal 3))
  320.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  321.         $phpExcelObject->getActiveSheet()->getStyle('P' . ($indiceFinal 3))
  322.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  323.         $phpExcelObject->getActiveSheet()->getStyle('R' . ($indiceFinal 3))
  324.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  325.         $phpExcelObject->setActiveSheetIndex(0)
  326.             ->setCellValue('N' . ($indiceFinal 4), '=SUM(' 'N' $indiceInicial ' : N' $indiceFinal ')')
  327.             ->setCellValue('P' . ($indiceFinal 4), '=SUM(' 'P' $indiceInicial ' : P' $indiceFinal ')')
  328.             ->setCellValue('R' . ($indiceFinal 4), '=SUM(' 'R' $indiceInicial ' : R' $indiceFinal ')');
  329.         $phpExcelObject->getActiveSheet()->setTitle('Estadísticas');
  330.         // Define el indice de página al número 1, para abrir esa página al abrir el archivo
  331.         $phpExcelObject->setActiveSheetIndex(0);
  332.         // Creamos pagina de Datos en bruto para Esteban Rincon
  333.         // Add new sheet
  334.         $objWorkSheet $phpExcelObject->createSheet(1); //Setting index when creating
  335.         $phpExcelObject->setActiveSheetIndex(1);
  336.         $phpExcelObject->getActiveSheet()->setTitle('Datos en bruto');
  337.         $x 1;
  338.         $phpExcelObject->setActiveSheetIndex(1)
  339.             ->setCellValue('A' $x'Fecha')
  340.             ->setCellValue('B' $x'Nombre')
  341.             ->setCellValue('C' $x'Expediente')
  342.             ->setCellValue('D' $x'Cliente')
  343.             ->setCellValue('E' $x'Venta Neta')
  344.             ->setCellValue('F' $x'Iva')
  345.             ->setCellValue('G' $x'Total');
  346.         foreach ($data['reservations'] as $item) {
  347.             $phpExcelObject->setActiveSheetIndex(1)
  348.                 ->setCellValue('A' . ($x 1), $item['dateStart']->format('d/m/Y'))
  349.                 ->setCellValue('B' . ($x 1), $item['title'])
  350.                 ->setCellValue('C' . ($x 1), $item['reservationId'])
  351.                 ->setCellValue('D' . ($x 1), $item['clientName'])
  352.                 ->setCellValue('E' . ($x 1), $item['neto'])
  353.                 ->setCellValue('F' . ($x 1), $item['vat'])
  354.                 ->setCellValue('G' . ($x 1), $item['total']);
  355.             $x++;
  356.         }
  357.         $phpExcelObject->setActiveSheetIndex(0);
  358.         // Crea el writer
  359.         $writer = new Xlsx($phpExcelObject);
  360.         // Envia la respuesta del controlador
  361.         $response = new StreamedResponse(
  362.             function () use ($writer) {
  363.                 $writer->save('php://output');
  364.             }
  365.         );
  366.         // Agrega los headers requeridos
  367.         $dispositionHeader $response->headers->makeDisposition(
  368.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  369.             'Grupo_Green_Patio' '.xlsx'
  370.         );
  371.         $response->headers->set('Content-Type''application/vnd.ms-excel; charset=utf-8');
  372.         $response->headers->set('Pragma''public');
  373.         $response->headers->set('Cache-Control''maxage=1');
  374.         $response->headers->set('Content-Disposition'$dispositionHeader);
  375.         $tot $indiceFinal 7;
  376.         $phpExcelObject->setActiveSheetIndex(0)
  377.             ->setCellValue('L' . ($tot 2), 'Grupo Green Patio')
  378.             ->setCellValue('L' . ($tot 3), 'comercial@greenpatio.es')
  379.             ->setCellValue('L' . ($tot 4), '+34 669 01 88 34');
  380.         $phpExcelObject
  381.             ->getActiveSheet()
  382.             ->getStyle('k' . ($tot 2) . ':' 'O' . ($tot 4))
  383.             ->getFill()
  384.             ->setFillType($fill::FILL_SOLID)
  385.             ->getStartColor()
  386.             ->setRGB('9ba67c');
  387.         $phpExcelObject->getActiveSheet()->setTitle('Estadísticas');
  388.         // Define el indice de página al número 1, para abrir esa página al abrir el archivo
  389.         $phpExcelObject->setActiveSheetIndex(0);
  390.         // Crea el writer
  391.         $writer = new Xlsx($phpExcelObject);
  392.         // Envia la respuesta del controlador
  393.         $response = new StreamedResponse(
  394.             function () use ($writer) {
  395.                 $writer->save('php://output');
  396.             }
  397.         );
  398.         // Agrega los headers requeridos
  399.         $dispositionHeader $response->headers->makeDisposition(
  400.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  401.             'Green Patio - Estadisticas' '.xlsx'
  402.         );
  403.         $response->headers->set('Content-Type''application/vnd.ms-excel; charset=utf-8');
  404.         $response->headers->set('Pragma''public');
  405.         $response->headers->set('Cache-Control''maxage=1');
  406.         $response->headers->set('Content-Disposition'$dispositionHeader);
  407.         return $response;
  408.     }
  409.     /**
  410.      * @Route("/liststatisticsproducts/",  name="reservations_greenpatio_list_statistics_products")
  411.      * Estadisticas por Porductos (Salas y Servicios)
  412.      */
  413.     public function listStatisticsReservationProductsAction(EntityManagerInterface $emRequest $request)
  414.     {
  415.         $clients $em->getRepository(Client::class)->findAll();
  416.         $salas $em->getRepository(ReservationLoungeDetails::class)->findAll();
  417.         return $this->render('MDS/GreenPatioBundle/reservations/list-statistics-products.html.twig',
  418.             array(
  419.                 'data' => null,
  420.                 'clients' => $clients,
  421.                 'clientId' => 0,
  422.                 'salas' => $salas,
  423.                 'consulta' => null,
  424.                 'dateStartReq' => null,
  425.                 'dateEndReq' => null,
  426.             ));
  427.     }
  428.     /**
  429.      * @Route("/responseliststatisticsproducts/",  name="reservations_greenpatio_response_list_statistics_products")
  430.      * Respuesta de la consulta de productos
  431.      */
  432.     public function responseListStatisticsReservationProductsAction(EntityManagerInterface $emRequest $request)
  433.     {
  434.         $salas $em->getRepository(ReservationLoungeDetails::class)->findAll();
  435.         $dateRequest $request->request->get('forecast');
  436.         $clientId $request->request->get('client');
  437.         $boolStatus $request->request->get('boolStatus');
  438.         $selectedSalasNames $request->request->get('selected_salas');
  439.         $arraySalasId = empty($request->request->get('tags')) ? null $request->request->get('tags')['tags2'];
  440.         $dateStartReq $dateRequest['date_start'];
  441.         $dateEndReq $dateRequest['date_end'];
  442.         $data = array();
  443.         $data $this->baseForecast($dateStartReq,$dateEndReq$boolStatus$clientId$arraySalasId);
  444.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  445.         $clients $em->getRepository(Client::class)->findAll();
  446.         $consulta 'Del '. (new \DateTime($dateStartReq))->format('d/m/Y').' al '.(new \DateTime($dateEndReq))->format('d/m/Y').',';
  447.         if (!empty($boolStatus['Blocked']) and
  448.             !empty($boolStatus['Confirmed']) and
  449.             !empty($boolStatus['Quoted']) and
  450.             !empty($boolStatus['Invoiced']) and
  451.             !empty($boolStatus['Cancel'])
  452.         ){
  453.             $consulta.=' todos los expedientes,';
  454.         } else {
  455.             $consulta.=' los expedientes';
  456.             if (!empty($boolStatus['Blocked'])) { $consulta .= ' Bloqueados,'; }
  457.             if (!empty($boolStatus['Confirmed'])) { $consulta .= ' Confirmados,'; }
  458.             if (!empty($boolStatus['Quoted'])) { $consulta .= ' Cotizados,'; }
  459.             if (!empty($boolStatus['Invoiced'])) { $consulta .= ' Facturados,'; }
  460.             if (!empty($boolStatus['Cancel'])) { $consulta .= ' Cancelados,'; }
  461.         }
  462.         if(empty($selectedSalasNames)) { $consulta.= ' de todas las salas.'; } else { $consulta.= ' en '.$selectedSalasNames.'.'; }
  463.         $boolBlocked = !empty($boolStatus['Blocked']) ? true false ;
  464.         $boolConfirmed = !empty($boolStatus['Confirmed']) ? true false;
  465.         $boolQuoted = !empty($boolStatus['Quoted']) ? true false;
  466.         $boolInvoiced = !empty($boolStatus['Invoiced']) ? true false;
  467.         $boolCancel = !empty($boolStatus['Cancel']) ? true false;
  468.         return $this->render('MDS/GreenPatioBundle/reservations/list-statistics-products.html.twig',
  469.             array(
  470.                 'data' => $data['reservations'],
  471.                 'clients' => $clients,
  472.                 'salas' => $salas,
  473.                 'consulta' => $consulta,
  474.                 'company' => $company,
  475.                 'clientId' => $clientId,
  476.                 'dateStartReq' => $dateStartReq,
  477.                 'dateEndReq' => $dateEndReq,
  478.                 'boolBlocked' => $boolBlocked,
  479.                 'boolConfirmed' => $boolConfirmed,
  480.                 'boolQuoted' => $boolQuoted,
  481.                 'boolInvoiced' => $boolInvoiced,
  482.                 'boolCancel' => $boolCancel,
  483.                 'selectedSalasNames' => $selectedSalasNames,
  484.                 'arraySalasId' => empty($arraySalasId) ? null implode(","$arraySalasId),
  485.                 'netoForeCast' => $data['netoForeCast'],
  486.                 'vatForeCast' => $data['vatForeCast'],
  487.                 'totalForeCast' => $data['totalForeCast'],
  488.             ));
  489.     }
  490.     /**
  491.      * @Route("/xlsstatisticsproducts/",  name="excel_statistics_products")
  492.      * Estadisticas de Productos de Green Patio en xls
  493.      */
  494.     public function excelStatisticsProductsAction(EntityManagerInterface $emRequest $request)
  495.     {
  496.         $dateStartReq $request->request->get('xls')['dateStartReq'];
  497.         $dateEndReq $request->request->get('xls')['dateEndReq'];
  498.         $clientId $request->request->get('xls')['clientId'];
  499.         $boolStatus = array();
  500.         if (!empty($request->request->get('xls')['boolBlocked'])){ $boolStatus['Blocked'] = 'on'; }
  501.         if (!empty($request->request->get('xls')['boolConfirmed'])){ $boolStatus['Confirmed'] = 'on'; }
  502.         if (!empty($request->request->get('xls')['boolQuoted'])){ $boolStatus['Quoted'] = 'on'; }
  503.         if (!empty($request->request->get('xls')['boolInvoiced'])){ $boolStatus['Invoiced'] = 'on'; }
  504.         if (!empty($request->request->get('xls')['boolCancel'])){ $boolStatus['Cancel'] = 'on'; }
  505.         $selectedSalasNames $request->request->get('xls')['selectedSalasNames'];
  506.         $arraySalasId = !empty($request->request->get('xls')['arraySalasId']) ? explode(","$request->request->get('xls')['arraySalasId']) : null ;
  507.         $data = array();
  508.         $data $this->baseForecast($dateStartReq,$dateEndReq$boolStatus$clientId$arraySalasId);
  509.         $consulta 'del '. (new \DateTime($dateStartReq))->format('d/m/Y').' al '.(new \DateTime($dateEndReq))->format('d/m/Y').',';
  510.         if (!empty($boolStatus['Blocked']) and
  511.             !empty($boolStatus['Confirmed']) and
  512.             !empty($boolStatus['Quoted']) and
  513.             !empty($boolStatus['Invoiced']) and
  514.             !empty($boolStatus['Cancel'])
  515.         ){
  516.             $consulta.=' todos los expedientes,';
  517.         } else {
  518.             $consulta.=' los expedientes';
  519.             if (!empty($boolStatus['Blocked'])) { $consulta .= ' Bloqueados,'; }
  520.             if (!empty($boolStatus['Confirmed'])) { $consulta .= ' Confirmados,'; }
  521.             if (!empty($boolStatus['Quoted'])) { $consulta .= ' Cotizados,'; }
  522.             if (!empty($boolStatus['Invoiced'])) { $consulta .= ' Facturados,'; }
  523.             if (!empty($boolStatus['Cancel'])) { $consulta .= ' Cancelados,'; }
  524.         }
  525.         if(empty($selectedSalasNames)) { $consulta.= ' de todas las salas.'; } else { $consulta.= ' en '.$selectedSalasNames.'.'; }
  526.         // Solicita el servicio de excel
  527.         $phpExcelObject = new Spreadsheet();
  528.         $phpExcelObject->getProperties()->setCreator("Grupo Green Patio")
  529.             ->setLastModifiedBy("Grupo Green Patio")
  530.             ->setTitle("Grupo Green Patio")
  531.             ->setSubject("Grupo Green Patio")
  532.             ->setDescription("Grupo Green Patio, generado usando clases de PHP")
  533.             ->setKeywords("office 2005 openxml php")
  534.             ->setCategory("Archivo de estadisticas");
  535.         $fill = new Fill();
  536.         $numberFormat = new NumberFormat();
  537.         $alignment = new Alignment();
  538.         $i 6;
  539.         $indiceInicial 7;
  540.         $indiceFinal 7;
  541.         $activesheet $phpExcelObject->getActiveSheet();
  542.         $drawingobject = new Drawing();
  543.         $drawingobject->setName('Image name');
  544.         $drawingobject->setDescription('Image description');
  545.         $drawingobject->setPath(getcwd() . '/assets/images/logo/logo_green_patio.png');
  546.         $drawingobject->setHeight(60);
  547.         $drawingobject->setOffsetY(20);
  548.         $drawingobject->setCoordinates('Q1');
  549.         $drawingobject->setWorksheet($activesheet);
  550.         $phpExcelObject
  551.             ->getActiveSheet()
  552.             ->getStyle('B3:O3')
  553.             ->getFill()
  554.             ->setFillType($fill::FILL_SOLID)
  555.             ->getStartColor()
  556.             ->setRGB('9ba67c');
  557.         $phpExcelObject->setActiveSheetIndex(0)
  558.             ->setCellValue('C3''Estadísticas ' $consulta);
  559.         $phpExcelObject
  560.             ->getActiveSheet()
  561.             ->getStyle('B' $i ':R' $i)
  562.             ->getFill()
  563.             ->setFillType($fill::FILL_SOLID)
  564.             ->getStartColor()
  565.             ->setRGB('d1d1cf');
  566.         $phpExcelObject->setActiveSheetIndex(0)
  567.             ->setCellValue('B' $i'Fecha')
  568.             ->setCellValue('D' $i'Nombre')
  569.             ->setCellValue('G' $i'Expediente')
  570.             ->setCellValue('I' $i'Cliente')
  571.             ->setCellValue('L' $i'Productos')
  572.             ->setCellValue('N' $i'Venta Neta')
  573.             ->setCellValue('P' $i'Iva')
  574.             ->setCellValue('R' $i'Total');
  575.         $phpExcelObject->getActiveSheet()->getStyle('N' $i)
  576.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  577.         $phpExcelObject->getActiveSheet()->getStyle('P' $i)
  578.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  579.         $phpExcelObject->getActiveSheet()->getStyle('R' $i)
  580.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  581.         foreach ($data['reservations'] as $item) {
  582.             $phpExcelObject
  583.                 ->getActiveSheet()
  584.                 ->getStyle('N' . ($i 1))
  585.                 ->getNumberFormat()
  586.                 ->setFormatCode('#,##0.00');
  587.             $phpExcelObject
  588.                 ->getActiveSheet()
  589.                 ->getStyle('P' . ($i 1))
  590.                 ->getNumberFormat()
  591.                 ->setFormatCode('#,##0.00');
  592.             $phpExcelObject
  593.                 ->getActiveSheet()
  594.                 ->getStyle('R' . ($i 1))
  595.                 ->getNumberFormat()
  596.                 ->setFormatCode('#,##0.00');
  597.             $txtProducto '';
  598.             $loungesData $item['arrayLoungesData'][$item['reservationId']] ?? [];
  599.             foreach ($loungesData as $elem) {
  600.                 $txtProducto.= $elem['loungeName']. ' - '$elem['category'].' - ('number_format((float)$elem['servicePrice'], 2',''.'). ' â‚¬ )'."\r\n";
  601.             }
  602.             $servicesData $item['arrayServicesData'][$item['reservationId']] ?? [];
  603.             foreach ($servicesData as $elem) {
  604.                 $txtProducto.= $elem['name']. ' - '$elem['category'].' - ('number_format((float)$elem['price'], 2',''.'). ' â‚¬ )'."\r\n";
  605.             }
  606.             $txtProducto rtrim($txtProducto"\r\n");
  607.             $phpExcelObject->getActiveSheet()->getStyle('L' . ($i 1))->getAlignment()->setWrapText(true);
  608.             $phpExcelObject->getActiveSheet()->getColumnDimension('L')->setAutoSize(true);
  609.             $phpExcelObject->getActiveSheet()->getRowDimension($i 1)->setRowHeight(-1);
  610.             $phpExcelObject->setActiveSheetIndex(0)
  611.                 ->setCellValue('B' . ($i 1), $item['dateStart']->format('d/m/Y'))
  612.                 ->setCellValue('D' . ($i 1), $item['title'])
  613.                 ->setCellValue('G' . ($i 1), $item['reservationId'])
  614.                 ->setCellValue('I' . ($i 1), $item['clientName'])
  615.                 ->setCellValue('L' . ($i 1), $txtProducto )
  616.                 ->setCellValue('N' . ($i 1), $item['neto'])
  617.                 ->setCellValue('P' . ($i 1), $item['vat'])
  618.                 ->setCellValue('R' . ($i 1), $item['total']);
  619.             $i++;
  620.             $indiceFinal++;
  621.         }
  622.         $indiceFinal--;
  623.         $phpExcelObject
  624.             ->getActiveSheet()
  625.             ->getStyle('L' . ($indiceFinal 3) . ':' 'R' . ($indiceFinal 3))
  626.             ->getFill()
  627.             ->setFillType($fill::FILL_SOLID)
  628.             ->getStartColor()
  629.             ->setRGB('9ba67c');
  630.         $phpExcelObject
  631.             ->getActiveSheet()
  632.             ->getStyle('N' . ($indiceFinal 4))
  633.             ->getNumberFormat()
  634.             ->setFormatCode('#,##0.00 â‚¬');
  635.         $phpExcelObject
  636.             ->getActiveSheet()
  637.             ->getColumnDimension('N')
  638.             ->setAutoSize(true);
  639.         $phpExcelObject
  640.             ->getActiveSheet()
  641.             ->getStyle('P' . ($indiceFinal 4))
  642.             ->getNumberFormat()
  643.             ->setFormatCode('#,##0.00 â‚¬');
  644.         $phpExcelObject
  645.             ->getActiveSheet()
  646.             ->getColumnDimension('P')
  647.             ->setAutoSize(true);
  648.         $phpExcelObject
  649.             ->getActiveSheet()
  650.             ->getStyle('R' . ($indiceFinal 4))
  651.             ->getNumberFormat()
  652.             ->setFormatCode('#,##0.00 â‚¬');
  653.         $phpExcelObject
  654.             ->getActiveSheet()
  655.             ->getColumnDimension('R')
  656.             ->setAutoSize(true);
  657.         $phpExcelObject->setActiveSheetIndex(0)
  658.             ->setCellValue('N' . ($indiceFinal 3), 'Neto')
  659.             ->setCellValue('P' . ($indiceFinal 3), 'Iva')
  660.             ->setCellValue('R' . ($indiceFinal 3), 'Total');
  661.         $phpExcelObject->getActiveSheet()->getStyle('N' . ($indiceFinal 3))
  662.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  663.         $phpExcelObject->getActiveSheet()->getStyle('P' . ($indiceFinal 3))
  664.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  665.         $phpExcelObject->getActiveSheet()->getStyle('R' . ($indiceFinal 3))
  666.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  667.         $phpExcelObject->setActiveSheetIndex(0)
  668.             ->setCellValue('N' . ($indiceFinal 4), '=SUM(' 'N' $indiceInicial ' : N' $indiceFinal ')')
  669.             ->setCellValue('P' . ($indiceFinal 4), '=SUM(' 'P' $indiceInicial ' : P' $indiceFinal ')')
  670.             ->setCellValue('R' . ($indiceFinal 4), '=SUM(' 'R' $indiceInicial ' : R' $indiceFinal ')');
  671.         $phpExcelObject->getActiveSheet()->setTitle('Estadísticas');
  672.         // Define el indice de página al número 1, para abrir esa página al abrir el archivo
  673.         $phpExcelObject->setActiveSheetIndex(0);
  674.         // Creamos pagina de Datos en bruto para Esteban Rincon
  675.         // Add new sheet
  676.         $objWorkSheet $phpExcelObject->createSheet(1); //Setting index when creating
  677.         $phpExcelObject->setActiveSheetIndex(1);
  678.         $phpExcelObject->getActiveSheet()->setTitle('Datos en bruto');
  679.         $x 1;
  680.         $phpExcelObject->setActiveSheetIndex(1)
  681.             ->setCellValue('A' $x'Fecha')
  682.             ->setCellValue('B' $x'Nombre')
  683.             ->setCellValue('C' $x'Expediente')
  684.             ->setCellValue('D' $x'Cliente')
  685.             ->setCellValue('E' $x'Productos')
  686.             ->setCellValue('F' $x'Categoria')
  687.             ->setCellValue('G' $x'Ubicacion')
  688.             ->setCellValue('H' $x'Venta Producto')
  689.             ->setCellValue('I' $x'Venta Neta')
  690.             ->setCellValue('J' $x'Iva')
  691.             ->setCellValue('K' $x'Total');
  692.         foreach ($data['reservations'] as $item) {
  693.             $phpExcelObject
  694.                 ->getActiveSheet()
  695.                 ->getStyle('H' . ($x 1))
  696.                 ->getNumberFormat()
  697.                 ->setFormatCode('#,##0.00 â‚¬');
  698.             $phpExcelObject
  699.                 ->getActiveSheet()
  700.                 ->getStyle('I' . ($x 1))
  701.                 ->getNumberFormat()
  702.                 ->setFormatCode('#,##0.00 â‚¬');
  703.             $phpExcelObject
  704.                 ->getActiveSheet()
  705.                 ->getStyle('J' . ($x 1))
  706.                 ->getNumberFormat()
  707.                 ->setFormatCode('#,##0.00 â‚¬');
  708.             $phpExcelObject
  709.                 ->getActiveSheet()
  710.                 ->getStyle('K' . ($x 1))
  711.                 ->getNumberFormat()
  712.                 ->setFormatCode('#,##0.00 â‚¬');
  713.             $phpExcelObject->setActiveSheetIndex(1)
  714.                 ->setCellValue('I' . ($x 1), $item['neto'])
  715.                 ->setCellValue('J' . ($x 1), $item['vat'])
  716.                 ->setCellValue('K' . ($x 1), $item['total']);
  717.             $location '';
  718.             $loungesData $item['arrayLoungesData'][$item['reservationId']] ?? [];
  719.             foreach ($loungesData as $elem) {
  720.                 $phpExcelObject
  721.                     ->getActiveSheet()
  722.                     ->getStyle('H' . ($x 1))
  723.                     ->getNumberFormat()
  724.                     ->setFormatCode('#,##0.00 â‚¬');
  725.                 $phpExcelObject->setActiveSheetIndex(1)
  726.                     ->setCellValue('A' . ($x 1), $item['dateStart']->format('d/m/Y'))
  727.                     ->setCellValue('B' . ($x 1), $item['title'])
  728.                     ->setCellValue('C' . ($x 1), $item['reservationId'])
  729.                     ->setCellValue('D' . ($x 1), $item['clientName'])
  730.                     ->setCellValue('E' . ($x 1), $elem['loungeName'])
  731.                     ->setCellValue('F' . ($x 1), $elem['category'])
  732.                     ->setCellValue('G' . ($x 1), $elem['location'])
  733.                     ->setCellValue('H' . ($x 1), (float)$elem['servicePrice'])
  734.                 ;
  735.                 $location $elem['location'];
  736.                 $x++;
  737.             }
  738.             $servicesData $item['arrayServicesData'][$item['reservationId']] ?? [];
  739.             foreach ($servicesData as $elem) {
  740.                 $phpExcelObject
  741.                     ->getActiveSheet()
  742.                     ->getStyle('H' . ($x 1))
  743.                     ->getNumberFormat()
  744.                     ->setFormatCode('#,##0.00 â‚¬');
  745.                 $phpExcelObject->setActiveSheetIndex(1)
  746.                     ->setCellValue('A' . ($x 1), $item['dateStart']->format('d/m/Y'))
  747.                     ->setCellValue('B' . ($x 1), $item['title'])
  748.                     ->setCellValue('C' . ($x 1), $item['reservationId'])
  749.                     ->setCellValue('D' . ($x 1), $item['clientName'])
  750.                     ->setCellValue('E' . ($x 1), $elem['name'])
  751.                     ->setCellValue('F' . ($x 1), $elem['category'])
  752.                     ->setCellValue('G' . ($x 1), $location)
  753.                     ->setCellValue('H' . ($x 1), (float)$elem['price'])
  754.                 ;
  755.                 $x++;
  756.             }
  757.         }
  758.         $phpExcelObject->setActiveSheetIndex(0);
  759.         // Crea el writer
  760.         $writer = new Xlsx($phpExcelObject);
  761.         // Envia la respuesta del controlador
  762.         $response = new StreamedResponse(
  763.             function () use ($writer) {
  764.                 $writer->save('php://output');
  765.             }
  766.         );
  767.         // Agrega los headers requeridos
  768.         $dispositionHeader $response->headers->makeDisposition(
  769.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  770.             'Grupo_Green_Patio' '.xlsx'
  771.         );
  772.         $response->headers->set('Content-Type''application/vnd.ms-excel; charset=utf-8');
  773.         $response->headers->set('Pragma''public');
  774.         $response->headers->set('Cache-Control''maxage=1');
  775.         $response->headers->set('Content-Disposition'$dispositionHeader);
  776.         $tot $indiceFinal 7;
  777.         $phpExcelObject->setActiveSheetIndex(0)
  778.             ->setCellValue('L' . ($tot 2), 'Grupo Green Patio')
  779.             ->setCellValue('L' . ($tot 3), 'comercial@greenpatio.es')
  780.             ->setCellValue('L' . ($tot 4), '+34 669 01 88 34');
  781.         $phpExcelObject
  782.             ->getActiveSheet()
  783.             ->getStyle('k' . ($tot 2) . ':' 'O' . ($tot 4))
  784.             ->getFill()
  785.             ->setFillType($fill::FILL_SOLID)
  786.             ->getStartColor()
  787.             ->setRGB('9ba67c');
  788.         $phpExcelObject->getActiveSheet()->setTitle('Estadísticas');
  789.         // Define el indice de página al número 1, para abrir esa página al abrir el archivo
  790.         $phpExcelObject->setActiveSheetIndex(0);
  791.         // Crea el writer
  792.         $writer = new Xlsx($phpExcelObject);
  793.         // Envia la respuesta del controlador
  794.         $response = new StreamedResponse(
  795.             function () use ($writer) {
  796.                 $writer->save('php://output');
  797.             }
  798.         );
  799.         // Agrega los headers requeridos
  800.         $dispositionHeader $response->headers->makeDisposition(
  801.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  802.             'Green Patio - Estadisticas' '.xlsx'
  803.         );
  804.         $response->headers->set('Content-Type''application/vnd.ms-excel; charset=utf-8');
  805.         $response->headers->set('Pragma''public');
  806.         $response->headers->set('Cache-Control''maxage=1');
  807.         $response->headers->set('Content-Disposition'$dispositionHeader);
  808.         return $response;
  809.     }
  810.     /**
  811.      * @Route("/liststatisticsclient/",  name="reservations_greenpatio_list_statistics_client")
  812.      * Estadisticas por las ventas de los clientes
  813.      */
  814.     public function listStatisticsClientReservationAction(EntityManagerInterface $emRequest $request)
  815.     {
  816.         $clients $em->getRepository(Client::class)->findAll();
  817.         $salas $em->getRepository(ReservationLoungeDetails::class)->findAll();
  818.         return $this->render('MDS/GreenPatioBundle/reservations/list-statistics-client.html.twig',
  819.             array(
  820.                 'data' => null,
  821.                 'clients' => $clients,
  822.                 'clientId' => 0,
  823.                 'salas' => $salas,
  824.                 'consulta' => null,
  825.                 'dateStartReq' => null,
  826.                 'dateEndReq' => null,
  827.             ));
  828.     }
  829.     /**
  830.      * @Route("/responseliststatisticsclient/",  name="reservations_greenpatio_response_list_statistics_client")
  831.      * Respuesta de las estadisticas de clientes
  832.      */
  833.     public function responseListStatisticsReservationClientAction(EntityManagerInterface $emRequest $request)
  834.     {
  835.         $salas $em->getRepository(ReservationLoungeDetails::class)->findAll();
  836.         $dateRequest $request->request->get('forecast');
  837.         $clientId $request->request->get('client');
  838. //        $boolStatus = $request->request->get('boolStatus');
  839.         $boolStatus = array('Invoiced' => 'on' );
  840.         $dateStartReq $dateRequest['date_start'];
  841.         $dateEndReq $dateRequest['date_end'];
  842.         $clients $em->getRepository(Client::class)->findAll();
  843.         $consulta 'Del '. (new \DateTime($dateStartReq))->format('d/m/Y').' al '.(new \DateTime($dateEndReq))->format('d/m/Y').' de todos los expedientes facturados';
  844.         $data $this->baseForecastClient($dateStartReq,$dateEndReq$boolStatus$clientId);
  845.         $boolBlocked = !empty($boolStatus['Blocked']) ? true false ;
  846.         $boolConfirmed = !empty($boolStatus['Confirmed']) ? true false;
  847.         $boolQuoted = !empty($boolStatus['Quoted']) ? true false;
  848.         $boolInvoiced = !empty($boolStatus['Invoiced']) ? true false;
  849.         $boolCancel = !empty($boolStatus['Cancel']) ? true false;
  850.         return $this->render('MDS/GreenPatioBundle/reservations/list-statistics-client.html.twig',
  851.             array(
  852.                 'data' => $data['reservationsClients'],
  853.                 'clients' => $clients,
  854.                 'salas' => $salas,
  855.                 'consulta' => $consulta,
  856.                 'clientId' => $clientId,
  857.                 'dateStartReq' => $dateStartReq,
  858.                 'dateEndReq' => $dateEndReq,
  859.                 'boolBlocked' => $boolBlocked,
  860.                 'boolConfirmed' => $boolConfirmed,
  861.                 'boolQuoted' => $boolQuoted,
  862.                 'boolInvoiced' => $boolInvoiced,
  863.                 'boolCancel' => $boolCancel,
  864.                 'netoForeCast' => $data['netoForeCast'],
  865.                 'vatForeCast' => $data['vatForeCast'],
  866.                 'totalForeCast' => $data['totalForeCast'],
  867.             ));
  868.     }
  869.     /**
  870.      * @Route("/xlsliststatisticsclient/",  name="excel_list_statistics_client")
  871.      * Respuesta de las estadisticas de clientes
  872.      */
  873.     public function excelListStatisticsReservationClientAction(EntityManagerInterface $emRequest $request)
  874.     {
  875.         $dateRequest $request->request->get('xls');
  876.         $clientId $dateRequest['clientId'];
  877. //        $boolStatus = $request->request->get('boolStatus');
  878.         $boolStatus = array('Invoiced' => 'on' );
  879.         $dateStartReq $dateRequest['dateStartReq'];
  880.         $dateEndReq $dateRequest['dateEndReq'];
  881.         $consulta 'Del '. (new \DateTime($dateStartReq))->format('d/m/Y').' al '.(new \DateTime($dateEndReq))->format('d/m/Y').',';
  882.         $data $this->baseForecastClient($dateStartReq,$dateEndReq$boolStatus$clientId);
  883.         // Solicita el servicio de excel
  884.         $phpExcelObject = new Spreadsheet();
  885.         $phpExcelObject->getProperties()->setCreator("Grupo Green Patio")
  886.             ->setLastModifiedBy("Grupo Green Patio")
  887.             ->setTitle("Grupo Green Patio")
  888.             ->setSubject("Grupo Green Patio")
  889.             ->setDescription("Grupo Green Patio, generado usando clases de PHP")
  890.             ->setKeywords("office 2005 openxml php")
  891.             ->setCategory("Archivo de estadisticas");
  892.         $fill = new Fill();
  893.         $numberFormat = new NumberFormat();
  894.         $alignment = new Alignment();
  895.         $i 6;
  896.         $indiceInicial 7;
  897.         $indiceFinal 7;
  898.         $activesheet $phpExcelObject->getActiveSheet();
  899.         $drawingobject = new Drawing();
  900.         $drawingobject->setName('Image name');
  901.         $drawingobject->setDescription('Image description');
  902.         $drawingobject->setPath(getcwd() . '/assets/images/logo/logo_green_patio.png');
  903.         $drawingobject->setHeight(60);
  904.         $drawingobject->setOffsetY(20);
  905.         $drawingobject->setCoordinates('Q1');
  906.         $drawingobject->setWorksheet($activesheet);
  907.         $phpExcelObject
  908.             ->getActiveSheet()
  909.             ->getStyle('B3:O3')
  910.             ->getFill()
  911.             ->setFillType($fill::FILL_SOLID)
  912.             ->getStartColor()
  913.             ->setRGB('9ba67c');
  914.         $phpExcelObject->setActiveSheetIndex(0)
  915.             ->setCellValue('C3''Estadísticas ' $consulta);
  916.         $phpExcelObject
  917.             ->getActiveSheet()
  918.             ->getStyle('B' $i ':R' $i)
  919.             ->getFill()
  920.             ->setFillType($fill::FILL_SOLID)
  921.             ->getStartColor()
  922.             ->setRGB('d1d1cf');
  923.         $phpExcelObject->setActiveSheetIndex(0)
  924.             ->setCellValue('B' $i'No. de Orden')
  925.             ->setCellValue('D' $i'Cliente')
  926.             ->setCellValue('G' $i'Neto (€)')
  927.             ->setCellValue('I' $i'Total Eventos (€)')
  928.             ->setCellValue('L' $i'Facturación (%)')
  929.             ->setCellValue('N' $i'Beneficio (€)')
  930.             ->setCellValue('P' $i'Eventos')
  931.             ->setCellValue('R' $i'Rentabilidad (%)');
  932.         $phpExcelObject->getActiveSheet()->getStyle('N' $i)
  933.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  934.         $phpExcelObject->getActiveSheet()->getStyle('P' $i)
  935.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  936.         $phpExcelObject->getActiveSheet()->getStyle('R' $i)
  937.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  938.         $indice 1;
  939.         foreach ($data['reservationsClients'] as $item) {
  940.             $phpExcelObject
  941.                 ->getActiveSheet()
  942.                 ->getStyle('L' . ($i 1))
  943.                 ->getNumberFormat()
  944.                 ->setFormatCode('#,##0.00');
  945.             $phpExcelObject
  946.                 ->getActiveSheet()
  947.                 ->getStyle('N' . ($i 1))
  948.                 ->getNumberFormat()
  949.                 ->setFormatCode('#,##0.00');
  950.             $phpExcelObject
  951.                 ->getActiveSheet()
  952.                 ->getStyle('R' . ($i 1))
  953.                 ->getNumberFormat()
  954.                 ->setFormatCode('#,##0.00');
  955. //            $txtProducto = '';
  956. //            $loungesData = $item['arrayLoungesData'][$item['reservationId']] ?? [];
  957. //            foreach ($loungesData as $elem) {
  958. //                $txtProducto.= $elem['loungeName']. ' - '. $elem['category'].' - ('. number_format((float)$elem['servicePrice'], 2, ',', '.'). ' â‚¬ )'."\r\n";
  959. //            }
  960. //
  961. //            $servicesData = $item['arrayServicesData'][$item['reservationId']] ?? [];
  962. //            foreach ($servicesData as $elem) {
  963. //                $txtProducto.= $elem['name']. ' - '. $elem['category'].' - ('. number_format((float)$elem['price'], 2, ',', '.'). ' â‚¬ )'."\r\n";
  964. //            }
  965. //            $txtProducto = rtrim($txtProducto, "\r\n");
  966.             $phpExcelObject->getActiveSheet()->getStyle('L' . ($i 1))->getAlignment()->setWrapText(true);
  967.             $phpExcelObject->getActiveSheet()->getColumnDimension('L')->setAutoSize(true);
  968.             $phpExcelObject->getActiveSheet()->getRowDimension($i 1)->setRowHeight(-1);
  969.             $phpExcelObject->setActiveSheetIndex(0)
  970.                 ->setCellValue('B' . ($i 1), $indice)
  971.                 ->setCellValue('D' . ($i 1), $item['reservas'][0]['clientName'])
  972.                 ->setCellValue('G' . ($i 1), $item['netoTotalCliente'])
  973.                 ->setCellValue('I' . ($i 1), $item['totalCliente'])
  974.                 ->setCellValue('L' . ($i 1), $item['percFacturaTotalClienteContraFacturaTotalEventos'] )
  975.                 ->setCellValue('N' . ($i 1), $item['beneficioCliente'])
  976.                 ->setCellValue('P' . ($i 1), $item['numeroEventosCliente'])
  977.                 ->setCellValue('R' . ($i 1), $item['rentabilidadPercBenefit']);
  978.             $i++;
  979.             $indice++;
  980.             $indiceFinal++;
  981.         }
  982.         $indiceFinal--;
  983.         $phpExcelObject
  984.             ->getActiveSheet()
  985.             ->getStyle('E' . ($indiceFinal 3) . ':' 'R' . ($indiceFinal 3))
  986.             ->getFill()
  987.             ->setFillType($fill::FILL_SOLID)
  988.             ->getStartColor()
  989.             ->setRGB('9ba67c');
  990.         $phpExcelObject
  991.             ->getActiveSheet()
  992.             ->getStyle('N' . ($indiceFinal 4))
  993.             ->getNumberFormat()
  994.             ->setFormatCode('#,##0.00 â‚¬');
  995.         $phpExcelObject
  996.             ->getActiveSheet()
  997.             ->getColumnDimension('N')
  998.             ->setAutoSize(true);
  999.         $phpExcelObject
  1000.             ->getActiveSheet()
  1001.             ->getStyle('G' . ($indiceFinal 4))
  1002.             ->getNumberFormat()
  1003.             ->setFormatCode('#,##0.00 â‚¬');
  1004.         $phpExcelObject
  1005.             ->getActiveSheet()
  1006.             ->getStyle('I' . ($indiceFinal 4))
  1007.             ->getNumberFormat()
  1008.             ->setFormatCode('#,##0.00 â‚¬');
  1009.         $phpExcelObject
  1010.             ->getActiveSheet()
  1011.             ->getColumnDimension('P')
  1012.             ->setAutoSize(true);
  1013.         $phpExcelObject
  1014.             ->getActiveSheet()
  1015.             ->getStyle('R' . ($indiceFinal 4))
  1016.             ->getNumberFormat()
  1017.             ->setFormatCode('#,##0.00 â‚¬');
  1018.         $phpExcelObject
  1019.             ->getActiveSheet()
  1020.             ->getColumnDimension('R')
  1021.             ->setAutoSize(true);
  1022.         $phpExcelObject->setActiveSheetIndex(0)
  1023.             ->setCellValue('G' . ($indiceFinal 3), 'Neto')
  1024.             ->setCellValue('I' . ($indiceFinal 3), 'Total Eventos')
  1025.             ->setCellValue('N' . ($indiceFinal 3), 'Beneficio')
  1026.             ->setCellValue('P' . ($indiceFinal 3), 'Eventos')
  1027. //            ->setCellValue('R' . ($indiceFinal + 3), 'Total')
  1028.         ;
  1029.         $phpExcelObject->getActiveSheet()->getStyle('N' . ($indiceFinal 3))
  1030.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  1031.         $phpExcelObject->getActiveSheet()->getStyle('P' . ($indiceFinal 3))
  1032.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  1033.         $phpExcelObject->getActiveSheet()->getStyle('R' . ($indiceFinal 3))
  1034.             ->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  1035.         $phpExcelObject->setActiveSheetIndex(0)
  1036.             ->setCellValue('G' . ($indiceFinal 4), '=SUM(' 'G' $indiceInicial ' : G' $indiceFinal ')')
  1037.             ->setCellValue('I' . ($indiceFinal 4), '=SUM(' 'I' $indiceInicial ' : I' $indiceFinal ')')
  1038.             ->setCellValue('N' . ($indiceFinal 4), '=SUM(' 'N' $indiceInicial ' : N' $indiceFinal ')')
  1039.             ->setCellValue('P' . ($indiceFinal 4), '=SUM(' 'P' $indiceInicial ' : P' $indiceFinal ')')
  1040. //            ->setCellValue('R' . ($indiceFinal + 4), '=SUM(' . 'R' . $indiceInicial . ' : R' . $indiceFinal . ')')
  1041.         ;
  1042.         $phpExcelObject->getActiveSheet()->setTitle('Estadísticas');
  1043.         // Define el indice de página al número 1, para abrir esa página al abrir el archivo
  1044.         $phpExcelObject->setActiveSheetIndex(0);
  1045.         // Creamos pagina de Datos en bruto para Esteban Rincon
  1046.         // Add new sheet
  1047.         $objWorkSheet $phpExcelObject->createSheet(1); //Setting index when creating
  1048.         $phpExcelObject->setActiveSheetIndex(1);
  1049.         $phpExcelObject->getActiveSheet()->setTitle('Datos en bruto');
  1050.         $x 1;
  1051.         $phpExcelObject->setActiveSheetIndex(1)
  1052.             ->setCellValue('A' $x'Fecha')
  1053.             ->setCellValue('B' $x'Nombre')
  1054.             ->setCellValue('C' $x'Expediente')
  1055.             ->setCellValue('D' $x'Cliente')
  1056.             ->setCellValue('E' $x'Productos')
  1057.             ->setCellValue('F' $x'Categoria')
  1058.             ->setCellValue('G' $x'Ubicacion')
  1059.             ->setCellValue('H' $x'Venta Producto')
  1060.             ->setCellValue('I' $x'Venta Neta')
  1061.             ->setCellValue('J' $x'Iva')
  1062.             ->setCellValue('K' $x'Total');
  1063.         if (false) {
  1064.     foreach ($data['reservations'] as $item) {
  1065.         $phpExcelObject
  1066.             ->getActiveSheet()
  1067.             ->getStyle('H' . ($x 1))
  1068.             ->getNumberFormat()
  1069.             ->setFormatCode('#,##0.00 â‚¬');
  1070.         $phpExcelObject
  1071.             ->getActiveSheet()
  1072.             ->getStyle('I' . ($x 1))
  1073.             ->getNumberFormat()
  1074.             ->setFormatCode('#,##0.00 â‚¬');
  1075.         $phpExcelObject
  1076.             ->getActiveSheet()
  1077.             ->getStyle('J' . ($x 1))
  1078.             ->getNumberFormat()
  1079.             ->setFormatCode('#,##0.00 â‚¬');
  1080.         $phpExcelObject
  1081.             ->getActiveSheet()
  1082.             ->getStyle('K' . ($x 1))
  1083.             ->getNumberFormat()
  1084.             ->setFormatCode('#,##0.00 â‚¬');
  1085.         $phpExcelObject->setActiveSheetIndex(1)
  1086.             ->setCellValue('I' . ($x 1), $item['neto'])
  1087.             ->setCellValue('J' . ($x 1), $item['vat'])
  1088.             ->setCellValue('K' . ($x 1), $item['total']);
  1089.         $location '';
  1090.         $loungesData $item['arrayLoungesData'][$item['reservationId']] ?? [];
  1091.         foreach ($loungesData as $elem) {
  1092.             $phpExcelObject
  1093.                 ->getActiveSheet()
  1094.                 ->getStyle('H' . ($x 1))
  1095.                 ->getNumberFormat()
  1096.                 ->setFormatCode('#,##0.00 â‚¬');
  1097.             $phpExcelObject->setActiveSheetIndex(1)
  1098.                 ->setCellValue('A' . ($x 1), $item['dateStart']->format('d/m/Y'))
  1099.                 ->setCellValue('B' . ($x 1), $item['title'])
  1100.                 ->setCellValue('C' . ($x 1), $item['reservationId'])
  1101.                 ->setCellValue('D' . ($x 1), $item['clientName'])
  1102.                 ->setCellValue('E' . ($x 1), $elem['loungeName'])
  1103.                 ->setCellValue('F' . ($x 1), $elem['category'])
  1104.                 ->setCellValue('G' . ($x 1), $elem['location'])
  1105.                 ->setCellValue('H' . ($x 1), (float)$elem['servicePrice']);
  1106.             $location $elem['location'];
  1107.             $x++;
  1108.         }
  1109.         $servicesData $item['arrayServicesData'][$item['reservationId']] ?? [];
  1110.         foreach ($servicesData as $elem) {
  1111.             $phpExcelObject
  1112.                 ->getActiveSheet()
  1113.                 ->getStyle('H' . ($x 1))
  1114.                 ->getNumberFormat()
  1115.                 ->setFormatCode('#,##0.00 â‚¬');
  1116.             $phpExcelObject->setActiveSheetIndex(1)
  1117.                 ->setCellValue('A' . ($x 1), $item['dateStart']->format('d/m/Y'))
  1118.                 ->setCellValue('B' . ($x 1), $item['title'])
  1119.                 ->setCellValue('C' . ($x 1), $item['reservationId'])
  1120.                 ->setCellValue('D' . ($x 1), $item['clientName'])
  1121.                 ->setCellValue('E' . ($x 1), $elem['name'])
  1122.                 ->setCellValue('F' . ($x 1), $elem['category'])
  1123.                 ->setCellValue('G' . ($x 1), $location)
  1124.                 ->setCellValue('H' . ($x 1), (float)$elem['price']);
  1125.             $x++;
  1126.         }
  1127.     }
  1128. }
  1129.         $phpExcelObject->setActiveSheetIndex(0);
  1130.         // Crea el writer
  1131.         $writer = new Xlsx($phpExcelObject);
  1132.         // Envia la respuesta del controlador
  1133.         $response = new StreamedResponse(
  1134.             function () use ($writer) {
  1135.                 $writer->save('php://output');
  1136.             }
  1137.         );
  1138.         // Agrega los headers requeridos
  1139.         $dispositionHeader $response->headers->makeDisposition(
  1140.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  1141.             'Grupo_Green_Patio' '.xlsx'
  1142.         );
  1143.         $response->headers->set('Content-Type''application/vnd.ms-excel; charset=utf-8');
  1144.         $response->headers->set('Pragma''public');
  1145.         $response->headers->set('Cache-Control''maxage=1');
  1146.         $response->headers->set('Content-Disposition'$dispositionHeader);
  1147.         $tot $indiceFinal 7;
  1148.         $phpExcelObject->setActiveSheetIndex(0)
  1149.             ->setCellValue('L' . ($tot 2), 'Grupo Green Patio')
  1150.             ->setCellValue('L' . ($tot 3), 'comercial@greenpatio.es')
  1151.             ->setCellValue('L' . ($tot 4), '+34 669 01 88 34');
  1152.         $phpExcelObject
  1153.             ->getActiveSheet()
  1154.             ->getStyle('k' . ($tot 2) . ':' 'O' . ($tot 4))
  1155.             ->getFill()
  1156.             ->setFillType($fill::FILL_SOLID)
  1157.             ->getStartColor()
  1158.             ->setRGB('9ba67c');
  1159.         $phpExcelObject->getActiveSheet()->setTitle('Estadísticas');
  1160.         // Define el indice de página al número 1, para abrir esa página al abrir el archivo
  1161.         $phpExcelObject->setActiveSheetIndex(0);
  1162.         // Crea el writer
  1163.         $writer = new Xlsx($phpExcelObject);
  1164.         // Envia la respuesta del controlador
  1165.         $response = new StreamedResponse(
  1166.             function () use ($writer) {
  1167.                 $writer->save('php://output');
  1168.             }
  1169.         );
  1170.         // Agrega los headers requeridos
  1171.         $dispositionHeader $response->headers->makeDisposition(
  1172.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  1173.             'Green Patio - Estadisticas' '.xlsx'
  1174.         );
  1175.         $response->headers->set('Content-Type''application/vnd.ms-excel; charset=utf-8');
  1176.         $response->headers->set('Pragma''public');
  1177.         $response->headers->set('Cache-Control''maxage=1');
  1178.         $response->headers->set('Content-Disposition'$dispositionHeader);
  1179.         return $response;
  1180.     }
  1181.     /**
  1182.      * @Route("/liststatquoting", name="reservations_greenpatio_list_stats_quoting")
  1183.      * Estadisticas de expedientes inicializados en un periodo de tiempo
  1184.      */
  1185.     public function listStatisticsQuotingReservationAction(EntityManagerInterface $emRequest $request)
  1186.     {
  1187.         return $this->render('MDS/GreenPatioBundle/reservations/list-statistics-quoting.html.twig',
  1188.             array(
  1189.                 'data' => null,
  1190.                 'dateStartReq' => null,
  1191.                 'dateEndReq' => null,
  1192.                 'numberTotRes' => null,
  1193.                 'numberIniciado' => null,
  1194.                 'numberBloqueado' => null,
  1195.                 'numberConfirmado' => null,
  1196.                 'numberCotizado' => null,
  1197.                 'numberCancelado' => null,
  1198.                 'numberFacturado' => null,
  1199.                 'percIniciado' => null,
  1200.                 'percBloqueado' => null,
  1201.                 'percConfirmado' => null,
  1202.                 'percCotizado' => null,
  1203.                 'percCancelado' => null,
  1204.                 'percFacturado' => null,
  1205.                 'dataDonut' => null,
  1206.                 'legend' => null,
  1207.             ));
  1208.     }
  1209.     /**
  1210.      * @Route("/responseliststatquoting", name="reservations_greenpatio_response_list_stats_quoting")
  1211.      * Respuesta de estadisticas de expedientes inicializados en un periodo de tiempo y sus cambios de estados
  1212.      */
  1213.     public function responseListStatisticsQuotingReservationAction(EntityManagerInterface $emRequest $request)
  1214.     {
  1215.         $dateRequest $request->request->get('forecast');
  1216.         $dateStartReq $dateRequest['date_start'];
  1217.         $dateStartReq .= ' 00:00:00';
  1218.         $dateEndReq $dateRequest['date_end'];
  1219.         $dateEndReq .= ' 23:59:59';
  1220.         $parameters = array( 'start' => $dateStartReq'end'=> $dateEndReq, );
  1221.         $dql "SELECT p
  1222.                 FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1223.                 WHERE p.createdAt BETWEEN :start  AND :end 
  1224.                 ORDER BY p.createdAt ASC
  1225.               ";
  1226.         $query $em->createQuery($dql)->setParameters($parameters);
  1227.         $reservations $query->getResult();
  1228.         $dql "SELECT p
  1229.                 FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1230.                 WHERE (p.dateStart BETWEEN :start  AND :end) 
  1231.                  AND (p.updatedAt BETWEEN :start  AND :end)
  1232.                  AND (p.createdAt < :start OR p.createdAt > :end)
  1233.                 ORDER BY p.createdAt ASC
  1234.               ";
  1235.         $query $em->createQuery($dql)->setParameters($parameters);
  1236.         $reservationsGanadas $query->getResult();
  1237.         $numberTotRes sizeof($reservations);
  1238.         $data = []; $numberIniciado $numberBloqueado $numberConfirmado $numberCotizado $numberCancelado $numberFacturado $numberGanado $numberGanConf $numberGanFac 0;
  1239.         if(!empty($reservations)){
  1240.             foreach ($reservations as $item){
  1241.                 $client = (empty($item->getClient())) ?
  1242.                     (empty($item->getNameContactUnregistered()) ? 'No se asigno un cliente, ni se especifico un cliente no registrado'$item->getNameContactUnregistered()) :
  1243.                     (empty($em->getRepository(Client::class)->findOneById($item->getClient())) ? 'No se pudo encontrar el cliente en la base de datos' : ($em->getRepository(Client::class)->findOneById($item->getClient()))->getName());
  1244.                 $agentId $item->getCreatedBy();
  1245.                 $agent $em->getRepository(User::class)->findOneById($agentId);
  1246.                 $agent = empty($agent) ? 'No se encontro al agente' : ($agent->getName() . ' '$agent->getLastName());
  1247.                 $resStatus null;
  1248.                 switch ($item->getStatus()){
  1249.                     case 'Iniciado'$numberIniciado++; $resStatus 'Iniciado'; break;
  1250.                     case 'Bloqueo'$numberBloqueado++; $resStatus 'Bloqueado'; break;
  1251.                     case 'Confirmed'$numberConfirmado++; $resStatus 'Confirmado'; break;
  1252.                     case 'Cotizado'$numberCotizado++; $resStatus 'Cotizado'; break;
  1253.                     case 'Deleted'$numberCancelado++; $resStatus 'Cancelado'; break;
  1254.                     case 'Invoiced'$numberFacturado++; $resStatus 'Facturado'; break;
  1255.                     default: break;
  1256.                 }
  1257.                 $data[]= array(
  1258.                     'dateReference' => $item->getCreatedAt(),
  1259.                     'reservationId' => $item->getId(),
  1260.                     'title' => $item->getTitle(),
  1261.                     'clientName' => $client,
  1262.                     'dateStart' => $item->getDateStart(),
  1263.                     'dateEnd' => $item->getDateEnd(),
  1264.                     'status' => $resStatus,
  1265.                     'createdAt' => $item->getCreatedAt(),
  1266.                     'createdBy' => $agentId,
  1267.                     'agentFullName' => $agent,
  1268.                 );
  1269.             }
  1270.         }
  1271.         if(!empty($reservationsGanadas)){
  1272.             foreach ($reservationsGanadas as $item){
  1273.                 if (($item->getStatus() == 'Confirmed') or ($item->getStatus() == 'Invoiced')) {
  1274.                     $client = (empty($item->getClient())) ?
  1275.                         (empty($item->getNameContactUnregistered()) ? 'No se asigno un cliente, ni se especifico un cliente no registrado' $item->getNameContactUnregistered()) :
  1276.                         (empty($em->getRepository(Client::class)->findOneById($item->getClient())) ? 'No se pudo encontrar el cliente en la base de datos' : ($em->getRepository(Client::class)->findOneById($item->getClient()))->getName());
  1277.                     $agentId $item->getCreatedBy();
  1278.                     $agent $em->getRepository(User::class)->findOneById($agentId);
  1279.                     $agent = empty($agent) ? 'No se encontro al agente' : ($agent->getName() . ' ' $agent->getLastName());
  1280.                     $resStatus null;
  1281.                     switch ($item->getStatus()) {
  1282.                         case 'Iniciado': break;
  1283.                         case 'Bloqueo': break;
  1284.                         case 'Confirmed':
  1285.                             $numberConfirmado++;
  1286.                             $numberGanado++;
  1287.                             $numberGanConf++;
  1288.                             $numberTotRes++;
  1289.                             $resStatus 'Confirmado ( Ganado )';
  1290.                             break;
  1291.                         case 'Cotizado': break;
  1292.                         case 'Deleted': break;
  1293.                         case 'Invoiced':
  1294.                             $numberFacturado++;
  1295.                             $numberGanado++;
  1296.                             $numberGanFac++;
  1297.                             $numberTotRes++;
  1298.                             $resStatus 'Facturado ( Ganado )';
  1299.                             break;
  1300.                         default:
  1301.                             break;
  1302.                     }
  1303.                     $data[] = array(
  1304.                         'dateReference' => $item->getCreatedAt(),
  1305.                         'reservationId' => $item->getId(),
  1306.                         'title' => $item->getTitle(),
  1307.                         'clientName' => $client,
  1308.                         'dateStart' => $item->getDateStart(),
  1309.                         'dateEnd' => $item->getDateEnd(),
  1310.                         'status' => $resStatus,
  1311.                         'createdAt' => $item->getCreatedAt(),
  1312.                         'createdBy' => $agentId,
  1313.                         'agentFullName' => $agent,
  1314.                     );
  1315.                 }
  1316.             }
  1317.         }
  1318.         if ($numberTotRes == 0){
  1319.             $percIniciado 0;
  1320.             $percBloqueado 0;
  1321.             $percConfirmado 0;
  1322.             $percCotizado 0;
  1323.             $percCancelado 0;
  1324.             $percFacturado 0;
  1325.         } else {
  1326.             $percIniciado = ($numberIniciado 100) / $numberTotRes;
  1327.             $percBloqueado = ($numberBloqueado 100) / $numberTotRes;
  1328.             $percConfirmado = ($numberConfirmado 100) / $numberTotRes;
  1329.             $percCotizado = ($numberCotizado 100) / $numberTotRes;
  1330.             $percCancelado = ($numberCancelado 100) / $numberTotRes;
  1331.             $percFacturado = ($numberFacturado 100) / $numberTotRes;
  1332.         }
  1333.         $numberSumConBloFac = ($numberBloqueado $numberConfirmado $numberFacturado);
  1334.         $perSumConBloFac = ($percBloqueado $percConfirmado $percFacturado);
  1335.         $dataDonut $legend = [];
  1336.         $dataDonut = [
  1337.             ['name' => 'Iniciado''value' => $numberIniciado],
  1338.             ['name' => 'Bloqueado''value' => $numberBloqueado],
  1339.             ['name' => 'Confirmado''value' => $numberConfirmado],
  1340.             ['name' => 'Cotizado''value' => $numberCotizado],
  1341.             ['name' => 'Cancelado''value' => $numberCancelado],
  1342.             ['name' => 'Facturado''value' => $numberFacturado]
  1343.         ];
  1344.         $legend = ['Iniciado''Bloqueado''Confirmado''Cotizado''Cancelado''Facturado'];
  1345.         return $this->render('MDS/GreenPatioBundle/reservations/list-statistics-quoting.html.twig',
  1346.             array(
  1347.                 'data' => $data,
  1348.                 'dateStartReq' => $dateStartReq,
  1349.                 'dateEndReq' => $dateEndReq,
  1350.                 'numberTotRes' => $numberTotRes,
  1351.                 'numberIniciado' => $numberIniciado,
  1352.                 'numberBloqueado' => $numberBloqueado,
  1353.                 'numberConfirmado' => $numberConfirmado,
  1354.                 'numberCotizado' => $numberCotizado,
  1355.                 'numberCancelado' => $numberCancelado,
  1356.                 'numberFacturado' => $numberFacturado,
  1357.                 'numberGanado' => $numberGanado,
  1358.                 'numberGanConf' => $numberGanConf,
  1359.                 'numberGanFac' => $numberGanFac,
  1360.                 'percIniciado' => $percIniciado,
  1361.                 'percBloqueado' => $percBloqueado,
  1362.                 'percConfirmado' => $percConfirmado,
  1363.                 'percCotizado' => $percCotizado,
  1364.                 'percCancelado' => $percCancelado,
  1365.                 'percFacturado' => $percFacturado,
  1366.                 'numberSumConBloFac' => $numberSumConBloFac,
  1367.                 'perSumConBloFac' => $perSumConBloFac,
  1368.                 'dataDonut' => $dataDonut,
  1369.                 'legend' => $legend,
  1370.             ));
  1371.     }
  1372.     /**
  1373.      * @Route("/liststattarif", name="reservations_greenpatio_list_stats_tarif")
  1374.      * Estadisticas de expedientes y el tarifario en un periodo de tiempo
  1375.      */
  1376.     public function listStatisticsTarifReservationAction(EntityManagerInterface $emRequest $request)
  1377.     {
  1378.         return $this->render('MDS/GreenPatioBundle/reservations/list-statistics-tarif.html.twig',
  1379.             array(
  1380.                 'data' => null,
  1381.                 'dateStartReq' => null,
  1382.                 'dateEndReq' => null,
  1383.                 'numberTotRes' => null,
  1384.                 'numberIniciado' => null,
  1385.                 'numberBloqueado' => null,
  1386.                 'numberConfirmado' => null,
  1387.                 'numberCotizado' => null,
  1388.                 'numberCancelado' => null,
  1389.                 'numberFacturado' => null,
  1390.                 'percIniciado' => null,
  1391.                 'percBloqueado' => null,
  1392.                 'percConfirmado' => null,
  1393.                 'percCotizado' => null,
  1394.                 'percCancelado' => null,
  1395.                 'percFacturado' => null,
  1396.                 'dataDonut' => null,
  1397.                 'legend' => null,
  1398.             ));
  1399.     }
  1400.     /**
  1401.      * @Route("/responseliststattarif", name="reservations_greenpatio_response_list_stats_tarif")
  1402.      * Respuesta de estadisticas de tarifarios
  1403.      */
  1404.     public function responseListStatisticsTarifReservationAction(EntityManagerInterface $emRequest $request)
  1405.     {
  1406.         $dateRequest $request->request->get('forecast');
  1407.         $dateStartReq $dateRequest['date_start'];
  1408.         $dateStartReq .= ' 00:00:00';
  1409.         $dateEndReq $dateRequest['date_end'];
  1410.         $dateEndReq .= ' 23:59:59';
  1411.         $parameters = array( 'start' => $dateStartReq'end'=> $dateEndReq'stat'=>['Confirmed','Invoiced'] );
  1412.         $dql "SELECT p
  1413.                 FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1414.                 WHERE p.dateStart BETWEEN :start  AND :end
  1415.                 AND p.status in (:stat) 
  1416.                 ORDER BY p.dateStart ASC
  1417.               ";
  1418.         $query $em->createQuery($dql)->setParameters($parameters);
  1419.         $reservations $query->getResult();
  1420.         $numberTotRes sizeof($reservations);
  1421.         $data = []; $numberConfirmado $numberFacturado 0$stat '';
  1422.         if(!empty($reservations)){
  1423.             foreach ($reservations as $item){
  1424.                 $agent $em->getRepository(User::class)->findOneById($item->getCreatedBy());
  1425.                 $agent = empty($agent) ? 'No se encontro el nombre del agente' $agent->getName().' '.$agent->getLastName();
  1426.                 $client $em->getRepository(Client::class)->findOneById($item->getClient());
  1427.                 $client = empty($client) ? 'No se encontro el nombre del cliente' $client->getName();
  1428.                 if ($item->getStatus() == 'Confirmed'){ $numberConfirmado++; $stat 'Confirmado'; } else { $numberFacturado++; $stat 'Facturado'; }
  1429.                 $data[$item->getId()]= array(
  1430.                     'dateReference' => $item->getDateStart(),
  1431.                     'reservationId' => $item->getId(),
  1432.                     'title' => $item->getTitle(),
  1433.                     'clientName' => $client,
  1434.                     'dateStart' => $item->getDateStart(),
  1435.                     'dateEnd' => $item->getDateEnd(),
  1436.                     'status' => $stat,
  1437.                     'createdAt' => $item->getCreatedAt(),
  1438.                     'createdBy' => $item->getCreatedBy(),
  1439.                     'agentFullName' => $agent,
  1440.                     'lounges' => [],
  1441.                 );
  1442.                 $reservaTionsLounges $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($item->getId());
  1443.                 foreach ($reservaTionsLounges as $elem){
  1444.                     // PRECIO POR TARIFA
  1445.                     $dateToFind = clone $elem->getDateStart();
  1446.                     $dateToFind->setTime(000);
  1447.                     $parameters = array(
  1448.                         'loungeId' => $elem->getIdLounge(),
  1449.                         'typePrice' => 'DIARIA',
  1450.                         'dateToFind' => $dateToFind,
  1451.                     );
  1452.                     $dql 'SELECT p
  1453.                             FROM GreenPatioBundle:ReservationLoungeProfile p
  1454.                             WHERE p.typePrice = :typePrice AND p.dateStart = :dateToFind AND p.loungeId = :loungeId
  1455.                             ORDER BY p.levelPrice DESC';
  1456.                     $query $em->createQuery($dql)->setParameters($parameters);
  1457.                     $loungesPeriodsDaily $query->getResult();
  1458.                     $priceTarifa = (!empty($loungesPeriodsDaily)) ? $loungesPeriodsDaily[0]->getPrice() : null;
  1459.                     if (!empty($elem->getType())){ $priceTarifa null; }       // por el momento no se han cargado tarifas para montajes ni desmontajes
  1460.                     $priceLounge $elem->getServicePrice();
  1461.                     if (($priceTarifa != 0) and !empty($priceTarifa)) {
  1462.                         $variacion = (($priceLounge $priceTarifa) / $priceTarifa) * 100;
  1463.                         $variacionTipo = ($priceLounge $priceTarifa) ? 'Positiva' : (($priceLounge == $priceTarifa) ? 'Neutral' 'Negativa');
  1464.                     } else {
  1465.                         // Si es cero la tarifa o nula, la variacion sera el precio
  1466.                         $variacion $priceLounge;
  1467.                         $variacionTipo 'No se pudo determinar la tarifa';
  1468.                     }
  1469.                     $typeLounge = empty($elem->getType()) ? null $elem->getType().' - ';
  1470.                     $data[$item->getId()]['lounges'][$elem->getId()] = array(
  1471.                         'idLounge'=>$elem->getIdLounge(),
  1472.                         'loungeName'=>$elem->getLoungeName(),
  1473.                         'loungeType'=>$typeLounge,
  1474.                         'loungeDate'=>$elem->getDateStart(),
  1475.                         'loungePrice'=>$elem->getServicePrice(),
  1476.                         'loungeTarifa'=>$priceTarifa,
  1477.                         'variacion'=>$variacion,
  1478.                         'variacionTipo'=>$variacionTipo,
  1479.                     );
  1480.                 }
  1481.             }
  1482.         }
  1483.         $dataDonut $legend = [];
  1484.         $dataDonut = [
  1485.             ['name' => 'Confirmado''value' => $numberConfirmado],
  1486.             ['name' => 'Facturado''value' => $numberFacturado]
  1487.         ];
  1488.         $legend = ['Confirmado''Facturado'];
  1489.         return $this->render('MDS/GreenPatioBundle/reservations/list-statistics-tarif.html.twig',
  1490.             array(
  1491.                 'data' => $data,
  1492.                 'dateStartReq' => $dateStartReq,
  1493.                 'dateEndReq' => $dateEndReq,
  1494.                 'numberTotRes' => $numberTotRes,
  1495.                 'numberConfirmado' => $numberConfirmado,
  1496.                 'numberFacturado' => $numberFacturado,
  1497.                 'dataDonut' => $dataDonut,
  1498.                 'legend' => $legend,
  1499.             ));
  1500.     }
  1501.     /**
  1502.      * @Route("/liststatisticsfromweb/", name="reservations_greenpatio_list_statistics_from_web")
  1503.      * Estadisticas de expedientes inicializados por formulario de la web
  1504.      */
  1505.     public function listStatisticsReservationFromWebAction(EntityManagerInterface $emRequest $request)
  1506.     {
  1507.         $clients $em->getRepository(Client::class)->findAll();
  1508.         $salas $em->getRepository(ReservationLoungeDetails::class)->findAll();
  1509.         return $this->render('MDS/GreenPatioBundle/reservations/list-statistics-from-web.html.twig',
  1510.             array(
  1511.                 'data' => null,
  1512. //                'clients' => $clients,
  1513. //                'clientId' => 0,
  1514.                 'salas' => $salas,
  1515.                 'consulta' => null,
  1516.                 'dateStartReq' => null,
  1517.                 'dateEndReq' => null,
  1518.             ));
  1519.     }
  1520.     /**
  1521.      * @Route("/responseliststatisticsfromweb/", name="reservations_greenpatio_response_list_statistics_from_web")
  1522.      * Respuesta de expedientes inicializados por formulario de la web
  1523.      */
  1524.     public function responseListStatisticsReservationFromWebAction(EntityManagerInterface $emRequest $request)
  1525.     {
  1526.         $salas $em->getRepository(ReservationLoungeDetails::class)->findAll();
  1527.         $dateRequest $request->request->get('forecast');
  1528. //        $clientId = $request->request->get('client');
  1529.         $boolStatus $request->request->get('boolStatus');
  1530.         $selectedSalasNames $request->request->get('selected_salas');
  1531.         $arraySalasId = empty($request->request->get('tags')) ? null $request->request->get('tags')['tags2'];
  1532.         $dateStartReq = (!empty($dateRequest)) ? $dateRequest['date_start'] : '01-10-2025';
  1533.         $dateEndReq =  (!empty($dateRequest)) ? $dateRequest['date_end'] : '31-10-2025';
  1534.         $data $this->baseForecastWeb($dateStartReq,$dateEndReq$boolStatus$arraySalasId);
  1535.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  1536.         $clients $em->getRepository(Client::class)->findAll();
  1537.         $consulta 'Del '. (new \DateTime($dateStartReq))->format('d/m/Y').' al '.(new \DateTime($dateEndReq))->format('d/m/Y').',';
  1538.         if (!empty($boolStatus['Blocked']) and
  1539.             !empty($boolStatus['Confirmed']) and
  1540.             !empty($boolStatus['Quoted']) and
  1541.             !empty($boolStatus['Invoiced']) and
  1542.             !empty($boolStatus['Cancel'])
  1543.         ){
  1544.             $consulta.=' todos los expedientes,';
  1545.         } else {
  1546.             $consulta.=' los expedientes';
  1547.             if (!empty($boolStatus['Blocked'])) { $consulta .= ' Bloqueados,'; }
  1548.             if (!empty($boolStatus['Confirmed'])) { $consulta .= ' Confirmados,'; }
  1549.             if (!empty($boolStatus['Quoted'])) { $consulta .= ' Cotizados,'; }
  1550.             if (!empty($boolStatus['Invoiced'])) { $consulta .= ' Facturados,'; }
  1551.             if (!empty($boolStatus['Cancel'])) { $consulta .= ' Cancelados,'; }
  1552.         }
  1553.         if(empty($selectedSalasNames)) { $consulta.= ' de todas las salas.'; } else { $consulta.= ' en '.$selectedSalasNames.'.'; }
  1554.         $boolBlocked = !empty($boolStatus['Blocked']) ? true false ;
  1555.         $boolConfirmed = !empty($boolStatus['Confirmed']) ? true false;
  1556.         $boolQuoted = !empty($boolStatus['Quoted']) ? true false;
  1557.         $boolInvoiced = !empty($boolStatus['Invoiced']) ? true false;
  1558.         $boolCancel = !empty($boolStatus['Cancel']) ? true false;
  1559.         return $this->render('MDS/GreenPatioBundle/reservations/list-statistics-from-web.html.twig',
  1560.             array(
  1561.                 'data' => $data['reservations'],
  1562.                 'clients' => $clients,
  1563.                 'salas' => $salas,
  1564.                 'consulta' => $consulta,
  1565.                 'company' => $company,
  1566. //                'clientId' => $clientId,
  1567.                 'arrayStatusCont' => $data['arrayStatusCont'],
  1568.                 'dateStartReq' => $dateStartReq,
  1569.                 'dateEndReq' => $dateEndReq,
  1570.                 'boolBlocked' => $boolBlocked,
  1571.                 'boolConfirmed' => $boolConfirmed,
  1572.                 'boolQuoted' => $boolQuoted,
  1573.                 'boolInvoiced' => $boolInvoiced,
  1574.                 'boolCancel' => $boolCancel,
  1575.                 'selectedSalasNames' => $selectedSalasNames,
  1576.                 'arraySalasId' => empty($arraySalasId) ? null implode(","$arraySalasId),
  1577.                 'netoForeCast' => $data['netoForeCast'],
  1578.                 'vatForeCast' => $data['vatForeCast'],
  1579.                 'totalForeCast' => $data['totalForeCast'],
  1580.             ));
  1581.     }
  1582.     private function baseForecast($dateStartReq$dateEndReq$boolStatus$clientId$arraySalasId)
  1583.     {
  1584.         $em $this->getDoctrine()->getManager();
  1585.         $today = new \DateTime("now"NULL);
  1586.         $data = [];
  1587.         if (empty($boolStatus['Blocked'])){ $opBlocked null; } else { $opBlocked 'Bloqueo'; }
  1588.         if (empty($boolStatus['Confirmed'])){ $opConfirmed null; } else { $opConfirmed 'Confirmed'; }
  1589.         if (empty($boolStatus['Quoted'])){ $opQuoted null; } else { $opQuoted 'Cotizado'; }
  1590.         if (empty($boolStatus['Invoiced'])){ $opInvoiced null; } else { $opInvoiced 'Invoiced'; }
  1591.         if (empty($boolStatus['Cancel'])){ $opDeleted null; } else { $opDeleted 'Deleted'; }
  1592.         $dateEndReq = empty($dateEndReq) ? null : new \Datetime($dateEndReq '+ 1 days'); //Se le suma un dia, para que se considere el ultimo dia en la consulta
  1593.         // Si solo introduce fecha de inicio
  1594.         // Se consulta de fecha inicio a fecha actual
  1595.         if (!empty($dateStartReq) and empty($dateEndReq) and empty($monthReq) and empty($yearReq)){
  1596.             $parameters = array(
  1597.                 'start' => $dateStartReq,
  1598.                 'end'=> $today,
  1599.                 'opBlocked'=> $opBlocked,
  1600.                 'opConfirmed'=> $opConfirmed,
  1601.                 'opQuoted'=> $opQuoted,
  1602.                 'opInvoiced'=> $opInvoiced,
  1603.                 'opDeleted'=> $opDeleted,
  1604.                 'clientId'=> $clientId,
  1605.             );
  1606.             if (empty($clientId)){
  1607.                 $dql "SELECT p
  1608.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1609.                         WHERE p.dateStart BETWEEN :start  AND :end 
  1610.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted)) 
  1611.                         AND p.client != :clientId
  1612.                         ORDER BY p.dateStart ASC
  1613.                       ";
  1614.             } else {
  1615.                 $dql "SELECT p
  1616.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1617.                         WHERE p.dateStart BETWEEN :start  AND :end 
  1618.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted)) 
  1619.                         AND p.client = :clientId
  1620.                         ORDER BY p.dateStart ASC
  1621.                       ";
  1622.             }
  1623.             $query $em->createQuery($dql)->setParameters($parameters);
  1624.             $data $query->getResult();
  1625.         }
  1626.         // Si solo introduce fecha de fin
  1627.         // Se consulta desde el inicio (2019) a la fecha indicada
  1628.         if (!empty($dateEndReq) and empty($dateStartReq) and empty($monthReq) and empty($yearReq)){
  1629.             $parameters = array(
  1630.                 'start' => '2019-01-01',
  1631.                 'end'=> $dateEndReq,
  1632.                 'opBlocked'=> $opBlocked,
  1633.                 'opConfirmed'=> $opConfirmed,
  1634.                 'opQuoted'=> $opQuoted,
  1635.                 'opInvoiced'=> $opInvoiced,
  1636.                 'opDeleted'=> $opDeleted,
  1637.                 'clientId'=> $clientId,
  1638.             );
  1639.             if (empty($clientId)) {
  1640.                 $dql "SELECT p
  1641.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1642.                         WHERE p.dateStart BETWEEN :start  AND :end
  1643.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  1644.                         AND p.client != :clientId
  1645.                         ORDER BY p.dateStart ASC
  1646.                       ";
  1647.             } else {
  1648.                 $dql "SELECT p
  1649.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1650.                         WHERE p.dateStart BETWEEN :start  AND :end
  1651.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  1652.                         AND p.client = :clientId
  1653.                         ORDER BY p.dateStart ASC
  1654.                       ";
  1655.             }
  1656.             $query $em->createQuery($dql)->setParameters($parameters);
  1657.             $data $query->getResult();
  1658.         }
  1659.         // Si solo introduce mes
  1660.         // Se consulta el mes indicado del año en curso
  1661.         if (!empty($monthReq) and empty($dateStartReq) and empty($dateEndReq) and empty($yearReq)){
  1662.             $stringStart $today->format('Y').'-'.$monthReq.'-01';
  1663.             $stringEnd $today->format('Y').'-'.$monthReq.'-31';                   // Todos los meses podrian ser consultados hasta el dia 31, incluso en febrero
  1664.             $parameters = array(
  1665.                 'start' => $stringStart,
  1666.                 'end'=> $stringEnd,
  1667.                 'opBlocked'=> $opBlocked,
  1668.                 'opConfirmed'=> $opConfirmed,
  1669.                 'opQuoted'=> $opQuoted,
  1670.                 'opInvoiced'=> $opInvoiced,
  1671.                 'opDeleted'=> $opDeleted,
  1672.                 'clientId'=> $clientId,
  1673.             );
  1674.             if (empty($clientId)) {
  1675.                 $dql "SELECT p
  1676.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1677.                         WHERE p.dateStart BETWEEN :start  AND :end
  1678.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  1679.                         AND p.client != :clientId
  1680.                         ORDER BY p.dateStart ASC
  1681.                       ";
  1682.             } else {
  1683.                 $dql "SELECT p
  1684.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1685.                         WHERE p.dateStart BETWEEN :start  AND :end
  1686.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  1687.                         AND p.client = :clientId
  1688.                         ORDER BY p.dateStart ASC
  1689.                       ";
  1690.             }
  1691.             $query $em->createQuery($dql)->setParameters($parameters);
  1692.             $data $query->getResult();
  1693.         }
  1694.         // Si solo introduce año
  1695.         //Se consulta del 01-01 al 31-12 del año indicado
  1696.         if (!empty($yearReq) and empty($dateStartReq) and empty($dateEndReq) and empty($monthReq)){
  1697.             $stringStart $yearReq.'-01-01';
  1698.             $stringEnd $yearReq.'-12-31';
  1699.             $parameters = array(
  1700.                 'start' => $stringStart,
  1701.                 'end'=> $stringEnd,
  1702.                 'opBlocked'=> $opBlocked,
  1703.                 'opConfirmed'=> $opConfirmed,
  1704.                 'opQuoted'=> $opQuoted,
  1705.                 'opInvoiced'=> $opInvoiced,
  1706.                 'opDeleted'=> $opDeleted,
  1707.                 'clientId'=> $clientId,
  1708.             );
  1709.             if (empty($clientId)) {
  1710.                 $dql "SELECT p
  1711.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1712.                         WHERE p.dateStart BETWEEN :start  AND :end
  1713.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  1714.                         AND p.client != :clientId
  1715.                         ORDER BY p.dateStart ASC
  1716.                       ";
  1717.             } else {
  1718.                 $dql "SELECT p
  1719.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1720.                         WHERE p.dateStart BETWEEN :start  AND :end
  1721.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  1722.                         AND p.client = :clientId
  1723.                         ORDER BY p.dateStart ASC
  1724.                       ";
  1725.             }
  1726.             $query $em->createQuery($dql)->setParameters($parameters);
  1727.             $data $query->getResult();
  1728.         }
  1729.         // Se introduce un mes de un año en especifico
  1730.         if (!empty($yearReq) and !empty($monthReq) and empty($dateEndReq) and empty($dateStartReq)){
  1731.             $stringStart $yearReq.'-'.$monthReq.'-01';
  1732.             $stringEnd $yearReq.'-'.$monthReq.'-31';
  1733.             $parameters = array(
  1734.                 'start' => $stringStart,
  1735.                 'end'=> $stringEnd,
  1736.                 'opBlocked'=> $opBlocked,
  1737.                 'opConfirmed'=> $opConfirmed,
  1738.                 'opQuoted'=> $opQuoted,
  1739.                 'opInvoiced'=> $opInvoiced,
  1740.                 'opDeleted'=> $opDeleted,
  1741.                 'clientId'=> $clientId,
  1742.             );
  1743.             if (empty($clientId)) {
  1744.                 $dql "SELECT p
  1745.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1746.                         WHERE p.dateStart BETWEEN :start  AND :end
  1747.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  1748.                         AND p.client != :clientId
  1749.                         ORDER BY p.dateStart ASC
  1750.                       ";
  1751.             } else {
  1752.                 $dql "SELECT p
  1753.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1754.                         WHERE p.dateStart BETWEEN :start  AND :end
  1755.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  1756.                         AND p.client = :clientId
  1757.                         ORDER BY p.dateStart ASC
  1758.                       ";
  1759.             }
  1760.             $query $em->createQuery($dql)->setParameters($parameters);
  1761.             $data $query->getResult();
  1762.         }
  1763.         // Se introduce una fecha de inicio y una fecha de fin
  1764.         if (!empty($dateEndReq) and !empty($dateStartReq) and empty($yearReq) and empty($monthReq)){
  1765.             $parameters = array(
  1766.                 'start' => $dateStartReq,
  1767.                 'end'=> $dateEndReq,
  1768.                 'opBlocked'=> $opBlocked,
  1769.                 'opConfirmed'=> $opConfirmed,
  1770.                 'opQuoted'=> $opQuoted,
  1771.                 'opInvoiced'=> $opInvoiced,
  1772.                 'opDeleted'=> $opDeleted,
  1773.                 'clientId'=> $clientId,
  1774.             );
  1775.             if (empty($clientId)) {
  1776.                 // Se modifican los parametros para despreciar el campo cliente
  1777.                 $parameters = array(
  1778.                     'start' => $dateStartReq,
  1779.                     'end'=>$dateEndReq,
  1780.                     'opBlocked'=> $opBlocked,
  1781.                     'opConfirmed'=> $opConfirmed,
  1782.                     'opQuoted'=> $opQuoted,
  1783.                     'opInvoiced'=> $opInvoiced,
  1784.                     'opDeleted'=> $opDeleted,
  1785.                 );
  1786.                 $dql "SELECT p
  1787.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1788.                         WHERE p.dateStart BETWEEN :start  AND :end
  1789.                         AND (p.dateEnd BETWEEN :start  AND :end)
  1790.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))                          
  1791.                         ORDER BY p.dateStart ASC
  1792.                       ";
  1793.             } else {
  1794.                 $dql "SELECT p
  1795.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1796.                         WHERE p.dateStart BETWEEN :start  AND :end
  1797.                         AND (p.dateEnd BETWEEN :start  AND :end)
  1798.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  1799.                         AND p.client = :clientId
  1800.                         ORDER BY p.dateStart ASC
  1801.                       ";
  1802.             }
  1803.             $query $em->createQuery($dql)->setParameters($parameters);
  1804.             $data $query->getResult();
  1805.             // Se requiere que los eventos que finalicen en el periodo solicitado se
  1806.             // reflejen en la respuesta incluso si el evento inicia antes del primer día
  1807.             // de la consulta. Solicitud: Rafael Guerrero y Gabriela Bracho.
  1808.             if (empty($clientId)) {
  1809.                 $dql "SELECT p
  1810.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1811.                         WHERE p.dateStart < :start
  1812.                         AND (p.dateEnd BETWEEN :start AND :end)
  1813.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))                          
  1814.                         ORDER BY p.dateStart ASC
  1815.                       ";
  1816.             } else {
  1817.                 $dql "SELECT p
  1818.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  1819.                         WHERE p.dateStart < :start
  1820.                         AND p.dateEnd BETWEEN :start AND :end
  1821.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  1822.                         AND p.client = :clientId
  1823.                         ORDER BY p.dateStart ASC
  1824.                       ";
  1825.             }
  1826.             $query $em->createQuery($dql)->setParameters($parameters);
  1827.             $zData $query->getResult();
  1828.             // Agregamos los eventos que iniciando fuera del periodo de consulta, terminan durante el periodo de consulta. Solicitud: Rafael Guerrero y Gabriela Bracho.
  1829.             foreach ($zData as $zItem){ $data[] = $zItem; }
  1830.         }
  1831.         // INICIO: Acotamos segun la(s) sala(s) seleccionada(s)
  1832.         if (!empty($arraySalasId)) {
  1833.             $zData = [];
  1834.             foreach ($data as $item) {
  1835.                 if ($item->getStatus() == 'Invoiced') {
  1836.                     $zExiste $em->getRepository(ReservationInvoiceItems::class)
  1837.                         ->createQueryBuilder('r')
  1838.                         ->where('r.reservationId = :reservationId')
  1839.                         ->andWhere('r.lngIdLounge IN (:arrayIndices)')
  1840.                         ->setParameter('reservationId'$item->getId())
  1841.                         ->setParameter('arrayIndices'$arraySalasId)
  1842.                         ->getQuery()
  1843.                         ->getResult();
  1844.                     if (empty($zExiste)){
  1845.                         $zExiste $em->getRepository(CvrReservationInvoiceItems::class)
  1846.                             ->createQueryBuilder('r')
  1847.                             ->where('r.reservationId = :reservationId')
  1848.                             ->andWhere('r.lngIdLounge IN (:arrayIndices)')
  1849.                             ->setParameter('reservationId'$item->getId())
  1850.                             ->setParameter('arrayIndices'$arraySalasId)
  1851.                             ->getQuery()
  1852.                             ->getResult();
  1853.                     }
  1854.                     if (empty($zExiste)){
  1855.                         $zExiste $em->getRepository(BlvReservationInvoiceItems::class)
  1856.                             ->createQueryBuilder('r')
  1857.                             ->where('r.reservationId = :reservationId')
  1858.                             ->andWhere('r.lngIdLounge IN (:arrayIndices)')
  1859.                             ->setParameter('reservationId'$item->getId())
  1860.                             ->setParameter('arrayIndices'$arraySalasId)
  1861.                             ->getQuery()
  1862.                             ->getResult();
  1863.                     }
  1864.                     if (!empty($zExiste)) {
  1865.                         $zData[] = $item;
  1866.                     }
  1867.                 } else {
  1868.                     $zExiste $em->getRepository(ReservationLoungeSimple::class)
  1869.                         ->createQueryBuilder('r')
  1870.                         ->where('r.idReservation = :idReservation')
  1871.                         ->andWhere('r.idLounge IN (:arrayIndices)')
  1872.                         ->setParameter('idReservation'$item->getId())
  1873.                         ->setParameter('arrayIndices'$arraySalasId)
  1874.                         ->getQuery()
  1875.                         ->getResult();
  1876.                     if (!empty($zExiste)) {
  1877.                         $zData[] = $item;
  1878.                     }
  1879.                 }
  1880.             }
  1881.             $data $zData;
  1882.         }
  1883.         // FIN: Acotamos segun la(s) sala(s) seleccionada(s)
  1884. //dd($data);
  1885. //  ************************************************************************************************************************
  1886. //  ************************************ AGREGAMOS LAS FACTURAS DE COMISION ************************************************
  1887. //  ************************************************************************************************************************
  1888. //        $parameters = array(
  1889. //            'start' => $dateStartReq,
  1890. //            'end'=> $dateEndReq,
  1891. //            'clientType'=> 'Supplier',
  1892. //        );
  1893. //
  1894. //        $dql = "SELECT p
  1895. //                FROM App\MDS\GreenPatioBundle\Entity\ReservationInvoice p
  1896. //                WHERE p.dateAt BETWEEN :start AND :end
  1897. //                AND p.clientType = :clientType
  1898. //                ORDER BY p.dateAt ASC";
  1899. //
  1900. //
  1901. //        $query = $em->createQuery($dql)->setParameters($parameters);
  1902. //        $invoiceSuppGp = $query->getResult();
  1903. //
  1904. //        $dql = "SELECT p
  1905. //                FROM App\MDS\GreenPatioBundle\Entity\CvrReservationInvoice p
  1906. //                WHERE p.dateAt BETWEEN :start AND :end
  1907. //                AND p.clientType = :clientType
  1908. //                ORDER BY p.dateAt ASC";
  1909. //
  1910. //
  1911. //        $query = $em->createQuery($dql)->setParameters($parameters);
  1912. //        $invoiceSuppCvr = $query->getResult();
  1913. //
  1914. //        $dql = "SELECT p
  1915. //                FROM App\MDS\GreenPatioBundle\Entity\BlvReservationInvoice p
  1916. //                WHERE p.dateAt BETWEEN :start AND :end
  1917. //                AND p.clientType = :clientType
  1918. //                ORDER BY p.dateAt ASC";
  1919. //
  1920. //
  1921. //        $query = $em->createQuery($dql)->setParameters($parameters);
  1922. //        $invoiceSuppBlv = $query->getResult();
  1923. //  ************************************************************************************************************************
  1924. //  ************************************ AGREGAMOS LAS FACTURAS DE COMISION ************************************************
  1925. //  ************************************************************************************************************************
  1926. //        if(!empty($invoiceSuppGp)){
  1927. //            // Verificamos si esta dentro de $data la reserva
  1928. //            foreach ($invoiceSuppGp as $item){
  1929. //                $logExisteData = false;
  1930. //                foreach ($data as $elem){
  1931. //                    if ($elem->getId() == $item->getReservationId()){ $logExisteData = true; }
  1932. //                }
  1933. //
  1934. //                if (!$logExisteData){
  1935. //                    $xResv = $em->getRepository(Reservation::class)->findOneById($item->getReservationId());
  1936. //                    $data[] = $xResv;
  1937. //                }
  1938. //            }
  1939. //        }
  1940. //
  1941. //        if(!empty($invoiceSuppCvr)){
  1942. //            // Verificamos si esta dentro de $data la reserva
  1943. //            foreach ($invoiceSuppCvr as $item){
  1944. //                $logExisteData = false;
  1945. //                foreach ($data as $elem){
  1946. //                    if ($elem->getId() == $item->getReservationId()){ $logExisteData = true; }
  1947. //                }
  1948. //
  1949. //                if (!$logExisteData){
  1950. //                    $xResv = $em->getRepository(Reservation::class)->findOneById($item->getReservationId());
  1951. //                    $data[] = $xResv;
  1952. //                }
  1953. //            }
  1954. //        }
  1955. //
  1956. //        if(!empty($invoiceSuppBlv)){
  1957. //            // Verificamos si esta dentro de $data la reserva
  1958. //            foreach ($invoiceSuppBlv as $item){
  1959. //                $logExisteData = false;
  1960. //                foreach ($data as $elem){
  1961. //                    if ($elem->getId() == $item->getReservationId()){ $logExisteData = true; }
  1962. //                }
  1963. //
  1964. //                if (!$logExisteData){
  1965. //                    $xResv = $em->getRepository(Reservation::class)->findOneById($item->getReservationId());
  1966. //                    $data[] = $xResv;
  1967. //                }
  1968. //            }
  1969. //        }
  1970.         $newData = [];
  1971.         $netoForeCast $vatForeCast $totalForeCast 0;
  1972.         foreach ($data as $item){
  1973.             $neto $vat $total 0;
  1974.                 $lounges $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationLoungeSimple')->findByIdReservation($item->getId());
  1975.             $txtArrayLoungesNames = [];
  1976.             $arrayLoungesData = [];
  1977.             foreach ($lounges as $elem){
  1978.                 //Verificamos que la sala se encuentre facturada, el expediente pudo entrar por una factura de comisión
  1979. //                $isInvoicedLoungeGp = $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationInvoiceItems')->findByLngControlId($elem->getId());
  1980. //                $isInvoicedLoungeCv = $em->getRepository('App\MDS\GreenPatioBundle\Entity\CvrReservationInvoiceItems')->findByLngControlId($elem->getId());
  1981. //                $isInvoicedLoungeBl = $em->getRepository('App\MDS\GreenPatioBundle\Entity\BlvReservationInvoiceItems')->findByLngControlId($elem->getId());
  1982. //
  1983. //                if (!empty($isInvoicedLoungeGp)){
  1984. //                    // Verificamos la fecha de la factura
  1985. //                    $xFact = $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationInvoice')->findOneById($isInvoicedLoungeGp[0]->getInvoiceId());
  1986. //                    if (!($xFact->getDateAt() >= $dateStartReq && $xFact->getDateAt() <= $dateEndReq)) {
  1987. //                        $isInvoicedLoungeGp = null;
  1988. //                    }
  1989. //                }
  1990. //
  1991. //                if (!empty($isInvoicedLoungeCv)){
  1992. //                    // Verificamos la fecha de la factura
  1993. //                    $xFact = $em->getRepository('App\MDS\GreenPatioBundle\Entity\CvrReservationInvoice')->findOneById($isInvoicedLoungeCv[0]->getInvoiceId());
  1994. //                    if (!($xFact->getDateAt() >= $dateStartReq && $xFact->getDateAt() <= $dateEndReq)) {
  1995. //                        $isInvoicedLoungeCv = null;
  1996. //                    }
  1997. //                }
  1998. //
  1999. //                if (!empty($isInvoicedLoungeBl)){
  2000. //                    // Verificamos la fecha de la factura
  2001. //                    $xFact = $em->getRepository('App\MDS\GreenPatioBundle\Entity\BlvReservationInvoice')->findOneById($isInvoicedLoungeBl[0]->getInvoiceId());
  2002. //                    if (!($xFact->getDateAt() >= $dateStartReq && $xFact->getDateAt() <= $dateEndReq)) {
  2003. //                        $isInvoicedLoungeBl = null;
  2004. //                    }
  2005. //                }
  2006. //                $isInvoicedLounge = array_merge($isInvoicedLoungeGp,$isInvoicedLoungeCv,$isInvoicedLoungeBl);
  2007. //                if (!empty($isInvoicedLounge)) {
  2008. //                if (true) {
  2009.                     if ($elem->getIdLounge() < 19) {
  2010.                         $location 'Green Patio';
  2011.                     } elseif ($elem->getIdLounge() > 19 && $elem->getIdLounge() < 22) {
  2012.                         $location 'Green Patio + Sala 25';
  2013.                     } elseif ($elem->getIdLounge() > 21 && $elem->getIdLounge() < 30) {
  2014.                         $location 'Covarrubias';
  2015.                     } elseif ($elem->getIdLounge() > 29 && $elem->getIdLounge() < 40) {
  2016.                         $location 'Bella View';
  2017.                     } else {
  2018.                         $location 'Sala 25';
  2019.                     }
  2020.                     $category = empty($elem->getType()) ? 'SALA' 'SALA ' $elem->getType();
  2021.                     $arrayLoungesData[$item->getId()][] = array('loungeName' => $elem->getLoungeName(), 'idLounge' => $elem->getIdLounge(), 'servicePrice' => $elem->getServicePrice(), 'location' => $location'category' => $category);
  2022.                     if (!empty($elem->getServicePrice())) {
  2023.                         $neto $neto floatval($elem->getServicePrice());
  2024.                         $vat $vat + (floatval($elem->getServicePrice()) * floatval($elem->getIva()) / 100);
  2025.                         $total $total + (floatval($elem->getServicePrice()) * (floatval($elem->getIva()) / 100));
  2026.                         $txtArrayLoungesNames[$elem->getIdLounge()] = $elem->getLoungeName();
  2027.                     }
  2028. //                }
  2029.             }
  2030.             // INICIO: Agregamos los servicios
  2031.             $servicesx $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationService')->findBy( array( 'reservationId' => $item->getId(), 'toinvoice' => true ));
  2032.             $arrayServicesData = [];
  2033.             foreach ($servicesx as $elem){
  2034.                 //Verificamos que el servicio se encuentre facturado, el expediente pudo entrar por una factura de comisión
  2035. //                $isInvoicedServiceGp = $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationInvoiceItems')->findBySrvControlId($elem->getId());
  2036. //                $isInvoicedServiceCv = $em->getRepository('App\MDS\GreenPatioBundle\Entity\CvrReservationInvoiceItems')->findBySrvControlId($elem->getId());
  2037. //                $isInvoicedServiceBl = $em->getRepository('App\MDS\GreenPatioBundle\Entity\BlvReservationInvoiceItems')->findBySrvControlId($elem->getId());
  2038. //
  2039. //                if (!empty($isInvoicedServiceGp)){
  2040. //                    // Verificamos la fecha de la factura
  2041. //                    $xFact = $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationInvoice')->findOneById($isInvoicedServiceGp[0]->getInvoiceId());
  2042. //                    if (!($xFact->getDateAt() >= $dateStartReq && $xFact->getDateAt() <= $dateEndReq)) {
  2043. //                        $isInvoicedServiceGp = null;
  2044. //                    }
  2045. //                }
  2046. //
  2047. //                if (!empty($isInvoicedServiceCv)){
  2048. //                    // Verificamos la fecha de la factura
  2049. //                    $xFact = $em->getRepository('App\MDS\GreenPatioBundle\Entity\CvrReservationInvoice')->findOneById($isInvoicedServiceCv[0]->getInvoiceId());
  2050. //                    if (!($xFact->getDateAt() >= $dateStartReq && $xFact->getDateAt() <= $dateEndReq)) {
  2051. //                        $isInvoicedServiceCv = null;
  2052. //                    }
  2053. //                }
  2054. //
  2055. //                if (!empty($isInvoicedServiceBl)){
  2056. //                    // Verificamos la fecha de la factura
  2057. //                    $xFact = $em->getRepository('App\MDS\GreenPatioBundle\Entity\BlvReservationInvoice')->findOneById($isInvoicedServiceBl[0]->getInvoiceId());
  2058. //                    if (!($xFact->getDateAt() >= $dateStartReq && $xFact->getDateAt() <= $dateEndReq)) {
  2059. //                        $isInvoicedServiceBl = null;
  2060. //                    }
  2061. //                }
  2062. //                $isInvoicedService = array_merge($isInvoicedServiceGp,$isInvoicedServiceCv,$isInvoicedServiceBl);
  2063. //                if (!empty($isInvoicedService)) {
  2064.                     if (!empty($elem->getPrice())) {
  2065.                         if (($elem->getUnits() == 0) or (empty($elem->getUnits()))) {
  2066.                             $unitsx 1;
  2067.                         } else {
  2068.                             $unitsx $elem->getUnits();
  2069.                         }
  2070.                         if (($elem->getPax() == 0) or (empty($elem->getPax()))) {
  2071.                             $paxx 1;
  2072.                         } else {
  2073.                             $paxx $elem->getPax();
  2074.                         }
  2075.                         if (($elem->getToinvoice() == 0) or (empty($elem->getToinvoice()))) {
  2076.                             $toinvoicex 0;
  2077.                         } else {
  2078.                             $toinvoicex 1;
  2079.                         }
  2080.                         $pricex = (float)$elem->getPrice() * $unitsx $paxx $toinvoicex;
  2081.                         $category = ($elem->getServiceCatName() == 'Others') ? 'Otros' $elem->getServiceCatName();
  2082.                         $arrayServicesData[$item->getId()][] = array(
  2083.                             'name' => $elem->getName(),
  2084.                             'serviceCatId' => $elem->getServiceCatId(),
  2085.                             'serviceCatName' => $elem->getServiceCatName(),
  2086.                             'price' => $elem->getPrice(),
  2087.                             'category' => $category,
  2088.                         );
  2089.                         switch ($elem->getIva()) {
  2090.                             case '21':
  2091.                                 $ivax 0.21;
  2092.                                 $ivaxPlus 1.21;
  2093.                                 break;
  2094.                             case '10':
  2095.                                 $ivax 0.10;
  2096.                                 $ivaxPlus 1.10;
  2097.                                 break;
  2098.                             case '0':
  2099.                                 $ivax 0;
  2100.                                 $ivaxPlus 1;
  2101.                                 break;
  2102.                             default:
  2103.                                 $ivax 0.21;
  2104.                                 $ivaxPlus 1.21;
  2105.                                 break;
  2106.                         }
  2107.                         $neto $neto $pricex;
  2108.                         $vat $vat + ($pricex $ivax);
  2109.                         $total $total + ($pricex $ivaxPlus);
  2110.                     }
  2111. //                }
  2112.             }
  2113.             // FIN: Agregamos los servicios
  2114.             // INICIO: Agregamos las facturas de comisión
  2115.             $repo $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationInvoice');
  2116.             $qb $repo->createQueryBuilder('ri');
  2117.             $qb->where('ri.reservationId = :resId')
  2118.                 ->andWhere('ri.clientType = :clientType')
  2119. //                ->andWhere('ri.dateAt BETWEEN :dateStart AND :dateEnd')
  2120.                 ->setParameter('resId'$item->getId())
  2121.                 ->setParameter('clientType''Supplier')
  2122. //                ->setParameter('dateStart', $dateStartReq)
  2123. //                ->setParameter('dateEnd', $dateEndReq)
  2124.             ;
  2125.             $supInvoicesxGp $qb->getQuery()->getResult();
  2126.             $repo $em->getRepository('App\MDS\GreenPatioBundle\Entity\CvrReservationInvoice');
  2127.             $qb $repo->createQueryBuilder('ri');
  2128.             $qb->where('ri.reservationId = :resId')
  2129.                 ->andWhere('ri.clientType = :clientType')
  2130. //                ->andWhere('ri.dateAt BETWEEN :dateStart AND :dateEnd')
  2131.                 ->setParameter('resId'$item->getId())
  2132.                 ->setParameter('clientType''Supplier')
  2133. //                ->setParameter('dateStart', $dateStartReq)
  2134. //                ->setParameter('dateEnd', $dateEndReq)
  2135.             ;
  2136.             $supInvoicesxCv $qb->getQuery()->getResult();
  2137.             $repo $em->getRepository('App\MDS\GreenPatioBundle\Entity\BlvReservationInvoice');
  2138.             $qb $repo->createQueryBuilder('ri');
  2139.             $qb->where('ri.reservationId = :resId')
  2140.                 ->andWhere('ri.clientType = :clientType')
  2141. //                ->andWhere('ri.dateAt BETWEEN :dateStart AND :dateEnd')
  2142.                 ->setParameter('resId'$item->getId())
  2143.                 ->setParameter('clientType''Supplier')
  2144. //                ->setParameter('dateStart', $dateStartReq)
  2145. //                ->setParameter('dateEnd', $dateEndReq)
  2146.             ;
  2147.             $supInvoicesxBl $qb->getQuery()->getResult();
  2148.             if (!empty($supInvoicesxGp)){
  2149.                 foreach ($supInvoicesxGp as $supInv){
  2150.                     $supInvIsRec $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationInvoiceRec')->findBy(array('invoiceToRec' => $supInv->getId()));
  2151.                     if (empty($supInvIsRec)) {          // Solo agregamos si no estan rectificadas las facturas de comision
  2152.                         if ($supInv->getDateAt() >= $dateStartReq && $supInv->getDateAt() <= $dateEndReq) {
  2153.                             $supInvItemGp $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationInvoiceItems')->findBy(array('invoiceId' => $supInv->getId()));
  2154.                             foreach ($supInvItemGp as $itemSupInv) {
  2155.                                 $arrayServicesData[$itemSupInv->getId() . 'InvSupGp'][] = array(
  2156.                                     'name' => $itemSupInv->getSrvName(),
  2157.                                     'serviceCatId' => $itemSupInv->getSrvServiceCatId(),
  2158.                                     'serviceCatName' => $itemSupInv->getSrvServiceCatName(),
  2159.                                     'price' => $itemSupInv->getSrvOver(),
  2160.                                     'category' => 'Factura de Comisión',
  2161.                                 );
  2162.                                 $neto += $itemSupInv->getSrvOver();
  2163.                                 $vat += $itemSupInv->getSrvOver() * 0.21;
  2164.                                 $total += $itemSupInv->getSrvOver() * 1.21;
  2165.                             }
  2166.                         }
  2167.                     }
  2168.                 }
  2169.             }
  2170.             if (!empty($supInvoicesxCv)){
  2171.                 foreach ($supInvoicesxCv as $supInv){
  2172.                     $supInvIsRec $em->getRepository('App\MDS\GreenPatioBundle\Entity\CvrReservationInvoiceRec')->findBy(array('invoiceToRec' => $supInv->getId()));
  2173.                     if (empty($supInvIsRec)) {          // Solo agregamos si no estan rectificadas las facturas de comision
  2174.                         if ($supInv->getDateAt() >= $dateStartReq && $supInv->getDateAt() <= $dateEndReq) {
  2175.                             $supInvItemCv $em->getRepository('App\MDS\GreenPatioBundle\Entity\CvrReservationInvoiceItems')->findBy(array('invoiceId' => $supInv->getId()));
  2176.                             foreach ($supInvItemCv as $itemSupInv) {
  2177.                                 $arrayServicesData[$itemSupInv->getId() . 'InvSupCvr'][] = array(
  2178.                                     'name' => $itemSupInv->getSrvName(),
  2179.                                     'serviceCatId' => $itemSupInv->getSrvServiceCatId(),
  2180.                                     'serviceCatName' => $itemSupInv->getSrvServiceCatName(),
  2181.                                     'price' => $itemSupInv->getSrvOver(),
  2182.                                     'category' => 'Factura de Comisión',
  2183.                                 );
  2184.                                 $neto += $itemSupInv->getSrvOver();
  2185.                                 $vat += $itemSupInv->getSrvOver() * 0.21;
  2186.                                 $total += $itemSupInv->getSrvOver() * 1.21;
  2187.                             }
  2188.                         }
  2189.                     }
  2190.                 }
  2191.             }
  2192.             if (!empty($supInvoicesxBl)){
  2193.                 foreach ($supInvoicesxBl as $supInv){
  2194.                     $supInvIsRec $em->getRepository('App\MDS\GreenPatioBundle\Entity\BlvReservationInvoiceRec')->findBy(array('invoiceToRec' => $supInv->getId()));
  2195.                     if (empty($supInvIsRec)) {          // Solo agregamos si no estan rectificadas las facturas de comision
  2196.                         if ($supInv->getDateAt() >= $dateStartReq && $supInv->getDateAt() <= $dateEndReq) {
  2197.                             $supInvItemBl $em->getRepository('App\MDS\GreenPatioBundle\Entity\BlvReservationInvoiceItems')->findBy(array('invoiceId' => $supInv->getId()));
  2198.                             foreach ($supInvItemBl as $itemSupInv) {
  2199.                                 $arrayServicesData[$itemSupInv->getId() . 'InvSupBlv'][] = array(
  2200.                                     'name' => $itemSupInv->getSrvName(),
  2201.                                     'serviceCatId' => $itemSupInv->getSrvServiceCatId(),
  2202.                                     'serviceCatName' => $itemSupInv->getSrvServiceCatName(),
  2203.                                     'price' => $itemSupInv->getSrvOver(),
  2204.                                     'category' => 'Factura de Comisión',
  2205.                                 );
  2206.                                 $neto += $itemSupInv->getSrvOver();
  2207.                                 $vat += $itemSupInv->getSrvOver() * 0.21;
  2208.                                 $total += $itemSupInv->getSrvOver() * 1.21;
  2209.                             }
  2210.                         }
  2211.                     }
  2212.                 }
  2213.             }
  2214.             // Agregamos las rectificativas que pueden anular las facturas de comision
  2215.             if (false) {
  2216.                 $repo $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationInvoiceRec');
  2217.                 $qb $repo->createQueryBuilder('ri');
  2218.                 $qb->where('ri.reservationId = :resId')
  2219.                     ->andWhere('ri.clientType = :clientType')
  2220. //                ->andWhere('ri.dateAt BETWEEN :dateStart AND :dateEnd')
  2221.                     ->setParameter('resId'$item->getId())
  2222.                     ->setParameter('clientType''Supplier')
  2223. //                ->setParameter('dateStart', $dateStartReq)
  2224. //                ->setParameter('dateEnd', $dateEndReq)
  2225.                 ;
  2226.                 $supInvoicesxGp $qb->getQuery()->getResult();
  2227.                 if (!empty($supInvoicesxGp)) {
  2228.                     foreach ($supInvoicesxGp as $supInv) {
  2229.                         if ($supInv->getDateAt() >= $dateStartReq && $supInv->getDateAt() <= $dateEndReq) {
  2230.                             $supInvItemGp $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationInvoiceRecItems')->findBy(array('invoiceId' => $supInv->getId()));
  2231.                             foreach ($supInvItemGp as $itemSupInv) {
  2232.                                 $arrayServicesData[$itemSupInv->getId() . 'InvSupGpRec'][] = array(
  2233.                                     'name' => $itemSupInv->getSrvName(),
  2234.                                     'serviceCatId' => $itemSupInv->getSrvServiceCatId(),
  2235.                                     'serviceCatName' => $itemSupInv->getSrvServiceCatName(),
  2236.                                     'price' => $itemSupInv->getSrvOver(),
  2237.                                     'category' => 'Factura de Comisión Rectificativa',
  2238.                                 );
  2239.                                 $neto += $itemSupInv->getSrvOver();
  2240.                                 $vat += $itemSupInv->getSrvOver() * 0.21;
  2241.                                 $total += $itemSupInv->getSrvOver() * 1.21;
  2242.                             }
  2243.                         }
  2244.                     }
  2245.                 }
  2246.                 $repo $em->getRepository('App\MDS\GreenPatioBundle\Entity\CvrReservationInvoiceRec');
  2247.                 $qb $repo->createQueryBuilder('ri');
  2248.                 $qb->where('ri.reservationId = :resId')
  2249.                     ->andWhere('ri.clientType = :clientType')
  2250. //                ->andWhere('ri.dateAt BETWEEN :dateStart AND :dateEnd')
  2251.                     ->setParameter('resId'$item->getId())
  2252.                     ->setParameter('clientType''Supplier')
  2253. //                ->setParameter('dateStart', $dateStartReq)
  2254. //                ->setParameter('dateEnd', $dateEndReq)
  2255.                 ;
  2256.                 $supInvoicesxCv $qb->getQuery()->getResult();
  2257.                 if (!empty($supInvoicesxCv)) {
  2258.                     foreach ($supInvoicesxCv as $supInv) {
  2259.                         if ($supInv->getDateAt() >= $dateStartReq && $supInv->getDateAt() <= $dateEndReq) {
  2260.                             $supInvItemCv $em->getRepository('App\MDS\GreenPatioBundle\Entity\CvrReservationInvoiceRecItems')->findBy(array('invoiceId' => $supInv->getId()));
  2261.                             foreach ($supInvItemCv as $itemSupInv) {
  2262.                                 $arrayServicesData[$itemSupInv->getId() . 'InvSupCvrRec'][] = array(
  2263.                                     'name' => $itemSupInv->getSrvName(),
  2264.                                     'serviceCatId' => $itemSupInv->getSrvServiceCatId(),
  2265.                                     'serviceCatName' => $itemSupInv->getSrvServiceCatName(),
  2266.                                     'price' => $itemSupInv->getSrvOver(),
  2267.                                     'category' => 'Factura de Comisión Rectificativa',
  2268.                                 );
  2269.                                 $neto += $itemSupInv->getSrvOver();
  2270.                                 $vat += $itemSupInv->getSrvOver() * 0.21;
  2271.                                 $total += $itemSupInv->getSrvOver() * 1.21;
  2272.                             }
  2273.                         }
  2274.                     }
  2275.                 }
  2276.                 $repo $em->getRepository('App\MDS\GreenPatioBundle\Entity\BlvReservationInvoiceRec');
  2277.                 $qb $repo->createQueryBuilder('ri');
  2278.                 $qb->where('ri.reservationId = :resId')
  2279.                     ->andWhere('ri.clientType = :clientType')
  2280. //                ->andWhere('ri.dateAt BETWEEN :dateStart AND :dateEnd')
  2281.                     ->setParameter('resId'$item->getId())
  2282.                     ->setParameter('clientType''Supplier')
  2283. //                ->setParameter('dateStart', $dateStartReq)
  2284. //                ->setParameter('dateEnd', $dateEndReq)
  2285.                 ;
  2286.                 $supInvoicesxBl $qb->getQuery()->getResult();
  2287.                 if (!empty($supInvoicesxBl)) {
  2288.                     foreach ($supInvoicesxBl as $supInv) {
  2289.                         if ($supInv->getDateAt() >= $dateStartReq && $supInv->getDateAt() <= $dateEndReq) {
  2290.                             $supInvItemBl $em->getRepository('App\MDS\GreenPatioBundle\Entity\BlvReservationInvoiceRecItems')->findBy(array('invoiceId' => $supInv->getId()));
  2291.                             foreach ($supInvItemBl as $itemSupInv) {
  2292.                                 $arrayServicesData[$itemSupInv->getId() . 'InvSupBlvRec'][] = array(
  2293.                                     'name' => $itemSupInv->getSrvName(),
  2294.                                     'serviceCatId' => $itemSupInv->getSrvServiceCatId(),
  2295.                                     'serviceCatName' => $itemSupInv->getSrvServiceCatName(),
  2296.                                     'price' => $itemSupInv->getSrvOver(),
  2297.                                     'category' => 'Factura de Comisión Rectificativa',
  2298.                                 );
  2299.                                 $neto += $itemSupInv->getSrvOver();
  2300.                                 $vat += $itemSupInv->getSrvOver() * 0.21;
  2301.                                 $total += $itemSupInv->getSrvOver() * 1.21;
  2302.                             }
  2303.                         }
  2304.                     }
  2305.                 }
  2306.             }
  2307.             // FIN: Agregamos las facturas de comisión
  2308.             $clientName $em->getRepository(Client::class)->findOneById($item->getClient());
  2309.             if (!empty($clientName)){ $clientName $clientName->getName(); } else { $clientName null; }
  2310.             $dateReference = ($item->getDateStart())->format('Ymd');
  2311.             $createdBy $em->getRepository(User::class)->findOneById($item->getCreatedBy());
  2312.             $createdBy $createdBy->getName().' '.$createdBy->getLastName();
  2313.             switch ($item->getStatus()){
  2314.                 case 'Deleted'$status 'Cancelado'; break;
  2315.                 case 'Bloqueo'$status 'Bloquado'; break;
  2316.                 case 'Cotizado'$status 'Cotizado'; break;
  2317.                 case 'Confirmed'$status 'Confirmado'; break;
  2318.                 case 'Invoiced'$status 'Facturado'; break;
  2319.                 default: $status ''; break;
  2320.             }
  2321.             $newData[] = array(
  2322.                 'dateReference' => $dateReference,
  2323.                 'reservationId' => $item->getId(),
  2324.                 'title' => $item->getTitle(),
  2325.                 'clientId' => $item->getClient(),
  2326.                 'clientName' => $clientName,
  2327.                 'dateStart' => $item->getDateStart(),
  2328.                 'dateEnd' => $item->getDateEnd(),
  2329.                 'status' => $status,
  2330.                 'createdAt' => $item->getCreatedAt(),
  2331.                 'txtArrayLoungesNames' => $txtArrayLoungesNames,
  2332.                 'createdBy' => $createdBy,
  2333.                 'arrayLoungesData' => $arrayLoungesData,
  2334.                 'arrayServicesData' => $arrayServicesData,
  2335.                 'neto' => $neto,
  2336.                 'vat' => $vat,
  2337.                 'total' => $total,
  2338.             );
  2339.             if (!empty($status) and !($status == 'Cancelado')){
  2340.                 $netoForeCast $netoForeCast $neto;
  2341.                 $vatForeCast $vatForeCast $vat;
  2342.                 $totalForeCast $totalForeCast $total;
  2343.             }
  2344.         }
  2345.         $data = array(
  2346.             'reservations' => $newData,
  2347.             'netoForeCast' => $netoForeCast,
  2348.             'vatForeCast' => $vatForeCast,
  2349.             'totalForeCast' => $totalForeCast,
  2350.         );
  2351.         return $data;
  2352.     }
  2353.     private function baseForecastClient($dateStartReq$dateEndReq$boolStatus$clientId)
  2354.     {
  2355.         $em $this->getDoctrine()->getManager();
  2356.         $today = new \DateTime("now"NULL);
  2357.         $data = [];
  2358.         if (empty($boolStatus['Blocked'])){ $opBlocked null; } else { $opBlocked 'Bloqueo'; }
  2359.         if (empty($boolStatus['Confirmed'])){ $opConfirmed null; } else { $opConfirmed 'Confirmed'; }
  2360.         if (empty($boolStatus['Quoted'])){ $opQuoted null; } else { $opQuoted 'Cotizado'; }
  2361.         if (empty($boolStatus['Invoiced'])){ $opInvoiced null; } else { $opInvoiced 'Invoiced'; }
  2362.         if (empty($boolStatus['Cancel'])){ $opDeleted null; } else { $opDeleted 'Deleted'; }
  2363.         $dateEndReq = empty($dateEndReq) ? null : new \Datetime($dateEndReq '+ 1 days'); //Se le suma un dia, para que se considere el ultimo dia en la consulta
  2364.         // Si solo introduce fecha de inicio
  2365.         // Se consulta de fecha inicio a fecha actual
  2366.         if (!empty($dateStartReq) and empty($dateEndReq) and empty($monthReq) and empty($yearReq)){
  2367.             $parameters = array(
  2368.                 'start' => $dateStartReq,
  2369.                 'end'=> $today,
  2370.                 'opBlocked'=> $opBlocked,
  2371.                 'opConfirmed'=> $opConfirmed,
  2372.                 'opQuoted'=> $opQuoted,
  2373.                 'opInvoiced'=> $opInvoiced,
  2374.                 'opDeleted'=> $opDeleted,
  2375.                 'clientId'=> $clientId,
  2376.             );
  2377.             if (empty($clientId)){
  2378.                 $dql "SELECT p
  2379.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2380.                         WHERE p.dateStart BETWEEN :start  AND :end 
  2381.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted)) 
  2382.                         AND p.client != :clientId
  2383.                         ORDER BY p.dateStart ASC
  2384.                       ";
  2385.             } else {
  2386.                 $dql "SELECT p
  2387.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2388.                         WHERE p.dateStart BETWEEN :start  AND :end 
  2389.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted)) 
  2390.                         AND p.client = :clientId
  2391.                         ORDER BY p.dateStart ASC
  2392.                       ";
  2393.             }
  2394.             $query $em->createQuery($dql)->setParameters($parameters);
  2395.             $data $query->getResult();
  2396.         }
  2397.         // Si solo introduce fecha de fin
  2398.         // Se consulta desde el inicio (2019) a la fecha indicada
  2399.         if (!empty($dateEndReq) and empty($dateStartReq) and empty($monthReq) and empty($yearReq)){
  2400.             $parameters = array(
  2401.                 'start' => '2019-01-01',
  2402.                 'end'=> $dateEndReq,
  2403.                 'opBlocked'=> $opBlocked,
  2404.                 'opConfirmed'=> $opConfirmed,
  2405.                 'opQuoted'=> $opQuoted,
  2406.                 'opInvoiced'=> $opInvoiced,
  2407.                 'opDeleted'=> $opDeleted,
  2408.                 'clientId'=> $clientId,
  2409.             );
  2410.             if (empty($clientId)) {
  2411.                 $dql "SELECT p
  2412.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2413.                         WHERE p.dateStart BETWEEN :start  AND :end
  2414.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  2415.                         AND p.client != :clientId
  2416.                         ORDER BY p.dateStart ASC
  2417.                       ";
  2418.             } else {
  2419.                 $dql "SELECT p
  2420.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2421.                         WHERE p.dateStart BETWEEN :start  AND :end
  2422.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  2423.                         AND p.client = :clientId
  2424.                         ORDER BY p.dateStart ASC
  2425.                       ";
  2426.             }
  2427.             $query $em->createQuery($dql)->setParameters($parameters);
  2428.             $data $query->getResult();
  2429.         }
  2430.         // Se introduce una fecha de inicio y una fecha de fin
  2431.         if (!empty($dateEndReq) and !empty($dateStartReq) and empty($yearReq) and empty($monthReq)){
  2432.             $parameters = array(
  2433.                 'start' => $dateStartReq,
  2434.                 'end'=> $dateEndReq,
  2435.                 'opBlocked'=> $opBlocked,
  2436.                 'opConfirmed'=> $opConfirmed,
  2437.                 'opQuoted'=> $opQuoted,
  2438.                 'opInvoiced'=> $opInvoiced,
  2439.                 'opDeleted'=> $opDeleted,
  2440.                 'clientId'=> $clientId,
  2441.             );
  2442.             if (empty($clientId)) {
  2443.                 // Se modifican los parametros para despreciar el campo cliente
  2444.                 $parameters = array(
  2445.                     'start' => $dateStartReq,
  2446.                     'end'=>$dateEndReq,
  2447.                     'opBlocked'=> $opBlocked,
  2448.                     'opConfirmed'=> $opConfirmed,
  2449.                     'opQuoted'=> $opQuoted,
  2450.                     'opInvoiced'=> $opInvoiced,
  2451.                     'opDeleted'=> $opDeleted,
  2452.                 );
  2453.                 $dql "SELECT p
  2454.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2455.                         WHERE p.dateStart BETWEEN :start  AND :end
  2456.                         AND (p.dateEnd BETWEEN :start  AND :end)
  2457.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))                          
  2458.                         ORDER BY p.dateStart ASC
  2459.                       ";
  2460.             } else {
  2461.                 $dql "SELECT p
  2462.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2463.                         WHERE p.dateStart BETWEEN :start  AND :end
  2464.                         AND (p.dateEnd BETWEEN :start  AND :end)
  2465.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  2466.                         AND p.client = :clientId
  2467.                         ORDER BY p.dateStart ASC
  2468.                       ";
  2469.             }
  2470.             $query $em->createQuery($dql)->setParameters($parameters);
  2471.             $data $query->getResult();
  2472.             // Se requiere que los eventos que finalicen en el periodo solicitado se
  2473.             // reflejen en la respuesta incluso si el evento inicia antes del primer día
  2474.             // de la consulta. Solicitud: Rafael Guerrero y Gabriela Bracho.
  2475.             if (empty($clientId)) {
  2476.                 $dql "SELECT p
  2477.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2478.                         WHERE p.dateStart < :start
  2479.                         AND (p.dateEnd BETWEEN :start AND :end)
  2480.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))                          
  2481.                         ORDER BY p.dateStart ASC
  2482.                       ";
  2483.             } else {
  2484.                 $dql "SELECT p
  2485.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2486.                         WHERE p.dateStart < :start
  2487.                         AND p.dateEnd BETWEEN :start AND :end
  2488.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  2489.                         AND p.client = :clientId
  2490.                         ORDER BY p.dateStart ASC
  2491.                       ";
  2492.             }
  2493.             $query $em->createQuery($dql)->setParameters($parameters);
  2494.             $zData $query->getResult();
  2495.             // Agregamos los eventos que iniciando fuera del periodo de consulta, terminan durante el periodo de consulta. Solicitud: Rafael Guerrero y Gabriela Bracho.
  2496.             foreach ($zData as $zItem){ $data[] = $zItem; }
  2497.         }
  2498.         $newData = array();
  2499.         $netoForeCast 0$vatForeCast 0$totalForeCast 0;
  2500.         $arrayClients = [];
  2501.         foreach ($data as $item){
  2502.             $neto 0$vat 0$total 0;
  2503. //            $lounges = $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationLoungeSimple')->findByIdReservation($item->getId());
  2504.             $lounges $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationInvoiceItems')->findBy( array( 'reservationId' => $item->getId(), 'itemType' => 'LOUNGE' ));
  2505.             $txtArrayLoungesNames = array(); $arrayLoungesData = array(); $benefit 0$benefitPerc 0;
  2506.             foreach ($lounges as $elem){
  2507.                 if ($elem->getLngIdLounge() < 19) {
  2508.                     $location 'Green Patio';
  2509.                 } elseif ($elem->getLngIdLounge() > 19 && $elem->getLngIdLounge() < 22) {
  2510.                     $location 'Green Patio + Sala 25';
  2511.                 } elseif ($elem->getLngIdLounge() > 21) {
  2512.                     $location 'Covarrubias';
  2513.                 } else {
  2514.                     $location 'Sala 25';
  2515.                 }
  2516. //                $category = empty($elem->getType()) ? 'SALA' : 'SALA '.$elem->getType();
  2517.                 $category 'SALA ';
  2518.                 $arrayLoungesData[$item->getId()][] = array('loungeName'=> $elem->getLngLoungeName(), 'idLounge'=> $elem->getLngIdLounge(), 'servicePrice'=> $elem->getLngServicePrice(), 'location'=> $location'category'=> $category );
  2519.                 if (!empty($elem->getLngServicePrice())) {
  2520.                     $neto $neto floatval($elem->getLngServicePrice());
  2521.                     $vat $vat + (floatval($elem->getLngServicePrice()) * 0.21);
  2522.                     $total $total + (floatval($elem->getLngServicePrice()) * 1.21);
  2523.                     $txtArrayLoungesNames[$elem->getLngIdLounge()] = $elem->getLngLoungeName();
  2524.                     $benefit += floatval($elem->getLngServicePrice());
  2525.                 }
  2526.             }
  2527.             // Salas rectificadas
  2528.             $loungesRec $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationInvoiceRecItems')->findBy( array( 'reservationId' => $item->getId(), 'itemType' => 'LOUNGE' ));
  2529.             foreach ($loungesRec as $elem){
  2530.                 if ($elem->getLngIdLounge() < 19) {
  2531.                     $location 'Green Patio';
  2532.                 } elseif ($elem->getLngIdLounge() > 19 && $elem->getLngIdLounge() < 22) {
  2533.                     $location 'Green Patio + Sala 25';
  2534.                 } elseif ($elem->getLngIdLounge() > 21) {
  2535.                     $location 'Covarrubias';
  2536.                 } else {
  2537.                     $location 'Sala 25';
  2538.                 }
  2539.                 $category 'SALA ';
  2540.                 $arrayLoungesData['R'.$item->getId()][] = array('loungeName'=> $elem->getLngLoungeName(), 'idLounge'=> $elem->getLngIdLounge(), 'servicePrice'=> $elem->getLngServicePrice(), 'location'=> $location'category'=> $category );
  2541.                 if (!empty($elem->getLngServicePrice())) {
  2542.                     $neto $neto floatval($elem->getLngServicePrice());
  2543.                     $vat $vat + (floatval($elem->getLngServicePrice()) * 0.21);
  2544.                     $total $total + (floatval($elem->getLngServicePrice()) * 1.21);
  2545.                     $txtArrayLoungesNames[$elem->getLngIdLounge()] = $elem->getLngLoungeName();
  2546.                     $benefit += floatval($elem->getLngServicePrice());
  2547.                 }
  2548.             }
  2549.             // INICIO: Agregamos los servicios
  2550.             $servicesx $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationService')->findBy( array( 'reservationId' => $item->getId(), ));
  2551.             $arrayServicesData = array();
  2552.             foreach ($servicesx as $elem){
  2553.                 if (!empty($elem->getPrice())) {
  2554.                     if (($elem->getUnits() == 0) or (empty($elem->getUnits()))){ $unitsx 1; } else { $unitsx $elem->getUnits(); }
  2555.                     if (($elem->getPax() == 0) or (empty($elem->getPax()))){ $paxx 1; } else { $paxx $elem->getPax(); }
  2556.                     if (($elem->getToinvoice() == 0) or (empty($elem->getToinvoice()))){ $toinvoicex 0; } else { $toinvoicex 1; }
  2557.                     //Se determina el monto de Comision y Over a sumar o restar al precio
  2558.                     if ($elem->getOpCommission() == 1){
  2559.                         // Comision positiva
  2560.                         if ($elem->getOpOver() == 1){
  2561.                             // Over positivo
  2562.                             if (!empty($elem->getCommission())){
  2563.                                 $commision = (($elem->getPrice() * $unitsx $paxx) * ($elem->getCommission() / 100 )); $over $elem->getOver();
  2564.                             } else {
  2565.                                 $commision 0$over $elem->getOver();
  2566.                             }
  2567.                         } else {
  2568.                             // Over negativo
  2569.                             if (!empty($elem->getCommission())){
  2570.                                 $commision = (($elem->getPrice() * $unitsx $paxx) * ($elem->getCommission() / 100 )); $over = ((-1) * $elem->getOver());
  2571.                             } else {
  2572.                                 $commision 0$over = ((-1) * $elem->getOver());
  2573.                             }
  2574.                         }
  2575.                     } else {
  2576.                         // Comision negativa
  2577.                         if ($elem->getOpOver() == 1){
  2578.                             // Over positivo
  2579.                             if (!empty($elem->getCommission())){
  2580.                                 $commision = ((-1) * (($elem->getPrice() * $unitsx $paxx) * ($elem->getCommission() / 100 ))); $over $elem->getOver();
  2581.                             } else {
  2582.                                 $commision 0$over $elem->getOver();
  2583.                             }
  2584.                         } else {
  2585.                             // Over negativo
  2586.                             if (!empty($elem->getCommission())){
  2587.                                 $commision = ((-1) * (($elem->getPrice() * $unitsx $paxx) * ($elem->getCommission() / 100 ))); $over = ((-1) * $elem->getOver());
  2588.                             } else {
  2589.                                 $commision 0$over = ((-1) * $elem->getOver());
  2590.                             }
  2591.                         }
  2592.                     }
  2593.                     // Se determina el precio final y beneficio
  2594.                     $pricex = (($elem->getPrice() * $unitsx $paxx) + $commision $over) * $toinvoicex;
  2595.                     if ($toinvoicex == 0){
  2596.                         //Si no va a factura el servicio es un costo, habra que restar el precio base, comision y over
  2597.                         $benefit -= ($elem->getPrice() * $unitsx $paxx);
  2598.                         $benefit -= $commision;
  2599.                         $benefit -= $over;
  2600.                     } else {
  2601.                         $benefit += $commision;
  2602.                         $benefit += $over;
  2603.                     }
  2604.                     $category = ($elem->getServiceCatName() == 'Others') ? 'Otros' $elem->getServiceCatName();
  2605.                     $arrayServicesData[$item->getId()][] = array(
  2606.                         'name'=> $elem->getName(),
  2607.                         'serviceCatId'=> $elem->getServiceCatId(),
  2608.                         'serviceCatName'=> $elem->getServiceCatName(),
  2609.                         'price'=> $elem->getPrice(),
  2610.                         'category'=> $category,
  2611.                     );
  2612.                     switch ($elem->getIva()){
  2613.                         case '21'$ivax 0.21$ivaxPlus 1.21; break;
  2614.                         case '10'$ivax 0.10$ivaxPlus 1.10; break;
  2615.                         case '0'$ivax 0$ivaxPlus 1; break;
  2616.                         default: $ivax 0.21$ivaxPlus 1.21; break;
  2617.                     }
  2618.                     $neto $neto $pricex;
  2619.                     $vat $vat + ($pricex $ivax);
  2620.                     $total $total + ($pricex $ivaxPlus);
  2621.                 }
  2622.             }
  2623.             // FIN: Agregamos los servicios
  2624.             $clientName $em->getRepository(Client::class)->findOneById($item->getClient());
  2625.             if (!empty($clientName)){ $clientName $clientName->getName(); } else { $clientName null; }
  2626.             $dateReference = ($item->getDateStart())->format('Ymd');
  2627.             $createdBy $em->getRepository(User::class)->findOneById($item->getCreatedBy());
  2628.             $createdBy $createdBy->getName().' '.$createdBy->getLastName();
  2629.             switch ($item->getStatus()){
  2630.                 case 'Deleted'$status 'Cancelado'; break;
  2631.                 case 'Bloqueo'$status 'Bloquado'; break;
  2632.                 case 'Cotizado'$status 'Cotizado'; break;
  2633.                 case 'Confirmed'$status 'Confirmado'; break;
  2634.                 case 'Invoiced'$status 'Facturado'; break;
  2635.                 default: $status ''; break;
  2636.             }
  2637.             $benefitPerc = ($neto == 0) ? : (($benefit 100)/$neto) ;
  2638.             $newData[] = array(
  2639.                 'dateReference' => $dateReference,
  2640.                 'reservationId' => $item->getId(),
  2641.                 'title' => $item->getTitle(),
  2642.                 'clientId' => $item->getClient(),
  2643.                 'clientName' => $clientName,
  2644.                 'dateStart' => $item->getDateStart(),
  2645.                 'dateEnd' => $item->getDateEnd(),
  2646.                 'status' => $status,
  2647.                 'createdAt' => $item->getCreatedAt(),
  2648.                 'txtArrayLoungesNames' => $txtArrayLoungesNames,
  2649.                 'createdBy' => $createdBy,
  2650.                 'arrayLoungesData' => $arrayLoungesData,
  2651.                 'arrayServicesData' => $arrayServicesData,
  2652.                 'neto' => $neto,
  2653.                 'vat' => $vat,
  2654.                 'total' => $total,
  2655.                 'beneficio' => $benefit,
  2656.                 'benefitPerc' => $benefitPerc,
  2657.             );
  2658.             if (!empty($status) and !($status == 'Cancelado')){
  2659.                 $netoForeCast $netoForeCast $neto;
  2660.                 $vatForeCast $vatForeCast $vat;
  2661.                 $totalForeCast $totalForeCast $total;
  2662.             }
  2663.         }
  2664.         foreach($newData as $item){
  2665.             $arrayClients[$item['clientId']]['reservas'][] = $item;
  2666.             $arrayClients[$item['clientId']]['netoTotalCliente'] = (array_key_exists('netoTotalCliente'$arrayClients[$item['clientId']])) ? ($arrayClients[$item['clientId']]['netoTotalCliente'] + $item['neto']) : $item['neto'];
  2667.             $arrayClients[$item['clientId']]['totalCliente'] = (array_key_exists('totalCliente'$arrayClients[$item['clientId']])) ? ($arrayClients[$item['clientId']]['totalCliente'] + $item['total']) : $item['total'];
  2668.             $arrayClients[$item['clientId']]['percFacturaTotalClienteContraFacturaTotalEventos'] = 0;
  2669.             $arrayClients[$item['clientId']]['beneficioCliente'] = (array_key_exists('beneficioCliente'$arrayClients[$item['clientId']])) ? ($arrayClients[$item['clientId']]['beneficioCliente'] + $item['beneficio']) : $item['beneficio'];
  2670.             $arrayClients[$item['clientId']]['numeroEventosCliente'] = count($arrayClients[$item['clientId']]['reservas']);
  2671.             $arrayClients[$item['clientId']]['rentabilidadPercBenefit'] = 0;
  2672.         }
  2673.         foreach ($arrayClients as $key => $item){
  2674.             $arrayClients[$key]['percFacturaTotalClienteContraFacturaTotalEventos'] = (($item['netoTotalCliente'] * 100) / $netoForeCast);
  2675.             if ($item['netoTotalCliente'] == 0){
  2676.                 // Si no aparece en factura el neto del cliente sera 0, la rentabilidad sera 0
  2677.                 $arrayClients[$key]['rentabilidadPercBenefit'] = 0;
  2678.             } else {
  2679.                 $arrayClients[$key]['rentabilidadPercBenefit'] = (($item['beneficioCliente'] * 100) / $item['netoTotalCliente']);
  2680.             }
  2681.         }
  2682.         // Ordenamos el arreglo de mayor a menor por el campo 'percFacturaTotalClienteContraFacturaTotalEventos'
  2683.         uasort($arrayClients, function ($a$b) { return $b['percFacturaTotalClienteContraFacturaTotalEventos'] <=> $a['percFacturaTotalClienteContraFacturaTotalEventos']; });
  2684.         $data = array(
  2685.             'reservationsClients' => $arrayClients,
  2686.             'netoForeCast' => $netoForeCast,
  2687.             'vatForeCast' => $vatForeCast,
  2688.             'totalForeCast' => $totalForeCast,
  2689.         );
  2690.         return $data;
  2691.     }
  2692.     private function baseForecastWeb($dateStartReq$dateEndReq$boolStatus$arraySalasId)
  2693.     {
  2694.         $em $this->getDoctrine()->getManager();
  2695.         $today = new \DateTime("now"NULL);
  2696.         $data = [];
  2697.         $clientId null;
  2698.         $arrayStatusCont =[ 'Iniciado' => 0'Cancelado' => 0'Bloqueado' => 0'Cotizado' => 0'Confirmado' => 0'Facturado' => ];
  2699.         if (empty($boolStatus['Blocked'])){ $opBlocked null; } else { $opBlocked 'Bloqueo'; }
  2700.         if (empty($boolStatus['Confirmed'])){ $opConfirmed null; } else { $opConfirmed 'Confirmed'; }
  2701.         if (empty($boolStatus['Quoted'])){ $opQuoted null; } else { $opQuoted 'Cotizado'; }
  2702.         if (empty($boolStatus['Invoiced'])){ $opInvoiced null; } else { $opInvoiced 'Invoiced'; }
  2703.         if (empty($boolStatus['Cancel'])){ $opDeleted null; } else { $opDeleted 'Deleted'; }
  2704.         $dateEndReq = empty($dateEndReq) ? null : new \Datetime($dateEndReq '+ 1 days'); //Se le suma un dia, para que se considere el ultimo dia en la consulta
  2705.         // Si solo introduce fecha de inicio
  2706.         // Se consulta de fecha inicio a fecha actual
  2707.         if (!empty($dateStartReq) and empty($dateEndReq) and empty($monthReq) and empty($yearReq)){
  2708.             $parameters = array(
  2709.                 'start' => $dateStartReq,
  2710.                 'end'=> $today,
  2711.                 'opBlocked'=> $opBlocked,
  2712.                 'opConfirmed'=> $opConfirmed,
  2713.                 'opQuoted'=> $opQuoted,
  2714.                 'opInvoiced'=> $opInvoiced,
  2715.                 'opDeleted'=> $opDeleted,
  2716.             );
  2717.             if (!empty($clientId)){
  2718.                 $dql "SELECT p
  2719.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2720.                         WHERE p.dateStart BETWEEN :start  AND :end 
  2721.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))                         
  2722.                         AND p.infoFormWeb <> null
  2723.                         ORDER BY p.dateStart ASC
  2724.                       ";
  2725.             }
  2726.             $query $em->createQuery($dql)->setParameters($parameters);
  2727.             $data $query->getResult();
  2728.         }
  2729.         // Si solo introduce fecha de fin
  2730.         // Se consulta desde el inicio (2019) a la fecha indicada
  2731.         if (!empty($dateEndReq) and empty($dateStartReq) and empty($monthReq) and empty($yearReq)){
  2732.             $parameters = array(
  2733.                 'start' => '2019-01-01',
  2734.                 'end'=> $dateEndReq,
  2735.                 'opBlocked'=> $opBlocked,
  2736.                 'opConfirmed'=> $opConfirmed,
  2737.                 'opQuoted'=> $opQuoted,
  2738.                 'opInvoiced'=> $opInvoiced,
  2739.                 'opDeleted'=> $opDeleted,
  2740.             );
  2741.             if (!empty($clientId)) {
  2742.                 $dql "SELECT p
  2743.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2744.                         WHERE p.dateStart BETWEEN :start  AND :end
  2745.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  2746.                         AND p.infoFormWeb <> null
  2747.                         ORDER BY p.dateStart ASC
  2748.                       ";
  2749.             }
  2750.             $query $em->createQuery($dql)->setParameters($parameters);
  2751.             $data $query->getResult();
  2752.         }
  2753.         // Si solo introduce mes
  2754.         // Se consulta el mes indicado del año en curso
  2755.         if (!empty($monthReq) and empty($dateStartReq) and empty($dateEndReq) and empty($yearReq)){
  2756.             $stringStart $today->format('Y').'-'.$monthReq.'-01';
  2757.             $stringEnd $today->format('Y').'-'.$monthReq.'-31';                   // Todos los meses podrian ser consultados hasta el dia 31, incluso en febrero
  2758.             $parameters = array(
  2759.                 'start' => $stringStart,
  2760.                 'end'=> $stringEnd,
  2761.                 'opBlocked'=> $opBlocked,
  2762.                 'opConfirmed'=> $opConfirmed,
  2763.                 'opQuoted'=> $opQuoted,
  2764.                 'opInvoiced'=> $opInvoiced,
  2765.                 'opDeleted'=> $opDeleted,
  2766.             );
  2767.             if (!empty($clientId)) {
  2768.                 $dql "SELECT p
  2769.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2770.                         WHERE p.dateStart BETWEEN :start  AND :end
  2771.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  2772.                         AND p.infoFormWeb <> null
  2773.                         ORDER BY p.dateStart ASC
  2774.                       ";
  2775.             }
  2776.             $query $em->createQuery($dql)->setParameters($parameters);
  2777.             $data $query->getResult();
  2778.         }
  2779.         // Si solo introduce año
  2780.         //Se consulta del 01-01 al 31-12 del año indicado
  2781.         if (!empty($yearReq) and empty($dateStartReq) and empty($dateEndReq) and empty($monthReq)){
  2782.             $stringStart $yearReq.'-01-01';
  2783.             $stringEnd $yearReq.'-12-31';
  2784.             $parameters = array(
  2785.                 'start' => $stringStart,
  2786.                 'end'=> $stringEnd,
  2787.                 'opBlocked'=> $opBlocked,
  2788.                 'opConfirmed'=> $opConfirmed,
  2789.                 'opQuoted'=> $opQuoted,
  2790.                 'opInvoiced'=> $opInvoiced,
  2791.                 'opDeleted'=> $opDeleted,
  2792.             );
  2793.             if (!empty($clientId)) {
  2794.                 $dql "SELECT p
  2795.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2796.                         WHERE p.dateStart BETWEEN :start  AND :end
  2797.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  2798.                         AND p.infoFormWeb <> null
  2799.                         ORDER BY p.dateStart ASC
  2800.                       ";
  2801.             }
  2802.             $query $em->createQuery($dql)->setParameters($parameters);
  2803.             $data $query->getResult();
  2804.         }
  2805.         // Se introduce un mes de un año en especifico
  2806.         if (!empty($yearReq) and !empty($monthReq) and empty($dateEndReq) and empty($dateStartReq)){
  2807.             $stringStart $yearReq.'-'.$monthReq.'-01';
  2808.             $stringEnd $yearReq.'-'.$monthReq.'-31';
  2809.             $parameters = array(
  2810.                 'start' => $stringStart,
  2811.                 'end'=> $stringEnd,
  2812.                 'opBlocked'=> $opBlocked,
  2813.                 'opConfirmed'=> $opConfirmed,
  2814.                 'opQuoted'=> $opQuoted,
  2815.                 'opInvoiced'=> $opInvoiced,
  2816.                 'opDeleted'=> $opDeleted,
  2817.             );
  2818.             if (!empty($clientId)) {
  2819.                 $dql "SELECT p
  2820.                         FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2821.                         WHERE p.dateStart BETWEEN :start  AND :end
  2822.                         AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  2823.                         AND p.infoFormWeb <> null
  2824.                         ORDER BY p.dateStart ASC
  2825.                       ";
  2826.             }
  2827.             $query $em->createQuery($dql)->setParameters($parameters);
  2828.             $data $query->getResult();
  2829.         }
  2830.         // Se introduce una fecha de inicio y una fecha de fin
  2831.         if (!empty($dateEndReq) and !empty($dateStartReq) and empty($yearReq) and empty($monthReq)){
  2832.             $parameters = array(
  2833.                 'start' => $dateStartReq,
  2834.                 'end'=> $dateEndReq,
  2835.                 'opBlocked'=> $opBlocked,
  2836.                 'opConfirmed'=> $opConfirmed,
  2837.                 'opQuoted'=> $opQuoted,
  2838.                 'opInvoiced'=> $opInvoiced,
  2839.                 'opDeleted'=> $opDeleted,
  2840.             );
  2841.             $dql "SELECT p
  2842.                     FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2843.                     WHERE p.dateStart BETWEEN :start  AND :end
  2844.                     AND (p.dateEnd BETWEEN :start  AND :end)
  2845.                     AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  2846.                     AND p.infoFormWeb IS NOT NULL
  2847.                     ORDER BY p.dateStart ASC
  2848.                   ";
  2849.             $query $em->createQuery($dql)->setParameters($parameters);
  2850.             $data $query->getResult();
  2851. //dd('check', $data);
  2852.             // Se requiere que los eventos que finalicen en el periodo solicitado se
  2853.             // reflejen en la respuesta incluso si el evento inicia antes del primer día
  2854.             // de la consulta. Solicitud: Rafael Guerrero y Gabriela Bracho.
  2855. //            if (!empty($clientId)) {
  2856. //                $dql = "SELECT p
  2857. //                        FROM App\MDS\GreenPatioBundle\Entity\Reservation p
  2858. //                        WHERE p.dateStart < :start
  2859. //                        AND p.dateEnd BETWEEN :start AND :end
  2860. //                        AND ((p.status = :opBlocked) OR (p.status = :opConfirmed) OR (p.status = :opQuoted) OR (p.status = :opInvoiced) OR (p.status = :opDeleted))
  2861. //                        AND p.infoFormWeb <> null
  2862. //                        ORDER BY p.dateStart ASC
  2863. //                      ";
  2864. //            }
  2865. //
  2866. //            $query = $em->createQuery($dql)->setParameters($parameters);
  2867. //            $zData = $query->getResult();
  2868. //
  2869. //            // Agregamos los eventos que iniciando fuera del periodo de consulta, terminan durante el periodo de consulta. Solicitud: Rafael Guerrero y Gabriela Bracho.
  2870. //            foreach ($zData as $zItem){ $data[] = $zItem; }
  2871.         }
  2872.         // INICIO: Acotamos segun la(s) sala(s) seleccionada(s)
  2873.         if (!empty($arraySalasId)) {
  2874.             $zData = [];
  2875.             foreach ($data as $item) {
  2876.                 if ($item->getStatus() == 'Invoiced') {
  2877.                     $zExiste $em->getRepository(ReservationInvoiceItems::class)
  2878.                         ->createQueryBuilder('r')
  2879.                         ->where('r.reservationId = :reservationId')
  2880.                         ->andWhere('r.lngIdLounge IN (:arrayIndices)')
  2881.                         ->setParameter('reservationId'$item->getId())
  2882.                         ->setParameter('arrayIndices'$arraySalasId)
  2883.                         ->getQuery()
  2884.                         ->getResult();
  2885.                     if (empty($zExiste)){
  2886.                         $zExiste $em->getRepository(CvrReservationInvoiceItems::class)
  2887.                             ->createQueryBuilder('r')
  2888.                             ->where('r.reservationId = :reservationId')
  2889.                             ->andWhere('r.lngIdLounge IN (:arrayIndices)')
  2890.                             ->setParameter('reservationId'$item->getId())
  2891.                             ->setParameter('arrayIndices'$arraySalasId)
  2892.                             ->getQuery()
  2893.                             ->getResult();
  2894.                     }
  2895.                     if (empty($zExiste)){
  2896.                         $zExiste $em->getRepository(BlvReservationInvoiceItems::class)
  2897.                             ->createQueryBuilder('r')
  2898.                             ->where('r.reservationId = :reservationId')
  2899.                             ->andWhere('r.lngIdLounge IN (:arrayIndices)')
  2900.                             ->setParameter('reservationId'$item->getId())
  2901.                             ->setParameter('arrayIndices'$arraySalasId)
  2902.                             ->getQuery()
  2903.                             ->getResult();
  2904.                     }
  2905.                     if (!empty($zExiste)) {
  2906.                         $zData[] = $item;
  2907.                     }
  2908.                 } else {
  2909.                     $zExiste $em->getRepository(ReservationLoungeSimple::class)
  2910.                         ->createQueryBuilder('r')
  2911.                         ->where('r.idReservation = :idReservation')
  2912.                         ->andWhere('r.idLounge IN (:arrayIndices)')
  2913.                         ->setParameter('idReservation'$item->getId())
  2914.                         ->setParameter('arrayIndices'$arraySalasId)
  2915.                         ->getQuery()
  2916.                         ->getResult();
  2917.                     if (!empty($zExiste)) {
  2918.                         $zData[] = $item;
  2919.                     }
  2920.                 }
  2921.             }
  2922.             $data $zData;
  2923.         }
  2924.         // FIN: Acotamos segun la(s) sala(s) seleccionada(s)
  2925. //dd('la data', $data);
  2926. //  ************************************************************************************************************************
  2927. //  ************************************ AGREGAMOS LAS FACTURAS DE COMISION ************************************************
  2928. //  ************************************************************************************************************************
  2929.         $parameters = array(
  2930.             'start' => $dateStartReq,
  2931.             'end'=> $today,
  2932.             'clientType'=> 'Supplier',
  2933.         );
  2934.         $dql "SELECT p
  2935.                 FROM App\MDS\GreenPatioBundle\Entity\ReservationInvoice p
  2936.                 WHERE p.dateAt BETWEEN :start AND :end                      
  2937.                 AND p.clientType = :clientType
  2938.                 ORDER BY p.dateAt ASC";
  2939.         $query $em->createQuery($dql)->setParameters($parameters);
  2940.         $invoiceSuppGp $query->getResult();
  2941.         $dql "SELECT p
  2942.                 FROM App\MDS\GreenPatioBundle\Entity\CvrReservationInvoice p
  2943.                 WHERE p.dateAt BETWEEN :start AND :end                      
  2944.                 AND p.clientType = :clientType
  2945.                 ORDER BY p.dateAt ASC";
  2946.         $query $em->createQuery($dql)->setParameters($parameters);
  2947.         $invoiceSuppCvr $query->getResult();
  2948.         $dql "SELECT p
  2949.                 FROM App\MDS\GreenPatioBundle\Entity\BlvReservationInvoice p
  2950.                 WHERE p.dateAt BETWEEN :start AND :end                      
  2951.                 AND p.clientType = :clientType
  2952.                 ORDER BY p.dateAt ASC";
  2953.         $query $em->createQuery($dql)->setParameters($parameters);
  2954.         $invoiceSuppBlv $query->getResult();
  2955. //  ************************************************************************************************************************
  2956. //  ************************************ AGREGAMOS LAS FACTURAS DE COMISION ************************************************
  2957. //  ************************************************************************************************************************
  2958.         if(!empty($invoiceSuppGp)){
  2959.             // Verificamos si esta dentro de $data la reserva
  2960.             foreach ($invoiceSuppGp as $item){
  2961.                 $logExisteData false;
  2962.                 foreach ($data as $elem){
  2963.                     if ($elem->getId() == $item->getReservationId()){ $logExisteData true; }
  2964.                 }
  2965.                 if (!$logExisteData){
  2966.                     $xResv $em->getRepository(Reservation::class)->findOneById($item->getReservationId());
  2967.                     if (!empty($xResv->getInfoFormWeb())) { $data[] = $xResv; }         // Solo se agregaran expedientes de la web
  2968.                 }
  2969.             }
  2970.         }
  2971.         if(!empty($invoiceSuppCvr)){
  2972.             // Verificamos si esta dentro de $data la reserva
  2973.             foreach ($invoiceSuppCvr as $item){
  2974.                 $logExisteData false;
  2975.                 foreach ($data as $elem){
  2976.                     if ($elem->getId() == $item->getReservationId()){ $logExisteData true; }
  2977.                 }
  2978.                 if (!$logExisteData){
  2979.                     $xResv $em->getRepository(Reservation::class)->findOneById($item->getReservationId());
  2980.                     if (!empty($xResv->getInfoFormWeb())) { $data[] = $xResv; }         // Solo se agregaran expedientes de la web
  2981.                 }
  2982.             }
  2983.         }
  2984.         if(!empty($invoiceSuppBlv)){
  2985.             // Verificamos si esta dentro de $data la reserva
  2986.             foreach ($invoiceSuppBlv as $item){
  2987.                 $logExisteData false;
  2988.                 foreach ($data as $elem){
  2989.                     if ($elem->getId() == $item->getReservationId()){ $logExisteData true; }
  2990.                 }
  2991.                 if (!$logExisteData){
  2992.                     $xResv $em->getRepository(Reservation::class)->findOneById($item->getReservationId());
  2993.                     if (!empty($xResv->getInfoFormWeb())) { $data[] = $xResv; }         // Solo se agregaran expedientes de la web
  2994.                 }
  2995.             }
  2996.         }
  2997. //dd($invoiceSuppGp, $invoiceSuppCvr, $invoiceSuppBlv, $data, 'BUSCAR LAS FACTURAS DE COMISION');
  2998.         $newData = [];
  2999.         $netoForeCast $vatForeCast $totalForeCast 0;
  3000.         foreach ($data as $item){
  3001.             $neto $vat $total 0;
  3002.             $lounges $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationLoungeSimple')->findByIdReservation($item->getId());
  3003.             $txtArrayLoungesNames = [];
  3004.             $arrayLoungesData = [];
  3005.             foreach ($lounges as $elem){
  3006.                 if ($elem->getIdLounge() < 19) {
  3007.                     $location 'Green Patio';
  3008.                 } elseif ($elem->getIdLounge() > 19 && $elem->getIdLounge() < 22) {
  3009.                     $location 'Green Patio + Sala 25';
  3010.                 } elseif ($elem->getIdLounge() > 21 && $elem->getIdLounge() < 30) {
  3011.                     $location 'Covarrubias';
  3012.                 } elseif ($elem->getIdLounge() > 29 && $elem->getIdLounge() < 40) {
  3013.                     $location 'Bella View';
  3014.                 } else {
  3015.                     $location 'Sala 25';
  3016.                 }
  3017.                 $category = empty($elem->getType()) ? 'SALA' 'SALA '.$elem->getType();
  3018.                 $arrayLoungesData[$item->getId()][] = array('loungeName'=> $elem->getLoungeName(), 'idLounge'=> $elem->getIdLounge(), 'servicePrice'=> $elem->getServicePrice(), 'location'=> $location'category'=> $category );
  3019.                 if (!empty($elem->getServicePrice())) {
  3020.                     $neto $neto floatval($elem->getServicePrice());
  3021.                     $vat $vat + (floatval($elem->getServicePrice()) * floatval($elem->getIva())/100);
  3022.                     $total $total + (floatval($elem->getServicePrice()) * (floatval($elem->getIva())/100));
  3023.                     $txtArrayLoungesNames[$elem->getIdLounge()] = $elem->getLoungeName();
  3024.                 }
  3025.             }
  3026.             // INICIO: Agregamos los servicios
  3027.             $servicesx $em->getRepository('App\MDS\GreenPatioBundle\Entity\ReservationService')->findBy( array( 'reservationId' => $item->getId(), 'toinvoice' => true ));
  3028.             $arrayServicesData = [];
  3029.             foreach ($servicesx as $elem){
  3030.                 if (!empty($elem->getPrice())) {
  3031.                     if (($elem->getUnits() == 0) or (empty($elem->getUnits()))){ $unitsx 1; } else { $unitsx $elem->getUnits(); }
  3032.                     if (($elem->getPax() == 0) or (empty($elem->getPax()))){ $paxx 1; } else { $paxx $elem->getPax(); }
  3033.                     if (($elem->getToinvoice() == 0) or (empty($elem->getToinvoice()))){ $toinvoicex 0; } else { $toinvoicex 1; }
  3034.                     $pricex = (float)$elem->getPrice() * $unitsx $paxx $toinvoicex;
  3035.                     $category = ($elem->getServiceCatName() == 'Others') ? 'Otros' $elem->getServiceCatName();
  3036.                     $arrayServicesData[$item->getId()][] = array(
  3037.                         'name'=> $elem->getName(),
  3038.                         'serviceCatId'=> $elem->getServiceCatId(),
  3039.                         'serviceCatName'=> $elem->getServiceCatName(),
  3040.                         'price'=> $elem->getPrice(),
  3041.                         'category'=> $category,
  3042.                     );
  3043.                     switch ($elem->getIva()){
  3044.                         case '21'$ivax 0.21$ivaxPlus 1.21; break;
  3045.                         case '10'$ivax 0.10$ivaxPlus 1.10; break;
  3046.                         case '0'$ivax 0$ivaxPlus 1; break;
  3047.                         default: $ivax 0.21$ivaxPlus 1.21; break;
  3048.                     }
  3049.                     $neto $neto $pricex;
  3050.                     $vat $vat + ($pricex $ivax);
  3051.                     $total $total + ($pricex $ivaxPlus);
  3052.                 }
  3053.             }
  3054.             // FIN: Agregamos los servicios
  3055.             $clientName $em->getRepository(Client::class)->findOneById($item->getClient());
  3056.             if (!empty($clientName)){ $clientName $clientName->getName(); } else { $clientName null; }
  3057.             $dateReference = ($item->getDateStart())->format('Ymd');
  3058.             $createdBy $em->getRepository(User::class)->findOneById($item->getCreatedBy());
  3059.             $createdBy $createdBy->getName().' '.$createdBy->getLastName();
  3060.             switch ($item->getStatus()){
  3061.                 case 'Iniciado'$status 'Iniciado'$arrayStatusCont['Iniciado'] += ; break;
  3062.                 case 'Deleted'$status 'Cancelado'$arrayStatusCont['Cancelado'] += ; break;
  3063.                 case 'Bloqueo'$status 'Bloqueado'$arrayStatusCont['Bloqueado'] += ; break;
  3064.                 case 'Cotizado'$status 'Cotizado'$arrayStatusCont['Cotizado'] += ; break;
  3065.                 case 'Confirmed'$status 'Confirmado'$arrayStatusCont['Confirmado'] += ; break;
  3066.                 case 'Invoiced'$status 'Facturado'$arrayStatusCont['Facturado'] += ; break;
  3067.                 default: $status ''; break;
  3068.             }
  3069.             $newData[] = array(
  3070.                 'dateReference' => $dateReference,
  3071.                 'reservationId' => $item->getId(),
  3072.                 'title' => $item->getTitle(),
  3073.                 'clientId' => $item->getClient(),
  3074.                 'clientName' => $clientName,
  3075.                 'infoFormWeb' => str_replace('||''<br>',$item->getInfoFormWeb()),
  3076.                 'dateStart' => $item->getDateStart(),
  3077.                 'dateEnd' => $item->getDateEnd(),
  3078.                 'status' => $status,
  3079.                 'createdAt' => $item->getCreatedAt(),
  3080.                 'txtArrayLoungesNames' => $txtArrayLoungesNames,
  3081.                 'createdBy' => $createdBy,
  3082.                 'arrayLoungesData' => $arrayLoungesData,
  3083.                 'arrayServicesData' => $arrayServicesData,
  3084.                 'neto' => $neto,
  3085.                 'vat' => $vat,
  3086.                 'total' => $total,
  3087.             );
  3088.             if (!empty($status) and !($status == 'Cancelado')){
  3089.                 $netoForeCast $netoForeCast $neto;
  3090.                 $vatForeCast $vatForeCast $vat;
  3091.                 $totalForeCast $totalForeCast $total;
  3092.             }
  3093.         }
  3094.         $data = array(
  3095.             'reservations' => $newData,
  3096.             'arrayStatusCont' => $arrayStatusCont,
  3097.             'netoForeCast' => $netoForeCast,
  3098.             'vatForeCast' => $vatForeCast,
  3099.             'totalForeCast' => $totalForeCast,
  3100.         );
  3101.         return $data;
  3102.     }
  3103. };