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