src/Controller/CarSaleController.php line 213

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\CarSale;
  4. use App\Entity\CarSaleBankCheck;
  5. use App\Entity\CarBuy;
  6. use App\Form\CarSaleType;
  7. use App\Repository\CarSaleRepository;
  8. use App\Repository\UserRepository;
  9. use Doctrine\Persistence\ManagerRegistry;
  10. use Dompdf\Dompdf;
  11. use Dompdf\Options;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpFoundation\JsonResponse;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  18. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  19. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  20. //use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
  21. use Doctrine\Common\Collections\ArrayCollection;
  22. use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
  23. use Knp\Snappy\Pdf;
  24. use App\Service\WhatsAppService;
  25. /**
  26.  * @Route("/car/sale")
  27.  */
  28. class CarSaleController extends AbstractController
  29. {
  30.     /**
  31.      * @Route("/indexJson", name="car_sale_index_json", methods={"GET", "POST"})
  32.      */
  33.     public function indexJson(Request $requestCarSaleRepository $entityRepository): Response
  34.     {
  35.         /*---- Filters [START] ----*/
  36.         $search   $request->get('searchPhrase');
  37.         $isDone   $request->get('isDone');
  38.         $curMonth $request->get('curMonth');
  39.         $dateFromRaw    $request->get('dateFrom');
  40.         $dateToRaw      $request->get('dateTo');
  41.         $dateFilter     filter_var($request->get('dateFilter'), FILTER_VALIDATE_BOOLEAN);
  42.         $priceFrom      $request->get('priceFrom');
  43.         $priceTo        $request->get('priceTo');
  44.         $priceFilter    filter_var($request->get('priceFilter'), FILTER_VALIDATE_BOOLEAN);
  45.         $agency      $request->get('agency');
  46.         $seller      $request->get('seller');
  47.         $dateFrom    $dateFromRaw $dateFromRaw ' 00:00:00' null;
  48.         $dateTo      $dateToRaw $dateToRaw ' 23:59:59' null;
  49.         /*---- Filters [END] ----*/
  50.         $totalR 0;
  51.         $curPage   $request->get('current');
  52.         $sizePage  $request->get('rowCount');
  53.         $startPage $curPage == : (($curPage 1) * $sizePage);
  54.         $data $entityRepository->createQueryBuilder('cs')
  55.             ->leftJoin('cs.carSale''c')
  56.             //->leftJoin('cs.carSalePayment', 'cp')
  57.             ->leftJoin('cs.carPayment''cscp')
  58.             ->leftJoin('cs.bankCheckId''csb')
  59.             ->leftJoin('cscp.car''cp')
  60.             ->leftJoin('cs.user''u')
  61.             ->leftJoin('cs.client''cl')
  62.             ->addSelect('c')
  63.             ->addSelect('cscp')
  64.             ->addSelect('csb')
  65.             ->addSelect('cp')
  66.             ->addSelect('u')
  67.             ->addSelect('cl')
  68.             ->where('cs.id > :id')
  69.             ->setParameter('id''0');
  70.         if ($search !== null && $search !== '') {
  71.             $data->andWhere(
  72.                 $data->expr()->orX(
  73.                     'c.name LIKE :search',
  74.                     'c.patent LIKE :search',
  75.                     'u.firstName LIKE :search',
  76.                     'u.lastName LIKE :search',
  77.                     'cs.price LIKE :search',
  78.                     'cs.origin LIKE :search'
  79.                 )
  80.             )->setParameter(':search'"%$search%");
  81.         }
  82.         $data $data->leftJoin(\App\Entity\Agency::class, 'ag''WITH''cs.id = ag.saleId')
  83.             ->addSelect('ag.enabledNotification, ag.status');
  84.         if ($isDone !== '' && $isDone !== null) {
  85.             $data $data->andWhere('cs.isDone = :isDone')
  86.                 ->setParameter(':isDone'$isDone);
  87.         }
  88.         if ($dateFilter && $dateFrom && $dateTo) {
  89.             $data->andWhere('cs.isDoneDate BETWEEN :dateFrom AND :dateTo')
  90.                 ->setParameter(':dateFrom'$dateFrom)
  91.                 ->setParameter(':dateTo'$dateTo);
  92.         }
  93.         if ($priceFilter && $priceFrom !== null && $priceTo !== null && $priceFrom !== '' && $priceTo !== '') {
  94.             $data->andWhere('cs.price BETWEEN :priceFrom AND :priceTo')
  95.                 ->setParameter(':priceFrom'$priceFrom)
  96.                 ->setParameter(':priceTo'$priceTo);
  97.         }
  98.         if (!empty($seller)) {
  99.             $data->andWhere('u.id = :userId')
  100.                 ->setParameter(':userId'$seller);
  101.         }
  102.         if ($curMonth === '1') {
  103.             $data->andWhere(
  104.                 $data->expr()->orX(
  105.                     $data->expr()->andX(
  106.                         'cs.isDone = 1',
  107.                         'MONTH(cs.isDoneDate) = MONTH(CURRENT_DATE())',
  108.                         'YEAR(cs.isDoneDate) = YEAR(CURRENT_DATE())'
  109.                     ),
  110.                     'cs.isDone = 0'
  111.                 )
  112.             );
  113.         }
  114.         $total $data->getQuery()
  115.             ->getArrayResult();
  116.         $data $data->orderBy('cs.isDone''DESC')
  117.             ->addOrderBy('cs.isDoneDate''ASC')
  118.             ->setFirstResult($startPage)
  119.             ->setMaxResults($sizePage)
  120.             ->getQuery()
  121.             ->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNStrue)
  122.             ->getArrayResult();
  123.             //->getScalarResult();
  124.         $nDelivered 0;
  125.         $nSignaled  0;
  126.         $nDeliveredPrice 0;
  127.         $nSignaledPrice  0;
  128.         /*---- Fix data for twig template [BEGIN] ----*/
  129.         foreach ($data as $key => $item) {
  130.             $aTmp $item[0];
  131.             $aTmp['enabledNotification'] = $item['enabledNotification'];
  132.             $aTmp['status'] = $item['status'];
  133.             if (!empty($aTmp['fechaFacturacion']) && $aTmp['fechaFacturacion'] instanceof \DateTimeInterface) {
  134.                 $aTmp['fechaFacturacion'] = $aTmp['fechaFacturacion']->format('Y-m-d');
  135.             }
  136.             $data[$key] = $aTmp;
  137.         }
  138.         /*---- Fix data for twig template [END] ----*/
  139.         //dump($data); exit();
  140.         foreach ($total as $item) {
  141.             /*if ($agency) {
  142.                 $isDone = $item[0]['isDone'];
  143.                 $price = $item[0]['price'];
  144.                 $signaledDate = $item[0]['signaledDate'];
  145.             } else {
  146.                 $isDone = $item['isDone'];
  147.                 $price = $item['price'];
  148.                 $signaledDate = $item['signaledDate'];
  149.             }*/
  150.             $isDone $item[0]['isDone'];
  151.             $price  $item[0]['price'];
  152.             $signaledDate $item[0]['signaledDate'];
  153.             if ($isDone) {
  154.                 $nDelivered ++;
  155.                 $nDeliveredPrice $nDeliveredPrice $price;
  156.             }
  157.             if (!$isDone && $signaledDate != null) {
  158.                 $nSignaled ++;
  159.                 $nSignaledPrice $nSignaledPrice $price;
  160.             }
  161.         }
  162.         $json_data = array(
  163.             'current' => intval($curPage),
  164.             'rowCount' => $sizePage,
  165.             'total' => count($total),
  166.             'rows' => $data,
  167.             'delivered' => $nDelivered,
  168.             'signaled' => $nSignaled,
  169.             'deliveredPrice' => $nDeliveredPrice,
  170.             'signaledPrice' => $nSignaledPrice,
  171.             'totalPrice' => $nDeliveredPrice $nSignaledPrice,
  172.         );
  173.         //dump($data); exit();
  174.         return $this->json($json_data);
  175.     }
  176.     /**
  177.      * @Route("/{id}/print", name="car_sale_print", methods={"GET"})
  178.      */
  179.     public function print(CarSale $carSalePdf $pdf): Response
  180.     {
  181.         /* Load the snappy pdf service * /
  182.         //$snappy = $this->get('knp_snappy.pdf');
  183.         $snappy = new Pdf();
  184.         $snappy->setOption('no-outline', true);
  185.         $snappy->setOption('page-size','LETTER');
  186.         $snappy->setOption('encoding', 'UTF-8');
  187.         /* Set title for pdf * /
  188.         $title = 'Detalle';
  189.         /* Render view, you can pass variables here to template view * /
  190.         $html = $this->renderView('car_sale/print.html.twig', [
  191.             'car_sale' => $carSale,
  192.         ]);
  193.         /* Set output file name and force pdf download in browser with PDFResponse * /
  194.         $filename = 'Detalle-ventas.pdf';
  195.         //exit($html);
  196.         return new PdfResponse(
  197.             $snappy->getOutputFromHtml($html),
  198.             $filename
  199.         ); //*/
  200.         /*return new Response(
  201.             $this->get('knp_snappy.pdf')->getOutputFromHtml($html),
  202.             200,
  203.             array(
  204.                 'Content-Type'          => 'application/pdf',
  205.                 'Content-Disposition'   => 'attachment; filename="tmp/file.pdf"'
  206.             )
  207.         );*/
  208.         /*---- [BEGIN] ----*/
  209.         $moneyAdvanceMultiple $carSale->getMoneyAdvanceMultiple();
  210.         $aTmp explode('|*|'$moneyAdvanceMultiple);
  211.         $moneyAdvanceMultiple "";
  212.         foreach ($aTmp as $item) {
  213.             $aTmp2 explode('|'$item);
  214.             if (count($aTmp2) > 1) {
  215.                 $amount = (float) str_replace(',''.'str_replace('.'''$aTmp2[3]));
  216.                 $moneyAdvanceMultiple .= $aTmp2[2] . number_format($amount0',''.') . ', ';
  217.             }
  218.         }
  219.         $moneyAdvanceMultiple rtrim($moneyAdvanceMultiple', ');
  220.         /*---- [END] ----*/
  221.         /*---- [BEGIN] ----*/
  222.         $cashMultiple $carSale->getCashMultiple();
  223.         $aTmp explode('|*|'$cashMultiple);
  224.         $cashMultiple "";
  225.         foreach ($aTmp as $item) {
  226.             $aTmp2 explode('|'$item);
  227.             if (count($aTmp2) > 1) {
  228.                 $amount = (float) str_replace(',''.'str_replace('.'''$aTmp2[3]));
  229.                 $cashMultiple .= $aTmp2[2] . number_format($amount0',''.') . ', ';
  230.             }
  231.         }
  232.         $cashMultiple rtrim($cashMultiple', ');
  233.         /*---- [END] ----*/
  234.         // Configure Dompdf according to your needs
  235.         $pdfOptions = new Options();
  236.         //$pdfOptions->set('defaultFont', 'Arial');
  237.         $pdfOptions->setIsHtml5ParserEnabled(true);
  238.         $pdfOptions->setIsRemoteEnabled(true);
  239.         // Instantiate Dompdf with our options
  240.         $dompdf = new Dompdf($pdfOptions);
  241.         //exit( $this->getParameter('kernel.project_dir') );
  242.         $dompdf->getOptions()->setChroot$this->getParameter('kernel.project_dir').'\public' );
  243.         //$html = $this->renderView('car_sale/print.html.twig', [
  244.         //$html = $this->renderView('pdf/car_sales_detail.html.twig', [
  245.         $html $this->renderView('pdf/car_sales_form.html.twig', [
  246.             'car_sale' => $carSale,
  247.             'money_advance_multiple' => $moneyAdvanceMultiple,
  248.             'cash_multiple' => $cashMultiple,
  249.             'server_root' => $_SERVER["DOCUMENT_ROOT"],
  250.         ]);
  251.         //echo $html; exit();
  252.         // Load HTML to Dompdf
  253.         $dompdf->loadHtml($html);
  254.         // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
  255.         $dompdf->setPaper('A4''portrait');
  256.         // Render the HTML as PDF
  257.         $dompdf->render();
  258.         ob_get_clean();
  259.         // Output the generated PDF to Browser (inline view)
  260.         $dompdf->stream("/pdfDetalle-ventas.pdf", [
  261.             "Attachment" => false,
  262.         ]);
  263.         /*
  264.         $filename = 'Detalle-ventas.pdf';
  265.         return new PdfResponse(
  266.             $pdf->getOutputFromHtml($html),
  267.             $filename
  268.         );*/
  269.     }
  270.     /**
  271.      * @Route("/{id}/detail", name="car_sale_detail", methods={"GET"})
  272.      */
  273.     public function detail(Request $requestCarSale $carSale): Response
  274.     {
  275.         if ($carSale->getProcedureDays() != null) {
  276.             $procedureDays $carSale->getProcedureDays();
  277.         }
  278.         //dump($carSale); exit();
  279.         //dump(json_decode($mandateSalePrice)); exit();
  280.         return $this->render('car_sale/detail.html.twig', [
  281.             'car_sale' => $carSale,
  282.             'currentMenu' => 'sales',
  283.         ]);
  284.     }
  285.     /**
  286.      * @Route("/{id}/receipt", name="car_sale_receipt", methods={"GET"})
  287.      */
  288.     public function carSaleReceipt(Request $requestCarSale $carSale$id): Response
  289.     {
  290.         $procedureLocation 'VILLA CARLOS PAZ';
  291.         $procedureDate date('Y/m/d');
  292.         $procedureTime date('H:i:s');
  293.         $procedureDays '7';
  294.         if ($carSale->getProcedureLocation() != null) {
  295.             $procedureLocation $carSale->getProcedureLocation();
  296.         }
  297.         if ($carSale->getProcedureDate() != null) {
  298.             $procedureDate $carSale->getProcedureDate();
  299.         }
  300.         /*if ($carSale->getProcedureTime() != null) {
  301.             $procedureTime = $carSale->getProcedureTime()->format('H:i:s');
  302.         }*/
  303.         if ($carSale->getProcedureDays() != null) {
  304.             $procedureDays $carSale->getProcedureDays();
  305.         }
  306.         /*---- [BEGIN] ----*/
  307.         $moneyAdvanceMultiple $carSale->getMoneyAdvanceMultiple();
  308.         $aTmp explode('|*|'$moneyAdvanceMultiple);
  309.         $moneyAdvanceMultiple "";
  310.         foreach ($aTmp as $item) {
  311.             $aTmp2 explode('|'$item);
  312.             if (count($aTmp2) > 1) {
  313.                 $amount = (float) str_replace(',''.'str_replace('.'''$aTmp2[3]));
  314.                 $moneyAdvanceMultiple .= $aTmp2[2] . number_format($amount0',''.') . ', ';
  315.             }
  316.         }
  317.         /*---- [END] ----*/
  318.         return $this->render('car_sale/receipt.html.twig', [
  319.             'car_sale' => $carSale,
  320.             'money_advance_multiple' => $moneyAdvanceMultiple,
  321.             'procedure_location' => $procedureLocation,
  322.             'procedure_date' => $procedureDate,
  323.             'procedure_time' => $procedureTime,
  324.             'procedure_days' => $procedureDays,
  325.             'isCreated' => $carSale->getReceiptGenerated(),
  326.             'form_number' => $carSale->getId(),
  327.             'currentMenu' => 'sales',
  328.         ]);
  329.     }
  330.     /**
  331.      * @Route("/excel", name="car_sale_excel", methods={"GET", "POST"})
  332.      */
  333.     public function excel(Request $requestCarSaleRepository $entityRepository): Response
  334.     {
  335.         /*---- Filters [START] ----*/
  336.         $search $request->get('searchPhrase');
  337.         $isDone $request->get('isDone');
  338.         $curMonth $request->get('curMonth');
  339.         $dateFromRaw $request->get('dateFrom');
  340.         $dateToRaw   $request->get('dateTo');
  341.         $dateFilter  filter_var($request->get('dateFilter'), FILTER_VALIDATE_BOOLEAN);
  342.         $priceFrom   $request->get('priceFrom');
  343.         $priceTo     $request->get('priceTo');
  344.         $priceFilter filter_var($request->get('priceFilter'), FILTER_VALIDATE_BOOLEAN);
  345.         $seller $request->get('seller');
  346.         /*---- Filters [END] ----*/
  347.         $totalR 0;
  348.         $curPage $request->get('current');
  349.         $sizePage $request->get('rowCount');
  350.         $data $entityRepository->createQueryBuilder('cs')
  351.             ->leftJoin('cs.carSale''c')
  352.             ->leftJoin('cs.carSalePayment''cp')
  353.             ->leftJoin('cs.user''u')
  354.             ->leftJoin('cs.client''cl')
  355.             ->addSelect('c')
  356.             ->addSelect('cp')
  357.             ->addSelect('u')
  358.             ->addSelect('cl')
  359.             ->where('cs.id > :id')
  360.             ->setParameter('id''0');
  361.         if ($search !== null && $search !== '') {
  362.             $data->andWhere(
  363.                 $data->expr()->orX(
  364.                     'c.name LIKE :search',
  365.                     'c.patent LIKE :search',
  366.                     'u.firstName LIKE :search',
  367.                     'u.lastName LIKE :search',
  368.                     'cs.price LIKE :search',
  369.                     'cs.origin LIKE :search'
  370.                 )
  371.             )->setParameter(':search'"%$search%");
  372.         }
  373.         $dateFrom $dateFromRaw $dateFromRaw ' 00:00:00' null;
  374.         $dateTo   $dateToRaw $dateToRaw ' 23:59:59' null;
  375.         if ($isDone !== '' && $isDone !== null) {
  376.             $data->andWhere('cs.isDone = :isDone')
  377.                 ->setParameter(':isDone'$isDone);
  378.         }
  379.         if ($dateFilter && $dateFrom && $dateTo) {
  380.             $data->andWhere('cs.isDoneDate BETWEEN :dateFrom AND :dateTo')
  381.                 ->setParameter(':dateFrom'$dateFrom)
  382.                 ->setParameter(':dateTo'$dateTo);
  383.         }
  384.         if ($priceFilter && $priceFrom !== null && $priceTo !== null && $priceFrom !== '' && $priceTo !== '') {
  385.             $data->andWhere('cs.price BETWEEN :priceFrom AND :priceTo')
  386.                 ->setParameter(':priceFrom'$priceFrom)
  387.                 ->setParameter(':priceTo'$priceTo);
  388.         }
  389.         if (!empty($seller)) {
  390.             $data->andWhere('u.id = :userId')
  391.                 ->setParameter(':userId'$seller);
  392.         }
  393.         if ($curMonth === '1') {
  394.             $data->andWhere(
  395.                 $data->expr()->orX(
  396.                     $data->expr()->andX(
  397.                         'cs.isDone = 1',
  398.                         'MONTH(cs.isDoneDate) = MONTH(CURRENT_DATE())',
  399.                         'YEAR(cs.isDoneDate) = YEAR(CURRENT_DATE())'
  400.                     ),
  401.                     'cs.isDone = 0'
  402.                 )
  403.             );
  404.         }
  405.         $data $data->getQuery()
  406.             ->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNStrue)
  407.             ->getArrayResult();
  408.         $spreadsheet = new Spreadsheet();
  409.         $sheet $spreadsheet->getActiveSheet();
  410.         $sheet->setTitle('Listado');
  411.         $sheet->getCell('A1')->setValue(strtoupper('Vendedor'));
  412.         $sheet->getCell('B1')->setValue(strtoupper('VehĂ­culo Vendido'));
  413.         $sheet->getCell('C1')->setValue(strtoupper('Año'));
  414.         $sheet->getCell('D1')->setValue(strtoupper('Patente'));
  415.         $sheet->getCell('E1')->setValue(strtoupper('VehĂ­culos Recibido'));
  416.         $sheet->getCell('F1')->setValue(strtoupper('Año'));
  417.         $sheet->getCell('G1')->setValue(strtoupper('Patente'));
  418.         $sheet->getCell('H1')->setValue(strtoupper('Precio Compra'));
  419.         $sheet->getCell('I1')->setValue(strtoupper('Adelanto'));
  420.         $sheet->getCell('J1')->setValue(strtoupper('Finalizada'));
  421.         $sheet->getCell('K1')->setValue(strtoupper('Creado'));
  422.         $sheet->getCell('L1')->setValue(strtoupper('Modificado'));
  423.         foreach(range('A','H') as $columnID) {
  424.             $sheet->getColumnDimension($columnID)->setAutoSize(true);
  425.         }
  426.         $sheet->getStyle('A1:L1')
  427.             ->getFill()
  428.             ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  429.             ->getStartColor()->setRGB('dedede');
  430.         setlocale(LC_MONETARY'it_IT');
  431.         $counter 2;
  432.         foreach ($data as $item) {
  433.             $carSalePayment $item['carSalePayment'] ?? null;
  434.             $carSalePaymentText '';
  435.             $carSalePaymentYear '';
  436.             $carSalePaymentPatent '';
  437.             if ($carSalePayment) {
  438.                 $carSalePaymentText   strtoupper($carSalePayment['name'].' ('.$carSalePayment['patent'].')');
  439.                 $carSalePaymentYear   strtoupper($carSalePayment['year']);
  440.                 $carSalePaymentPatent strtoupper($carSalePayment['patent']);
  441.             }
  442.             $sheet->getCell('A'.$counter)->setValue(strtoupper($item['user']['firstName'].' '.$item['user']['lastName']));
  443.             $sheet->getCell('B'.$counter)->setValue(strtoupper($item['carSale']['name'].' ('.$item['carSale']['patent'].')'));
  444.             $sheet->getCell('C'.$counter)->setValue(strtoupper($item['carSale']['year']));
  445.             $sheet->getCell('D'.$counter)->setValue(strtoupper($item['carSale']['patent']));
  446.             $sheet->getCell('E'.$counter)->setValue($carSalePaymentText);
  447.             $sheet->getCell('F'.$counter)->setValue($carSalePaymentYear);
  448.             $sheet->getCell('G'.$counter)->setValue($carSalePaymentPatent);
  449.             //$sheet->getCell('H'.$counter)->setValue(strtoupper($item['price']));
  450.             $sheet->getCell('H'.$counter)->setValue$item['currency'].number_format($item['price'], 0',''.') );
  451.             $sheet->getCell('I'.$counter)->setValue$item['moneyAdvanceCurrency'].number_format($item['moneyAdvance'], 0',''.') );
  452.             $sheet->getCell('J'.$counter)->setValue(strtoupper($item['isDone'] == 'No' 'SĂ­'));
  453.             if ($item['createdAt'] != null) {
  454.                 $sheet->getCell('K' $counter)->setValue($item['createdAt']->format('d-m-Y H:i:s'));
  455.             }
  456.             if ($item['updatedAt'] != null) {
  457.                 $sheet->getCell('L'.$counter)->setValue($item['updatedAt']->format('d-m-Y H:i:s'));
  458.             }
  459.             $counter ++;
  460.         }
  461.         // Increase row cursor after header write
  462.         //$sheet->fromArray($data,null, 'A2', true);
  463.         $writer = new Xlsx($spreadsheet);
  464.         // Create a Temporary file in the system
  465.         $fileName 'Ventas_'.date('d-m-Y').'.xlsx';
  466.         $temp_file tempnam(sys_get_temp_dir(), $fileName);
  467.         // Create the excel file in the tmp directory of the system
  468.         $writer->save($temp_file);
  469.         // Return the excel file as an attachment
  470.         return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE);
  471.     }
  472.     /**
  473.      * @Route("/sale/{id}/receiptsave/", name="car_sale_receipt_save", methods="POST")
  474.      */
  475.     public function receiptSave(Request $request$id)
  476.     {
  477.         $data json_decode($request->getContent(), true);
  478.         $aProcedure['location'] = $data['procedure-location'];
  479.         $aProcedure['date']     = new \DateTime($data['procedure-date'].'00:00:01');
  480.         $aProcedure['time']     = new \DateTime($data['procedure-date']. $data['procedure-time']);
  481.         $aProcedure['days'] = $data['procedure-days'];
  482.         /*---- [BEGIN] ----*/
  483.         $carsale $this->getDoctrine()->getRepository('App\Entity\CarSale')->findOneBy([ 'id' => $id ]);
  484.         $carsale->setProcedureLocation($aProcedure['location']);
  485.         $carsale->setProcedureDate($aProcedure['date']);
  486.         $carsale->setProcedureTime($aProcedure['time']);
  487.         $carsale->setProcedureDays($aProcedure['days']);
  488.         $carsale->setReceiptGenerated(1);
  489.         $this->getDoctrine()->getManager()->persist($carsale);
  490.         $this->getDoctrine()->getManager()->flush();
  491.         /*---- [END] ----*/
  492.         return $this->json('ok');
  493.     }
  494.     /**
  495.      * @Route("/sale/{id}/detailsave/", name="car_sale_detail_save", methods="POST")
  496.      */
  497.     public function detailSave(Request $request$id)
  498.     {
  499.         $data json_decode($request->getContent(), true);
  500.         $aProcedure['balance'] = $data['balance'];
  501.         /*---- [BEGIN] ----*/
  502.         $carsale $this->getDoctrine()->getRepository('App\Entity\CarSale')->findOneBy([ 'id' => $id ]);
  503.         $carsale->setBalance($aProcedure['balance']);
  504.         $this->getDoctrine()->getManager()->persist($carsale);
  505.         $this->getDoctrine()->getManager()->flush();
  506.         /*---- [END] ----*/
  507.         return $this->json('ok');
  508.     }
  509.     /**
  510.      * @Route("/sale/{id}/pdf/receipt", name="car_sale_receipt_pdf", methods="GET")
  511.      */
  512.     public function receiptPdf(Request $requestCarSale $carSale$id)
  513.     {
  514.         $procedureLocation $carSale->getProcedureLocation();
  515.         $procedureDate $carSale->getProcedureDate();
  516.         $procedureTime $carSale->getProcedureTime();;
  517.         $procedureDays $carSale->getProcedureDays();;
  518.         //$procedureTime = date('H:i:s');
  519.         $moneyAdvance '';
  520.         /*---- [BEGIN] ----*/
  521.         $moneyAdvanceMultiple $carSale->getMoneyAdvanceMultiple();
  522.         $aTmp explode('|*|'$moneyAdvanceMultiple);
  523.         $moneyAdvanceMultiple "";
  524.         foreach ($aTmp as $item) {
  525.             $aTmp2 explode('|'$item);
  526.             if (count($aTmp2) > 1) {
  527.                 $amount = (float) str_replace(',''.'str_replace('.'''$aTmp2[3]));
  528.                 $moneyAdvanceMultiple .= $aTmp2[2] . number_format($amount0',''.') . ', ';
  529.             }
  530.         }
  531.         /*---- [END] ----*/
  532.         // Configure Dompdf according to your needs
  533.         $pdfOptions = new Options();
  534.         //$pdfOptions->set('defaultFont', 'Arial');
  535.         $pdfOptions->setIsHtml5ParserEnabled(true);
  536.         $pdfOptions->setIsRemoteEnabled(true);
  537.         // Instantiate Dompdf with our options
  538.         $dompdf = new Dompdf($pdfOptions);
  539.         //exit( $this->getParameter('kernel.project_dir') );
  540.         $dompdf->getOptions()->setChroot$this->getParameter('kernel.project_dir').'\public' );
  541.         // Retrieve the HTML generated in our twig file
  542.         $html $this->renderView('pdf/car_sale_receipt.html.twig', [
  543.             'car_sale' => $carSale,
  544.             'money_advance_multiple' => $moneyAdvanceMultiple,
  545.             'procedure_location' => $procedureLocation,
  546.             'procedure_date' => $procedureDate,
  547.             'procedure_days' => $procedureDays,
  548.             'money_advance' => $moneyAdvance,
  549.             'form_number' => $carSale->getId(),
  550.             'server_root' => $_SERVER["DOCUMENT_ROOT"],
  551.         ]);
  552.         //dump($html); exit();
  553.         // Load HTML to Dompdf
  554.         $dompdf->loadHtml($html);
  555.         // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
  556.         $dompdf->setPaper('A4''portrait');
  557.         // Render the HTML as PDF
  558.         $dompdf->render();
  559.         ob_get_clean();
  560.         // Output the generated PDF to Browser (inline view)
  561.         $dompdf->stream("/Recibo-seña.pdf", [
  562.             "Attachment" => false,
  563.         ]);
  564.         //exit(0);
  565.     }
  566.     /**
  567.      * @Route("/index", name="car_sale_index", methods={"GET"})
  568.      */
  569.     public function index(ManagerRegistry $doctrineCarSaleRepository $carSaleRepository): Response
  570.     {
  571.         $sellers $this->getDoctrine()->getManager()->getRepository(\App\Entity\User::class)->createQueryBuilder('u')
  572.             ->indexBy('u''u.id')
  573.             ->orderBy('u.firstName''ASC')
  574.             ->getQuery()
  575.             ->getArrayResult();
  576.         $query "
  577.             SELECT id, name
  578.             FROM branches
  579.             ORDER BY name ASC
  580.         ";
  581.         $conn $doctrine->getConnection();
  582.         $result $conn->executeQuery($query);
  583.         $branches  $result->fetchAllKeyValue();
  584.         return $this->render('car_sale/index.html.twig', [
  585.             'car_sales' => $carSaleRepository->findAll(),
  586.             'branches' => $branches,
  587.             'currentMenu' => 'car_sale',
  588.             'sellers' => $sellers,
  589.         ]);
  590.     }
  591.     /**
  592.      * @Route("/addSeller", name="car_sale_add_seller", methods={"GET"})
  593.      */
  594.     public function addSeller(UserRepository $userRepository): Response
  595.     {
  596.         //$sellers = $userRepository->findBy(['roles' => 'ROLE_SALE']);
  597.         //dump($sellers); exit();
  598.         return $this->render('car_sale/add_seller.html.twig', [
  599.             'sellers' => $userRepository->findAll(),
  600.         ]);
  601.     }
  602.     /**
  603.      * @Route("/new", name="car_sale_new", methods={"GET","POST"})
  604.      */
  605.     public function new(Request $request): Response
  606.     {
  607.         $carSale = new CarSale();
  608.         $form $this->createForm(CarSaleType::class, $carSale);
  609.         $form->handleRequest($request);
  610.         if ($form->isSubmitted() && $form->isValid()) {
  611.             if ($this->getUser()->getRoles()[0] != 'ROLE_ADMIN') {
  612.                 $carSale->SetUser($this->getUser());
  613.             }
  614.             $carSale->SetProcedureDays(7);
  615.             $entityManager $this->getDoctrine()->getManager();
  616.             $entityManager->persist($carSale);
  617.             $entityManager->flush();
  618.             if ($carSale->getIsDone()) {
  619.                 /*---- Updated vehicle to sale [BEGIN] ----*/
  620.                 $car $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $carSale->getCarSale()->getId());
  621.                 $car->setStatus('sold');
  622.                 $this->getDoctrine()->getManager()->persist($car);
  623.                 $this->getDoctrine()->getManager()->flush();
  624.                 /*---- Updated vehicle to sale [END] ----*/
  625.                 /*---- Updated vehicle_payment [BEGIN] ----*/
  626.                 if ($carSale->getCarSalePayment()) {
  627.                     $car $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $carSale->getCarSalePayment()->getId());
  628.                     $car->setStatus('entered');
  629.                     $this->getDoctrine()->getManager()->persist($car);
  630.                     $this->getDoctrine()->getManager()->flush();
  631.                 }
  632.                 /*---- Updated vehicle_payment [END] ----*/
  633.             } else {
  634.                 /*---- Updated vehicle to sale [BEGIN] ----*/
  635.                 $car $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $carSale->getCarSale()->getId());
  636.                 $car->setStatus('signaled');
  637.                 $this->getDoctrine()->getManager()->persist($car);
  638.                 $this->getDoctrine()->getManager()->flush();
  639.                 /*---- Updated vehicle to sale [END] ----*/
  640.                 /*---- Updated vehicle_payment [BEGIN] ----*/
  641.                 if ($carSale->getCarSalePayment()) {
  642.                     $car $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $carSale->getCarSalePayment()->getId());
  643.                     $car->setStatus('to enter');
  644.                     $this->getDoctrine()->getManager()->persist($car);
  645.                     $this->getDoctrine()->getManager()->flush();
  646.                 }
  647.                 /*---- Updated vehicle_payment [END] ----*/
  648.             }
  649.             $this->syncCarPaymentPurchases($carSale);
  650.             return $this->redirectToRoute('car_sale_index', [], Response::HTTP_SEE_OTHER);
  651.         }
  652.         return $this->render('car_sale/new.html.twig', [
  653.             'car_sale' => $carSale,
  654.             'form' => $form->createView(),
  655.             'currentMenu' => 'car_sale',
  656.         ]);
  657.     }
  658.     /**
  659.      * @Route("/{id}", name="car_sale_show", methods={"GET"})
  660.      */
  661.     public function show(CarSale $carSale): Response
  662.     {
  663.         return $this->render('car_sale/show.html.twig', [
  664.             'car_sale' => $carSale,
  665.             'currentMenu' => 'car_sale',
  666.         ]);
  667.     }
  668.     /**
  669.      * @Route("/{id}/modal", name="car_sale_show_modal", methods={"GET"})
  670.      */
  671.     public function showModal(CarSale $carSale): Response
  672.     {
  673.         $sellers $this->getDoctrine()->getManager()->getRepository(\App\Entity\User::class)->createQueryBuilder('u')
  674.             ->indexBy('u''u.id')
  675.             ->orderBy('u.firstName''ASC')
  676.             ->getQuery()
  677.             ->getArrayResult();
  678.         return $this->render('car_sale/show_modal.html.twig', [
  679.             'car_sale' => $carSale,
  680.             'sellers' => $sellers,
  681.             'currentMenu' => 'car_sale',
  682.         ]);
  683.     }
  684.     /**
  685.      * @Route("/{id}/edit", name="car_sale_edit", methods={"GET","POST"})
  686.      */
  687.     public function edit(Request $requestCarSale $carSale): Response
  688.     {
  689.         if ($carSale->getIsDone() && $this->getUser()->getRoles()[0] != 'ROLE_ADMIN') {
  690.             return $this->render('messages/no_edit_record.html.twig', [
  691.                 'currentMenu' => 'car_sale',
  692.             ]);
  693.         }
  694.         $options['edit'] = true;
  695.         $options['carSaleId']    = $carSale->getCarSale() != null $carSale->getCarSale()->getId() : 0;
  696.         $options['carPaymentId'] = $carSale->getCarSalePayment() != null $carSale->getCarSalePayment()->getId() : 0;
  697.         // save the records that are in the database first to compare them with the new one the user sent
  698.         // make sure this line comes before the $form->handleRequest();
  699.         $orignalBankCheck = new ArrayCollection();
  700.         foreach ($carSale->getBankCheckId() as $item) {
  701.             $orignalBankCheck->add($item);
  702.         }
  703.         $orignalCarPayment = new ArrayCollection();
  704.         foreach ($carSale->getCarPayment() as $item) {
  705.             $orignalCarPayment->add($item);
  706.         }
  707.         //dump($carSale->getCarPayment()); //exit();
  708.         //dump($request);
  709.         //dump($request->getMethod()); exit();
  710.         if ($request->getMethod() == 'POST') {
  711.             //exit('---- 1 ----');
  712.         }
  713.         $form $this->createForm(CarSaleType::class, $carSale$options);
  714.         $form->handleRequest($request);
  715.         if ($request->getMethod() == 'POST') {
  716.             //exit('---- 2 ----');
  717.         }
  718.         /*if ($form->isSubmitted()) {
  719.             dump($request);
  720.             exit($request->get('carSalePayment') . '-------');
  721.         } //*/
  722.         //exit($request->get('carSalePayment') . '-------here'. $form->isSubmitted());
  723.         if ($form->isSubmitted() && $form->isValid()) {
  724.             if ($this->getUser()->getRoles()[0] != 'ROLE_ADMIN') {
  725.                 $carSale->SetUser($this->getUser());
  726.             }
  727.             //dump($carSale->getBankCheckId()); exit();
  728.             //dump($request); dump($carSale->getBankCheck()); exit();
  729.             /*---- get rid of the ones that the user got rid of in the interface (DOM) [BEGIN] ----*/
  730.             foreach ($orignalBankCheck as $item) {
  731.                 // check if the exp is in the $user->getExp()
  732.                 // dump($user->getExp()->contains($exp));
  733.                 if ($carSale->getBankCheckId()->contains($item) === false) {
  734.                     $this->getDoctrine()->getManager()->remove($item);
  735.                 }
  736.             }
  737.             foreach ($orignalCarPayment as $item) {
  738.                 if ($carSale->getCarPayment()->contains($item) === false) {
  739.                     $this->getDoctrine()->getManager()->remove($item);
  740.                 }
  741.             }
  742.             //dump($carSale->getCarPayment()); exit();
  743.             /*---- get rid of the ones that the user got rid of in the interface (DOM) [END] ----*/
  744.             //dump($carSale); exit();
  745.             $this->getDoctrine()->getManager()->flush();
  746.             //exit('---- 3 ----');
  747.             /*---- Updated vehicle to sale [BEGIN] ----*/
  748.             $car $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $carSale->getCarSale()->getId());
  749.             if ($carSale->getIsDone()) {
  750.                 $car->setStatus('sold');
  751.             } else {
  752.                 $car->setStatus('signaled');
  753.             }
  754.             $this->getDoctrine()->getManager()->persist($car);
  755.             $this->getDoctrine()->getManager()->flush();
  756.             /*---- Updated vehicle to sale [END] ----*/
  757.             /*---- Updated vehicle_payment [BEGIN] ----*/
  758.             if ($carSale->getCarSalePayment()) {
  759.                 $car $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $carSale->getCarSalePayment()->getId());
  760.                 if ($carSale->getIsDone()) {
  761.                     $car->setStatus('entered');
  762.                 } else {
  763.                     $car->setStatus('to enter');
  764.                 }
  765.                 $this->getDoctrine()->getManager()->persist($car);
  766.                 $this->getDoctrine()->getManager()->flush();
  767.             } else if ($options['carPaymentId'] > 0) {
  768.                 $car $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $options['carPaymentId']);
  769.                 $entityManager $this->getDoctrine()->getManager();
  770.                 $entityManager->remove($car);
  771.                 $entityManager->flush();
  772.             }
  773.             /*---- Updated vehicle_payment [END] ----*/
  774.             /*
  775.             if ($carSale->getIsDone()) {
  776.                 /*---- Updated vehicle to sale [BEGIN] ----* /
  777.                 $car = $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $carSale->getCarSale()->getId());
  778.                 $car->setStatus('sold');
  779.                 $this->getDoctrine()->getManager()->persist($car);
  780.                 $this->getDoctrine()->getManager()->flush();
  781.                 /*---- Updated vehicle to sale [END] ----*/
  782.                 /*---- Updated vehicle_payment [BEGIN] ----* /
  783.                 if ($carSale->getCarSalePayment()) {
  784.                     $car = $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $carSale->getCarSalePayment()->getId());
  785.                     $car->setStatus('entered');
  786.                     $this->getDoctrine()->getManager()->persist($car);
  787.                     $this->getDoctrine()->getManager()->flush();
  788.                 } else if ($options['carPaymentId'] > 0) {
  789.                     $car = $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $options['carPaymentId']);
  790.                     $entityManager = $this->getDoctrine()->getManager();
  791.                     $entityManager->remove($car);
  792.                     $entityManager->flush();
  793.                 }
  794.                 /*---- Updated vehicle_payment [END] ----* /
  795.             } else {
  796.                 /*---- Updated vehicle to sale [BEGIN] ----* /
  797.                 $car = $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $carSale->getCarSale()->getId());
  798.                 $car->setStatus('signaled');
  799.                 $this->getDoctrine()->getManager()->persist($car);
  800.                 $this->getDoctrine()->getManager()->flush();
  801.                 /*---- Updated vehicle to sale [END] ----*/
  802.                 /*---- Updated vehicle_payment [BEGIN] ----* /
  803.                 if ($carSale->getCarSalePayment()) {
  804.                     $car = $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $carSale->getCarSalePayment()->getId());
  805.                     $car->setStatus('to enter');
  806.                     $this->getDoctrine()->getManager()->persist($car);
  807.                     $this->getDoctrine()->getManager()->flush();
  808.                 } else if ($options['carPaymentId'] > 0) {
  809.                     $car = $this->getDoctrine()->getManager()->getReference(\App\Entity\Car::class, $options['carPaymentId']);
  810.                     $entityManager = $this->getDoctrine()->getManager();
  811.                     $entityManager->remove($car);
  812.                     $entityManager->flush();
  813.                 }
  814.                 /*---- Updated vehicle_payment [END] ----* /
  815.             }*/
  816.             $this->syncCarPaymentPurchases($carSale$orignalCarPayment);
  817.             return $this->redirectToRoute('car_sale_index', [], Response::HTTP_SEE_OTHER);
  818.         }
  819.         $sellers $this->getDoctrine()->getManager()->getRepository(\App\Entity\User::class)->createQueryBuilder('u')
  820.             ->indexBy('u''u.id')
  821.             ->orderBy('u.firstName''ASC')
  822.             ->getQuery()
  823.             ->getArrayResult();
  824.         return $this->render('car_sale/edit.html.twig', [
  825.             'car_sale' => $carSale,
  826.             'sellers' => $sellers,
  827.             'form' => $form->createView(),
  828.             //'form' => $form,
  829.             'currentMenu' => 'car_sale',
  830.         ]);
  831.     }
  832.     private function syncCarPaymentPurchases(CarSale $carSale, ?ArrayCollection $originalCarPayments null): void
  833.     {
  834.         $entityManager   $this->getDoctrine()->getManager();
  835.         $carBuyRepo      $entityManager->getRepository(CarBuy::class);
  836.         $carSaleVehicle  $carSale->getCarSale();
  837.         $isDone          $carSale->getIsDone();
  838.         $defaultCurrency $carSale->getCurrency() ?? '$';
  839.         $defaultOrigin   $carSale->getOrigin() ?? 'Sales Room';
  840.         foreach ($carSale->getCarPayment() as $payment) {
  841.             $paymentCar $payment->getCar();
  842.             if ($paymentCar === null) {
  843.                 continue;
  844.             }
  845.             $carBuy $carBuyRepo->findOneBy([
  846.                 'car' => $paymentCar,
  847.                 'carSwap' => $carSaleVehicle,
  848.             ]);
  849.             if ($carBuy === null) {
  850.                 $carBuy = new CarBuy();
  851.                 $carBuy->setCar($paymentCar);
  852.                 $carBuy->setCarSwap($carSaleVehicle);
  853.                 $entityManager->persist($carBuy);
  854.             }
  855.             $pricePurchase    $paymentCar->getPricePurchase() ?? 0;
  856.             $currencyPurchase $paymentCar->getPriceCurrencyPurchase() ?? $defaultCurrency;
  857.             $carBuy->setPrice($pricePurchase);
  858.             $carBuy->setCurrency($currencyPurchase);
  859.             $carBuy->setOrigin($defaultOrigin);
  860.             $carBuy->setDescription(sprintf('VehĂ­culo tomado en parte de pago de la venta #%d'$carSale->getId()));
  861.             $carBuy->setUser($carSale->getUser());
  862.             $carBuy->setClient($carSale->getClient());
  863.             $carBuy->setIsDone($isDone);
  864.             $carBuy->setIsDoneDate($isDone $carSale->getIsDoneDate() : null);
  865.             $paymentCar->setPricePurchase($pricePurchase);
  866.             $paymentCar->setPriceCurrencyPurchase($currencyPurchase);
  867.             $paymentCar->setStatus($isDone 'entered' 'to enter');
  868.             $entityManager->persist($paymentCar);
  869.         }
  870.         if ($originalCarPayments !== null) {
  871.             foreach ($originalCarPayments as $payment) {
  872.                 if ($carSale->getCarPayment()->contains($payment)) {
  873.                     continue;
  874.                 }
  875.                 $paymentCar $payment->getCar();
  876.                 if ($paymentCar === null) {
  877.                     continue;
  878.                 }
  879.                 $carBuy $carBuyRepo->findOneBy([
  880.                     'car' => $paymentCar,
  881.                     'carSwap' => $carSaleVehicle,
  882.                 ]);
  883.                 if ($carBuy !== null) {
  884.                     $entityManager->remove($carBuy);
  885.                 }
  886.             }
  887.         }
  888.         $entityManager->flush();
  889.     }
  890.     /**
  891.      * @Route("/{id}", name="car_sale_delete", methods={"POST"})
  892.      */
  893.     public function delete(Request $requestCarSale $carSale): Response
  894.     {
  895.         if ($this->isCsrfTokenValid('delete'.$carSale->getId(), $request->request->get('_token'))) {
  896.             $entityManager $this->getDoctrine()->getManager();
  897.             $entityManager->remove($carSale);
  898.             $entityManager->flush();
  899.         }
  900.         return $this->redirectToRoute('car_sale_index', [], Response::HTTP_SEE_OTHER);
  901.     }
  902.     /**
  903.      * @Route("/{id}/delete", name="car_sale_delete_ra", methods={"GET"})
  904.      */
  905.     public function deleteRa(Request $request): Response
  906.     {
  907.         $entityManager $this->getDoctrine()->getManager();
  908.         $carSale $entityManager->getReference(\App\Entity\CarSale::class, $request->get('id'));
  909.         $entityManager->remove($carSale);
  910.         $entityManager->flush();
  911.         return $this->redirectToRoute('car_sale_index', [], Response::HTTP_SEE_OTHER);
  912.     }
  913.     #[Route('/ventas/{id}/send-thank-you'name'ventas_send_thank_you'methods: ['POST','GET'])]
  914.     public function sendThankYou(CarSale $ventaWhatsAppService $whatsappService): JsonResponse
  915.     {
  916.         $cliente $venta->getClient();
  917.         $ok $whatsappService->sendThankYouMessage($cliente);
  918.         if ($ok) {
  919.             return new JsonResponse([
  920.                 'success' => true,
  921.                 'message' => 'Mensaje enviado correctamente'
  922.             ], 200);
  923.         }
  924.         else{
  925.             return new JsonResponse([
  926.                 'success' => false,
  927.                 'message' => 'No se pudo enviar el mensaje'
  928.             ], 500);
  929.         }
  930.        
  931.     }  
  932. }