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

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