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

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