src/MDS/GreenPatioBundle/Controller/ReservationsInvoiceController.php line 128

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: Carlos.Rojas
  5.  * Date: 18/12/2019
  6.  * Time: 12:49
  7.  */
  8. namespace App\MDS\GreenPatioBundle\Controller;
  9. use App\Entity\Cities;
  10. use App\Entity\Client;
  11. use App\Entity\Country;
  12. use App\Entity\Regions;
  13. use App\Entity\SettingsCompany;
  14. use App\Entity\Supplier;
  15. use App\MDS\GreenPatioBundle\Entity\CvrReservationInvoiceItems;
  16. use App\MDS\GreenPatioBundle\Entity\Reservation;
  17. use App\MDS\GreenPatioBundle\Entity\ReservationBudgetItems;
  18. use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceItems;
  19. use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceProformaItems;
  20. use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceRec;
  21. use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceRecItems;
  22. use App\MDS\GreenPatioBundle\Entity\ReservationPaymentsClient;
  23. use App\MDS\GreenPatioBundle\Entity\ReservationProforma;
  24. use App\MDS\GreenPatioBundle\Entity\ReservationInvoice;
  25. use App\MDS\GreenPatioBundle\Entity\ReservationProformaDeposit;
  26. use App\MDS\GreenPatioBundle\Entity\ReservationTracing;
  27. use App\MDS\GreenPatioBundle\Form\ReservationPaymentsClientType;
  28. use App\MDS\GreenPatioBundle\Form\ReservationInvoiceType;
  29. use Symfony\Component\Routing\Annotation\Route;
  30. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use Symfony\Component\HttpFoundation\JsonResponse;
  33. use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceDepositItems;
  34. use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceDepositControl;
  35. use App\MDS\GreenPatioBundle\Entity\ReservationLounge;
  36. use App\MDS\GreenPatioBundle\Entity\ReservationLoungeProfile;
  37. use App\MDS\GreenPatioBundle\Entity\ReservationLoungeSimple;
  38. use App\MDS\GreenPatioBundle\Entity\ReservationService;
  39. use App\MDS\GreenPatioBundle\Form\ReservationInvoiceDepositItemsType;
  40. use DateTime;
  41. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  42. use PhpOffice\PhpSpreadsheet\Style\Fill;
  43. use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
  44. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  45. use Symfony\Contracts\Translation\TranslatorInterface;
  46. class ReservationsInvoiceController extends AbstractController
  47. {
  48.     private $translator;
  49.     public function __construct(TranslatorInterface $translator) {
  50.         $this->translator $translator;
  51.     }
  52.     
  53.     /**
  54.      * @Route("/payment/{id}",  name="reservations_payment")
  55.      */
  56.     public function detailsReservationProformaAction($idRequest $request)
  57.     {
  58.         $em $this->getDoctrine()->getManager();
  59.         $paymentsClient = new ReservationPaymentsClient();
  60.         $paymentsClient->setReservationId($id);
  61.         $form $this->createReservationPaymentsClientForm($paymentsClient);
  62.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  63.         $payments $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
  64.         $services $em->getRepository(ReservationService::class)->findByReservationId($id);
  65.         $proforma $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  66.         $reservaInv = new ReservationInvoice();
  67.         $reservaInv->setReservationId($id);
  68.         $form1 $this->createReservationInvoiceProformaForm($reservaInv);
  69.         if (!empty($proforma)){
  70.             $type 'Proforma';
  71.             $number $proforma->getId();
  72.             $date $proforma->getDateAt();
  73.             $prefix $proforma->getPrefix();
  74.             $data $this->baseInvoiceReservation($id$type$number$prefix$date);
  75.             $token $data['token'];
  76.         }else{
  77.             return $this->redirectToRoute('reservations_generate_proforma',
  78.                 array(
  79.                     'id' => $id
  80.                 )
  81.             );
  82.         }
  83.         $idLounges = array();
  84.         $loungesBoolToInvoice = array();
  85.         if (array_key_exists('lounge',$data['datasupplier'])) {
  86.             foreach ($data['datasupplier']['lounge'] as $item) {
  87.                 $idLounges[] = $item['id'];
  88.                 $loungesBoolToInvoice[] = 1;
  89.             }
  90.             $idLounges implode(','$idLounges);
  91.             $loungesBoolToInvoice implode(','$loungesBoolToInvoice);
  92.         } else {
  93.             $idLounges '0';
  94.             $loungesBoolToInvoice '0';
  95.         }
  96.         $idPayments = array();
  97.         $paymentsBoolToInvoice = array();
  98.         if (array_key_exists('payment',$data['datasupplier'])) {
  99.             foreach ($data['datasupplier']['payment'] as $item) {
  100.                 $idPayments[] = $item['id'];
  101.                 $paymentsBoolToInvoice[] = 1;
  102.             }
  103.             $idPayments implode(','$idPayments);
  104.             $paymentsBoolToInvoice implode(','$paymentsBoolToInvoice);
  105.             // Se han generado dos arreglos, cada uno dividido en 2 strings
  106.             // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
  107.             // Para manipularlos entre la vista y el JS
  108.         } else {
  109.             $idPayments '0';
  110.             $paymentsBoolToInvoice '0';
  111.         }
  112.         /* Obtengo usuario logueado */
  113.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  114.         $user_id $user_logueado->getId();
  115.         //INICIO: Facturas de deposito
  116.         $allInvoiceDeposit = array();
  117. //        $allInvoiceDepositControl = $em->getRepository(ReservationInvoiceDepositControl::class)->findByReservationId($id);
  118. //        foreach($allInvoiceDepositControl as $control){
  119. //
  120. //            $items = $em->getRepository(ReservationInvoiceDepositItems::class)->findByControlId($control->getId());
  121. //
  122. //            foreach ($items as $item){
  123. //                $allInvoiceDeposit[$control->getId()] = array(
  124. //                    'controlId' => $control->getId(),
  125. //                    'dateAt' => $control->getDateAt(),
  126. //                    'itemId' => $item->getId(),
  127. //                    'name' => $item->getName(),
  128. //                    'amount' => $item->getAmount(),
  129. //                    'iva' => $item->getIva(),
  130. //                    'reservationId' => $item->getReservationId()
  131. //                );
  132. //            }
  133. //        }
  134.         $items $em->getRepository(ReservationProformaDeposit::class)->findByReservationId($id);
  135.         foreach ($items as $item){
  136.             $allInvoiceDeposit[$item->getId()] = array(
  137. //                'controlId' => $control->getId(),
  138. //                'dateAt' => $control->getDateAt(),
  139.                 'itemId' => $item->getId(),
  140.                 'name' => $item->getName(),
  141.                 'amount' => $item->getAmount(),
  142.                 'iva' => $item->getIva(),
  143.                 'reservationId' => $item->getReservationId(),
  144.                 'total' => $item->getTotal()
  145.             );
  146.         }
  147.         //FIN: Facturas de deposito
  148.         return $this->render('MDS/GreenPatioBundle/reservations/services-proforma-reservation.html.twig',
  149.             array(
  150.                 'id' => $id,
  151.                 'idLounges' => $idLounges,
  152.                 'reserva' => $reserva,
  153.                 'idPayments' => $idPayments,
  154.                 'loungesBoolToInvoice' => $loungesBoolToInvoice,
  155.                 'paymentsBoolToInvoice' => $paymentsBoolToInvoice,
  156.                 'type' => $data['type'],
  157.                 'number' => $data['number'],
  158.                 'prefix' => $data['prefix'],
  159.                 'date' => $data['date'],
  160.                 'token' => $token,
  161.                 'company' => $data['company'],
  162.                 'clients' => $data['clients'],
  163.                 'datasupplier' => $data['datasupplier'],
  164.                 'currency' => $data['currency'],
  165.                 'totales_neto' => $data['totales_neto'],
  166.                 'bases_imponibles' => $data['bases_imponibles'],
  167.                 'totales' => $data['totales'],
  168.                 'balance' => $data['balance'],
  169.                 'paymentInvoice' => $data['paymentInvoice'],
  170.                 'payments' => $payments,
  171.                 'allInvoiceDeposit' => $allInvoiceDeposit,
  172.                 'user_id' => $user_id,
  173.                 'form' => $form->createView(),
  174.                 'form1' => $form1->createView(),
  175.             )
  176.         );
  177.     }
  178.     private function createReservationInvoiceProformaForm(ReservationInvoice $entity)
  179.     {
  180.         $form $this->createForm(ReservationInvoiceType::class, $entity, array(
  181.             'action' => $this->generateUrl('reservation_proforma_invoice_pdf_print_action'),
  182.             'method' => 'POST'
  183.         ));
  184.         return $form;
  185.     }
  186.     private function createReservationPaymentsClientForm(ReservationPaymentsClient $entity)
  187.     {
  188.         $form $this->createForm(ReservationPaymentsClientType::class, $entity, array(
  189.             'action' => $this->generateUrl('reservation_payments_client_add'),
  190.             'method' => 'POST'
  191. //            'method' => 'PUT'
  192.         ));
  193.         return $form;
  194.     }
  195.     /**
  196.      * @Route("/payment/delete/{id}",  name="reservations_payment_delete")
  197.      */
  198.     public function deleteReservationPaymentAction($idRequest $request)
  199.     {
  200.         $em $this->getDoctrine()->getManager();
  201.         $payment $em->getRepository(ReservationPaymentsClient::class)->findOneById($id);
  202.         $reservationId $payment->getReservationId();
  203.         $em->remove($payment);
  204.         $em->flush();
  205.         return $this->redirectToRoute('reservations_payment',
  206.             array(
  207.                 'id' =>$reservationId
  208.             )
  209.         );
  210.     }
  211.     /**
  212.      * @Route("/reservations/payments", name="reservation_payments_client_add")
  213.      */
  214.     public function createAction(Request $request)
  215.     {
  216.         $paymentsClient = new ReservationPaymentsClient();
  217.         $form $this->createReservationPaymentsClientForm($paymentsClient);
  218.         $form->handleRequest($request);
  219.         // INICIO: Si la reserva esta facturada no puede ser modificada, no se pueden agregar pagos
  220.         $em $this->getDoctrine()->getManager();
  221.         $tempoReserva $em->getRepository(Reservation::class)->findOneById($paymentsClient->getReservationId());
  222.         if ($tempoReserva->getStatus() == 'Invoiced'){
  223.             return $this->redirectToRoute('reservations_payment',
  224.                 array('id' => $paymentsClient->getReservationId()));
  225.         }
  226.         // FIN: Si la reserva esta facturada no puede ser modificada, no se pueden agregar pagos
  227.         if($form->isValid())
  228.         {
  229.             $em $this->getDoctrine()->getManager();
  230.             /* Obtengo usuario logueado */
  231.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  232.             $user_id $user_logueado->getId();
  233.             $paymentsClient->setCreatedAt(new \DateTime('now'));
  234.             $paymentsClient->setCreatedId($user_id);
  235.             $paymentsClient->setUpdatedId($user_id);
  236.             $paymentsClient->setUpdatedAt(new \DateTime('now'));
  237.             /* Gestión de eventos en Log */
  238.             $user_lastname $user_logueado->getLastname();
  239.             $user_name $user_logueado->getName();
  240.             $user_email $user_logueado->getEmail();
  241.             $user_rol $user_logueado->getRoles();
  242.             $event_url $request->getPathInfo();
  243.             $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  244.             $em->persist($paymentsClient);
  245.             $em->flush();
  246.             $event 'the payment was registered';
  247.             $successMessage $this->translator->trans($event);
  248.             $this->addFlash('mensajepaymentsclient'$successMessage);
  249.             $tempoReserva->setStatus('Confirmed');
  250.             $em->persist($tempoReserva);
  251.             $em->flush();
  252.             return $this->redirectToRoute('reservations_payment',
  253.                 array(
  254.                     'id' => $paymentsClient->getReservationId()
  255.                 )
  256.             );
  257.         }else{
  258.             $errorMessage $this->translator->trans('Error, some fields are empty');
  259.             $this->addFlash('mensajepaymentsclienterror'$errorMessage);
  260.         }
  261.         return $this->redirectToRoute('reservations_payment',
  262.             array(
  263.                 'id' => $paymentsClient->getReservationId()
  264.             )
  265.         );
  266.     }
  267.     /**
  268.      * @Route("/reservations/proforma/invoice/pdf/print/action", name="reservation_proforma_invoice_pdf_print_action")
  269.      */
  270.     public function createProformaInvoicePdfPrintAction(Request $request)
  271.     {
  272. //        d('llegue', $request);
  273.         $array $request->request->get('mds_greenpatiobundle_reservationsinvoice');
  274. //        d(
  275. //            array_keys($array)[0]
  276. //
  277. //        );
  278. //        d($request->request->get('mds_greenpatiobundle_reservationsinvoice'));
  279. //
  280. //        exit();
  281.         $paymentsClient = new ReservationPaymentsClient();
  282.         $form $this->createReservationPaymentsClientForm($paymentsClient);
  283.         $form->handleRequest($request);
  284.         if($form->isValid())
  285.         {
  286.             $em $this->getDoctrine()->getManager();
  287.             /* Obtengo usuario logueado */
  288.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  289.             $user_id $user_logueado->getId();
  290.             $paymentsClient->setCreatedAt(new \DateTime('now'));
  291.             $paymentsClient->setCreatedId($user_id);
  292.             $paymentsClient->setUpdatedId($user_id);
  293.             $paymentsClient->setUpdatedAt(new \DateTime('now'));
  294.             /* Gestión de eventos en Log */
  295.             $user_lastname $user_logueado->getLastname();
  296.             $user_name $user_logueado->getName();
  297.             $user_email $user_logueado->getEmail();
  298.             $user_rol $user_logueado->getRoles();
  299.             $event_url $request->getPathInfo();
  300.             $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  301.             $em->persist($paymentsClient);
  302.             $em->flush();
  303.             $event 'the payment was registered';
  304.             $successMessage $this->translator->trans($event);
  305.             $this->addFlash('mensajepaymentsclient'$successMessage);
  306.             return $this->redirectToRoute('reservations_payment',
  307.                 array(
  308.                     'id' => $paymentsClient->getReservationId()
  309.                 )
  310.             );
  311.         }else{
  312.             $errorMessage $this->translator->trans('Error, some fields are empty');
  313.             $this->addFlash('mensajepaymentsclienterror'$errorMessage);
  314.         }
  315.         return $this->redirectToRoute('reservations_payment',
  316.             array(
  317.                 'id' => $paymentsClient->getReservationId()
  318.             )
  319.         );
  320.     }
  321.     /**
  322.      * @Route("/reservations/generate/proforma/{id}",  name="reservations_generate_proforma")
  323.      */
  324.     public function generateProformaAction($idRequest $request)
  325.     {
  326.         $em $this->getDoctrine()->getManager();
  327.         $proforma $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  328.         $prefix "GP-".date('dmy')."-";
  329.         if (is_null($proforma)){
  330.             $proforma_new = new ReservationProforma();
  331.             $proforma_new->setReservationId($id);
  332.             $proforma_new->setPrefix($prefix);
  333.             $proforma_new->setDateAt(new \DateTime("now"));
  334.             // En items, se ponen todas las salas y pagos de esa reserva
  335.             $lounges $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
  336.             $payments $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
  337.             $services $em->getRepository(ReservationService::class)->findByReservationId($id);
  338.             $items '';
  339.             if (!empty($lounges)) {
  340.                 foreach ($lounges as $item) {
  341.                     if ($items == ''){
  342.                         $items 'L' $item->getId();  // L## para lounges
  343.                     } else {
  344.                         $items $items ',' 'L' $item->getId();  // L## para lounges
  345.                     }
  346.                 }
  347.             }
  348.             if (!empty($payments)) {
  349.                 foreach ($payments as $item) {
  350.                     if ($items == ''){
  351.                         $items 'P' $item->getId();  // P## para payments
  352.                     } else {
  353.                         $items $items ',' 'P' $item->getId();  // P## para payments
  354.                     }
  355.                 }
  356.             }
  357.             if (!empty($services)) {
  358.                 foreach ($services as $item) {
  359.                     if ($items == ''){
  360.                         $items 'S' $item->getId();  // S## para services
  361.                     } else {
  362.                         $items $items ',' 'S' $item->getId();  // S## para services
  363.                     }
  364.                 }
  365.             }
  366.             $proforma_new->setItems($items);
  367.             /* Obtengo usuario logueado */
  368.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  369.             $user_id $user_logueado->getId();
  370.             $proforma_new->setCreatedId($user_id);
  371.             $proforma_new->setUpdatedId($user_id);
  372.             $proforma_new->setCreatedAt(new \DateTime("now"));
  373.             $proforma_new->setUpdatedAt(new \DateTime("now"));
  374.             //Access Key para entrar en la proforma
  375.             $accessKey md5('CR-JDEF'rand() * time());
  376.             $proforma_new->setAccessKey($accessKey);
  377.             $em->persist($proforma_new);
  378.             $em->flush();
  379.         }
  380.         return $this->redirectToRoute('reservations_payment',
  381.             array(
  382.                 'id' => $id
  383.             )
  384.         );
  385.     }
  386.     private function baseInvoiceReservation($id$type$number$prefix$date)
  387.     {
  388.         $em $this->getDoctrine()->getManager();
  389.         $reservation $em->getRepository(Reservation::class)->findOneById($id);
  390.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  391.         $client $em->getRepository(Client::class)->findById($reservation->getClient());
  392.         if (!empty($client)){
  393.             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  394.             $client[0]->setPopulation($city);
  395.             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  396.             $client[0]->setRegion($region);
  397.             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  398.             $client[0]->setCountry($country);
  399.             $client['city'] = $city;
  400.             $client['region'] = $region;
  401.             $client['country'] = $country;
  402.         } else {
  403.             $client[0] = new Client();
  404.             $client[0]->setName('');
  405.             $client[0]->setTitle('');
  406.             $client[0]->setIdDocument('');
  407.             $client[0]->setPopulation('');
  408.             $client[0]->setRegion('');
  409.             $client[0]->setCountry('');
  410.         }
  411.         // Acumuladores de los calculos
  412.         $totales_neto_all 0;
  413.         $data_iva = array(
  414.             'iva' => 21,
  415.             'ivaMontoVeintiUno' => 0,
  416.             'ivaMontoDiez' => 0,
  417.             'ivaMontoCero' => 0,
  418.         );
  419.         // Buscamos las salas reservadas, pagos y servicios para el evento
  420.         $reservationLounges $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
  421.         $payments $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
  422.         $services $em->getRepository(ReservationService::class)->findBy(['reservationId' => $id'toinvoice' => 1]);
  423.         $data_supplier = array();
  424.         $i 0;
  425.         $iva '21';            // Esteban Rincon: "Por Ley de localización del impuesto, siempre será un 21%". Si tiene un Iva se sustituirá. Modificación en la ley.
  426.         $pax '-';
  427.         $qty '1';
  428.         $lounge = array(
  429.             'neto' => 0,
  430.             'sumSubT' => 0,
  431.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  432.         $service = array(
  433.             'neto' => 0,
  434.             'sumSubT' => 0,
  435.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  436.         foreach ($reservationLounges as $item){
  437.             // Verificamos que el salon no se encuentre ya en una factura
  438.             $existe $em->getRepository(ReservationInvoiceItems::class)->findByLngControlId($item->getId());
  439.             $existeCvr $em->getRepository(CvrReservationInvoiceItems::class)->findByLngControlId($item->getId());
  440.             $existe = (!empty($existe) or !empty($existeCvr));
  441.             if (is_null($item->getServicePrice()) or empty($item->getServicePrice()) or !empty($existe)){
  442.                 $subtotal 0;
  443.                 $neto 0;
  444.                 $subneto 0;
  445.                 $subtotalLounge 0;
  446.             } else {
  447.                 $iva = ($item->getIva() === null || $item->getIva() === '') ? 21 $item->getIva();
  448.                 $subtotalLounge = ($item->getServicePrice() * (+ ($iva 100)));
  449.                 $subneto $item->getServicePrice();
  450.                 $subtotal =  $subtotalLounge;
  451.                 $neto =  $subneto;
  452.                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  453.                 $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  454.                 $neto round($neto,2,PHP_ROUND_HALF_UP);
  455.             }
  456.             // Acumula netos totales e IVA
  457.             $totales_neto_all $totales_neto_all $neto;
  458.             switch ($iva){
  459.                 case 21$data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto 0.21); break;
  460.                 case 10$data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto 0.1); break;
  461.                 case 0: break;
  462.                 default: $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto 0.21); break;
  463.             }
  464.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  465.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  466.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  467.             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
  468.             // Acumula netos totales e IVA
  469.             $lounge['neto'] = $lounge['neto'] + $neto;
  470.             $lounge['sumSubT'] = $lounge['sumSubT'] + $subtotal;
  471.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  472.             $lounge['neto'] = round($lounge['neto'],2,PHP_ROUND_HALF_UP);
  473.             $lounge['sumSubT'] = round($lounge['sumSubT'],2,PHP_ROUND_HALF_UP);
  474.             $data_supplier['lounge'][$i] = array (
  475.                 'id' => $item->getId(),
  476.                 'loungeName' => $item->getLoungeName(),
  477.                 'idLounge' => $item->getIdLounge(),
  478.                 'dateStart' => $item->getDateStart(),
  479.                 'dateEnd' => $item->getDateEnd(),
  480.                 'servicePrice' => $item->getServicePrice(),
  481.                 'subtotalLounge' => $subtotalLounge,
  482.                 'iva' => $iva,
  483.                 'pax' => $pax,
  484.                 'qty' => $qty,
  485.                 'type' => $item->getType(),
  486.                 'subtotal' => $subtotal,
  487.             );
  488.             $i++;
  489.         }
  490.         $data_supplier['loungeSubTotal'] = array(
  491.             'neto' => $lounge['neto'],
  492.             'sumSubT' => $lounge['sumSubT'],
  493.         );
  494.         $payment = array(
  495.             'neto' => 0,
  496.             'sumSubT' => 0,
  497.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  498.         $i 0;
  499.         foreach ($payments as $item){
  500.             // Verificamos que el pago no se encuentre ya en una factura
  501.             $existe $em->getRepository(ReservationInvoiceItems::class)->findByPayControlId($item->getId());
  502.             $existeCvr $em->getRepository(CvrReservationInvoiceItems::class)->findByPayControlId($item->getId());
  503.             $existe = (!empty($existe) or !empty($existeCvr));
  504.             // Por indicaciones de Esteban Rincon, no deseamos estos conceptos en las facturas
  505.             if (!($item->getWayToPay() == 'TRANSFERENCIA') and !($item->getWayToPay() == 'VISA') and !($item->getWayToPay() == 'AMEX') and !($item->getWayToPay() == 'CHEQUE') and !($item->getWayToPay() == 'EFECTIVO')) {
  506.                 if (!empty($existe)) {
  507.                     $payment['sumSubT'] = $payment['sumSubT'] + 0;
  508.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  509.                     $payment['sumSubT'] = round($payment['sumSubT'], 2PHP_ROUND_HALF_UP);
  510.                 } else {
  511.                     $subtotalLounge $item->getAmountTotal() * (-1);
  512.                     $subneto $item->getAmount() * (-1);
  513.                     $subtotal $subtotalLounge;
  514.                     $neto $subneto;
  515.                     $payment['sumSubT'] = $payment['sumSubT'] - $item->getAmountTotal();
  516.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  517.                     $payment['sumSubT'] = round($payment['sumSubT'], 2PHP_ROUND_HALF_UP);
  518.                     // Acumula netos totales e IVA
  519.                     $ivaPayment $item->getVat();
  520.                     if (empty($item->getVat()) && !is_numeric($item->getVat())) {
  521.                         $ivaPayment 21;
  522.                     }
  523.                     $totales_neto_all $totales_neto_all $neto;
  524.                     $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($ivaPayment 100));
  525.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  526.                     $totales_neto_all round($totales_neto_all2PHP_ROUND_HALF_UP);
  527.                     $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'], 2PHP_ROUND_HALF_UP);
  528.                     // Acumula netos totales e IVA
  529.                 }
  530.                 $data_supplier['payment'][$i] = array(
  531.                     'id' => $item->getId(),
  532.                     'amount' => $item->getAmount() * (-1),
  533.                     'datePayAt' => $item->getDatePayAt(),
  534.                     'wayToPay' => $item->getWayToPay(),
  535.                     'amountTotal' => $item->getAmountTotal() * (-1),
  536.                     'vat' => $item->getVat(),
  537.                 );
  538.                 $i++;
  539.             }
  540.         }
  541.         if (!empty($payments)) {
  542.             $data_supplier['paymentSubTotal'] = array(
  543.                 'neto' => $payment['neto'],
  544.                 'sumSubT' => $payment['sumSubT'],
  545.             );
  546.         }
  547.         // Mapeo de serviceCatId a serviceType
  548.         $serviceTypes = [
  549.             => 'Hotel',
  550.             => 'Actividad',
  551.             => 'AV',
  552.             => 'Creativo',
  553.             => 'Crucero',
  554.             => 'Entretenimiento',
  555.             => 'Regalos',
  556.             => 'Guía',
  557.             => 'Itinerarios',
  558.             11 => 'Catering',
  559.             12 => 'Otros',
  560.             13 => 'Transporte',
  561.             14 => 'Tecnología',
  562.             15 => 'Asistente',
  563.             16 => 'DDR',
  564.             17 => 'Seguridad',
  565.             18 => 'WiFi',
  566.             19 => 'Mobiliario',
  567.             20 => 'Parking',
  568.             21 => 'Limpieza',
  569.             // Agrega más mapeos según sea necesario
  570.         ];
  571.         $i 0;
  572.         foreach ($services as $item) {
  573.             // Verificar si el servicio ya existe en una factura
  574.             $existe = !empty($em->getRepository(ReservationInvoiceItems::class)->findBySrvControlId($item->getId())) ||
  575.                     !empty($em->getRepository(CvrReservationInvoiceItems::class)->findBySrvControlId($item->getId()));
  576.             // Inicializar variables comunes
  577.             $pax max(1, (int)$item->getPax());
  578.             $unitsServ max(1, (int)$item->getUnits());
  579.             $dateIn $item->getDateInAt();
  580.             $dateOut $item->getDateOutAt();
  581.             $days = ($item->getServiceCatId() == 5) ? $dateIn->diff($dateOut)->days : ($dateIn->diff($dateOut)->days 1);
  582.             $dateServ = ($days 1) ? $dateIn->format('d/m/Y') . ' - ' $dateOut->format('d/m/Y') : $dateIn->format('d/m/Y');
  583.             // Obtener el tipo de servicio
  584.             $serviceCatId $item->getServiceCatId();
  585.             $serviceType = isset($serviceTypes[$serviceCatId]) ? $serviceTypes[$serviceCatId] : 'Otros';
  586.             // Determinar si se usa precio del item o se calcula
  587.             if (is_null($item->getPrice()) || empty($item->getPrice()) || $existe) {
  588.                 $subtotalService 0;
  589.                 $subneto 0;
  590.                 if ($serviceCatId == 1) { // Alojamiento
  591.                     $numNoches $dateIn->diff($dateOut)->days;
  592.                     $subtotalService $subtotalService $numNoches $unitsServ;
  593.                     $subnetoUnit $subneto;
  594.                     $subneto $subneto $numNoches $unitsServ;
  595.                 } else {
  596.                     // Para otras categorías, se asume la misma lógica base
  597.                     $subtotalService 0;
  598.                     $subneto 0;
  599.                 }
  600.                 // Configurar datos del proveedor
  601.                 $data_supplier['service'][$i] = [
  602.                     'id' => $item->getId(),
  603.                     'serviceCatId' => $serviceCatId,
  604.                     'serviceName' => $item->getName(),
  605.                     'serviceType' => $serviceType,
  606.                     'date' => $dateServ,
  607.                     'qty' => $unitsServ,
  608.                     'iva' => $item->getIva(),
  609.                     'pax' => ($serviceCatId == 1) ? '-' $pax,
  610.                     'precioUnit' => isset($subnetoUnit) ? $subnetoUnit 0,
  611.                     'subneto' => $subneto,
  612.                     'subtotal' => $subtotalService,
  613.                 ];
  614.             } else {
  615.                 // Calcular subtotalService y subneto basado en el precio del item
  616.                 $subtotalService = (float)$item->getPrice();
  617.                 $subneto = (float)$item->getPrice();
  618.                 // Aplicar comisión
  619.                 $comTemp $item->getCommission();
  620.                 if ($item->getOpCommission() == '1') {
  621.                     $subtotalService *= (+ ((float)($comTemp) / 100));
  622.                     $subneto *= (+ ((float)($comTemp) / 100));
  623.                 } else {
  624.                     $subtotalService *= (- ((float)($comTemp) / 100));
  625.                     $subneto *= (- ((float)($comTemp) / 100));
  626.                 }
  627.                 // Calcular subtotal y subneto según la categoría de servicio
  628.                 switch ($serviceCatId) {
  629.                     case 1// Alojamiento
  630.                         $numNoches $dateIn->diff($dateOut)->days;
  631.                         $subtotalService *= $numNoches $unitsServ;
  632.                         $subnetoUnit $subneto;
  633.                         $subneto *= $numNoches $unitsServ;
  634.                         break;
  635.                     case 2// Actividades
  636.                         $subtotalService *= $days $unitsServ;
  637.                         $subnetoUnit $subneto;
  638.                         $subneto *= $days $unitsServ;
  639.                         break;
  640.                     // Agrega más casos según las necesidades específicas de cada categoría
  641.                     default:
  642.                         $subtotalService *= $days $unitsServ $pax;
  643.                         $subnetoUnit $subneto;
  644.                         $subneto *= $days $unitsServ $pax;
  645.                         break;
  646.                 }
  647.                 // Actualizar datos del proveedor
  648.                 $data_supplier['service'][$i] = [
  649.                     'id' => $item->getId(),
  650.                     'serviceCatId' => $serviceCatId,
  651.                     'serviceName' => $item->getName(),
  652.                     'serviceType' => $serviceType,
  653.                     'date' => $dateServ,
  654.                     'qty' => $unitsServ,
  655.                     'iva' => $item->getIva(),
  656.                     'pax' => ($serviceCatId == 1) ? '-' $pax,
  657.                     'precioUnit' => $subnetoUnit ?? 0,
  658.                     'subneto' => $subneto,
  659.                     'subtotal' => $subtotalService,
  660.                 ];
  661.                 // Manejar Over
  662.                 if ($item->getOpOver() == '1') {
  663.                     $subtotalService += $item->getOver();
  664.                     $subneto += $item->getOver();
  665.                 } else {
  666.                     $subtotalService -= $item->getOver();
  667.                     $subneto -= $item->getOver();
  668.                 }
  669.                 // Aplicar IVA
  670.                 if ($item->getOpIva() == '1') {
  671.                     $subtotalService *= (+ ($item->getIva() / 100));
  672.                 } else {
  673.                     $subtotalService = ($item->getPrice() * 100) / (100 $item->getIva());
  674.                     $subneto = ($subneto 100) / (100 $item->getIva());
  675.                 }
  676.                 // Actualizar subtotal y subneto en data_supplier
  677.                 $data_supplier['service'][$i]['subneto'] = $subneto;
  678.                 $data_supplier['service'][$i]['subtotal'] = $subtotalService;
  679.                 // Acumular subtotales
  680.                 $subtotal round($subtotalService2PHP_ROUND_HALF_UP);
  681.                 $neto round($subneto2PHP_ROUND_HALF_UP);
  682.             }
  683.             // Acumular IVA
  684.             switch ($item->getIva()) {
  685.                 case 21:
  686.                     $data_iva['ivaMontoVeintiUno'] += ($neto 0.21);
  687.                     break;
  688.                 case 10:
  689.                     $data_iva['ivaMontoDiez'] += ($neto 0.10);
  690.                     break;
  691.                 case 0:
  692.                     // No se acumula IVA
  693.                     break;
  694.                 default:
  695.                     $data_iva['ivaMontoVeintiUno'] += ($neto * ($item->getIva() / 100));
  696.                     break;
  697.             }
  698.             // Acumular totales netos
  699.             $totales_neto_all += $neto;
  700.             $totales_neto_all round($totales_neto_all2PHP_ROUND_HALF_UP);
  701.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'], 2PHP_ROUND_HALF_UP);
  702.             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'], 2PHP_ROUND_HALF_UP);
  703.             // Acumular en la estructura de servicios
  704.             $service['neto'] = round(($service['neto'] ?? 0) + $neto2PHP_ROUND_HALF_UP);
  705.             $service['sumSubT'] = round(($service['sumSubT'] ?? 0) + $subtotal2PHP_ROUND_HALF_UP);
  706.             $i++;
  707.         }
  708.         $data_supplier['serviceSubTotal'] = array(
  709.             'neto' => $service['neto'],
  710.             'sumSubT' => $service['sumSubT'],
  711.         );
  712.         $currency '€';
  713.         $totales_total $totales_neto_all $data_iva['ivaMontoVeintiUno'] + $data_iva['ivaMontoDiez'];
  714.         if (!empty($payments)) {
  715.             $amount_pay $data_supplier['paymentSubTotal']['sumSubT'];
  716.         } else {
  717.             $amount_pay 0;
  718.         }
  719.         $totales_all $totales_total $amount_pay;
  720.         $data = array(
  721.             'id' => $id,
  722.             'type' => $type,
  723.             'number' => $number,
  724.             'prefix' => $prefix,
  725.             'date' => $date,
  726.             'reservation' => $reservation,
  727.             'token' => $reservation->getAccessKey(),
  728.             'company' => $company,
  729.             'clients' => $client,
  730.             'datasupplier' => $data_supplier,
  731.             'currency' => $currency,
  732.             'totales_neto' => $totales_neto_all,
  733.             'bases_imponibles' => $data_iva,
  734.             'totales' => $totales_total,
  735.             'balance' => $totales_all,
  736.             'paymentInvoice' => $amount_pay,
  737.         );
  738.         return $data;
  739.     }
  740.     /**
  741.      * @Route("/reservations/invoice/proforma/print/{id}",  name="reservations_invoice_proforma_print")
  742.      */
  743.     public function detailsProformaPrintAction($idRequest $request)
  744.     {
  745.         $data = array();
  746.         $em $this->getDoctrine()->getManager();
  747.         $proforma $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  748.         if (!empty($proforma)){
  749.             $type 'Proforma';
  750.             $number $proforma->getId();
  751.             $date $proforma->getDateAt();
  752.             $prefix $proforma->getPrefix();
  753.             $data $this->baseInvoiceReservation($id$type$number$prefix$date);
  754.             $token $data['token'];
  755.         }else{
  756.             return $this->redirectToRoute('reservations_generate_proforma',
  757.                 array(
  758.                     'id' => $id
  759.                 )
  760.             );
  761.         }
  762.         return $this->render('MDS/GreenPatioBundle/reservations/services-proforma-print-reservation.html.twig',
  763.             array(
  764.                 'id' => $id,
  765.                 'type' => $data['type'],
  766.                 'number' => $data['number'],
  767.                 'prefix' => $data['prefix'],
  768.                 'date' => $data['date'],
  769.                 'token' => $token,
  770.                 'company' => $data['company'],
  771.                 'clients' => $data['clients'],
  772.                 'datasupplier' => $data['datasupplier'],
  773.                 'totales_neto' => $data['totales_neto'],
  774.                 'bases_imponibles' => $data['bases_imponibles'],
  775.                 'totales' => $data['totales'],
  776.                 'balance' => $data['balance'],
  777.                 'currency' => $data['currency'],
  778.                 'paymentInvoice' => $data['paymentInvoice']
  779.             )
  780.         );
  781.     }
  782.     /**
  783.      * @Route("/invoice/{id}",  name="reservations_invoice")
  784.      */
  785.     public function detailsReservationInvoiceAction($idRequest $request)
  786.     {
  787.         $em $this->getDoctrine()->getManager();
  788.         $payments $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
  789. ////        $services = $em->getRepository(ReservationService::class)->findByReservationId($id);     // ********************************************** PENDIENTE POR PROGRAMAR EL CALCULO DE CADA TIPO DE SERVICIO PARA LA FACTURA **********************************************
  790. //        $invoice = $em->getRepository(ReservationInvoice::class)->findOneByReservationId($id);
  791.         $invoice $em->getRepository(ReservationInvoice::class)->findOneBy(
  792.             array(
  793.                 'reservationId' => $id,
  794.                 'master' => 'master',
  795.             )
  796.         );
  797.         $reservaInv = new ReservationInvoice();
  798.         $reservaInv->setReservationId($id);
  799.         $form1 $this->createReservationInvoiceProformaForm($reservaInv);
  800.         if (!empty($invoice)){
  801.             $type 'Invoice';
  802.             $number $invoice->getId();
  803.             $date $invoice->getDateAt();
  804.             $prefix $invoice->getPrefix();
  805.             $data $this->baseInvoiceReservation($id$type$number$prefix$date);
  806.             $token $data['token'];
  807.         }else{
  808.             // No hay factura creada se debe enviar a proforma, si es un ADMIN podra generar la factura. Tal vez sea necesario poner un mensaje indicando que no hay factura generada aun
  809.             return $this->redirectToRoute('reservations_generate_proforma',
  810.                 array(
  811.                     'id' => $id
  812.                 )
  813.             );
  814.         }
  815.         $idLounges = array();
  816.         $loungesBoolToInvoice = array();
  817.         if (array_key_exists('lounge',$data['datasupplier'])) {
  818.             foreach ($data['datasupplier']['lounge'] as $item) {
  819.                 $idLounges[] = $item['id'];
  820.                 $loungesBoolToInvoice[] = 1;
  821.             }
  822.             $idLounges implode(','$idLounges);
  823.             $loungesBoolToInvoice implode(','$loungesBoolToInvoice);
  824.         } else {
  825.             $idLounges '0';
  826.             $loungesBoolToInvoice '0';
  827.         }
  828.         $idPayments = array();
  829.         $paymentsBoolToInvoice = array();
  830.         if (array_key_exists('payment',$data['datasupplier'])) {
  831.             foreach ($data['datasupplier']['payment'] as $item) {
  832.                 $idPayments[] = $item['id'];
  833.                 $paymentsBoolToInvoice[] = 1;
  834.             }
  835.             $idPayments implode(','$idPayments);
  836.             $paymentsBoolToInvoice implode(','$paymentsBoolToInvoice);
  837.             // Se han generado dos arreglos, cada uno dividido en 2 strings
  838.             // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
  839.             // Para manipularlos entre la vista y el JS
  840.         } else {
  841.             $idPayments '';
  842.             $paymentsBoolToInvoice '';
  843.         }
  844.         return $this->render('MDS/GreenPatioBundle/reservations/services-invoice-reservation.html.twig',
  845.             array(
  846.                 'id' => $id,
  847.                 'idLounges' => $idLounges,
  848.                 'idPayments' => $idPayments,
  849.                 'loungesBoolToInvoice' => $loungesBoolToInvoice,
  850.                 'paymentsBoolToInvoice' => $paymentsBoolToInvoice,
  851.                 'type' => $data['type'],
  852.                 'number' => $data['number'],
  853.                 'prefix' => $data['prefix'],
  854.                 'date' => $data['date'],
  855.                 'token' => $token,
  856.                 'company' => $data['company'],
  857.                 'clients' => $data['clients'],
  858.                 'datasupplier' => $data['datasupplier'],
  859.                 'currency' => $data['currency'],
  860.                 'totales_neto' => $data['totales_neto'],
  861.                 'bases_imponibles' => $data['bases_imponibles'],
  862.                 'totales' => $data['totales'],
  863.                 'balance' => $data['balance'],
  864.                 'paymentInvoice' => $data['paymentInvoice'],
  865.                 'payments' => $payments,
  866.                 'form1' => $form1->createView(),
  867.                 'clientName' => $invoice->getClientName(),
  868.                 'clientAddress' => $invoice->getClientAddress(),
  869.                 'clientDocument' => $invoice->getClientDocument(),
  870.             )
  871.         );
  872.     }
  873.     /**
  874.      * @Route("/reservations/invoice/print/{id}",  name="reservations_invoice_print")
  875.      */
  876.     public function detailsInvoicePrintAction($idRequest $request)
  877.     {
  878.         $data = array();
  879.         $em $this->getDoctrine()->getManager();
  880.         $invoice $em->getRepository(ReservationInvoice::class)->findOneByReservationId($id);
  881.         if (!empty($invoice)){
  882.             $type 'Invoice';
  883.             $number $invoice->getId();
  884.             $date $invoice->getDateAt();
  885.             $prefix $invoice->getPrefix();
  886.             $data $this->baseInvoiceReservation($id$type$number$prefix$date);
  887.             $token $data['token'];
  888.         }else{
  889.             return $this->redirectToRoute('reservations_generate_invoice',
  890.                 array(
  891.                     'id' => $id
  892.                 )
  893.             );
  894.         }
  895.         return $this->render('MDS/GreenPatioBundle/reservations/services-invoice-print-reservation.html.twig',
  896.             array(
  897.                 'id' => $id,
  898.                 'type' => $data['type'],
  899.                 'number' => $data['number'],
  900.                 'prefix' => $data['prefix'],
  901.                 'date' => $data['date'],
  902.                 'token' => $token,
  903.                 'company' => $data['company'],
  904.                 'clients' => $data['clients'],
  905.                 'datasupplier' => $data['datasupplier'],
  906.                 'totales_neto' => $data['totales_neto'],
  907.                 'bases_imponibles' => $data['bases_imponibles'],
  908.                 'totales' => $data['totales'],
  909.                 'balance' => $data['balance'],
  910.                 'currency' => $data['currency'],
  911.                 'paymentInvoice' => $data['paymentInvoice']
  912.             )
  913.         );
  914.     }
  915.     /**
  916.      * @Route("/invoice/generate/{id}",  name="reservations_generate_invoice")
  917.      */
  918.     public function generateInvoiceAction($idRequest $request)
  919.     {
  920.         $em $this->getDoctrine()->getManager();
  921.         $invoiceGenerate $request->request->get('invoiceGenerate');
  922.         $invoice $em->getRepository(ReservationInvoice::class)->findOneBy(
  923.             array(
  924.                 'reservationId' => $id,
  925.                 'master' => 'master',
  926.             )
  927.         );
  928.         if (is_null($invoice)){
  929.             $reserva $em->getRepository(Reservation::class)->findOneById($id);
  930.             $pagos $em->getRepository(ReservationPaymentsClient::class)->findOneByReservationId($id);
  931.             $servicios $em->getRepository(ReservationService::class)->findOneByReservationId($id);
  932.             $salas $em->getRepository(ReservationLounge::class)->findOneByIdReservation($id);
  933. //
  934. //  Aqui se deberia verificar que pagos, salas o servicios, al menos uno sea distinto de null. En caso contrario no hay nada que facturar
  935. //            if (empty($pagos) and empty($servicios) and empty($salas)){
  936. //                d('factura vacia');
  937. //            }
  938. //
  939. //
  940. //
  941. //
  942.             $reserva->setStatus('Invoiced');
  943.             $em->persist($reserva);
  944.             $em->flush();
  945.             $invoice_new = new ReservationInvoice();
  946.             $invoice_new->setNumber('GPF-'.date('d').date('m').substr(date('Y'),-2).'-'.$id);           //GreenPatioFactura - dia mes año idReserva
  947.             $invoice_new->setDateAt(new \DateTime());
  948.             $invoice_new->setType($invoiceGenerate['type']);
  949.             $invoice_new->setReservationId($invoiceGenerate['id']);
  950.             $invoice_new->setReservationId($id);
  951.             $invoice_new->setPrefix('');
  952.             $invoice_new->setType('Invoice');
  953.             $proforma $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  954.             $type 'Invoice';
  955.             $number $proforma->getId();
  956.             $date $proforma->getDateAt();
  957.             $prefix $proforma->getPrefix();
  958.             $data $this->baseInvoiceReservation($id$type$number$prefix$date);
  959.             $em->clear();
  960.             $invoice_new->setTotal($data['totales']);
  961.             $invoice_new->setTotalNet($data['totales_neto']);
  962.             $invoice_new->setVat($data['totales'] - $data['totales_neto']);
  963.             /* Obtengo usuario logueado */
  964.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  965.             $user_id $user_logueado->getId();
  966.             $invoice_new->setCreatedId($user_id);
  967.             $invoice_new->setUpdatedId($user_id);
  968.             $invoice_new->setCreatedAt(new \DateTime());
  969.             $invoice_new->setUpdatedAt(new \DateTime());
  970.             // Guardamos los datos del cliente dentro de la factura
  971.             $typeClient $request->request->get('typeClient');
  972.             $typeClient = empty($typeClient) ? 'Client' $typeClient;
  973.             $idClient $request->request->get('idClient');
  974.             $idClient = empty($idClient) ? $reserva->getClient() : $idClient;
  975.             $invoice_new $this->clientDataToInvoice($invoice_new$typeClient$idClient$invoice_new->getReservationId());
  976.             $em->persist($invoice_new);
  977.             $em->flush();
  978.         }
  979.         return $this->redirectToRoute('reservations_invoice', array( 'id' => $id ));
  980.     }
  981.     /**
  982.      * @Route("/reservations/invoice/generatenew",  name="reservations_generatenew_invoice")
  983.      * Generar una nueva factura
  984.      */
  985.     public function generatenewInvoiceAction(Request $request)
  986.     {
  987.         $em $this->getDoctrine()->getManager();
  988.         // Se genera y muestra en nueva pantalla la nueva proforma
  989.         $arrayBools = array( 'lounge' => null'service' => null'payment' => null, );
  990.         $arrayBools['lounge'] = $request->request->get('inv_lounge_hidden_bool');
  991.         $arrayBools['service'] = $request->request->get('inv_service_hidden_bool');
  992.         $arrayBools['payment'] = $request->request->get('inv_payment_hidden_bool');
  993.         $clientName $request->request->get('clientName');
  994.         $clientAddress $request->request->get('clientAddress');
  995.         $clientDocument $request->request->get('clientDocument');
  996.         $clientType $request->request->get('clientType');
  997.         $id $request->request->get('inv_reservation_id');
  998.         // INICIO: Verificamos la linea de facturacion
  999.         $parameters = array( 'id' => $id, );
  1000.         $dql 'SELECT p
  1001.                 FROM GreenPatioBundle:ReservationLoungeSimple p
  1002.                 WHERE p.idReservation = :id AND p.idLounge > 21';
  1003.         $query $em->createQuery($dql)->setParameters($parameters);
  1004.         $loungesSimples $query->getResult();
  1005.         if (!empty($loungesSimples)){
  1006.             // Redirigir a Covarrubias
  1007.             return $this->redirectToRoute('reservations_generatenew_invoice_cvr',
  1008.                 array(
  1009.                     'id' => $id,
  1010.                     'lounge' => $arrayBools['lounge'],
  1011.                     'service' => $arrayBools['service'],
  1012.                     'payment' => $arrayBools['payment'],
  1013.                     'clientName' => $clientName,
  1014.                     'clientAddress' => $clientAddress,
  1015.                     'clientDocument' => $clientDocument,
  1016.                     'clientType' => $clientType
  1017.                 )
  1018.             );
  1019.         }
  1020.         // FIN: Verificamos la linea de facturacion
  1021.         //INICIO: buscamos el ID de la factura
  1022.         $allFacturas $em->getRepository(ReservationInvoice::class)->findAll();
  1023.         if (!empty($allFacturas)){
  1024.             $invoiceId end($allFacturas)->getId() + 1;
  1025.         } else {
  1026.             $invoiceId 1;
  1027.         }
  1028.         $boolMakeInvoice false;  // Control para verificar si se debe hacer factura o todos los indicadores (sala, servicios y pagos) estaban en falso
  1029.         //FIN: buscamos el ID de la factura
  1030.         /* Obtengo usuario logueado */
  1031.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1032.         $user_id $user_logueado->getId();
  1033.         //Acumuladores de datos globales de la factura
  1034.         $valorTotalNet 0;
  1035.         $valorVat 0;
  1036.         //INICIO: Creamos los items de la factura
  1037.         if (!empty($arrayBools['lounge'])) {
  1038.             foreach ($arrayBools['lounge'] as $key => $item) {
  1039.                 if ($item == 'true') {
  1040.                     $boolMakeInvoice true;
  1041.                     $sala $em->getRepository(ReservationLoungeSimple::class)->findOneById($key);
  1042.                     $itemInvoice = new ReservationInvoiceItems();
  1043.                     $itemInvoice->setReservationId($id);
  1044.                     $itemInvoice->setInvoiceId($invoiceId);
  1045.                     $itemInvoice->setItemType('LOUNGE');
  1046.                     $itemInvoice->setLngControlId($key);
  1047.                     $itemInvoice->setLngLoungeName($sala->getLoungeName());
  1048.                     $itemInvoice->setLngIdLounge($sala->getIdLounge());
  1049.                     $itemInvoice->setLngIdLounge($sala->getIdLounge());
  1050.                     $itemInvoice->setLngDateStart($sala->getDateStart());
  1051.                     $itemInvoice->setLngDateEnd($sala->getDateEnd());
  1052.                     $itemInvoice->setLngServicePrice($sala->getServicePrice());
  1053.                     $itemInvoice->setLngPax($sala->getPax());
  1054.                     $itemInvoice->setLngType($sala->getType());
  1055.                     $itemInvoice->setLngIva($sala->getIva() ?? 21);
  1056.                     $itemInvoice->setLngOpIva($sala->getOpIva());
  1057.                     $itemInvoice->setCreatedId($user_id);
  1058.                     $itemInvoice->setCreatedAt(new DateTime('now'));
  1059.                     $itemInvoice->setUpdatedId($user_id);
  1060.                     $itemInvoice->setUpdatedAt(new DateTime('now'));
  1061.                     $itemInvoice->setLngHourStart($sala->getHourStart());
  1062.                     $itemInvoice->setLngMinStart($sala->getMinStart());
  1063.                     $itemInvoice->setLngHourEnd($sala->getHourEnd());
  1064.                     $itemInvoice->setLngMinEnd($sala->getMinEnd());
  1065.                     $em->persist($itemInvoice);
  1066.                     $em->flush();
  1067.                     //Acumulamos neto e iva para la factura
  1068.                     $valorTotalNet += $itemInvoice->getLngServicePrice();
  1069.                     $valorVat += round(($itemInvoice->getLngServicePrice() * ($itemInvoice->getLngIva() / 100)),2,PHP_ROUND_HALF_UP);
  1070.                 }
  1071.             }
  1072.         }
  1073.         if (!empty($arrayBools['service'])) {
  1074.             foreach ($arrayBools['service'] as $key => $item) {
  1075.                 if ($item == 'true') {
  1076.                     $boolMakeInvoice true;
  1077.                     $servicio $em->getRepository(ReservationService::class)->findOneById($key);
  1078.                     $itemInvoice = new ReservationInvoiceItems();
  1079.                     $itemInvoice->setReservationId($id);
  1080.                     $itemInvoice->setInvoiceId($invoiceId);
  1081.                     $itemInvoice->setItemType('SERVICE');
  1082.                     $itemInvoice->setSrvControlId($key);
  1083.                     $itemInvoice->setSrvName($servicio->getName());
  1084.                     $itemInvoice->setSrvSupplierId($servicio->getSupplierId());
  1085.                     $itemInvoice->setSrvServiceId($servicio->getServiceId());
  1086.                     $itemInvoice->setSrvServiceCatId($servicio->getServiceCatId());
  1087.                     $itemInvoice->setSrvServiceCatName($servicio->getServiceCatName());
  1088.                     $itemInvoice->setSrvPrice($servicio->getPrice());
  1089.                     $itemInvoice->setSrvCurrency($servicio->getCurrency());
  1090.                     $itemInvoice->setSrvUnits($servicio->getUnits());
  1091.                     $itemInvoice->setSrvOpCommission($servicio->getOpCommission());
  1092.                     $itemInvoice->setSrvCommission($servicio->getCommission());
  1093.                     $itemInvoice->setSrvOpOver($servicio->getOpOver());
  1094.                     $itemInvoice->setSrvOver($servicio->getOver());
  1095.                     $itemInvoice->setSrvOpIva($servicio->getOpIva());
  1096.                     $itemInvoice->setSrvIva($servicio->getIva());
  1097.                     $itemInvoice->setSrvPax($servicio->getPax());
  1098.                     $itemInvoice->setSrvHour($servicio->getHour());
  1099.                     $itemInvoice->setSrvDateInAt($servicio->getDateInAt());
  1100.                     $itemInvoice->setSrvDateOutAt($servicio->getDateOutAt());
  1101.                     $itemInvoice->setSrvContcolor($servicio->getContcolor());
  1102.                     $itemInvoice->setSrvRank($servicio->getRank());
  1103.                     $itemInvoice->setSrvAssistantId($servicio->getAssistantId());
  1104.                     $itemInvoice->setSrvActivityId($servicio->getActivityId());
  1105.                     $itemInvoice->setSrvPay($servicio->getPay());
  1106.                     $itemInvoice->setCreatedAt(new DateTime('now'));
  1107.                     $itemInvoice->setUpdatedAt(new DateTime('now'));
  1108.                     $itemInvoice->setCreatedId($user_id);
  1109.                     $itemInvoice->setUpdatedId($user_id);
  1110.                     $em->persist($itemInvoice);
  1111.                     $em->flush();
  1112.                     //Acumulamos neto e iva para la factura
  1113.                     if (is_null($itemInvoice->getSrvPrice()) or empty($itemInvoice->getSrvPrice())){
  1114.                         $subtotal 0;
  1115.                         $neto 0;
  1116.                         $subtotalService 0;
  1117.                     } else {
  1118.                         $subtotalService = (float)$itemInvoice->getSrvPrice();
  1119.                         $subneto = (float)$itemInvoice->getSrvPrice();
  1120.                         // Commission
  1121.                         if ($itemInvoice->getSrvOpCommission()=='1'){
  1122.                             $subtotalService $subtotalService * (+ ($itemInvoice->getSrvCommission()/100));
  1123.                             $subneto $subneto  * (+ ($itemInvoice->getSrvCommission()/100));
  1124.                         } else {
  1125.                             $subtotalService $subtotalService * (- ($itemInvoice->getSrvCommission()/100));
  1126.                             $subneto $subneto * (- ($itemInvoice->getSrvCommission()/100));
  1127.                         }
  1128.                         // Over
  1129.                         if ($itemInvoice->getSrvOpOver()=='1'){
  1130.                             $subtotalService $subtotalService $itemInvoice->getSrvOver();
  1131.                             $subneto $subneto $itemInvoice->getSrvOver();
  1132.                         } else {
  1133.                             $subtotalService $subtotalService $itemInvoice->getSrvOver();
  1134.                             $subneto $subneto $itemInvoice->getSrvOver();
  1135.                         }
  1136.                         // IVA
  1137.                         if ($itemInvoice->getSrvOpIva()=='1'){
  1138.                             $subtotalService $subtotalService * (+ ($itemInvoice->getSrvIva()/100));
  1139.                         } else {
  1140.                             $subtotalService $itemInvoice->getSrvPrice();
  1141.                             $subneto = ($subneto 100) / (100 $itemInvoice->getSrvIva());
  1142.                         }
  1143.                         switch ($itemInvoice->getSrvServiceCatId()){
  1144.                             case 1// Alojamiento
  1145.                                 // el numero de noches $numNoches; precio unitario $subneto
  1146.                                 $numNoches = (($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days;
  1147.                                 // La personas no afectan este calculo
  1148.                                 $subtotal $subtotalService $numNoches $itemInvoice->getSrvUnits();
  1149.                                 $subnetoUnit $subneto;
  1150.                                 $subneto $subneto $numNoches $itemInvoice->getSrvUnits();
  1151.                                 break;
  1152.                             case 2//Actividades
  1153.                                 // El número de personas es considerado en el calculo
  1154.                                 $pax $itemInvoice->getSrvPax();
  1155.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1156.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1157.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1158.                                 $subtotal $subtotalService $days $itemInvoice->getSrvUnits();
  1159.                                 $subnetoUnit $subneto;
  1160.                                 $subneto $subneto $days $itemInvoice->getSrvUnits();
  1161.                                 break;
  1162.                             case 3// AV
  1163.                                 $pax $itemInvoice->getSrvPax();
  1164.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1165.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1166.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1167.                                 $unitsServ $itemInvoice->getSrvUnits();
  1168.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1169.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1170.                                 $subnetoUnit $subneto;
  1171.                                 $subneto $subneto $days $unitsServ $pax;
  1172.                                 break;
  1173.                             case 4//Creative
  1174.                                 $pax $itemInvoice->getSrvPax();
  1175.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1176.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1177.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1178.                                 $unitsServ $itemInvoice->getSrvUnits();
  1179.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1180.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1181.                                 $subnetoUnit $subneto;
  1182.                                 $subneto $subneto $days $unitsServ $pax;
  1183.                                 break;
  1184.                             case 5//Cruise
  1185.                                 $pax $itemInvoice->getSrvPax();
  1186.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1187.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days);
  1188.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1189.                                 $unitsServ $itemInvoice->getSrvUnits();
  1190.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1191.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1192.                                 $subnetoUnit $subneto;
  1193.                                 $subneto $subneto $days $unitsServ $pax;
  1194.                                 break;
  1195.                             case 6//Entertaiment
  1196.                                 $pax $itemInvoice->getSrvPax();
  1197.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1198.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1199.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1200.                                 $unitsServ $itemInvoice->getSrvUnits();
  1201.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1202.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1203.                                 $subnetoUnit $subneto;
  1204.                                 $subneto $subneto $days $unitsServ $pax;
  1205.                                 break;
  1206.                             case 7// Gifts
  1207.                                 $pax $itemInvoice->getSrvPax();
  1208.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1209.                                 $days 1;
  1210.                                 $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1211.                                 $unitsServ $itemInvoice->getSrvUnits();
  1212.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1213.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1214.                                 $subnetoUnit $subneto;
  1215.                                 $subneto $subneto $days $unitsServ $pax;
  1216.                                 break;
  1217.                             case 8//Guide
  1218.                                 $pax $itemInvoice->getSrvPax();
  1219.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1220.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1221.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1222.                                 $unitsServ $itemInvoice->getSrvUnits();
  1223.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1224.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1225.                                 $subnetoUnit $subneto;
  1226.                                 $subneto $subneto $days $unitsServ $pax;
  1227.                                 break;
  1228.                             case 9//Itineraries
  1229.                                 $pax $itemInvoice->getSrvPax();
  1230.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1231.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1232.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1233.                                 $unitsServ $itemInvoice->getSrvUnits();
  1234.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1235.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1236.                                 $subnetoUnit $subneto;
  1237.                                 $subneto $subneto $days $unitsServ $pax;
  1238.                                 break;
  1239.                             case 10//Lounge  -- No Aplica
  1240.                                 break;
  1241.                             case 11//Menu (Catering)
  1242.                                 $pax $itemInvoice->getSrvPax();
  1243.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1244.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1245.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1246.                                 $unitsServ $itemInvoice->getSrvUnits();
  1247.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1248.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1249.                                 $subnetoUnit $subneto;
  1250.                                 $subneto $subneto $days $unitsServ $pax;
  1251.                                 break;
  1252.                             case 12//Others
  1253.                                 $pax $itemInvoice->getSrvPax();
  1254.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1255.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1256.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1257.                                  $unitsServ $itemInvoice->getSrvUnits();
  1258.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1259.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1260.                                 $subnetoUnit $subneto;
  1261.                                 $subneto $subneto $days $unitsServ $pax;
  1262.                                 break;
  1263.                             case 13//Transport
  1264.                                 $pax $itemInvoice->getSrvPax();
  1265.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1266.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1267.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1268.                                 $unitsServ $itemInvoice->getSrvUnits();
  1269.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1270.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1271.                                 $subnetoUnit $subneto;
  1272.                                 $subneto $subneto $days $unitsServ $pax;
  1273.                                 break;
  1274.                             case 14//Technology
  1275.                                 $pax $itemInvoice->getSrvPax();
  1276.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1277.                                 $days 1;
  1278.                                 $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  1279.                                 $unitsServ $itemInvoice->getSrvUnits();
  1280.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1281.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1282.                                 $subnetoUnit $subneto;
  1283.                                 $subneto $subneto $days $unitsServ $pax;
  1284.                                 break;
  1285.                             case 15//Assisstant
  1286.                                 $pax $itemInvoice->getSrvPax();
  1287.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1288.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1289.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1290.                                 $unitsServ $itemInvoice->getSrvUnits();
  1291.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1292.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1293.                                 $subnetoUnit $subneto;
  1294.                                 $subneto $subneto $days $unitsServ $pax;
  1295.                                 break;
  1296.                             case 16//DDR
  1297.                                 $pax $itemInvoice->getSrvPax();
  1298.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1299.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1300.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1301.                                 $unitsServ $itemInvoice->getSrvUnits();
  1302.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1303.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1304.                                 $subnetoUnit $subneto;
  1305.                                 $subneto $subneto $days $unitsServ $pax;
  1306.                                 break;
  1307.                             case 17//Seguridad
  1308.                                 $pax $itemInvoice->getSrvPax();
  1309.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1310.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1311.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1312.                                 $unitsServ $itemInvoice->getSrvUnits();
  1313.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1314.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1315.                                 $subnetoUnit $subneto;
  1316.                                 $subneto $subneto $days $unitsServ $pax;
  1317.                                 break;
  1318.                             case 18//WiFi
  1319.                                 $pax $itemInvoice->getSrvPax();
  1320.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1321.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1322.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1323.                                 $unitsServ $itemInvoice->getSrvUnits();
  1324.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1325.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1326.                                 $subnetoUnit $subneto;
  1327.                                 $subneto $subneto $days $unitsServ $pax;
  1328.                                 break;
  1329.                             case 19//Mobiliario
  1330.                                 $pax $itemInvoice->getSrvPax();
  1331.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1332.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1333.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1334.                                 $unitsServ $itemInvoice->getSrvUnits();
  1335.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1336.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1337.                                 $subnetoUnit $subneto;
  1338.                                 $subneto $subneto $days $unitsServ $pax;
  1339.                                 break;
  1340.                             case 20//Parking
  1341.                                 $pax $itemInvoice->getSrvPax();
  1342.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1343.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1344.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1345.                                 $unitsServ $itemInvoice->getSrvUnits();
  1346.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1347.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1348.                                 $subnetoUnit $subneto;
  1349.                                 $subneto $subneto $days $unitsServ $pax;
  1350.                                 break;
  1351.                             case 21//Limpieza
  1352.                                 $pax $itemInvoice->getSrvPax();
  1353.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1354.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1355.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1356.                                 $unitsServ $itemInvoice->getSrvUnits();
  1357.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1358.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1359.                                 $subnetoUnit $subneto;
  1360.                                 $subneto $subneto $days $unitsServ $pax;
  1361.                                 break;
  1362.                             default: //Others (por default)
  1363.                                 $pax $itemInvoice->getSrvPax();
  1364.                                 if (empty($pax) or $pax == "0") { $pax 1; }
  1365.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1366.                                 $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1367.                                 $unitsServ $itemInvoice->getSrvUnits();
  1368.                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  1369.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1370.                                 $subnetoUnit $subneto;
  1371.                                 $subneto $subneto $days $unitsServ $pax;
  1372.                                 break;
  1373.                         }
  1374.                         // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  1375.                         $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  1376.                         $neto round($subneto,2,PHP_ROUND_HALF_UP);
  1377.                         $valorTotalNet $valorTotalNet $neto;
  1378.                         $valorVat $valorVat + ($subtotal $neto);
  1379.                     }
  1380.                 }
  1381.             }
  1382.         }
  1383.         if (!empty($arrayBools['payment'])) {
  1384.             foreach ($arrayBools['payment'] as $key => $item) {
  1385.                 if ($item == 'true') {
  1386.                     $boolMakeInvoice true;
  1387.                     $pago $em->getRepository(ReservationPaymentsClient::class)->findOneById($key);
  1388.                     $itemInvoice = new ReservationInvoiceItems();
  1389.                     $itemInvoice->setReservationId($id);
  1390.                     $itemInvoice->setInvoiceId($invoiceId);
  1391.                     $itemInvoice->setItemType('PAYMENT');
  1392.                     $itemInvoice->setPayControlId($key);
  1393.                     $itemInvoice->setPayAmount($pago->getAmount());
  1394.                     $itemInvoice->setPayVat($pago->getVat());
  1395.                     $itemInvoice->setPayAmountTotal($pago->getAmountTotal());
  1396.                     $itemInvoice->setPayDatePayAt($pago->getDatePayAt());
  1397.                     $itemInvoice->setPayWayToPay($pago->getWayToPay());
  1398.                     $itemInvoice->setCreatedAt(new DateTime('now'));
  1399.                     $itemInvoice->setUpdatedAt(new DateTime('now'));
  1400.                     $itemInvoice->setCreatedId($user_id);
  1401.                     $itemInvoice->setUpdatedId($user_id);
  1402.                     $em->persist($itemInvoice);
  1403.                     $em->flush();
  1404.                     //Acumulamos neto e iva para la factura
  1405.                     //$valorTotalNet = $valorTotalNet - $itemInvoice->getPayAmount();    // El pago no puede afectar el neto de la factura
  1406.                     $valorTotalNet $valorTotalNet $itemInvoice->getPayAmount();
  1407.                     $valorVat $valorVat round(($itemInvoice->getPayAmount() * 0.21),2,PHP_ROUND_HALF_UP);
  1408.                 }
  1409.             }
  1410.         }
  1411.         //FIN: Creamos los items de la factura
  1412.         $valorTotal $valorTotalNet $valorVat;
  1413.         //INICIO: Creamos la factura
  1414.         $newInvoice = new ReservationInvoice();
  1415.         $newInvoice->setNumber("GPF-".date('dmy')."-".$id);
  1416.         $newInvoice->setDateAt(new DateTime('now'));
  1417.         $newInvoice->setType('Invoice');
  1418.         $newInvoice->setReservationId($id);
  1419.         $newInvoice->setTotalNet($valorTotalNet);
  1420.         $newInvoice->setVat($valorVat);
  1421.         $newInvoice->setTotal($valorTotal);
  1422.         $newInvoice->setCreatedAt(new DateTime('now'));
  1423.         $newInvoice->setCreatedId($user_id);
  1424.         $newInvoice->setUpdatedAt(new DateTime('now'));
  1425.         $newInvoice->setUpdatedId($user_id);
  1426.         $newInvoice->setMaster('master');
  1427.         $newInvoice->setClientName($clientName);
  1428.         $newInvoice->setClientAddress($clientAddress);
  1429.         $newInvoice->setClientDocument($clientDocument);
  1430.         $newInvoice->setClientType($clientType);
  1431.         if ($boolMakeInvoice){
  1432.             // Solo se debe crear factura si hay un elemento
  1433.             $em->persist($newInvoice);
  1434.             $em->flush();
  1435.             $newInvoice->setNumber($newInvoice->getNumber().'-'.$newInvoice->getId());
  1436.             $em->persist($newInvoice);
  1437.             $em->flush();
  1438.         } else {
  1439.             // Se llama a la vista de facturas del expediente
  1440.             return $this->redirectToRoute('reservations_viewreservation_invoices',array('id' => $id));
  1441.         }
  1442.         //FIN: Creamos la factura
  1443.         $paymentsClient = new ReservationPaymentsClient();
  1444.         $paymentsClient->setReservationId($id);
  1445.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  1446.         if ($boolMakeInvoice){
  1447.             // Si se creo la factura se cambia el estado de la reserva a Facturado
  1448.             $reserva->setStatus('Invoiced');
  1449.             $em->persist($reserva);
  1450.             $em->flush();
  1451.         }
  1452.         return $this->redirectToRoute('reservations_viewnew_invoice',array('id' => $newInvoice->getId()));
  1453.     }
  1454.     /**
  1455.      * @Route("/reservations/invoice/generatenewproforma",  name="reservations_generatenew_proforma")
  1456.      */
  1457.     public function generatenewProformaAction(Request $request)
  1458.     {
  1459.         $em $this->getDoctrine()->getManager();
  1460.         // Se genera y muestra en nueva pantalla la nueva proforma
  1461.         $arrayBools = array(
  1462.             'lounge' => null,
  1463.             'service' => null,
  1464.             'payment' => null,
  1465.         );
  1466.         $arrayBools['lounge'] = $request->request->get('lounge_hidden_bool');
  1467.         $arrayBools['service'] = $request->request->get('service_hidden_bool');
  1468.         $arrayBools['payment'] = $request->request->get('payment_hidden_bool');
  1469.         $id $request->request->get('reservation_id');
  1470.         $proforma_number $request->request->get('proforma_number');
  1471.         $boolMakeInvoice false;  // Control para verificar si se debe hacer (PROFORMA) o todos los indicadores (sala, servicios y pagos) estaban en falso
  1472.         //FIN: buscamos el ID de la factura
  1473.         /* Obtengo usuario logueado */
  1474.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1475.         $user_id $user_logueado->getId();
  1476.         //INICIO: Creamos los items de la proforma
  1477.         if (!empty($arrayBools['lounge'])) {
  1478.             foreach ($arrayBools['lounge'] as $key => $item) {
  1479.                 if ($item == 'true') {
  1480.                     $boolMakeInvoice true;
  1481.                     $sala $em->getRepository(ReservationLoungeSimple::class)->findOneById($key);
  1482.                     $itemProforma = new ReservationInvoiceProformaItems();
  1483.                     $itemProforma->setType('LOUNGE');
  1484.                     $itemProforma->setReservationId($id);
  1485.                     $itemProforma->setProformaId($proforma_number);
  1486.                     $itemProforma->setControlId($key);
  1487.                     $em->persist($itemProforma);
  1488.                     $em->flush();
  1489.                 }
  1490.             }
  1491.         }
  1492.         if (!empty($arrayBools['service'])) {
  1493.             foreach ($arrayBools['service'] as $key => $item) {
  1494.                 if ($item === 'true') {
  1495.                     $boolMakeInvoice true;
  1496.                     $servicio $em->getRepository(ReservationService::class)->findOneById($key);
  1497.             
  1498.                     // Creación y persistencia del ítem proforma
  1499.                     $itemProforma = new ReservationInvoiceProformaItems();
  1500.                     $itemProforma->setType('SERVICE')
  1501.                                  ->setReservationId($id)
  1502.                                  ->setProformaId($proforma_number)
  1503.                                  ->setControlId($key);
  1504.                     $em->persist($itemProforma);
  1505.                     $em->flush();
  1506.                 }
  1507.             }
  1508.         }
  1509.         if (!empty($arrayBools['payment'])) {
  1510.             foreach ($arrayBools['payment'] as $key => $item) {
  1511.                 if ($item == 'true') {
  1512.                     $boolMakeInvoice true;
  1513.                     $itemProforma = new ReservationInvoiceProformaItems();
  1514.                     $itemProforma->setType('PAYMENT');
  1515.                     $itemProforma->setReservationId($id);
  1516.                     $itemProforma->setProformaId($proforma_number);
  1517.                     $itemProforma->setControlId($key);
  1518.                     $em->persist($itemProforma);
  1519.                     $em->flush();
  1520.                 }
  1521.             }
  1522.         }
  1523.         //FIN: Creamos los items de la proforma
  1524.         //INICIO: Creamos la proforma
  1525.         $newProforma = new ReservationProforma();
  1526.         $newProforma->setPrefix("GPP-".date('dmy')."-".$id);
  1527.         $newProforma->setDateAt(new DateTime('now'));
  1528.         $newProforma->setReservationId($id);
  1529.         $newProforma->setCreatedAt(new DateTime('now'));
  1530.         $newProforma->setCreatedId($user_id);
  1531.         $newProforma->setUpdatedAt(new DateTime('now'));
  1532.         $newProforma->setUpdatedId($user_id);
  1533.         $newProforma->setItems(null);
  1534.         $newProforma->setAccessKey(null);
  1535.         if ($boolMakeInvoice){
  1536.             // Solo se debe crear factura si hay un elemento
  1537.             $em->persist($newProforma);
  1538.             $em->flush();
  1539.         } else {
  1540.             // Se llama a la vista de facturas del expediente
  1541.             return $this->redirectToRoute('reservations_viewreservation_proformas',array('id' => $id));
  1542.         }
  1543.         //FIN: Creamos la proforma
  1544.         return $this->redirectToRoute('reservations_viewnew_proforma',array('id' => $newProforma->getId()));
  1545.     }
  1546.     /**
  1547.      * @Route("/reservations/invoice/viewnew/{id}",  name="reservations_viewnew_invoice")
  1548.      */
  1549.     public function viewNewInvoiceAction($idRequest $request)
  1550.     {
  1551.         $em $this->getDoctrine()->getManager();
  1552.         // Se genera y muestra en nueva pantalla la nueva proforma
  1553.         $arrayBools = array(
  1554.             'lounge' => null,
  1555.             'service' => null,
  1556.             'payment' => null,
  1557.         );
  1558.         $arrayBools['lounge'] = $request->request->get('inv_lounge_hidden_bool');
  1559.         $arrayBools['service'] = $request->request->get('inv_service_hidden_bool');
  1560.         $arrayBools['payment'] = $request->request->get('inv_payment_hidden_bool');
  1561.         /* Obtengo usuario logueado */
  1562.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1563.         //INICIO: Creamos la factura
  1564.         $newInvoice $em->getRepository(ReservationInvoice::class)->findOneById($id);
  1565.         //FIN: Creamos la factura
  1566.         $data = array();
  1567.         $data $this->baseInvoiceDoneReservation($newInvoice->getReservationId(), $id,'I');
  1568.         $paymentsClient = new ReservationPaymentsClient();
  1569.         $paymentsClient->setReservationId($id);
  1570.         $reservaInv = new ReservationInvoice();
  1571.         $reservaInv->setReservationId($id);
  1572.         $idLounges = array();
  1573.         $loungesBoolToInvoice = array();
  1574.         if (array_key_exists('lounge',$data['datasupplier'])) {
  1575.             foreach ($data['datasupplier']['lounge'] as $item) {
  1576.                 $idLounges[] = $item['id'];
  1577.                 $loungesBoolToInvoice[] = 1;
  1578.             }
  1579.             $idLounges implode(','$idLounges);
  1580.             $loungesBoolToInvoice implode(','$loungesBoolToInvoice);
  1581.         } else {
  1582.             $idLounges '0';
  1583.             $loungesBoolToInvoice '0';
  1584.         }
  1585.         $idPayments = array();
  1586.         $paymentsBoolToInvoice = array();
  1587.         if (array_key_exists('payment',$data['datasupplier'])) {
  1588.             foreach ($data['datasupplier']['payment'] as $item) {
  1589.                 $idPayments[] = $item['id'];
  1590.                 $paymentsBoolToInvoice[] = 1;
  1591.             }
  1592.             $idPayments implode(','$idPayments);
  1593.             $paymentsBoolToInvoice implode(','$paymentsBoolToInvoice);
  1594.             // Se han generado dos arreglos, cada uno dividido en 2 strings
  1595.             // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
  1596.             // Para manipularlos entre la vista y el JS
  1597.         } else {
  1598.             $idPayments '0';
  1599.             $paymentsBoolToInvoice '0';
  1600.         }
  1601.         // Una factura solo se puede rectificar una vez
  1602.         $rectf $em->getRepository(ReservationInvoiceRec::class)->findBy( array('number' => 'REC-'.$newInvoice->getNumber()));
  1603.         $boolToRec = empty($rectf);
  1604.         $allInvoices $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
  1605.         $allInvoicesRec $em->getRepository(ReservationInvoiceRec::class)->findByReservationId($newInvoice->getReservationId());
  1606.         foreach ($allInvoicesRec as $item){
  1607.             array_push($allInvoices$item);
  1608.         }
  1609.         $allProformas $em->getRepository(ReservationProforma::class)->findByReservationId($newInvoice->getReservationId());
  1610.         if(empty($data['type'])){$data['type'] = 'Invoice';}
  1611.         $reservaEquis $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
  1612.         if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
  1613.             $newInvoice $this->clientDataToInvoice($newInvoice'Client'$reservaEquis->getClient(), $newInvoice->getReservationId());
  1614.         }
  1615.         return $this->render('MDS/GreenPatioBundle/reservations/invoice-new-invoice.html.twig',
  1616.             array(
  1617.                 'id' => $newInvoice->getReservationId(),
  1618.                 'cid' => '',
  1619.                 'fid' => $id,
  1620.                 'invoice' => $allInvoices,
  1621.                 'proformas' => $allProformas,
  1622.                 'boolToRec' => $boolToRec,
  1623.                 'numberadmin' => '',
  1624.                 'type' => $data['type'],
  1625.                 'number' => $newInvoice->getId(),
  1626.                 'prefix' => $data['prefix'],
  1627.                 'date' => $data['date'],
  1628.                 'token' =>  $data['token'],
  1629.                 'reservation' => $data['reservation'],
  1630.                 'company' => $data['company'],
  1631.                 'clients' => $data['clients'],
  1632.                 'user' => $user_logueado,
  1633.                 'invoicedeposititems' => '',
  1634.                 'arrayItems' => $data['arrayItems'],
  1635.                 'datasupplier' => $data['datasupplier'],
  1636.                 'totales_neto' => $data['totales_neto'],
  1637.                 'totales_iva' => '',
  1638.                 'totales' => $data['totales'],
  1639.                 'bases_imponibles' => $data['bases_imponibles'],
  1640.                 'balance' => $data['balance'],
  1641.                 'paymentInvoice' => $data['paymentInvoice'],
  1642.                 'currency' => $data['currency'],
  1643.                 'clientName' => $newInvoice->getClientName(),
  1644.                 'clientAddress' => $newInvoice->getClientAddress(),
  1645.                 'clientDocument' => $newInvoice->getClientDocument(),
  1646.             )
  1647.         );
  1648.     }
  1649.     /**
  1650.      * @Route("/reservations/invoice/viewnewprof/{id}",  name="reservations_viewnew_proforma")
  1651.      */
  1652.     public function viewNewProformaAction($idRequest $request)
  1653.     {
  1654.         $em $this->getDoctrine()->getManager();
  1655.         // Se genera y muestra en nueva pantalla la nueva proforma
  1656.         $arrayBools = array(
  1657.             'lounge' => null,
  1658.             'service' => null,
  1659.             'payment' => null,
  1660.         );
  1661.         $arrayBools['lounge'] = $request->request->get('inv_lounge_hidden_bool');
  1662.         $arrayBools['service'] = $request->request->get('inv_service_hidden_bool');
  1663.         $arrayBools['payment'] = $request->request->get('inv_payment_hidden_bool');
  1664.         /* Obtengo usuario logueado */
  1665.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1666.         //FIN: Creamos los items de la proforma
  1667.         $newInvoice $em->getRepository(ReservationProforma::class)->findOneById($id);
  1668.         //FIN: Creamos la proforma
  1669.         $data = array();
  1670.         $data $this->baseInvoiceDoneReservation($newInvoice->getReservationId(), $id,'P');
  1671.         // Una factura solo se puede rectificar una vez (Las proformas no se rectifican)
  1672.         $boolToRec false;
  1673.         $allInvoices $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
  1674.         $allInvoicesRec $em->getRepository(ReservationInvoiceRec::class)->findByReservationId($newInvoice->getReservationId());
  1675.         foreach ($allInvoicesRec as $item){
  1676.             array_push($allInvoices$item);
  1677.         }
  1678.         $allProformas $em->getRepository(ReservationProforma::class)->findByReservationId($newInvoice->getReservationId());
  1679.         if(empty($data['type'])){$data['type'] = 'Proforma';}
  1680.         $newInvoiceProf $this->clientDataToInvoice(nullnullnull$newInvoice->getReservationId());
  1681.         return $this->render('MDS/GreenPatioBundle/reservations/invoice-new-invoice.html.twig',
  1682.             array(
  1683.                 'id' => $newInvoice->getReservationId(),
  1684.                 'cid' => '',
  1685.                 'fid' => $id,
  1686.                 'invoice' => $allInvoices,
  1687.                 'proformas' => $allProformas,
  1688.                 'boolToRec' => $boolToRec,
  1689.                 'numberadmin' => '',
  1690.                 'type' => $data['type'],
  1691.                 'number' => $newInvoice->getId(),
  1692.                 'prefix' => $data['prefix'],
  1693.                 'date' => $data['date'],
  1694.                 'token' =>  $data['token'],
  1695.                 'reservation' => $data['reservation'],
  1696.                 'company' => $data['company'],
  1697.                 'clients' => $data['clients'],
  1698.                 'user' => $user_logueado,
  1699.                 'invoicedeposititems' => '',
  1700.                 'arrayItems' => $data['arrayItems'],
  1701.                 'datasupplier' => $data['datasupplier'],
  1702.                 'totales_neto' => $data['totales_neto'],
  1703.                 'totales_iva' => '',
  1704.                 'totales' => $data['totales'],
  1705.                 'bases_imponibles' => $data['bases_imponibles'],
  1706.                 'balance' => $data['balance'],
  1707.                 'paymentInvoice' => $data['paymentInvoice'],
  1708.                 'currency' => $data['currency'],
  1709.                 'clientName' => $newInvoiceProf->getClientName(),
  1710.                 'clientAddress' => $newInvoiceProf->getClientAddress(),
  1711.                 'clientDocument' => $newInvoiceProf->getClientDocument(),
  1712.             )
  1713.         );
  1714.     }
  1715.     /**
  1716.      * @Route("/reservations/invoice/viewrec/{id}",  name="reservations_viewrec_invoice")
  1717.      */
  1718.     public function viewRecInvoiceAction($idRequest $request)
  1719.     {
  1720.         $em $this->getDoctrine()->getManager();
  1721.         // Se genera y muestra en nueva pantalla la nueva proforma
  1722.         $arrayBools = array(
  1723.             'lounge' => null,
  1724.             'service' => null,
  1725.             'payment' => null,
  1726.         );
  1727.         $arrayBools['lounge'] = $request->request->get('inv_lounge_hidden_bool');
  1728.         $arrayBools['service'] = $request->request->get('inv_service_hidden_bool');
  1729.         $arrayBools['payment'] = $request->request->get('inv_payment_hidden_bool');
  1730.         /* Obtengo usuario logueado */
  1731.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1732.         $user_id $user_logueado->getId();
  1733.         //Acumuladores de datos globales de la factura
  1734.         $valorTotalNet 0;
  1735.         $valorVat 0;
  1736. //        $valorTotal = 0;
  1737.         //INICIO: Creamos los items de la factura
  1738.         $arrayInvoicedItems $em->getRepository(ReservationInvoiceRecItems::class)->findByInvoiceId($id);
  1739.         if (!empty($arrayInvoicedItems)) {
  1740.             foreach ($arrayInvoicedItems as $itemInvoice) {
  1741.                 if ($itemInvoice->getItemType() == 'LOUNGE') {
  1742.                     $ivaNew $itemInvoice->getLngIva();
  1743.                     //Acumulamos neto e iva para la factura
  1744.                     $valorTotalNet $valorTotalNet $itemInvoice->getLngServicePrice();
  1745.                     $valorVat $valorVat round(($itemInvoice->getLngServicePrice() * ($ivaNew 100)),2,PHP_ROUND_HALF_UP);
  1746.                 }
  1747.             }
  1748.         }
  1749.         if (!empty($arrayInvoicedItems)) {
  1750.             foreach ($arrayInvoicedItems as $itemInvoice) {
  1751.                 if ($itemInvoice->getItemType() == 'SERVICE') {
  1752.                     //Acumulamos neto e iva para la factura
  1753.                     if (is_null($itemInvoice->getSrvPrice()) or empty($itemInvoice->getSrvPrice())){
  1754.                         $subtotal 0;
  1755.                         $neto 0;
  1756.                         $subtotalService 0;
  1757.                     } else {
  1758.                         $subtotalService = (float)$itemInvoice->getSrvPrice();
  1759.                         $subneto = (float)$itemInvoice->getSrvPrice();
  1760.                         // Commission
  1761.                         if ($itemInvoice->getSrvOpCommission()=='1'){
  1762.                             $subtotalService $subtotalService * (+ ($itemInvoice->getSrvCommission()/100));
  1763.                             $subneto $subneto  * (+ ($itemInvoice->getSrvCommission()/100));
  1764.                         } else {
  1765.                             $subtotalService $subtotalService * (- ($itemInvoice->getSrvCommission()/100));
  1766.                             $subneto $subneto * (- ($itemInvoice->getSrvCommission()/100));
  1767.                         }
  1768.                         // Over
  1769.                         if ($itemInvoice->getSrvOpOver()=='1'){
  1770.                             $subtotalService $subtotalService $itemInvoice->getSrvOver();
  1771.                             $subneto $subneto $itemInvoice->getSrvOver();
  1772.                         } else {
  1773.                             $subtotalService $subtotalService $itemInvoice->getSrvOver();
  1774.                             $subneto $subneto $itemInvoice->getSrvOver();
  1775.                         }
  1776.                         // IVA
  1777.                         if ($itemInvoice->getSrvOpIva()=='1'){
  1778.                             $subtotalService $subtotalService * (+ ($itemInvoice->getSrvIva()/100));
  1779.                         } else {
  1780.                             $subtotalService $itemInvoice->getSrvPrice();
  1781.                             $subneto = ($subneto 100) / (100 $itemInvoice->getSrvIva());
  1782.                         }
  1783.                         switch ($itemInvoice->getSrvServiceCatId()){
  1784.                             case 1// Alojamiento
  1785.                                 // el numero de noches $numNoches; precio unitario $subneto
  1786.                                 $numNoches = (($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days;
  1787.                                 // La personas no afectan este calculo
  1788.                                 $subtotal $subtotalService $numNoches $itemInvoice->getSrvUnits();
  1789.                                 $subnetoUnit $subneto;
  1790.                                 $subneto $subneto $numNoches $itemInvoice->getSrvUnits();
  1791.                                 break;
  1792.                             case 2//Actividades
  1793.                                 // El número de personas es considerado en el calculo
  1794.                                 $pax $itemInvoice->getSrvPax();
  1795.                                 if (empty($pax) or $pax == "0") {
  1796.                                     $pax 1;
  1797.                                 }
  1798.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1799.                                 if ($days 1){
  1800.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  1801.                                 } else {
  1802.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1803.                                 }
  1804.                                 $subtotal $subtotalService $days $itemInvoice->getSrvUnits();
  1805.                                 $subnetoUnit $subneto;
  1806.                                 $subneto $subneto $days $itemInvoice->getSrvUnits();
  1807.                                 break;
  1808.                             case 3// AV
  1809.                                 $pax $itemInvoice->getSrvPax();
  1810.                                 if (empty($pax) or $pax == "0") {
  1811.                                     $pax 1;
  1812.                                 }
  1813.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1814.                                 if ($days 1){
  1815.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  1816.                                 } else {
  1817.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1818.                                 }
  1819.                                 $unitsServ $itemInvoice->getSrvUnits();
  1820.                                 if (empty($unitsServ) or $unitsServ == "0") {
  1821.                                     $unitsServ 1;
  1822.                                 }
  1823.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1824.                                 $subnetoUnit $subneto;
  1825.                                 $subneto $subneto $days $unitsServ $pax;
  1826.                                 break;
  1827.                             case 4//Creative
  1828.                                 $pax $itemInvoice->getSrvPax();
  1829.                                 if (empty($pax) or $pax == "0") {
  1830.                                     $pax 1;
  1831.                                 }
  1832.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1833.                                 if ($days 1){
  1834.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  1835.                                 } else {
  1836.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1837.                                 }
  1838.                                 $unitsServ $itemInvoice->getSrvUnits();
  1839.                                 if (empty($unitsServ) or $unitsServ == "0") {
  1840.                                     $unitsServ 1;
  1841.                                 }
  1842.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1843.                                 $subnetoUnit $subneto;
  1844.                                 $subneto $subneto $days $unitsServ $pax;
  1845.                                 break;
  1846.                             case 5//Cruise
  1847.                                 $pax $itemInvoice->getSrvPax();
  1848.                                 if (empty($pax) or $pax == "0") {
  1849.                                     $pax 1;
  1850.                                 }
  1851.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days);
  1852.                                 if ($days 1){
  1853.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  1854.                                 } else {
  1855.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1856.                                 }
  1857.                                 $unitsServ $itemInvoice->getSrvUnits();
  1858.                                 if (empty($unitsServ) or $unitsServ == "0") {
  1859.                                     $unitsServ 1;
  1860.                                 }
  1861.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1862.                                 $subnetoUnit $subneto;
  1863.                                 $subneto $subneto $days $unitsServ $pax;
  1864.                                 break;
  1865.                             case 6//Entertaiment
  1866.                                 $pax $itemInvoice->getSrvPax();
  1867.                                 if (empty($pax) or $pax == "0") {
  1868.                                     $pax 1;
  1869.                                 }
  1870.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1871.                                 if ($days 1){
  1872.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  1873.                                 } else {
  1874.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1875.                                 }
  1876.                                 $unitsServ $itemInvoice->getSrvUnits();
  1877.                                 if (empty($unitsServ) or $unitsServ == "0") {
  1878.                                     $unitsServ 1;
  1879.                                 }
  1880.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1881.                                 $subnetoUnit $subneto;
  1882.                                 $subneto $subneto $days $unitsServ $pax;
  1883.                                 break;
  1884.                             case 7// Gifts
  1885.                                 $pax $itemInvoice->getSrvPax();
  1886.                                 if (empty($pax) or $pax == "0") {
  1887.                                     $pax 1;
  1888.                                 }
  1889.                                 $days 1;
  1890.                                 if ($days 1){
  1891.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  1892.                                 } else {
  1893.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1894.                                 }
  1895.                                 $unitsServ $itemInvoice->getSrvUnits();
  1896.                                 if (empty($unitsServ) or $unitsServ == "0") {
  1897.                                     $unitsServ 1;
  1898.                                 }
  1899.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1900.                                 $subnetoUnit $subneto;
  1901.                                 $subneto $subneto $days $unitsServ $pax;
  1902.                                 break;
  1903.                             case 8//Guide
  1904.                                 $pax $itemInvoice->getSrvPax();
  1905.                                 if (empty($pax) or $pax == "0") {
  1906.                                     $pax 1;
  1907.                                 }
  1908.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1909.                                 if ($days 1){
  1910.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  1911.                                 } else {
  1912.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1913.                                 }
  1914.                                 $unitsServ $itemInvoice->getSrvUnits();
  1915.                                 if (empty($unitsServ) or $unitsServ == "0") {
  1916.                                     $unitsServ 1;
  1917.                                 }
  1918.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1919.                                 $subnetoUnit $subneto;
  1920.                                 $subneto $subneto $days $unitsServ $pax;
  1921.                                 break;
  1922.                             case 9//Itineraries
  1923.                                 $pax $itemInvoice->getSrvPax();
  1924.                                 if (empty($pax) or $pax == "0") {
  1925.                                     $pax 1;
  1926.                                 }
  1927.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1928.                                 if ($days 1){
  1929.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  1930.                                 } else {
  1931.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1932.                                 }
  1933.                                 $unitsServ $itemInvoice->getSrvUnits();
  1934.                                 if (empty($unitsServ) or $unitsServ == "0") {
  1935.                                     $unitsServ 1;
  1936.                                 }
  1937.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1938.                                 $subnetoUnit $subneto;
  1939.                                 $subneto $subneto $days $unitsServ $pax;
  1940.                                 break;
  1941.                             case 10//Lounge  -- No Aplica
  1942.                                 break;
  1943.                             case 11//Menu
  1944.                                 $pax $itemInvoice->getSrvPax();
  1945.                                 if (empty($pax) or $pax == "0") {
  1946.                                     $pax 1;
  1947.                                 }
  1948.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1949.                                 if ($days 1){
  1950.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  1951.                                 } else {
  1952.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1953.                                 }
  1954.                                 $unitsServ $itemInvoice->getSrvUnits();
  1955.                                 if (empty($unitsServ) or $unitsServ == "0") {
  1956.                                     $unitsServ 1;
  1957.                                 }
  1958.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1959.                                 $subnetoUnit $subneto;
  1960.                                 $subneto $subneto $days $unitsServ $pax;
  1961.                                 break;
  1962.                             case 12//Others
  1963.                                 $pax $itemInvoice->getSrvPax();
  1964.                                 if (empty($pax) or $pax == "0") {
  1965.                                     $pax 1;
  1966.                                 }
  1967.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1968.                                 if ($days 1){
  1969.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  1970.                                 } else {
  1971.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1972.                                 }
  1973.                                 $unitsServ $itemInvoice->getSrvUnits();
  1974.                                 if (empty($unitsServ) or $unitsServ == "0") {
  1975.                                     $unitsServ 1;
  1976.                                 }
  1977.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1978.                                 $subnetoUnit $subneto;
  1979.                                 $subneto $subneto $days $unitsServ $pax;
  1980.                                 break;
  1981.                             case 13//Transport
  1982.                                 $pax $itemInvoice->getSrvPax();
  1983.                                 if (empty($pax) or $pax == "0") {
  1984.                                     $pax 1;
  1985.                                 }
  1986.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  1987.                                 if ($days 1){
  1988.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  1989.                                 } else {
  1990.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  1991.                                 }
  1992.                                 $unitsServ $itemInvoice->getSrvUnits();
  1993.                                 if (empty($unitsServ) or $unitsServ == "0") {
  1994.                                     $unitsServ 1;
  1995.                                 }
  1996.                                 $subtotal $subtotalService $days $unitsServ $pax;
  1997.                                 $subnetoUnit $subneto;
  1998.                                 $subneto $subneto $days $unitsServ $pax;
  1999.                                 break;
  2000.                             case 14//Technology
  2001.                                 $pax $itemInvoice->getSrvPax();
  2002.                                 if (empty($pax) or $pax == "0") {
  2003.                                     $pax 1;
  2004.                                 }
  2005.                                 $days 1;
  2006.                                 $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  2007.                                 $unitsServ $itemInvoice->getSrvUnits();
  2008.                                 if (empty($unitsServ) or $unitsServ == "0") {
  2009.                                     $unitsServ 1;
  2010.                                 }
  2011.                                 $subtotal $subtotalService $days $unitsServ $pax;
  2012.                                 $subnetoUnit $subneto;
  2013.                                 $subneto $subneto $days $unitsServ $pax;
  2014.                                 break;
  2015.                             case 15//Assisstant
  2016.                                 $pax $itemInvoice->getSrvPax();
  2017.                                 if (empty($pax) or $pax == "0") {
  2018.                                     $pax 1;
  2019.                                 }
  2020.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2021.                                 if ($days 1){
  2022.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  2023.                                 } else {
  2024.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2025.                                 }
  2026.                                 $unitsServ $itemInvoice->getSrvUnits();
  2027.                                 if (empty($unitsServ) or $unitsServ == "0") {
  2028.                                     $unitsServ 1;
  2029.                                 }
  2030.                                 $subtotal $subtotalService $days $unitsServ $pax;
  2031.                                 $subnetoUnit $subneto;
  2032.                                 $subneto $subneto $days $unitsServ $pax;
  2033.                                 break;
  2034.                             case 16//DDR
  2035.                                 $pax $itemInvoice->getSrvPax();
  2036.                                 if (empty($pax) or $pax == "0") {
  2037.                                     $pax 1;
  2038.                                 }
  2039.                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2040.                                 if ($days 1){
  2041.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  2042.                                 } else {
  2043.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2044.                                 }
  2045.                                 $unitsServ $itemInvoice->getSrvUnits();
  2046.                                 if (empty($unitsServ) or $unitsServ == "0") {
  2047.                                     $unitsServ 1;
  2048.                                 }
  2049.                                 $subtotal $subtotalService $days $unitsServ $pax;
  2050.                                 $subnetoUnit $subneto;
  2051.                                 $subneto $subneto $days $unitsServ $pax;
  2052.                                 break;
  2053.                             default:
  2054.                                 break;
  2055.                         }
  2056.                         // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  2057.                         $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  2058.                         $neto round($subneto,2,PHP_ROUND_HALF_UP);
  2059.                         $valorTotalNet $valorTotalNet $neto;
  2060.                         $valorVat $valorVat + ($subtotal $neto);
  2061.                     }
  2062.                 }
  2063.             }
  2064.         }
  2065.         if (!empty($arrayInvoicedItems)) {
  2066.             foreach ($arrayInvoicedItems as $itemInvoice) {
  2067.                 if ($itemInvoice->getItemType() == 'PAYMENT') {
  2068. //                    $pago = $em->getRepository(ReservationPaymentsClient::class)->findOneById($key);
  2069. //
  2070. //                    $itemInvoice = new ReservationInvoiceItems();
  2071. //                    $itemInvoice->setReservationId($id);
  2072. //                    $itemInvoice->setInvoiceId($invoiceId);
  2073. //                    $itemInvoice->setItemType('PAYMENT');
  2074. //                    $itemInvoice->setPayControlId($key);
  2075. //                    $itemInvoice->setPayAmount($pago->getAmount());
  2076. //                    $itemInvoice->setPayDatePayAt($pago->getDatePayAt());
  2077. //                    $itemInvoice->setPayWayToPay($pago->getWayToPay());
  2078. //                    $itemInvoice->setCreatedAt(new DateTime('now'));
  2079. //                    $itemInvoice->setUpdatedAt(new DateTime('now'));
  2080. //                    $itemInvoice->setCreatedId($user_id);
  2081. //                    $itemInvoice->setUpdatedId($user_id);
  2082. //
  2083. //                    $em->persist($itemInvoice);
  2084. //                    $em->flush();
  2085.                     //Acumulamos neto e iva para la factura
  2086.                     //$valorTotalNet = $valorTotalNet - $itemInvoice->getPayAmount();    // El pago no puede afectar el neto de la factura
  2087.                 }
  2088.             }
  2089.         }
  2090.         //FIN: Creamos los items de la factura
  2091.         $valorTotal $valorTotalNet $valorVat;
  2092.         //INICIO: Creamos la factura
  2093.         $newInvoice $em->getRepository(ReservationInvoiceRec::class)->findOneById($id);
  2094.         //FIN: Creamos la factura
  2095.         $data = array();
  2096.         $data $this->baseInvoiceDoneReservation($newInvoice->getReservationId(), $id,'R');
  2097.         $paymentsClient = new ReservationPaymentsClient();
  2098.         $paymentsClient->setReservationId($id);
  2099.         $reservaInv = new ReservationInvoice();
  2100.         $reservaInv->setReservationId($id);
  2101.         $idLounges = array();
  2102.         $loungesBoolToInvoice = array();
  2103.         if (array_key_exists('lounge',$data['datasupplier'])) {
  2104.             foreach ($data['datasupplier']['lounge'] as $item) {
  2105.                 $idLounges[] = $item['id'];
  2106.                 $loungesBoolToInvoice[] = 1;
  2107.             }
  2108.             $idLounges implode(','$idLounges);
  2109.             $loungesBoolToInvoice implode(','$loungesBoolToInvoice);
  2110.         } else {
  2111.             $idLounges '0';
  2112.             $loungesBoolToInvoice '0';
  2113.         }
  2114.         $idPayments = array();
  2115.         $paymentsBoolToInvoice = array();
  2116.         if (array_key_exists('payment',$data['datasupplier'])) {
  2117.             foreach ($data['datasupplier']['payment'] as $item) {
  2118.                 $idPayments[] = $item['id'];
  2119.                 $paymentsBoolToInvoice[] = 1;
  2120.             }
  2121.             $idPayments implode(','$idPayments);
  2122.             $paymentsBoolToInvoice implode(','$paymentsBoolToInvoice);
  2123.             // Se han generado dos arreglos, cada uno dividido en 2 strings
  2124.             // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
  2125.             // Para manipularlos entre la vista y el JS
  2126.         } else {
  2127.             $idPayments '0';
  2128.             $paymentsBoolToInvoice '0';
  2129.         }
  2130.         // Una factura solo se puede rectificar una vez
  2131.         //$rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('number' => 'REC-'.$newInvoice->getNumber()));
  2132.         //$boolToRec = empty($rectf);
  2133.         $boolToRec false// Estas viendo una factura rectificativa
  2134.         $allInvoices $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
  2135.         $allInvoicesRec $em->getRepository(ReservationInvoiceRec::class)->findByReservationId($newInvoice->getReservationId());
  2136.         foreach ($allInvoicesRec as $item){ array_push($allInvoices$item); }
  2137.         $allProformas $em->getRepository(ReservationProforma::class)->findByReservationId($newInvoice->getReservationId());
  2138.         // Por ser una factura rectificativa multiplicamos por -1 el balance
  2139. //        $data['balance'] = $data['balance'] * (-1);
  2140.         if(empty($data['type'])){$data['type'] = 'Invoice Rec';}
  2141.         $reservaEquis $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
  2142.         if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
  2143.             $newInvoice $this->clientDataToInvoice($newInvoice'Client'$reservaEquis->getClient(), $newInvoice->getReservationId());
  2144.         }
  2145.         return $this->render('MDS/GreenPatioBundle/reservations/invoice-new-invoice.html.twig',
  2146.             array(
  2147.                 'id' => $newInvoice->getReservationId(),
  2148.                 'invoiceIdToRec' => $newInvoice->getInvoiceToRec(),
  2149.                 'cid' => '',
  2150.                 'fid' => $id,
  2151.                 'invoice' => $allInvoices,
  2152.                 'proformas' => $allProformas,
  2153.                 'boolToRec' => $boolToRec,
  2154.                 'numberadmin' => '',
  2155.                 'type' => $data['type'],
  2156.                 'number' => $newInvoice->getId(),
  2157.                 'prefix' => $data['prefix'],
  2158.                 'date' => $data['date'],
  2159.                 'token' =>  $data['token'],
  2160.                 'reservation' => $data['reservation'],
  2161.                 'company' => $data['company'],
  2162.                 'clients' => $data['clients'],
  2163.                 'user' => $user_logueado,
  2164.                 'invoicedeposititems' => '',
  2165.                 'arrayItems' => $data['arrayItems'],
  2166.                 'datasupplier' => $data['datasupplier'],
  2167.                 'totales_neto' => $data['totales_neto'],
  2168.                 'totales_iva' => '',
  2169.                 'totales' => $data['totales'],
  2170.                 'bases_imponibles' => $data['bases_imponibles'],
  2171.                 'balance' => $data['balance'],
  2172.                 'paymentInvoice' => $data['paymentInvoice'],
  2173.                 'currency' => $data['currency'],
  2174.                 'clientName' => $newInvoice->getClientName(),
  2175.                 'clientAddress' => $newInvoice->getClientAddress(),
  2176.                 'clientDocument' => $newInvoice->getClientDocument(),
  2177.             )
  2178.         );
  2179.     }
  2180.     /**
  2181.      * @Route("/reservations/invoice/viewreservationinvoices/{id}",  name="reservations_viewreservation_invoices")
  2182.      */
  2183.     public function viewReservationInvoicesAction($idRequest $request)
  2184.     {
  2185.         $em $this->getDoctrine()->getManager();
  2186.         $allInvoices $em->getRepository(ReservationInvoice::class)->findByReservationId($id);
  2187.         $allInvoicesRec $em->getRepository(ReservationInvoiceRec::class)->findByReservationId($id);
  2188.         foreach ($allInvoicesRec as $item){
  2189.             array_push($allInvoices$item);
  2190.         }
  2191.         $reservation $em->getRepository(Reservation::class)->findOneById($id);
  2192.         $client $em->getRepository(Client::class)->findOneById($reservation->getClient());
  2193.         /* Obtengo usuario logueado */
  2194.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2195.         $user_id $user_logueado->getId();
  2196.         $data = array();
  2197.         $data['clients'][0] = $client;
  2198.         $data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  2199.         $data['datasupplier'] = '';
  2200.         $data['totales_neto'] = '';
  2201.         $data['totales'] = '';
  2202.         $data['bases_imponibles'] = '';
  2203.         $data['balance'] = '';
  2204.         $data['paymentInvoice'] = '';
  2205.         $data['currency'] = '';
  2206.         // Una factura solo se puede rectificar una vez
  2207.         //$rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('number' => 'REC-'.$newInvoice->getNumber()));
  2208.         //$boolToRec = empty($rectf);
  2209.         $boolToRec false;
  2210.         return $this->render('MDS/GreenPatioBundle/reservations/invoice-new-invoice.html.twig',
  2211.             array(
  2212.                 'id' => $id,
  2213.                 'cid' => '',
  2214.                 'fid' => null,
  2215.                 'invoice' => $allInvoices,
  2216.                 'boolToRec' => $boolToRec,
  2217.                 'numberadmin' => '',
  2218.                 'type' => 'Invoice',
  2219.                 'number' => '',
  2220.                 'prefix' => '',
  2221.                 'date' => '',
  2222.                 'token' => '',
  2223.                 'reservation' => '',
  2224.                 'company' => $data['company'],
  2225.                 'clients' => $data['clients'],
  2226.                 'user' => $user_logueado,
  2227.                 'invoicedeposititems' => '',
  2228.                 'datasupplier' => $data['datasupplier'],
  2229.                 'totales_neto' => $data['totales_neto'],
  2230.                 'totales_iva' => '',
  2231.                 'totales' => $data['totales'],
  2232.                 'bases_imponibles' => $data['bases_imponibles'],
  2233.                 'balance' => $data['balance'],
  2234.                 'paymentInvoice' => $data['paymentInvoice'],
  2235.                 'currency' => $data['currency'],
  2236.             )
  2237.         );
  2238.     }
  2239.     /**
  2240.      * @Route("/reservations/invoice/viewreservationproformas/{id}",  name="reservations_viewreservation_proformas")
  2241.      */
  2242.     public function viewReservationProformasAction($idRequest $request)
  2243.     {
  2244.         $em $this->getDoctrine()->getManager();
  2245.         $allInvoices $em->getRepository(ReservationProforma::class)->findByReservationId($id);
  2246.         $allProformas $allInvoices;
  2247.         $reservation $em->getRepository(Reservation::class)->findOneById($id);
  2248.         $client $em->getRepository(Client::class)->findOneById($reservation->getClient());
  2249.         /* Obtengo usuario logueado */
  2250.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2251.         $user_id $user_logueado->getId();
  2252.         $data = array();
  2253.         $data['clients'][0] = $client;
  2254.         $data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  2255.         $data['datasupplier'] = '';
  2256.         $data['totales_neto'] = '';
  2257.         $data['totales'] = '';
  2258.         $data['bases_imponibles'] = '';
  2259.         $data['balance'] = '';
  2260.         $data['paymentInvoice'] = '';
  2261.         $data['currency'] = '';
  2262.         // Una factura solo se puede rectificar una vez
  2263.         //$rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('number' => 'REC-'.$newInvoice->getNumber()));
  2264.         //$boolToRec = empty($rectf);
  2265.         $boolToRec false;
  2266.         return $this->render('MDS/GreenPatioBundle/reservations/invoice-new-invoice.html.twig',
  2267.             array(
  2268.                 'id' => $id,
  2269.                 'cid' => '',
  2270.                 'fid' => null,
  2271.                 'invoice' => $allInvoices,
  2272.                 'proformas' => $allProformas,
  2273.                 'boolToRec' => $boolToRec,
  2274.                 'numberadmin' => '',
  2275.                 'type' => 'Proforma',
  2276.                 'number' => '',
  2277.                 'prefix' => '',
  2278.                 'date' => '',
  2279.                 'token' => '',
  2280.                 'reservation' => '',
  2281.                 'company' => $data['company'],
  2282.                 'clients' => $data['clients'],
  2283.                 'user' => $user_logueado,
  2284.                 'invoicedeposititems' => '',
  2285.                 'datasupplier' => $data['datasupplier'],
  2286.                 'totales_neto' => $data['totales_neto'],
  2287.                 'totales_iva' => '',
  2288.                 'totales' => $data['totales'],
  2289.                 'bases_imponibles' => $data['bases_imponibles'],
  2290.                 'balance' => $data['balance'],
  2291.                 'paymentInvoice' => $data['paymentInvoice'],
  2292.                 'currency' => $data['currency'],
  2293.             )
  2294.         );
  2295.     }
  2296.     /**
  2297.      * @Route("/selinvoice/{id}",  name="reservations_newinvoice")
  2298.      */
  2299.     public function generateReservationNewInvoiceAction($idRequest $request)
  2300.     {
  2301.         $em $this->getDoctrine()->getManager();
  2302.         $paymentsClient = new ReservationPaymentsClient();
  2303.         $paymentsClient->setReservationId($id);
  2304.         $clientType 'Client';
  2305.         $clientRequest $request->request->get('reservation')['client'] ?? null;
  2306.         if (!empty($clientRequest)){
  2307.             $dataCliSup $this->clientOrSupplierDataSearchToInvoice($clientRequest$id);
  2308.             $clientName $dataCliSup['clientName'];
  2309.             $clientAddress $dataCliSup['clientAddress'];
  2310.             $clientDocument $dataCliSup['clientDocument'];
  2311.             $clientType $dataCliSup['clientType'];
  2312.         }
  2313.         if (empty($clientName) and empty($clientAddress) and empty($clientDocument)){
  2314.             $newInvoice $this->clientDataToInvoice(nullnullnull$id);
  2315.         } else {
  2316.             $newInvoice = new ReservationInvoice();
  2317.             $newInvoice->setClientName($clientName);
  2318.             $newInvoice->setClientAddress($clientAddress);
  2319.             $newInvoice->setClientDocument($clientDocument);
  2320.         }
  2321.         $form $this->createReservationPaymentsClientForm($paymentsClient);
  2322.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  2323.         $payments $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
  2324.         $services $em->getRepository(ReservationService::class)->findByReservationId($id);
  2325.         $proforma $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  2326.         $allProformas $em->getRepository(ReservationProforma::class)->findAll();
  2327.         if (!empty($allProformas)){
  2328.             $number end($allProformas)->getId() + 1;
  2329.         } else {
  2330.             // Primer registro de proformas
  2331.             $number 1;
  2332.         }
  2333.         $type 'Proforma';
  2334.         $date = new DateTime('now');
  2335.         $prefix "GP-".$date->format('dmy')."-";
  2336.         $reservaInv = new ReservationInvoice();
  2337.         $reservaInv->setReservationId($id);
  2338.         $form1 $this->createReservationInvoiceProformaForm($reservaInv);
  2339.         $data $this->baseInvoiceReservation($id$type$number$prefix$date);
  2340.         $token $data['token'];
  2341.         $idLounges = array();
  2342.         if (array_key_exists('lounge',$data['datasupplier'])) {
  2343.             foreach ($data['datasupplier']['lounge'] as $key => $item) {
  2344.                 $existe $em->getRepository(ReservationInvoiceItems::class)->findOneByLngControlId($item['id']);
  2345.                 $existeCvr $em->getRepository(CvrReservationInvoiceItems::class)->findByLngControlId($item['id']);
  2346.                 $existe = (!empty($existe) or !empty($existeCvr));
  2347.                 if (empty($existe)){
  2348.                     $data['datasupplier']['lounge'][$key]['enabledToInvoice'] = true;
  2349.                 } else {
  2350.                     $data['datasupplier']['lounge'][$key]['enabledToInvoice'] = false;
  2351.                 }
  2352.             }
  2353.         }
  2354.         if (array_key_exists('service',$data['datasupplier'])) {
  2355.             foreach ($data['datasupplier']['service'] as $key => $item) {
  2356.                 $existe $em->getRepository(ReservationInvoiceItems::class)->findOneBySrvControlId($item['id']);
  2357.                 $existeCvr $em->getRepository(CvrReservationInvoiceItems::class)->findBySrvControlId($item['id']);
  2358.                 $existe = (!empty($existe) or !empty($existeCvr));
  2359.                 if (empty($existe)){
  2360.                     $data['datasupplier']['service'][$key]['enabledToInvoice'] = true;
  2361.                 } else {
  2362.                     $data['datasupplier']['service'][$key]['enabledToInvoice'] = false;
  2363.                 }
  2364.             }
  2365.         }
  2366.         $idPayments = array();
  2367.         if (array_key_exists('payment',$data['datasupplier'])) {
  2368.             foreach ($data['datasupplier']['payment'] as $key => $item) {
  2369.                 $existe $em->getRepository(ReservationInvoiceItems::class)->findOneByPayControlId($item['id']);
  2370.                 $existeCvr $em->getRepository(CvrReservationInvoiceItems::class)->findByPayControlId($item['id']);
  2371.                 $existe = (!empty($existe) or !empty($existeCvr));
  2372.                 if (empty($existe)){
  2373.                     $data['datasupplier']['payment'][$key]['enabledToInvoice'] = true;
  2374.                 } else {
  2375.                     $data['datasupplier']['payment'][$key]['enabledToInvoice'] = false;
  2376.                 }
  2377.             }
  2378.         }
  2379.         /* Obtengo usuario logueado */
  2380.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2381.         $user_id $user_logueado->getId();
  2382.         // Si el Status no lo permite solo se podra sacar proformas
  2383.         if ($reserva->getStatus() == 'Invoiced' or $reserva->getStatus() == 'Confirmed'){ $cotizarPorEstado true; } else { $cotizarPorEstado false; }
  2384.         return $this->render('MDS/GreenPatioBundle/reservations/services-invoice-select-items.html.twig',
  2385.             array(
  2386.                 'id' => $id,
  2387.                 'idLounges' => $idLounges,
  2388.                 'reserva' => $reserva,
  2389.                 'idPayments' => $idPayments,
  2390.                 'type' => $data['type'],
  2391.                 'number' => $data['number'],
  2392.                 'prefix' => $data['prefix'],
  2393.                 'date' => $data['date'],
  2394.                 'token' => $token,
  2395.                 'company' => $data['company'],
  2396.                 'clients' => $data['clients'],
  2397.                 'datasupplier' => $data['datasupplier'],
  2398.                 'currency' => $data['currency'],
  2399.                 'totales_neto' => $data['totales_neto'],
  2400.                 'bases_imponibles' => $data['bases_imponibles'],
  2401.                 'totales' => $data['totales'],
  2402.                 'balance' => $data['balance'],
  2403.                 'paymentInvoice' => $data['paymentInvoice'],
  2404.                 'payments' => $payments,
  2405.                 'user_id' => $user_id,
  2406.                 'form' => $form->createView(),
  2407.                 'form1' => $form1->createView(),
  2408.                 'cotizarPorEstado' => $cotizarPorEstado,
  2409.                 'clientName' => $newInvoice->getClientName(),
  2410.                 'clientAddress' => $newInvoice->getClientAddress(),
  2411.                 'clientDocument' => $newInvoice->getClientDocument(),
  2412.                 'clientType' => $clientType,
  2413.             )
  2414.         );
  2415.     }
  2416.     /**
  2417.      * @Route("/reservations/invoice/invoice-proforma/print/{type}/{id}",  name="reservations_invoiceorproforma_print")
  2418.      */
  2419.     public function detailsInvoiceProformaPrintAction($type$idRequest $request)
  2420.     {
  2421.         $data = array();
  2422.         $em $this->getDoctrine()->getManager();
  2423.         // Si el ID de factura viene vacio regresamos a ver facturas
  2424.         if (empty($type)){
  2425.             return $this->redirectToRoute('reservations_viewreservation_invoices',array('id' => $id));
  2426.         }
  2427.         //Acumuladores de datos globales de la factura o proforma
  2428.         $valorTotalNet 0;
  2429.         $valorVat 0;
  2430.         if ($type == 'I'){
  2431.             //Es una factura
  2432.             //INICIO: Creamos los items de la factura
  2433.             $arrayInvoicedItems $em->getRepository(ReservationInvoiceItems::class)->findByInvoiceId($id);
  2434.             if (!empty($arrayInvoicedItems)) {
  2435.                 foreach ($arrayInvoicedItems as $itemInvoice) {
  2436.                     if ($itemInvoice->getItemType() == 'LOUNGE') {
  2437.                         //Acumulamos neto e iva para la factura
  2438.                         $valorTotalNet $valorTotalNet $itemInvoice->getLngServicePrice();
  2439.                         $valorVat $valorVat round(($itemInvoice->getLngServicePrice() * 0.21),2,PHP_ROUND_HALF_UP);
  2440.                     }
  2441.                 }
  2442.             }
  2443.             if (!empty($arrayInvoicedItems)) {
  2444.                 foreach ($arrayInvoicedItems as $itemInvoice) {
  2445.                     if ($itemInvoice->getItemType() == 'SERVICE') {
  2446.                         //Acumulamos neto e iva para la factura
  2447.                         if (is_null($itemInvoice->getSrvPrice()) or empty($itemInvoice->getSrvPrice())){
  2448.                             $subtotal 0;
  2449.                             $neto 0;
  2450.                             $subtotalService 0;
  2451.                         } else {
  2452.                             $subtotalService $itemInvoice->getSrvPrice();
  2453.                             $subtotalService str_replace(',','.',$subtotalService);
  2454.                             $subtotalService floatval($subtotalService);
  2455.                             $subneto $itemInvoice->getSrvPrice();
  2456.                             $subneto str_replace(',','.',$subneto);
  2457.                             $subneto floatval($subneto);
  2458.                             // Commission
  2459.                             if ($itemInvoice->getSrvOpCommission()=='1'){
  2460.                                 $subtotalService $subtotalService * (+ ($itemInvoice->getSrvCommission()/100));
  2461.                                 $subneto $subneto  * (+ ($itemInvoice->getSrvCommission()/100));
  2462.                             } else {
  2463.                                 $subtotalService $subtotalService * (- ($itemInvoice->getSrvCommission()/100));
  2464.                                 $subneto $subneto * (- ($itemInvoice->getSrvCommission()/100));
  2465.                             }
  2466.                             // Over
  2467.                             if ($itemInvoice->getSrvOpOver()=='1'){
  2468.                                 $subtotalService $subtotalService $itemInvoice->getSrvOver();
  2469.                                 $subneto $subneto $itemInvoice->getSrvOver();
  2470.                             } else {
  2471.                                 $subtotalService $subtotalService $itemInvoice->getSrvOver();
  2472.                                 $subneto $subneto $itemInvoice->getSrvOver();
  2473.                             }
  2474.                             // IVA
  2475.                             if ($itemInvoice->getSrvOpIva()=='1'){
  2476.                                 $subtotalService $subtotalService * (+ ($itemInvoice->getSrvIva()/100));
  2477.                             } else {
  2478.                                 $subtotalService $itemInvoice->getSrvPrice();
  2479.                                 $subneto = ($subneto 100) / (100 $itemInvoice->getSrvIva());
  2480.                             }
  2481.                             switch ($itemInvoice->getSrvServiceCatId()){
  2482.                                 case 1// Alojamiento
  2483.                                     // el numero de noches $numNoches; precio unitario $subneto
  2484.                                     $numNoches = (($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days;
  2485.                                     // La personas no afectan este calculo
  2486.                                     $subtotal $subtotalService $numNoches $itemInvoice->getSrvUnits();
  2487.                                     $subnetoUnit $subneto;
  2488.                                     $subneto $subneto $numNoches $itemInvoice->getSrvUnits();
  2489.                                     break;
  2490.                                 case 2//Actividades
  2491.                                     // El número de personas es considerado en el calculo
  2492.                                     $pax $itemInvoice->getSrvPax();
  2493.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2494.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2495.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2496.                                     $subtotal $subtotalService $days $itemInvoice->getSrvUnits();
  2497.                                     $subnetoUnit $subneto;
  2498.                                     $subneto $subneto $days $itemInvoice->getSrvUnits();
  2499.                                     break;
  2500.                                 case 3// AV
  2501.                                     $pax $itemInvoice->getSrvPax();
  2502.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2503.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2504.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2505.                                     $unitsServ $itemInvoice->getSrvUnits();
  2506.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2507.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2508.                                     $subnetoUnit $subneto;
  2509.                                     $subneto $subneto $days $unitsServ $pax;
  2510.                                     break;
  2511.                                 case 4//Creative
  2512.                                     $pax $itemInvoice->getSrvPax();
  2513.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2514.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2515.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2516.                                     $unitsServ $itemInvoice->getSrvUnits();
  2517.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2518.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2519.                                     $subnetoUnit $subneto;
  2520.                                     $subneto $subneto $days $unitsServ $pax;
  2521.                                     break;
  2522.                                 case 5//Cruise
  2523.                                     $pax $itemInvoice->getSrvPax();
  2524.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2525.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days);
  2526.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2527.                                     $unitsServ $itemInvoice->getSrvUnits();
  2528.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2529.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2530.                                     $subnetoUnit $subneto;
  2531.                                     $subneto $subneto $days $unitsServ $pax;
  2532.                                     break;
  2533.                                 case 6//Entertaiment
  2534.                                     $pax $itemInvoice->getSrvPax();
  2535.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2536.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2537.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2538.                                     $unitsServ $itemInvoice->getSrvUnits();
  2539.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2540.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2541.                                     $subnetoUnit $subneto;
  2542.                                     $subneto $subneto $days $unitsServ $pax;
  2543.                                     break;
  2544.                                 case 7// Gifts
  2545.                                     $pax $itemInvoice->getSrvPax();
  2546.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2547.                                     $days 1;
  2548.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2549.                                     $unitsServ $itemInvoice->getSrvUnits();
  2550.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2551.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2552.                                     $subnetoUnit $subneto;
  2553.                                     $subneto $subneto $days $unitsServ $pax;
  2554.                                     break;
  2555.                                 case 8//Guide
  2556.                                     $pax $itemInvoice->getSrvPax();
  2557.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2558.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2559.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2560.                                     $unitsServ $itemInvoice->getSrvUnits();
  2561.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2562.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2563.                                     $subnetoUnit $subneto;
  2564.                                     $subneto $subneto $days $unitsServ $pax;
  2565.                                     break;
  2566.                                 case 9//Itineraries
  2567.                                     $pax $itemInvoice->getSrvPax();
  2568.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2569.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2570.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2571.                                     $unitsServ $itemInvoice->getSrvUnits();
  2572.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2573.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2574.                                     $subnetoUnit $subneto;
  2575.                                     $subneto $subneto $days $unitsServ $pax;
  2576.                                     break;
  2577.                                 case 10//Lounge  -- No Aplica
  2578.                                     break;
  2579.                                 case 11//Menu (Catering)
  2580.                                     $pax $itemInvoice->getSrvPax();
  2581.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2582.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2583.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2584.                                     $unitsServ $itemInvoice->getSrvUnits();
  2585.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2586.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2587.                                     $subnetoUnit $subneto;
  2588.                                     $subneto $subneto $days $unitsServ $pax;
  2589.                                     break;
  2590.                                 case 12//Others
  2591.                                     $pax $itemInvoice->getSrvPax();
  2592.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2593.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2594.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2595.                                     $unitsServ $itemInvoice->getSrvUnits();
  2596.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2597.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2598.                                     $subnetoUnit $subneto;
  2599.                                     $subneto $subneto $days $unitsServ $pax;
  2600.                                     break;
  2601.                                 case 13//Transport
  2602.                                     $pax $itemInvoice->getSrvPax();
  2603.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2604.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2605.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2606.                                     $unitsServ $itemInvoice->getSrvUnits();
  2607.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2608.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2609.                                     $subnetoUnit $subneto;
  2610.                                     $subneto $subneto $days $unitsServ $pax;
  2611.                                     break;
  2612.                                 case 14//Technology
  2613.                                     $pax $itemInvoice->getSrvPax();
  2614.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2615.                                     $days 1;
  2616.                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  2617.                                     $unitsServ $itemInvoice->getSrvUnits();
  2618.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2619.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2620.                                     $subnetoUnit $subneto;
  2621.                                     $subneto $subneto $days $unitsServ $pax;
  2622.                                     break;
  2623.                                 case 15//Assisstant
  2624.                                     $pax $itemInvoice->getSrvPax();
  2625.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2626.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2627.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2628.                                     $unitsServ $itemInvoice->getSrvUnits();
  2629.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2630.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2631.                                     $subnetoUnit $subneto;
  2632.                                     $subneto $subneto $days $unitsServ $pax;
  2633.                                     break;
  2634.                                 case 16//DDR
  2635.                                     $pax $itemInvoice->getSrvPax();
  2636.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2637.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2638.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2639.                                     $unitsServ $itemInvoice->getSrvUnits();
  2640.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2641.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2642.                                     $subnetoUnit $subneto;
  2643.                                     $subneto $subneto $days $unitsServ $pax;
  2644.                                     break;
  2645.                                 case 17//Seguridad
  2646.                                     $pax $itemInvoice->getSrvPax();
  2647.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2648.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2649.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2650.                                     $unitsServ $itemInvoice->getSrvUnits();
  2651.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2652.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2653.                                     $subnetoUnit $subneto;
  2654.                                     $subneto $subneto $days $unitsServ $pax;
  2655.                                     break;
  2656.                                 case 18//WiFi
  2657.                                     $pax $itemInvoice->getSrvPax();
  2658.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2659.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2660.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2661.                                     $unitsServ $itemInvoice->getSrvUnits();
  2662.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2663.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2664.                                     $subnetoUnit $subneto;
  2665.                                     $subneto $subneto $days $unitsServ $pax;
  2666.                                     break;
  2667.                                 case 19//Mobiliario
  2668.                                     $pax $itemInvoice->getSrvPax();
  2669.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2670.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2671.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2672.                                     $unitsServ $itemInvoice->getSrvUnits();
  2673.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2674.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2675.                                     $subnetoUnit $subneto;
  2676.                                     $subneto $subneto $days $unitsServ $pax;
  2677.                                     break;
  2678.                                 case 20//Parking
  2679.                                     $pax $itemInvoice->getSrvPax();
  2680.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2681.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2682.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2683.                                     $unitsServ $itemInvoice->getSrvUnits();
  2684.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2685.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2686.                                     $subnetoUnit $subneto;
  2687.                                     $subneto $subneto $days $unitsServ $pax;
  2688.                                     break;
  2689.                                 case 21//Limpieza
  2690.                                     $pax $itemInvoice->getSrvPax();
  2691.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2692.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2693.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2694.                                     $unitsServ $itemInvoice->getSrvUnits();
  2695.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2696.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2697.                                     $subnetoUnit $subneto;
  2698.                                     $subneto $subneto $days $unitsServ $pax;
  2699.                                     break;
  2700.                                 default: //Others (por default)
  2701.                                     $pax $itemInvoice->getSrvPax();
  2702.                                     if (empty($pax) or $pax == "0") { $pax 1; }
  2703.                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2704.                                     $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2705.                                     $unitsServ $itemInvoice->getSrvUnits();
  2706.                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2707.                                     $subtotal $subtotalService $days $unitsServ $pax;
  2708.                                     $subnetoUnit $subneto;
  2709.                                     $subneto $subneto $days $unitsServ $pax;
  2710.                                     break;
  2711.                             }
  2712.                             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  2713.                             $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  2714.                             $neto round($subneto,2,PHP_ROUND_HALF_UP);
  2715.                             $valorTotalNet $valorTotalNet $neto;
  2716.                             $valorVat $valorVat + ($subtotal $neto);
  2717.                         }
  2718.                     }
  2719.                 }
  2720.             }
  2721.             if (!empty($arrayInvoicedItems)) {
  2722.                 foreach ($arrayInvoicedItems as $itemInvoice) {
  2723.                     if ($itemInvoice->getItemType() == 'PAYMENT') {
  2724.                         //Acumulamos neto e iva para la factura
  2725.                         //$valorTotalNet = $valorTotalNet - $itemInvoice->getPayAmount();    // El pago no puede afectar el neto de la factura
  2726.                     }
  2727.                 }
  2728.             }
  2729.             //FIN: Creamos los items de la factura
  2730.             $valorTotal $valorTotalNet $valorVat;
  2731.             //INICIO: Creamos la factura
  2732.             $newInvoice $em->getRepository(ReservationInvoice::class)->findOneById($id);
  2733.             //FIN: Creamos la factura
  2734.             $data = array();
  2735.             $data $this->baseInvoiceDoneReservation($newInvoice->getReservationId(), $id,'I');
  2736.             $paymentsClient = new ReservationPaymentsClient();
  2737.             $paymentsClient->setReservationId($id);
  2738.             $reservaInv = new ReservationInvoice();
  2739.             $reservaInv->setReservationId($id);
  2740.             $idLounges = array();
  2741.             $loungesBoolToInvoice = array();
  2742.             if (array_key_exists('lounge',$data['datasupplier'])) {
  2743.                 foreach ($data['datasupplier']['lounge'] as $item) {
  2744.                     $idLounges[] = $item['id'];
  2745.                     $loungesBoolToInvoice[] = 1;
  2746.                 }
  2747.                 $idLounges implode(','$idLounges);
  2748.                 $loungesBoolToInvoice implode(','$loungesBoolToInvoice);
  2749.             } else {
  2750.                 $idLounges '0';
  2751.                 $loungesBoolToInvoice '0';
  2752.             }
  2753.             $idPayments = array();
  2754.             $paymentsBoolToInvoice = array();
  2755.             if (array_key_exists('payment',$data['datasupplier'])) {
  2756.                 foreach ($data['datasupplier']['payment'] as $item) {
  2757.                     $idPayments[] = $item['id'];
  2758.                     $paymentsBoolToInvoice[] = 1;
  2759.                 }
  2760.                 $idPayments implode(','$idPayments);
  2761.                 $paymentsBoolToInvoice implode(','$paymentsBoolToInvoice);
  2762.                 // Se han generado dos arreglos, cada uno dividido en 2 strings
  2763.                 // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
  2764.                 // Para manipularlos entre la vista y el JS
  2765.             } else {
  2766.                 $idPayments '0';
  2767.                 $paymentsBoolToInvoice '0';
  2768.             }
  2769.             $allInvoices $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
  2770.             //Es una proforma
  2771.             $proforma $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  2772.             $invoiceIdToRec null;
  2773.             $reservaEquis $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
  2774.             if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
  2775.                 $newInvoice $this->clientDataToInvoice($newInvoice'Client'$reservaEquis->getClient(), $newInvoice->getReservationId());
  2776.             }
  2777.         } else {
  2778.             if ($type == 'R'){
  2779.                 //El tipo es una factura rectificativa
  2780.                 //INICIO: Creamos los items de la factura rectficativa
  2781.                 $arrayInvoicedItems $em->getRepository(ReservationInvoiceRecItems::class)->findByInvoiceRecId($id);
  2782.                 if (!empty($arrayInvoicedItems)) {
  2783.                     foreach ($arrayInvoicedItems as $itemInvoice) {
  2784.                         if ($itemInvoice->getItemType() == 'LOUNGE') {
  2785.                             //Acumulamos neto e iva para la factura rectificativa
  2786.                             $valorTotalNet $valorTotalNet $itemInvoice->getLngServicePrice();
  2787.                             $valorVat $valorVat round(($itemInvoice->getLngServicePrice() * 0.21),2,PHP_ROUND_HALF_UP);
  2788.                         }
  2789.                     }
  2790.                 }
  2791.                 if (!empty($arrayInvoicedItems)) {
  2792.                     foreach ($arrayInvoicedItems as $itemInvoice) {
  2793.                         if ($itemInvoice->getItemType() == 'SERVICE') {
  2794.                             //Acumulamos neto e iva para la factura
  2795.                             if (is_null($itemInvoice->getSrvPrice()) or empty($itemInvoice->getSrvPrice())){
  2796.                                 $subtotal 0;
  2797.                                 $neto 0;
  2798.                                 $subtotalService 0;
  2799.                             } else {
  2800.                                 $subtotalService = (float)$itemInvoice->getSrvPrice();
  2801.                                 $subneto = (float)$itemInvoice->getSrvPrice();
  2802.                                 // Commission
  2803.                                 if ($itemInvoice->getSrvOpCommission()=='1'){
  2804.                                     $subtotalService $subtotalService * (+ ($itemInvoice->getSrvCommission()/100));
  2805.                                     $subneto $subneto  * (+ ($itemInvoice->getSrvCommission()/100));
  2806.                                 } else {
  2807.                                     $subtotalService $subtotalService * (- ($itemInvoice->getSrvCommission()/100));
  2808.                                     $subneto $subneto * (- ($itemInvoice->getSrvCommission()/100));
  2809.                                 }
  2810.                                 // Over
  2811.                                 if ($itemInvoice->getSrvOpOver()=='1'){
  2812.                                     $subtotalService $subtotalService $itemInvoice->getSrvOver();
  2813.                                     $subneto $subneto $itemInvoice->getSrvOver();
  2814.                                 } else {
  2815.                                     $subtotalService $subtotalService $itemInvoice->getSrvOver();
  2816.                                     $subneto $subneto $itemInvoice->getSrvOver();
  2817.                                 }
  2818.                                 // IVA
  2819.                                 if ($itemInvoice->getSrvOpIva()=='1'){
  2820.                                     $subtotalService $subtotalService * (+ ($itemInvoice->getSrvIva()/100));
  2821.                                 } else {
  2822.                                     $subtotalService $itemInvoice->getSrvPrice();
  2823.                                     $subneto = ($subneto 100) / (100 $itemInvoice->getSrvIva());
  2824.                                 }
  2825.                                 switch ($itemInvoice->getSrvServiceCatId()){
  2826.                                     case 1// Alojamiento
  2827.                                         // el numero de noches $numNoches; precio unitario $subneto
  2828.                                         $numNoches = (($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days;
  2829.                                         // La personas no afectan este calculo
  2830.                                         $subtotal $subtotalService $numNoches $itemInvoice->getSrvUnits();
  2831.                                         $subnetoUnit $subneto;
  2832.                                         $subneto $subneto $numNoches $itemInvoice->getSrvUnits();
  2833.                                         break;
  2834.                                     case 2//Actividades
  2835.                                         // El número de personas es considerado en el calculo
  2836.                                         $pax $itemInvoice->getSrvPax();
  2837.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2838.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2839.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2840.                                         $subtotal $subtotalService $days $itemInvoice->getSrvUnits();
  2841.                                         $subnetoUnit $subneto;
  2842.                                         $subneto $subneto $days $itemInvoice->getSrvUnits();
  2843.                                         break;
  2844.                                     case 3// AV
  2845.                                         $pax $itemInvoice->getSrvPax();
  2846.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2847.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2848.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2849.                                         $unitsServ $itemInvoice->getSrvUnits();
  2850.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2851.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2852.                                         $subnetoUnit $subneto;
  2853.                                         $subneto $subneto $days $unitsServ $pax;
  2854.                                         break;
  2855.                                     case 4//Creative
  2856.                                         $pax $itemInvoice->getSrvPax();
  2857.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2858.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2859.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2860.                                         $unitsServ $itemInvoice->getSrvUnits();
  2861.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2862.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2863.                                         $subnetoUnit $subneto;
  2864.                                         $subneto $subneto $days $unitsServ $pax;
  2865.                                         break;
  2866.                                     case 5//Cruise
  2867.                                         $pax $itemInvoice->getSrvPax();
  2868.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2869.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days);
  2870.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2871.                                         $unitsServ $itemInvoice->getSrvUnits();
  2872.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2873.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2874.                                         $subnetoUnit $subneto;
  2875.                                         $subneto $subneto $days $unitsServ $pax;
  2876.                                         break;
  2877.                                     case 6//Entertaiment
  2878.                                         $pax $itemInvoice->getSrvPax();
  2879.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2880.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2881.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2882.                                         $unitsServ $itemInvoice->getSrvUnits();
  2883.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2884.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2885.                                         $subnetoUnit $subneto;
  2886.                                         $subneto $subneto $days $unitsServ $pax;
  2887.                                         break;
  2888.                                     case 7// Gifts
  2889.                                         $pax $itemInvoice->getSrvPax();
  2890.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2891.                                         $days 1;
  2892.                                         $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2893.                                         $unitsServ $itemInvoice->getSrvUnits();
  2894.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2895.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2896.                                         $subnetoUnit $subneto;
  2897.                                         $subneto $subneto $days $unitsServ $pax;
  2898.                                         break;
  2899.                                     case 8//Guide
  2900.                                         $pax $itemInvoice->getSrvPax();
  2901.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2902.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2903.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2904.                                         $unitsServ $itemInvoice->getSrvUnits();
  2905.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2906.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2907.                                         $subnetoUnit $subneto;
  2908.                                         $subneto $subneto $days $unitsServ $pax;
  2909.                                         break;
  2910.                                     case 9//Itineraries
  2911.                                         $pax $itemInvoice->getSrvPax();
  2912.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2913.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2914.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2915.                                         $unitsServ $itemInvoice->getSrvUnits();
  2916.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2917.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2918.                                         $subnetoUnit $subneto;
  2919.                                         $subneto $subneto $days $unitsServ $pax;
  2920.                                         break;
  2921.                                     case 10//Lounge  -- No Aplica
  2922.                                         break;
  2923.                                     case 11//Catering
  2924.                                         $pax $itemInvoice->getSrvPax();
  2925.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2926.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2927.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2928.                                         $unitsServ $itemInvoice->getSrvUnits();
  2929.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2930.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2931.                                         $subnetoUnit $subneto;
  2932.                                         $subneto $subneto $days $unitsServ $pax;
  2933.                                         break;
  2934.                                     case 12//Others
  2935.                                         $pax $itemInvoice->getSrvPax();
  2936.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2937.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2938.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2939.                                         $unitsServ $itemInvoice->getSrvUnits();
  2940.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2941.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2942.                                         $subnetoUnit $subneto;
  2943.                                         $subneto $subneto $days $unitsServ $pax;
  2944.                                         break;
  2945.                                     case 13//Transport
  2946.                                         $pax $itemInvoice->getSrvPax();
  2947.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2948.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2949.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2950.                                         $unitsServ $itemInvoice->getSrvUnits();
  2951.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2952.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2953.                                         $subnetoUnit $subneto;
  2954.                                         $subneto $subneto $days $unitsServ $pax;
  2955.                                         break;
  2956.                                     case 14//Technology
  2957.                                         $pax $itemInvoice->getSrvPax();
  2958.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2959.                                         $days 1;
  2960.                                         $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
  2961.                                         $unitsServ $itemInvoice->getSrvUnits();
  2962.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2963.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2964.                                         $subnetoUnit $subneto;
  2965.                                         $subneto $subneto $days $unitsServ $pax;
  2966.                                         break;
  2967.                                     case 15//Assisstant
  2968.                                         $pax $itemInvoice->getSrvPax();
  2969.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2970.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2971.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2972.                                         $unitsServ $itemInvoice->getSrvUnits();
  2973.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2974.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2975.                                         $subnetoUnit $subneto;
  2976.                                         $subneto $subneto $days $unitsServ $pax;
  2977.                                         break;
  2978.                                     case 16//DDR
  2979.                                         $pax $itemInvoice->getSrvPax();
  2980.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2981.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2982.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2983.                                         $unitsServ $itemInvoice->getSrvUnits();
  2984.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2985.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2986.                                         $subnetoUnit $subneto;
  2987.                                         $subneto $subneto $days $unitsServ $pax;
  2988.                                         break;
  2989.                                     case 17//Seguridad
  2990.                                         $pax $itemInvoice->getSrvPax();
  2991.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  2992.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  2993.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  2994.                                         $unitsServ $itemInvoice->getSrvUnits();
  2995.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  2996.                                         $subtotal $subtotalService $days $unitsServ $pax;
  2997.                                         $subnetoUnit $subneto;
  2998.                                         $subneto $subneto $days $unitsServ $pax;
  2999.                                         break;
  3000.                                     case 18//WiFi
  3001.                                         $pax $itemInvoice->getSrvPax();
  3002.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3003.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  3004.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  3005.                                         $unitsServ $itemInvoice->getSrvUnits();
  3006.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3007.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3008.                                         $subnetoUnit $subneto;
  3009.                                         $subneto $subneto $days $unitsServ $pax;
  3010.                                         break;
  3011.                                     case 19//Mobiliario
  3012.                                         $pax $itemInvoice->getSrvPax();
  3013.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3014.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  3015.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  3016.                                         $unitsServ $itemInvoice->getSrvUnits();
  3017.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3018.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3019.                                         $subnetoUnit $subneto;
  3020.                                         $subneto $subneto $days $unitsServ $pax;
  3021.                                         break;
  3022.                                     case 20//Parking
  3023.                                         $pax $itemInvoice->getSrvPax();
  3024.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3025.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  3026.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  3027.                                         $unitsServ $itemInvoice->getSrvUnits();
  3028.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3029.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3030.                                         $subnetoUnit $subneto;
  3031.                                         $subneto $subneto $days $unitsServ $pax;
  3032.                                         break;
  3033.                                     case 21//Limpieza
  3034.                                         $pax $itemInvoice->getSrvPax();
  3035.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3036.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  3037.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  3038.                                         $unitsServ $itemInvoice->getSrvUnits();
  3039.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3040.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3041.                                         $subnetoUnit $subneto;
  3042.                                         $subneto $subneto $days $unitsServ $pax;
  3043.                                         break;
  3044.                                     default: //Others (por default)
  3045.                                         $pax $itemInvoice->getSrvPax();
  3046.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3047.                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days 1);
  3048.                                         $dateServ = ($days 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
  3049.                                         $unitsServ $itemInvoice->getSrvUnits();
  3050.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3051.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3052.                                         $subnetoUnit $subneto;
  3053.                                         $subneto $subneto $days $unitsServ $pax;
  3054.                                         break;
  3055.                                 }
  3056.                                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  3057.                                 $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  3058.                                 $neto round($subneto,2,PHP_ROUND_HALF_UP);
  3059.                                 $valorTotalNet $valorTotalNet $neto;
  3060.                                 $valorVat $valorVat + ($subtotal $neto);
  3061.                             }
  3062.                         }
  3063.                     }
  3064.                 }
  3065.                 if (!empty($arrayInvoicedItems)) {
  3066.                     foreach ($arrayInvoicedItems as $itemInvoice) {
  3067.                         if ($itemInvoice->getItemType() == 'PAYMENT') {
  3068.                             //Acumulamos neto e iva para la factura
  3069.                             //$valorTotalNet = $valorTotalNet - $itemInvoice->getPayAmount();    // El pago no puede afectar el neto de la factura
  3070.                         }
  3071.                     }
  3072.                 }
  3073.                 //FIN: Creamos los items de la factura
  3074.                 $valorTotal $valorTotalNet $valorVat;
  3075.                 //INICIO: Creamos la factura rectificativa
  3076.                 $newInvoice $em->getRepository(ReservationInvoiceRec::class)->findOneById($id);
  3077.                 //FIN: Creamos la factura rectificativa
  3078.                 $data = array();
  3079.                 $data $this->baseInvoiceDoneReservation($newInvoice->getReservationId(), $id,'R');
  3080.                 $paymentsClient = new ReservationPaymentsClient();
  3081.                 $paymentsClient->setReservationId($id);
  3082.                 $reservaInv = new ReservationInvoice();
  3083.                 $reservaInv->setReservationId($id);
  3084.                 $idLounges = array();
  3085.                 $loungesBoolToInvoice = array();
  3086.                 if (array_key_exists('lounge',$data['datasupplier'])) {
  3087.                     foreach ($data['datasupplier']['lounge'] as $item) {
  3088.                         $idLounges[] = $item['id'];
  3089.                         $loungesBoolToInvoice[] = 1;
  3090.                     }
  3091.                     $idLounges implode(','$idLounges);
  3092.                     $loungesBoolToInvoice implode(','$loungesBoolToInvoice);
  3093.                 } else {
  3094.                     $idLounges '0';
  3095.                     $loungesBoolToInvoice '0';
  3096.                 }
  3097.                 $idPayments = array();
  3098.                 $paymentsBoolToInvoice = array();
  3099.                 if (array_key_exists('payment',$data['datasupplier'])) {
  3100.                     foreach ($data['datasupplier']['payment'] as $item) {
  3101.                         $idPayments[] = $item['id'];
  3102.                         $paymentsBoolToInvoice[] = 1;
  3103.                     }
  3104.                     $idPayments implode(','$idPayments);
  3105.                     $paymentsBoolToInvoice implode(','$paymentsBoolToInvoice);
  3106.                     // Se han generado dos arreglos, cada uno dividido en 2 strings
  3107.                     // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
  3108.                     // Para manipularlos entre la vista y el JS
  3109.                 } else {
  3110.                     $idPayments '0';
  3111.                     $paymentsBoolToInvoice '0';
  3112.                 }
  3113.                 $allInvoices $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
  3114.                 //Es una proforma
  3115.                 $proforma $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  3116.                 $invoiceIdToRec $newInvoice->getInvoiceToRec();
  3117.                 $data['number'] = $data['number']->getNumber();
  3118.                 $data['balance'] = $data['balance'] *(-1);
  3119.                 $reservaEquis $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
  3120.                 if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
  3121.                     $newInvoice $this->clientDataToInvoice($newInvoice'Client'$reservaEquis->getClient(), $newInvoice->getReservationId());
  3122.                 }
  3123.             } else {
  3124.                 // El tipo es una proforma
  3125.                 //INICIO: Creamos los items de la proforma
  3126.                 $arrayInvoicedItems $em->getRepository(ReservationInvoiceProformaItems::class)->findByProformaId($id);
  3127.                 if (!empty($arrayInvoicedItems)) {
  3128.                     foreach ($arrayInvoicedItems as $itemInvoice) {
  3129.                         if ($itemInvoice->getType() == 'LOUNGE') {
  3130.                             $itemPro $em->getRepository(ReservationLoungeSimple::class)->findOneById($itemInvoice->getControlId());
  3131.                             //Acumulamos neto e iva para la factura
  3132.                             $valorTotalNet $valorTotalNet $itemPro->getServicePrice();
  3133.                             $valorVat $valorVat round(($itemPro->getServicePrice() * 0.21),2,PHP_ROUND_HALF_UP);
  3134.                         }
  3135.                     }
  3136.                 }
  3137.                 if (!empty($arrayInvoicedItems)) {
  3138.                     foreach ($arrayInvoicedItems as $itemInvoice) {
  3139.                         if ($itemInvoice->getType() == 'SERVICE') {
  3140.                             $itemPro $em->getRepository(ReservationService::class)->findOneById($itemInvoice->getControlId());
  3141.                             //Acumulamos neto e iva para la factura
  3142.                             if (is_null($itemPro->getPrice()) or empty($itemPro->getPrice())){
  3143.                                 $subtotal 0;
  3144.                                 $neto 0;
  3145.                                 $subtotalService 0;
  3146.                             } else {
  3147.                                 $subtotalService $itemPro->getPrice();
  3148.                                 $subneto $itemPro->getPrice();
  3149.                                 // Commission
  3150.                                 if ($itemPro->getOpCommission()=='1'){
  3151.                                     $subtotalService $subtotalService * (+ ($itemPro->getCommission()/100));
  3152.                                     $subneto $subneto  * (+ ($itemPro->getCommission()/100));
  3153.                                 } else {
  3154.                                     $subtotalService $subtotalService * (- ($itemPro->getCommission()/100));
  3155.                                     $subneto $subneto * (- ($itemPro->getCommission()/100));
  3156.                                 }
  3157.                                 // Over
  3158.                                 if ($itemPro->getOpOver()=='1'){
  3159.                                     $subtotalService $subtotalService $itemPro->getOver();
  3160.                                     $subneto $subneto $itemPro->getOver();
  3161.                                 } else {
  3162.                                     $subtotalService $subtotalService $itemPro->getOver();
  3163.                                     $subneto $subneto $itemPro->getOver();
  3164.                                 }
  3165.                                 // IVA
  3166.                                 if ($itemPro->getOpIva()=='1'){
  3167.                                     $subtotalService $subtotalService * (+ ($itemPro->getIva()/100));
  3168.                                 } else {
  3169.                                     $subtotalService $itemPro->getPrice();
  3170.                                     $subneto = ($subneto 100) / (100 $itemPro->getIva());
  3171.                                 }
  3172.                                 switch ($itemPro->getServiceCatId()){
  3173.                                     case 1// Alojamiento
  3174.                                         // el numero de noches $numNoches; precio unitario $subneto
  3175.                                         $numNoches = (($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days;
  3176.                                         // La personas no afectan este calculo
  3177.                                         $subtotal $subtotalService $numNoches $itemPro->getUnits();
  3178.                                         $subnetoUnit $subneto;
  3179.                                         $subneto $subneto $numNoches $itemPro->getUnits();
  3180.                                         break;
  3181.                                     case 2//Actividades
  3182.                                         // El número de personas es considerado en el calculo
  3183.                                         $pax $itemPro->getPax();
  3184.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3185.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3186.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3187.                                         $subtotal $subtotalService $days $itemPro->getUnits();
  3188.                                         $subnetoUnit $subneto;
  3189.                                         $subneto $subneto $days $itemPro->getUnits();
  3190.                                         break;
  3191.                                     case 3// AV
  3192.                                         $pax $itemPro->getPax();
  3193.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3194.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3195.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3196.                                         $unitsServ $itemPro->getUnits();
  3197.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3198.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3199.                                         $subnetoUnit $subneto;
  3200.                                         $subneto $subneto $days $unitsServ $pax;
  3201.                                         break;
  3202.                                     case 4//Creative
  3203.                                         $pax $itemPro->getPax();
  3204.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3205.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3206.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3207.                                         $unitsServ $itemPro->getUnits();
  3208.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3209.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3210.                                         $subnetoUnit $subneto;
  3211.                                         $subneto $subneto $days $unitsServ $pax;
  3212.                                         break;
  3213.                                     case 5//Cruise
  3214.                                         $pax $itemPro->getPax();
  3215.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3216.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days);
  3217.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3218.                                         $unitsServ $itemPro->getUnits();
  3219.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3220.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3221.                                         $subnetoUnit $subneto;
  3222.                                         $subneto $subneto $days $unitsServ $pax;
  3223.                                         break;
  3224.                                     case 6//Entertaiment
  3225.                                         $pax $itemPro->getPax();
  3226.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3227.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3228.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3229.                                         $unitsServ $itemPro->getUnits();
  3230.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3231.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3232.                                         $subnetoUnit $subneto;
  3233.                                         $subneto $subneto $days $unitsServ $pax;
  3234.                                         break;
  3235.                                     case 7// Gifts
  3236.                                         $pax $itemPro->getPax();
  3237.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3238.                                         $days 1;
  3239.                                         $dateServ = ($itemPro->getDateInAt())->format('d/m/Y');
  3240.                                         $unitsServ $itemPro->getUnits();
  3241.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3242.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3243.                                         $subnetoUnit $subneto;
  3244.                                         $subneto $subneto $days $unitsServ $pax;
  3245.                                         break;
  3246.                                     case 8//Guide
  3247.                                         $pax $itemPro->getPax();
  3248.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3249.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3250.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3251.                                         $unitsServ $itemPro->getUnits();
  3252.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3253.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3254.                                         $subnetoUnit $subneto;
  3255.                                         $subneto $subneto $days $unitsServ $pax;
  3256.                                         break;
  3257.                                     case 9//Itineraries
  3258.                                         $pax $itemPro->getPax();
  3259.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3260.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3261.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3262.                                         $unitsServ $itemPro->getUnits();
  3263.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3264.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3265.                                         $subnetoUnit $subneto;
  3266.                                         $subneto $subneto $days $unitsServ $pax;
  3267.                                         break;
  3268.                                     case 10//Lounge  -- No Aplica
  3269.                                         break;
  3270.                                     case 11//Menu
  3271.                                         $pax $itemPro->getPax();
  3272.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3273.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3274.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3275.                                         $unitsServ $itemPro->getUnits();
  3276.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3277.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3278.                                         $subnetoUnit $subneto;
  3279.                                         $subneto $subneto $days $unitsServ $pax;
  3280.                                         break;
  3281.                                     case 12//Others
  3282.                                         $pax $itemPro->getPax();
  3283.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3284.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3285.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3286.                                         $unitsServ $itemPro->getUnits();
  3287.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3288.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3289.                                         $subnetoUnit $subneto;
  3290.                                         $subneto $subneto $days $unitsServ $pax;
  3291.                                         break;
  3292.                                     case 13//Transport
  3293.                                         $pax $itemPro->getPax();
  3294.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3295.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3296.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3297.                                         $unitsServ $itemPro->getUnits();
  3298.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3299.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3300.                                         $subnetoUnit $subneto;
  3301.                                         $subneto $subneto $days $unitsServ $pax;
  3302.                                         break;
  3303.                                     case 14//Technology
  3304.                                         $pax $itemPro->getPax();
  3305.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3306.                                         $days 1;
  3307.                                         $dateServ = ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y');
  3308.                                         $unitsServ $itemPro->getUnits();
  3309.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3310.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3311.                                         $subnetoUnit $subneto;
  3312.                                         $subneto $subneto $days $unitsServ $pax;
  3313.                                         break;
  3314.                                     case 15//Assisstant
  3315.                                         $pax $itemPro->getPax();
  3316.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3317.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3318.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3319.                                         $unitsServ $itemPro->getUnits();
  3320.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3321.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3322.                                         $subnetoUnit $subneto;
  3323.                                         $subneto $subneto $days $unitsServ $pax;
  3324.                                         break;
  3325.                                     case 16//DDR
  3326.                                         $pax $itemPro->getPax();
  3327.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3328.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3329.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3330.                                         $unitsServ $itemPro->getUnits();
  3331.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3332.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3333.                                         $subnetoUnit $subneto;
  3334.                                         $subneto $subneto $days $unitsServ $pax;
  3335.                                         break;
  3336.                                     case 17//Seguridad
  3337.                                         $pax $itemPro->getPax();
  3338.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3339.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3340.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3341.                                         $unitsServ $itemPro->getUnits();
  3342.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3343.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3344.                                         $subnetoUnit $subneto;
  3345.                                         $subneto $subneto $days $unitsServ $pax;
  3346.                                         break;
  3347.                                     case 18//WiFi
  3348.                                         $pax $itemPro->getPax();
  3349.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3350.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3351.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3352.                                         $unitsServ $itemPro->getUnits();
  3353.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3354.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3355.                                         $subnetoUnit $subneto;
  3356.                                         $subneto $subneto $days $unitsServ $pax;
  3357.                                         break;
  3358.                                     case 19//Mobiliario
  3359.                                         $pax $itemPro->getPax();
  3360.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3361.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3362.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3363.                                         $unitsServ $itemPro->getUnits();
  3364.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3365.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3366.                                         $subnetoUnit $subneto;
  3367.                                         $subneto $subneto $days $unitsServ $pax;
  3368.                                         break;
  3369.                                     case 20//Parking
  3370.                                         $pax $itemPro->getPax();
  3371.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3372.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3373.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3374.                                         $unitsServ $itemPro->getUnits();
  3375.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3376.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3377.                                         $subnetoUnit $subneto;
  3378.                                         $subneto $subneto $days $unitsServ $pax;
  3379.                                         break;
  3380.                                     case 21//Limpieza
  3381.                                         $pax $itemPro->getPax();
  3382.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3383.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3384.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3385.                                         $unitsServ $itemPro->getUnits();
  3386.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3387.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3388.                                         $subnetoUnit $subneto;
  3389.                                         $subneto $subneto $days $unitsServ $pax;
  3390.                                         break;
  3391.                                     default: //Others (por default)
  3392.                                         $pax $itemPro->getPax();
  3393.                                         if (empty($pax) or $pax == "0") { $pax 1; }
  3394.                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days 1);
  3395.                                         $dateServ = ($days 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
  3396.                                         $unitsServ $itemPro->getUnits();
  3397.                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ 1; }
  3398.                                         $subtotal $subtotalService $days $unitsServ $pax;
  3399.                                         $subnetoUnit $subneto;
  3400.                                         $subneto $subneto $days $unitsServ $pax;
  3401.                                         break;
  3402.                                 }
  3403.                                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  3404.                                 $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  3405.                                 $neto round($subneto,2,PHP_ROUND_HALF_UP);
  3406.                                 $valorTotalNet $valorTotalNet $neto;
  3407.                                 $valorVat $valorVat + ($subtotal $neto);
  3408.                             }
  3409.                         }
  3410.                     }
  3411.                 }
  3412.                 if (!empty($arrayInvoicedItems)) {
  3413.                     foreach ($arrayInvoicedItems as $itemInvoice) {
  3414.                         if ($itemInvoice->getType() == 'PAYMENT') {
  3415.                             //Acumulamos neto e iva para la factura
  3416.                             //$valorTotalNet = $valorTotalNet - $itemInvoice->getPayAmount();    // El pago no puede afectar el neto de la factura
  3417.                         }
  3418.                     }
  3419.                 }
  3420.                 //FIN: Creamos los items de la factura
  3421.                 $valorTotal $valorTotalNet $valorVat;
  3422.                 //INICIO: Creamos la factura
  3423.                 $newInvoice $em->getRepository(ReservationProforma::class)->findOneById($id);
  3424.                 //FIN: Creamos la factura
  3425.                 $data = array();
  3426.                 $data $this->baseInvoiceDoneReservation($newInvoice->getReservationId(), $id,'P');
  3427.                 $paymentsClient = new ReservationPaymentsClient();
  3428.                 $paymentsClient->setReservationId($id);
  3429.                 $reservaInv = new ReservationInvoice();
  3430.                 $reservaInv->setReservationId($id);
  3431.                 $idLounges = array();
  3432.                 $loungesBoolToInvoice = array();
  3433.                 if (array_key_exists('lounge',$data['datasupplier'])) {
  3434.                     foreach ($data['datasupplier']['lounge'] as $item) {
  3435.                         $idLounges[] = $item['id'];
  3436.                         $loungesBoolToInvoice[] = 1;
  3437.                     }
  3438.                     $idLounges implode(','$idLounges);
  3439.                     $loungesBoolToInvoice implode(','$loungesBoolToInvoice);
  3440.                 } else {
  3441.                     $idLounges '0';
  3442.                     $loungesBoolToInvoice '0';
  3443.                 }
  3444.                 $idPayments = array();
  3445.                 $paymentsBoolToInvoice = array();
  3446.                 if (array_key_exists('payment',$data['datasupplier'])) {
  3447.                     foreach ($data['datasupplier']['payment'] as $item) {
  3448.                         $idPayments[] = $item['id'];
  3449.                         $paymentsBoolToInvoice[] = 1;
  3450.                     }
  3451.                     $idPayments implode(','$idPayments);
  3452.                     $paymentsBoolToInvoice implode(','$paymentsBoolToInvoice);
  3453.                     // Se han generado dos arreglos, cada uno dividido en 2 strings
  3454.                     // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
  3455.                     // Para manipularlos entre la vista y el JS
  3456.                 } else {
  3457.                     $idPayments '0';
  3458.                     $paymentsBoolToInvoice '0';
  3459.                 }
  3460.                 $allInvoices $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
  3461.                 //Es una proforma
  3462.                 $proforma $em->getRepository(ReservationProforma::class)->findOneById($id);
  3463.                 $invoiceIdToRec null;
  3464.                 $reservaEquis $em->getRepository(Reservation::class)->findOneById($proforma->getReservationId());
  3465. //                if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
  3466.                 if(true){ $newInvoice $this->clientDataToInvoice(null'Client'$reservaEquis->getClient(), $reservaEquis->getId()); }
  3467.             }
  3468.         }
  3469.         return $this->render('MDS/GreenPatioBundle/reservations/services-proforma-print-reservation.html.twig',
  3470.             array(
  3471.                 'id' => $id,
  3472.                 'type' => $data['type'],
  3473.                 'number' => $data['number'],
  3474.                 'invoiceIdToRec' => $invoiceIdToRec,
  3475.                 'prefix' => $data['prefix'],
  3476.                 'date' => $data['date'],
  3477.                 'token' => '',
  3478.                 'company' => $data['company'],
  3479.                 'clients' => $data['clients'],
  3480.                 'datasupplier' => $data['datasupplier'],
  3481.                 'totales_neto' => $data['totales_neto'],
  3482.                 'bases_imponibles' => $data['bases_imponibles'],
  3483.                 'totales' => $data['totales'],
  3484.                 'balance' => $data['balance'],
  3485.                 'currency' => $data['currency'],
  3486.                 'paymentInvoice' => $data['paymentInvoice'],
  3487.                 'clientName' => $newInvoice->getClientName(),
  3488.                 'clientAddress' => $newInvoice->getClientAddress(),
  3489.                 'clientDocument' => $newInvoice->getClientDocument(),
  3490.             )
  3491.         );
  3492.     }
  3493.     /**
  3494.      * @Route("/reservations/invoice/proforma/printnew",  name="reservations_invoice_printnew")
  3495.      */
  3496.     public function detailsProformaPrintNewAction(Request $request){
  3497.         $em $this->getDoctrine()->getManager();
  3498.         // Se genera y muestra en nueva pantalla la nueva proforma
  3499.         $arrayBools = array(
  3500.             'lounge' => null,
  3501.             'service' => null,
  3502.             'payment' => null,
  3503.         );
  3504.         $arrayBools['lounge'] = $request->request->get('lounge_hidden_bool');
  3505.         $arrayBools['service'] = $request->request->get('service_hidden_bool');
  3506.         $arrayBools['payment'] = $request->request->get('payment_hidden_bool');
  3507.         $id $request->request->get('reservation_id');
  3508.         $proformaPrefix $request->request->get('proforma_prefix');
  3509.         //INICIO: Verificamos que el ID de la proforma se exactamente el ultimo
  3510.         $proformaId $request->request->get('proforma_number');
  3511.         $allProformas $em->getRepository(ReservationProforma::class)->findAll();
  3512.         if (!empty($allProformas)){
  3513.             $numberLast end($allProformas)->getId() + 1;
  3514.         } else {
  3515.             // Primer registro de proformas
  3516.             $numberLast 1;
  3517.         }
  3518.         if ($numberLast $proformaId){
  3519.             $proformaId $numberLast;
  3520.         }
  3521.         //FIN: Verificamos que el ID de la proforma se exactamente el ultimo
  3522.         /* Obtengo usuario logueado */
  3523.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  3524.         $user_id $user_logueado->getId();
  3525.         //INICIO: Creamos los items de la proforma
  3526.         if (!empty($arrayBools['lounge'])) {
  3527.             foreach ($arrayBools['lounge'] as $key => $item) {
  3528.                 if ($item == 'true') {
  3529.                     $itemProforma = new ReservationInvoiceProformaItems();
  3530.                     $itemProforma->setControlId($key);
  3531.                     $itemProforma->setProformaId($proformaId);
  3532.                     $itemProforma->setReservationId($id);
  3533.                     $itemProforma->setType('LOUNGE');
  3534.                     $em->persist($itemProforma);
  3535.                     $em->flush();
  3536.                 }
  3537.             }
  3538.         }
  3539.         if (!empty($arrayBools['service'])) {
  3540.             foreach ($arrayBools['service'] as $key => $item) {
  3541.                 if ($item == 'true') {
  3542.                     $itemProforma = new ReservationInvoiceProformaItems();
  3543.                     $itemProforma->setControlId($key);
  3544.                     $itemProforma->setProformaId($proformaId);
  3545.                     $itemProforma->setReservationId($id);
  3546.                     $itemProforma->setType('SERVICE');
  3547.                     $em->persist($itemProforma);
  3548.                     $em->flush();
  3549.                 }
  3550.             }
  3551.         }
  3552.         if (!empty($arrayBools['payment'])) {
  3553.             foreach ($arrayBools['payment'] as $key => $item) {
  3554.                 if ($item == 'true') {
  3555.                     $itemProforma = new ReservationInvoiceProformaItems();
  3556.                     $itemProforma->setControlId($key);
  3557.                     $itemProforma->setProformaId($proformaId);
  3558.                     $itemProforma->setReservationId($id);
  3559.                     $itemProforma->setType('PAYMENT');
  3560.                     $em->persist($itemProforma);
  3561.                     $em->flush();
  3562.                 }
  3563.             }
  3564.         }
  3565.         //FIN: Creamos los items de la proforma
  3566.         //INICIO: Creamos la proforma
  3567.         $newProforma = new ReservationProforma();
  3568.         $newProforma->setDateAt(new DateTime('now'));
  3569.         $newProforma->setPrefix("GP-".date('dmy')."-");
  3570.         $newProforma->setReservationId($id);
  3571.         $newProforma->setCreatedAt(new DateTime('now'));
  3572.         $newProforma->setCreatedId($user_id);
  3573.         $newProforma->setUpdatedAt(new DateTime('now'));
  3574.         $newProforma->setUpdatedId($user_id);
  3575.         $accessKey md5('CR-JDEF'rand() * time());
  3576.         $newProforma->setAccessKey($accessKey);
  3577.         $em->persist($newProforma);
  3578.         $em->flush();
  3579.         //FIN: Creamos la proforma
  3580.         $data = array();
  3581.         $data $this->baseInvoiceSelectedReservation($id$arrayBools'P'.$newProforma->getId());
  3582.         $paymentsClient = new ReservationPaymentsClient();
  3583.         $paymentsClient->setReservationId($id);
  3584.         $form $this->createReservationPaymentsClientForm($paymentsClient);
  3585.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  3586.         $payments $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
  3587.         $services $em->getRepository(ReservationService::class)->findByReservationId($id);
  3588.         $proforma $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  3589.         $reservaInv = new ReservationInvoice();
  3590.         $reservaInv->setReservationId($id);
  3591.         $form1 $this->createReservationInvoiceProformaForm($reservaInv);
  3592.         $idLounges = array();
  3593.         $loungesBoolToInvoice = array();
  3594.         if (array_key_exists('lounge',$data['datasupplier'])) {
  3595.             foreach ($data['datasupplier']['lounge'] as $item) {
  3596.                 $idLounges[] = $item['id'];
  3597.                 $loungesBoolToInvoice[] = 1;
  3598.             }
  3599.             $idLounges implode(','$idLounges);
  3600.             $loungesBoolToInvoice implode(','$loungesBoolToInvoice);
  3601.         } else {
  3602.             $idLounges '0';
  3603.             $loungesBoolToInvoice '0';
  3604.         }
  3605.         $idPayments = array();
  3606.         $paymentsBoolToInvoice = array();
  3607.         if (array_key_exists('payment',$data['datasupplier'])) {
  3608.             foreach ($data['datasupplier']['payment'] as $item) {
  3609.                 $idPayments[] = $item['id'];
  3610.                 $paymentsBoolToInvoice[] = 1;
  3611.             }
  3612.             $idPayments implode(','$idPayments);
  3613.             $paymentsBoolToInvoice implode(','$paymentsBoolToInvoice);
  3614.             // Se han generado dos arreglos, cada uno dividido en 2 strings
  3615.             // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
  3616.             // Para manipularlos entre la vista y el JS
  3617.         } else {
  3618.             $idPayments '0';
  3619.             $paymentsBoolToInvoice '0';
  3620.         }
  3621.         return $this->render('MDS/GreenPatioBundle/reservations/services-proforma-print-reservation.html.twig',
  3622.             array(
  3623.                 'id' => $id,
  3624.                 'idLounges' => $idLounges,
  3625.                 'reserva' => $reserva,
  3626.                 'idPayments' => $idPayments,
  3627.                 'loungesBoolToInvoice' => $loungesBoolToInvoice,
  3628.                 'paymentsBoolToInvoice' => $paymentsBoolToInvoice,
  3629.                 'type' => $data['type'],
  3630.                 'number' => $proformaId,
  3631.                 'prefix' => $proformaPrefix,
  3632.                 'date' => $data['date'],
  3633.                 'token' => $data['token'],
  3634.                 'company' => $data['company'],
  3635.                 'clients' => $data['clients'],
  3636.                 'datasupplier' => $data['datasupplier'],
  3637.                 'currency' => $data['currency'],
  3638.                 'totales_neto' => $data['totales_neto'],
  3639.                 'bases_imponibles' => $data['bases_imponibles'],
  3640.                 'totales' => $data['totales'],
  3641.                 'balance' => $data['balance'],
  3642.                 'paymentInvoice' => $data['paymentInvoice'],
  3643.                 'payments' => $payments,
  3644.                 'user_id' => $user_id,
  3645.                 'form' => $form->createView(),
  3646.                 'form1' => $form1->createView(),
  3647.             )
  3648.         );
  3649.     }
  3650.     private function baseInvoiceSelectedReservation($id$arrayBools$number)
  3651.     {
  3652.         $em $this->getDoctrine()->getManager();
  3653.         $reservation $em->getRepository(Reservation::class)->findOneById($id);
  3654.         $items $em->getRepository(ReservationInvoiceProformaItems::class)->findByReservationId($reservation->getId());
  3655.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  3656.         $client $em->getRepository(Client::class)->findById($reservation->getClient());
  3657.         if (!empty($client)){
  3658.             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  3659.             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  3660.             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  3661.             $client['city'] = $city$client['region'] = $region$client['country'] = $country;
  3662.         } else {
  3663.             $client[0] = new Client();
  3664.             $client[0]->setName('');
  3665.             $client[0]->setTitle('');
  3666.             $client[0]->setIdDocument('');
  3667.             $client[0]->setPopulation('');
  3668.             $client[0]->setRegion('');
  3669.             $client[0]->setCountry('');
  3670.         }
  3671.         // Acumuladores de los calculos
  3672.         $totales_neto_all 0;
  3673.         $data_iva = array(
  3674.             'iva' => 21,
  3675.             'ivaMontoVeintiUno' => 0,
  3676.             'ivaMontoDiez' => 0,
  3677.             'ivaMontoCero' => 0,
  3678.         );
  3679.         //INICIO: Determinamos el numero de factura o proforma
  3680.         if (substr($number,0,1) == 'I'){
  3681.             // Es una Factura
  3682.             $numberInvoiceOrProforma substr($number,1);
  3683.             $number $numberInvoiceOrProforma;
  3684.             $number $em->getRepository(ReservationInvoice::class)->findOneById($number);
  3685.             $number $number->getNumber();
  3686.             $type 'Invoice';
  3687.         } else {
  3688.             // Es una Proforma
  3689.             $numberInvoiceOrProforma substr($number,1);
  3690.             $number $numberInvoiceOrProforma;
  3691.             $number $em->getRepository(ReservationProforma::class)->findOneById($number);
  3692.             $number $number->getPrefix().$number->getReservationId();
  3693.             $type 'Proforma';
  3694.         }
  3695.         //FIN: Determinamos el numero de factura o proforma
  3696.         // Buscamos las salas reservadas, pagos y servicios para el evento
  3697.         $arrayItems = array();
  3698.         $reservationLounges = array();
  3699.         if (!empty($arrayBools['lounge'])) {
  3700.             foreach ($arrayBools['lounge'] as $key => $item) {
  3701.                 if ($item == 'true') { $reservationLounges[] = $em->getRepository(ReservationLoungeSimple::class)->findOneById($key); }
  3702.             }
  3703.         }
  3704.         $payments = array();
  3705.         if (!empty($arrayBools['payment'])) {
  3706.             foreach ($arrayBools['payment'] as $key => $item) {
  3707.                 if ($item == 'true') { $payments[] = $em->getRepository(ReservationPaymentsClient::class)->findOneById($key); }
  3708.             }
  3709.         }
  3710.         $services = array();
  3711.         if (!empty($arrayBools['service'])) {
  3712.             foreach ($arrayBools['service'] as $key => $item) {
  3713.                 if ($item == 'true') { $services[] = $em->getRepository(ReservationService::class)->findOneById($key); }
  3714.             }
  3715.         }
  3716.         $data_supplier = array();
  3717.         $i 0;
  3718.         $iva '21';            // Esteban Rincon: "Por Ley de localización del impuesto, siempre será un 21%". La ley ha cambiado.
  3719.         $pax '-';
  3720.         $qty '1';
  3721.         $lounge = array(
  3722.             'neto' => 0,
  3723.             'sumSubT' => 0,
  3724.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  3725.         $service = array(
  3726.             'neto' => 0,
  3727.             'sumSubT' => 0,
  3728.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  3729.         foreach ($reservationLounges as $item){
  3730.             if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
  3731.                 $subtotal 0;
  3732.                 $neto 0;
  3733.                 $subnetoMounting 0;
  3734.                 $subtotalLounge 0;
  3735.                 $subnetoRemoval 0;
  3736.             } else {
  3737. //                if (!empty($item->getMountingPrice()) and ($item->getMountingPrice() != 0 )){
  3738. //                    $subtotalMounting = $item->getMountingPrice() * 1.21;
  3739. //                    $subnetoMounting = $item->getMountingPrice();
  3740. //                } else {
  3741. //                    $subtotalMounting = 0;
  3742. //                    $subnetoMounting = 0;
  3743. //                }
  3744.                 $subtotalLounge $item->getServicePrice() * (+ ($item->getIva() / 100));
  3745.                 $subneto $item->getServicePrice();
  3746. //                if (!empty($item->getRemovalPrice()) and ($item->getRemovalPrice() != 0 )){
  3747. //                    $subtotalRemoval = $item->getRemovalPrice() * 1.21;
  3748. //                    $subnetoRemoval = $item->getRemovalPrice();
  3749. //                } else {
  3750. //                    $subtotalRemoval = 0;
  3751. //                    $subnetoRemoval = 0;
  3752. //                }
  3753.                 $subtotal =  $subtotalLounge;
  3754.                 $neto =  $subneto;
  3755.                 $iva $item->getIva();
  3756.                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  3757.                 $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  3758.                 $neto round($neto,2,PHP_ROUND_HALF_UP);
  3759.                 $arrayItems[] = array(
  3760.                     'type' => 'Lounge',
  3761.                     'name' => $item->getLoungeName(),
  3762.                     'amount' => $neto,
  3763.                     'iva' => $iva,
  3764.                     'total' => $subtotal,
  3765.                 );
  3766.             }
  3767.             // Acumula netos totales e IVA
  3768.             $totales_neto_all $totales_neto_all $neto;
  3769. //            $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21);
  3770.             switch ($iva){
  3771.                 case 21$data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto 0.21); break;
  3772.                 case 10$data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto 0.1); break;
  3773.                 case 0: break;
  3774.                 default: $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto 0.21); break;
  3775.             }
  3776.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  3777.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  3778.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  3779.             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
  3780.             // Acumula netos totales e IVA
  3781.             $lounge['neto'] = $lounge['neto'] + $neto;
  3782.             $lounge['sumSubT'] = $lounge['sumSubT'] + $subtotal;
  3783.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  3784.             $lounge['neto'] = round($lounge['neto'],2,PHP_ROUND_HALF_UP);
  3785.             $lounge['sumSubT'] = round($lounge['sumSubT'],2,PHP_ROUND_HALF_UP);
  3786.             $data_supplier['lounge'][$i] = array (
  3787.                 'id' => $item->getId(),
  3788.                 'loungeName' => $item->getLoungeName(),
  3789.                 'idLounge' => $item->getIdLounge(),
  3790.                 'dateStart' => $item->getDateStart(),
  3791.                 'dateEnd' => $item->getDateEnd(),
  3792.                 'servicePrice' => $item->getServicePrice(),
  3793.                 'subtotalLounge' => $subtotalLounge,
  3794.                 'iva' => $iva,
  3795.                 'pax' => $pax,
  3796.                 'qty' => $qty,
  3797.                 'type' => $item->getType(),
  3798.                 'subtotal' => $subtotal,
  3799.             );
  3800.             $i++;
  3801.         }
  3802.         $data_supplier['loungeSubTotal'] = array(
  3803.             'neto' => $lounge['neto'],
  3804.             'sumSubT' => $lounge['sumSubT'],
  3805.         );
  3806.         $payment = array(
  3807.             'neto' => 0,
  3808.             'sumSubT' => 0,
  3809.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  3810.         $i 0;
  3811.         foreach ($payments as $item){
  3812.             $payment['neto'] = $payment['neto'] + ($item->getAmount()*(-1));
  3813.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  3814.             $payment['neto'] = round($payment['neto'],2,PHP_ROUND_HALF_UP);
  3815.             $payment['sumSubT'] = $payment['sumSubT'] + ($item->getAmountTotal()*(-1));
  3816.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  3817.             $payment['sumSubT'] = round($payment['sumSubT'],2,PHP_ROUND_HALF_UP);
  3818.             $data_supplier['payment'][$i] = array (
  3819.                 'id' => $item->getId(),
  3820.                 'amount' => $item->getAmount()*(-1),
  3821.                 'amountTotal' => $item->getAmountTotal()*(-1),
  3822.                 'vat' => $item->getVat(),
  3823.                 'datePayAt' => $item->getDatePayAt(),
  3824.                 'wayToPay' => $item->getWayToPay(),
  3825.             );
  3826.             $arrayItems[] = array(
  3827.                 'type' => 'Payment',
  3828.                 'name' => $item->getWayToPay(),
  3829.                 'amount' => $item->getAmount()*(-1),
  3830.                 'total' => $item->getAmountTotal()*(-1),
  3831.                 'iva' => $item->getVat(),
  3832. //                    'iva' => '',
  3833. //                    'total' => $item->getAmount(),
  3834.             );
  3835.             // Acumula netos totales e IVA
  3836.             $totales_neto_all $totales_neto_all + ($item->getAmount()*(-1));
  3837.             $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + (($item->getAmount()*(-1)) * 0.21);
  3838.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  3839.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  3840.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  3841.             // Acumula netos totales e IVA
  3842.             $i++;
  3843.         }
  3844.         if (!empty($payments)) {
  3845.             $data_supplier['paymentSubTotal'] = array(
  3846.                 'neto' => $payment['neto'],
  3847.                 'sumSubT' => $payment['sumSubT'],
  3848.             );
  3849.         }
  3850.         foreach ($services as $item) {
  3851.             if (is_null($item->getPrice()) || empty($item->getPrice())) {
  3852.                 $subtotal 0;
  3853.                 $neto 0;
  3854.                 $subtotalService 0;
  3855.             } else {
  3856.                 // Inicialización de subtotalService y subneto
  3857.                 $subtotalService $item->getPrice();
  3858.                 $subneto $item->getPrice();
  3859.         
  3860.                 // Comisión
  3861.                 $commissionFactor = ($item->getOpCommission() === '1'
  3862.                     ? + ($item->getCommission() / 100
  3863.                     : - ($item->getCommission() / 100);
  3864.                 $subtotalService *= $commissionFactor;
  3865.                 $subneto *= $commissionFactor;
  3866.         
  3867.                 // Cálculos comunes
  3868.                 $pax $item->getPax();
  3869.                 if (empty($pax) || $pax == "0") { 
  3870.                     $pax 1
  3871.                 }
  3872.         
  3873.                 $unitsServ $item->getUnits();
  3874.                 if (empty($unitsServ) || $unitsServ == "0") { 
  3875.                     $unitsServ 1
  3876.                 }
  3877.         
  3878.                 // Mapeo de serviceCatId a serviceType
  3879.                 $serviceTypes = [
  3880.                     => 'Hotel',
  3881.                     => 'Actividad',
  3882.                     => 'AV',
  3883.                     => 'Creativo',
  3884.                     => 'Crucero',
  3885.                     => 'Entretenimiento',
  3886.                     => 'Regalos',
  3887.                     => 'Guía',
  3888.                     => 'Itinerarios',
  3889.                     11 => 'Catering',
  3890.                     12 => 'Otros',
  3891.                     13 => 'Transporte',
  3892.                     14 => 'Tecnología',
  3893.                     15 => 'Asistente',
  3894.                     16 => 'DDR',
  3895.                     17 => 'Seguridad',
  3896.                     18 => 'WiFi',
  3897.                     19 => 'Mobiliario',
  3898.                     20 => 'Parking',
  3899.                     21 => 'Limpieza',
  3900.                 ];
  3901.         
  3902.                 $serviceCatId $item->getServiceCatId();
  3903.                 $serviceType = isset($serviceTypes[$serviceCatId]) ? $serviceTypes[$serviceCatId] : 'Otros';
  3904.         
  3905.                 // Cálculo de días y fecha
  3906.                 $dateIn $item->getDateInAt();
  3907.                 $dateOut $item->getDateOutAt();
  3908.                 $diffDays $dateIn->diff($dateOut)->days;
  3909.                 $days = ($serviceCatId === || $serviceCatId === 5) ? $diffDays $diffDays 1;
  3910.         
  3911.                 $dateServ = ($days 1
  3912.                     ? $dateIn->format('d/m/Y') . ' - ' $dateOut->format('d/m/Y'
  3913.                     : $dateIn->format('d/m/Y');
  3914.         
  3915.                 // Cálculo del subtotal y subneto
  3916.                 $subtotal $subtotalService $days $unitsServ $pax;
  3917.                 $subnetoUnit $subneto;
  3918.                 $subneto $subneto $days $unitsServ $pax;
  3919.                 // Over
  3920.                 $over $item->getOver();
  3921.                 $overFactor = ($item->getOpOver() === '1') ? : -1;
  3922.                 $subtotal += $overFactor $over;
  3923.                 $subneto += $overFactor $over;
  3924.         
  3925.                 // Asignación al arreglo data_supplier
  3926.                 $data_supplier['service'][$i] = [
  3927.                     'id' => $item->getId(),
  3928.                     'serviceCatId' => $serviceCatId,
  3929.                     'serviceName' => $item->getName(),
  3930.                     'serviceType' => $serviceType,
  3931.                     'date' => $dateServ,
  3932.                     'qty' => $unitsServ,
  3933.                     'iva' => $item->getIva(),
  3934.                     'pax' => $item->getPax(),
  3935.                     'precioUnit' => $subnetoUnit,
  3936.                     'subneto' => $subneto,
  3937.                     'subtotal' => round($subtotal2PHP_ROUND_HALF_UP),
  3938.                 ];
  3939.         
  3940.                 // Acumulación en arrayItems
  3941.                 $arrayItems[] = [
  3942.                     'type' => 'Service',
  3943.                     'name' => $item->getName(),
  3944.                     'amount' => round($subneto2PHP_ROUND_HALF_UP),
  3945.                     'iva' => $item->getIva(),
  3946.                     'total' => round($subtotal2PHP_ROUND_HALF_UP),
  3947.                 ];
  3948.         
  3949.                 // Manejo de IVA
  3950.                 switch ($item->getIva()) {
  3951.                     case 21:
  3952.                         $data_iva['ivaMontoVeintiUno'] += round($subneto * ($item->getIva() / 100), 2PHP_ROUND_HALF_UP);
  3953.                         break;
  3954.         
  3955.                     case 10:
  3956.                         $data_iva['ivaMontoDiez'] += round($subneto * ($item->getIva() / 100), 2PHP_ROUND_HALF_UP);
  3957.                         break;
  3958.         
  3959.                     case 0:
  3960.                     default:
  3961.                         // No se acumula IVA
  3962.                         break;
  3963.                 }
  3964.         
  3965.                 // Acumulación de totales
  3966.                 $totales_neto_all += $subneto;
  3967.                 $totales_neto_all round($totales_neto_all2PHP_ROUND_HALF_UP);
  3968.                 $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'], 2PHP_ROUND_HALF_UP);
  3969.                 $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'], 2PHP_ROUND_HALF_UP);
  3970.         
  3971.                 $service['neto'] += round($subneto2PHP_ROUND_HALF_UP);
  3972.                 $service['sumSubT'] += round($subtotal2PHP_ROUND_HALF_UP);
  3973.             }
  3974.         
  3975.             $i++;
  3976.         }        
  3977.         $data_supplier['serviceSubTotal'] = array(
  3978.             'neto' => $service['neto'],
  3979.             'sumSubT' => $service['sumSubT'],
  3980.         );
  3981.         $currency '€';
  3982.         $totales_total $totales_neto_all $data_iva['ivaMontoVeintiUno'] + $data_iva['ivaMontoDiez'];
  3983.         if (!empty($payments)) {
  3984.             $amount_pay $data_supplier['paymentSubTotal']['sumSubT'];
  3985.         } else {
  3986.             $amount_pay 0;
  3987.         }
  3988.         $totales_all $totales_total $amount_pay;
  3989.         if ($type == 'Invoice'){
  3990.             $em->clear();   // sin este clear se producia error al guardar
  3991.             $newInvoice $em->getRepository(ReservationInvoice::class)->findOneById($numberInvoiceOrProforma);
  3992.             $newInvoice->setBalance($totales_all);
  3993.             $em->persist($newInvoice);
  3994.             $em->flush();
  3995.         }
  3996.         $data = array(
  3997.             'id' => $id,
  3998.             'type' => $type,
  3999.             'number' => $number,
  4000.             'prefix' => 'GPF-'.(new DateTime('now'))->format('dmy').'-',
  4001.             'date' => new DateTime('now'),
  4002.             'reservation' => $reservation,
  4003.             'token' => $reservation->getAccessKey(),
  4004.             'company' => $company,
  4005.             'clients' => $client,
  4006.             'arrayItems' => $arrayItems,
  4007.             'datasupplier' => $data_supplier,
  4008.             'currency' => $currency,
  4009.             'totales_neto' => $totales_neto_all,
  4010.             'bases_imponibles' => $data_iva,
  4011.             'totales' => $totales_total,
  4012.             'balance' => $totales_all,
  4013.             'paymentInvoice' => $amount_pay,
  4014.         );
  4015.         return $data;
  4016.     }
  4017.     private function baseInvoiceDoneReservation($reservationId$invoiceId$typeBase)
  4018.     {
  4019.         $em $this->getDoctrine()->getManager();
  4020.         $reservation $em->getRepository(Reservation::class)->findOneById($reservationId);
  4021.         $dateDocument null;                                                                           //Fecha final del documento
  4022.         if (($typeBase == 'I') or ($typeBase == 'P')) {
  4023.             if ($typeBase == 'I') {
  4024.                 $items $em->getRepository(ReservationInvoiceItems::class)->findBy(array('reservationId' => $reservationId'invoiceId' => $invoiceId));
  4025.             } else {
  4026.                 // Es factura ni proforma
  4027.                 $items $em->getRepository(ReservationInvoiceProformaItems::class)->findBy(array('reservationId' => $reservationId'proformaId' => $invoiceId));
  4028.             }
  4029.         } else {
  4030.             // No es factura ni proforma, es una rectificativa
  4031.             $items $em->getRepository(ReservationInvoiceRecItems::class)->findBy(array('reservationId' => $reservationId'invoiceRecId' => $invoiceId));
  4032.         }
  4033.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  4034.         $client $em->getRepository(Client::class)->findById($reservation->getClient());
  4035.         if (!empty($client)){
  4036.             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  4037.             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  4038.             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  4039.             $client['city'] = $city$client['region'] = $region$client['country'] = $country;
  4040.         } else {
  4041.             $client[0] = new Client();
  4042.             $client[0]->setName('');
  4043.             $client[0]->setTitle('');
  4044.             $client[0]->setIdDocument('');
  4045.             $client[0]->setPopulation('');
  4046.             $client[0]->setRegion('');
  4047.             $client[0]->setCountry('');
  4048.         }
  4049.         // Acumuladores de los calculos
  4050.         $totales_neto_all 0;
  4051.         $data_iva = array(
  4052.             'iva' => 21,
  4053.             'ivaMontoVeintiUno' => 0,
  4054.             'ivaMontoDiez' => 0,
  4055.             'ivaMontoCero' => 0,
  4056.         );
  4057.         //INICIO: Determinamos el numero de factura o proforma
  4058.         if ($typeBase == 'I'){
  4059.             // Es una Factura
  4060.             $number $em->getRepository(ReservationInvoice::class)->findOneById($invoiceId);
  4061.             $dateDocument $number->getDateAt();
  4062.             $number $number->getNumber();
  4063.             $type 'Invoice';
  4064.         } else {
  4065.             if ($typeBase == 'R'){
  4066.                 // Es una factura rectificativa
  4067.                 $number $em->getRepository(ReservationInvoiceRec::class)->findOneById($invoiceId);
  4068.                 $dateDocument $number->getDateAt();
  4069.                 $type 'Invoice Rec';
  4070.             } else {
  4071.                 // Es una Proforma
  4072.                 $number $invoiceId;
  4073.                 $type 'Proforma';
  4074.             }
  4075.         }
  4076.         //FIN: Determinamos el numero de factura o proforma
  4077.         // Buscamos las salas reservadas, pagos y servicios para el evento
  4078.         $arrayItems = array();
  4079.         $reservationLounges = array();
  4080.         $payments = array();
  4081.         $services = array();
  4082.         if (!empty($items)) {
  4083.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  4084.                 foreach ($items as $item) {
  4085.                     switch ($item->getItemType()) {
  4086.                         case 'LOUNGE'// Salon
  4087.                             $reservationLounges[] = $item;
  4088.                             break;
  4089.                         case 'PAYMENT'// Pago
  4090.                             $payments[] = $item;
  4091.                             break;
  4092.                         case 'SERVICE'// Servicio
  4093.                             $services[] = $item;
  4094.                             break;
  4095.                         default: break;
  4096.                     }
  4097.                 }
  4098.             } else {
  4099.                 // Es una proforma
  4100.                 foreach ($items as $item) {
  4101.                     switch ($item->getType()) {
  4102.                         case 'LOUNGE'// Salon
  4103.                             $loungePro $em->getRepository(ReservationLoungeSimple::class)->findOneById($item->getControlId());
  4104.                             if (!empty($loungePro)) {
  4105.                                 $reservationLounges[] = $loungePro;
  4106.                             }
  4107.                             break;
  4108.                         case 'PAYMENT'// Pago
  4109.                             $paymentPro $em->getRepository(ReservationPaymentsClient::class)->findOneById($item->getControlId());
  4110.                             if (!empty($paymentPro)) {
  4111.                                 $payments[] = $paymentPro;
  4112.                             }
  4113.                             break;
  4114.                         case 'SERVICE'// Servicio
  4115.                             $servicePro $em->getRepository(ReservationService::class)->findOneById($item->getControlId());
  4116.                             if (!empty($servicePro)) {
  4117.                                 $services[] = $servicePro;
  4118.                             }
  4119.                             break;
  4120.                         default: break;
  4121.                     }
  4122.                 }
  4123.             }
  4124.         }
  4125.         $data_supplier = array();
  4126.         $i 0;
  4127.         $pax '-';
  4128.         $qty '1';
  4129.         $lounge = array(
  4130.             'neto' => 0,
  4131.             'sumSubT' => 0,
  4132.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  4133.         $service = array(
  4134.             'neto' => 0,
  4135.             'sumSubT' => 0,
  4136.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  4137.         foreach ($reservationLounges as $item){
  4138.             if (($typeBase == 'I') or $typeBase == 'R') {
  4139.                 $iva $item->getLngIva();
  4140.             } else {
  4141.                 $iva $item->getIva();
  4142.             }
  4143.             if(is_null($iva) || (empty($iva) && !is_numeric($iva))){
  4144.                 $iva 21;
  4145.             }
  4146.             
  4147.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  4148.                 if (is_null($item->getLngServicePrice()) or empty($item->getLngServicePrice())){
  4149.                     $subtotal 0;
  4150.                     $neto 0;
  4151.                     $subnetoMounting 0;
  4152.                     $subtotalLounge 0;
  4153.                     $subnetoRemoval 0;
  4154.                 } else {
  4155. //                    $subtotalLounge = $item->getLngServicePrice() * 1.21;
  4156.                     $subtotalLounge $item->getLngServicePrice() * (+ ($iva 100));
  4157.                     $subneto $item->getLngServicePrice();
  4158.                     $subtotal =  $subtotalLounge;
  4159.                     $neto =  $subneto;
  4160.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  4161.                     $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  4162.                     $neto round($neto,2,PHP_ROUND_HALF_UP);
  4163.                     $arrayItems[] = array(
  4164.                         'type' => 'Lounge',
  4165.                         'name' => $item->getLngLoungeName(),
  4166.                         'amount' => $neto,
  4167.                         'iva' => $iva,
  4168.                         'total' => $subtotal,
  4169.                     );
  4170.                 }
  4171.             } else {
  4172.                 // Es proforma
  4173.                 if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
  4174.                     $subtotal 0;
  4175.                     $neto 0;
  4176.                     $subnetoMounting 0;
  4177.                     $subtotalLounge 0;
  4178.                     $subnetoRemoval 0;
  4179.                 } else {
  4180. //                    $subtotalLounge = $item->getServicePrice() * 1.21;
  4181.                     $subtotalLounge $item->getServicePrice() * (+ ($iva 100));
  4182.                     $subneto $item->getServicePrice();
  4183.                     $subtotal =  $subtotalLounge;
  4184.                     $neto =  $subneto;
  4185.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
  4186.                     $subtotal round($subtotal,2,PHP_ROUND_HALF_UP);
  4187.                     $neto round($neto,2,PHP_ROUND_HALF_UP);
  4188.                     $arrayItems[] = array(
  4189.                         'type' => 'Lounge',
  4190.                         'name' => $item->getLoungeName(),
  4191.                         'amount' => $neto,
  4192.                         'iva' => $iva,
  4193.                         'total' => $subtotal,
  4194.                     );
  4195.                 }
  4196.             }
  4197.             // Acumula netos totales e IVA
  4198.             $totales_neto_all $totales_neto_all $neto;
  4199. //            $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21);
  4200.             switch ($iva){
  4201.                 case 21$data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto 0.21); break;
  4202.                 case 10$data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto 0.1); break;
  4203.                 case 0: break;
  4204.                 default: $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto 0.21); break;
  4205.             }
  4206.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  4207.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  4208.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  4209.             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
  4210.             // Acumula netos totales e IVA
  4211.             $lounge['neto'] = $lounge['neto'] + $neto;
  4212.             $lounge['sumSubT'] = $lounge['sumSubT'] + $subtotal;
  4213.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  4214.             $lounge['neto'] = round($lounge['neto'],2,PHP_ROUND_HALF_UP);
  4215.             $lounge['sumSubT'] = round($lounge['sumSubT'],2,PHP_ROUND_HALF_UP);
  4216.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  4217.                 $data_supplier['lounge'][$i] = array(
  4218.                     'id' => $item->getId(),
  4219.                     'loungeName' => $item->getLngLoungeName(),
  4220.                     'idLounge' => $item->getLngIdLounge(),
  4221.                     'dateStart' => $item->getLngDateStart(),
  4222.                     'dateEnd' => $item->getLngDateEnd(),
  4223.                     'servicePrice' => $item->getLngServicePrice(),
  4224.                     'subtotalLounge' => $subtotalLounge,
  4225.                     'iva' => $iva,
  4226.                     'pax' => $pax,
  4227.                     'qty' => $qty,
  4228.                     'type' => $item->getLngType(),
  4229.                     'subtotal' => $subtotal,
  4230.                 );
  4231.             } else {
  4232.                 // Es proforma
  4233.                 $data_supplier['lounge'][$i] = array(
  4234.                     'id' => $item->getId(),
  4235.                     'loungeName' => $item->getLoungeName(),
  4236.                     'idLounge' => $item->getIdLounge(),
  4237.                     'dateStart' => $item->getDateStart(),
  4238.                     'dateEnd' => $item->getDateEnd(),
  4239.                     'servicePrice' => $item->getServicePrice(),
  4240.                     'subtotalLounge' => $subtotalLounge,
  4241.                     'iva' => $iva,
  4242.                     'pax' => $pax,
  4243.                     'qty' => $qty,
  4244.                     'type' => $item->getType(),
  4245.                     'subtotal' => $subtotal,
  4246.                 );
  4247.             }
  4248.             $i++;
  4249.         }
  4250.         $data_supplier['loungeSubTotal'] = array(
  4251.             'neto' => $lounge['neto'],
  4252.             'sumSubT' => $lounge['sumSubT'],
  4253.         );
  4254.         $payment = array(
  4255.             'neto' => 0,
  4256.             'sumSubT' => 0,
  4257.         ); // Acumula sumatoria de netos y sumantoria de subtotales
  4258.         $i 0;
  4259.         foreach ($payments as $item){
  4260.             if (($typeBase == 'I') or ($typeBase == 'R')) {
  4261.                 $ivaPayment $item->getPayVat();
  4262.                 if(is_null($ivaPayment) || (empty($ivaPayment) && !is_numeric($ivaPayment))){
  4263.                     $ivaPayment 21;
  4264.                 }
  4265.                 if ($typeBase == 'I') {
  4266.                     $payment['neto'] = $payment['neto'] + ($item->getPayAmount() * (-1));
  4267.                     $payment['sumSubT'] = $payment['sumSubT'] + ($item->getPayAmountTotal() * (-1));
  4268.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  4269.                     $payment['sumSubT'] = round($payment['sumSubT'], 2PHP_ROUND_HALF_UP);
  4270.                     $payment['neto'] = round($payment['neto'], 2PHP_ROUND_HALF_UP);
  4271.                     // Acumula netos totales e IVA
  4272.                     $totales_neto_all $totales_neto_all + ($item->getPayAmount() * (-1));
  4273.                     $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($item->getPayAmount() * (-($ivaPayment 100)));
  4274.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  4275.                     $totales_neto_all round($totales_neto_all2PHP_ROUND_HALF_UP);
  4276.                     $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'], 2PHP_ROUND_HALF_UP);
  4277.                     // Acumula netos totales e IVA
  4278.                     $data_supplier['payment'][$i] = array(
  4279.                         'id' => $item->getId(),
  4280.                         'amount' => $item->getPayAmount() * (-1),
  4281.                         'amountTotal' => $item->getPayAmountTotal() * (-1),
  4282.                         'vat' => $item->getPayVat(),
  4283.                         'datePayAt' => $item->getPayDatePayAt(),
  4284.                         'wayToPay' => $item->getPayWayToPay(),
  4285.                     );
  4286.                     $arrayItems[] = array(
  4287.                         'type' => 'Payment',
  4288.                         'name' => $item->getPayWayToPay(),
  4289.                         'amount' => $item->getPayAmount() * (-1),
  4290.                         'total' => $item->getPayAmountTotal() * (-1),
  4291.                         'iva' => $item->getPayVat(),
  4292. //                    'iva' => '',
  4293. //                    'total' => $item->getPayAmount(),
  4294.                     );
  4295.                 } else {
  4296.                     //Es una rectificativa
  4297.                     $payment['neto'] = $payment['neto'] + ($item->getPayAmount());
  4298.                     $payment['sumSubT'] = $payment['sumSubT'] + ($item->getPayAmountTotal());
  4299.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  4300.                     $payment['sumSubT'] = round($payment['sumSubT'], 2PHP_ROUND_HALF_UP);
  4301.                     $payment['neto'] = round($payment['neto'], 2PHP_ROUND_HALF_UP);
  4302.                     // Acumula netos totales e IVA
  4303.                     $totales_neto_all $totales_neto_all + ($item->getPayAmount());
  4304.                     $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($item->getPayAmount()*($ivaPayment 100));
  4305.                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  4306.                     $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  4307.                     $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  4308.                     // Acumula netos totales e IVA
  4309.                     $data_supplier['payment'][$i] = array(
  4310.                         'id' => $item->getId(),
  4311.                         'amount' => $item->getPayAmount(),
  4312.                         'amountTotal' => $item->getPayAmountTotal(),
  4313.                         'vat' => $item->getPayVat(),
  4314.                         'datePayAt' => $item->getPayDatePayAt(),
  4315.                         'wayToPay' => $item->getPayWayToPay(),
  4316.                     );
  4317.                     $arrayItems[] = array(
  4318.                         'type' => 'Payment',
  4319.                         'name' => $item->getPayWayToPay(),
  4320.                         'amount' => $item->getPayAmount(),
  4321.                         'total' => $item->getPayAmountTotal(),
  4322.                         'iva' => $item->getPayVat(),
  4323. //                    'iva' => '',
  4324. //                    'total' => $item->getPayAmount(),
  4325.                     );
  4326.                 }
  4327.             } else {
  4328.                 $ivaPayment $item->getVat();
  4329.                 if(is_null($ivaPayment) || (empty($ivaPayment) && !is_numeric($ivaPayment))){
  4330.                     $ivaPayment 21;
  4331.                 }
  4332.                 // Es una proforma
  4333.                 $payment['neto'] = $payment['neto'] + ($item->getAmount()*(-1));
  4334.                 $payment['sumSubT'] = $payment['sumSubT'] + $item->getAmountTotal()*(-1);
  4335.                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  4336.                 $payment['sumSubT'] = round($payment['sumSubT'], 2PHP_ROUND_HALF_UP);
  4337.                 $payment['neto'] = round($payment['neto'], 2PHP_ROUND_HALF_UP);
  4338.                 // Acumula netos totales e IVA
  4339.                 $totales_neto_all $totales_neto_all + ($item->getAmount()*(-1));
  4340.                 $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($item->getAmount()*(-($ivaPayment 100)));
  4341.                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  4342.                 $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  4343.                 $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  4344.                 // Acumula netos totales e IVA
  4345.                 $data_supplier['payment'][$i] = array(
  4346.                     'id' => $item->getId(),
  4347.                     'amount' => $item->getAmount()*(-1),
  4348.                     'amountTotal' => $item->getAmountTotal()*(-1),
  4349.                     'vat' => $item->getVat(),
  4350.                     'datePayAt' => $item->getDatePayAt(),
  4351.                     'wayToPay' => $item->getWayToPay(),
  4352.                 );
  4353.                 $arrayItems[] = array(
  4354.                     'type' => 'Payment',
  4355.                     'name' => $item->getWayToPay(),
  4356.                     'amount' => $item->getAmount()*(-1),
  4357.                     'total' => $item->getAmountTotal()*(-1),
  4358.                     'iva' => $item->getVat(),
  4359. //                    'iva' => '',
  4360. //                    'total' => $item->getAmount(),
  4361.                 );
  4362.             }
  4363.             $i++;
  4364.         }
  4365.         if (!empty($payments)) {
  4366.             $data_supplier['paymentSubTotal'] = array(
  4367.                 'neto' => $payment['neto'],
  4368.                 'sumSubT' => $payment['sumSubT'],
  4369.             );
  4370.         }
  4371.         foreach ($services as $item) {
  4372.             // Inicialización de variables basadas en typeBase
  4373.             if ($typeBase === 'I' || $typeBase === 'R') {
  4374.                 $price $item->getSrvPrice();
  4375.                 $opCommission $item->getSrvOpCommission();
  4376.                 $commission $item->getSrvCommission();
  4377.                 $opOver $item->getSrvOpOver();
  4378.                 $over $item->getSrvOver();
  4379.                 $opIva $item->getSrvOpIva();
  4380.                 $iva $item->getSrvIva();
  4381.                 $serviceCatId $item->getSrvServiceCatId();
  4382.                 $dateInAt $item->getSrvDateInAt();
  4383.                 $dateOutAt $item->getSrvDateOutAt();
  4384.                 $units $item->getSrvUnits();
  4385.                 $name $item->getSrvName();
  4386.                 $id $item->getId();
  4387.                 $pax $item->getSrvPax(); // Valor predeterminado para Alojamiento
  4388.             } else {
  4389.                 // Proforma
  4390.                 $price $item->getPrice();
  4391.                 $opCommission $item->getOpCommission();
  4392.                 $commission $item->getCommission();
  4393.                 $opOver $item->getOpOver();
  4394.                 $over $item->getOver();
  4395.                 $opIva $item->getOpIva();
  4396.                 $iva $item->getIva();
  4397.                 $serviceCatId $item->getServiceCatId();
  4398.                 $dateInAt $item->getDateInAt();
  4399.                 $dateOutAt $item->getDateOutAt();
  4400.                 $units $item->getUnits();
  4401.                 $name $item->getName();
  4402.                 $id $item->getId();
  4403.                 $pax $item->getPax();
  4404.             }
  4405.         
  4406.             // Verificación de precio nulo o vacío
  4407.             if (is_null($price) || empty($price)) {
  4408.                 $subtotal 0;
  4409.                 $neto 0;
  4410.                 $subtotalService 0;
  4411.             } else {
  4412.                 // Procesamiento del precio
  4413.                 $subtotalService floatval(str_replace(',''.'$price));
  4414.                 $subneto floatval(str_replace(',''.'$price));
  4415.         
  4416.                 // Cálculo de Comisión
  4417.                 if ($opCommission === '1') {
  4418.                     $subtotalService *= (+ ($commission 100));
  4419.                     $subneto *= (+ ($commission 100));
  4420.                 } else {
  4421.                     $subtotalService *= (- ($commission 100));
  4422.                     $subneto *= (- ($commission 100));
  4423.                 }
  4424.         
  4425.                 
  4426.         
  4427.                 // Mapeo de serviceCatId a serviceType
  4428.                 $serviceTypes = [
  4429.                     => 'Hotel',
  4430.                     => 'Actividad',
  4431.                     => 'AV',
  4432.                     => 'Creativo',
  4433.                     => 'Crucero',
  4434.                     => 'Entretenimiento',
  4435.                     => 'Regalos',
  4436.                     => 'Guía',
  4437.                     => 'Itinerarios',
  4438.                     10 => 'Lounge'// No Aplica
  4439.                     11 => 'Catering',
  4440.                     12 => 'Otros',
  4441.                     13 => 'Transporte',
  4442.                     14 => 'Tecnología',
  4443.                     15 => 'Asistente',
  4444.                     16 => 'DDR',
  4445.                     17 => 'Seguridad',
  4446.                     18 => 'WiFi',
  4447.                     19 => 'Mobiliario',
  4448.                     20 => 'Parking',
  4449.                     21 => 'Limpieza',
  4450.                 ];
  4451.         
  4452.                 $serviceType = isset($serviceTypes[$serviceCatId]) ? $serviceTypes[$serviceCatId] : 'Otros';
  4453.         
  4454.                 // Cálculos específicos según serviceCatId
  4455.                 if ($serviceCatId === 1) { // Alojamiento
  4456.                     $numNoches $dateOutAt->diff($dateInAt)->days;
  4457.                     $subtotal $subtotalService $numNoches $units;
  4458.                     $subnetoUnit $subneto;
  4459.                     $subneto *= $numNoches $units;
  4460.                     $dateServ $dateInAt->format('d/m/Y') . ' - ' $dateOutAt->format('d/m/Y');
  4461.                     $paxDisplay '-';
  4462.                     $qty $units;
  4463.                 } else {
  4464.                     // Para otros tipos de servicio
  4465.                     $pax = (empty($pax) || $pax == "0" $pax);
  4466.                     $days in_array($serviceCatId, [5714]) ? (($serviceCatId === 5) ? $dateOutAt->diff($dateInAt)->days 1) : ($dateOutAt->diff($dateInAt)->days 1);
  4467.                     $dateServ = ($days 1) ? $dateInAt->format('d/m/Y') . ' - ' $dateOutAt->format('d/m/Y') : $dateInAt->format('d/m/Y');
  4468.                     $unitsServ = empty($units) || $units == "0" $units;
  4469.                     $subtotal $subtotalService $days $unitsServ * (($pax !== '-') ? $pax 1);
  4470.                     $subnetoUnit $subneto;
  4471.                     $subneto *= $days $unitsServ * (($pax !== '-') ? $pax 1);
  4472.                     $paxDisplay = ($serviceCatId !== 1) ? $pax '-';
  4473.                     $qty $unitsServ;
  4474.                 }
  4475.                 // Cálculo de Over
  4476.                 if ($opOver === '1') {
  4477.                     $subtotal += $over;
  4478.                     $subneto += $over;
  4479.                 } else {
  4480.                     $subtotal -= $over;
  4481.                     $subneto -= $over;
  4482.                 }
  4483.         
  4484.                 // Asignación de datos al array data_supplier
  4485.                 $data_supplier['service'][$i] = [
  4486.                     'id' => $id,
  4487.                     'serviceCatId' => $serviceCatId,
  4488.                     'serviceName' => $name,
  4489.                     'serviceType' => $serviceType,
  4490.                     'date' => $dateServ,
  4491.                     'qty' => $qty,
  4492.                     'iva' => $iva,
  4493.                     'pax' => $paxDisplay,
  4494.                     'precioUnit' => $subnetoUnit,
  4495.                     'subneto' => $subneto,
  4496.                     'subtotal' => round($subtotal2PHP_ROUND_HALF_UP),
  4497.                 ];
  4498.         
  4499.                 // Redondeo de valores
  4500.                 $subtotal round($subtotal2PHP_ROUND_HALF_UP);
  4501.                 $neto round($subneto2PHP_ROUND_HALF_UP);
  4502.         
  4503.                 // Asignación a arrayItems
  4504.                 $arrayItems[] = [
  4505.                     'type' => 'Service',
  4506.                     'name' => $name,
  4507.                     'amount' => $neto,
  4508.                     'iva' => $iva,
  4509.                     'total' => $subtotal,
  4510.                 ];
  4511.             }
  4512.         
  4513.             // Acumulación de IVA
  4514.             switch ($iva) {
  4515.                 case 21:
  4516.                     $data_iva['ivaMontoVeintiUno'] += ($neto * ($iva 100));
  4517.                     break;
  4518.         
  4519.                 case 10:
  4520.                     $data_iva['ivaMontoDiez'] += ($neto * ($iva 100));
  4521.                     break;
  4522.         
  4523.                 case 0:
  4524.                 default:
  4525.                     break;
  4526.             }
  4527.         
  4528.             // Acumulación de totales
  4529.             $totales_neto_all += $neto;
  4530.             $totales_neto_all round($totales_neto_all2PHP_ROUND_HALF_UP);
  4531.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'], 2PHP_ROUND_HALF_UP);
  4532.             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'], 2PHP_ROUND_HALF_UP);
  4533.         
  4534.             $service['neto'] += $neto;
  4535.             $service['sumSubT'] += $subtotal;
  4536.             $service['neto'] = round($service['neto'], 2PHP_ROUND_HALF_UP);
  4537.             $service['sumSubT'] = round($service['sumSubT'], 2PHP_ROUND_HALF_UP);
  4538.         
  4539.             $i++;
  4540.         }
  4541.         $data_supplier['serviceSubTotal'] = array(
  4542.             'neto' => $service['neto'],
  4543.             'sumSubT' => $service['sumSubT'],
  4544.         );
  4545.         $currency '€';
  4546.         $totales_total $totales_neto_all $data_iva['ivaMontoVeintiUno'] + $data_iva['ivaMontoDiez'];
  4547.         if (!empty($payments)) {
  4548.             $amount_pay $data_supplier['paymentSubTotal']['sumSubT'];
  4549.         } else {
  4550.             $amount_pay 0;
  4551.         }
  4552.         $totales_all $totales_total $amount_pay;
  4553.         if (empty($dateDocument)){
  4554.             $dateDocument = new DateTime('now');
  4555.         }
  4556.         $data = array(
  4557.             'id' => $reservationId,
  4558.             'type' => $type,
  4559.             'number' => $number,
  4560.             'prefix' => 'GP-'.(new DateTime('now'))->format('dmy').'-',
  4561.             'date' => $dateDocument,
  4562.             'reservation' => $reservation,
  4563.             'token' => $reservation->getAccessKey(),
  4564.             'company' => $company,
  4565.             'clients' => $client,
  4566.             'arrayItems' => $arrayItems,
  4567.             'datasupplier' => $data_supplier,
  4568.             'currency' => $currency,
  4569.             'totales_neto' => $totales_neto_all,
  4570.             'bases_imponibles' => $data_iva,
  4571.             'totales' => $totales_total,
  4572.             'balance' => $totales_all,
  4573.             'paymentInvoice' => $amount_pay,
  4574.         );
  4575.         return $data;
  4576.     }
  4577.     /**
  4578.      * @Route("/reservations/newinvoicedeposit/proforma/{id}",  name="reservation_new_invoice_deposit_proforma")
  4579.      */
  4580.     public function detailsNewProformaInvoiceDepositAction($idRequest $request){
  4581.         // Generamos Proforma de deposito
  4582.        $proformaDeposit $request->request->get('invoicedep');
  4583.        if (empty($proformaDeposit['name']) or empty($proformaDeposit['amount'])){
  4584.            // Se necesitan todos los datos
  4585.            return $this->redirectToRoute('reservations_payment', array( 'id' => $id ) );
  4586.        }
  4587.         $em $this->getDoctrine()->getManager();
  4588.         /* Obtengo usuario logueado */
  4589.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  4590.         $user_id $user_logueado->getId();
  4591.         // Obtenemos el Id a asignar a la proforma de deposito y se guarda en Number
  4592.         $allInvoicedeposititems $em->getRepository(ReservationProformaDeposit::class)->findAll();
  4593.         if (!empty($allInvoicedeposititems)){
  4594.             $number end($allInvoicedeposititems)->getId() + 1;
  4595.         } else {
  4596.             $number 1;
  4597.         }
  4598.         $total floatval(str_replace',''.'$proformaDeposit['amount'])) + ((floatval(str_replace',''.'$proformaDeposit['amount'])) * $proformaDeposit['iva'])/100);
  4599.         $total round($total2);
  4600.         $ivaNew = (empty($proformaDeposit['iva'])) ? $proformaDeposit['iva'];
  4601.         $newProformaDeposit = new ReservationProformaDeposit();
  4602.         $newProformaDeposit->setDateAt(new DateTime('now'));
  4603.         $newProformaDeposit->setReservationId($id);
  4604.         $newProformaDeposit->setName($proformaDeposit['name']);
  4605.         $newProformaDeposit->setAmount(str_replace',''.'$proformaDeposit['amount']));
  4606.         $newProformaDeposit->setIva($ivaNew);
  4607.         $newProformaDeposit->setNumber($number);
  4608.         $newProformaDeposit->setTotal($total);
  4609.         $newProformaDeposit->setPrefix('IFD-');
  4610.         $newProformaDeposit->setCreatedId($user_id);
  4611.         $newProformaDeposit->setUpdatedId($user_id);
  4612.         $newProformaDeposit->setCreatedAt(new DateTime('now'));
  4613.         $newProformaDeposit->setUpdatedAt(new DateTime('now'));
  4614.         $em->persist($newProformaDeposit);
  4615.         $em->flush();
  4616.         $invoicedeposititems $em->getRepository(ReservationProformaDeposit::class)->findBy(
  4617.             array(
  4618.                 'reservationId' => $id,
  4619.                 'number' => $number,
  4620.             )
  4621.         );
  4622.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  4623.         // Buscamos el cliente
  4624.         $reservation $em->getRepository(Reservation::class)->findOneById($id);
  4625.         $client $em->getRepository(Client::class)->findById($reservation->getClient());
  4626.         if (!empty($client)){
  4627.             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  4628.             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  4629.             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  4630.             $client['city'] = $city$client['region'] = $region$client['country'] = $country;
  4631.         } else {
  4632.             $client[0] = new Client();
  4633.             $client[0]->setName('');
  4634.             $client[0]->setTitle('');
  4635.             $client[0]->setIdDocument('');
  4636.             $client[0]->setPopulation('');
  4637.             $client[0]->setRegion('');
  4638.             $client[0]->setCountry('');
  4639.         }
  4640.         // Buscamos el cliente
  4641.         $allInvoiceDeposit $em->getRepository(ReservationProformaDeposit::class)->findBy(
  4642.             array(
  4643.                 'reservationId' => $id,
  4644.             )
  4645.         );
  4646.         $totales_iva = (str_replace',''.'$proformaDeposit['amount']) * $proformaDeposit['iva'])/100;
  4647.         $totales str_replace',''.'$proformaDeposit['amount']) + $totales_iva;
  4648.         $boolToRec false;
  4649.         return $this->redirectToRoute('reservation_view_new_invoice_deposit_proforma',array('id' => $newProformaDeposit->getId()));
  4650.     }
  4651.     /**
  4652.      * @Route("/reservations/newinvoicedeposit/viewproforma/{id}",  name="reservation_view_new_invoice_deposit_proforma")
  4653.      */
  4654.     public function detailsViewNewProformaInvoiceDepositAction($idRequest $request){
  4655.         // Visualizar Proforma de Deposito
  4656.         $em $this->getDoctrine()->getManager();
  4657.         /* Obtengo usuario logueado */
  4658.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  4659.         $user_id $user_logueado->getId();
  4660.         $newProformaDeposit $em->getRepository(ReservationProformaDeposit::class)->findOneById($id);
  4661.         $total $newProformaDeposit->getAmount() + (($newProformaDeposit->getAmount() * $newProformaDeposit->getIva())/100);
  4662.         $invoicedeposititems $em->getRepository(ReservationProformaDeposit::class)->findBy(
  4663.             array(
  4664.                 'reservationId' => $newProformaDeposit->getReservationId(),
  4665.                 'number' => $id,
  4666.             )
  4667.         );
  4668.         $invoiceDeposit $em->getRepository(ReservationProformaDeposit::class)->findOneById($id);
  4669.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  4670.         // Buscamos el cliente
  4671.         $reservation $em->getRepository(Reservation::class)->findOneById($invoiceDeposit->getReservationId());
  4672.         $client $em->getRepository(Client::class)->findById($reservation->getClient());
  4673.         if (!empty($client)){
  4674.             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  4675.             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  4676.             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  4677.             $client['city'] = $city$client['region'] = $region$client['country'] = $country;
  4678.         } else {
  4679.             $client[0] = new Client();
  4680.             $client[0]->setName('');
  4681.             $client[0]->setTitle('');
  4682.             $client[0]->setIdDocument('');
  4683.             $client[0]->setPopulation('');
  4684.             $client[0]->setRegion('');
  4685.             $client[0]->setCountry('');
  4686.         }
  4687.         // Buscamos el cliente
  4688.         $allInvoiceDeposit $em->getRepository(ReservationProformaDeposit::class)->findBy(
  4689.             array(
  4690.                 'reservationId' => $invoiceDeposit->getReservationId(),
  4691.             )
  4692.         );
  4693.         $totales_iva = ($newProformaDeposit->getAmount() * $newProformaDeposit->getIva())/100;
  4694.         $totales $newProformaDeposit->getAmount() + $totales_iva;
  4695.         $boolToRec false// Una proforma no se va a rectificar
  4696.         $reservaEquis $em->getRepository(Reservation::class)->findOneById($invoiceDeposit->getReservationId());
  4697. //                if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
  4698.         if(true){ $newInvoice $this->clientDataToInvoice(null'Client'$reservaEquis->getClient(), $reservaEquis->getId()); }
  4699.         return $this->render('MDS/GreenPatioBundle/reservations/invoice-deposit-invoice.html.twig',
  4700.             array(
  4701.                 'id' => $invoiceDeposit->getReservationId(),
  4702.                 'cid' => '',
  4703.                 'fid' => $newProformaDeposit->getId(),
  4704.                 'invoice' => '',
  4705.                 'numberadmin' => $newProformaDeposit->getId(),
  4706.                 'type' => 'Proforma Deposit',
  4707.                 'number' => $newProformaDeposit->getId(),
  4708.                 'prefix' => '',
  4709.                 'date' => '',
  4710.                 'token' =>  '',
  4711.                 'company' => $company,
  4712.                 'clients' => $client,
  4713.                 'user' => $user_logueado,
  4714.                 'boolToRec' => $boolToRec,
  4715.                 'invoicedeposititems' => $invoicedeposititems,
  4716.                 'allProformaDeposit' => $allInvoiceDeposit,
  4717.                 'totales_neto' => $newProformaDeposit->getAmount(),
  4718.                 'totales_iva' => $totales_iva,
  4719.                 'totales' => $totales,
  4720.                 'bases_imponibles' => $newProformaDeposit->getIva(),
  4721.                 'currency' => '€',
  4722.                 'clientName' => $newInvoice->getClientName(),
  4723.                 'clientAddress' => $newInvoice->getClientAddress(),
  4724.                 'clientDocument' => $newInvoice->getClientDocument(),
  4725. //                'mcp' => $proposal->getMcp(),
  4726.             )
  4727.         );
  4728.     }
  4729.     /**
  4730.      * @Route("/reservations/newinvoicedeposit/invoice/{id}",  name="reservation_new_invoice_deposit_invoice")
  4731.      */
  4732.     public function detailsNewInvoiceDepositAction($idRequest $request){
  4733.         // Generamos la nueva factura de deposito
  4734.         $em $this->getDoctrine()->getManager();
  4735.         $proformaDeposit $em->getRepository(ReservationProformaDeposit::class)->findOneById($id);
  4736.         $vat = ($proformaDeposit->getAmount() * $proformaDeposit->getIva())/100;
  4737.         $vat round($vat,2);
  4738.         $totalInvoiceDep $proformaDeposit->getAmount() + $vat;
  4739.         $totalInvoiceDep round($totalInvoiceDep2);
  4740.         $balanceInvoiceDep $totalInvoiceDep * (-1);  // una factura de deposito es ingreso a caja por eso multiplicamos por -1
  4741.         if (empty($proformaDeposit->getName()) or empty($proformaDeposit->getAmount())){
  4742.             // Se necesitan todos los datos
  4743.             return $this->redirectToRoute('reservations_payment', array( 'id' => $proformaDeposit->getReservationId()));
  4744.         }
  4745.         // INICIO: Verificamos la linea de facturacion
  4746.         $parameters = array( 'id' => $proformaDeposit->getReservationId(), );
  4747.         $dql 'SELECT p
  4748.                 FROM GreenPatioBundle:ReservationLoungeSimple p
  4749.                 WHERE p.idReservation = :id AND p.idLounge > 21';
  4750.         $query $em->createQuery($dql)->setParameters($parameters);
  4751.         $loungesSimples $query->getResult();
  4752.         if (!empty($loungesSimples)){
  4753.             // Redirigir a Covarrubias
  4754. //            return $this->redirectToRoute('reservation_new_invoice_deposit_invoice_cvr', array( 'id' => $id, ) );
  4755.         }
  4756.         // FIN: Verificamos la linea de facturacion
  4757.         /* Obtengo usuario logueado */
  4758.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  4759.         $user_id $user_logueado->getId();
  4760.         // INICIO: Generamos la factura
  4761.         $invoice = new ReservationInvoice();
  4762.         $invoice->setNumber('GPF-'.date('d').date('m').substr(date('Y'),-2).'-'.$proformaDeposit->getReservationId());
  4763.         $invoice->setPrefix(null);
  4764.         $invoice->setDateAt(new DateTime('now'));
  4765.         $invoice->setType('Invoice Deposit');
  4766.         $invoice->setReservationId($proformaDeposit->getReservationId());;
  4767.         $invoice->setTotalNet($proformaDeposit->getAmount());
  4768.         $invoice->setVat($vat);
  4769.         $invoice->setTotal($totalInvoiceDep);
  4770.         $invoice->setBalance($balanceInvoiceDep);
  4771.         $invoice->setMaster('master');
  4772.         $invoice->setCreatedAt(new DateTime('now'));
  4773.         $invoice->setUpdatedAt(new DateTime('now'));
  4774.         $invoice->setCreatedId($user_id);
  4775.         $invoice->setUpdatedId($user_id);
  4776.         $reservaEquis $em->getRepository(Reservation::class)->findOneById($proformaDeposit->getReservationId());
  4777.         if(true){ $invoice $this->clientDataToInvoice($invoice'Client'$reservaEquis->getClient(), $reservaEquis->getId()); }
  4778.         $em->persist($invoice);
  4779.         $em->flush();
  4780.         // FIN: Generamos la factura
  4781.         // INICIO: Generamos el invoice deposit Control
  4782.         $control = new ReservationInvoiceDepositControl();
  4783.         $control->setPrefix('IFD-');
  4784.         $control->setNumber($invoice->getId());
  4785.         $control->setDateAt(new DateTime('now'));
  4786.         $control->setReservationId($proformaDeposit->getReservationId());
  4787.         $control->setCreatedAt(new DateTime('now'));
  4788.         $control->setUpdatedAt(new DateTime('now'));
  4789.         $control->setCreatedId($user_id);
  4790.         $control->setUpdatedId($user_id);
  4791.         $em->persist($control);
  4792.         $em->flush();
  4793.         // FIN: Generamos el invoice deposit Control
  4794.         // INICIO: Generamos el invoice deposit item
  4795.         $invDepositItem = new ReservationInvoiceDepositItems();
  4796.         $invDepositItem->setControlId($control->getId());
  4797.         $invDepositItem->setName($proformaDeposit->getName());
  4798.         $invDepositItem->setAmount($proformaDeposit->getAmount());
  4799.         $invDepositItem->setIva($proformaDeposit->getIva());
  4800.         $invDepositItem->setReservationId($proformaDeposit->getReservationId());
  4801.         $invDepositItem->setCreatedAt(new DateTime('now'));
  4802.         $invDepositItem->setUpdatedAt(new DateTime('now'));
  4803.         $invDepositItem->setCreatedId($user_id);
  4804.         $invDepositItem->setUpdatedId($user_id);
  4805.         $em->persist($invDepositItem);
  4806.         $em->flush();
  4807.         // FIN: Generamos el invoice deposit item
  4808.         // INICIO: Generamos el pago asociado
  4809.         // Por solicitud de Esteban Rincon se genera de forma automatica un pago para representar en la factura final el descuento por concepto de factura de deposito
  4810.         $payment = new ReservationPaymentsClient();
  4811.         $payment->setDatePayAt(new DateTime('now'));
  4812.         $payment->setAmount($proformaDeposit->getAmount());
  4813.         $payment->setVat($proformaDeposit->getIva());
  4814.         $payment->setAmountTotal($proformaDeposit->getAmount() + ($proformaDeposit->getAmount() * $proformaDeposit->getIva())/100);
  4815.         $payment->setWayToPay('FACTURA DE DEPOSITO');
  4816.         $payment->setReservationId($proformaDeposit->getReservationId());;
  4817.         $payment->setInvoiceId($invoice->getId());
  4818.         $payment->setCreatedAt(new DateTime('now'));
  4819.         $payment->setUpdatedAt(new DateTime('now'));
  4820.         $payment->setCreatedId($user_id);
  4821.         $payment->setUpdatedId($user_id);
  4822.         $em->persist($payment);
  4823.         $em->flush();
  4824.         $payment->setWayToPay($payment->getWayToPay().' - '.$invoice->getId());
  4825.         $em->persist($payment);
  4826.         $em->flush();
  4827.         // INICIO: Generamos el pago asociado
  4828.         $total $totalInvoiceDep;
  4829.         $invoicedeposititems = array();
  4830.         $invoicedeposititems[] = $invDepositItem;
  4831.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  4832.         // Buscamos el cliente
  4833.         $reservation $em->getRepository(Reservation::class)->findOneById($proformaDeposit->getReservationId());
  4834.         $client $em->getRepository(Client::class)->findById($reservation->getClient());
  4835.         if (!empty($client)){
  4836.             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  4837.             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  4838.             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  4839.             $client['city'] = $city$client['region'] = $region$client['country'] = $country;
  4840.         } else {
  4841.             $client[0] = new Client();
  4842.             $client[0]->setName('');
  4843.             $client[0]->setTitle('');
  4844.             $client[0]->setIdDocument('');
  4845.             $client[0]->setPopulation('');
  4846.             $client[0]->setRegion('');
  4847.             $client[0]->setCountry('');
  4848.         }
  4849.         // Buscamos el cliente
  4850.         $allInvoiceDeposit $em->getRepository(ReservationInvoice::class)->findBy(
  4851.             array(
  4852.                 'reservationId' => $invoice->getReservationId(),
  4853.             )
  4854.         );
  4855.         $totales_iva $vat;
  4856.         $totales $invoice->getTotalNet() + $totales_iva;
  4857.         // Una factura solo se puede rectificar una vez
  4858.         $rectf $em->getRepository(ReservationInvoiceRec::class)->findBy( array('invoiceToRec' => $invoice->getId()));
  4859.         $boolToRec = empty($rectf);
  4860.         return $this->redirectToRoute('reservation_view_new_invoice_deposit',array('id' => $invoice->getId()));
  4861.     }
  4862.     /**
  4863.      * @Route("/reservations/newinvoicedeposit/viewinvoicedeposit/{id}",  name="reservation_view_new_invoice_deposit")
  4864.      */
  4865.     public function detailsViewNewInvoiceDepositAction($idRequest $request){
  4866.         // Visualizar Factura de Deposito
  4867.         $em $this->getDoctrine()->getManager();
  4868.         $dateDocument null;                                           // Fecha del documento
  4869.         /* Obtengo usuario logueado */
  4870.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  4871.         $user_id $user_logueado->getId();
  4872.         $newProformaDeposit $em->getRepository(ReservationInvoice::class)->findOneById($id);
  4873.         if(!empty($newProformaDeposit)){ $dateDocument $newProformaDeposit->getDateAt(); }
  4874.         $total $newProformaDeposit->getTotal();
  4875.         $controlInvDep $em->getRepository(ReservationInvoiceDepositControl::class)->findOneByNumber($id);
  4876.         $invoicedeposititems $em->getRepository(ReservationInvoiceDepositItems::class)->findBy(
  4877.             array(
  4878.                 'reservationId' => $newProformaDeposit->getReservationId(),
  4879.                 'controlId' => $controlInvDep->getId(),
  4880.             )
  4881.         );
  4882.         if (!empty($invoicedeposititems)){$bases_imponibles $invoicedeposititems[0]->getIva();} else {$bases_imponibles '';}
  4883.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  4884.         // Buscamos el cliente
  4885.         $reservation $em->getRepository(Reservation::class)->findOneById($newProformaDeposit->getReservationId());
  4886.         $client $em->getRepository(Client::class)->findById($reservation->getClient());
  4887.         if (!empty($client)){
  4888.             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  4889.             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  4890.             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  4891.             $client['city'] = $city$client['region'] = $region$client['country'] = $country;
  4892.         } else {
  4893.             $client[0] = new Client();
  4894.             $client[0]->setName('');
  4895.             $client[0]->setTitle('');
  4896.             $client[0]->setIdDocument('');
  4897.             $client[0]->setPopulation('');
  4898.             $client[0]->setRegion('');
  4899.             $client[0]->setCountry('');
  4900.         }
  4901.         // Buscamos el cliente
  4902.         $allInvoiceDeposit $em->getRepository(ReservationInvoice::class)->findBy(
  4903.             array(
  4904.                 'reservationId' => $newProformaDeposit->getReservationId(),
  4905.             )
  4906.         );
  4907.         $totales_iva $newProformaDeposit->getVat();
  4908.         $totales $newProformaDeposit->getTotal();
  4909.         // Una factura solo se puede rectificar una vez
  4910.         $rectf $em->getRepository(ReservationInvoiceRec::class)->findBy( array('invoiceToRec' => $newProformaDeposit->getId()));
  4911.         $boolToRec = empty($rectf);
  4912.         $reservaEquis $em->getRepository(Reservation::class)->findOneById($newProformaDeposit->getReservationId());
  4913.         if(empty($newProformaDeposit->getClientName()) and empty($newProformaDeposit->getClientAddress()) and empty($newProformaDeposit->getClientDocument())){
  4914.             $newProformaDeposit $this->clientDataToInvoice($newProformaDeposit'Client'$reservaEquis->getClient(), $newProformaDeposit->getReservationId());
  4915.         }
  4916.         return $this->render('MDS/GreenPatioBundle/reservations/invoice-deposit-invoice.html.twig',
  4917.             array(
  4918.                 'id' => $newProformaDeposit->getReservationId(),
  4919.                 'cid' => '',
  4920.                 'fid' => $newProformaDeposit->getId(),
  4921.                 'invoice' => '',
  4922.                 'numberadmin' => $newProformaDeposit->getId(),
  4923.                 'type' => 'Invoice Deposit',
  4924.                 'number' => $newProformaDeposit->getId(),
  4925.                 'prefix' => '',
  4926.                 'date' => $dateDocument,
  4927.                 'token' =>  '',
  4928.                 'company' => $company,
  4929.                 'clients' => $client,
  4930.                 'user' => $user_logueado,
  4931.                 'boolToRec' => $boolToRec,
  4932.                 'invoicedeposititems' => $invoicedeposititems,
  4933.                 'allProformaDeposit' => $allInvoiceDeposit,
  4934.                 'totales_neto' => $newProformaDeposit->getTotalNet(),
  4935.                 'totales_iva' => $totales_iva,
  4936.                 'totales' => $totales,
  4937.                 'bases_imponibles' => $bases_imponibles,
  4938.                 'currency' => '€',
  4939.                 'clientName' => $newProformaDeposit->getClientName(),
  4940.                 'clientAddress' => $newProformaDeposit->getClientAddress(),
  4941.                 'clientDocument' => $newProformaDeposit->getClientDocument(),
  4942.             )
  4943.         );
  4944.     }
  4945.     /**
  4946.      * @Route("/reservations/newinvoicedeposit/invoicerec/{id}",  name="reservation_new_invoice_deposit_invoicerec")
  4947.      */
  4948.     public function detailsNewInvoiceDepositRecAction($idRequest $request){
  4949.         // Generamos la factura de deposito rectificativa
  4950.         $em $this->getDoctrine()->getManager();
  4951.         if (true){
  4952.             // Verificamos que no exista una factura rectificativa previa sobre la misma factura
  4953.             $previusInvoiceRec $em->getRepository(ReservationInvoiceRec::class)->findOneByInvoiceToRec($id);
  4954.             if (!empty($previusInvoiceRec)){ return $this->redirectToRoute('reservation_view_new_invoice_deposit_rec', array('id' => $previusInvoiceRec->getId())); }
  4955.         }
  4956.         $proformaDeposit $em->getRepository(ReservationInvoice::class)->findOneById($id);
  4957.         $vat $proformaDeposit->getVat() * (-1);                   // En una rectificativa Esteban ha pedido todos los valores en negativo
  4958.         $totalInvoiceDep $proformaDeposit->getTotal() * (-1);
  4959.         $balanceInvoiceDep $proformaDeposit->getBalance() * (-1);  //una factura de deposito rectificativa  es egreso a caja por eso multiplicamos por -1 lo que teniamos como ingreso
  4960.         // Buscamos el Id del deposit item a partir de la factura
  4961.         $resDepControl $em->getRepository(ReservationInvoiceDepositControl::class)->findOneByNumber($id);
  4962.         $resInvDepItem $em->getRepository(ReservationInvoiceDepositItems::class)->findOneByControlId($resDepControl->getId());
  4963.         $equisInv $em->getRepository(ReservationInvoice::class)->findOneById($id);
  4964.         /* Obtengo usuario logueado */
  4965.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  4966.         $user_id $user_logueado->getId();
  4967.         // INICIO: Generamos la factura de deposito rectificativa
  4968.         $invoice = new ReservationInvoiceRec();
  4969.         $invoice->setNumber('REC-GPFD-'.date('d').date('m').substr(date('Y'),-2).'-'.$proformaDeposit->getReservationId());
  4970.         $invoice->setPrefix(null);
  4971.         $invoice->setDateAt(new DateTime('now'));
  4972.         $invoice->setType('Invoice Deposit Rec');
  4973.         $invoice->setInvoiceToRec($id);
  4974.         $invoice->setReservationId($proformaDeposit->getReservationId());;
  4975.         $invoice->setTotalNet($proformaDeposit->getTotalNet()*(-1));
  4976.         $invoice->setVat($vat);
  4977.         $invoice->setTotal($totalInvoiceDep);
  4978.         $invoice->setBalance($balanceInvoiceDep);
  4979.         $invoice->setMaster('master');
  4980.         $invoice->setCreatedAt(new DateTime('now'));
  4981.         $invoice->setUpdatedAt(new DateTime('now'));
  4982.         $invoice->setCreatedId($user_id);
  4983.         $invoice->setUpdatedId($user_id);
  4984.         $invoice->setClientName($equisInv->getClientName());
  4985.         $invoice->setClientAddress($equisInv->getClientAddress());
  4986.         $invoice->setClientDocument($equisInv->getClientDocument());
  4987.         $invoice->setClientType($equisInv->getClientType());
  4988.         $em->persist($invoice);
  4989.         $em->flush();
  4990.         // FIN: Generamos la factura de deposito rectificativa
  4991.         // INICIO: Generamos el invoice rec item
  4992.         $invDepositItem = new ReservationInvoiceRecItems();
  4993.         $invDepositItem->setDepControlId($resInvDepItem->getId());
  4994.         $invDepositItem->setDepName($resInvDepItem->getName());
  4995.         $invDepositItem->setDepAmount($resInvDepItem->getAmount() * (-1));              // Esteban ha pedido todos los datos de la rectificativa en negativo
  4996.         $invDepositItem->setDepIva($resInvDepItem->getIva());
  4997.         $invDepositItem->setDepDateAt($resDepControl->getDateAt());
  4998.         $invDepositItem->setReservationId($proformaDeposit->getReservationId());
  4999.         $invDepositItem->setCreatedAt(new DateTime('now'));
  5000.         $invDepositItem->setUpdatedAt(new DateTime('now'));
  5001.         $invDepositItem->setCreatedId($user_id);
  5002.         $invDepositItem->setUpdatedId($user_id);
  5003.         $invDepositItem->setInvoiceId($id);
  5004.         $invDepositItem->setItemType('DEPOSIT');
  5005.         $invDepositItem->setInvoiceRecId($invoice->getId());
  5006.         $em->persist($invDepositItem);
  5007.         $em->flush();
  5008.         // FIN: Generamos el invoice deposit item
  5009.         // INICIO: Buscamos Pagos asociados a la factura de deposito (se crean de forma automatica, se van a eliminar de forma automatica)
  5010.         $payToDelete $em->getRepository(ReservationPaymentsClient::class)->findOneByInvoiceId($id);
  5011.         if (!empty($payToDelete)){
  5012.             $em->remove($payToDelete);
  5013.             $em->flush();
  5014.         }
  5015.         // FIN: Buscamos Pagos asociados a la factura de deposito (se crean de forma automatica, se van a eliminar de forma automatica)
  5016.         $total $totalInvoiceDep;
  5017.         $invoicedeposititems = array();
  5018.         $invoicedeposititems[] = $invDepositItem;
  5019.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  5020.         // Buscamos el cliente
  5021.         $reservation $em->getRepository(Reservation::class)->findOneById($proformaDeposit->getReservationId());
  5022.         $client $em->getRepository(Client::class)->findById($reservation->getClient());
  5023.         if (!empty($client)){
  5024.             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  5025.             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  5026.             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  5027.             $client['city'] = $city$client['region'] = $region$client['country'] = $country;
  5028.         } else {
  5029.             $client[0] = new Client();
  5030.             $client[0]->setName('');
  5031.             $client[0]->setTitle('');
  5032.             $client[0]->setIdDocument('');
  5033.             $client[0]->setPopulation('');
  5034.             $client[0]->setRegion('');
  5035.             $client[0]->setCountry('');
  5036.         }
  5037.         // Buscamos el cliente
  5038.         $allInvoiceDeposit $em->getRepository(ReservationProformaDeposit::class)->findBy(
  5039.             array(
  5040.                 'reservationId' => $id,
  5041.             )
  5042.         );
  5043.         $totales_iva $vat;
  5044. //        $totales = ($invoice->getTotalNet() * (-1)) + $totales_iva;
  5045.         $totales $invoice->getTotalNet() + $totales_iva;
  5046.         // Una factura solo se puede rectificar una vez
  5047. //        $rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('invoiceToRec' => $invoice->getId()));
  5048.         $boolToRec false;
  5049.         $invoicedeposititemsTemp = array(
  5050.             'name' => $invoicedeposititems[0]->getDepName(),
  5051.             'amount' => $invoicedeposititems[0]->getDepAmount(),
  5052.             'iva' => $invoicedeposititems[0]->getDepIva(),
  5053.         );
  5054.         $invoicedeposititems = array();
  5055.         $invoicedeposititems[] = $invoicedeposititemsTemp;
  5056.         return $this->redirectToRoute('reservation_view_new_invoice_deposit_rec',array('id' => $invoice->getId()));
  5057.     }
  5058.     /**
  5059.      * @Route("/reservations/newinvoicedeposit/viewinvoicedepositrec/{id}",  name="reservation_view_new_invoice_deposit_rec")
  5060.      */
  5061.     public function detailsViewNewInvoiceDepositRecAction($idRequest $request){
  5062.         // Visualizar Factura de Deposito Rectificativa
  5063.         $em $this->getDoctrine()->getManager();
  5064.         /* Obtengo usuario logueado */
  5065.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  5066.         $user_id $user_logueado->getId();
  5067.         $newProformaDeposit $em->getRepository(ReservationInvoiceRec::class)->findOneById($id);
  5068.         $total $newProformaDeposit->getTotal();
  5069.         $invoicedeposititems $em->getRepository(ReservationInvoiceRecItems::class)->findBy(
  5070.             array(
  5071.                 'reservationId' => $newProformaDeposit->getReservationId(),
  5072.                 'invoiceRecId' => $id,
  5073.             )
  5074.         );
  5075.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  5076.         // Buscamos el cliente
  5077.         $reservation $em->getRepository(Reservation::class)->findOneById($newProformaDeposit->getReservationId());
  5078.         $client $em->getRepository(Client::class)->findById($reservation->getClient());
  5079.         if (!empty($client)){
  5080.             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  5081.             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  5082.             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  5083.             $client['city'] = $city$client['region'] = $region$client['country'] = $country;
  5084.         } else {
  5085.             $client[0] = new Client();
  5086.             $client[0]->setName('');
  5087.             $client[0]->setTitle('');
  5088.             $client[0]->setIdDocument('');
  5089.             $client[0]->setPopulation('');
  5090.             $client[0]->setRegion('');
  5091.             $client[0]->setCountry('');
  5092.         }
  5093.         // Buscamos el cliente
  5094.         $allInvoiceDeposit $em->getRepository(ReservationProformaDeposit::class)->findBy(
  5095.             array(
  5096.                 'reservationId' => $newProformaDeposit->getReservationId(),
  5097.             )
  5098.         );
  5099.         $totales_iva $newProformaDeposit->getVat();
  5100.         $totales $newProformaDeposit->getTotal();
  5101.         // Una factura solo se puede rectificar una vez
  5102. //        $rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('invoiceToRec' => $newProformaDeposit->getId()));
  5103.         $boolToRec false;
  5104.         $invoicedeposititemsTemp = array(
  5105.             'name' => $invoicedeposititems[0]->getDepName(),
  5106.             'amount' => $invoicedeposititems[0]->getDepAmount(),
  5107.             'iva' => $invoicedeposititems[0]->getDepIva(),
  5108.         );
  5109.         $invoicedeposititems = array();
  5110.         $invoicedeposititems[] = $invoicedeposititemsTemp;
  5111.         $reservaEquis $em->getRepository(Reservation::class)->findOneById($newProformaDeposit->getReservationId());
  5112.         if(empty($newProformaDeposit->getClientName()) and empty($newProformaDeposit->getClientAddress()) and empty($newProformaDeposit->getClientDocument())){
  5113.             $newProformaDeposit $this->clientDataToInvoice($newProformaDeposit'Client'$reservaEquis->getClient(), $newProformaDeposit->getReservationId());
  5114.         }
  5115.         return $this->render('MDS/GreenPatioBundle/reservations/invoice-deposit-invoice.html.twig',
  5116.             array(
  5117.                 'id' => $newProformaDeposit->getReservationId(),
  5118.                 'cid' => '',
  5119.                 'fid' => $newProformaDeposit->getId(),
  5120.                 'invoice' => '',
  5121.                 'numberadmin' => null,
  5122.                 'type' => 'Invoice Deposit Rec',
  5123.                 'number' => $id,
  5124.                 'prefix' => '',
  5125.                 'date' => $newProformaDeposit->getDateAt(),
  5126.                 'token' =>  '',
  5127.                 'company' => $company,
  5128.                 'clients' => $client,
  5129.                 'user' => $user_logueado,
  5130.                 'boolToRec' => $boolToRec,
  5131.                 'invoiceIdToRec' => $newProformaDeposit->getInvoiceToRec(),
  5132.                 'invoicedeposititems' => $invoicedeposititems,
  5133.                 'allProformaDeposit' => $allInvoiceDeposit,
  5134.                 'totales_neto' => $newProformaDeposit->getTotalNet(),
  5135.                 'totales_iva' => $totales_iva,
  5136.                 'totales' => $totales,
  5137.                 'balance' => (-1) * $newProformaDeposit->getBalance(),
  5138.                 'bases_imponibles' => '',
  5139.                 'currency' => '€',
  5140.                 'clientName' => $newProformaDeposit->getClientName(),
  5141.                 'clientAddress' => $newProformaDeposit->getClientAddress(),
  5142.                 'clientDocument' => $newProformaDeposit->getClientDocument(),
  5143.             )
  5144.         );
  5145.     }
  5146.     /**
  5147.      * @Route("/reservations/invoice/invoicedeposit-proforma/print/{type}/{id}",  name="reservations_invoicedepositproforma_print")
  5148.      */
  5149.     public function detailsInvoiceDepositProformaPrintAction($type$idRequest $request)
  5150.     {
  5151.         // Pantalla para imprimir Proformas, Facturas y Facturas Rectificativas de Deposito
  5152.         $data = array();
  5153.         $em $this->getDoctrine()->getManager();
  5154.         // Si el ID de factura viene vacio regresamos a ver facturas
  5155.         if (empty($type)){
  5156.             return $this->redirectToRoute('reservations_viewreservation_invoices',array('id' => $id));
  5157.         }
  5158.         //Acumuladores de datos globales de la factura o proforma
  5159.         $valorTotalNet 0;
  5160.         $valorVat 0;
  5161.         if ($type == 'I'){
  5162.             // El tipo es una factura de deposito
  5163.             $data['type'] = 'Invoice Deposit';
  5164.             $data['number'] = $id;
  5165.             $proDepositNet 0;
  5166.             $proDepositIva 0;
  5167.             $proDepositTotal 0;
  5168.             $ivaPorcentaje 0;
  5169.             $monto 0;
  5170.             $concepto ='';
  5171.             //INICIO: Buscamos los items de la factura
  5172.             $controlInvDep $em->getRepository(ReservationInvoiceDepositControl::class)->findOneByNumber($id);
  5173.             $arrayInvoicedItems $em->getRepository(ReservationInvoiceDepositItems::class)->findByControlId($controlInvDep->getId());
  5174.             if (!empty($arrayInvoicedItems)) {
  5175.                 foreach ($arrayInvoicedItems as $itemInvoice) {
  5176.                     if (is_numeric($itemInvoice->getAmount()) and is_numeric($itemInvoice->getIva())) {
  5177.                         $proDepositNet $itemInvoice->getAmount();
  5178.                         $proDepositIva = ($itemInvoice->getAmount()*$itemInvoice->getIva())/100;
  5179.                         $proDepositTotal $itemInvoice->getAmount() + $proDepositIva;
  5180.                         $ivaPorcentaje $itemInvoice->getIva();
  5181.                         $monto $itemInvoice->getAmount();
  5182.                         $concepto $itemInvoice->getName();
  5183.                         //Acumulamos neto e iva para la factura
  5184.                         $valorTotalNet $valorTotalNet $proDepositNet;
  5185.                         $valorVat $valorVat round($proDepositTotal,2,PHP_ROUND_HALF_UP);
  5186.                     }
  5187.                 }
  5188.             }
  5189.             $valorTotal $valorTotalNet $valorVat;
  5190.             //INICIO: Creamos la factura
  5191.             $newInvoice $em->getRepository(ReservationInvoice::class)->findOneById($id);
  5192.             //FIN: Creamos la factura
  5193.             $allInvoices $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
  5194.             // Buscamos el cliente
  5195.             $reservation $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
  5196.             $client $em->getRepository(Client::class)->findById($reservation->getClient());
  5197.             if (!empty($client)){
  5198.                 $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  5199.                 $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  5200.                 $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  5201.                 $client['city'] = $city$client['region'] = $region$client['country'] = $country;
  5202.             } else {
  5203.                 $client[0] = new Client();
  5204.                 $client[0]->setName('');
  5205.                 $client[0]->setTitle('');
  5206.                 $client[0]->setIdDocument('');
  5207.                 $client[0]->setPopulation('');
  5208.                 $client[0]->setRegion('');
  5209.                 $client[0]->setCountry('');
  5210.             }
  5211.             // Buscamos el cliente
  5212.             $invoiceIdToRec null;
  5213.             $data['prefix'] = $newInvoice->getPrefix();
  5214.             $data['date'] = $newInvoice->getDateAt();
  5215.             $data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  5216.             $data['totales_neto'] = $proDepositNet;
  5217.             $data['totales'] = $proDepositTotal;
  5218.             $data['balance'] = $proDepositTotal;
  5219.             $data['currency'] = '€';
  5220.             $data['datasupplier'] = $newInvoice;
  5221.             $data['bases_imponibles'] = array(
  5222.                 'iva' => $ivaPorcentaje,
  5223.                 'ivaAmount' => ($monto $ivaPorcentaje)/100
  5224.             );
  5225.             $data['paymentInvoice'] = $newInvoice;
  5226.             $dataTemp = array(
  5227.                 'balance' => $data['datasupplier']->getBalance(),
  5228.                 'dateAt' => $data['datasupplier']->getDateAt(),
  5229.                 'id' => $data['datasupplier']->getId(),
  5230.                 'reservationId' => $data['datasupplier']->getReservationId(),
  5231.                 'total' => $data['datasupplier']->getTotal(),
  5232.                 'amount' => $data['datasupplier']->getTotalNet(),
  5233.                 'type' => $data['datasupplier']->getType(),
  5234.                 'vat' => $data['datasupplier']->getVat(),
  5235.                 'name' => $concepto
  5236.             );
  5237.             $data['datasupplier'] = $dataTemp;
  5238.             //Es una proforma
  5239.             $proforma $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  5240.             $invoiceIdToRec null;
  5241.             $reservaEquis $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
  5242.             if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
  5243.                 $newInvoice $this->clientDataToInvoice($newInvoice'Client'$reservaEquis->getClient(), $newInvoice->getReservationId());
  5244.             }
  5245.         } else {
  5246.             if ($type == 'R'){
  5247.                 //El tipo es una factura rectificativa
  5248.                 //INICIO: Creamos los items de la factura rectficativa
  5249.                 $arrayInvoicedItems $em->getRepository(ReservationInvoiceRecItems::class)->findByInvoiceRecId($id);
  5250.                 $vatItem 0;
  5251.                 $concepto ='';
  5252.                 if (!empty($arrayInvoicedItems)) {
  5253.                     foreach ($arrayInvoicedItems as $itemInvoice) {
  5254.                         if ($itemInvoice->getItemType() == 'DEPOSIT') {
  5255.                             //Acumulamos neto e iva para la factura rectificativa
  5256.                             $valorTotalNet $valorTotalNet $itemInvoice->getDepAmount();
  5257.                             $valorVat $valorVat round((($itemInvoice->getDepAmount() * $itemInvoice->getDepIva())/100),2,PHP_ROUND_HALF_UP);
  5258.                             $vatItem $itemInvoice->getDepIva();
  5259.                             $concepto $itemInvoice->getDepName();
  5260.                         }
  5261.                     }
  5262.                 }
  5263.                 $valorTotal $valorTotalNet $valorVat;
  5264.                 //INICIO: Creamos la factura rectificativa
  5265.                 $newInvoice $em->getRepository(ReservationInvoiceRec::class)->findOneById($id);
  5266.                 //FIN: Creamos la factura rectificativa
  5267.                 $paymentsClient = new ReservationPaymentsClient();
  5268.                 $paymentsClient->setReservationId($id);
  5269.                 $reservaInv = new ReservationInvoice();
  5270.                 $reservaInv->setReservationId($id);
  5271.                 $idLounges = array();
  5272.                 $loungesBoolToInvoice = array();
  5273.                 $idPayments = array();
  5274.                 $paymentsBoolToInvoice = array();
  5275.                 $allInvoices $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
  5276.                 //Es una proforma
  5277.                 $proforma $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  5278.                 // Buscamos el cliente
  5279.                 $reservation $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
  5280.                 $client $em->getRepository(Client::class)->findById($reservation->getClient());
  5281.                 if (!empty($client)){
  5282.                     $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  5283.                     $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  5284.                     $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  5285.                     $client['city'] = $city$client['region'] = $region$client['country'] = $country;
  5286.                 } else {
  5287.                     $client[0] = new Client();
  5288.                     $client[0]->setName('');
  5289.                     $client[0]->setTitle('');
  5290.                     $client[0]->setIdDocument('');
  5291.                     $client[0]->setPopulation('');
  5292.                     $client[0]->setRegion('');
  5293.                     $client[0]->setCountry('');
  5294.                 }
  5295.                 // Buscamos el cliente
  5296.                 $invoiceIdToRec $newInvoice->getInvoiceToRec();
  5297.                 $data['number'] = $id;
  5298.                 $data['balance'] = $newInvoice->getBalance();
  5299.                 $data['type'] = 'Invoice Deposit Rec';
  5300.                 $data['prefix'] = 'R';
  5301.                 $data['date'] = $newInvoice->getDateAt();
  5302.                 $data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  5303.                 $data['totales_neto'] = $newInvoice->getTotalNet();
  5304.                 $data['totales'] = $newInvoice->getTotal();
  5305.                 $data['balance'] = $newInvoice->getBalance();
  5306.                 $data['currency'] = '€';
  5307.                 $data['datasupplier'] = $newInvoice;
  5308.                 $data['bases_imponibles'] = array(
  5309.                     'iva' => $vatItem,
  5310.                     'ivaAmount' => $newInvoice->getVat()
  5311.                 );
  5312.                 $data['paymentInvoice'] = $newInvoice;
  5313.                 $dataTemp = array(
  5314.                     'balance' => $data['datasupplier']->getBalance(),
  5315.                     'dateAt' => $data['datasupplier']->getDateAt(),
  5316.                     'id' => $data['datasupplier']->getId(),
  5317.                     'reservationId' => $data['datasupplier']->getReservationId(),
  5318.                     'total' => $data['datasupplier']->getTotal(),
  5319.                     'amount' => $data['datasupplier']->getTotalNet(),
  5320.                     'type' => $data['datasupplier']->getType(),
  5321.                     'vat' => $data['datasupplier']->getVat(),
  5322.                     'name' => $concepto
  5323.                 );
  5324.                 $data['datasupplier'] = $dataTemp;
  5325.                 //Es una proforma
  5326.                 $proforma $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  5327.                 $reservaEquis $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
  5328.                 if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
  5329.                     $newInvoice $this->clientDataToInvoice($newInvoice'Client'$reservaEquis->getClient(), $newInvoice->getReservationId());
  5330.                 }
  5331.             } else {
  5332.                 // El tipo es una proforma de deposito
  5333.                 $data['type'] = 'Proforma Deposit';
  5334.                 $data['number'] = $id;
  5335.                 $proDepositNet 0;
  5336.                 $proDepositIva 0;
  5337.                 $proDepositTotal 0;
  5338.                 //INICIO: Creamos los items de la proforma
  5339.                 $arrayInvoicedItems $em->getRepository(ReservationProformaDeposit::class)->findById($id);
  5340.                 if (!empty($arrayInvoicedItems)) {
  5341.                     foreach ($arrayInvoicedItems as $itemInvoice) {
  5342.                         if (is_numeric($itemInvoice->getAmount()) and is_numeric($itemInvoice->getIva())) {
  5343.                             $proDepositNet $itemInvoice->getAmount();
  5344.                             $proDepositIva = ($itemInvoice->getAmount()*$itemInvoice->getIva())/100;
  5345.                             $proDepositTotal $itemInvoice->getAmount() + (($itemInvoice->getAmount()*$itemInvoice->getIva())/100);
  5346.                             //Acumulamos neto e iva para la factura
  5347.                             $valorTotalNet $valorTotalNet $proDepositNet;
  5348.                             $valorVat $valorVat round($proDepositTotal,2,PHP_ROUND_HALF_UP);
  5349.                         }
  5350.                     }
  5351.                 }
  5352.                 $valorTotal $valorTotalNet $valorVat;
  5353.                 //INICIO: Creamos la factura
  5354.                 $newInvoice $em->getRepository(ReservationProformaDeposit::class)->findOneById($id);
  5355.                 //FIN: Creamos la factura
  5356.                 $allInvoices $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
  5357.                 // Buscamos el cliente
  5358.                 $reservation $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
  5359.                 $client $em->getRepository(Client::class)->findById($reservation->getClient());
  5360.                 if (!empty($client)){
  5361.                     $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
  5362.                     $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
  5363.                     $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
  5364.                     $client['city'] = $city$client['region'] = $region$client['country'] = $country;
  5365.                 } else {
  5366.                     $client[0] = new Client();
  5367.                     $client[0]->setName('');
  5368.                     $client[0]->setTitle('');
  5369.                     $client[0]->setIdDocument('');
  5370.                     $client[0]->setPopulation('');
  5371.                     $client[0]->setRegion('');
  5372.                     $client[0]->setCountry('');
  5373.                 }
  5374.                 // Buscamos el cliente
  5375.                 $invoiceIdToRec null;
  5376.                 $data['prefix'] = $newInvoice->getPrefix();
  5377.                 $data['date'] = $newInvoice->getDateAt();
  5378.                 $data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  5379.                 $data['totales_neto'] = $proDepositNet;
  5380.                 $data['totales'] = $proDepositTotal;
  5381.                 $data['balance'] = $proDepositTotal;
  5382.                 $data['currency'] = '€';
  5383.                 $data['datasupplier'] = $newInvoice;
  5384.                 $data['bases_imponibles'] = array(
  5385.                     'iva' => $newInvoice->getIva(),
  5386.                     'ivaAmount' => ($newInvoice->getAmount() * $newInvoice->getIva())/100
  5387.                 );
  5388.                 $data['paymentInvoice'] = $newInvoice;
  5389.                 $reservaEquis $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
  5390.                 if(true){ $newInvoice $this->clientDataToInvoice(null'Client'$reservaEquis->getClient(), $reservaEquis->getId()); }
  5391.             }
  5392.         }
  5393.         if (!empty($data['bases_imponibles']['iva'])){$bases_imponibles $data['bases_imponibles']['iva'];} else {$bases_imponibles '';}
  5394.         return $this->render('MDS/GreenPatioBundle/reservations/services-proforma-deposit-print-reservation.html.twig',
  5395.             array(
  5396.                 'id' => $id,
  5397.                 'type' => $data['type'],
  5398.                 'number' => $data['number'],
  5399.                 'invoiceIdToRec' => $invoiceIdToRec,
  5400.                 'prefix' => $data['prefix'],
  5401.                 'date' => $data['date'],
  5402.                 'token' => null,
  5403.                 'company' => $data['company'],
  5404.                 'clients' => $client,
  5405.                 'datasupplier' => $data['datasupplier'],
  5406.                 'totales_neto' => $data['totales_neto'],
  5407.                 'bases_imponibles' => $data['bases_imponibles'],
  5408.                 'totales' => $data['totales'],
  5409.                 'balance' => $data['balance'],
  5410.                 'currency' => $data['currency'],
  5411.                 'iva' => $bases_imponibles,
  5412.                 'paymentInvoice' => $data['paymentInvoice'],
  5413.                 'clientName' => $newInvoice->getClientName(),
  5414.                 'clientAddress' => $newInvoice->getClientAddress(),
  5415.                 'clientDocument' => $newInvoice->getClientDocument(),
  5416.             )
  5417.         );
  5418.     }
  5419.     /**
  5420.      * @Route("/instantUpdateInvoice", name="instant_update_invoice")
  5421.      */
  5422.     public function instantUpdateInvoiceAction(Request $request) {
  5423.         $codProfile $_POST['idprofile'];
  5424. //        $codProfile = "1";
  5425. //        $codProfile = $request->request->get('idProfile');
  5426. //        $codProfile = $idProfile;
  5427.         $em $this->getDoctrine()->getManager();
  5428.         $salasPorPerfil $em->getRepository(ReservationLoungeProfile::class)->findBy(
  5429.             array(
  5430.                 'periodId' => $codProfile
  5431.             )
  5432.         );
  5433.         $datos = array();
  5434.         if (!empty($salasPorPerfil)){
  5435.             foreach($salasPorPerfil as $sala){
  5436.                 $datos[] = array(
  5437.                     "id" => $sala->getId(),
  5438.                     "idlounge" => $sala->getLoungeId(),
  5439.                     "nameDescription" => $sala->getDescription(),
  5440.                     "price" => $sala->getPrice(),
  5441.                 );
  5442.             }
  5443.         }
  5444.         $return = array(
  5445.             'salasPerfil' => $datos,
  5446.             'id' => $codProfile,
  5447.         );
  5448.         $response = new JsonResponse($return);
  5449.         return $response;
  5450.     }
  5451.     /**
  5452.      * @Route("/invoicerec/{id}",  name="reservations_invoice_rec")
  5453.      */
  5454.     public function generateReservationInvoiceRecAction($idRequest $request)
  5455.     {
  5456.         $em $this->getDoctrine()->getManager();
  5457.         $invoice $em->getRepository(ReservationInvoice::class)->findOneById($id);
  5458.         if (true){
  5459.             // Verificamos que no exista una factura rectificativa previa sobre la misma factura
  5460.             $previusInvoiceRec $em->getRepository(ReservationInvoiceRec::class)->findOneByInvoiceToRec($id);
  5461.             if (!empty($previusInvoiceRec)){ return $this->redirectToRoute('reservations_viewrec_invoice', array('id' => $previusInvoiceRec->getId())); }
  5462.         }
  5463.         $now = new DateTime();
  5464.         /* Obtengo usuario logueado */
  5465.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  5466.         $user_id $user_logueado->getId();
  5467.         $invoiceRec = new ReservationInvoiceRec();
  5468.         $invoiceRec->setInvoiceToRec($id);
  5469.         $invoiceRec->setCreatedAt($now);
  5470.         $invoiceRec->setUpdatedAt($now);
  5471.         $invoiceRec->setCreatedId($user_id);
  5472.         $invoiceRec->setUpdatedId($user_id);
  5473.         $invoiceRec->setDateAt($now);
  5474.         $invoiceRec->setMaster($invoice->getMaster());
  5475.         $invoiceRec->setNumber('REC-'.$invoice->getNumber());
  5476.         $invoiceRec->setPrefix('R');
  5477.         $invoiceRec->setReservationId($invoice->getReservationId());
  5478.         $invoiceRec->setTotal($invoice->getTotal()*(-1));
  5479.         $invoiceRec->setTotalNet($invoice->getTotalNet()*(-1));
  5480.         $invoiceRec->setType('Invoice Rec');
  5481.         $invoiceRec->setVat($invoice->getVat()*(-1));
  5482.         $invoiceRec->setBalance($invoice->getBalance()*(-1));
  5483.         $invoiceRec->setClientName($invoice->getClientName());
  5484.         $invoiceRec->setClientAddress($invoice->getClientAddress());
  5485.         $invoiceRec->setClientDocument($invoice->getClientDocument());
  5486.         $invoiceRec->setClientType($invoice->getClientType());
  5487.         $em->persist($invoiceRec);
  5488.         $em->flush();
  5489.         $invoiceItems $em->getRepository(ReservationInvoiceItems::class)->findByInvoiceId($id);
  5490.         // Cada elemento se duplica en ItemsRec y se libera asignando ID = 0
  5491.         foreach ($invoiceItems as $item){
  5492.             $itemRec = new ReservationInvoiceRecItems();
  5493.             $itemRec->setReservationId($item->getReservationId());
  5494.             $itemRec->setInvoiceId($item->getInvoiceId());
  5495.             $itemRec->setItemType($item->getItemType());
  5496.             $itemRec->setInvoiceRecId($invoiceRec->getId());
  5497.             $itemRec->setLngControlId($item->getLngControlId());
  5498.             $itemRec->setLngLoungeName($item->getLngLoungeName());
  5499.             $itemRec->setLngIdLounge($item->getLngIdLounge());
  5500.             $itemRec->setLngIdLounge($item->getLngIdLounge());
  5501.             $itemRec->setLngDateStart($item->getLngDateStart());
  5502.             $itemRec->setLngDateEnd($item->getLngDateEnd());
  5503.             $itemRec->setLngServicePrice($item->getLngServicePrice()*(-1));
  5504.             $itemRec->setLngPax($item->getLngPax());
  5505.             $itemRec->setLngType($item->getLngType());
  5506.             $itemRec->setLngHourStart($item->getLngHourStart());
  5507.             $itemRec->setLngMinStart($item->getLngMinStart());
  5508.             $itemRec->setLngHourEnd($item->getLngHourEnd());
  5509.             $itemRec->setLngMinEnd($item->getLngMinEnd());
  5510.             $itemRec->setLngIva($item->getLngIva());
  5511.             $itemRec->setLngOpIva($item->getLngOpIva());
  5512.             $itemRec->setSrvControlId($item->getSrvControlId());
  5513.             $itemRec->setSrvSupplierId($item->getSrvSupplierId());
  5514.             $itemRec->setSrvServiceId($item->getSrvServiceId());
  5515.             $itemRec->setSrvServiceCatId($item->getSrvServiceCatId());
  5516.             $itemRec->setSrvServiceCatName($item->getSrvServiceCatName());
  5517.             $itemRec->setSrvPrice($item->getSrvPrice()*(-1));
  5518.             $itemRec->setSrvCurrency($item->getSrvCurrency());
  5519.             $itemRec->setSrvUnits($item->getSrvUnits());
  5520.             $itemRec->setSrvOpCommission($item->getSrvOpCommission());
  5521.             $itemRec->setSrvCommission($item->getSrvCommission());
  5522.             $itemRec->setSrvOpOver($item->getSrvOpOver());
  5523.             $itemRec->setSrvOver($item->getSrvOver()*(-1));
  5524.             $itemRec->setSrvOpIva($item->getSrvOpIva());
  5525.             $itemRec->setSrvIva($item->getSrvIva());
  5526.             $itemRec->setSrvPax($item->getSrvPax());
  5527.             $itemRec->setSrvHour($item->getSrvHour());
  5528.             $itemRec->setSrvDateInAt($item->getSrvDateInAt());
  5529.             $itemRec->setSrvDateOutAt($item->getSrvDateOutAt());
  5530.             $itemRec->setSrvContcolor($item->getSrvContcolor());
  5531.             $itemRec->setSrvRank($item->getSrvRank());
  5532.             $itemRec->setSrvAssistantId($item->getSrvAssistantId());
  5533.             $itemRec->setSrvActivityId($item->getSrvActivityId());
  5534.             $itemRec->setSrvPay($item->getSrvPay());
  5535.             $itemRec->setSrvName($item->getSrvName());
  5536.             $itemRec->setPayControlId($item->getPayControlId());
  5537. //            $itemRec->setPayAmount($item->getPayAmount()*(-1));
  5538.             $itemRec->setPayAmount($item->getPayAmount());          // Los pagos han pasado a ser las facturas de deposito, en la tabla su amount se encuentra en positivo, en la rectificativa, este valor lo necesitamos en positivo
  5539.             $itemRec->setPayDatePayAt($item->getPayDatePayAt());
  5540.             $itemRec->setPayWayToPay($item->getPayWayToPay());
  5541. //            $itemRec->setPayAmountTotal($item->getPayAmountTotal()*(-1));
  5542.             $itemRec->setPayAmountTotal($item->getPayAmountTotal());    // Los pagos han pasado a ser las facturas de deposito, en la tabla su amount se encuentra en positivo, en la rectificativa, este valor lo necesitamos en positivo
  5543.             $itemRec->setPayVat($item->getPayVat());
  5544.             $itemRec->setCreatedId($user_id);
  5545.             $itemRec->setCreatedAt(new DateTime('now'));
  5546.             $itemRec->setUpdatedId($user_id);
  5547.             $itemRec->setUpdatedAt(new DateTime('now'));
  5548.             $em->persist($itemRec);
  5549.             $em->flush();
  5550.             // Se libera asignando ID = 0
  5551.             $item->setLngControlId(0);
  5552.             $item->setSrvControlId(0);
  5553.             $item->setPayControlId(0);
  5554.             $em->persist($item);
  5555.             $em->flush();
  5556.         }
  5557.         $allInvoices $em->getRepository(ReservationInvoice::class)->findByReservationId($invoice->getReservationId());
  5558.         $allInvoicesRec $em->getRepository(ReservationInvoiceRec::class)->findByReservationId($invoice->getReservationId());
  5559.         foreach ($allInvoicesRec as $item){ array_push($allInvoices$item); }
  5560.         $reservation $em->getRepository(Reservation::class)->findOneById($invoice->getReservationId());
  5561.         $client $em->getRepository(Client::class)->findOneById($reservation->getClient());
  5562.         $data = array();
  5563.         $data['clients'][0] = $client;
  5564.         $data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  5565.         $data['datasupplier'] = '';
  5566.         $data['totales_neto'] = '';
  5567.         $data['totales'] = '';
  5568.         $data['bases_imponibles'] = '';
  5569.         $data['balance'] = '';
  5570.         $data['paymentInvoice'] = '';
  5571.         $data['currency'] = '';
  5572.         // Una factura solo se puede rectificar una vez
  5573.         $rectf $em->getRepository(ReservationInvoiceRec::class)->findBy( array('number' => 'REC-'.$invoice->getNumber()));
  5574.         $boolToRec = empty($rectf);
  5575.         return $this->redirectToRoute('reservations_viewrec_invoice', array('id' => $invoiceRec->getId()));
  5576.     }
  5577.     /**
  5578.      * @Route("/reservations/invoicedeposit/proforma/{id}",  name="reservation_invoice_deposit_proforma")
  5579.      */
  5580.     public function detailsProformaAction($idRequest $request)
  5581.     {
  5582.         $em $this->getDoctrine()->getManager();
  5583.         $reservation $em->getRepository(Reservation::class)->findOneById($id);
  5584.         $invoicedepositcontrol $em->getRepository(ReservationInvoiceDepositControl::class)->findByReservationId($id);
  5585.         $invoicedeposit = new ReservationInvoiceDepositItems();
  5586.         $invoicedeposit->setReservationId($id);
  5587.         $form $this->createReservationInvoiceDepositItemsForm($invoicedeposit);
  5588.         $controlId null;
  5589.         $type "Proforma";
  5590.         $prefix "PFD-";
  5591.         $date = new \DateTime('now');
  5592.         $data $this->baseInvoiceDepositReservation($id$controlId$type$id$prefix$date$request);
  5593.         return $this->render('MDS/GreenPatioBundle/reservations/invoice-deposit-proforma.html.twig',
  5594.             array(
  5595.                 'id' => $id,
  5596.                 'cid' => $data['cid'],
  5597.                 'numberadmin' => null,
  5598.                 'type' => $data['type'],
  5599.                 'invoice' => $invoicedepositcontrol,
  5600.                 'number' => $data['number'],
  5601.                 'prefix' => $data['prefix'],
  5602.                 'date' => $data['date'],
  5603.                 'token' =>  $data['token'],
  5604.                 'reservation' => $data['reservation'],
  5605.                 'company' => $data['company'],
  5606.                 'clients' => $data['clients'],
  5607.                 'invoicedeposititems' => $data['invoicedeposititems'],
  5608.                 'totales_neto' => $data['totales_neto'],
  5609.                 'totales_iva' => $data['totales_iva'],
  5610.                 'totales' => $data['totales'],
  5611.                 'bases_imponibles' => $data['ivas'],
  5612.                 'currency' => $data['currency'],
  5613.                 'form' => $form->createView(),
  5614. //                'mcp' => $proposal->getMcp(),
  5615.             )
  5616.         );
  5617.     }
  5618.     private function createReservationInvoiceDepositItemsForm(ReservationInvoiceDepositItems $entity)
  5619.     {
  5620.         $form $this->createForm(ReservationInvoiceDepositItemsType::class, $entity, array(
  5621.             'action' => $this->generateUrl('reservation_invoice_Deposit_proforma_add'),
  5622.             'method' => 'POST'
  5623.         ));
  5624.         return $form;
  5625.     }
  5626.     private function baseInvoiceDepositReservation($id$controlId$type$number$prefix$dateRequest $request)
  5627.     {
  5628.         $em $this->getDoctrine()->getManager();
  5629.         $reservation $em->getRepository(Reservation::class)->findOneById($id);
  5630.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
  5631.         $parameters = array(
  5632.             'id' => $reservation->getClient(),
  5633.         );
  5634.         $dql 'SELECT cl,  c.country, re.region, p.name, r.city
  5635.                 FROM App:Client cl
  5636.                 INNER JOIN App:Country c WITH c.id = cl.country
  5637.                 INNER JOIN App:Regions re WITH re.id = cl.region
  5638.                 INNER JOIN App:Provinces p WITH p.id = cl.province
  5639.                 INNER JOIN App:Cities r WITH r.id = cl.population
  5640.                 WHERE cl.id = :id';
  5641.         $query $em->createQuery($dql)->setParameters($parameters);
  5642.         $client $query->getResult();
  5643.         if (!is_null($controlId)){
  5644.             $invoicecontrol $em->getRepository(ReservationInvoiceDepositControl::class)->findOneById($controlId);
  5645.             if (!is_null($invoicecontrol->getNumber())){
  5646.                 $numberadmin $invoicecontrol->getNumber();
  5647.             }else{
  5648.                 $numberadmin null;
  5649.             }
  5650.         }else{
  5651.             $numberadmin null;
  5652.         }
  5653.         $invoicedeposititems $em->getRepository(ReservationInvoiceDepositItems::class)->findBy(
  5654.             array(
  5655.                 'reservationId' => $id,
  5656.                 'controlId' => $controlId,
  5657.             )
  5658.         );
  5659.         $totales_neto_all "0";
  5660.         $totales_iva_all "0";
  5661.         $totales_con_iva_all "0";
  5662.         $data_iva = array();
  5663.         $data_deposititems = array();
  5664.         foreach($invoicedeposititems as $deposititems){
  5665.             $amount $deposititems->getAmount();
  5666.             $iva_base $deposititems->getIva();
  5667.             $iva $iva_base 100;
  5668.             if($iva_base !='0'){
  5669.                 $amount_iva $amount $iva;
  5670.             }else{
  5671.                 $amount_iva "0";
  5672.             }
  5673.             $amount_con_iva $amount $amount_iva;
  5674.             $totales_neto_all += $amount;
  5675.             $totales_iva_all += $amount_iva;
  5676.             $totales_con_iva_all += $amount_con_iva;
  5677.             if (empty($totales_ivas_all[$iva_base])){
  5678.                 $totales_ivas_all[$iva_base]= 0;
  5679.             }
  5680.             $totales_ivas_all[$iva_base] += $amount_iva;
  5681.             $data_iva[$iva_base] = array(
  5682.                 'iva' => $iva_base,
  5683.                 'ivas' => $totales_ivas_all[$iva_base],
  5684.             );
  5685.             $data_deposititems[] = array(
  5686.                 'id' => $deposititems->getId(),
  5687.                 'name' => $deposititems->getName(),
  5688.                 'amount' => $amount,
  5689.                 'iva' => $iva_base,
  5690.                 'total' => $amount_con_iva
  5691.             );
  5692.         }
  5693.         $currency ="€";
  5694.         $data = array(
  5695.             'id' => $id,
  5696.             'cid' => $controlId,
  5697.             'type' => $type,
  5698.             'number' => $number,
  5699.             'prefix' => $prefix,
  5700.             'numberadmin' => $numberadmin,
  5701.             'date' => $date,
  5702.             'token' => $reservation->getAccessKey(),
  5703.             'reservation' => $reservation,
  5704.             'company' => $company,
  5705.             'clients' => $client,
  5706.             'invoicedeposititems' => $data_deposititems,
  5707.             'totales_neto' => $totales_neto_all,
  5708.             'totales_iva' => $totales_iva_all,
  5709.             'totales' => $totales_con_iva_all,
  5710.             'ivas' => $data_iva,
  5711.             'currency' => $currency,
  5712.         );
  5713.         return $data;
  5714.     }
  5715.     /**
  5716.      * @Route("/reservations/invoicedeposit/add", name="reservation_invoice_Deposit_proforma_add")
  5717.      */
  5718.     public function createDepositAction(Request $request)
  5719.     {
  5720.         $invoicedeposit = new ReservationInvoiceDepositItems();
  5721.         $form $this->createReservationInvoiceDepositItemsForm($invoicedeposit);
  5722.         $form->handleRequest($request);
  5723.         if($form->isValid())
  5724.         {
  5725.             $em $this->getDoctrine()->getManager();
  5726.             /* Obtengo usuario logueado */
  5727.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  5728.             $user_id $user_logueado->getId();
  5729.             $invoicedeposit->setCreatedId($user_id);
  5730.             $invoicedeposit->setUpdatedId($user_id);
  5731.             /* Gestión de eventos en Log */
  5732.             $user_lastname $user_logueado->getLastname();
  5733.             $user_name $user_logueado->getName();
  5734.             $user_email $user_logueado->getEmail();
  5735.             $user_rol $user_logueado->getRoles();
  5736.             $event_url $request->getPathInfo();
  5737.             $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  5738.             $em->persist($invoicedeposit);
  5739.             $em->flush();
  5740.             $event 'the Items was registered';
  5741.             $successMessage $this->translator->trans($event);
  5742.             $this->addFlash('mensajeinvoicedepositservices'$successMessage);
  5743.             return $this->redirectToRoute('reservation_invoice_deposit_proforma',
  5744.                 array(
  5745.                     'id' => $invoicedeposit->getReservationId()
  5746.                 ));
  5747.         } else {
  5748.             $errorMessage $this->translator->trans('Error, some fields are empty');
  5749.             $this->addFlash('mensajeinvoicedepositserviceserror'$errorMessage);
  5750.         }
  5751.         return $this->redirectToRoute('reservation_invoice_deposit_proforma', array('id' => $invoicedeposit->getReservationId()));
  5752.     }
  5753.     /**
  5754.      * @Route("/reservations/invoicedeposit/invoice/{id}/{fid}", defaults={"fid" = ""}, name="reservation_invoice_deposit")
  5755.      */
  5756.     public function detailsInvoiceDepositAction($id$fidRequest $request)
  5757.     {
  5758.         $data = array();
  5759.         $em $this->getDoctrine()->getManager();
  5760.         $reservation $em->getRepository(Reservation::class)->findOneById($id);
  5761.         $invoicecontrol $em->getRepository(ReservationInvoiceDepositControl::class)->findByReservationId($id);
  5762. //        $number = $invoicecontrol->getNumber();
  5763.         $prefix "IFD-";
  5764.         if (empty($fid)){
  5765.             $invoicedeposititems $em->getRepository(ReservationInvoiceDepositItems::class)->findBy(
  5766.                 array(
  5767.                     'reservationId' => $id,
  5768.                     'controlId' => null,
  5769.                 )
  5770.             );
  5771.             if (!empty($invoicedeposititems)){
  5772.                 /* Obtengo usuario logueado */
  5773.                 $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  5774.                 $user_id $user_logueado->getId();
  5775.                 $invoicedeposit = new ReservationInvoice();
  5776.                 $invoicedeposit->setDateAt(new \DateTime());
  5777.                 $invoicedeposit->setMaster('0');
  5778.                 $invoicedeposit->setNumber('0');
  5779.                 $invoicedeposit->setType('Invoice Deposit');
  5780.                 $invoicedeposit->setReservationId($id);
  5781.                 $invoicedeposit->setPrefix('');
  5782.                 $invoicedeposit->setTotal('0');
  5783.                 $invoicedeposit->setTotalNet('0');
  5784.                 $invoicedeposit->setVat('0');
  5785.                 $invoicedeposit->setCreatedId($user_id);
  5786.                 $invoicedeposit->setUpdatedId($user_id);
  5787.                 $invoicedeposit->setCreatedAt(new \DateTime());
  5788.                 $invoicedeposit->setUpdatedAt(new \DateTime());
  5789.                 $em->persist($invoicedeposit);
  5790.                 $em->flush();
  5791.                 $number $invoicedeposit->getId();
  5792.                 $invoicedepositcontrol = new ReservationInvoiceDepositControl();
  5793.                 $invoicedepositcontrol->setReservationId($id);
  5794.                 $invoicedepositcontrol->setNumber($invoicedeposit->getId());
  5795.                 $invoicedepositcontrol->setDateAt(new \DateTime("now"));
  5796.                 $invoicedepositcontrol->setPrefix($prefix);
  5797.                 $invoicedepositcontrol->setCreatedId($user_id);
  5798.                 $invoicedepositcontrol->setUpdatedId($user_id);
  5799.                 $em->persist($invoicedepositcontrol);
  5800.                 $em->flush();
  5801.                 $invoiceSQL $em->getRepository(ReservationInvoice::class)->findOneById($invoicedeposit->getId());
  5802.                 $invoiceSQL->setMaster($invoicedepositcontrol->getId());
  5803.                 $invoiceSQL->setNumber($invoicedepositcontrol->getId());
  5804.                 $em->persist($invoiceSQL);
  5805.                 $em->flush();
  5806.                 $controlId $invoicedepositcontrol->getId();
  5807.                 $date $invoicedepositcontrol->getDateAt();
  5808.                 foreach($invoicedeposititems as $invoicedeposit){
  5809.                     $invoicedeposit->setControlId($controlId);
  5810.                     $em->persist($invoicedeposit);
  5811.                 }
  5812.                 $em->flush();
  5813.                 return $this->redirectToRoute('reservation_invoice_deposit',
  5814.                     array(
  5815.                         'id' => $id,
  5816.                         'fid' => $invoicedepositcontrol->getId(),
  5817.                     )
  5818.                 );
  5819.             }else{
  5820.                 return $this->redirectToRoute('reservation_invoice_deposit_proforma',
  5821.                     array(
  5822.                         'id' => $id
  5823.                     )
  5824.                 );
  5825.             }
  5826.         }else{
  5827.             $invoicedepositcontrolconsulta $em->getRepository(ReservationInvoiceDepositControl::class)->findOneBy(
  5828.                 array(
  5829.                     'reservationId' => $id,
  5830.                     'id' => $fid
  5831.                 )
  5832.             );
  5833.             $controlId $invoicedepositcontrolconsulta->getId();
  5834.             $date $invoicedepositcontrolconsulta->getDateAt();
  5835.         }
  5836.         $number $id;
  5837.         $type "Invoice";
  5838.         $data $this->baseInvoiceDepositReservation($id$controlId$type$number$prefix$date$request);
  5839.         /* Obtengo usuario logueado */
  5840.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  5841.         $user_id $user_logueado->getId();
  5842.         if ($reservation->getStatus() != 'Invoiced'){
  5843.             $reservation->setStatus('Confirmed');
  5844.             $em->persist($reservation);
  5845.             $em->flush();
  5846.         }
  5847.         // Una factura solo se puede rectificar una vez
  5848.         $rectf $em->getRepository(ReservationInvoiceRec::class)->findByInvoiceToRec($number);
  5849.         $boolToRec = empty($rectf);
  5850.         $newclient[] = $data['clients'];
  5851.         return $this->render('MDS/GreenPatioBundle/reservations/invoice-deposit-invoice.html.twig',
  5852.             array(
  5853.                 'id' => $id,
  5854.                 'cid' => $data['cid'],
  5855.                 'fid' => $controlId,
  5856.                 'invoice' => $invoicecontrol,
  5857.                 'numberadmin' => $data['numberadmin'],
  5858.                 'type' => $data['type'],
  5859.                 'number' => $data['number'],
  5860.                 'prefix' => $data['prefix'],
  5861.                 'date' => $data['date'],
  5862.                 'token' =>  $data['token'],
  5863.                 'reservation' => $data['reservation'],
  5864.                 'company' => $data['company'],
  5865.                 'clients' => $newclient,
  5866.                 'user' => $user_logueado,
  5867.                 'boolToRec' => $boolToRec,
  5868.                 'invoicedeposititems' => $data['invoicedeposititems'],
  5869.                 'totales_neto' => $data['totales_neto'],
  5870.                 'totales_iva' => $data['totales_iva'],
  5871.                 'totales' => $data['totales'],
  5872.                 'bases_imponibles' => $data['ivas'],
  5873.                 'currency' => $data['currency'],
  5874. //                'mcp' => $proposal->getMcp(),
  5875.             )
  5876.         );
  5877.     }
  5878.     /**
  5879.      * @Route("/reservations/invoicedeposit/number/updated/{cid}/{id}", name="reservation_invoicedeposit_number_update")
  5880.      */
  5881.     public function InvoiceEmptyNumberInvoiceDepositUpdateAction($cid$idRequest $request)
  5882.     {
  5883.         $em $this->getDoctrine()->getManager();
  5884.         $invoice $em->getRepository(ReservationInvoiceDepositControl::class)->findOneById($id);
  5885.         $numberinvoice $request->request->get('invoice')['number'];
  5886.         if(!empty($numberinvoice) and !is_null($invoice))
  5887.         {
  5888.             $invoice->setNumber($numberinvoice);
  5889.             /* Obtengo usuario logueado */
  5890.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  5891.             $user_id $user_logueado->getId();
  5892.             $invoice->setUpdatedId($user_id);
  5893.             $em->persist($invoice);
  5894.             $em->flush();
  5895.             $event 'The Invoice Deposit has been Updated.';
  5896.             $successMessage $this->translator->trans($event);
  5897.             $this->addFlash('mensajeinvoicedepositservices'$successMessage);
  5898.         }else{
  5899.             $errorMessage $this->translator->trans('Error, some fields are empty');
  5900.             $this->addFlash('mensajeinvoicedepositserviceserror'$errorMessage);
  5901.         }
  5902.         return $this->redirectToRoute('reservation_invoice_deposit',
  5903.             array(
  5904.                 'id' => $cid,
  5905.                 'fid' => $id,
  5906.             )
  5907.         );
  5908.     }
  5909.     /**
  5910.      * @Route("/reservations/invoicedepositdelete/invoice/{id}/{fid}", defaults={"fid" = ""}, name="reservation_invoice_deposit_delete")
  5911.      */
  5912.     public function deleteInvoiceDepositAction($id$fidRequest $request)
  5913.     {
  5914.         $em $this->getDoctrine()->getManager();
  5915.         // INICIO: Buscamos en ITEMS los elementos que coincidan
  5916.         $invoicedeposititems $em->getRepository(ReservationInvoiceDepositItems::class)->findBy(
  5917.             array(
  5918.                 'reservationId' => $id,
  5919.                 'controlId' => $fid
  5920.             )
  5921.         );
  5922.         foreach ($invoicedeposititems as $item){
  5923.             $em->remove($item);
  5924.             $em->flush();
  5925.         }
  5926.         // FIN: Buscamos en ITEMS los elementos que coincidan
  5927.         // INICIO: Buscamos en CONTROL los elementos que coincidan
  5928.         $invoicedepositcontrol $em->getRepository(ReservationInvoiceDepositControl::class)->findBy(
  5929.             array(
  5930.                 'reservationId' => $id,
  5931.                 'id' => $fid
  5932.             )
  5933.         );
  5934.         foreach ($invoicedepositcontrol as $item){
  5935.             $numberDeposit $item->getNumber();
  5936.             $em->remove($item);
  5937.             $em->flush();
  5938.         }
  5939.         // FIN: Buscamos en CONTROL los elementos que coincidan
  5940.         /* Obtengo usuario logueado */
  5941.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  5942.         $user_id $user_logueado->getId();
  5943.         $now = new DateTime('now');
  5944.         $tracingDeleteDeposit = new ReservationTracing();
  5945.         $tracingDeleteDeposit->setDateAt($now);
  5946.         $tracingDeleteDeposit->setCreatedAt($now);
  5947.         $tracingDeleteDeposit->setUpdatedAt($now);
  5948.         $tracingDeleteDeposit->setText('Ha eliminado la Factura de deposito No. '.$numberDeposit);
  5949.         $tracingDeleteDeposit->setAgentId($user_id);
  5950.         $tracingDeleteDeposit->setReservationId($id);
  5951.         $tracingDeleteDeposit->setViewed('no');
  5952.         $tracingDeleteDeposit->setCreatedId($user_id);
  5953.         $tracingDeleteDeposit->setUpdatedId($user_id);
  5954.         try{
  5955.             $em->persist($tracingDeleteDeposit);
  5956.             $em->flush();
  5957.             $event 'The item has been deleted.';
  5958.             $successMessage $this->translator->trans($event);
  5959.             $this->addFlash('mensajereservation'$successMessage);
  5960.         } catch (\Exception $e){
  5961.             $event 'An error occurred: '.$e->getMessage();
  5962.             $errorMessage $this->translator->trans($event);
  5963.             $this->addFlash('mensajereservationerror'$errorMessage);
  5964.         }
  5965.         return $this->redirectToRoute('reservation_invoice_deposit_proforma',
  5966.             array('id' => $id));
  5967.     }
  5968.     /**
  5969.      * @Route("/reservations/invoicedeposit/print/invoice/{id}/{fid}",  name="reservation_invoice_deposit_invoice_print_externo")
  5970.      */
  5971.     public function printdetailsInvoicedepositAction($id$fidRequest $request)
  5972.     {
  5973.         $data = array();
  5974.         $em $this->getDoctrine()->getManager();
  5975.         $invoicedepositcontrolconsulta $em->getRepository(ReservationInvoiceDepositControl::class)->findOneBy(
  5976.             array(
  5977.                 'reservationId' => $id,
  5978.                 'id' => $fid
  5979.             )
  5980.         );
  5981.         $type "Invoice";
  5982.         $controlId $invoicedepositcontrolconsulta->getId();
  5983.         $date $invoicedepositcontrolconsulta->getDateAt();
  5984.         $prefix $invoicedepositcontrolconsulta->getPrefix();
  5985.         $data $this->baseInvoiceDepositReservation($id$controlId$type$id$prefix$date$request);
  5986.         return $this->render('MDS/GreenPatioBundle/reservations/print-invoice-deposit-proforma.html.twig',
  5987.             array(
  5988.                 'id' => $id,
  5989.                 'type' => $data['type'],
  5990.                 'number' => $data['number'],
  5991.                 'prefix' => $data['prefix'],
  5992.                 'numberadmin' => $data['numberadmin'],
  5993.                 'date' => $data['date'],
  5994.                 'token' =>  $data['token'],
  5995.                 'reservation' => $data['reservation'],
  5996.                 'company' => $data['company'],
  5997.                 'clients' => $data['clients'],
  5998.                 'invoicedeposititems' => $data['invoicedeposititems'],
  5999.                 'totales_neto' => $data['totales_neto'],
  6000.                 'totales_iva' => $data['totales_iva'],
  6001.                 'totales' => $data['totales'],
  6002.                 'bases_imponibles' => $data['ivas'],
  6003.                 'currency' => $data['currency'],
  6004.             )
  6005.         );
  6006.     }
  6007.     /**
  6008.      * @Route("/reservations/invoicedeposit/deleted/items/{id}", name="reservation_invoice_deposit_invoice_deleted_items")
  6009.      *
  6010.      */
  6011.     public function deleteItemsInvoiceDepositAction($idRequest $request)
  6012.     {
  6013.         $em $this->getDoctrine()->getManager();
  6014.         $delete $em->getRepository(ReservationInvoiceDepositItems::class)->findOneById($id);
  6015.         $em->remove($delete);
  6016.         $em->flush();
  6017.         $event 'The item in the deposit proforma has been removed';
  6018.         $successMessage $this->translator->trans($event);
  6019.         $this->addFlash('mensajeinvoicedepositservices'$successMessage);
  6020.         return $this->redirectToRoute('reservation_invoice_deposit_proforma', array( 'id' => $delete->getReservationId(), ));
  6021.     }
  6022.     /**
  6023.      * @Route("/reservations/invoice/list", name="reservation_invoice_list")
  6024.      */
  6025.     public function indexAction(Request $request) {
  6026.         $em $this->getDoctrine()->getManager();
  6027.         $todayTwoYearAgo = new DateTime('now -2 year');
  6028.         $parameters = array( 'dateStart' => $todayTwoYearAgo, );
  6029.         $dql 'SELECT p
  6030.                 FROM GreenPatioBundle:ReservationInvoice p
  6031.                 WHERE p.dateAt > :dateStart';
  6032.         $query $em->createQuery($dql)->setParameters($parameters);
  6033.         $invoiced $em->getRepository(ReservationInvoice::class)->findAll();
  6034.         $invoiced $query->getResult();
  6035.         $parameters = array( 'dateStart' => $todayTwoYearAgo, );
  6036.         $dql 'SELECT p
  6037.                 FROM GreenPatioBundle:ReservationInvoiceRec p
  6038.                 WHERE p.dateAt > :dateStart';
  6039.         $query $em->createQuery($dql)->setParameters($parameters);
  6040.         $invoicedRec $em->getRepository(ReservationInvoiceRec::class)->findAll();
  6041.         $invoicedRec $query->getResult();
  6042.         // Agregamos las rectificativas al arreglo de facturas con el indice "R(id)"
  6043.         foreach ($invoicedRec as $idRecArray => $item){
  6044.             $invoiced['R'.$item->getId()] = $item;
  6045.         }
  6046.         $sumatoriaTotalNet 0;
  6047.         $sumatoriaTotalVat 0;
  6048.         $sumatoriaTotal 0;
  6049.         foreach ($invoiced as $idArray => $item){
  6050.             $reserva $em->getRepository(Reservation::class)->findOneById($item->getReservationId());
  6051.             $invoiced[$idArray]->setNumber($reserva->getTitle());
  6052.             $client $em->getRepository(Client::class)->findOneById($reserva->getClient());
  6053.             if(!empty($client)){
  6054.                 $invoiced[$idArray]->setPrefix($client->getName());
  6055.             } else {
  6056.                 $invoiced[$idArray]->setPrefix('');
  6057.             }
  6058.             $estaEnFactura false;
  6059.             $estaEnFacturaRectificativa false;
  6060.             if ($item->getType() == 'Invoice Deposit'){
  6061.                 // Si la factura de deposito se encuentra en una factura sumara 0
  6062.                 // INICIO: Verificamos factura de deposito dentro de alguna factura
  6063.                 $payOfInvoiceDeposit $em->getRepository(ReservationPaymentsClient::class)->findOneByInvoiceId($item->getId());
  6064.                 if (!empty($payOfInvoiceDeposit)){
  6065.                     // Verificamos si el deposito esta dentro de una factura
  6066.                     $itemInvoiceOfInvoiceDeposit $em->getRepository(ReservationInvoiceItems::class)->findOneByPayControlId($payOfInvoiceDeposit->getId());
  6067.                 }
  6068.                 if (!empty($itemInvoiceOfInvoiceDeposit)){
  6069.                     $estaEnFactura true;
  6070.                 } else {
  6071.                     // Verificamos que el control Id no haya sido seteado a 0 por rectificar la factura
  6072.                     if (!empty($payOfInvoiceDeposit)) {
  6073.                         $itemInvoiceOfInvoiceDeposit $em->getRepository(ReservationInvoiceRecItems::class)->findOneByPayControlId($payOfInvoiceDeposit->getId());
  6074.                         if (!empty($itemInvoiceOfInvoiceDeposit)) {
  6075.                             $estaEnFactura true;
  6076.                         }
  6077.                     }
  6078.                 }
  6079.                 if (!empty($payOfInvoiceDeposit)){
  6080.                     // Verificamos si el deposito esta dentro de una factura rectificativa
  6081.                     $itemInvoiceOfInvoiceDepositRec $em->getRepository(ReservationInvoiceRecItems::class)->findOneByPayControlId($payOfInvoiceDeposit->getId());
  6082.                 }
  6083.                 if (!empty($itemInvoiceOfInvoiceDepositRec)){
  6084.                     $estaEnFacturaRectificativa true;
  6085.                 }
  6086.                 // FIN: Verificamos factura de deposito dentro de alguna factura
  6087.                 $invoicedDepositItems $em->getRepository(ReservationInvoiceDepositItems::class)->findByControlId($item->getMaster());
  6088.                 foreach ($invoicedDepositItems as $itemDep){
  6089.                         $invoiced[$idArray]->setTotalNet($invoiced[$idArray]->getTotalNet() + $itemDep->getAmount());
  6090.                         $invoiced[$idArray]->setVat($invoiced[$idArray]->getVat() + (($itemDep->getAmount() * $itemDep->getIva())/100));
  6091.                         $invoiced[$idArray]->setTotal($invoiced[$idArray]->getTotal() + ($itemDep->getAmount() + (($itemDep->getAmount() * $itemDep->getIva())/100)));
  6092.                 }
  6093.             }
  6094.             // Sumara cuando ambos esten en false (no esta en factura ni en fact rect) o en true en ambas (fue facturado pero luego rectificado)
  6095.             if ((!$estaEnFactura and !$estaEnFacturaRectificativa) or ($estaEnFactura and $estaEnFacturaRectificativa)) {
  6096.                 $sumatoriaTotalNet $sumatoriaTotalNet $item->getTotalNet();
  6097.                 $sumatoriaTotalVat $sumatoriaTotalVat $item->getVat();
  6098.                 $sumatoriaTotal $sumatoriaTotal $item->getTotal();
  6099.             }
  6100.         }
  6101.         $toXls $request->request->get('boolToXls');
  6102.         if (!empty($toXls)){
  6103.             $id 0;
  6104.             // Solicita el servicio de excel
  6105.             $phpExcelObject $this->get('phpexcel')->createPHPExcelObject();
  6106.             $phpExcelObject->getProperties()->setCreator("InOut Travel & Events")
  6107.                 ->setLastModifiedBy("InOut Travel & Events")
  6108.                 ->setTitle("InOut Travel & Events")
  6109.                 ->setSubject("InOut Travel & Events")
  6110.                 ->setDescription("InOut Travel & Events, generado usando clases de PHP")
  6111.                 ->setKeywords("office 2005 openxml php")
  6112.                 ->setCategory("Archivo de ejemplo");
  6113.             $fill = new Fill();
  6114.             $numberFormat = new NumberFormat();
  6115.             $alignment = new Alignment();
  6116.             $i 6;
  6117.             $indiceInicial 7;
  6118.             $indiceFinal 7;
  6119.             $activesheet $phpExcelObject->getActiveSheet();
  6120.             $drawingobject $this->get('phpexcel')->createPHPExcelWorksheetDrawing();
  6121.             $drawingobject->setName('Image name');
  6122.             $drawingobject->setDescription('Image description');
  6123.             $drawingobject->setPath(getcwd().'/assets/images/logo/logo_green_patio.png');
  6124.             $drawingobject->setHeight(60);
  6125.             $drawingobject->setOffsetY(20);
  6126.             $drawingobject->setCoordinates('Q1');
  6127.             $drawingobject->setWorksheet($activesheet);
  6128.             $phpExcelObject
  6129.                 ->getActiveSheet()
  6130.                 ->getStyle('B3:O3')
  6131.                 ->getFill()
  6132.                 ->setFillType($fill::FILL_SOLID)
  6133.                 ->getStartColor()
  6134.                 ->setRGB('9fc4a6');
  6135.             $phpExcelObject->setActiveSheetIndex(0)
  6136.                 ->setCellValue('C3','LISTADO DE FACTURACION')
  6137.             ;
  6138.             $phpExcelObject->setActiveSheetIndex(0)
  6139.                 ->setCellValue('B'.$i'Fecha')
  6140.                 ->setCellValue('D'.$i'Número')
  6141.                 ->setCellValue('F'.$i'Expediente')
  6142.                 ->setCellValue('H'.$i'Nombre del Evento')
  6143.                 ->setCellValue('L'.$i'Cliente')
  6144.                 ->setCellValue('O'.$i'Tipo')
  6145.                 ->setCellValue('Q'.$i'Neto')
  6146.                 ->setCellValue('S'.$i'Total')
  6147.             ;
  6148.             $data = array();
  6149.             $data $invoiced;
  6150.             foreach ($data as $item) {
  6151.                 $time $item->getDateAt()->format('d/m/Y');
  6152.                 $idExp = ($item->getType() == 'Invoice Rec') ? 'R'.$item->getId() : $item->getId();
  6153.                 $clientTypeText = ($item->getClientType() == 'Client') ? 'Cliente' 'Proveedor';
  6154.                 $phpExcelObject->setActiveSheetIndex(0)
  6155.                     ->setCellValue('B' . ($i 1), $time)
  6156.                     ->setCellValue('D' . ($i 1), $idExp)
  6157.                     ->setCellValue('F' . ($i 1), $item->getReservationId())
  6158.                     ->setCellValue('H' . ($i 1), $item->getNumber())
  6159.                     ->setCellValue('L' . ($i 1), $item->getClientName())
  6160.                     ->setCellValue('O' . ($i 1), $clientTypeText)
  6161.                     ->setCellValue('Q' . ($i 1), $item->getTotalNet())
  6162.                     ->setCellValue('S' . ($i 1), $item->getTotal())
  6163.                 ;
  6164.                 $i++;
  6165.                 $indiceFinal++;
  6166.             }
  6167.             $indiceFinal--;
  6168.             $indicesResta $indiceFinal $indiceInicial 1;
  6169.             $phpExcelObject
  6170.                 ->getActiveSheet()
  6171.                 ->getStyle('Q' . ($indiceFinal 3) . ':' 'S' . ($indiceFinal 3))
  6172.                 ->getFill()
  6173.                 ->setFillType($fill::FILL_SOLID)
  6174.                 ->getStartColor()
  6175.                 ->setRGB('9fc4a6');
  6176.             $phpExcelObject->setActiveSheetIndex(0)
  6177.                 ->setCellValue('Q' . ($indiceFinal 3), 'Total Neto')
  6178.                 ->setCellValue('S' . ($indiceFinal 3), 'Total');
  6179.             $phpExcelObject->setActiveSheetIndex(0)
  6180.                 ->setCellValue('Q' . ($indiceFinal 4), '=SUM(' 'Q' $indiceInicial ' : Q' $indiceFinal ')')
  6181.                 ->setCellValue('S' . ($indiceFinal 4), '=SUM(' 'S' $indiceInicial ' : U' $indiceFinal ')');
  6182.             $phpExcelObject->getActiveSheet()->setTitle('Estadísticas por sala');
  6183.             // Define el indice de página al número 1, para abrir esa página al abrir el archivo
  6184.             $phpExcelObject->setActiveSheetIndex(0);
  6185.             // Creamos pagina de Datos en bruto para Esteban Rincon
  6186.             // Add new sheet
  6187.             $objWorkSheet $phpExcelObject->createSheet(1); //Setting index when creating
  6188.             $phpExcelObject->setActiveSheetIndex(1);
  6189.             $phpExcelObject->getActiveSheet()->setTitle('Datos en bruto');
  6190.             $x 1;
  6191.             $phpExcelObject->setActiveSheetIndex(1)
  6192.                 ->setCellValue('A'.$x'Fecha')
  6193.                 ->setCellValue('B'.$x'Número')
  6194.                 ->setCellValue('C'.$x'Expediente')
  6195.                 ->setCellValue('D'.$x'Nombre del Evento')
  6196.                 ->setCellValue('E'.$x'Cliente')
  6197.                 ->setCellValue('F'.$x'Tipo')
  6198.                 ->setCellValue('G'.$x'Neto')
  6199.                 ->setCellValue('H'.$x'Total')
  6200.             ;
  6201.             foreach ($data as $item) {
  6202.                 $time $item->getDateAt()->format('d/m/Y');
  6203.                 $idExp = ($item->getType() == 'Invoice Rec') ? 'R'.$item->getId() : $item->getId();
  6204.                 $clientTypeText = ($item->getClientType() == 'Client') ? 'Cliente' 'Proveedor';
  6205.                 $phpExcelObject->setActiveSheetIndex(1)
  6206.                     ->setCellValue('A' . ($x 1), $time)
  6207.                     ->setCellValue('B' . ($x 1), $idExp)
  6208.                     ->setCellValue('C' . ($x 1), $item->getReservationId())
  6209.                     ->setCellValue('D' . ($x 1), $item->getNumber())
  6210.                     ->setCellValue('E' . ($x 1), $item->getClientName())
  6211.                     ->setCellValue('F' . ($x 1), $clientTypeText)
  6212.                     ->setCellValue('G' . ($x 1), $item->getTotalNet())
  6213.                     ->setCellValue('H' . ($x 1), $item->getTotal())
  6214.                 ;
  6215.                 $x++;
  6216.             }
  6217.             $phpExcelObject->setActiveSheetIndex(0);
  6218.             // Crea el writer
  6219.             $writer $this->get('phpexcel')->createWriter($phpExcelObject'Excel2007');
  6220.             // Envia la respuesta del controlador
  6221.             $response $this->get('phpexcel')->createStreamedResponse($writer);
  6222.             // Agrega los headers requeridos
  6223.             $dispositionHeader $response->headers->makeDisposition(
  6224.                 ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  6225.                 'Green Patio - Listado Facturas La Imprenta'.'.xlsx'
  6226.             );
  6227.             $response->headers->set('Content-Type''application/vnd.ms-excel; charset=utf-8');
  6228.             $response->headers->set('Pragma''public');
  6229.             $response->headers->set('Cache-Control''maxage=1');
  6230.             $response->headers->set('Content-Disposition'$dispositionHeader);
  6231.             $phpExcelObject->getActiveSheet()->setTitle('Facturación Green Patio');
  6232.             // Define el indice de página al número 1, para abrir esa página al abrir el archivo
  6233.             $phpExcelObject->setActiveSheetIndex(0);
  6234.             // Crea el writer
  6235.             $writer $this->get('phpexcel')->createWriter($phpExcelObject'Excel2007');
  6236.             // Envia la respuesta del controlador
  6237.             $response $this->get('phpexcel')->createStreamedResponse($writer);
  6238.             // Agrega los headers requeridos
  6239.             $dispositionHeader $response->headers->makeDisposition(
  6240.                 ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  6241.                 'Green Patio - Listado Facturacion La Imprenta.xlsx'
  6242.             );
  6243.             $response->headers->set('Content-Type''application/vnd.ms-excel; charset=utf-8');
  6244.             $response->headers->set('Pragma''public');
  6245.             $response->headers->set('Cache-Control''maxage=1');
  6246.             $response->headers->set('Content-Disposition'$dispositionHeader);
  6247.             return $response;
  6248.         }
  6249.         return $this->render('MDS/GreenPatioBundle/reservations/list-reservations-invoice.html.twig',
  6250.             array(
  6251.                 'invocied' => $invoiced,
  6252.                 'sumatoriaTotalNet' => $sumatoriaTotalNet,
  6253.                 'sumatoriaTotalVat' => $sumatoriaTotalVat,
  6254.                 'sumatoriaTotal' => $sumatoriaTotal,
  6255.             )
  6256.         );
  6257.     }
  6258.     /**
  6259.      * @Route("/reservations/updateinvoicedate/", name="reservation_update_invoice_date")
  6260.      * Editar la fecha de una factura
  6261.      */
  6262.     public function updateInvoiceDateActionRequest $request){
  6263.         $em $this->getDoctrine()->getManager();
  6264.         $invoiceId $request->request->get('invoice_id');
  6265.         $invoiceNewDate $request->request->get('new_invoice_date');
  6266.         /* Obtengo usuario logueado */
  6267.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  6268.         $user_id $user_logueado->getId();
  6269.         $invoice $em->getRepository(ReservationInvoice::class)->findOneById($invoiceId);
  6270.         $newDate = new DateTime($invoiceNewDate);
  6271.         $invoice->setDateAt($newDate);
  6272.         // Modificamos el number para que se adapte a la nueva fecha
  6273.         $invoice->setNumber('GPF-' $newDate->format('dmy') . substr($invoice->getNumber(),10));
  6274.         $invoice->setUpdatedId($user_id);
  6275.         $invoice->setUpdatedAt(new DateTime('now'));
  6276.         $em->persist($invoice);
  6277.         $em->flush();
  6278.         return $this->redirectToRoute('reservation_invoice_list');
  6279.     }
  6280.     /**
  6281.      * @Route("/mkbdgt/{token}", name="reservations_greenpatio_make_budget")
  6282.      */
  6283.     public function makeBudgetAction($tokenRequest $request)
  6284.     {
  6285.         $em $this->getDoctrine()->getManager();
  6286.         $budgetControl $em->getRepository(ReservationBudgetControl::class)->findOneByToken($token);
  6287.         $allBudgets $em->getRepository(ReservationBudgetControl::class)->findByReservationId($budgetControl->getReservationId());
  6288.         $id $budgetControl->getReservationId();
  6289. //        $paymentsClient = new ReservationPaymentsClient();
  6290. //        $paymentsClient->setReservationId($id);
  6291. //        $form = $this->createReservationPaymentsClientForm($paymentsClient);
  6292.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  6293. //        $payments = $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
  6294.         $services $em->getRepository(ReservationService::class)->findByReservationId($id);
  6295.         $proforma $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  6296. //        $allProformas = $em->getRepository(ReservationProforma::class)->findAll();
  6297. //        if (!empty($allProformas)){
  6298. //            $number = end($allProformas)->getId() + 1;
  6299. //        } else {
  6300.         // Primer registro de proformas
  6301.         $number 1;
  6302. //        }
  6303.         $type 'Proforma';
  6304.         $date = new DateTime('now');
  6305.         $prefix "GP-".$date->format('dmy')."-";
  6306.         $reservaInv = new ReservationInvoice();
  6307.         $reservaInv->setReservationId($id);
  6308. //        $form1 = $this->createReservationInvoiceProformaForm($reservaInv);
  6309.         $data $this->baseInvoiceReservation($id$type$number$prefix$date);
  6310. //        $token = $data['token'];
  6311.         $idLounges = array();
  6312.         if (array_key_exists('lounge',$data['datasupplier'])) {
  6313.             foreach ($data['datasupplier']['lounge'] as $key => $item) {
  6314.                 $existe $em->getRepository(ReservationInvoiceItems::class)->findOneByLngControlId($item['id']);
  6315.                 if (empty($existe)){
  6316.                     $data['datasupplier']['lounge'][$key]['enabledToInvoice'] = true;
  6317.                 } else {
  6318.                     $data['datasupplier']['lounge'][$key]['enabledToInvoice'] = false;
  6319.                 }
  6320.             }
  6321.         }
  6322.         if (array_key_exists('service',$data['datasupplier'])) {
  6323.             foreach ($data['datasupplier']['service'] as $key => $item) {
  6324.                 $existe $em->getRepository(ReservationInvoiceItems::class)->findOneBySrvControlId($item['id']);
  6325.                 if (empty($existe)){
  6326.                     $data['datasupplier']['service'][$key]['enabledToInvoice'] = true;
  6327.                 } else {
  6328.                     $data['datasupplier']['service'][$key]['enabledToInvoice'] = false;
  6329.                 }
  6330.             }
  6331.         }
  6332. //        $idPayments = array();
  6333. //        if (array_key_exists('payment',$data['datasupplier'])) {
  6334. //            foreach ($data['datasupplier']['payment'] as $key => $item) {
  6335. //                $existe = $em->getRepository(ReservationInvoiceItems::class)->findOneByPayControlId($item['id']);
  6336. //
  6337. //                if (empty($existe)){
  6338. //                    $data['datasupplier']['payment'][$key]['enabledToInvoice'] = true;
  6339. //                } else {
  6340. //                    $data['datasupplier']['payment'][$key]['enabledToInvoice'] = false;
  6341. //                }
  6342. //            }
  6343. //        }
  6344.         /* Obtengo usuario logueado */
  6345.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  6346.         $user_id $user_logueado->getId();
  6347.         return $this->render('MDS/GreenPatioBundle/reservations/budget-add-items.html.twig',
  6348.             array(
  6349.                 'id' => $id,
  6350.                 'idLounges' => $idLounges,
  6351.                 'reserva' => $reserva,
  6352.                 'idPayments' => null,
  6353.                 'type' => $data['type'],
  6354.                 'number' => $data['number'],
  6355.                 'prefix' => $data['prefix'],
  6356.                 'date' => $data['date'],
  6357.                 'token' => $token,
  6358.                 'company' => $data['company'],
  6359.                 'clients' => $data['clients'],
  6360.                 'datasupplier' => $data['datasupplier'],
  6361.                 'currency' => $data['currency'],
  6362.                 'totales_neto' => $data['totales_neto'],
  6363.                 'bases_imponibles' => $data['bases_imponibles'],
  6364.                 'totales' => $data['totales'],
  6365.                 'balance' => $data['balance'],
  6366.                 'paymentInvoice' => $data['paymentInvoice'],
  6367.                 'payments' => null,
  6368.                 'user_id' => $user_id,
  6369.                 'allBudgets' => $allBudgets,
  6370.             )
  6371.         );
  6372.     }
  6373.     /**
  6374.      * @Route("/createbdgt/{token}", name="reservations_greenpatio_create_budget")
  6375.      */
  6376.     public function createBudgetAction($tokenRequest $request)
  6377.     {
  6378.         $em $this->getDoctrine()->getManager();
  6379.         $budgetControl $em->getRepository(ReservationBudgetControl::class)->findOneByToken($token);
  6380.         $nameBud $request->request->get('budget_name_hidden');
  6381.         $budgetControl->setName($nameBud);
  6382.         $em->persist($budgetControl);
  6383.         $em->flush();
  6384.         /* Obtengo usuario logueado */
  6385.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  6386.         $user_id $user_logueado->getId();
  6387.         $arrayLounge $request->request->get('lounge_hidden_bool');
  6388.         $arrayService $request->request->get('service_hidden_bool');
  6389.         foreach ($arrayLounge as $key => $item) {
  6390.             if ($item == 'true'){
  6391.                 //Buscamos la sala
  6392.                 $lounge $em->getRepository(ReservationLoungeSimple::class)->findOneById($key);
  6393.                 $budgetItem = new ReservationBudgetItems();
  6394.                 $budgetItem->setReservationId($budgetControl->getReservationId());
  6395.                 $budgetItem->setControlId($budgetControl->getId());
  6396.                 $budgetItem->setItemType('LOUNGE');
  6397.                 $budgetItem->setLngControlId($key);
  6398.                 $budgetItem->setLngLoungeName($lounge->getLoungeName());
  6399.                 $budgetItem->setLngIdLounge($lounge->getIdLounge());
  6400.                 $budgetItem->setLngDateStart($lounge->getDateStart());
  6401.                 $budgetItem->setLngDateEnd($lounge->getDateEnd());
  6402.                 $budgetItem->setLngServicePrice($lounge->getServicePrice());
  6403.                 $budgetItem->setLngPax($lounge->getPax());
  6404.                 $budgetItem->setLngType($lounge->getType());
  6405.                 $budgetItem->setLngHourStart($lounge->getHourStart());
  6406.                 $budgetItem->setLngMinStart($lounge->getMinStart());
  6407.                 $budgetItem->setLngHourEnd($lounge->getHourEnd());
  6408.                 $budgetItem->setLngMinEnd($lounge->getMinEnd());
  6409.                 $budgetItem->setCreatedAt(new DateTime('now'));
  6410.                 $budgetItem->setCreatedId($user_id);
  6411.                 $budgetItem->setUpdatedAt(new DateTime('now'));
  6412.                 $budgetItem->setUpdatedId($user_id);
  6413.                 $em->persist($budgetItem);
  6414.                 $em->flush();
  6415.             }
  6416.         }
  6417.         foreach ($arrayService as $key => $item) {
  6418.             if ($item == 'true'){
  6419.                 //Buscamos el servicio
  6420.                 $service $em->getRepository(ReservationService::class)->findOneById($key);
  6421.                 $budgetItem = new ReservationBudgetItems();
  6422.                 $budgetItem->setReservationId($budgetControl->getReservationId());
  6423.                 $budgetItem->setControlId($budgetControl->getId());
  6424.                 $budgetItem->setItemType('SERVICE');
  6425.                 $budgetItem->setSrvControlId($key);
  6426.                 $budgetItem->setSrvSupplierId($service->getSupplierId());
  6427.                 $budgetItem->setSrvServiceId($service->getServiceId());
  6428.                 $budgetItem->setSrvServiceCatId($service->getServiceCatId());
  6429.                 $budgetItem->setSrvServiceCatName($service->getServiceCatName());
  6430.                 $budgetItem->setSrvName($service->getName());
  6431.                 $budgetItem->setSrvPrice($service->getPrice());
  6432.                 $budgetItem->setSrvCurrency($service->getCurrency());
  6433.                 $budgetItem->setSrvUnits($service->getUnits());
  6434.                 $budgetItem->setSrvOpCommissions($service->getOpCommissions());
  6435.                 $budgetItem->setSrvCommissions($service->getCommissions());
  6436.                 $budgetItem->setSrvOpOver($service->getOpOver());
  6437.                 $budgetItem->setSrvOver($service->getOver());
  6438.                 $budgetItem->setSrvOpIva($service->getOpIva());
  6439.                 $budgetItem->setSrvIva($service->getIva());
  6440.                 $budgetItem->setSrvPax($service->getPax());
  6441.                 $budgetItem->setSrvHour($service->getHour());
  6442.                 $budgetItem->setSrvHour($service->getHour());
  6443.                 $budgetItem->setSrvDateInAt($service->getDateInAt());
  6444.                 $budgetItem->setSrvDateOutAt($service->getDateOutAt());
  6445.                 $budgetItem->setSrvContcolor($service->getContcolor());
  6446.                 $budgetItem->setSrvRank($service->getRank());
  6447.                 $budgetItem->setSrvAssistantId($service->getAssistantId());
  6448.                 $budgetItem->setSrvActivityId($service->getActivityId());
  6449.                 $budgetItem->setSrvPay($service->getPay());
  6450.                 $budgetItem->setCreatedAt(new DateTime('now'));
  6451.                 $budgetItem->setCreatedId($user_id);
  6452.                 $budgetItem->setUpdatedAt(new DateTime('now'));
  6453.                 $budgetItem->setUpdatedId($user_id);
  6454.                 $em->persist($budgetItem);
  6455.                 $em->flush();
  6456.             }
  6457.         }
  6458.         $data = array();
  6459.         $data $this->baseInvoiceDoneReservation($budgetControl->getReservationId(), 0,'P');
  6460. //        $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
  6461.         $allInvoices null;
  6462.             //Es una proforma
  6463. //        $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
  6464.         $invoiceIdToRec null;
  6465.         return $this->render('MDS/GreenPatioBundle/reservations/budget-print.html.twig', array(
  6466.         'id' => $budgetControl->getReservationId(),
  6467.         'type' => $data['type'],
  6468.         'number' => $data['number'],
  6469.         'invoiceIdToRec' => $invoiceIdToRec,
  6470.         'prefix' => $data['prefix'],
  6471.         'date' => $data['date'],
  6472.         'token' => '',
  6473.         'company' => $data['company'],
  6474.         'clients' => $data['clients'],
  6475.         'datasupplier' => $data['datasupplier'],
  6476.         'totales_neto' => $data['totales_neto'],
  6477.         'bases_imponibles' => $data['bases_imponibles'],
  6478.         'totales' => $data['totales'],
  6479.         'balance' => $data['balance'],
  6480.         'currency' => $data['currency'],
  6481.         'paymentInvoice' => $data['paymentInvoice']
  6482.     ));
  6483.     }
  6484.     /**
  6485.      * @Route("/selinvoicesp/{id}",  name="reservations_select_invoice_special")
  6486.      * Vista previa para selecionar la entidad a la cual se le va a facturar (cliente o proveedor)
  6487.      */
  6488.     public function generateReservationSpecialInvoiceAction($idRequest $request)
  6489.     {
  6490.         $em $this->getDoctrine()->getManager();
  6491.         //Buscamos los clientes
  6492.         $clients $em->getRepository(Client::class)->findAll();
  6493.         //Buscamos los proveedores
  6494.         $suppliers $em->getRepository(Supplier::class)->findAll();
  6495.         //Unimos en un solo arreglo
  6496.         $arrayClients = array();
  6497.         foreach ($clients as $item){
  6498.             $arrayClients[] = array(
  6499.                 'nombre' => $item->getName(),
  6500.                 'id' => $item->getId(),
  6501.                 'tipo' => 'CLIENTE',
  6502.                 'indice' => 'C'.$item->getId(),
  6503.             );
  6504.         }
  6505.         foreach ($suppliers as $item){
  6506.             $arrayClients[] = array(
  6507.                 'nombre' => $item->getCompany(),
  6508.                 'id' => $item->getId(),
  6509.                 'tipo' => 'PROVEEDOR',
  6510.                 'indice' => 'S'.$item->getId(),
  6511.             );
  6512.         }
  6513.         return $this->render('MDS/GreenPatioBundle/reservations/services-invoice-select-client-supplier.html.twig',
  6514.             array(
  6515.                 'id' => $id,
  6516.                 'clients' => $arrayClients,
  6517.             )
  6518.         );
  6519.     }
  6520.     private function clientDataToInvoice($invoice$typeClient$idClient$reservationId){
  6521.         //Recibe una ReservationInvoice y se le agregan los datos del cliente
  6522.         $em $this->getDoctrine()->getManager();
  6523.         $address null;
  6524.         if (empty($invoice)){
  6525.             // Venimos de un selector y vamos a cotizar
  6526.             $reserva $em->getRepository(Reservation::class)->findOneById($reservationId);
  6527.             $typeClient 'Client'$idClient $reserva->getClient();
  6528.             $invoice = new ReservationInvoice();
  6529.         }
  6530.         if ($typeClient == 'Client'){
  6531.             $client $em->getRepository(Client::class)->findOneById($idClient); $typeClient 'Client';
  6532.             if (!empty($client)){ $name $client->getName(); $address $client->getAddress() . ' ' $client->getAddressNumber(); }
  6533.         } else {
  6534.             // Proveedor (Para facturas de comision)
  6535.             $client $em->getRepository(Supplier::class)->findOneById($idClient); $typeClient 'Supplier';
  6536.             if (!empty($client)){ $name $client->getCompany(); $address $client->getAddress(); }
  6537.         }
  6538.         if(empty($client)){
  6539.             // No se encontro el cliente o proveedor, se utilizará por defecto el de la reserva
  6540.             $reserva $em->getRepository(Reservation::class)->findOneById($invoice->getReservationId()); $typeClient 'Client';
  6541.             $client $em->getRepository(Client::class)->findOneById($reserva->getClient());
  6542.             if (!empty($client)){ $name $client->getName(); $address $client->getAddress() . ' ' $client->getAddressNumber(); }
  6543.         }
  6544.         $region $em->getRepository(Regions::class)->findOneById($client->getRegion());
  6545.         $country $em->getRepository(Country::class)->findOneById($client->getCountry());
  6546.         $address = (empty($client->getRegion())) ? $address $address', ' $region->getRegion();
  6547.         $address = (empty($client->getZipCode())) ? $address $address' - ' $client->getZipCode();
  6548.         $address = (empty($client->getCountry())) ? $address $address', ' $country->getCountry();
  6549.         $invoice->setClientAddress($address);
  6550.         $invoice->setClientName($name);
  6551.         $clientDocument null;
  6552.         $clientDocument = (empty($client->getTypeDocument())) ? $clientDocument $client->getTypeDocument();
  6553.         $clientDocument = (empty($client->getIdDocument())) ? ' ' $clientDocument': ' $client->getIdDocument();
  6554.         $invoice->setClientDocument($clientDocument);
  6555.         $invoice->setClientType($typeClient);
  6556.         return $invoice;
  6557.     }
  6558.     private function clientOrSupplierDataSearchToInvoice($index$reservationId){
  6559.         //Recibe un indice C22 o S41 para buscar los datos del cliente 22 o el proveedor 41 y pasar esos datos para la siguiente factura
  6560.         $em $this->getDoctrine()->getManager();
  6561.         $address null$name null$clientDocument null$typeClient null;
  6562.         if (substr($index,0,1) == 'C'){
  6563.             // Cliente
  6564.             $client $em->getRepository(Client::class)->findOneById(substr($index,1,strlen($index))); $typeClient 'Client';
  6565.             if (!empty($client)){ $name $client->getName(); $address $client->getAddress() . ' ' $client->getAddressNumber(); }
  6566.         } else {
  6567.             // Proveedor (Para facturas de comision)
  6568.             $client $em->getRepository(Supplier::class)->findOneById(substr($index,1,strlen($index))); $typeClient 'Supplier';
  6569.             if (!empty($client)){ $name $client->getCompany(); $address $client->getAddress(); }
  6570.         }
  6571.         if(empty($client)){
  6572.             // No se encontro el cliente o proveedor, se utilizará por defecto el de la reserva
  6573.             $reserva $em->getRepository(Reservation::class)->findOneById($reservationId); $typeClient 'Client';
  6574.             $client $em->getRepository(Client::class)->findOneById($reserva->getClient());
  6575.             if (!empty($client)){ $name $client->getName(); $address $client->getAddress() . ' ' $client->getAddressNumber(); }
  6576.         }
  6577.         $region $em->getRepository(Regions::class)->findOneById($client->getRegion());
  6578.         $country $em->getRepository(Country::class)->findOneById($client->getCountry());
  6579.         $address = (empty($client->getRegion())) ? $address $address', ' $region->getRegion();
  6580.         $address = (empty($client->getZipCode())) ? $address $address' - ' $client->getZipCode();
  6581.         $address = (empty($client->getCountry())) ? $address $address', ' $country->getCountry();
  6582.         $clientDocument = (empty($client->getTypeDocument())) ? $clientDocument $client->getTypeDocument();
  6583.         $clientDocument = (empty($client->getIdDocument())) ? ' ' $clientDocument': ' $client->getIdDocument();
  6584.         $dataClient = array(
  6585.                             'clientName' => $name,
  6586.                             'clientAddress' => $address,
  6587.                             'clientDocument' => $clientDocument,
  6588.                             'clientType' => $typeClient);
  6589.         return $dataClient;
  6590.     }
  6591.     private function selectorLineaDeFacturacion($id$lounge$service$payment$clientName$clientAddress$clientDocument$clientType){
  6592.         // Se elige si la factura ha de ir por GreenPatio o Covarrubias, las salas con ID > 21 son de Covarrubias
  6593.         $em $this->getDoctrine()->getManager();
  6594.         $parameters = array( 'id' => $id, );
  6595.         $dql 'SELECT p
  6596.                 FROM GreenPatioBundle:ReservationLoungeSimple p
  6597.                 WHERE p.idReservation = :id AND p.idLounge > 21';
  6598.         $query $em->createQuery($dql)->setParameters($parameters);
  6599.         $loungesSimples $query->getResult();
  6600.         if (!empty($loungesSimples)){
  6601.             // Redirigir a Covarrubias
  6602.             return $this->redirectToRoute('reservations_generatenew_invoice_cvr',
  6603.                 array(
  6604.                     'id' => $id,
  6605.                     'lounge' => $lounge,
  6606.                     'service' => $service,
  6607.                     'payment' => $payment,
  6608.                     'clientName' => $clientName,
  6609.                     'clientAddress' => $clientAddress,
  6610.                     'clientDocument' => $clientDocument,
  6611.                     'clientType' => $clientType
  6612.                 )
  6613.             );
  6614.         }
  6615.         return true;
  6616.     }
  6617. }