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

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