src/Controller/BillingController.php line 156

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Address;
  4. use App\Entity\Billing;
  5. use App\Entity\BillingItem;
  6. use App\Entity\Client;
  7. use App\Entity\Company;
  8. use App\Entity\Intervenant;
  9. use App\Entity\Parameter;
  10. use App\Entity\Product;
  11. use App\Entity\RDV;
  12. use App\Entity\RDVBilling;
  13. use App\Entity\RDVProduct;
  14. use App\Entity\Reglement;
  15. use App\Entity\Salon;
  16. use App\Entity\Session;
  17. use App\Entity\Site;
  18. use App\Entity\User;
  19. use App\Form\Billing\ContencieuxType;
  20. use App\Form\Billing\EasyCollect;
  21. use App\Form\Billing\LotType;
  22. use App\Form\Billing\RelanceType;
  23. use App\Form\Billing\SendType;
  24. use App\Form\Billing\ValidateType;
  25. use App\Form\BillingType;
  26. use App\Form\CompanyType;
  27. use App\Form\Billing\GenerateType;
  28. use App\Form\RDVType;
  29. use App\Form\ReplanningType;
  30. use App\Manager\BillingItemManager;
  31. use App\Manager\BillingManager;
  32. use App\Manager\RDVBillingManager;
  33. use App\Manager\ReglementManager;
  34. use App\Repository\BillingItemsRepository;
  35. use App\Repository\BillingRepository;
  36. use App\Repository\ClientRepository;
  37. use App\Repository\CompanyRepository;
  38. use App\Repository\ProductRepository;
  39. use App\Repository\RDVProductRepository;
  40. use App\Repository\RDVRepository;
  41. use App\Repository\SiteRepository;
  42. use App\Service\FileUploader;
  43. use App\Service\MailService;
  44. use App\Service\PaytweakService;
  45. use App\Service\SepaService;
  46. use App\Traits\MailServiceTrait;
  47. use App\Traits\ManagerTrait;
  48. use App\Traits\PdfServiceTrait;
  49. use Doctrine\Common\Collections\ArrayCollection;
  50. use Doctrine\ORM\EntityManagerInterface;
  51. use Doctrine\Persistence\ManagerRegistry;
  52. use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
  53. use Knp\Snappy\Pdf;
  54. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  55. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  56. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  57. use Symfony\Component\HttpFoundation\JsonResponse;
  58. use Symfony\Component\HttpFoundation\RedirectResponse;
  59. use Symfony\Component\HttpFoundation\Request;
  60. use Symfony\Component\HttpFoundation\Response;
  61. use Symfony\Component\HttpFoundation\StreamedResponse;
  62. use Symfony\Component\Routing\Annotation\Route;
  63. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  64. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  65. use Symfony\Component\Serializer\Serializer;
  66. use Symfony\Component\Serializer\SerializerInterface;
  67. use Digitick\Sepa\TransferFile\Factory\TransferFileFacadeFactory;
  68. use Digitick\Sepa\PaymentInformation;
  69. /**
  70.  * @Route("/facturation")
  71.  */
  72. class BillingController extends AbstractController
  73. {
  74.     private $billingItemManager;
  75.     /** @var BillingManager $billingManager */
  76.     private $billingManager;
  77.     use ManagerTrait;
  78.     use MailServiceTrait;
  79.     use PdfServiceTrait;
  80.     /**
  81.      * BillingController constructor.
  82.      * @param BillingItemManager $billingItemManager
  83.      */
  84.     public function __construct(BillingManager $billingManagerBillingItemManager $billingItemManager)
  85.     {
  86.         $this->billingItemManager $billingItemManager;
  87.         $this->billingManager $billingManager;
  88.     }
  89.     /**
  90.      * @Route("/testSepa", methods={"GET","POST"})
  91.      */
  92.     public function testSepa(
  93.         Request $request,
  94.         BillingRepository $billingRepository,
  95.         SepaService $sepaService,
  96.         CompanyRepository $companyRepository
  97.     ): Response
  98.     {
  99.         $entityManager $this->getDoctrine()->getManager();
  100.         $billings $billingRepository->findBy([],null,20);
  101.         $company $companyRepository->find(1);
  102.         $directDebit $sepaService->generate($company);
  103.         foreach($billings as $billing){
  104.             $directDebit $sepaService->addTransaction($directDebit$billing);
  105.         }
  106.         //dd(count($billings));
  107.         return new Response($directDebit->asXML(), Response::HTTP_OK, [
  108.             'Content-Type' => 'application/octect-stream',
  109.             'Content-Transfer-Encoding' => 'Binary',
  110.             'Content-disposition' => 'attachment;  filename="sepa.xml"'
  111.         ]);
  112.     }
  113.     /**
  114.      * @Route("/billing/rendrecontencieux", name="app_billing_rendrecontencieux", methods={"POST"})
  115.      */
  116.     public function rendreContencieux(Request $requestBillingRepository $billingRepositoryEntityManagerInterface  $entityManager): JsonResponse
  117.     {
  118.         // Get the 'ids' from the AJAX request
  119.         $selectedIds $request->request->get('ids', []);
  120.         if (!empty($selectedIds)) {
  121.              foreach ($selectedIds as $id) {
  122.                  $billing $billingRepository->find($id);
  123.                  if ($billing) {
  124.                      $billing->setStatus('contentieux');
  125.                      $entityManager->persist($billing);
  126.                  }
  127.              }
  128.              $entityManager->flush();
  129.             // Return a JSON response indicating success
  130.             return new JsonResponse(['message' => 'Factures marquées comme contentieuses avec succès.'], 200);
  131.         } else {
  132.             // Return a JSON response indicating an error
  133.             return new JsonResponse(['message' => 'Aucune facture sélectionnée.'], 400);
  134.         }
  135.     }
  136.     /**
  137.      * @Route("/liste", methods={"GET","POST"})
  138.      * @Template()
  139.      * @return array|RedirectResponse
  140.      */
  141.     public function index(
  142.         Request $request,
  143.         CompanyRepository $companyRepository,
  144.         SiteRepository $siteRepository,
  145.         BillingRepository $billingRepository,
  146.         MailService $mailService,
  147.         PaytweakService $paytweakService,
  148.         SepaService $sepaService,
  149.         Pdf $knpSnappyPdf,
  150.         ReglementManager $reglementManager,
  151.         ManagerRegistry  $em,
  152.         ParameterBagInterface $parameterBag
  153.     )
  154.     {
  155.         $sites $siteRepository->findAll();
  156.         $compagnies $companyRepository->findAll();
  157.         $form $this->createForm(GenerateType::class);
  158.         $validateForm $this->createForm(ValidateType::class);
  159.         $sendForm $this->createForm(SendType::class);
  160.         $relanceForm $this->createForm(RelanceType::class);
  161.         $lotForm $this->createForm(LotType::class);
  162.         $easyCollect $this->createForm(EasyCollect::class);
  163.         $billingsSEPA = [];
  164.         $company null;
  165.         $filterForm $this->createForm(\App\Form\Billing\FilterType::class, null, ['company' => $companyRepository->find(2)]);
  166.         $form->handleRequest($request);
  167.         $filterForm->handleRequest($request);
  168.         $sendForm->handleRequest($request);
  169.         $validateForm->handleRequest($request);
  170.         $relanceForm->handleRequest($request);
  171.         $easyCollect->handleRequest($request);
  172.         $lotForm->handleRequest($request);
  173.         // FILTER FORM
  174.         if ($filterForm->isSubmitted() && $filterForm->isValid()) {
  175.             $site $filterForm['site']->getData();
  176.             $statusSite $filterForm['statusSite']->getData();
  177.             $company $filterForm['company']->getData();
  178.             $numFacture $filterForm['numFacture']->getData();
  179.             $client $filterForm['client']->getData();
  180.             $dateDebut $filterForm['dateDebut']->getData();
  181.             $dateFin $filterForm['dateFin']->getData();
  182.             $status $filterForm['status']->getData();
  183.             $billings $billingRepository->filter($site$client$dateDebut,$dateFin$status$company$numFacturefalsenull$statusSite);
  184.             $billingsSEPA $billingRepository->findBy(['company' => $company]);
  185.             $billingsEncaissement $billingRepository->searchForEncaissement($site$client$dateDebut,$dateFin$company$numFacture);
  186.         }
  187.         else {
  188.             $billings $billingRepository->findBy([],['code' => 'DESC'],200);
  189.             $billingsEncaissement $billingRepository->searchForEncaissement();
  190.         }
  191.         // VALIDATE
  192.         if ($validateForm->isSubmitted() ) {
  193.             $site $validateForm['site']->getData();
  194.             $company $validateForm['company']->getData();
  195.             $start $validateForm['start']->getData();
  196.             $end $validateForm['end']->getData();
  197.             $dateBillingStr $validateForm['dateBilling']->getData();
  198.             $dateBilling null;
  199.             if($dateBillingStr){
  200.                 $dateBilling date_create_from_format('Y-m-d'$dateBillingStr);
  201.             }
  202.             $billings $billingRepository->searchForValidate($site$company$start$end);
  203.             /** @var Billing $billing */
  204.             $i 0;
  205.             $lastCode null;
  206.             foreach($billings as $billing) {
  207.                 if($i === 0){
  208.                     $code $this->billingManager->getCodeBilling($company$billing$dateBilling);
  209.                 }
  210.                 else {
  211.                     $code $this->billingManager->getCodeBillingByLastCode($company$billing$lastCode$dateBilling);
  212.                 }
  213.                 $billing->setCode($code);
  214.                 $billing->setStatus(Billing::STATUS_VALIDE);
  215.                 if($billing->getHt() <= || $billing->getSolde() < 0){
  216.                     $billing->setStatus(Billing::STATUS_REGLEE);
  217.                 }
  218.                 $em->getManager()->persist($billing);
  219.                 $lastCode $code;
  220.                 $i++;
  221.             }
  222.             $em->getManager()->flush();
  223.             return $this->redirectToRoute('app_billing_index');
  224.         }
  225.         // HANDLE encaissement
  226.         if($request->isMethod(Request::METHOD_POST) && $request->request->get('payment-method')) {
  227.             $paymentMethod $request->request->get('payment-method');
  228.             $reference $request->request->get('reference');
  229.             $companyKey $request->request->get('company');
  230.             $date $request->request->get('date');
  231.             $encaissementDate $request->request->get('date');
  232.             $client $request->request->get('client');
  233.             $encaissements $request->request->get('encaissement');
  234.             if($encaissementDate) {
  235.                 $encaissementDate date_create_from_format('Y-m-d'$encaissementDate);
  236.             }
  237.             else {
  238.                 $encaissementDate = new \DateTime();
  239.             }
  240.             if(!$date) {
  241.                 $date = new \DateTime('now');
  242.             } else {
  243.                 $dateObj date_create_from_format('d-m-Y'$date);
  244.                 $date = ($dateObj !== false) ? $dateObj : new \DateTime('now');
  245.             }
  246.             $company null;
  247.             if($companyKey) {
  248.                 $company $companyRepository->find($companyKey);
  249.             }
  250.             // SEPA
  251.             if(( $paymentMethod === Reglement::MODE_SEPA  && $company)) {
  252.                 $directDebit $sepaService->generate($company);
  253.                 if(!$encaissements){
  254.                     $this->addFlash('error','Pas d\'encaissements selectionés');
  255.                 }
  256.                 if($encaissements){
  257.                     // generare onereglement per billing
  258.                     foreach($encaissements as $key => $solde) {
  259.                         if(!$solde || $solde == 0) {
  260.                             continue;
  261.                         }
  262.                         $billing $billingRepository->findOneBy(['id'=> $key]);
  263.                         $clientBilling $billing->getClient();
  264.                         $oldSolde $billing->getSolde();
  265.                         $newSolde $oldSolde $solde;
  266.                         $billing->setSolde(number_format($newSolde2));
  267.                         if($newSolde <= 0){
  268.                             $billing->setStatus(Billing::STATUS_REGLEE);
  269.                         }
  270.                         $reglementManager->create($date$billing$billing->getTtc(),$reference$clientBilling$paymentMethod);
  271.                         $em->getManager()->persist($billing);
  272.                         $directDebit $sepaService->addTransaction($directDebit$billing);
  273.                     }
  274.                     $em->getManager()->flush();
  275.                     try {
  276.                         $xml $directDebit->asXML();
  277.                         return new Response($xmlResponse::HTTP_OK, [
  278.                             'Content-Type' => 'application/octect-stream',
  279.                             'Content-Transfer-Encoding' => 'Binary',
  280.                             'Content-disposition' => 'attachment;  filename="sepa.xml"'
  281.                         ]);
  282.                     } catch (\Exception $exception){
  283.                         $this->addFlash('error''Manquement des informations bancaires, ICS, IBAN...');
  284.                     }
  285.                 }
  286.             }
  287.             // OTHERS PAYMENT METHODS
  288.             if($company) {
  289.                 $billings = [];
  290.                 $sumSolde 0;
  291.                 // generare one reglement per billing
  292.                 foreach($encaissements as $key => $encaissement) {
  293.                     //if it's checked
  294.                     if(!isset($encaissement['value'])){
  295.                         continue;
  296.                     }
  297.                     $solde $encaissement['solde'];
  298.                     if(!$solde || $solde == 0) {
  299.                         continue;
  300.                     }
  301.                     $billing $billingRepository->findOneBy(['id'=> $key]);
  302.                     $oldSolde $billing->getSolde();
  303.                     $newSolde $oldSolde $solde;
  304.                     $billing->setSolde($newSolde);
  305.                     if($newSolde <= 0){
  306.                         $billing->setStatus(Billing::STATUS_REGLEE);
  307.                     }
  308.                     $clientBilling $billing->getClient();
  309.                     $em->getManager()->persist($billing);
  310.                     $isDuplicate false;
  311.                     foreach ($billings as $existingBilling) {
  312.                         if ($existingBilling->getId() === $billing->getId()) {
  313.                             $isDuplicate true;
  314.                             break;
  315.                         }
  316.                     }
  317.                     if (!$isDuplicate) {
  318.                         $billings[] = $billing;
  319.                     }
  320.                     $sumSolde+= $solde;
  321.                 }
  322.                 $reglementManager->createByBillings($encaissementDate$billings$sumSolde$reference$billings[0]->getClient(), $paymentMethod $company);
  323.             }
  324.             $em->getManager()->flush();
  325.         }
  326.         // facture
  327.         if ($form->isSubmitted() && $form->isValid()) {
  328.             $this->generateBilling($form->getData());
  329.             return $this->redirectToRoute('app_billing_index');
  330.         }
  331.         /***********
  332.          * SEND FORM
  333.          ************/
  334.         if($sendForm->isSubmitted() && $sendForm->isValid()){
  335.             $pdfBillings = [];
  336.             $modeEnvoi $sendForm->getData()['modeEnvoi'];
  337.             $start $sendForm->getData()['start'];
  338.             $end $sendForm->getData()['end'];
  339.             $company $sendForm->getData()['company'];
  340.             $site $sendForm->getData()['site'];
  341. //            $start = \DateTime::createFromFormat('Y-m-d',$start)->format('Y-m-d');
  342. //            $end = \DateTime::createFromFormat('d-m-Y', $end)->format('Y-m-d');
  343.             $billings $billingRepository->searchForSend($site$company$start$end);
  344.             //dd($billings);
  345.             /** @var Billing $billing */
  346.             foreach($billings as $billing) {
  347.                 /** @var Client $client */
  348.                 $client $billing->getClient();
  349.                 $payMode $client->getBillingInfos()->getPayMode();
  350.                 $sendMode $client->getBillingInfos()->getSendMode();
  351.                 // mail + SEPA
  352.                 if($modeEnvoi === 'mail' && $sendMode === Client\BillingInfos::SEND_MODE_EMAIL &&
  353.                     ($payMode == Client\BillingInfos::PAY_MODE_SEPA) ) {
  354.                     if($billing->getClient()->getBillingInfos()->getEmail()){
  355.                         $html $this->renderView('billing/pdf.html.twig',[
  356.                             'billings' => [$billing],
  357.                             'company'  => $billing->getCompany()
  358.                         ]);
  359.                         $knpSnappyPdf->setOption('enable-local-file-access'true);
  360.                         $pdf$knpSnappyPdf->getOutputFromHtml($html, ['encoding' => 'utf-8']);
  361.                             if($billing->getClient()->getBillingInfos()->getEmail()){
  362.                                 try {
  363.                                     $mailService->sent(new \Symfony\Component\Mime\Address'comptabilite@silverbeaute.com''Comptabilité Silver Beauté'), $billing->getClient()->getBillingInfos()->getEmail(), $company,$pdf$billing );
  364.                                     $billing->setStatus(Billing::STATUS_SENT);
  365.                                     $billing->setSendingDate(new \DateTime());
  366.                                     $em->getManager()->persist($billing);
  367.                                 }
  368.                                 catch (\Exception $exception){
  369.                                 }
  370.                             }
  371.                     }
  372.                 }
  373.                 elseif($modeEnvoi === 'courrier' && $sendMode === Client\BillingInfos::SEND_MODE_COURRIER ){
  374.                     $pdfBillings[] = $billing;
  375.                     $billing->setStatus(Billing::STATUS_SENT);
  376.                     $billing->setSendingDate(new \DateTime());
  377.                     $em->getManager()->persist($billing);
  378.                 }
  379.                 elseif (
  380.                     $modeEnvoi === 'mail'  &&
  381.                     $billing->getSolde() > && (
  382.                         (
  383.                             $sendMode === Client\BillingInfos::SEND_MODE_EMAIL &&
  384.                             ($payMode == Client\BillingInfos::PAY_MODE_CB
  385.                                 || $payMode == Client\BillingInfos::PAY_MODE_CHEQUES
  386.                                 || $payMode == Client\BillingInfos::PAY_MODE_VIREMENT)
  387.                         )
  388.                         ||
  389.                         ($sendMode === Client\BillingInfos::SEND_MODE_COURRIER && $payMode == Client\BillingInfos::PAY_MODE_CB  )
  390.                         || ( $sendMode === Client\BillingInfos::SEND_MODE_EMAIL && $payMode === null)
  391.                     )
  392.                 )
  393.                 {
  394.                     $invoice $paytweakService->createInvoiceFromClient($client$billing);
  395.                     $call  $paytweakService->createBilling($invoice$company);
  396.                     if($call['code'] == 'OK') {
  397.                         $billing->setStatus(Billing::STATUS_SENT);
  398.                         if(isset($call['link_id'] )){
  399.                             $billing->setLinkPaytweak($call['link_id']);
  400.                         }
  401.                         $billing->setSendingDate(new \DateTime());
  402.                         $em->getManager()->persist($billing);
  403.                     }
  404.                     else {
  405.                         $mailService->sentErrorPaytweak($billing$call['code'], $call['message']);
  406.                     }
  407.                 }
  408.             }
  409.             $em->getManager()->flush();
  410.             if(count($pdfBillings) > 0){
  411.                 $html $this->renderView('billing/pdf.html.twig',[
  412.                     'billings' => $pdfBillings,
  413.                     'company'  => $billing->getCompany()
  414.                 ]);
  415.                 $knpSnappyPdf->setOption('enable-local-file-access'true);
  416.                 return new PdfResponse(
  417.                     $knpSnappyPdf->getOutputFromHtml($html, ['encoding' => 'utf-8']),
  418.                     'file.pdf'
  419.                 );
  420.             }
  421.             $em->getManager()->flush();
  422.         }
  423.         /***********
  424.          * SEND FORM
  425.          ************/
  426.         if($easyCollect->isSubmitted() && $easyCollect->isValid()){
  427.             $modeEnvoi $easyCollect->getData()['modeEnvoi'];
  428.             $start $easyCollect->getData()['start'];
  429.             $end $easyCollect->getData()['end'];
  430.             $company $easyCollect->getData()['company'];
  431.             $site $easyCollect->getData()['site'];
  432. //            $start = \DateTime::createFromFormat('Y-m-d',$start)->format('Y-m-d');
  433. //            $end = \DateTime::createFromFormat('d-m-Y', $end)->format('Y-m-d');
  434.             $billings $billingRepository->searchForSend($site$company$start$end);
  435.             //dd($billings);
  436.             /** @var Billing $billing */
  437.             foreach($billings as $billing) {
  438.                 /** @var Client $client */
  439.                 $client $billing->getClient();
  440.                 $payMode $client->getBillingInfos()->getPayMode();
  441.                 $sendMode $client->getBillingInfos()->getSendMode();
  442.                 $hasSigned = !!$client->isHasSignedEasyCollect();
  443.                 if (
  444.                     $modeEnvoi === 'mail'  &&
  445.                     $billing->getSolde() > && $sendMode === Client\BillingInfos::SEND_MODE_EMAIL
  446.                     && !$hasSigned
  447.                 )
  448.                 {
  449.                     $amount $billing->getSolde();
  450.                     // PDF
  451.                     $invoice $paytweakService->createInvoiceFromClient($client$billing);
  452.                     //$call  = $paytweakService->createBilling($invoice, $company);
  453.                     //if($call['code'] == 'OK') {
  454.                     if(!$client->isHasSignedEasyCollect()) {
  455.                         $paytweakService->createLinkScenario($billing->getCompany(),null'BhaXARK'$amount,
  456.                             $client->getBillingInfos() ? $client->getBillingInfos()->getEmail() : $client->getEmail(),
  457.                             $client->getFirstname(),
  458.                             $client->getLastname(),
  459.                             $client->getGender(),
  460.                             $billing->getCode(),
  461.                             null,
  462.                             'B7EV3PN'
  463.                         );
  464.                         $billing->setStatus(Billing::STATUS_SENT);
  465.                         $billing->setSendingDate(new \DateTime());
  466.                         $em->getManager()->persist($billing);
  467.                     }
  468.                     else {
  469.                         // email
  470.                         // TODO: rappel endpoint email
  471.                         $paytweakService->createLinkScenario($billing->getCompany(),null'BhaXARK'$amount,
  472.                             $client->getBillingInfos() ? $client->getBillingInfos()->getEmail() : $client->getEmail(),
  473.                             $client->getFirstname(),
  474.                             $client->getLastname(),
  475.                             $client->getGender(),
  476.                             $billing->getCode(),
  477.                             $client->getBillingInfos() ? $client->getBillingInfos()->getRum() : null,
  478.                             'HURNEAN'
  479.                         );
  480.                         $billing->setStatus(Billing::STATUS_SENT);
  481.                         $billing->setSendingDate(new \DateTime());
  482.                         $em->getManager()->persist($billing);
  483.                     }
  484.                 }
  485.             }
  486.             $em->getManager()->flush();
  487.         }
  488.         /***********
  489.          * RELANCE FORM
  490.          ************/
  491.         if($relanceForm->isSubmitted() && $relanceForm->isValid()){
  492.             $start $relanceForm->getData()['start'];
  493.             $end $relanceForm->getData()['end'];
  494.             $company $relanceForm->getData()['company'];
  495.             $site $relanceForm->getData()['site'];
  496.             $modeEnvoi $relanceForm->getData()['modeEnvoi'];
  497.             $pdfBillings = [];
  498.             $billings $billingRepository->searchForRelance($site$company$start$end);
  499.             foreach($billings as $billing) {
  500.                 /** @var Client $client */
  501.                 $client $billing->getClient();
  502.                 $payMode $client->getBillingInfos()->getPayMode();
  503.                 $sendMode $client->getBillingInfos()->getSendMode();
  504.                 if (
  505.                     $modeEnvoi === 'mail'  &&
  506.                     $billing->getSolde() > && (
  507.                         (
  508.                             $sendMode === Client\BillingInfos::SEND_MODE_EMAIL &&
  509.                             ($payMode == Client\BillingInfos::PAY_MODE_CB
  510.                                 || $payMode == Client\BillingInfos::PAY_MODE_CHEQUES
  511.                                 || $payMode == Client\BillingInfos::PAY_MODE_VIREMENT)
  512.                         )
  513.                         ||
  514.                         ($sendMode === Client\BillingInfos::SEND_MODE_COURRIER &&
  515.                             ($payMode == Client\BillingInfos::PAY_MODE_CB
  516.                                 || $payMode == Client\BillingInfos::PAY_MODE_CHEQUES
  517.                                 || $payMode == null
  518.                                 || $payMode == Client\BillingInfos::PAY_MODE_VIREMENT)  )
  519.                         || ( $sendMode === Client\BillingInfos::SEND_MODE_EMAIL && $payMode === null)
  520.                     )
  521.                 )
  522.                 {
  523.                     $email $billing->getClient()->getBillingInfos() ? $billing->getClient()->getBillingInfos()->getEmail(): null;
  524.                     if($email){
  525.                         $senderAdress = new \Symfony\Component\Mime\Address'comptabilite@silverbeaute.com''Comptabilité Silver Beauté');
  526.                         $html $this->renderView('billing/pdf.html.twig',[
  527.                             'billings' => [$billing],
  528.                             'company'  => $billing->getCompany()
  529.                         ]);
  530.                         $this->pdfService->setTimeout(120);
  531.                         $this->pdfService->setOption('enable-local-file-access'true);
  532.                         $pdf $this->pdfService->getOutputFromHtml($html);
  533.                         //$call  = $paytweakService->reSend($company, $billing->getCode(), $email);
  534.                         $res  $paytweakService->getLink($company$billing->getCode());
  535.                         if($res['code'] === PaytweakService::CODE_OK) {
  536.                             $link reset($res);
  537.                             if($link["paid"] == "1"){
  538.                                 continue;
  539.                             }
  540.                             try {
  541.                                 $this->mailService->sentRelance($senderAdress,$email$company$pdf$billing$link["link_url"]);
  542.                             }
  543.                             catch (\Exception $exception){
  544.                             }
  545.                         }
  546.                         elseif($res['code'] === PaytweakService::CODE_NOT_FOUND){
  547.                             $invoice $paytweakService->createInvoiceFromClient($client$billing);
  548.                             $call  $paytweakService->createBilling($invoice$company);
  549.                             if($call['code'] == 'OK') {
  550.                                 $billing->setStatus(Billing::STATUS_SENT);
  551.                                 $billing->setSendingDate(new \DateTime());
  552.                                 $em->getManager()->persist($billing);
  553.                             }
  554.                             else {
  555.                                 $mailService->sentErrorPaytweak($billing$call['code'], $call['message']);
  556.                             }
  557.                         }
  558.                         else {
  559.                             //$mailService->sentErrorPaytweak($billing, $call['code'], $call['message']);
  560.                         }
  561.                     }
  562.                 }
  563.                 elseif($modeEnvoi === 'courrier' && $sendMode === Client\BillingInfos::SEND_MODE_COURRIER ){
  564.                     $pdfBillings[] = $billing;
  565.                     $billing->setStatus(Billing::STATUS_SENT);
  566.                     $billing->setSendingDate(new \DateTime());
  567.                     $em->getManager()->persist($billing);
  568.                 }
  569.             }
  570.             $em->getManager()->flush();
  571.             if(count($pdfBillings) > 0){
  572.                 $html $this->renderView('billing/pdf.html.twig',[
  573.                     'billings' => $pdfBillings,
  574.                     'company'  => $billing->getCompany()
  575.                 ]);
  576.                 $knpSnappyPdf->setOption('enable-local-file-access'true);
  577.                 return new PdfResponse(
  578.                     $knpSnappyPdf->getOutputFromHtml($html, ['encoding' => 'utf-8']),
  579.                     'file.pdf'
  580.                 );
  581.             }
  582.         }
  583.         /***********
  584.          * LOT FORM
  585.          ************/
  586.         if($lotForm->isSubmitted() && $lotForm->isValid()) {
  587.             $start $lotForm->getData()['start'];
  588.             $company $lotForm->getData()['company'];
  589.             $end $lotForm->getData()['end'];
  590.             $site $lotForm->getData()['site'];
  591.             $modeEnvoi $lotForm->getData()['modeEnvoi'];
  592.             $status $lotForm->getData()['status'];
  593.             $clientFilter $lotForm->getData()['client'];
  594.             $pdfBillings = [];
  595.             $billings $billingRepository->searchForLot($site$company$start$end$status$modeEnvoi$clientFilter);
  596.             foreach($billings as $billing) {
  597.                 /** @var Client $client */
  598.                 $client $billing->getClient();
  599.                 $pdfBillings[] = $billing;
  600.             }
  601.             $em->getManager()->flush();
  602.             if(count($pdfBillings) > 0){
  603.                 $html $this->renderView('billing/pdf.html.twig',[
  604.                     'billings' => $pdfBillings,
  605.                     'company'  => $billing->getCompany()
  606.                 ]);
  607.                 $knpSnappyPdf->setOption('enable-local-file-access'true);
  608.                 $knpSnappyPdf->setTimeout(600);
  609.                 return new PdfResponse(
  610.                     $knpSnappyPdf->getOutputFromHtml($html, ['encoding' => 'utf-8']),
  611.                     'file.pdf'
  612.                 );
  613.             }
  614.         }
  615.         return [
  616.             'billings' => $billings,
  617.             'billingsEncaissement' => $billingsEncaissement,
  618.             'billingsSEPA' => $billingsSEPA,
  619.             'compagnies' => $compagnies,
  620.             'company' => $company,
  621.             'sites' => $sites,
  622.             'generateForm' => $form->createView(),
  623.             'formFilter' => $filterForm->createView(),
  624.             'validateForm' => $validateForm->createView(),
  625.             'easycollect' => $easyCollect->createView(),
  626.             'sendForm' => $sendForm->createView(),
  627.             'lotForm' => $lotForm->createView(),
  628.             'relanceForm' => $relanceForm->createView()
  629.         ];
  630.     }
  631.     /**
  632.      * @Route("/new/rdv/{id}", name="billing_new_rdv", methods={"GET","POST"})
  633.      */
  634.     public function new(
  635.         RDV $RDV,
  636.         Request $request,
  637.         BillingRepository $billingRepository,
  638.         BillingItemManager $billingItemManager,
  639.         RDVBillingManager $RDVBillingManager,
  640.         CsrfTokenManagerInterface  $csrfTokenManager,
  641.         PaytweakService  $paytweakService,
  642.         MailService  $mailService
  643.     ): Response
  644.     {
  645.         if($RDV->getStatus() === RDV::STATUS_FACTURER){
  646.             return $this->redirectToRoute('app_planning_coiffeurliste');
  647.         }
  648.         $entityManager $this->getDoctrine()->getManager();
  649.         /** @var Parameter $setting */
  650.         $setting $this->getDoctrine()->getRepository(Parameter::class)->find(1);
  651.         $tva $setting->getTva();
  652.         $billing = new Billing();
  653.         $codePromo $RDV->getCodePromo();
  654.         $promoPercentage 0;
  655.         if ($codePromo) {
  656.             // Assuming a method exists to retrieve the percentage associated with the promo code
  657.             $promoPercentage $codePromo->getPurcent(); // e.g., returns 10 for 10%
  658.         }
  659.         $billing->setDateBilling(new \DateTime());
  660.         $total 0;
  661.         $total_ht 0;
  662.         /** @var RDVProduct $rdvProduct */
  663.         foreach($RDV->getRdvProducts() as $rdvProduct){
  664.             $product $rdvProduct->getProduct();
  665.             $billingItem $billingItemManager->create($product$billing1$tva);
  666.             // date du jour du rdv pour facturer immadialite
  667.             $billingItem->setDateRDV($RDV->getStart());
  668.             $gridPrice null;
  669.             $salon =  $RDV->getSalon();
  670.             if($salon) {
  671.                 $gridPrice $RDV->getSalon()->getGridPrice();
  672.             }
  673.             $price null;
  674.             if($gridPrice) {
  675.                 switch ($gridPrice->getId()) {
  676.                     case 1:
  677.                         $price $product->getPriceHtA();
  678.                         break;
  679.                     case 2:
  680.                         $price $product->getPriceHtB();
  681.                         break;
  682.                     case 3:
  683.                         $price $product->getPriceHtC();
  684.                         break;
  685.                     case 4:
  686.                         $price $product->getPriceHtD();
  687.                         break;
  688.                 }
  689.             }
  690.             else {
  691.                 $price $product->getPriceHtA();
  692.             }
  693.             $billingItem->setPrice($price);
  694.             // protect
  695.             $remise $RDV->getClient()->getBillingInfos()->getDiscount();
  696.             if($product->getRemiseGenerale() > $remise ){
  697.                 $remise $product->getRemiseGenerale();
  698.             }
  699.             if($remise){
  700.                 $billingItem->setDiscount(floatval($remise));
  701.             }
  702.             if ($promoPercentage) {
  703.                 $price *= ($promoPercentage 100);
  704.                 $billingItem->setDiscount($promoPercentage);
  705.             }
  706.             $remisePurcent $remise ? ($remise 100) : 0;
  707.             if($remisePurcent != 0){
  708.                 $price $price $remisePurcent;
  709.             }
  710.             $calcultHt number_format((float)$price2);
  711.             if($tva <= 0) {
  712.                 $tva 20;
  713.             }
  714.             $ttc = (float) number_format($price * ($tva 100),2);
  715.             $billingItem->setRefProduct($product->getReference());
  716.             $billingItem->setTtc($ttc);
  717.             $billing->getBillingItems()->add($billingItem);
  718.             $total += $ttc;
  719.             $total_ht += $calcultHt;
  720.         }
  721.         $billing->setHt(number_format((float)$total_ht2"."""));
  722.         $billing->setTtc(number_format((float)$total2"."""));
  723.         $billing->setSolde(number_format($billing->getTtc(),2"."""));
  724.         $form $this->createForm(BillingType::class, $billing);
  725.         $form->handleRequest($request);
  726.         if($form->isSubmitted() && !$form->isValid()) {
  727.             $submittedToken $request->request->get('token');
  728.             if (!$this->isCsrfTokenValid('token_id'$submittedToken)) {
  729.                 return $this->redirectToRoute('app_planning_coiffeurliste');
  730.             }
  731.         }
  732.         if ($form->isSubmitted() && $form->isValid()) {
  733.             // FLAGGER ICI le loading comme ca pas de doublon
  734.             $billingsRDV $RDV->getRDVBillings();
  735.             $count 0;
  736.             if($billingsRDV->count() > 0){
  737.                 foreach ($billingsRDV as $itemBilling) {
  738.                     if ($itemBilling->getBilling() && $itemBilling->getBilling()->getStatus() !== Billing::STATUS_SOLDE_AVOIR && $itemBilling->getBilling()->getStatus() !== Billing::STATUS_SOLDE) {
  739.                         $count++;
  740.                     }
  741.                 }
  742.                 if($count 0){
  743.                     $this->addFlash('error''RDV déjà facturé');
  744.                     return $this->redirectToRoute('app_planning_coiffeurliste');
  745.                 }
  746.             }
  747.             $csrfTokenManager->refreshToken("form_intention");
  748.             $company null;
  749.             $date $form['dateBilling']->getData();
  750.             $billing->setDateBilling($date);
  751.             $total 0;
  752.             $totalHt 0;
  753.             $calcultHt 0;
  754.             /** @var BillingItem $billingItem */
  755.             foreach($form['billingItems']->getData() as $billingItem) {
  756.                 $date $billingItem->getDateRDV();
  757.                 $billingItem->setDateRDV($date);
  758.                 $billingItem->setQuantity($billingItem->getQuantity());
  759.                 $billingItem->setRefProduct($billingItem->getRefProduct());
  760.                 $billingItem->setTtc($billingItem->getTtc());
  761.                 $remise $billingItem->getDiscount() ?: 0;
  762.                 $price $billingItem->getPrice();
  763.                 if($remise && $remise != 0){
  764.                     $calcul = (floatval($price) * $billingItem->getQuantity() * ($remise 100 )) * ($billingItem->getTva() / 100);
  765.                     $calcultHt = (floatval($price)* $billingItem->getQuantity() * ( $remise 100 ));
  766.                 }
  767.                 else {
  768.                     $calcul floatval($price)* $billingItem->getQuantity()  * ($billingItem->getTva()  / 100);
  769.                     $calcultHt floatval($price) * $billingItem->getQuantity();
  770.                 }
  771.                 $total += $calcul;
  772.                 $totalHt += $calcultHt;
  773.                 $billingItem->setDateRDV($date);
  774.                 $entityManager->persist($billingItem);
  775.             }
  776.             $billing->setClient($RDV->getClient());
  777.             //retrive company
  778.             if($RDV->getClient()) {
  779.                 $billingInfos $RDV->getClient()->getBillingInfos();
  780.                 if ($billingInfos) {
  781.                     $company $billingInfos->getCompany();
  782.                     $billing->setCompany($company);
  783.                 }
  784.             }
  785.             $code $this->billingManager->getCodeBilling($company$billing);
  786.             $billing->setCode($code);
  787.             $billing->setTtc(number_format((float) $total2,"."""));
  788.             $billing->setHt(number_format($totalHt2,"."""));
  789.             $billing->setStatus(Billing::STATUS_VALIDE);
  790.             if($billing->getHt() <= || $billing->getSolde() <= 0){
  791.                 $billing->setStatus(Billing::STATUS_REGLEE);
  792.             }
  793.             $billing->setCreator($this->getUser());
  794.             $billing->setModeFacturation(Billing::MODE_FRDV);
  795.             //$this->persistBillingItems($RDV, $billing);
  796.             $rdvBilling $RDVBillingManager->create($billing$RDV);
  797.             $billing->addRDVBilling($rdvBilling);
  798.             $RDV->addRDVBilling($rdvBilling);
  799.             $RDV->setStatus(RDV::STATUS_FACTURER);
  800.             $entityManager->persist($RDV);
  801.             $entityManager->persist($billing);
  802.             $entityManager->flush();
  803.             // TODO fix product list in invoice
  804.              $invoice $paytweakService->createInvoiceFromClient($RDV->getClient(), $billing);
  805.              $call  $paytweakService->createBilling($invoice$company);
  806.              if($call['code'] == 'OK') {
  807.                  if($billing->getHt() <= || $billing->getSolde() <= 0){
  808.                      $billing->setStatus(Billing::STATUS_REGLEE);
  809.                  }
  810.                  else {
  811.                      $billing->setStatus(Billing::STATUS_SENT);
  812.                  }
  813.                  if(isset($call['link_id'] )){
  814.                      $billing->setLinkPaytweak($call['link_id']);
  815.                  }
  816.                  $billing->setSendingDate(new \DateTime());
  817.                  $entityManager->persist($billing);
  818.              }
  819.              else {
  820.                  $mailService->sentErrorPaytweak($billing$call['code'], $call['message']);
  821.              }
  822.              $entityManager->flush();
  823.             return $this->redirectToRoute('app_planning_coiffeurliste');
  824.         }
  825.         return $this->render('billing/new_rdv.html.twig', [
  826.             'billing' => $billing,
  827.             'rdv' => $RDV,
  828.             'tva' => $tva,
  829.             'form' => $form->createView(),
  830.         ]);
  831.     }
  832.     /**
  833.      * @Route("/edit/{id}", name="billing_edit", methods={"GET","POST"})
  834.      */
  835.     public function edit(Request $requestBilling $billingPdf $knpSnappyPdf): Response
  836.     {
  837.         $entityManager $this->getDoctrine()->getManager();
  838. //        if($billing->getDateBilling()){
  839. //            $billing->setDateBilling($billing->getDateBilling()->format('d/m/Y'));
  840. //        }
  841.         //dd($billing->getDateBilling());
  842.         /** @var BillingItem $billingItem */
  843.         foreach($billing->getBillingItems() as $billingItem) {
  844.             if($billingItem->getDateRDV()){
  845.                 $billingItem->setDateRDV($billingItem->getDateRDV());
  846.             }
  847.         }
  848.         $form $this->createForm(BillingType::class, $billing);
  849.         $contencieux $this->createForm(ContencieuxType::class, $billing);
  850.         $client $billing->getClient();
  851.         /** @var Parameter $setting */
  852.         $setting $this->getDoctrine()->getRepository(Parameter::class)->find(1);
  853.         $tva $setting->getTva();
  854.         // SET FIELD ICI A FAIRE
  855.         $pdf $request->request->get('pdf');
  856.         if($pdf){
  857.             $html $this->renderView('billing/pdf.html.twig',[
  858.                 'billings' => [$billing],
  859.                 'company'  => $billing->getCompany()
  860.             ]);
  861.             $knpSnappyPdf->setOption('enable-local-file-access'true);
  862.             return new PdfResponse(
  863.                 $knpSnappyPdf->getOutputFromHtml($html, ['encoding' => 'utf-8']),
  864.                 'file.pdf'
  865.             );
  866.         }
  867.         $form->handleRequest($request);
  868.         //dump($form->getErrors());die;
  869.         if ($form->isSubmitted() && $form->isValid()) {
  870.             $total 0;
  871.             $totalHt 0;
  872.             $calcultHt 0;
  873.             $date $form['dateBilling']->getData();
  874.             $billing->setDateBilling($date);
  875.             foreach($form['billingItems']->getData() as $billingItem) {
  876.                 $date $billingItem->getDateRDV();
  877.                 $price $billingItem->getPrice();
  878.                 $remise $billingItem->getDiscount() ?: 0;
  879.                 if($remise && $remise != 0){
  880.                     $calculationTtc = ($price $billingItem->getQuantity() * ($remise 100)) * ($tva 100);
  881.                     $calcul = (floatval($price) * $billingItem->getQuantity() * ($remise 100 )) * ($billingItem->getTva() / 100);
  882.                     $calcultHt = (floatval($price)* $billingItem->getQuantity() * ( $remise 100 ));
  883.                 }
  884.                 else {
  885.                     $calculationTtc $price $billingItem->getQuantity() * ($tva 100);
  886.                     $calcul floatval($price)* $billingItem->getQuantity()  * ($billingItem->getTva()  / 100);
  887.                     $calcultHt floatval($price) * $billingItem->getQuantity();
  888.                 }
  889.                 $billingItem->setQuantity($billingItem->getQuantity());
  890.                 $calculationTtc number_format((float) $calculationTtc2,".""");
  891.                 $billingItem->setTtc($calculationTtc);
  892.                 $total += $calcul;
  893.                 $totalHt += $calcultHt;
  894.                 $billingItem->setDateRDV($date);
  895.                 $entityManager->persist($billingItem);
  896.             }
  897.             $billing->setTtc(number_format($total2,"."""));
  898.             $billing->setHt(number_format($totalHt2,"."""));
  899.             //$billing->setSolde(number_format($billing->getTtc(), 2));s
  900.             if($billing->getHt() <= || $billing->getSolde() < 0){
  901.                 $billing->setStatus(Billing::STATUS_REGLEE);
  902.             }
  903.             $billing->setCreator($this->getUser());
  904.             $billing->setMaj($this->getUser());
  905.             $entityManager->persist($billing);
  906.             $entityManager->flush();
  907.             return $this->redirectToRoute('app_billing_index');
  908.         }
  909.         $contencieux->handleRequest($request);
  910.         if ($contencieux->isSubmitted() && $contencieux->isValid()) {
  911.             $billing->setStatus(Billing::STATUS_CONTENTIEUX);
  912.             $entityManager->persist($billing);
  913.             $entityManager->flush();
  914.         }
  915.         return $this->render('billing/edit.html.twig', [
  916.             'billing' => $billing,
  917.             'client' => $client,
  918.             'tva' => $tva,
  919.             'form' => $form->createView(),
  920.             'contencieuxForm' => $contencieux->createView(),
  921.         ]);
  922.     }
  923.     /**
  924.      * @Route("/cancel/{id}/{date}", name="billing_cancel", methods={"GET","POST"})
  925.      */
  926.     public function cancel(Request $requestBilling $billingBillingRepository $billingRepositoryBillingItemManager $billingItemManager$date): Response
  927.     {
  928.         $em $this->getDoctrine()->getManager();
  929.         if($billing->getStatus() === Billing::STATUS_EN_COURS){
  930.             foreach ($billing->getRDVBillings() as $RDVBilling){
  931.                 $rdv $RDVBilling->getRDV();
  932.                 if($rdv && $rdv->getId()){
  933.                     $rdv->setStatus(RDV::STATUS_VALIDATED);
  934.                     $em->persist($rdv);
  935.                 }
  936.                 $em->remove($RDVBilling);
  937.             }
  938.             $em->remove($billing);
  939.             $em->flush();
  940.             return $this->redirectToRoute('app_billing_index');
  941.         }
  942.         $dateObject = new \DateTime($date);
  943.         $this->billingManager->createAvoir($billing$this->getUser(), $dateObject);
  944.         $em->flush();
  945.         return $this->redirectToRoute('app_billing_index');
  946.     }
  947.     /**
  948.      * @Route("/import-ajax", name="billing_importajax")
  949.      */
  950.     public function importajax(Request $requestFileUploader $fileUploader){
  951.         $path $this->getParameter('updatebilling_import_directory');
  952.         $file $request->files->get('file');
  953.         if($file) {
  954.             try {
  955.                 $resp $fileUploader->upload($request->files->get('file'), $path);
  956.                 return new JsonResponse(['filename' => $resp ]);
  957.             }catch (\Exception $e) {
  958.             }
  959.         }
  960.         return new JsonResponse(['error' => '' ]);
  961.     }
  962.     /**
  963.      * @Route("/importCSV", name="import_csv", methods={"GET","POST"})
  964.      */
  965.     public function importCSV(Request $requestBillingRepository $billingRepositoryEntityManagerInterface  $entityManager){
  966.         $path $this->getParameter('updatebilling_import_directory');
  967.         if($request->isMethod(Request::METHOD_POST)) {
  968.             $files $request->request->get('files');
  969.             $path_file $path '/' $files[0];
  970.             if(file_exists($path_file)) {
  971.                 try {
  972.                     /**  Identify the type of $inputFileName  **/
  973.                     $inputFileType \PhpOffice\PhpSpreadsheet\IOFactory::identify($path_file);
  974.                     /**  Create a new Reader of the type defined in $inputFileType  **/
  975.                     $reader \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
  976.                     /**  Advise the Reader that we only want to load cell data  **/
  977.                     $reader->setReadDataOnly(true);
  978.                     $spreadsheet $reader->load($path_file);
  979.                     $worksheet =  $spreadsheet->getActiveSheet();
  980.                     //$lines = $spreadsheet->getActiveSheet()->toArray();
  981.                     foreach ($worksheet->getRowIterator() as $key => $row) {
  982.                         $cellIterator $row->getCellIterator();
  983.                         $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
  984.                         $billingfound null;
  985.                         foreach ($cellIterator as $key2 => $cell) {
  986.                             $value $cell->getValue();
  987.                             switch ($key2) {
  988.                                 case 'A':
  989.                                 {
  990.                                     $billingfound =  $billingRepository->findOneBy(['id' => (int) $value]);
  991.                                     break;
  992.                                 }
  993.                                 case 'B':
  994.                                 {
  995.                                     if($billingfound) {
  996.                                         $billingfound->setCode($value);
  997.                                         $entityManager->persist($billingfound);
  998.                                     }
  999.                                     break;
  1000.                                 }
  1001.                                 default:
  1002.                                     break;
  1003.                             }
  1004.                         }
  1005.                     }
  1006.                 }
  1007.                 catch (\Exception $exception) {
  1008.                     dump($exception);die;
  1009.                 }
  1010.                 $entityManager->flush();
  1011.             }
  1012.             $this->addFlash('success''Fichier importé');
  1013.         }
  1014.         return $this->render('billing/import.html.twig', [
  1015.         ]);
  1016.     }
  1017.     /**
  1018.      * @Route("/downloadExcel")
  1019.      */
  1020.     public function downloadExcel(Request $requestBillingRepository $repository) {
  1021.         $date_debut $request->request->get('date_debut') ?? null;
  1022.         $date_fin $request->request->get('date_fin') ?? null;
  1023.         $entities =  new ArrayCollection($repository->filter(null,null $date_debut,$date_fin));
  1024.         $response = new StreamedResponse();
  1025.         $columns $this->getColumnsForEntity(Billing::class);
  1026.         $billingItemColumns $this->getColumnsForEntity(BillingItem::class);
  1027.         $response->setCallback(function () use ($entities$columns$billingItemColumns) {
  1028.             $handle fopen('php://output''w+');
  1029.             // Add header
  1030.             fputcsv($handlearray_keys($columns));
  1031.             /** @var Billing $entity */
  1032.             while ($entity $entities->current()) {
  1033.                 $values = [];
  1034.                 foreach ($columns as $column => $callback) {
  1035.                     $value $callback;
  1036.                     if (is_callable($callback)) {
  1037.                         $value $callback($entity);
  1038.                     }
  1039.                     $values[] = $value;
  1040.                 }
  1041.                 fputcsv($handle$values);
  1042. //                fputcsv($handle, array_keys($billingItemColumns));
  1043. //                $values = [];
  1044. //                foreach ($entity->getBillingItems() as $billingItem) {
  1045. //                    foreach ($billingItemColumns as $column => $callback) {
  1046. //                        $value = $callback;
  1047. //                        if (is_callable($callback)) {
  1048. //                            $value = $callback($billingItem);
  1049. //                        }
  1050. //                        $values[] = $value;
  1051. //                    }
  1052. //                }
  1053. //
  1054. //                fputcsv($handle, $values);
  1055.                 $entities->next();
  1056.             }
  1057.             fclose($handle);
  1058.         });
  1059.         $filename 'billing.csv';
  1060.         $response->headers->set('Content-Type''text/csv; charset=utf-8');
  1061.         $response->headers->set('Content-Disposition''attachment; filename="' $filename '"');
  1062.         return $response;
  1063.     }
  1064.     /**
  1065.      * @Route("/downloadItemsExcel")
  1066.      */
  1067.     public function downloadItemsExcel(BillingItemsRepository $repository) {
  1068.         $entities =  new ArrayCollection($repository->findAll());
  1069.         $response = new StreamedResponse();
  1070.         $columns $this->getColumnsForEntity(BillingItem::class);
  1071.         $response->setCallback(function () use ($entities$columns) {
  1072.             $handle fopen('php://output''w+');
  1073.             // Add header
  1074.             fputcsv($handlearray_keys($columns));
  1075.             while ($entity $entities->current()) {
  1076.                 $values = [];
  1077.                 foreach ($columns as $column => $callback) {
  1078.                     $value $callback;
  1079.                     if (is_callable($callback)) {
  1080.                         $value $callback($entity);
  1081.                     }
  1082.                     $values[] = $value;
  1083.                 }
  1084.                 fputcsv($handle$values);
  1085.                 $entities->next();
  1086.             }
  1087.             fclose($handle);
  1088.         });
  1089.         $filename 'billing_items.csv';
  1090.         $response->headers->set('Content-Type''text/csv; charset=utf-8');
  1091.         $response->headers->set('Content-Disposition''attachment; filename="' $filename '"');
  1092.         return $response;
  1093.     }
  1094.     /**
  1095.      * @param RDV $RDV
  1096.      * @param Billing $billing
  1097.      */
  1098.     private function persistBillingItems(RDV $RDVBilling $billing)
  1099.     {
  1100.         $em $this->getDoctrine()->getManager();
  1101.         /** @var RR $rdvProduct */
  1102.         foreach ($RDV->getRdvProducts() as $rdvProduct) {
  1103.             $product $rdvProduct->getProduct();
  1104.             // Fetch products to add billings..
  1105.             $billingItem = new BillingItem();
  1106.             $billingItem->setBilling($billing);
  1107.             $billingItem->setRefProduct($product->getReference());
  1108.             $billingItem->setLibelleProduct($product->getName());
  1109.             $billingItem->setProduct($product);
  1110.             $em->persist($billingItem);
  1111.         }
  1112.     }
  1113.     /**
  1114.      * @param array $data
  1115.      * @throws \Exception
  1116.      */
  1117.     private function generateBilling(array $data)
  1118.     {
  1119.         $em $this->managerRegistry;
  1120.         /** @var RDVRepository $repository */
  1121.         $repository $em->getRepository(RDV::class);
  1122.         /** @var ClientRepository $clientRepository */
  1123.         $clientRepository $em->getRepository(Client::class);
  1124.         /** @var SiteRepository $siteRepository */
  1125.         $siteRepository $em->getRepository(Site::class);
  1126.         /** @var ProductRepository $productRepository */
  1127.         $productRepository $em->getRepository(Product::class);
  1128.         /** @var BillingRepository $billingRepository */
  1129.         $billingRepository $em->getRepository(Billing::class);
  1130.         $typeBilling $data['typeBilling'];
  1131.         $start $data['start'];
  1132.         $end $data['end'];
  1133.         $company $data['company'];
  1134.         $site =  $data['site'];
  1135.         /** @var Parameter $setting */
  1136.         $setting $this->managerRegistry->getRepository(Parameter::class)->find(1);
  1137.         $tva $setting->getTva();
  1138.         $billing_added 0;
  1139.         //dump($company);die;
  1140.         $rdvs $repository->findForBilling($start$endRDV::STATUS_VALIDATED$company$site);
  1141.         //$company = $companyRepository->find
  1142.         $merge_rdv = [];
  1143.         /** @var RDV $rdv */
  1144.         foreach ($rdvs as $rdv) {
  1145.             if ($typeBilling === 'client') {
  1146.                 $client_id $rdv['client_id'];
  1147.                 $merge_rdv[$client_id][] = $rdv;
  1148.             } else {
  1149.                 $site_id $rdv['site_id'];
  1150.                 $merge_rdv[$site_id][] = $rdv;
  1151.             }
  1152.         }
  1153.         // Merge contiient tout les rdvs trié soit pppar client_id soit par site_id
  1154.         //dump($merge_rdv);die;
  1155.         // pour  chaque site ou client
  1156.         foreach ($merge_rdv as $key => $rdvs) {
  1157.             $billing = new Billing();
  1158.             $billing->setCreator($this->getUser());
  1159.             $client null;
  1160.             if ($typeBilling === 'client') {
  1161.                 $client $clientRepository->find($key);
  1162.                 $billing->setClient($client);
  1163.             } elseif ($typeBilling === 'site') {
  1164.                 $site $siteRepository->find($key);
  1165.                 $billing->setSite($site);
  1166.             }
  1167.             if($company) {
  1168.                 $billing->setCompany($company);
  1169.             }
  1170.             $total 0;
  1171.             $totalHt 0;
  1172.             foreach ($rdvs as $rdv) {
  1173.                 $rdv_id $rdv['id'];
  1174.                 // get the rdv
  1175.                 $rdvObj $repository->findOneBy(['id' => $rdv_id]);
  1176.                 $dateRdv $rdvObj->getEnd();
  1177.                 // if we bill from site take client from rdv because it will be null
  1178.                 if(!$client){
  1179.                     $client $rdvObj->getClient();
  1180.                 }
  1181.                 // GET PRODUCT OF RDV
  1182.                 $rdvProducts $rdvObj->getRdvProducts();
  1183.                 $products = [];
  1184.                 /** @var RDVProduct $rdvProduct */
  1185.                 foreach ($rdvProducts as $rdvProduct) {
  1186.                     $product $rdvProduct->getProduct();
  1187.                     if(array_key_exists($product->getId(),$products)) {
  1188.                         $products[$product->getId()] = $products[$product->getId()]++;
  1189.                     }
  1190.                     else {
  1191.                         $products[$product->getId()] = 1;
  1192.                     }
  1193.                 }
  1194.                 foreach ($products as $key => $productQuantity) {
  1195.                     $product $productRepository->find($key);
  1196.                     // Fetch products to add billings..
  1197.                     $billingItem $this->billingItemManager->create($product$billing$productQuantity$tva$rdvObj);
  1198.                     //date fin de RDV
  1199.                     //$castedDate = new \DateTime($end);
  1200.                     $billingItem->setDateRDV($dateRdv);
  1201.                     $em->getManager()->persist($billingItem);
  1202.                     $gridPrice null;
  1203.                     $salon =  $rdvObj->getSalon();
  1204.                     if($salon) {
  1205.                         $gridPrice $rdvObj->getSalon()->getGridPrice();
  1206.                     }
  1207.                     $price null;
  1208.                     if($gridPrice) {
  1209.                         switch ($gridPrice->getId()) {
  1210.                             case 1:
  1211.                                 $price $product->getPriceHtA();
  1212.                                 break;
  1213.                             case 2:
  1214.                                 $price $product->getPriceHtB();
  1215.                                 break;
  1216.                             case 3:
  1217.                                 $price $product->getPriceHtC();
  1218.                                 break;
  1219.                             case 4:
  1220.                                 $price $product->getPriceHtD();
  1221.                                 break;
  1222.                         }
  1223.                     }
  1224.                     else {
  1225.                         $price $product->getPriceHtA();
  1226.                     }
  1227.                     /**
  1228.                      *
  1229.                      */
  1230.                     // protect
  1231.                     $remiseClient $client->getBillingInfos()->getDiscount() ?: 0;
  1232.                     $remise $remiseClient;
  1233.                     if($product->getRemiseGenerale() && $product->getRemiseGenerale() > $remiseClient ){
  1234.                         $remise $product->getRemiseGenerale() ?: 0;
  1235.                     }
  1236.                     if($tva <= 0) {
  1237.                         $tva 20;
  1238.                     }
  1239.                     if($remise && $remise != 0){
  1240.                         $calcul = (floatval($price) * ($remise 100 )) * ($tva 100) * $billingItem->getQuantity();
  1241.                         $calcultHt = (floatval($price) * ( $remise 100 ) ) * $billingItem->getQuantity() ;
  1242.                     }
  1243.                     else {
  1244.                         $calcul floatval($price)  * ($tva 100)  * $billingItem->getQuantity();
  1245.                         $calcultHt floatval($price)  * $billingItem->getQuantity();
  1246.                     }
  1247.                     $ttc number_format($calcul2".""");
  1248.                     if($remise){
  1249.                         $billingItem->setDiscount(floatval($remise));
  1250.                     }
  1251.                     $billingItem->setPrice(floatval($price));
  1252.                     $billingItem->setTtc($ttc);
  1253.                     // ADD ITEM
  1254.                     $billing->addBillingItem($billingItem);
  1255.                     $total += $billingItem->getTtc();
  1256.                     $totalHt += $calcultHt;
  1257.                 }
  1258.                 //UPDATE RDV
  1259.                 $rdvObj->setStatus(RDV::STATUS_FACTURER);
  1260.                 // LINK TO BILLING / RDV
  1261.                 $rdvBilling = new RDVBilling();
  1262.                 $rdvBilling->setBilling($billing);
  1263.                 $rdvBilling->setRDV($rdvObj);
  1264.                 $em->getManager()->persist($rdvBilling);
  1265.                 $billing->addRDVBilling($rdvBilling);
  1266.                 $rdvObj->addRDVBilling($rdvBilling);
  1267.                 $em->getManager()->persist($rdvObj);
  1268.             }
  1269.             // facture need to be in brouillon
  1270.             //$code = $this->billingManager->getCodeBilling($company);
  1271.             //$billing->setCode($code);
  1272.             $billing->setModeFacturation(Billing::MODE_FFDP);
  1273.             // set billing to total of all RDV
  1274.             $billing->setTtc(number_format((float)$total2"."""));
  1275.             $billing->setHt($totalHt);
  1276.             $ttc str_replace(array("."","), array(",""."), $billing->getTtc());
  1277.             $billing->setSolde(number_format((float)$ttc2"."""));
  1278.             // UPDTAE  BILLING
  1279.             $billing->setStatus(Billing::STATUS_EN_COURS);
  1280. //            if($billing->getHt() <= 0 || $billing->getSolde() < 0){
  1281. //                $billing->setStatus(Billing::STATUS_REGLEE);
  1282. //            }
  1283.             $billing->setCreator($this->getUser());
  1284.             $billing->setMaj($this->getUser());
  1285.             // set end of period to billing date
  1286.             $date date_create_from_format('Y-m-d'$end);
  1287.             $billing->setDateBilling($date);
  1288.             $em->getManager()->persist($billing);
  1289.             $billing_added++;
  1290.         }
  1291.         $em->getManager()->flush();
  1292.     }
  1293.     /**
  1294.      * @param $class
  1295.      * @return mixed
  1296.      */
  1297.     private function getColumnsForEntity($class)
  1298.     {
  1299.         $columns[Billing::class] = [
  1300.             'Id' => function (Billing $billing) {
  1301.                 return (string) $billing->getId();
  1302.             },
  1303.             'Date' => function (Billing $billing) {
  1304.                 return $billing->getDateBilling() ? $billing->getDateBilling()->format('d-m-Y H:i:s') : '';
  1305.             },
  1306.             'Mode de facturation' => function (Billing $billing) {
  1307.                 return $billing->getModeFacturation();
  1308.             },
  1309.             'Code' => function (Billing $billing) {
  1310.                 return $billing->getCode();
  1311.             },
  1312.             'Comment' => function (Billing $billing) {
  1313.                 return $billing->getComment();
  1314.             },
  1315.             'Ttc' => function (Billing $billing) {
  1316.                 return (string) $billing->getTtc();
  1317.             },
  1318.             'Solde' => function (Billing $billing) {
  1319.                 return (string) $billing->getSolde();
  1320.             },
  1321.             'Status' => function (Billing $billing) {
  1322.                 return $billing->getStatus();
  1323.             },
  1324.             'Accompte' => function (Billing $billing) {
  1325.                 return $billing->getAccompte();
  1326.             },
  1327.             'Type' => function (Billing $billing) {
  1328.                 return $billing->getType();
  1329.             },
  1330.             'Site' => function (Billing $billing) {
  1331.                 return $billing->getClient() && $billing->getClient()->getSite() ? $billing->getClient()->getSite()->getName() : "";
  1332.             },
  1333.             'Status Site' => function (Billing $billing) {
  1334.                 return $billing->getClient() && $billing->getClient()->getSite() ? $billing->getClient()->getSite()->getStatus() : "";
  1335.             },
  1336.             'ID client' => function (Billing $billing) {
  1337.                 return $billing->getClient() ? $billing->getClient()->getId(): "";
  1338.             },
  1339.             'Civilité' => function (Billing $billing) {
  1340.                 return $billing->getClient() ? $billing->getClient()->getCivilite(): "";
  1341.             },
  1342.             'Client' => function (Billing $billing) {
  1343.                 return (string) $billing->getClient();
  1344.             },
  1345.             'Statut Client' => function (Billing $billing) {
  1346.                 return (string) $billing->getClient() ? $billing->getClient()->getStatusProspect() : null;
  1347.             },
  1348.             'Tel facturation' => function (Billing $billing) {
  1349.                 return $billing->getClient() && $billing->getClient()->getBillingInfos() ? $billing->getClient()->getBillingInfos()->getPhone(): "";
  1350.             },
  1351.             'Adresse email facturation' => function (Billing $billing) {
  1352.                 return (string) $billing->getClient() && $billing->getClient()->getBillingInfos() ? $billing->getClient()->getBillingInfos()->getEmail() : "";
  1353.             },
  1354.             'Adresse  facturation' => function (Billing $billing) {
  1355.                 return (string) $billing->getClient() ? $billing->getClient()->getAddressFacturation(): "";
  1356.             },
  1357.             'Adresse complément facturation' => function (Billing $billing) {
  1358.                 return (string) $billing->getClient() ? $billing->getClient()->getComplementAdresseFacturation(): "";
  1359.             },
  1360.             'Ville  facturation' => function (Billing $billing) {
  1361.                 return (string) $billing->getClient() ? $billing->getClient()->getVilleFacturation(): "";
  1362.                 },
  1363.             'Code postal facturation' => function (Billing $billing) {
  1364.                 return (string) $billing->getClient() ? $billing->getClient()->getCodePostalFacturation(): "";
  1365.             },
  1366.             'Mode envoi facturation' => function (Billing $billing) {
  1367.                 return $billing->getClient() && $billing->getClient()->getBillingInfos() ? $billing->getClient()->getBillingInfos()->getSendMode() : "";
  1368.             },
  1369.         ];
  1370.         $columns[BillingItem::class] = [
  1371.             'Id' => function (BillingItem $billing) {
  1372.                 return $billing->getId();
  1373.             },
  1374.             'ReferenceFacture' => function (BillingItem $billing) {
  1375.                 return $billing->getBilling()->getCode();
  1376.             },
  1377.             'Date' => function (BillingItem $billing) {
  1378.                 return $billing->getDateRDV() ? $billing->getDateRDV()->format('d-m-Y H:i:s') : '';
  1379.             },
  1380.             'Réf product' => function (BillingItem $billing) {
  1381.                 return $billing->getRefProduct();
  1382.             },
  1383.             'Price' => function (BillingItem $billing) {
  1384.                 return (string) $billing->getPrice();
  1385.             },
  1386.             'Discount' => function (BillingItem $billing) {
  1387.                 return (string) $billing->getDiscount();
  1388.             },
  1389.             'Ttc' => function (BillingItem $billing) {
  1390.                 return (string) $billing->getTtc();
  1391.             },
  1392.             'Quantity' => function (BillingItem $billing) {
  1393.                 return (string) $billing->getQuantity();
  1394.             },
  1395.             'Libelle Produit' => function (BillingItem $billing) {
  1396.                 return $billing->getLibelleProduct();
  1397.             },
  1398.         ];
  1399.         if (array_key_exists($class$columns)) {
  1400.             return $columns[$class];
  1401.         }
  1402.         throw new \InvalidArgumentException(sprintf(
  1403.             'No columns set for "%s" entity',
  1404.             $class
  1405.         ));
  1406.     }
  1407. }