src/Controller/BillingController.php line 743

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