src/MDS/EventsBundle/Controller/ProposalInvoiceController.php line 269

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by Mediterranean Develup Solutions
  4.  * User: jorge.defreitas@develup.solutions
  5.  * Date: 04/12/2017
  6.  * Time: 9:49
  7.  */
  8. namespace App\MDS\EventsBundle\Controller;
  9. use App\Constants\VacationsConstants;
  10. use App\Entity\Activities;
  11. use App\Entity\Cities;
  12. use App\Entity\Client;
  13. use App\Entity\Configuration;
  14. use App\Entity\Country;
  15. use App\Entity\Destination;
  16. use App\Entity\Ideas;
  17. use App\Entity\ProposalsInvoiceSummary;
  18. use App\Entity\Provinces;
  19. use App\Entity\Regions;
  20. use App\Entity\SettingsCompany;
  21. use App\Entity\SettingsRol;
  22. use App\Entity\Supplier;
  23. use App\Entity\User;
  24. use App\MDS\EventsBundle\Entity\Proposal;
  25. use App\MDS\EventsBundle\Entity\ProposalDiscount;
  26. use App\MDS\EventsBundle\Entity\ProposalFee;
  27. use App\MDS\EventsBundle\Entity\ProposalFeeInvoice;
  28. use App\MDS\EventsBundle\Entity\ProposalInvoice;
  29. use App\MDS\EventsBundle\Entity\ProposalInvoiceDepositControl;
  30. use App\MDS\EventsBundle\Entity\ProposalInvoiceDepositItems;
  31. use App\MDS\EventsBundle\Entity\ProposalPaymentsClient;
  32. use App\MDS\EventsBundle\Entity\ProposalProforma;
  33. use App\MDS\EventsBundle\Entity\ProposalsSupplierServicesAssistantName;
  34. use App\MDS\EventsBundle\Entity\ProposalSupplierServicesCostsClient;
  35. use App\MDS\EventsBundle\Entity\ProposalTracing;
  36. use App\MDS\EventsBundle\Form\ProposalPaymentsClientType;
  37. use Swift_Mailer;
  38. use Swift_Message;
  39. use Swift_SmtpTransport;
  40. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  41. use Symfony\Component\Routing\Annotation\Route;
  42. use Symfony\Component\HttpFoundation\Request;
  43. use Symfony\Component\HttpFoundation\Response;
  44. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  45. use Symfony\Contracts\Translation\TranslatorInterface;
  46. class ProposalInvoiceController extends AbstractController
  47. {
  48.     private $translator;
  49.     public function __construct(TranslatorInterface $translator) {
  50.         $this->translator $translator;
  51.     }
  52.     /*
  53.     * ATENCION LAS RAIZ DE @Route POR DEFECTO DEL BUNDLE: EventsBundle ES  /events/, NO PONERLO EN LA @Route("")
  54.     *
  55.     * */
  56.     /**
  57.      * @Route("/proposal/invoice/{id}",  name="proposal_invoice_detector")
  58.      */
  59.     public function detectorInvoiceAction($idRequest $request)
  60.     {
  61.         $em $this->getDoctrine()->getManager();
  62.         $invoiceconsulta= array();
  63.         $typeconsulta ='';
  64.         $invoice $em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
  65.         if (!empty($invoice)){
  66.             $invoiceconsulta $invoice;
  67.             $typeconsulta $invoice->getType();
  68.         }
  69. //        $novatinvoice= $em->getRepository(ProposalNoVatInvoice::class)->findOneByProposalId($id);
  70. //        if (!empty($novatinvoice)){
  71. //            $invoiceconsulta = $novatinvoice;
  72. //            $typeconsulta = 'No Vat Invoice';
  73. //        }
  74. //        $invoiceconsulta = $em->getRepository(ProposalNoVatInvoice::class)->findOneByProposalId($id);
  75.         if (!empty($invoiceconsulta)){
  76.             $type $typeconsulta;
  77. //            $number = $invoiceconsulta->getId();
  78.             $number $invoiceconsulta->getNumber();
  79.             $date $invoiceconsulta->getDateAt();
  80.             $prefix $invoiceconsulta->getPrefix();
  81.             /* Obtengo usuario logueado */
  82.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  83.             $user_id $user_logueado->getId();
  84.             $data $this->baseInvoiceProposal($id$type$number$prefix$date$request);
  85.             $token $data['token'];
  86.             $em->clear();
  87.             $invoice_query $em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
  88.             $invoice_query->setTotalnet($data['totales_neto']);
  89.             $invoice_query->setVat(serialize($data['bases_imponibles']));
  90.             $invoice_query->setTotal($data['totales']);
  91.             $em->persist($invoice_query);
  92.             $em->flush();
  93.         }else{
  94.             return $this->redirectToRoute('proposal_generate_proforma',
  95.                 array(
  96.                     'id' => $id
  97.                 )
  98.             );
  99.         }
  100.         $fees $em->getRepository(ProposalFeeInvoice::class)->findByProposalId($id);
  101.         if (!empty($fees)){ if (!($fees[0]->getToInvoice())){ $fees null; } }     // Si no se debe mostrar en factura se pone a null
  102.         $summary $em->getRepository(ProposalsInvoiceSummary::class)->findOneByProposalId($id);
  103.         $summaryInvoice = !empty($summary);
  104.         $summaryInvoiceText = !empty($summary) ? $summary->getDescription() : null;
  105.         return $this->render('MDS/EventsBundle/services/services-invoice-proposal.html.twig',
  106.             array(
  107.                 'id' => $id,
  108.                 'type' => $data['type'],
  109.                 'number' => $data['number'],
  110.                 'prefix' => $data['prefix'],
  111.                 'date' => $data['date'],
  112.                 'token' => $token,
  113.                 'proposal' => $data['proposal'],
  114.                 'company' => $data['company'],
  115.                 'clients' => $data['clients'],
  116.                 'datasupplier' => $data['datasupplier'],
  117.                 'totales_neto_antes' => $data['totales_neto_antes'],
  118.                 'totales_neto' => $data['totales_neto'], // totales neto
  119.                 'bases_imponibles' => $data['bases_imponibles'],
  120.                 'totales_antes' => $data['totales_antes'],
  121.                 'totales' => $data['totales'], // totales generales
  122.                 'balance' => $data['balance'],
  123.                 'totales_generales' => $data['totales_generales'],
  124.                 'currency' => $data['currency'],
  125.                 'detail_iva' => 'no',
  126.                 'discounts' => $data['discounts'],
  127.                 'fees' => $fees,
  128.                 'summaryInvoice' => $summaryInvoice,
  129.                 'summaryInvoiceText' => $summaryInvoiceText,
  130.                 'paymentInvoice' => $data['paymentInvoice'],
  131.                 'invoiceDesposit' => $data['invoiceDesposit'],
  132.                 'mcp' => $data['proposal']->getMcp()
  133.             )
  134.         );
  135.     }
  136.     /**
  137.      * @Route("/proposal/invoice/print/{id}",  name="proposal_invoice_detector_print")
  138.      */
  139.     public function detectorInvoicePrintAction($idRequest $request)
  140.     {
  141.         $em $this->getDoctrine()->getManager();
  142.         $invoiceconsulta= array();
  143.         $typeconsulta ='';
  144.         $invoice$em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
  145.         if (!empty($invoice)){
  146.             $invoiceconsulta $invoice;
  147.             $typeconsulta $invoice->getType();
  148.         }
  149. //        $novatinvoice= $em->getRepository(ProposalNoVatInvoice::class)->findOneByProposalId($id);
  150. //        if (!empty($novatinvoice)){
  151. //            $invoiceconsulta = $novatinvoice;
  152. //            $typeconsulta = 'No Vat Invoice';
  153. //        }
  154. //        $invoiceconsulta = $em->getRepository(ProposalNoVatInvoice::class)->findOneByProposalId($id);
  155.         if (!empty($invoiceconsulta)){
  156.             $type $typeconsulta;
  157. //            $number = $invoiceconsulta->getId();
  158.             $number $invoiceconsulta->getNumber();
  159.             $date $invoiceconsulta->getDateAt();
  160.             $prefix $invoiceconsulta->getPrefix();
  161.             $data $this->baseInvoiceProposal($id$type$number$prefix$date$request);
  162.             $token $data['token'];
  163.         }else{
  164.             return $this->redirectToRoute('proposal_generate_proforma',
  165.                 array(
  166.                     'id' => $id
  167.                 )
  168.             );
  169.         }
  170.         $fees $em->getRepository(ProposalFeeInvoice::class)->findByProposalId($id);
  171.         if (!empty($fees)){
  172.             $fees[0]->setAmount($fees[0]->getFeeNet());
  173.             if (!($fees[0]->getToInvoice())){ $fees null; } } // Si no se debe mostrar en factura se pone a null
  174.         $summary $em->getRepository(ProposalsInvoiceSummary::class)->findOneByProposalId($id);
  175.         $summaryInvoice = !empty($summary);
  176.         $summaryInvoiceText = !empty($summary) ? $summary->getDescription() : null;
  177.         return $this->render('MDS/EventsBundle/services/services-invoice-print-proposal.html.twig',
  178.             array(
  179.                 'id' => $id,
  180.                 'type' => $data['type'],
  181.                 'number' => $data['number'],
  182.                 'prefix' => $data['prefix'],
  183.                 'date' => $data['date'],
  184.                 'token' => $token,
  185.                 'proposal' => $data['proposal'],
  186.                 'company' => $data['company'],
  187.                 'clients' => $data['clients'],
  188.                 'datasupplier' => $data['datasupplier'],
  189.                 'totales_neto_antes' => $data['totales_neto_antes'],
  190.                 'totales_neto' => $data['totales_neto'],
  191.                 'bases_imponibles' => $data['bases_imponibles'],
  192.                 'totales_antes' => $data['totales_antes'],
  193.                 'totales' => $data['totales'],
  194.                 'balance' => $data['balance'],
  195.                 'totales_generales' => $data['totales_generales'],
  196.                 'currency' => $data['currency'],
  197.                 'detail_iva' => 'no',
  198.                 'discounts' => $data['discounts'],
  199.                 'fees' => $fees,
  200.                 'paymentInvoice' => $data['paymentInvoice'],
  201.                 'invoiceDesposit' => $data['invoiceDesposit'],
  202.                 'summaryInvoice' => $summaryInvoice,
  203.                 'summaryInvoiceText' => $summaryInvoiceText,
  204.             )
  205.         );
  206.     }
  207.     /**
  208.      * @Route("/proposal/generate/proforma/{id}",  name="proposal_generate_proforma")
  209.      */
  210.     public function generateProformaAction($idRequest $request)
  211.     {
  212.         $em $this->getDoctrine()->getManager();
  213.         $proforma $em->getRepository(ProposalProforma::class)->findOneByProposalId($id);
  214.         $prefix "MP".date('ymd')."-";
  215.         if (is_null($proforma)){
  216.             $proforma_new = new ProposalProforma();
  217.             $proforma_new->setProposalId($id);
  218.             $proforma_new->setPrefix($prefix);
  219.             $proforma_new->setDateAt(new \DateTime("now"));
  220.             /* Obtengo usuario logueado */
  221.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  222.             $user_id $user_logueado->getId();
  223.             $proforma_new->setCreatedId($user_id);
  224.             $proforma_new->setUpdatedId($user_id);
  225.             $proposal $em->getRepository(Proposal::class)->findOneById($id);
  226.             if($proposal->getStatus() != 'Invoiced'){
  227.                 $em->persist($proforma_new);
  228.                 $em->flush();
  229.             }
  230.         }
  231.         return $this->redirectToRoute('proposal_invoice_proforma', array( 'id' => $id ) );
  232.     }
  233.     /**
  234.      * @Route("/proposal/invoice/proforma/{id}",  name="proposal_invoice_proforma")
  235.      */
  236.     public function detailsProformaAction($idRequest $request)
  237.     {
  238.         $data = array();
  239.         $em $this->getDoctrine()->getManager();
  240.         $paymentsClient = new ProposalPaymentsClient();
  241.         $paymentsClient->setProposalId($id);
  242.         $form $this->createProposalPaymentsClientForm($paymentsClient);
  243.         $payments $em->getRepository(ProposalPaymentsClient::class)->findByProposalId($id);
  244.         $proforma $em->getRepository(ProposalProforma::class)->findOneByProposalId($id);
  245.         if (!empty($proforma)){
  246.             $type 'Proforma';
  247.             $number $proforma->getId();
  248.             $date $proforma->getDateAt();
  249.             $prefix $proforma->getPrefix();
  250.             $data $this->baseInvoiceProposal($id$type$number$prefix$date$request);
  251.             $token $data['token'];
  252.         }else{
  253.             return $this->redirectToRoute('proposal_generate_proforma',
  254.                 array(
  255.                     'id' => $id
  256.                 )
  257.             );
  258.         }
  259.         $fees $em->getRepository(ProposalFee::class)->findByProposalId($id);
  260.         if (!empty($fees)){ if (!($fees[0]->getToInvoice())){ $fees null; } } // Si no se debe mostrar en factura se pone a null
  261.         return $this->render('MDS/EventsBundle/services/services-proforma-proposal.html.twig',
  262.             array(
  263.                 'id' => $id,
  264.                 'type' => $data['type'],
  265.                 'number' => $data['number'],
  266.                 'prefix' => $data['prefix'],
  267.                 'date' => $data['date'],
  268.                 'token' => $token,
  269.                 'proposal' => $data['proposal'],
  270.                 'company' => $data['company'],
  271.                 'clients' => $data['clients'],
  272.                 'datasupplier' => $data['datasupplier'],
  273.                 'totales_neto_antes' => $data['totales_neto_antes'],
  274.                 'totales_neto' => $data['totales_neto'],
  275.                 'bases_imponibles' => $data['bases_imponibles'],
  276.                 'totales_antes' => $data['totales_antes'],
  277.                 'totales' => $data['totales'],
  278.                 'balance' => $data['balance'],
  279.                 'totales_generales' => $data['totales_generales'],
  280.                 'currency' => $data['currency'],
  281.                 'detail_iva' => 'yes',
  282.                 'discounts' => $data['discounts'],
  283.                 'fees' => $fees,
  284.                 'paymentInvoice' => $data['paymentInvoice'],
  285.                 'payments' => $payments,
  286.                 'invoiceDesposit' => $data['invoiceDesposit'],
  287.                 'form' => $form->createView(),
  288.                 'mcp' => $data['proposal']->getMcp(),
  289.             )
  290.         );
  291.     }
  292.     private function createProposalPaymentsClientForm(ProposalPaymentsClient $entity)
  293.     {
  294.         $form $this->createForm(ProposalPaymentsClientType::class, $entity, array(
  295.             'action' => $this->generateUrl('proposal_payments_client_add'),
  296.             'method' => 'POST'
  297.         ));
  298.         return $form;
  299.     }
  300.     /**
  301.      * @Route("/proposal/payments", name="proposal_payments_client_add")
  302.      */
  303.     public function createAction(Request $request)
  304.     {
  305.         $paymentsClient = new ProposalPaymentsClient();
  306.         $form $this->createProposalPaymentsClientForm($paymentsClient);
  307.         $form->handleRequest($request);
  308.         if($form->isValid())
  309.         {
  310.             $em $this->getDoctrine()->getManager();
  311.             /* Obtengo usuario logueado */
  312.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  313.             $user_id $user_logueado->getId();
  314.             $paymentsClient->setCreatedId($user_id);
  315.             $paymentsClient->setUpdatedId($user_id);
  316.             /* Gestión de eventos en Log */
  317.             $user_lastname $user_logueado->getLastname();
  318.             $user_name $user_logueado->getName();
  319.             $user_email $user_logueado->getEmail();
  320.             $user_rol $user_logueado->getRoles();
  321.             $event_url $request->getPathInfo();
  322.             $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  323.             $proposal $em->getRepository(Proposal::class)->findOneById($paymentsClient->getProposalId());
  324.             if($proposal->getStatus() != 'Invoiced'){
  325.                 $em->persist($paymentsClient);
  326.                 $em->flush();
  327.                 $event 'the payment was registered';
  328.                 $successMessage $this->translator->trans($event);
  329.                 $this->addFlash('mensajepaymentsclient'$successMessage);
  330.             }else{
  331.                 $errorMessage $this->translator->trans('Error, the proposal is invoiced and cannot be modified');
  332.                 $this->addFlash('mensajepaymentsclienterror'$errorMessage);
  333.             }
  334.             return $this->redirectToRoute('proposal_invoice_proforma',
  335.                 array(
  336.                     'id' => $paymentsClient->getProposalId()
  337.                 )
  338.             );
  339.         }else{
  340.             $errorMessage $this->translator->trans('Error, some fields are empty');
  341.             $this->addFlash('mensajepaymentsclienterror'$errorMessage);
  342.         }
  343.         return $this->redirectToRoute('proposal_invoice_proforma',
  344.             array(
  345.                 'id' => $paymentsClient->getProposalId()
  346.             )
  347.         );
  348.     }
  349.     /**
  350.      * @Route("/proposal/pdfpdf",  name="proposal_invoice_proforma_pdf_prueba")
  351.      */
  352.     public function pdfAction()
  353.     {
  354.         $snappy $this->get('knp_snappy.pdf');
  355.         $filename 'myFirstSnappyPDF';
  356.         $url 'http://mante.develup.solutions';
  357.         return new Response(
  358.             $snappy->getOutput($url),
  359.             200,
  360.             array(
  361.                 'Content-Type'          => 'application/pdf',
  362.                 'Content-Disposition'   => 'inline; filename="'.$filename.'.pdf"'
  363.             )
  364.         );
  365.     }
  366.     /**
  367.      * @Route("/proposal/invoice/proforma/pdf/{id}",  name="proposal_invoice_proforma_pdf")
  368.      */
  369.     public function detailsProformaPdfActionAction($idRequest $request)
  370.     {
  371.         $snappy $this->get('knp_snappy.pdf');
  372.         $filename 'myFirstSnappyPDF';
  373.         // use absolute path !
  374.         $pageUrl $this->generateUrl('proposal_invoice_proforma_print_externo', array('id'=>$id), UrlGeneratorInterface::ABSOLUTE_URL);
  375.         return new Response(
  376.             $snappy->getOutput($pageUrl),
  377.             200,
  378.             array(
  379.                 'Content-Type'          => 'application/pdf',
  380.                 'Content-Disposition'   => 'inline; filename="'.$filename.'.pdf"'
  381.             )
  382.         );
  383.     }
  384.     /**
  385.      * @Route("/proposal/invoice/pdf/{id}",  name="proposal_invoice_proforma_pdf")
  386.      */
  387.     public function detailsInvoicePdfActionAction($idRequest $request)
  388.     {
  389.         $snappy $this->get('knp_snappy.pdf');
  390.         $filename 'myFirstSnappyPDF';
  391.         // use absolute path !
  392.         $pageUrl $this->generateUrl('proposal_invoice_detector_print_externo', array('id'=>$id), UrlGeneratorInterface::ABSOLUTE_URL);
  393.         return new Response(
  394.             $snappy->getOutput($pageUrl),
  395.             200,
  396.             array(
  397.                 'Content-Type'          => 'application/pdf',
  398.                 'Content-Disposition'   => 'inline; filename="'.$filename.'.pdf"'
  399.             )
  400.         );
  401.     }
  402.     /**
  403.      * @Route("/proposal/invoice/proforma/print/{id}",  name="proposal_invoice_proforma_print")
  404.      */
  405.     public function detailsProformaPrintAction($idRequest $request)
  406.     {
  407. //        $token = "";
  408.         $em $this->getDoctrine()->getManager();
  409.         $proforma $em->getRepository(ProposalProforma::class)->findOneByProposalId($id);
  410.         if (!empty($proforma)){
  411.             $type 'Proforma';
  412.             $number $proforma->getId();
  413.             $date $proforma->getDateAt();
  414.             $prefix $proforma->getPrefix();
  415.             $data $this->baseInvoiceProposal($id$type$number$prefix$date$request);
  416.             $token $data['token'];
  417.         }else{
  418.             return $this->redirectToRoute('proposal_generate_proforma',
  419.                 array(
  420.                     'id' => $id
  421.                 )
  422.             );
  423.         }
  424.         $fees $em->getRepository(ProposalFee::class)->findByProposalId($id);
  425.         if (!empty($fees)){ if (!($fees[0]->getToInvoice())){ $fees null; } } // Si no se debe mostrar en factura se pone a null
  426.         $summary $em->getRepository(ProposalsInvoiceSummary::class)->findOneByProposalId($id);
  427.         $summaryInvoice = !empty($summary);
  428.         $summaryInvoiceText = !empty($summary) ? $summary->getDescription() : null;
  429.         return $this->render('MDS/EventsBundle/services/services-invoice-print-proposal.html.twig',
  430.             array(
  431.                 'id' => $id,
  432.                 'type' => $data['type'],
  433.                 'number' => $data['number'],
  434.                 'prefix' => $data['prefix'],
  435.                 'date' => $data['date'],
  436.                 'token' => $token,
  437.                 'proposal' => $data['proposal'],
  438.                 'company' => $data['company'],
  439.                 'clients' => $data['clients'],
  440.                 'datasupplier' => $data['datasupplier'],
  441.                 'totales_neto_antes' => $data['totales_neto_antes'],
  442.                 'totales_neto' => $data['totales_neto'],
  443.                 'bases_imponibles' => $data['bases_imponibles'],
  444.                 'totales_antes' => $data['totales_antes'],
  445.                 'totales' => $data['totales'],
  446.                 'balance' => $data['balance'],
  447.                 'totales_generales' => $data['totales_generales'],
  448.                 'currency' => $data['currency'],
  449.                 'detail_iva' => 'yes',
  450.                 'discounts' => $data['discounts'],
  451.                 'fees' => $fees,
  452.                 'paymentInvoice' => $data['paymentInvoice'],
  453.                 'summaryInvoice' => $summaryInvoice,
  454.                 'invoiceDesposit' => $data['invoiceDesposit'],
  455.                 'summaryInvoiceText' => $summaryInvoiceText,
  456.             )
  457.         );
  458.     }
  459.     /**
  460.      * @Route("/proposal/generate/invoice/{id}",  name="proposal_generate_invoice")
  461.      */
  462.     public function generateInvoiceAction($idRequest $request)
  463.     {
  464.         $em $this->getDoctrine()->getManager();
  465.         $invoiceGenerate $request->request->get('invoiceGenerate');
  466.         $invoice$em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
  467. //        d($invoiceGenerate);
  468. //        exit();
  469.         if (is_null($invoice)){
  470.             $proposal$em->getRepository(Proposal::class)->findOneById($id);
  471.             $status $proposal->getStatus(); // Para controlar que se guarde si no está facturado
  472.             $proposal->setStatus('Invoiced');
  473.             $invoice_new = new ProposalInvoice();
  474.             $invoice_new->setNumber($invoiceGenerate['number']);
  475.             $invoice_new->setDateAt(new \DateTime($invoiceGenerate['dateInvoice']));
  476.             $invoice_new->setType($invoiceGenerate['type']);
  477.             $invoice_new->setProposalId($invoiceGenerate['id']);
  478.             $invoice_new->setPrefix('');
  479. //            $invoice_new->setDateAt(new \DateTime("now"));
  480.             /* Obtengo usuario logueado */
  481.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  482.             $user_id $user_logueado->getId();
  483.             $invoice_new->setCreatedId($user_id);
  484.             $invoice_new->setUpdatedId($user_id);
  485.             if($status != 'Invoiced'){
  486.                 $em->persist($invoice_new);
  487.                 $em->persist($proposal);
  488.                 $em->flush();
  489.             }
  490.             //Envio correo a administracion en el caso que no tenga numero de factura y este como no enviado
  491.             if( empty($invoiceGenerate['number'])){
  492.                 $time = new \DateTime("now");
  493.                 $agent $em->getRepository(User::class)->findOneBy(
  494.                     array(
  495.                         "id" => $proposal->getAgentId(),
  496.                         "status" => VacationsConstants::PAYROLL_STAFF_STATUS
  497.                     )
  498.                 )
  499.                 ;
  500.                 $mailAgent[] = $agent->getEmail();
  501.                 $agentMail $agent->getEmail();
  502.                 $passGmail $agent->getPassGmail();
  503.                 $firmGmail $agent->getFirmGmail();
  504.                 $mailAgentSent = array(
  505.                     $agent->getEmail() => $agent->getName().' '$agent->getLastName()
  506.                 );
  507.                 $setting_rol $em->getRepository(SettingsRol::class)->findBy(
  508.                     array(
  509.                         'weight' => array('2','3'),
  510.                         'madmin' => '1',
  511.                     )
  512.                 );
  513.                 $mailAdmin = array();
  514.                 foreach($setting_rol as $settingRol){
  515.                     $administration $em->getRepository(User::class)->findByUserrol($settingRol->getId());
  516.                     foreach($administration as $admin){
  517.                         $mailAdmin[] = $admin->getEmail();
  518.                     }
  519.                 }
  520.                 $body ='P#'.$proposal->getId().', '.$proposal->getTitle().'<br><br>
  521.                             <a href="http://'.$request->server->get('HTTP_HOST').'/events/proposal/invoice/number/'.$proposal->getId().'">Asignar Número de Factura</a><br>
  522.                             <a href="http://'.$request->server->get('HTTP_HOST').'/events/proposal/edit/'.$proposal->getId().'">Ir al Proposal</a> - 
  523.                             <a href="http://'.$request->server->get('HTTP_HOST').'/events/proposal/summary/prices/'.$proposal->getId().'">Ver Resumen</a>
  524.                             <br><br>
  525.                             Alerta de solicitud automatizada de número de factura en fecha: '.$time->format('d/m/Y H:i:s').'<br><br>';
  526.                 $data = array(
  527.                     'body' => $body,
  528.                     'firm' => $firmGmail,
  529.                 );
  530.                 $mailTodos array_merge($mailAgent$mailAdmin);
  531.                 // EJECUTAR ENVIO DE ALERTA DE VISTO POR CLIENTE
  532.                 $transporter = new Swift_SmtpTransport();
  533.                 $transporter->setHost('smtp.gmail.com')
  534.                     ->setEncryption('ssl'//ssl / tls
  535.                     ->setPort(465// 465 / 587
  536.                     ->setUsername($agentMail)
  537.                     ->setPassword($passGmail);
  538. //                        ->setUsername('desarrollo@develup.solutions')
  539. //                        ->setPassword('Develup2017');
  540.                 $mailer = new Swift_Mailer($transporter);
  541.                 $message = new Swift_Message();
  542.                 $message->setSubject('P#'.$proposal->getId().', Solicitud de número de factura automatizada')
  543.                     ->setSender($agentMail)
  544.                     ->setFrom($mailAgentSent)
  545.                     ->setReplyTo($mailAgentSent)
  546.                     ->setTo($mailTodos)
  547.                     ->setBody(
  548.                         $this->renderView(
  549.                             'mail/structure-mail.html.twig',
  550.                             array('data' => $data)
  551.                         ),
  552.                         'text/html'
  553.                     )
  554.                 ;
  555.                 $mailer->send($message);
  556.             }
  557.             // Guardo en historico de seguimiento
  558.             $textHistory $this->translator->trans('Billed Proposal');
  559.             $history $this->TracingHistoryOperations($proposal->getId(), $textHistory);
  560.             // Verificamos si se debe crear un Fee asociado a la factura
  561.             $fee $em->getRepository(ProposalFee::class)->findOneByProposalId($id);
  562.             if (!empty($fee)){
  563.                 $feeInvoice = new ProposalFeeInvoice();
  564.                 $feeInvoice->setProposalId($id);
  565.                 $feeInvoice->setName($fee->getName());
  566.                 $feeInvoice->setType($fee->getType());
  567.                 $feeInvoice->setAmount($fee->getAmount());
  568.                 $feeInvoice->setOpIva($fee->getOpIva());
  569.                 $feeInvoice->setIva($fee->getIva());
  570.                 $feeInvoice->setToInvoice($fee->getToInvoice());
  571.                 $feeInvoice->setInvoiceId($invoice_new->getId());
  572.                 $feeInvoice->setFeeNet(0);
  573.                 $feeInvoice->setFeeTotal(0);
  574.                 $feeInvoice->setCreatedId($user_id);
  575.                 $feeInvoice->setCreatedAt(new \DateTime("now"));
  576.                 if($status != 'Invoiced'){
  577.                     $em->persist($feeInvoice);
  578.                     $em->flush();
  579.                 }
  580.             }
  581.         }
  582.         return $this->redirectToRoute('proposal_invoice_detector',
  583.             array(
  584.                 'id' => $invoiceGenerate['id']
  585.             )
  586.         );
  587.     }
  588.     /**
  589.      * @Route("/proposal/invoice/proforma/payments/delete/{id}",  name="proposal_invoice_proforma_payments_delete")
  590.      */
  591.     public function deletePaymentsProformaAction($idRequest $request)
  592.     {
  593.         $em $this->getDoctrine()->getManager();
  594.         $delete$em->getRepository(ProposalPaymentsClient::class)->findOneById($id);
  595.         $proposalId $delete->getProposalId();
  596.         $em->remove($delete);
  597.         $em->flush();
  598.         return $this->redirectToRoute('proposal_invoice_proforma',
  599.             array(
  600.                 'id' =>$proposalId
  601.             )
  602.         );
  603.     }
  604.     private function baseInvoiceProposal($id$type$number$prefix$dateRequest $request)
  605.     {
  606.         $em $this->getDoctrine()->getManager();
  607.         $proposal$em->getRepository(Proposal::class)->findOneById($id);
  608.         $services_supplier $em->getRepository(ProposalSupplierServicesCostsClient::class)->findBy(
  609.             array(
  610.                 'proposalId' => $id,
  611.                 'serviceIdFather' => '0'
  612.             ),
  613.             array(
  614.                 'id' => 'ASC'
  615.             )
  616.         );
  617.         $data_iva = array();
  618.         $supplier_control = array();
  619.         foreach($services_supplier as $servicessupplier){
  620. ////            $supplier_control[$servicessupplier->getSupplierId()] = $servicessupplier->getSupplierId();
  621. //            $supplier_control[$servicessupplier->getSupplierId()] = array(
  622. //                'id' => $servicessupplier->getSupplierId(),
  623. //                'destinoId' => $servicessupplier->getDestinationId(),
  624. //            );
  625.             if(!is_null($servicessupplier->getActivityId())){
  626.                 $supplier_control[$servicessupplier->getActivityId()] = array(
  627.                     'master' => 'activity',
  628.                     'id' => $servicessupplier->getActivityId(),
  629.                     'destinoId' => $servicessupplier->getDestinationId(),
  630.                 );
  631.             }
  632.             if(!is_null($servicessupplier->getIdeaId())){
  633.                 $supplier_control[$servicessupplier->getIdeaId()] = array(
  634.                     'master' => 'idea',
  635.                     'id' => $servicessupplier->getIdeaId(),
  636.                     'destinoId' => $servicessupplier->getDestinationId(),
  637.                 );
  638.             }
  639.             if((!is_null($servicessupplier->getSupplierId())) and ($servicessupplier->getIdeaId() == null) and ($servicessupplier->getActivityId() == null)){
  640.                 $supplier_control[$servicessupplier->getSupplierId()] = array(
  641.                     'master' => 'supplier',
  642.                     'id' => $servicessupplier->getSupplierId(),
  643.                     'destinoId' => $servicessupplier->getDestinationId(),
  644.                 );
  645.             }
  646.         }
  647.         $data_serviceCat = array();
  648.         $data_supplier = array();
  649.         $totales_neto_all 0;
  650.         $totales_all 0;
  651.         $currency ="";
  652.         $data_service_supplier = array();
  653.         foreach($supplier_control as $suppliercontrol){
  654. //            $destination = $em->getRepository(Destination::class)->findOneById($suppliercontrol['destinoId']);
  655.             $destination $em->getRepository(Destination::class)->findOneById($suppliercontrol['destinoId']);
  656.             $colorlabel"bg-success-300";
  657.             $sqlactivities "";
  658.             if($suppliercontrol['master'] == 'activity'){
  659.                 $master "activity";
  660.                 $sqlactivities $em->getRepository(Activities::class)->findOneById($suppliercontrol['id']);
  661.                 // ORDEN DESCENDENTE Y POR SERVICES
  662.                 $parameters = array(
  663.                     'proposalId' => $id,
  664.                     'serviceIdFather' => '0',
  665.                     'activityId' => $suppliercontrol['id']
  666.                 );
  667.                 $dql 'SELECT p
  668.                     FROM EventsBundle:ProposalSupplierServicesCostsClient p
  669.                     WHERE p.proposalId = :proposalId AND p.activityId = :activityId AND p.serviceIdFather = :serviceIdFather 
  670.                     ORDER BY p.serviceCatId, p.rank ASC ';
  671.                 $query $em->createQuery($dql)->setParameters($parameters);
  672.                 $data_service_supplier $query->getResult();
  673.             }
  674.             $sqlideas "";
  675.             if($suppliercontrol['master'] == 'idea'){
  676.                 $master "idea";
  677.                 $sqlideas $em->getRepository(Ideas::class)->findOneById($suppliercontrol['id']);
  678.                 // ORDEN DESCENDENTE Y POR SERVICES
  679.                 $parameters = array(
  680.                     'proposalId' => $id,
  681.                     'serviceIdFather' => '0',
  682.                     'ideaId' => $suppliercontrol['id']
  683.                 );
  684.                 $dql 'SELECT p
  685.                     FROM EventsBundle:ProposalSupplierServicesCostsClient p
  686.                     WHERE p.proposalId = :proposalId AND p.ideaId = :ideaId AND p.serviceIdFather = :serviceIdFather 
  687.                     ORDER BY p.serviceCatId, p.rank ASC ';
  688.                 $query $em->createQuery($dql)->setParameters($parameters);
  689.                 $data_service_supplier $query->getResult();
  690.             }
  691.             $sqlsuppliers ="";
  692.             if($suppliercontrol['master'] == 'supplier'){
  693.                 $master "supplier";
  694.                 $sqlsuppliers $em->getRepository(Supplier::class)->findOneById($suppliercontrol['id']);
  695.                 if(!is_null($sqlsuppliers)){
  696.                     switch ($sqlsuppliers->getStar()) {
  697.                         case 1:
  698.                             $sqlsuppliers->setStar('<i class="icon-star-full2"></i>');
  699.                             break;
  700.                         case 2:
  701.                             $sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i>');
  702.                             break;
  703.                         case 3:
  704.                             $sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i>');
  705.                             break;
  706.                         case 4:
  707.                             $sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i>');
  708.                             break;
  709.                         case 5:
  710.                             $sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i> SUP');
  711.                             break;
  712.                         case 6:
  713.                             $sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i>');
  714.                             break;
  715.                         case 7:
  716.                             $sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i> GL');
  717.                             break;
  718.                         case 8:
  719.                             $sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i> GL');
  720.                             break;
  721.                     }
  722.                 }
  723.                 // ORDEN DESCENDENTE Y POR SERVICES
  724.                 $parameters = array(
  725.                     'proposalId' => $id,
  726.                     'serviceIdFather' => '0',
  727.                     'supplierId' => $suppliercontrol['id']
  728.                 );
  729.                 $dql 'SELECT p
  730.                     FROM EventsBundle:ProposalSupplierServicesCostsClient p
  731.                     WHERE p.proposalId = :proposalId AND p.supplierId = :supplierId AND p.ideaId is null AND p.activityId is null AND p.serviceIdFather = :serviceIdFather 
  732.                     ORDER BY p.serviceCatId, p.rank ASC ';
  733.                 $query $em->createQuery($dql)->setParameters($parameters);
  734.                 $data_service_supplier $query->getResult();
  735.                 // Agrupamos asistencias de In-Out por ID de Agente
  736.                 $new_data_service_supplier = array();
  737.                 $arregloAcumulador = array();
  738.                 $acumulador = array();
  739.                 if ($sqlsuppliers->getCompany() == 'IN OUT TRAVEL & EVENTS') {
  740.                     // El proveedor es In Out
  741.                     foreach ($data_service_supplier as $dtsp){
  742.                         $zNameSrvOrNameUsr $em->getRepository(ProposalsSupplierServicesAssistantName::class)->findOneByPrpSupSrvId($dtsp->getServiceIdProposal());
  743.                         if ($dtsp->getServiceCatId() != 15){
  744.                             $new_data_service_supplier[] = $dtsp;
  745.                         } else {
  746.                             // Tenemos una asistencia de In Out
  747.                             // vamos acumulando precios, over, etc
  748.                             if ((! array_key_exists($dtsp->getAssistantId().'-'.$dtsp->getPrice(),$arregloAcumulador) ) and (!is_null($dtsp->getAssistantId()))){
  749. //                                Antes se comprobaba sololo con el id ahora el id del agente y el precio de la asistencia
  750. //                                $zAg= $em->getRepository(User::class)->findOneById($dtsp->getAssistantId());
  751. //                                $dtsp->setName('Staff In Out Events: '. $zAg->getName(). ' ' . $zAg->getLastName());
  752. //                                $dtsp->setUnits(1);
  753. //                                $arregloAcumulador[$dtsp->getAssistantId()] = $dtsp;
  754.                                 $zAg$em->getRepository(User::class)->findOneById($dtsp->getAssistantId());
  755. //                                if($zAg->getId() == 20){
  756. //                                  AQUI TENDRIAMOS LA CONDICION PARA QUE APAREZCA O NO EL NOMBRE EDL AGENTE (FUTURO DESARROLLO)
  757. //                                }else {
  758.                                 if (empty($zNameSrvOrNameUsr) && !is_null($zAg)) {
  759.                                     $dtsp->setName('Staff In Out Events: ' $zAg->getName() . ' ' $zAg->getLastName());
  760.                                 }
  761. //                                }
  762.                                 $dtsp->setUnits(1);
  763.                                 $arregloAcumulador[$dtsp->getAssistantId().'-'.$dtsp->getPrice()] = $dtsp;
  764.                             } else {
  765.                                 if ((!is_null($dtsp->getAssistantId()))){
  766. //                                Antes se comprobaba sololo con el id ahora el id del agente y el precio de la asistencia
  767. //                                $tempAcum = $arregloAcumulador[$dtsp->getAssistantId()];
  768.                                     $tempAcum $arregloAcumulador[$dtsp->getAssistantId().'-'.$dtsp->getPrice()];
  769.                                     $tempAcum->setUnits($tempAcum->getUnits() + 1);
  770.                                     //Si el dia de inicio es menor actualizas (para establecer rangos de varios dias)
  771.                                     if ($dtsp->getDateInAt() < $tempAcum->getDateInAt()) {
  772.                                         $tempAcum->setDateInAt($dtsp->getDateInAt());
  773.                                     }
  774.                                     //Si el dia de fin es mayor actualizas (para establecer rangos de varios dias)
  775.                                     if ($dtsp->getDateOutAt() > $tempAcum->getDateOutAt()) {
  776.                                         $tempAcum->setDateOutAt($dtsp->getDateOutAt());
  777.                                     }
  778. //                                Antes se comprobaba sololo con el id ahora el id del agente y el precio de la asistencia
  779. //                                $arregloAcumulador[$dtsp->getAssistantId()] = $tempAcum;
  780.                                     $arregloAcumulador[$dtsp->getAssistantId().'-'.$dtsp->getPrice()] = $tempAcum;
  781.                                 } else {
  782.                                     // Tenemos una asistencia de un agente EXTERNO - este agente no se encuentra en el listado de agentes de In Out
  783.                                     if ( array_key_exists($dtsp->getName(),$arregloAcumulador) ){
  784.                                         $tempAcum $arregloAcumulador[$dtsp->getName()];
  785.                                         $tempAcum->setUnits($tempAcum->getUnits() + 1);
  786.                                         if (empty($zNameSrvOrNameUsr)) {
  787.                                             $tempAcum->setName('Staff In Out Events: ' $dtsp->getName());
  788.                                         }
  789.                                         //Si el dia de inicio es menor actualizas (para establecer rangos de varios dias)
  790. //                                        if ($dtsp->getDateInAt() < $tempAcum->getDateInAt()) {
  791. //                                            $tempAcum->setDateInAt($dtsp->getDateInAt());
  792. //                                        }
  793. //                                        //Si el dia de fin es mayor actualizas (para establecer rangos de varios dias)
  794. //                                        if ($dtsp->getDateOutAt() > $tempAcum->getDateOutAt()) {
  795. //                                            $tempAcum->setDateOutAt($dtsp->getDateOutAt());
  796. //                                        }
  797.                                         $arregloAcumulador[$dtsp->getName()] = $tempAcum;
  798.                                     } else {
  799.                                         $arregloAcumulador[$dtsp->getName()] = $dtsp;
  800.                                         if (empty($zNameSrvOrNameUsr)) {
  801.                                             $arregloAcumulador[$dtsp->getName()]->setName('Staff In Out Events: ' $dtsp->getName());
  802.                                         }
  803.                                     }
  804.                                 }
  805.                             }
  806.                         }
  807.                     }
  808.                     //
  809.                     foreach ($arregloAcumulador as $aAc){
  810.                         $new_data_service_supplier[] = $aAc;
  811.                     }
  812.                     $data_service_supplier $new_data_service_supplier;
  813.                 }
  814.                 // FIN  -  Agrupamos asistencias de In-Out por ID de Agente
  815.             }
  816.             $imagenSmall null;
  817.             $service_supplier_data = array();
  818.             $totales_neto ='0';
  819.             $totales_iva ='0';
  820.             $totales_con_iva ='0';
  821.             $totales_paying ='0';
  822.             $totales_pago ='0';
  823.             $totales_benefit_moneda ='0';
  824.             $totales_benefit_porsentaje ='0';
  825.             foreach($data_service_supplier as $data_service){
  826. //                d($data_service->getId());
  827.                 //Currency
  828.                 $currency $data_service->getCurrency();
  829.                 if (isset($currency)){$currency="Euro";}
  830.                 if ($currency == "Euro"){$currency="€";}
  831.                 if ($currency == "Dolar"){$currency=" $";}
  832.                 if ($currency == "MXN"){$currency=" MXN";}
  833.                 $data_service->setCurrency($currency);
  834.                 $idcat $data_service->getServiceCatId();
  835.                 $price = ($data_service->getPrice() == "")? $data_service->getPrice();
  836.                 $units = ($data_service->getUnits() == "")? $data_service->getUnits();
  837.                 $pax = ($data_service->getPax() == "")? $data_service->getPax();
  838.                 $opcommission $data_service->getOpCommission();
  839.                 $commission $data_service->getCommission();
  840.                 $opover $data_service->getOpOver();
  841.                 $over $data_service->getOver();
  842.                 $opiva $data_service->getOpIva();
  843. //                $iva = $data_service->getIva();
  844.                 $iva = empty($data_service->getIva())? $data_service->getIva();
  845.                 $dateInAt $data_service->getDateInAt();
  846.                 $dateOutAt $data_service->getDateOutAt();
  847.                 if (!is_null($dateInAt) and !is_null($dateOutAt)){
  848.                     $days $dateInAt->diff($dateOutAt);
  849.                     $day $days->days;
  850.                 }else{
  851.                     $day "0";
  852.                 }
  853.                 if(!is_null($data_service->getActivityId())){
  854.                     $name_supplier $em->getRepository(Activities::class)->findOneById($data_service->getActivityId());
  855.                     if (empty($name_supplier)){
  856.                         $namesupplier '';
  857.                     }else{
  858.                         $namesupplier $name_supplier->getName();
  859.                     }
  860.                 }
  861.                 if(!is_null($data_service->getIdeaId())){
  862.                     $name_supplier $em->getRepository(Ideas::class)->findOneById($data_service->getIdeaId());
  863.                     if (empty($name_supplier)){
  864.                         $namesupplier '';
  865.                     }else{
  866.                         $namesupplier $name_supplier->getName();
  867.                     }
  868.                 }
  869.                 if((!is_null($data_service->getSupplierId())) and ($data_service->getIdeaId() == null) and ($data_service->getActivityId() == null) ){
  870.                     $name_supplier $em->getRepository(Supplier::class)->findOneById($data_service->getSupplierId());
  871.                     if (empty($name_supplier)){
  872.                         $namesupplier '';
  873.                     }else{
  874.                         $namesupplier $name_supplier->getName();
  875.                     }
  876.                 }
  877. //                $name_supplier = $em->getRepository(Supplier::class)->findOneById($data_service->getSupplierId());
  878. //                $namesupplier = $name_supplier->getName();
  879.                 if($type == 'No Vat Invoice'){
  880.                     $iva="0";
  881.                     $data_service->setIva($iva);
  882.                 }
  883.                 $calculos $this->CalculoTotalesservices($price$units$pax$day$opcommission$commission$opover$over$opiva$iva$idcat);
  884.                 $data_service->setPrice($calculos['precio']); //ojo aqui
  885.                 $service_supplier_data[] = array(
  886.                     'calculos' => $calculos,
  887.                     'services_data' => $data_service,
  888.                     'namesupplier' => $namesupplier
  889.                 );
  890.                 $totales_neto += $calculos['total_neto'];
  891.                 $totales_iva += $calculos['sub_total_iva'];
  892.                 $totales_con_iva += $calculos['total'];
  893.                 $totales_paying += $calculos['total_paying'];
  894.                 $totales_pago += $calculos['total_pago'];
  895.                 $totales_benefit_moneda += $calculos['benefit_moneda'];
  896.                 /* base imponible por servicios */
  897.                 if (empty($base_imponible_service[$idcat])){
  898.                     $base_imponible_service[$idcat]= 0;
  899.                 }
  900.                 $base_imponible_service[$idcat] += $calculos['total_neto'];
  901.                 $data_serviceCat[$idcat] = array(
  902.                     'idcat' => $idcat,
  903.                     'total_neto' => $base_imponible_service[$idcat],
  904.                 );
  905.                 /* base impobnible detalles por diferentes Ivas */
  906.                 if (empty($base_imponible_iva[$iva])){
  907.                     $base_imponible_iva[$iva]= 0;
  908.                 }
  909.                 $base_imponible_iva[$iva] += $calculos['total_neto'];
  910.                 if (empty($totales_ivas_all[$iva])){
  911.                     $totales_ivas_all[$iva]= 0;
  912.                 }
  913.                 $totales_ivas_all[$iva] += $calculos['sub_total_iva'];
  914.                 $totales_neto_all += $calculos['total_neto'];
  915.                 $totales_all += $calculos['total'];
  916.                 $data_iva[$iva] = array(
  917.                     'iva' => $iva,
  918.                     'ivas' => $totales_ivas_all[$iva],
  919.                     'total_iva' => $base_imponible_iva[$iva]
  920.                 );
  921.                 if ($totales_benefit_moneda == '0'){
  922.                     $totales_benefit_porsentaje =  '0';
  923.                 }else{
  924.                     if ($totales_neto != 0) {
  925.                         $totales_benefit_porsentaje $totales_benefit_moneda $totales_neto 100// arreglado or esteban
  926.                     } else {
  927.                         $totales_benefit_porsentaje 0;
  928.                     }
  929.                 }
  930.             }
  931.             $calculos_totatales = array(
  932.                 'totales_neto' => $totales_neto,
  933.                 'totales_iva' => $totales_iva,
  934.                 'totales_con_iva' => $totales_con_iva,
  935.                 'totales_paying' => $totales_paying,
  936.                 'totales_benefit_moneda' => $totales_benefit_moneda,
  937.                 'totales_benefit_porsentaje' => $totales_benefit_porsentaje
  938.             );
  939.             $data_supplier[$destination->getTitle()][] = array(
  940.                 'master' => $master,
  941.                 'colorlabel' => $colorlabel,
  942.                 'control' => "1",
  943.                 'supplier' => $sqlsuppliers,
  944.                 'idea' => $sqlideas,
  945.                 'activity' => $sqlactivities,
  946.                 'image' => $imagenSmall,
  947.                 'services' => $service_supplier_data,
  948.                 'totales_services' => $calculos_totatales
  949.             );
  950.         }
  951.         $totales_neto_antes $totales_neto_all;
  952.         $totales_antes $totales_all;
  953.         /*Group Everything*/
  954.         if($type == 'Group Everything'){
  955.             $data_supplier = array();
  956.             $service_supplier_data = array();
  957.             $messageitems $this->translator->trans('Grouped Services');
  958.             $data_service = array(
  959.                 "price" => $totales_neto_antes,
  960.                 "name" => $messageitems,
  961.                 "units" => 1,
  962.                 "iva" => $iva,
  963.                 "dateInAt" => "2018-4-4",
  964.                 "dateOutAt" => "2018-4-4",
  965.             );
  966.             $calculos = array(
  967.                 "precio" => $totales_neto_antes,
  968.                 "total_days" => 1,
  969.                 "sub_total" => $totales_neto_antes,
  970.                 "sub_total_iva" => 0,
  971.                 "total_neto" => $totales_neto_antes,
  972.                 "total_iva" => 0,
  973.                 "total_paying" => 0,
  974.                 "total_pago" => 0,
  975.                 "total_comision" => "0",
  976.                 "total" => $totales_antes,
  977.                 "benefit_moneda" => 0,
  978.             );
  979.             $service_supplier_data[] = array(
  980.                 'calculos' => $calculos,
  981.                 'services_data' => $data_service,
  982.                 'namesupplier' => ""
  983.             );
  984.             $calculos_totatales = array(
  985.                 'totales_neto' => $totales_neto_antes,
  986.                 'totales_iva' => "",
  987.                 'totales_con_iva' => $totales_antes,
  988.                 'totales_paying' => "",
  989.                 'totales_benefit_moneda' => "",
  990.                 'totales_benefit_porsentaje' => ""
  991.             );
  992.             $data_supplier[$messageitems][] = array(
  993.                 'master' => '',
  994.                 'colorlabel' => '',
  995.                 'control' => "1",
  996.                 'supplier' => '',
  997.                 'idea' => '',
  998.                 'activity' => '',
  999.                 'image' => '',
  1000.                 'services' => $service_supplier_data,
  1001.                 'totales_services' => $calculos_totatales
  1002.             );
  1003.         }
  1004.         $data_serviceOut = array(
  1005.             'idcat' => null,
  1006.             'total_neto' => $totales_neto_all,
  1007.         );
  1008. //        d($data_serviceCat,$data_serviceOut);
  1009.         array_push $data_serviceCat$data_serviceOut );
  1010.         $company $em->getRepository(SettingsCompany::class)->findOneByPriority('1');
  1011.         $parameters = array(
  1012.             'id' => $proposal->getclientId(),
  1013.         );
  1014.         $dql 'SELECT cl,  c.country, re.region, p.name, r.city
  1015.                 FROM App:Client cl
  1016.                 INNER JOIN App:Country c WITH c.id = cl.country
  1017.                 INNER JOIN App:Regions re WITH re.id = cl.region
  1018.                 INNER JOIN App:Provinces p WITH p.id = cl.province
  1019.                 INNER JOIN App:Cities r WITH r.id = cl.population
  1020.                 WHERE cl.id = :id';
  1021.         $query $em->createQuery($dql)->setParameters($parameters);
  1022.         $client $query->getResult();
  1023. //        d($data_iva);
  1024.         $data_invoice = array();
  1025.         $inv_neto_total 0;
  1026.         $inv_total 0;
  1027.         $invoice_deposit_control $em->getRepository(ProposalInvoiceDepositControl::class)->findByProposalId($proposal->getId());
  1028.         if (!empty($invoice_deposit_control)){
  1029.             foreach($invoice_deposit_control as $invoicedepositcontrol) {
  1030.                 $data_items_inv = array();
  1031.                 $invoice_deposit_items $em->getRepository(ProposalInvoiceDepositItems::class)->findByControlId($invoicedepositcontrol->getId());
  1032.                 foreach($invoice_deposit_items as $invoicedeposititems) {
  1033.                     $invamount $invoicedeposititems->getAmount();
  1034.                     $invamount_iva $invoicedeposititems->getIva();
  1035.                     $invamount_el_iva $invamount * ($invamount_iva 100);
  1036.                     $invamount_con_iva $invamount * (($invamount_iva 100) + );
  1037.                     $inv_neto_total += $invamount;
  1038.                     $inv_total += $invamount_con_iva;
  1039.                     if (is_null($invoicedepositcontrol->getNumber())){
  1040.                         $numInvoice $invoicedepositcontrol->getId();
  1041.                     }else{
  1042.                         $numInvoice $invoicedepositcontrol->getNumber();
  1043.                     }
  1044.                     $data_items_inv[] = array(
  1045.                         'numInvoice' => $numInvoice,
  1046.                         'name' => $invoicedeposititems->getName(),
  1047.                         'amount' => $invoicedeposititems->getAmount(),
  1048.                         'iva' => $invoicedeposititems->getIva(),
  1049.                         'ivaamount' => $invamount_el_iva,
  1050.                         'total' => $invamount_con_iva,
  1051.                     );
  1052.                     foreach($data_iva as $items_iva) {
  1053.                         if ($items_iva['iva'] == $invoicedeposititems->getIva()){
  1054.                             $new_iva $items_iva['iva'];
  1055.                             $new_ivas $items_iva['ivas'] - $invamount_el_iva;
  1056.                             $new_total_iva $items_iva['total_iva'] - $invoicedeposititems->getAmount();
  1057.                             $new_data_iva = array(
  1058.                                 'iva' => $new_iva,
  1059.                                 'ivas' => $new_ivas,
  1060.                                 'total_iva' => $new_total_iva
  1061.                             );
  1062.                             $data_iva array_replace($data_iva, array( $new_iva => $new_data_iva ));
  1063.                         }
  1064.                     }
  1065.                 }
  1066.                 $data_invoice[] = array(
  1067.                     'itemsInvoice' => $data_items_inv,
  1068.                 );
  1069.             }
  1070. //            d($inv_neto_total, $inv_total);
  1071.             $totales_neto_all $totales_neto_all $inv_neto_total;
  1072.             $totales_all $totales_all $inv_total;
  1073. //            d($totales_neto_all, $totales_all);
  1074.         }
  1075. //        d($data_invoice, $data_iva);
  1076. //        d($data_iva);
  1077.         $consulta_discount $em->getRepository(ProposalDiscount::class)->findByProposalId($id);
  1078.         $cuantosdiscount count($consulta_discount);
  1079. //
  1080. //
  1081. //        if (!empty($consulta_discount)){
  1082. //            $descuento =array();
  1083. //            $name ="";
  1084. //            $amount = "";
  1085. //            $type_des = "";
  1086. //            $iva_discount="";
  1087. //            $totales_generales="";
  1088. //            $totales_neto_des = $totales_neto_all;
  1089. //            $calculo_net_negativo="";
  1090. //            $total_con_iva_desc="";
  1091. //
  1092. //            foreach($consulta_discount as $consultadiscount) {
  1093. //
  1094. //                $iva = $consultadiscount->getIva() / 100;
  1095. //                if ($consultadiscount->getType()=="0"){
  1096. //                    $por = $consultadiscount->getAmount() / 100;
  1097. //                    $totales_neto_des = $totales_neto_des / ($por + 1) ;
  1098. //
  1099. //                    $name = $consultadiscount->getName();
  1100. //                    $type_des = $consultadiscount->getType();
  1101. //                    $amount = $consultadiscount->getAmount();
  1102. //                }
  1103. //
  1104. //
  1105. //                if ($consultadiscount->getType()=="1"){
  1106. //                    $totales_neto_des = $totales_neto_des - $consultadiscount->getAmount();
  1107. //                    $name = $consultadiscount->getName();
  1108. //                    $type_des = $consultadiscount->getType();
  1109. //                    $amount = $consultadiscount->getAmount();
  1110. //                }
  1111. //
  1112. //                // resultados en negativo
  1113. //                $calculo_net_negativo =  $totales_neto_des - $totales_neto_all;
  1114. //
  1115. //                $total_desc = "0";
  1116. //                // resultados para calculos
  1117. //                $calculo_net = $totales_neto_all - $totales_neto_des;
  1118. //                if($consultadiscount->getOpIva() =='0'){
  1119. //                    $iva_discount = $calculo_net - ($calculo_net / ($iva + 1));
  1120. //                    $calculo_net_negativo = $calculo_net_negativo + $iva_discount;
  1121. //                    $totales_neto_des = $totales_neto_des + $iva_discount;
  1122. //                    $total_desc = $iva_discount;
  1123. //                }
  1124. //                if($consultadiscount->getOpIva() =='1'){
  1125. //                    $iva_discount = $calculo_net * $iva;
  1126. //                    $total_desc = $iva_discount;
  1127. //                }
  1128. //
  1129. //                if($type == 'No Vat Invoice'){
  1130. //                    $iva_discount = "0";
  1131. //                }
  1132. //                // resultados en negativo
  1133. ////                $calculo_net_negativo =  $totales_neto_des - $totales_neto_all;
  1134. //
  1135. //                $total_con_iva_desc = $calculo_net_negativo - $iva_discount;
  1136. //
  1137. //
  1138. //                $operacion = $totales_all - $totales_neto_all;
  1139. //                $totales_generales = $totales_neto_des + $operacion - $total_desc;
  1140. //
  1141. //
  1142. //
  1143. //                $descuento[] = array(
  1144. //                    'name' => $name,
  1145. //                    'type' => $type_des,
  1146. //                    'amount' => $amount,
  1147. //                    'iva' => $consultadiscount->getIva(),
  1148. //                    'totales_neto_des' => $calculo_net_negativo,
  1149. //                    'total' => $total_con_iva_desc,
  1150. //                );
  1151. //
  1152. //                $totales_neto_all = $totales_neto_des;
  1153. //                $totales_all = $totales_generales;
  1154. //
  1155. //            }
  1156. //        }
  1157.         $totales_generales="";
  1158.         $descuento =array();
  1159.         if (!empty($consulta_discount)){
  1160. //            d($data_serviceCat);
  1161.             $quitar_en_todos 0;
  1162.             $datos_total_neto_suma 0;
  1163.             foreach($data_serviceCat as $dataserviceat) {
  1164.                 $name ="";
  1165.                 $amount "";
  1166.                 $type_des "";
  1167.                 $iva_discount="";
  1168.                 $datos_idcat $dataserviceat['idcat'];
  1169.                 $datos_total_neto $dataserviceat['total_neto'];
  1170.                 $totales_neto_des $datos_total_neto;
  1171.                 $datosiva_neto_des $datos_total_neto;
  1172.                 $calculo_net_negativo="";
  1173.                 $total_con_iva_desc="";
  1174.                 $contarveces 1;
  1175.                 foreach($consulta_discount as $consultadiscount) {
  1176.                     if($dataserviceat['idcat'] == null){
  1177.                         if($contarveces ){
  1178.                             $totales_neto_des $datos_total_neto_suma;
  1179.                             $datosiva_neto_des $datos_total_neto_suma;
  1180.                             $datos_total_neto $datos_total_neto_suma;
  1181.                         }else{
  1182.                             if($cuantosdiscount 1){
  1183.                                 $totales_neto_des $dataserviceat['total_neto'] - $quitar_en_todos;
  1184.                                 $datosiva_neto_des $dataserviceat['total_neto'] - $quitar_en_todos;
  1185.                                 $datos_total_neto $dataserviceat['total_neto'] - $quitar_en_todos;
  1186.                             }
  1187.                         }
  1188.                         $contarveces += 1;
  1189.                     }
  1190.                     if ($dataserviceat['idcat'] == $consultadiscount->getServiceId()){
  1191.                         $iva $consultadiscount->getIva() / 100;
  1192.                         if ($consultadiscount->getType()=="0"){
  1193.                             $por $consultadiscount->getAmount() / 100;
  1194. //                            $datosiva_neto_des = $datosiva_neto_des / ($por + 1) ;
  1195.                             $datosiva_neto_des $datosiva_neto_des - ($datosiva_neto_des $por) ;
  1196.                             $name $consultadiscount->getName();
  1197.                             $type_des $consultadiscount->getType();
  1198.                             $amount $consultadiscount->getAmount();
  1199.                         }
  1200.                         if ($consultadiscount->getType()=="1"){
  1201.                             $datosiva_neto_des $datosiva_neto_des $consultadiscount->getAmount();
  1202.                             $name $consultadiscount->getName();
  1203.                             $type_des $consultadiscount->getType();
  1204.                             $amount $consultadiscount->getAmount();
  1205.                         }
  1206. //                        d($dataserviceat['idcat'], $datos_total_neto);
  1207.                         // resultados en negativo
  1208.                         $calculo_net_negativo =  $datosiva_neto_des $datos_total_neto;
  1209. //                        d($calculo_net_negativo);
  1210.                         $total_desc "0";
  1211.                         // resultados para calculos
  1212.                         $calculo_net $datos_total_neto $datosiva_neto_des;
  1213.                         if($consultadiscount->getOpIva() =='0'){
  1214.                             $iva_discount $calculo_net - ($calculo_net / ($iva 1));
  1215.                             $calculo_net_negativo $calculo_net_negativo $iva_discount;
  1216.                             $totales_neto_des $totales_neto_des $iva_discount;
  1217.                             $total_desc $iva_discount;
  1218.                         }
  1219.                         if($consultadiscount->getOpIva() =='1'){
  1220.                             $iva_discount $calculo_net $iva;
  1221.                             $total_desc $iva_discount;
  1222.                         }
  1223.                         if($type == 'No Vat Invoice'){
  1224.                             $iva_discount "0";
  1225.                         }
  1226. //                        if($dataserviceat['idcat'] == null){
  1227.                         $datos_total_neto_suma $datos_total_netoabs($calculo_net_negativo);
  1228. //                        }
  1229.                         $quitar_en_todos $quitar_en_todos abs($calculo_net_negativo);
  1230. //                        d($datosiva_neto_des, $calculo_net_negativo);
  1231. //                        $datosiva_neto_des = $datosiva_neto_des + $calculo_net_negativo;
  1232. //                        d($quitar_en_todos);
  1233.                         $total_con_iva_desc $calculo_net_negativo $iva_discount;
  1234.                         $totales_neto_all $totales_neto_all abs($calculo_net_negativo);
  1235.                         $totales_all $totales_all abs($total_con_iva_desc);
  1236.                         $descuento[] = array(
  1237.                             'name' => $name,
  1238.                             'type' => $type_des,
  1239.                             'amount' => $amount,
  1240.                             'iva' => $consultadiscount->getIva(),
  1241.                             'iva_amount' => $iva_discount,
  1242.                             'totales_neto_des' => $calculo_net_negativo,
  1243.                             'total' => $total_con_iva_desc,
  1244.                         );
  1245.                         // Nueva actualizacion 17-07-2019 Recalcular Ivas
  1246.                         foreach($data_iva as $items_iva) {
  1247.                             if ($items_iva['iva'] == $consultadiscount->getIva()){
  1248.                                 $new_iva $items_iva['iva'];
  1249.                                 $new_ivas $items_iva['ivas'] - $iva_discount;
  1250.                                 $new_total_iva $items_iva['total_iva'] - $iva_discount;
  1251.                                 $new_data_iva = array(
  1252.                                     'iva' => $new_iva,
  1253.                                     'ivas' => $new_ivas,
  1254.                                     'total_iva' => $new_total_iva
  1255.                                 );
  1256.                                 $data_iva array_replace($data_iva, array( $new_iva => $new_data_iva ));
  1257.                             }
  1258.                         }
  1259.                     }
  1260.                 }
  1261.             }
  1262.         }
  1263. //        d($descuento);
  1264. //        d($data_iva);
  1265.         $payments $em->getRepository(ProposalPaymentsClient::class)->findByProposalId($id);
  1266.         $amount_pay 0;
  1267.         foreach($payments as $payment) {
  1268.             $amount_pay $amount_pay $payment->getAmount();
  1269.         }
  1270.         $totales_all round($totales_all,2);
  1271.         $totales_total $totales_all;
  1272.         if (!empty($payments)){
  1273.             $totales_all $totales_all $amount_pay;
  1274.         }
  1275.         //Si hay uno o varios depositos previos el IVA debe ser calculado en funcion de totales_neto = totales_neto_antes - amount
  1276. //        $adelanto = 0;
  1277. //        if(sizeof($data_invoice)!=0){
  1278. //            foreach ($data_invoice as $pago_previo){
  1279. //                foreach ($pago_previo as $adel){
  1280. //                    foreach ($adel as $ade){
  1281. //                        $adelanto = $adelanto + $ade['amount'];
  1282. //                    }
  1283. //                }
  1284. //            }
  1285. //        }
  1286. //
  1287. //        if ($adelanto != 0){
  1288. //            $new_data_iva = null;
  1289. //            $new_iva = number_format($totales_neto_antes, 2, '.','') - number_format($adelanto, 2, '.','');
  1290. //            $new_iva = $new_iva * $data_iva['21']['iva'];
  1291. //            $new_iva =$new_iva/100;
  1292. //            $new_iva = number_format($new_iva, 2, '.','');
  1293. //            foreach ($data_iva as $dativ){
  1294. //                $dativ['ivas'] = $new_iva;
  1295. //                $new_data_iva['21'] = $dativ;
  1296. //            }
  1297. //
  1298. //            $data_iva = $new_data_iva;
  1299. //
  1300. //        }
  1301.         $data = array(
  1302.             'id' => $id,
  1303.             'type' => $type,
  1304.             'number' => $number,
  1305.             'prefix' => $prefix,
  1306.             'date' => $date,
  1307.             'token' => $proposal->getAccessKey(),
  1308.             'proposal' => $proposal,
  1309.             'company' => $company,
  1310.             'clients' => $client,
  1311.             'datasupplier' => $data_supplier,
  1312.             'totales_neto_antes' => $totales_neto_antes,
  1313.             'totales_neto' => $totales_neto_all,
  1314.             'totales_generales' => $totales_generales,
  1315.             'bases_imponibles' => $data_iva,
  1316.             'totales_antes' => $totales_antes,
  1317.             'totales' => $totales_total,
  1318.             'balance' => $totales_all,
  1319.             'currency' => $currency,
  1320.             'paymentInvoice' => $amount_pay,
  1321.             'discounts' => $descuento,
  1322.             'invoiceDesposit' => $data_invoice,
  1323.         );
  1324. // ************************************************  FEE    ************************************************************
  1325.         $fees $em->getRepository(ProposalFee::class)->findByProposalId($id);
  1326.         $feesInvoice $em->getRepository(ProposalFeeInvoice::class)->findByProposalId($id);
  1327.         if (!empty($feesInvoice)) {
  1328.             // Fee en factura
  1329.             // Solo se haran los calculos si el Fee va a la factura, en caso contrario es un fee oculto y ya estará cargado en los servicios
  1330.             if ($feesInvoice[0]->getToinvoice() == true) {
  1331.                 foreach ($feesInvoice as $feeInv) {
  1332.                     if ($feeInv->getType() == 0) {
  1333.                         // Tenemos un porcentaje en el Fee de la factura, debe calcularse
  1334.                         $feeNet = ($data['totales_neto_antes'] * $feeInv->getAmount()) / 100;
  1335.                     } else {
  1336.                         $feeNet $feeInv->getAmount();
  1337.                     }
  1338.                     $feeTotal $feeNet 1.21;                     //El fee siempre será al 21%, Esteban Rincón
  1339.                     if ($feeInv->getToInvoice() == true) {
  1340.                         $data['totales_neto'] += $feeNet;
  1341.                         $data['totales'] += $feeTotal;
  1342.                         $data['balance'] += $feeTotal;
  1343.                         if (array_key_exists('21'$data['bases_imponibles'])) {
  1344.                             $data['bases_imponibles']['21']['ivas'] += $feeNet 0.21;
  1345.                             $data['bases_imponibles']['21']['total_iva'] += $feeNet;
  1346.                         } else {
  1347.                             $data['bases_imponibles']['21']['iva'] = '21';
  1348.                             $data['bases_imponibles']['21']['ivas'] = $feeNet 0.21;
  1349.                             $data['bases_imponibles']['21']['total_iva'] = $feeNet;
  1350.                         }
  1351.                     }
  1352.                     if ($feeInv->getFeeNet() == or empty($feeInv->getFeeNet())) {
  1353.                         // La asignación solo se hace la primera vez
  1354.                         $feeInv->setFeeNet($feeNet);
  1355.                         $feeInv->setFeeTotal($feeTotal);
  1356.                         $em->persist($feeInv);
  1357.                         $em->flush();
  1358.                     }
  1359.                 }
  1360.             }
  1361.         } else {
  1362.             // Fee en proforma
  1363.             if (!empty($fees)) {
  1364.                 // Solo se haran los calculos si el Fee va a la factura, en caso contrario es un fee oculto y ya estará cargado en los servicios
  1365.                 if ($fees[0]->getToinvoice() == true) {
  1366.                     foreach ($fees as $fee) {
  1367.                         if ($fee->getType() == 0) {
  1368.                             // Tenemos un porcentaje, debe calcularse
  1369.                             $amount = ($data['totales_neto_antes'] * $fee->getAmount()) / 100;
  1370.                             $fee->setAmount($amount);
  1371.                         }
  1372.                         $fee->setFeeTotal($fee->getAmount() * 1.21);        //El fee siempre será al 21%, Esteban Rincón
  1373.                         if ($fee->getToInvoice() == true) {
  1374.                             $data['totales_neto'] += $fee->getAmount();
  1375.                             $data['totales'] += $fee->getFeeTotal();
  1376.                             $data['balance'] += $fee->getFeeTotal();
  1377.                             if (array_key_exists('21'$data['bases_imponibles'])) {
  1378.                                 $data['bases_imponibles']['21']['ivas'] += $fee->getAmount() * 0.21;
  1379.                                 $data['bases_imponibles']['21']['total_iva'] += $fee->getAmount();
  1380.                             } else {
  1381.                                 $data['bases_imponibles']['21']['iva'] = '21';
  1382.                                 $data['bases_imponibles']['21']['ivas'] = $fee->getAmount() * 0.21;
  1383.                                 $data['bases_imponibles']['21']['total_iva'] = $fee->getAmount();
  1384.                             }
  1385.                         }
  1386.                     }
  1387.                 }
  1388.             }
  1389.         }
  1390. // ************************************************  FEE    ************************************************************
  1391.         return $data;
  1392.     }
  1393.     public function CalculoTotalesservices($price$units$pax$days$opcommission$commission$opover$over$opiva$iva$idcat)
  1394.     {
  1395.         $price trim($price);
  1396.         $over trim($over);
  1397.         $price str_replace(",""."$price);
  1398.         $over str_replace(",""."$over);
  1399.         if (empty($iva)){$iva=0;}
  1400.         $iva $iva 100;
  1401.         if($opiva =='0'){
  1402.             $price $price / ($iva 1);
  1403.         }
  1404.         if(!empty($commission)){
  1405.             if($opcommission=='0'){
  1406.                 $commission = (100 $commission) / 100;
  1407.                 $precio_units $price;
  1408.                 $price $price $commission;
  1409.             }
  1410.             if($opcommission=='1'){
  1411.                 $commission = ($commission 100) + 1;
  1412.                 $precio_units $price $commission;
  1413.             }
  1414.         }else{
  1415.             $precio_units $price;
  1416.         }
  1417.         //Units
  1418.         if(empty($units) or $units =="0"){
  1419.             $units "1";
  1420.         }
  1421.         // Calculo Especial por categoria
  1422.         //Alojamientos
  1423.         if($idcat =="1"){
  1424.             $informativo_days "si";
  1425.             $pax "1";
  1426.         }
  1427.         //Transporte
  1428.         elseif($idcat =="13"){
  1429.             $informativo_days "no";
  1430.             $pax "1";
  1431.             //            if($days > "1"){
  1432.             //                $days = "2";
  1433.             //            }else{
  1434.             //                $days = "1";
  1435.             //            }
  1436.         }
  1437.         //Lounge
  1438.         elseif($idcat =="10"){
  1439.             $informativo_days "no";
  1440.             $pax "1";
  1441.         }
  1442.         //Guia
  1443.         elseif($idcat =="8"){
  1444.             $informativo_days "no";
  1445.             $pax "1";
  1446.         }
  1447.         //Asistencia
  1448.         elseif($idcat =="15"){
  1449.             $informativo_days "no";
  1450.             $days '0';
  1451.         }else{
  1452.             $informativo_days "no";
  1453.         }
  1454.         //Pax
  1455.         if(empty($pax) or $pax =="0"){
  1456.             $pax "1";
  1457.         }
  1458.         //Over
  1459.         if(empty($over)){
  1460.             $over "0";
  1461.         }
  1462.         if($informativo_days =="no"){
  1463.             //Days
  1464.             if(empty($days) or $days =="0"){
  1465.                 $days "1";
  1466.             }else{
  1467.                 $days $days ;
  1468.             }
  1469.         }
  1470.         $total_items $price $units $pax $days;
  1471. //        $total_pdirect = $price * $units * $pax * $days;
  1472.         $total_over $over $units $pax $days;
  1473. //        if($opover=='0'){
  1474. //            $total_neto = $total_items / $commission - $total_over ;
  1475. //            $precio_units = $precio_units - $over;
  1476. //        }
  1477. //        if($opover=='1'){
  1478. //            $total_neto = $total_items / $commission + $total_over;
  1479. //            $precio_units = $precio_units + $over;
  1480. //        }
  1481.         if(!empty($commission)){
  1482.             if($opcommission=='0'){
  1483.                 $total_neto $total_items $commission;
  1484.             }
  1485.             if($opcommission=='1'){
  1486.                 $total_neto $total_items $commission;
  1487.             }
  1488.         }else{
  1489.             $total_neto $total_items;
  1490.         }
  1491.         if($opover=='0'){
  1492.             $total_neto $total_neto $total_over ;
  1493.             $precio_units $precio_units $over;
  1494.         }
  1495.         if($opover=='1'){
  1496.             $total_neto $total_neto +  $total_over;
  1497.             $precio_units $precio_units $over;
  1498.         }
  1499.         $total_paying $total_items * ($iva 1);
  1500.         $total_comision ="0";
  1501.         $total_pago $total_items;
  1502.         $total_iva $total_items $iva;
  1503.         $sub_total_iva $total_neto $iva;
  1504.         $total $total_neto $sub_total_iva;
  1505.         $benefit_moneda $total_neto $total_items;
  1506.         $data_calculos = array(
  1507.             'precio' => $precio_units,
  1508.             'total_days' => $days,
  1509.             'sub_total' => $total_items,
  1510.             'sub_total_iva' => $sub_total_iva,
  1511.             'total_neto' => $total_neto,
  1512.             'total_iva' => $total_iva,
  1513.             'total_paying' => $total_paying,
  1514.             'total_pago' => $total_pago,
  1515.             'total_comision' => $total_comision,
  1516.             'total' => $total,
  1517.             'benefit_moneda' => $benefit_moneda
  1518.         );
  1519.         return $data_calculos;
  1520.     }
  1521.     /**
  1522.      * @Route("/proposal/invoice/number/{id}", name="proposal_invoice_number")
  1523.      */
  1524.     public function InvoiceEmptyNumberAction($idRequest $request) {
  1525.         $em $this->getDoctrine()->getManager();
  1526.         $proposal $em->getRepository(Proposal::class)->findOneById($id);
  1527.         $invoice $em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
  1528.         $client $em->getRepository(Client::class)->findOneById($proposal->getClientId());
  1529.         $country $em->getRepository(Country::class)->findOneById($client->getCountry());
  1530.         $client->setCountry($country->getCountry());
  1531.         $regions $em->getRepository(Regions::class)->findOneById($client->getRegion());
  1532.         $client->setRegion($regions->getRegion());
  1533.         $province $em->getRepository(Provinces::class)->findOneById($client->getProvince());
  1534.         $client->setProvince($province->getName());
  1535.         $cities $em->getRepository(Cities::class)->findOneById($client->getPopulation());
  1536.         $client->setPopulation($cities->getCity());
  1537.         return $this->render('MDS/EventsBundle/invoice/add-number-invoice.html.twig', array(
  1538.             'id' => $id,
  1539.             'invoice' => $invoice,
  1540.             'mcp' => $proposal->getMcp(),
  1541.             'token' => $proposal->getAccessKey(),
  1542.             'proposal' => $proposal,
  1543.             'client' => $client,
  1544.         ));
  1545.     }
  1546.     /**
  1547.      * @Route("/proposal/invoice/number/updated/{id}", name="proposal_invoice_number_update")
  1548.      */
  1549.     public function InvoiceEmptyNumberupdateAction($idRequest $request)
  1550.     {
  1551.         $em $this->getDoctrine()->getManager();
  1552.         $proposal $em->getRepository(Proposal::class)->findOneById($id);
  1553.         $invoice $em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
  1554.         $numberinvoice $request->request->get('invoice')['number'];
  1555.         $dateAt = new \DateTime($request->request->get('invoice')['dateAt']);
  1556.         if(!empty($numberinvoice))
  1557.         {
  1558.             $invoice->setNumber($numberinvoice);
  1559.             $invoice->setDateAt($dateAt);
  1560.             // Envio correo al agente para informar que fue colocado el numero de factura
  1561.             $time = new \DateTime("now");
  1562.             $agent $em->getRepository(User::class)->findOneById($proposal->getAgentId());
  1563.             $mailAgent[] = $agent->getEmail();
  1564.             $agentMail $agent->getEmail();
  1565.             $passGmail $agent->getPassGmail();
  1566.             $firmGmail $agent->getFirmGmail();
  1567.             $mailAgentSent = array(
  1568.                 $agent->getEmail() => $agent->getName().' '$agent->getLastName()
  1569.             );
  1570.             $body 'P#'.$proposal->getId().', '.$proposal->getTitle().'<br>
  1571.                         <a href="http://'.$request->server->get('HTTP_HOST').'/events/events/proposal/edit/'.$proposal->getId().'">Ir al Proposal</a> - 
  1572.                         <a href="http://'.$request->server->get('HTTP_HOST').'/events/proposal/invoice/'.$proposal->getId().'">Ver Factura</a><br>
  1573.                         <br>Alerta de Fatura activada: '.$time->format('d/m/Y H:i:s').'<br><br>';
  1574.             $data = array(
  1575.                 'body' => $body,
  1576.                 'firm' => $firmGmail,
  1577.             );
  1578.             $mailTodos array_merge($mailAgent);
  1579.             // EJECUTAR ENVIO DE ALERTA DE VISTO POR CLIENTE
  1580.             $transporter = new Swift_SmtpTransport();
  1581.             $transporter->setHost('smtp.gmail.com')
  1582.                 ->setEncryption('ssl'//ssl / tls
  1583.                 ->setPort(465// 465 / 587
  1584.                 ->setUsername($agentMail)
  1585.                 ->setPassword($passGmail);
  1586.             //                        ->setUsername('desarrollo@develup.solutions')
  1587.             //                        ->setPassword('MeDITeRRANeAN_Develup30102023#');
  1588.             $mailer = new Swift_Mailer($transporter);
  1589.             $message = new Swift_Message();
  1590.             $message->setSubject('P#'.$proposal->getId().', Alerta de Fatura activada.')
  1591.                 ->setSender($agentMail)
  1592.                 ->setFrom($mailAgentSent)
  1593.                 ->setReplyTo($mailAgentSent)
  1594.                 ->setTo($mailTodos)
  1595.                 ->setBody(
  1596.                     $this->renderView(
  1597.                         'mail/structure-mail.html.twig',
  1598.                         array('data' => $data)
  1599.                     ),
  1600.                     'text/html'
  1601.                 )
  1602.             ;
  1603.             $mailer->send($message);
  1604.             /* Obtengo usuario logueado */
  1605.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1606.             $user_id $user_logueado->getId();
  1607.             $proposal->setUpdatedId($user_id);
  1608.             $em->persist($invoice);
  1609.             $em->persist($proposal);
  1610.             $em->flush();
  1611.             $event 'The Invoice has been Updated. Now';
  1612.             $successMessage $this->translator->trans($event);
  1613.             $this->addFlash('mensajeproposaldestination'$successMessage);
  1614.         }else{
  1615.             $errorMessage $this->translator->trans('Error, some fields are empty');
  1616.             $this->addFlash('mensajeproposaldestinationerror'$errorMessage);
  1617.         }
  1618.         return $this->redirectToRoute('proposal_invoice_number',
  1619.             array(
  1620.                 'id' => $id
  1621.             )
  1622.         );
  1623.     }
  1624.     /**
  1625.      * @Route("/proposal/invoice/number/liberate/{id}", name="proposal_invoice_number_liberate")
  1626.      */
  1627.     public function InvoiceEmptyNumberliberateAction($idRequest $request)
  1628.     {
  1629.         $em $this->getDoctrine()->getManager();
  1630.         $proposal $em->getRepository(Proposal::class)->findOneById($id);
  1631.         $proposal->setStatus('Confirmed');
  1632.         $em->persist($proposal);
  1633.         $invoice $em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
  1634.         $em->remove($invoice);
  1635.         $em->flush();
  1636.         $event 'The Invoice has been Liberate. Now';
  1637.         $successMessage $this->translator->trans($event);
  1638.         $this->addFlash('mensajeproposaldestination'$successMessage);
  1639.         $feesInvoice $em->getRepository(ProposalFeeInvoice::class)->findOneByProposalId($id);
  1640.         if (!empty($feesInvoice)){
  1641.             $em->remove($feesInvoice);
  1642.             $em->flush();
  1643.         }
  1644.         return $this->redirectToRoute('proposal_invoice_number',
  1645.             array(
  1646.                 'id' => $id
  1647.             )
  1648.         );
  1649.     }
  1650.     // Funcion para insertar historico de seguimiento
  1651.     // $textHistory = $this->translator->trans('');
  1652.     // $history = $this->TracingHistoryOperations($proposal->getId(), $text);
  1653.     private function TracingHistoryOperations($id$text)
  1654.     {
  1655.         $em $this->getDoctrine()->getManager();
  1656.         /* Obtengo usuario logueado */
  1657.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1658.         $user_id $user_logueado->getId();
  1659.         $history = new ProposalTracing();
  1660.         $history->setDateAt(new \DateTime('now'));
  1661.         $history->setText($text);
  1662.         $history->setAgentId($user_id);
  1663.         $history->setProposalId($id);
  1664.         $history->setViewed('no');
  1665.         $history->setCreatedId($user_id);
  1666.         $history->setUpdatedId($user_id);
  1667.         $em->persist($history);
  1668.         $em->flush();
  1669.         $success 'success';
  1670.         return $success;
  1671.     }
  1672. }