src/Controller/CommandeController.php line 2847

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use DateTime;
  4. use DateTimeZone;
  5. use App\Entity\Colis;
  6. use App\Entity\Client;
  7. use App\Entity\Commande;
  8. use App\Form\SearchType;
  9. use App\Form\CommandeType;
  10. use App\Entity\ClientFinal;
  11. use App\Service\FedexService;
  12. use App\Service\UtilsService;
  13. use App\Form\CommandeAdminType;
  14. use App\Service\BandeauService;
  15. use App\Service\EmailGenerator;
  16. use App\Form\CommandeCreneauType;
  17. use App\Form\CommandeAdminEditType;
  18. use App\Repository\ColisRepository;
  19. use App\Repository\ClientRepository;
  20. use App\Repository\CommandeRepository;
  21. use PhpOffice\PhpSpreadsheet\Writer\Csv;
  22. use PhpOffice\PhpSpreadsheet\Writer\Xls;
  23. use App\Repository\ClientFinalRepository;
  24. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  25. use PhpOffice\PhpSpreadsheet\Style\Color;
  26. use Knp\Component\Pager\PaginatorInterface;
  27. use Symfony\Component\HttpFoundation\Request;
  28. use Symfony\Component\Mailer\MailerInterface;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use Symfony\Component\Security\Csrf\CsrfToken;
  31. use Symfony\Component\Routing\Annotation\Route;
  32. use Symfony\Component\HttpFoundation\JsonResponse;
  33. use Symfony\Component\HttpFoundation\StreamedResponse;
  34. use Symfony\Component\Form\Extension\Core\Type\FileType;
  35. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  36. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  37. /**
  38.  * @Route("/commande")
  39.  */
  40. class CommandeController extends AbstractController
  41. {
  42.     private $utilsService;
  43.     private $emailGeneratorService;
  44.     private $fedexService;
  45.     private $roleAdmin;
  46.     private $baseDomain 'https://wine.mbebordeaux.fr';
  47.     private $bandeauService;
  48.     public function __construct(UtilsService $utilsServiceEmailGenerator $emailGeneratorServiceFedexService $fedexServiceBandeauService $bandeauService)
  49.     {
  50.         $this->utilsService $utilsService;
  51.         $this->emailGeneratorService $emailGeneratorService;
  52.         $this->fedexService $fedexService;
  53.         $this->roleAdmin $this->utilsService->isAdmin();
  54.         $this->bandeauService $bandeauService;
  55.     }
  56.     /**
  57.      * @Route("/", name="app_commande_index", methods={"GET"})
  58.      */
  59.     public function index(CommandeRepository $commandeRepositoryPaginatorInterface $paginatorRequest $request): Response
  60.     {
  61.         $user $this->getUser();
  62.         $packaging $request->query->get('packaging');
  63.         $state $request->query->get('state');
  64.         if ($packaging == null) {
  65.             if ($this->roleAdmin) {
  66.                 $packaging "emballage_par_mbe";
  67.             }
  68.             else {
  69.                 $packaging "emballage_par_caviste";
  70.             }
  71.         }
  72.         if ($state == null) {
  73.             if ($this->roleAdmin) {
  74.                 $state "preparation";
  75.             }
  76.             else {
  77.                 $state "emballage_caviste";
  78.             }
  79.         }
  80.         $data null;
  81.         $needPacking false;
  82.         $needCollect false;
  83.         $a_emballer_caviste false;
  84.         $a_preparer_collecte false
  85.         $emb_livraison false;
  86.         $exportPackingClient false;
  87.         $exportPrepsClient false;
  88.         $display_emballage_par_caviste false;
  89.         $display_emballage_par_mbe false;
  90.         $attention_emballage_par_caviste false;
  91.         $attention_emballage_par_mbe false;
  92.         if($packaging == "emballage_par_caviste") {
  93.             $emb_livraison true;
  94.         }
  95.         if($state == "urgent"){
  96.             if ($this->roleAdmin){
  97.                 $data $commandeRepository->findUrgentOrderAdmin();
  98.             } else {
  99.                 $data $commandeRepository->findUrgentOrderClient($user->getClient());
  100.             }
  101.         } else {
  102.             if ($this->roleAdmin) {
  103.                 if($packaging == "emballage_tous") {
  104.                     $data $commandeRepository->findby(
  105.                         array(),
  106.                         array('dateCollecte' => 'DESC')
  107.                     );
  108.                 }
  109.                 else if($packaging == "archive_tous") {
  110.                     //$data = $commandeRepository->findByState("archive", array('dateCollecte' => 'ASC'));
  111.                     $data $commandeRepository->findCommandesArchives();
  112.                 }
  113.                 else {
  114.                     //Pour chaque onglet, on recherche par state et categorie pour tous les clients
  115.                     /* if($state == 'tous') {
  116.                         $data = $commandeRepository->findByEmballageLivraison($emb_livraison);
  117.                     }
  118.                     else { */
  119.                         $data $commandeRepository->findByStateAndEmballageLivraison($state$emb_livraison);
  120.                     /* } */
  121.                 }
  122.                 
  123.                 $needPacking = empty($commandeRepository->findByStateAndEmballageLivraison("emballage_mbe"$emb_livraison)) ? false true;      
  124.                 $needCollect = empty($commandeRepository->findByStateAndEmballageLivraison("attente_collecte_mbe"$emb_livraison)) ? false true;  
  125.                 if($needPacking || $needCollect) {
  126.                     $attention_emballage_par_mbe true;
  127.                 }
  128.             } else {
  129.     
  130.                 $client $user->getClient();
  131.                 if($packaging == "emballage_tous") {
  132.                     $data $commandeRepository->findByClient($client, array('dateCollecte' => 'DESC'));
  133.                 }
  134.                 else if($packaging == "archive_tous") {
  135.                     $data $commandeRepository->findByStateAndClient(["archive""canceled"], $client);
  136.                 }
  137.                 else {
  138.                     if($state == "traitement_mbe") {
  139.                         //req pour avoir les 2 states fusionnés
  140.                         $data $commandeRepository->findByTraitementMbeAndEmballageLivraisonAndCaviste($emb_livraison$client);
  141.                     }
  142.                     else {
  143.                         $data $commandeRepository->findByStateAndEmballageLivraisonAndCaviste($state$emb_livraison$client);
  144.                     }
  145.                 }
  146.     
  147.     
  148.     
  149.     
  150.                 /* if ($state == "tous") {
  151.                     $data = $commandeRepository->findByClient($client);
  152.                 } else if ($state == "prepare"){
  153.                     $data = $commandeRepository->findOrderToPrepare($client);
  154.                 } else {
  155.                     $data = $commandeRepository->findByStateAndClient($state, $client);
  156.                     // if ($state == 'attente') {
  157.                     //     $data += $commandeRepository->findByStateAndClient('emballage', $client);
  158.                     // }
  159.                 } */
  160.                   
  161.                 $a_emballer_caviste = empty($commandeRepository->findByStateAndEmballageLivraisonAndCaviste("emballage_caviste"$emb_livraison$client)) ? false true;  
  162.                 $a_preparer_collecte = empty($commandeRepository->findByStateAndEmballageLivraisonAndCaviste("preparation"$emb_livraison$client)) ? false true
  163.                 $exportPackingClient = empty($commandeRepository->findByStateAndClient("emballage_caviste"$client)) ? false true;
  164.                 $exportPrepsClient = empty($commandeRepository->findByStateAndClient("preparation"$client)) ? false true;
  165.                 $display_emballage_par_caviste = empty($commandeRepository->findByEmballageLivraisonAndCaviste(true$client)) ? false true;  
  166.                 $display_emballage_par_mbe = empty($commandeRepository->findByEmballageLivraisonAndCaviste(false$client)) ? false true;  
  167.                 if($a_emballer_caviste) {
  168.                     $attention_emballage_par_caviste true;
  169.                 }
  170.                 if($a_preparer_collecte) {
  171.                     $attention_emballage_par_mbe true;
  172.                 }
  173.             }
  174.         }
  175.         foreach($data as $com){
  176.             $previDebut = clone $com->getDateCollecte();
  177.             $previFin = clone $com->getDateCollecte();
  178.             $creoUpdatable $com->getDateCollecte()->getTimestamp() > strtotime("+3 days");
  179.             $com->setPreviDebut($previDebut->modify("+7 days"));
  180.             $com->setPreviFin($previFin->modify("+12 days"));
  181.             $com->setcrenoUpdatable($creoUpdatable);
  182.             
  183.         }
  184.         $commandes $paginator->paginate(
  185.             $data,
  186.             $request->query->getInt('page'1),
  187.             20
  188.         );
  189.         $isIsFirstConnexion $user->isIsFirstConnexion();
  190.         $form $this->createForm(SearchType::class);
  191.         $form->handleRequest($request);
  192.         $search $request->query->get('search');
  193.         if ($search !== null && $search['recherche'] !== null) {
  194.             $data $this->utilsService->search($search['recherche'], $this->roleAdmin);
  195.             $commandesfilter $paginator->paginate(
  196.                 $data,
  197.                 $request->query->getInt('page',1),
  198.                 20
  199.             );
  200.             $returnData = [
  201.                 'commandes' => $commandesfilter,
  202.                 'packagingController' => 'emballage_tous',
  203.                 'stateController' => '',
  204.                 'user' => $this->getUser(),
  205.                 'admin' => $this->roleAdmin,
  206.                 'packing' => $needPacking,
  207.                 'collect' => $needCollect,
  208.                 'a_emballer_caviste' => $a_emballer_caviste,
  209.                 'a_preparer_collecte' => $a_preparer_collecte,
  210.                 'display_emballage_par_caviste' => $display_emballage_par_caviste,
  211.                 'display_emballage_par_mbe' => $display_emballage_par_mbe,
  212.                 'attention_emballage_par_caviste' => $attention_emballage_par_caviste,
  213.                 'attention_emballage_par_mbe' => $attention_emballage_par_mbe,
  214.                 'exportPackingClient' => $exportPackingClient,
  215.                 'exportPrepsClient' => $exportPrepsClient,
  216.                 'isFirstConnexion' => $isIsFirstConnexion,
  217.                 'searchForm' => $form,
  218.                 'searchValue' => $search['recherche'],
  219.                 'bandeau' => $this->bandeauService->displayPopup()
  220.             ];
  221.         } else {
  222.             $returnData = [
  223.                 'commandes' => $commandes,
  224.                 'packagingController' => $packaging,
  225.                 'stateController' => $state,
  226.                 'user' => $this->getUser(),
  227.                 'admin' => $this->roleAdmin,
  228.                 'packing' => $needPacking,
  229.                 'collect' => $needCollect,
  230.                 'a_emballer_caviste' => $a_emballer_caviste,
  231.                 'a_preparer_collecte' => $a_preparer_collecte,
  232.                 'display_emballage_par_caviste' => $display_emballage_par_caviste,
  233.                 'display_emballage_par_mbe' => $display_emballage_par_mbe,
  234.                 'attention_emballage_par_caviste' => $attention_emballage_par_caviste,
  235.                 'attention_emballage_par_mbe' => $attention_emballage_par_mbe,
  236.                 'exportPackingClient' => $exportPackingClient,
  237.                 'exportPrepsClient' => $exportPrepsClient,
  238.                 'isFirstConnexion' => $isIsFirstConnexion,
  239.                 'searchForm' => $form,
  240.                 'bandeau' => $this->bandeauService->displayPopup()
  241.             ];
  242.         }
  243.         if ($this->roleAdmin) {
  244.             return $this->renderForm('commande/index_admin.html.twig'$returnData);
  245.         }
  246.         return $this->renderForm('commande/index.html.twig'$returnData);
  247.     }
  248.     public function horizontalSearch($worksheet$highestColumn$colSearch$rowSearch) {
  249.         for ($column $colSearch$column != $highestColumn$column++) {
  250.             if($column != $colSearch) {
  251.                 $cell $worksheet->getCell($column.$rowSearch);
  252.                 if($cell != '') {
  253.                     if(str_starts_with($cell->getValue(), '=')) {
  254.                         return $cell->getCalculatedValue();
  255.                     }
  256.                     return $cell->getValue();
  257.                 }
  258.             }
  259.         }
  260.     }
  261.     public function verticalSearch($worksheet$highestRow$colSearch$rowSearch$type$produits) {
  262.         $values = [];
  263.         $stop false;
  264.         $prestop 0;
  265.         for ($row $rowSearch$row != $highestRow$row++) {
  266.             if(($row != $rowSearch) && !$stop) {
  267.                 $cell $worksheet->getCell($colSearch.$row);
  268.                 
  269.                 if(($type == 'destinataire') && ($cell != '')) {
  270.                     $values[] = $cell->getValue();
  271.                     $cleanValue mb_strtolower(str_replace(" """mb_convert_encoding($cell->getValue(), "UTF-8""auto")));
  272.                     if(str_starts_with($cleanValue'email:')) {
  273.                         $stop true;
  274.                     }
  275.                 }
  276.                 else { //designation
  277.                     if($cell != '') {
  278.                         $produits $this->productsSearch($worksheet$row$produits);
  279.                     }
  280.                     else {
  281.                         if($prestop == 2) { //Ligne vide après "désignation, ne pas arrêter à cet endroit
  282.                             $stop true;
  283.                         }
  284.                         $prestop++;
  285.                     }
  286.                 }
  287.             }
  288.         }
  289.         if($type == 'designation') {
  290.             return $produits;
  291.         }
  292.         return $values;
  293.     }
  294.     
  295.     public function productsSearch($worksheet$rowSearch$produits) {
  296.         $volume 'classic';
  297.         $type 'red';
  298.         $produit_nom mb_strtolower(mb_convert_encoding($worksheet->getCell('A'.$rowSearch)->getValue(), "UTF-8""auto"));
  299.         $produit_qte intval(mb_strtolower(mb_convert_encoding($worksheet->getCell('E'.$rowSearch)->getValue(), "UTF-8""auto")));
  300.         $produit_prixTotalEuros mb_strtolower(mb_convert_encoding($worksheet->getCell('G'.$rowSearch)->getCalculatedValue(), "UTF-8""auto"));
  301.         //Livraison
  302.         if (str_contains($produit_nom'transport')) {
  303.             $produits['livraison_prix'] = $produit_prixTotalEuros;
  304.             $produit_qte 0;
  305.         }
  306.         // Contenance
  307.         if (str_contains($produit_nom'1.5 l ')) {
  308.             $volume 'magnum';
  309.         }
  310.         // Type
  311.         if (str_contains($produit_nom'white ')) {
  312.             $type 'white';
  313.         }
  314.         else if (str_contains($produit_nom'sparkling ')) {
  315.             $type 'sparkling';
  316.         }
  317.         // Quantité
  318.         $produits[$volume][$type] += $produit_qte;
  319.         $produits[$volume]['total'] += $produit_qte;
  320.         
  321.         return $produits;
  322.     }
  323.     function in_array_recursive($needle$haystack$strict)
  324.     {
  325.         foreach ($haystack as $key => $element) {
  326.             
  327.             if (!is_array($element)) {
  328.                 if (strtolower($element) === strtolower($needle)) {
  329.                     return true;
  330.                 }
  331.             }
  332.             $isFound false;
  333.             if (is_array($element)) {
  334.                 $isFound $this->in_array_recursive($needle$element$strict);
  335.             }
  336.             
  337.             if ($isFound === true) {
  338.                 return $key;
  339.             }
  340.         }
  341.     
  342.         return false;
  343.     }
  344.     /* function searchForUsState($authorizedStates, $adresse, $stringSearch) {
  345.         $stringSearch = str_replace(array(", ", ","), " ", $stringSearch);
  346.         
  347.         $stringSearchClean = strtolower($stringSearch);
  348.         $explodeSeparator = '';
  349.         $adresse['ville'] = '';
  350.         $adresse['etat_us'] = '';
  351.         $adresse['province'] = '';
  352.         $adresse['zip'] = '';
  353.         $exceptionsStates[] = ['name' => 'district of columbia', 'etat_us' => 'DC', 'province' => 'District de Columbia'];
  354.         $exceptionsStates[] = ['name' => 'new hampshire', 'etat_us' => 'NH', 'province' => 'New Hampshire'];
  355.         $exceptionsStates[] = ['name' => 'new-hampshire', 'etat_us' => 'NH', 'province' => 'New Hampshire'];
  356.         $exceptionsStates[] = ['name' => 'new jersey', 'etat_us' => 'NJ', 'province' => 'New Jersey'];
  357.         $exceptionsStates[] = ['name' => 'new-jersey', 'etat_us' => 'NJ', 'province' => 'New Jersey'];
  358.         $exceptionsStates[] = ['name' => 'new mexico', 'etat_us' => 'NM', 'province' => 'Nouveau-Mexique'];
  359.         $exceptionsStates[] = ['name' => 'new-mexico', 'etat_us' => 'NM', 'province' => 'Nouveau-Mexique'];
  360.         $exceptionsStates[] = ['name' => 'new york', 'etat_us' => 'NY', 'province' => 'New York'];
  361.         $exceptionsStates[] = ['name' => 'new-york', 'etat_us' => 'NY', 'province' => 'New York'];
  362.         $exceptionsStates[] = ['name' => 'north carolina', 'etat_us' => 'NC', 'province' => 'Caroline du Nord'];
  363.         $exceptionsStates[] = ['name' => 'north-carolina', 'etat_us' => 'NC', 'province' => 'Caroline du Nord'];
  364.         $exceptionsStates[] = ['name' => 'north dakota', 'etat_us' => 'ND', 'province' => 'Dakota du Nord'];
  365.         $exceptionsStates[] = ['name' => 'north-dakota', 'etat_us' => 'ND', 'province' => 'Dakota du Nord'];
  366.         $exceptionsStates[] = ['name' => 'rhode island', 'etat_us' => 'RI', 'province' => 'Rhode Island'];
  367.         $exceptionsStates[] = ['name' => 'south carolina', 'etat_us' => 'SC', 'province' => 'Caroline du Sud'];
  368.         $exceptionsStates[] = ['name' => 'south-carolina', 'etat_us' => 'SC', 'province' => 'Caroline du Sud'];
  369.         $exceptionsStates[] = ['name' => 'south dakota', 'etat_us' => 'SD', 'province' => 'Dakota du Sud'];
  370.         $exceptionsStates[] = ['name' => 'south-dakota', 'etat_us' => 'SD', 'province' => 'Dakota du Sud'];
  371.         $exceptionsStates[] = ['name' => 'virginia', 'etat_us' => 'VA', 'province' => 'Virginie'];
  372.         $exceptionsStates[] = ['name' => 'west virginia', 'etat_us' => 'WV', 'province' => 'Virginie-Occidentale'];
  373.         $exceptionsStates[] = ['name' => 'west-virginia', 'etat_us' => 'WV', 'province' => 'Virginie-Occidentale'];
  374.         foreach ($exceptionsStates as $key => $exceptionState) {
  375.             if (str_contains($stringSearchClean, $exceptionState['name'])) {
  376.                 $explodeSeparator = $exceptionState['name'] . ' ';
  377.                 $adresse['etat_us'] = $exceptionState['etat_us'];
  378.                 $adresse['province'] = $exceptionState['province'];
  379.             }
  380.         }
  381.         if($explodeSeparator != '') {
  382.             $adressParts = explode($explodeSeparator, $stringSearchClean);
  383.             if($adressParts[0]) {
  384.                 $adresse['ville'] = $adressParts[0];
  385.             }
  386.             if($adressParts[1]) {
  387.                 $adresse['zip'] = $adressParts[1];
  388.             }
  389.         }
  390.         else {
  391.             
  392.             $pieces = explode(" ", $stringSearch);
  393.             $zip = $pieces[intval(count($pieces)) - 1];
  394.             unset($pieces[intval(count($pieces)) - 1]);
  395.             $state = $pieces[intval(count($pieces)) - 1];
  396.             unset($pieces[intval(count($pieces)) - 1]);
  397.             $town = implode(" ", $pieces);
  398.             if(is_numeric($zip)) {
  399.                 if($this->in_array_recursive($state, $authorizedStates, true)) {
  400.                     $state = $this->in_array_recursive($state, $authorizedStates, true);
  401.                 }
  402.                 if (array_key_exists($state, $authorizedStates)) {
  403.                     $adresse['zip'] = $zip;
  404.                     $adresse['etat_us'] = $state;
  405.                     $adresse['province'] = $authorizedStates[$state]['fr'];
  406.                     $adresse['ville'] = $town;
  407.                 }
  408.             }
  409.         }
  410.                 
  411.         return $adresse;
  412.     } */
  413.     function searchForUsState($authorizedStates$adresse$stringSearch) {
  414.         $stringSearch str_replace(array(", "","), " "$stringSearch);
  415.         $pieces explode(" "$stringSearch);
  416.         $adresse['ville'] = '';
  417.         $adresse['etat_us'] = '';
  418.         $adresse['province'] = '';
  419.         $adresse['zip'] = '';
  420.         
  421.         foreach($pieces as $key => $piece) {
  422.             if (array_key_exists($piece$authorizedStates)) {
  423.                 $adresse['etat_us'] = $piece;
  424.                 $adresse['province'] = $authorizedStates[$piece]['fr'];
  425.                 $adresse['found'] = true;
  426.             }
  427.             else {
  428.                 
  429.                 $hasFullnameState $this->in_array_recursive($piece$authorizedStatestrue);
  430.                 if($hasFullnameState) {
  431.                     $adresse['etat_us'] = $hasFullnameState;
  432.                     $adresse['province'] = $authorizedStates[$hasFullnameState]['fr'];
  433.                     $adresse['found'] = true;
  434.                     $hasFullnameState false;
  435.                 }
  436.                 else {
  437.                     if($adresse['found']) {
  438.                         $adresse['zip'] .= $piece .' ';
  439.                     }
  440.                     else {
  441.                         $adresse['ville'] .= $piece .' ';
  442.                     }
  443.                 }
  444.             }
  445.         }
  446.         
  447.         return $adresse;
  448.     }
  449.     /* public function explodeAdress($data) {
  450.         $authorizedStates['AL'] = ['fr'=> 'Alabama', 'en' => 'Alabama'];
  451.         $authorizedStates['AK'] = ['fr'=> 'Alaska', 'en' => 'Alaska'];
  452.         $authorizedStates['AZ'] = ['fr'=> 'Arizona', 'en' => 'Arizona'];
  453.         $authorizedStates['AR'] = ['fr'=> 'Arkansas', 'en' => 'Arkansas'];
  454.         $authorizedStates['CA'] = ['fr'=> 'Californie', 'en' => 'California'];
  455.         $authorizedStates['CO'] = ['fr'=> 'Colorado', 'en' => 'Colorado'];
  456.         $authorizedStates['CT'] = ['fr'=> 'Connecticut', 'en' => 'Connecticut'];
  457.         $authorizedStates['DE'] = ['fr'=> 'Delaware', 'en' => 'Delaware'];
  458.         $authorizedStates['DC'] = ['fr'=> 'District de Columbia', 'en' => 'District of Columbia'];
  459.         $authorizedStates['FL'] = ['fr'=> 'Floride', 'en' => 'Florida'];
  460.         $authorizedStates['GA'] = ['fr'=> 'Géorgie', 'en' => 'Georgia'];
  461.         $authorizedStates['HI'] = ['fr'=> 'Hawaii', 'en' => 'Hawaii'];
  462.         $authorizedStates['ID'] = ['fr'=> 'Idaho', 'en' => 'Idaho'];
  463.         $authorizedStates['IL'] = ['fr'=> 'Illinois', 'en' => 'Illinois'];
  464.         $authorizedStates['IN'] = ['fr'=> 'Indiana', 'en' => 'Indiana'];
  465.         $authorizedStates['IA'] = ['fr'=> 'Iowa', 'en' => 'Iowa'];
  466.         $authorizedStates['KS'] = ['fr'=> 'Kansas', 'en' => 'Kansas'];
  467.         $authorizedStates['KY'] = ['fr'=> 'Kentucky', 'en' => 'Kentucky'];
  468.         $authorizedStates['LA'] = ['fr'=> 'Louisiane', 'en' => 'Louisiana'];
  469.         $authorizedStates['ME'] = ['fr'=> 'Maine', 'en' => 'Maine'];
  470.         $authorizedStates['MD'] = ['fr'=> 'Maryland', 'en' => 'Maryland'];
  471.         $authorizedStates['MA'] = ['fr'=> 'Massachusetts', 'en' => 'Massachusetts'];
  472.         $authorizedStates['MI'] = ['fr'=> 'Michigan', 'en' => 'Michigan'];
  473.         $authorizedStates['MN'] = ['fr'=> 'Minnesota', 'en' => 'Minnesota'];
  474.         // $authorizedStates['MS'] = ['fr'=> 'Mississippi', 'en' => 'Mississippi'];
  475.         $authorizedStates['MO'] = ['fr'=> 'Missouri', 'en' => 'Missouri'];
  476.         $authorizedStates['MT'] = ['fr'=> 'Montana', 'en' => 'Montana'];
  477.         $authorizedStates['NE'] = ['fr'=> 'Nebraska', 'en' => 'Nebraska'];
  478.         $authorizedStates['NV'] = ['fr'=> 'Nevada', 'en' => 'Nevada'];
  479.         $authorizedStates['NH'] = ['fr'=> 'New Hampshire', 'en' => 'New Hampshire'];
  480.         $authorizedStates['NJ'] = ['fr'=> 'New Jersey', 'en' => 'New Jersey'];
  481.         $authorizedStates['NM'] = ['fr'=> 'Nouveau-Mexique', 'en' => 'New Mexico'];
  482.         $authorizedStates['NY'] = ['fr'=> 'New York', 'en' => 'New York'];
  483.         $authorizedStates['NC'] = ['fr'=> 'Caroline du Nord', 'en' => 'North Carolina'];
  484.         $authorizedStates['ND'] = ['fr'=> 'Dakota du Nord', 'en' => 'North Dakota'];
  485.         $authorizedStates['OH'] = ['fr'=> 'Ohio', 'en' => 'Ohio'];
  486.         $authorizedStates['OK'] = ['fr'=> 'Oklahoma', 'en' => 'Oklahoma'];
  487.         $authorizedStates['OR'] = ['fr'=> 'Oregon', 'en' => 'Oregon'];
  488.         $authorizedStates['PA'] = ['fr'=> 'Pennsylvanie', 'en' => 'Pennsylvania'];
  489.         $authorizedStates['RI'] = ['fr'=> 'Rhode Island', 'en' => 'Rhode Island'];
  490.         $authorizedStates['SC'] = ['fr'=> 'Caroline du Sud', 'en' => 'South Carolina'];
  491.         $authorizedStates['SD'] = ['fr'=> 'Dakota du Sud', 'en' => 'South Dakota'];
  492.         $authorizedStates['TN'] = ['fr'=> 'Tennessee', 'en' => 'Tennessee'];
  493.         $authorizedStates['TX'] = ['fr'=> 'Texas', 'en' => 'Texas'];
  494.         // $authorizedStates['UT'] = ['fr'=> 'Utah', 'en' => 'Utah'];
  495.         $authorizedStates['VT'] = ['fr'=> 'Vermont', 'en' => 'Vermont'];
  496.         $authorizedStates['VA'] = ['fr'=> 'Virginie', 'en' => 'Virginia'];
  497.         $authorizedStates['WA'] = ['fr'=> 'Washington', 'en' => 'Washington'];
  498.         $authorizedStates['WV'] = ['fr'=> 'Virginie-Occidentale', 'en' => 'West Virginia'];
  499.         $authorizedStates['WI'] = ['fr'=> 'Wisconsin', 'en' => 'Wisconsin'];
  500.         $authorizedStates['WY'] = ['fr'=> 'Wyoming', 'en' => 'Wyoming'];
  501.         $adresse = [];
  502.         $adresse['found'] = false;
  503.         // $adresse['adresse'] = $data['destinataire'][1];
  504.         //On regarde si la ligne suivant l'adresse comprend un US state
  505.         // $adresse = $this->searchForUsState($authorizedStates, $adresse, $data['destinataire'][3]);
  506.         // $adresse['complement'] = $data['destinataire'][2];
  507.         
  508.         // if(!$adresse['found']) {
  509.         //     $adresse = $this->searchForUsState($authorizedStates, $adresse, $data['destinataire'][2]);
  510.         //     $adresse['complement'] = '';
  511.         // } 
  512.         $reversedData = array_reverse($data['destinataire'], true);
  513.                 
  514.         // exit();
  515.         $tempName = [];
  516.         $tempAdress = [];
  517.         $tempComplement = [];
  518.         $isAdressFound = false;
  519.         foreach($reversedData as $key => $reversedLine) {
  520.             $cleanValue = strtolower(str_replace(" ", "", $reversedLine));
  521.             if(!str_starts_with($cleanValue, 'tel:') && !str_starts_with($cleanValue, 'mobile:') && !str_starts_with($cleanValue, 'email:') && !str_starts_with($cleanValue, 'etats-unis') && !str_starts_with($cleanValue, 'etats unis') && !str_starts_with($cleanValue, 'united states')) {
  522.                                
  523.                 if(!$adresse['found']) {
  524.                     $adresse = $this->searchForUsState($authorizedStates, $adresse, $reversedLine);
  525.                 }
  526.                 else {
  527.                     if(!$isAdressFound) {
  528.                         if(is_numeric($reversedLine[0])) {
  529.                             $tempAdress[$key] = $reversedLine;
  530.                             $isAdressFound = true;
  531.                         }
  532.                         else {
  533.                             $tempComplement[$key] = $reversedLine;
  534.                         }
  535.                     }
  536.                     else {
  537.                         $tempName[$key] = $reversedLine;
  538.                     }
  539.                 }
  540.                     
  541.             }
  542.         }
  543.         
  544.         $adresse['client'] = implode(", ", array_reverse($tempName, true));
  545.         $adresse['adresse'] = implode(", ", array_reverse($tempAdress, true));
  546.         $adresse['complement'] = implode(", ", array_reverse($tempComplement, true));
  547.         // exit();
  548.         return $adresse;
  549.     } */
  550.     public function explodeAdress($data) {
  551.         $authorizedStates['AL'] = ['fr'=> 'Alabama''en' => 'Alabama'];
  552.         $authorizedStates['AK'] = ['fr'=> 'Alaska''en' => 'Alaska'];
  553.         $authorizedStates['AZ'] = ['fr'=> 'Arizona''en' => 'Arizona'];
  554.         $authorizedStates['AR'] = ['fr'=> 'Arkansas''en' => 'Arkansas'];
  555.         $authorizedStates['CA'] = ['fr'=> 'Californie''en' => 'California'];
  556.         $authorizedStates['CO'] = ['fr'=> 'Colorado''en' => 'Colorado'];
  557.         $authorizedStates['CT'] = ['fr'=> 'Connecticut''en' => 'Connecticut'];
  558.         $authorizedStates['DE'] = ['fr'=> 'Delaware''en' => 'Delaware'];
  559.         $authorizedStates['DC'] = ['fr'=> 'District de Columbia''en' => 'District of Columbia'];
  560.         $authorizedStates['FL'] = ['fr'=> 'Floride''en' => 'Florida'];
  561.         $authorizedStates['GA'] = ['fr'=> 'Géorgie''en' => 'Georgia'];
  562.         $authorizedStates['HI'] = ['fr'=> 'Hawaii''en' => 'Hawaii'];
  563.         $authorizedStates['ID'] = ['fr'=> 'Idaho''en' => 'Idaho'];
  564.         $authorizedStates['IL'] = ['fr'=> 'Illinois''en' => 'Illinois'];
  565.         $authorizedStates['IN'] = ['fr'=> 'Indiana''en' => 'Indiana'];
  566.         $authorizedStates['IA'] = ['fr'=> 'Iowa''en' => 'Iowa'];
  567.         $authorizedStates['KS'] = ['fr'=> 'Kansas''en' => 'Kansas'];
  568.         $authorizedStates['KY'] = ['fr'=> 'Kentucky''en' => 'Kentucky'];
  569.         $authorizedStates['LA'] = ['fr'=> 'Louisiane''en' => 'Louisiana'];
  570.         $authorizedStates['ME'] = ['fr'=> 'Maine''en' => 'Maine'];
  571.         $authorizedStates['MD'] = ['fr'=> 'Maryland''en' => 'Maryland'];
  572.         $authorizedStates['MA'] = ['fr'=> 'Massachusetts''en' => 'Massachusetts'];
  573.         $authorizedStates['MI'] = ['fr'=> 'Michigan''en' => 'Michigan'];
  574.         $authorizedStates['MN'] = ['fr'=> 'Minnesota''en' => 'Minnesota'];
  575.         // $authorizedStates['MS'] = ['fr'=> 'Mississippi', 'en' => 'Mississippi'];
  576.         $authorizedStates['MO'] = ['fr'=> 'Missouri''en' => 'Missouri'];
  577.         $authorizedStates['MT'] = ['fr'=> 'Montana''en' => 'Montana'];
  578.         $authorizedStates['NE'] = ['fr'=> 'Nebraska''en' => 'Nebraska'];
  579.         $authorizedStates['NV'] = ['fr'=> 'Nevada''en' => 'Nevada'];
  580.         $authorizedStates['NH'] = ['fr'=> 'New Hampshire''en' => 'New Hampshire'];
  581.         $authorizedStates['NJ'] = ['fr'=> 'New Jersey''en' => 'New Jersey'];
  582.         $authorizedStates['NM'] = ['fr'=> 'Nouveau-Mexique''en' => 'New Mexico'];
  583.         $authorizedStates['NY'] = ['fr'=> 'New York''en' => 'New York'];
  584.         $authorizedStates['NC'] = ['fr'=> 'Caroline du Nord''en' => 'North Carolina'];
  585.         $authorizedStates['ND'] = ['fr'=> 'Dakota du Nord''en' => 'North Dakota'];
  586.         $authorizedStates['OH'] = ['fr'=> 'Ohio''en' => 'Ohio'];
  587.         $authorizedStates['OK'] = ['fr'=> 'Oklahoma''en' => 'Oklahoma'];
  588.         $authorizedStates['OR'] = ['fr'=> 'Oregon''en' => 'Oregon'];
  589.         $authorizedStates['PA'] = ['fr'=> 'Pennsylvanie''en' => 'Pennsylvania'];
  590.         $authorizedStates['RI'] = ['fr'=> 'Rhode Island''en' => 'Rhode Island'];
  591.         $authorizedStates['SC'] = ['fr'=> 'Caroline du Sud''en' => 'South Carolina'];
  592.         $authorizedStates['SD'] = ['fr'=> 'Dakota du Sud''en' => 'South Dakota'];
  593.         $authorizedStates['TN'] = ['fr'=> 'Tennessee''en' => 'Tennessee'];
  594.         $authorizedStates['TX'] = ['fr'=> 'Texas''en' => 'Texas'];
  595.         // $authorizedStates['UT'] = ['fr'=> 'Utah', 'en' => 'Utah'];
  596.         $authorizedStates['VT'] = ['fr'=> 'Vermont''en' => 'Vermont'];
  597.         $authorizedStates['VA'] = ['fr'=> 'Virginie''en' => 'Virginia'];
  598.         $authorizedStates['WA'] = ['fr'=> 'Washington''en' => 'Washington'];
  599.         $authorizedStates['WV'] = ['fr'=> 'Virginie-Occidentale''en' => 'West Virginia'];
  600.         $authorizedStates['WI'] = ['fr'=> 'Wisconsin''en' => 'Wisconsin'];
  601.         $authorizedStates['WY'] = ['fr'=> 'Wyoming''en' => 'Wyoming'];
  602.         $adresse = [];
  603.         $adresse['found'] = false;
  604.         // $adresse['adresse'] = $data['destinataire'][1];
  605.         //On regarde si la ligne suivant l'adresse comprend un US state
  606.         /* $adresse = $this->searchForUsState($authorizedStates, $adresse, $data['destinataire'][3]);
  607.         $adresse['complement'] = $data['destinataire'][2];
  608.         
  609.         if(!$adresse['found']) {
  610.             $adresse = $this->searchForUsState($authorizedStates, $adresse, $data['destinataire'][2]);
  611.             $adresse['complement'] = '';
  612.         } */
  613.         $reversedData array_reverse($data['destinataire'], true);
  614.         $tempName = [];
  615.         $tempAdress = [];
  616.         $tempComplement = [];
  617.         $isAdressFound false;
  618.         foreach($reversedData as $key => $reversedLine) {
  619.             $cleanValue strtolower(str_replace(" """$reversedLine));
  620.             if(!str_starts_with($cleanValue'tel:') && !str_starts_with($cleanValue'mobile:') && !str_starts_with($cleanValue'email:') && !str_starts_with($cleanValue'etats-unis') && !str_starts_with($cleanValue'etats unis') && !str_starts_with($cleanValue'united states')) {
  621.                
  622.                 if(!$adresse['found']) {
  623.                     $adresse $this->searchForUsState($authorizedStates$adresse$reversedLine);
  624.                 }
  625.                 else {
  626.                     if(!$isAdressFound) {
  627.                         if(is_numeric($reversedLine[0])) {
  628.                             $tempAdress[$key] = $reversedLine;
  629.                             $isAdressFound true;
  630.                         }
  631.                         else {
  632.                             $tempComplement[$key] = $reversedLine;
  633.                         }
  634.                     }
  635.                     else {
  636.                         $tempName[$key] = $reversedLine;
  637.                     }
  638.                 }
  639.                     
  640.             }
  641.         }
  642.         $adresse['client'] = implode(", "array_reverse($tempNametrue));
  643.         $adresse['adresse'] = implode(", "array_reverse($tempAdresstrue));
  644.         $adresse['complement'] = implode(", "array_reverse($tempComplementtrue));
  645.         return $adresse;
  646.     }
  647.     public function create_via_import(ClientRepository $clientRepositoryCommandeRepository $commandeRepository)//: Response
  648.     {
  649.         $em $this->getDoctrine()->getManager();
  650.         $path 'xdeUEDJuejUDEiduhEDIOehdEUDHe/';
  651.         
  652.         $createCommandeResponse['errorFound'] = false;
  653.         $createCommandeResponse['errorDetails'] = '';
  654.         $createCommandeResponse['excelFilePath'] = [];
  655.         foreach(glob($path.'*.xls') as $file) {
  656.             $erreur '';
  657.             $originalFile str_replace($path""$file);
  658.             $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
  659.             $reader->setReadDataOnly(true);
  660.             $spreadsheet $reader->load($file);
  661.     
  662.             $worksheet $spreadsheet->getActiveSheet();
  663.     
  664.             $highestRow $worksheet->getHighestRow();
  665.             $highestColumn $worksheet->getHighestColumn();
  666.             $highestColumn++;
  667.     
  668.             $data = [];
  669.             $produits = [];
  670.             $produits['livraison_prix'] = 0;
  671.             $produits['classic']['red'] = 0;
  672.             $produits['classic']['white'] = 0;
  673.             $produits['classic']['sparkling'] = 0;
  674.             $produits['classic']['total'] = 0;
  675.             $produits['magnum']['red'] = 0;
  676.             $produits['magnum']['white'] = 0;
  677.             $produits['magnum']['sparkling'] = 0;
  678.             $produits['magnum']['total'] = 0;
  679.     
  680.     
  681.             for ($column 'A'$column != $highestColumn$column++) {
  682.     
  683.                 for ($row 1$row <= $highestRow$row++) {
  684.                     $cell $worksheet->getCell($column.$row);
  685.     
  686.                     if($column.$row == 'A1') {
  687.                         $data['caviste'] = $cell->getValue();
  688.                     }
  689.                     else {
  690.                         $cleanValue mb_strtolower(str_replace(" """mb_convert_encoding($cell->getValue(), "UTF-8""auto")));
  691.                         if(str_starts_with($cleanValue'facturen')) {
  692.                             $data['facture'] = $this->horizontalSearch($worksheet$highestColumn$column$row);
  693.                         }
  694.                         else if(str_starts_with($cleanValue'date:')) {
  695.                             $data['date'] = $this->horizontalSearch($worksheet$highestColumn$column$row);
  696.                         }
  697.                         else if(str_starts_with($cleanValue'dateexpeditionsouhaitee:')) {
  698.                             $data['date_expedition'] = $this->horizontalSearch($worksheet$highestColumn$column$row);
  699.                         }
  700.                         else if(str_starts_with($cleanValue'totaleuros')) {
  701.                             $data['total_euros'] = $this->horizontalSearch($worksheet$highestColumn$column$row);
  702.                         }
  703.                         else if(str_starts_with($cleanValue'consignee/')) {
  704.                             $data['destinataire'] = $this->verticalSearch($worksheet$highestRow$column$row'destinataire'false);
  705.                         }
  706.                         else if(str_starts_with($cleanValue'désignation')) {
  707.                             $produits $this->verticalSearch($worksheet$highestRow$column$row'designation'$produits);
  708.                         }
  709.                     }
  710.                 }
  711.             }
  712.             $data['telephone'] = '';
  713.             $data['email'] = '';
  714.             foreach($data['destinataire'] as $data_dest) {
  715.                 $cleanValue strtolower(str_replace(" """$data_dest));
  716.                 if(str_starts_with($cleanValue'tel:') || str_starts_with($cleanValue'mobile:')) { 
  717.                     $infos_tel explode(":"$data_dest);
  718.                     $data['telephone'] = $infos_tel[1];
  719.                 }
  720.                 else if(str_starts_with($cleanValue'email:')) {
  721.                     $infos_email explode(":"$data_dest);
  722.                     $data['email'] = $infos_email[1];
  723.                 }
  724.             }
  725.             
  726.             if($data['caviste'] == 'Ets MARTIN') { //ETSM - ETS MARTIN
  727.                 $client $clientRepository->find(295);
  728.             }
  729.             else if($data['caviste'] == 'La Grande Cave de Saint Emilion') { //ETSM - LGC
  730.                 $client $clientRepository->find(296);
  731.             }
  732.             else { //ETSM - BX CLASSIQUE
  733.                 $client $clientRepository->find(320);
  734.             }
  735.             
  736.             $adress $this->explodeAdress($data);
  737.             $now = new DateTime('now', new DateTimeZone('Europe/Paris'));
  738.             $nombreBouteillesTotal $produits['classic']['total'] + ($produits['magnum']['total'] * 2);
  739.             $nombre_colis_total 0
  740.     
  741.             $cmdFacture $commandeRepository->findOneBy([
  742.                 'numeroFacture' => $data['facture'],
  743.                 'client' => $client,
  744.             ]);              
  745.             
  746.             $erreur .= $this->searchError(
  747.                 $adress['client'],
  748.                 $data['telephone'],
  749.                 $data['email'],
  750.                 $data['facture'],
  751.                 $data['total_euros'],
  752.                 $adress['zip'],
  753.                 $adress['ville'],
  754.                 $adress['adresse'],
  755.                 $adress['etat_us'],
  756.                 $cmdFacture,
  757.                 $originalFile,
  758.                 false
  759.             );
  760.             if($erreur == '') {
  761.                 $commande = new Commande();
  762.     
  763.                 $stop false;
  764.                 while($stop == false) {
  765.         
  766.                     $colis = new Colis();
  767.         
  768.                     if($nombreBouteillesTotal 12 >= 0) {
  769.                         $nombreBouteillesTotal $nombreBouteillesTotal 12;
  770.                         $colis->setNombreBouteille(12);
  771.         
  772.                         //Si il ne reste plus de bouteilles, on sort
  773.                         if($nombreBouteillesTotal == 0) {
  774.                             $stop true;
  775.                         }
  776.                     }
  777.                     else {
  778.                         //add 1 colis de nombreBouteilles
  779.                         $colis->setNombreBouteille($nombreBouteillesTotal);
  780.                         $stop true;
  781.                     }
  782.         
  783.                     $colis->setCommande($commande);
  784.                     $em->persist($colis);
  785.         
  786.                     $commande->addColi($colis);
  787.                     $nombre_colis_total++;
  788.         
  789.                 }
  790.                 $commande->setNombreColisTotal($nombre_colis_total);
  791.                 $commande->setClient($client);
  792.             
  793.                     $clientFinal = new ClientFinal();
  794.                     $clientFinal->setEmail($data['email']);
  795.                     $clientFinal->setTelephone($data['telephone']);
  796.                     $clientFinal->setCommande($commande);
  797.                     $clientFinal->setFullName($adress['client']);
  798.                 $commande->setClientFinal($clientFinal);
  799.                 
  800.                 $commande->setAssuranceLivraison($client->isAssuranceDefaut());
  801.                 $commande->setEmballageLivraison($client->isEmballageDefaut());
  802.                 $commande->setNumeroFacture($data['facture']);
  803.                 $commande->setMontantTotalFacture($data['total_euros'] - $produits['livraison_prix']);
  804.                 $commande->setCodePostalLivraison($adress['zip']);
  805.                 $commande->setVilleLivraison($adress['ville']);
  806.                 $commande->setAdresseLivraison($adress['adresse']);
  807.                 $commande->setComplementAdresseLivraison($adress['complement']);
  808.                 $commande->setProvince($adress['province']);
  809.                 $commande->setEtatUs($adress['etat_us']);
  810.                 $commande->setDateCommandeSoumission($now);
  811.                 $commande->setFedexPdfGenerated(false);
  812.                 $commande->setFedexPdfAvailable(false);
  813.                 $commande->setIsTemporaire(false);
  814.                 $commande->setIsValideeParClient(true);
  815.         
  816.                 // if($client->isEmballageDefaut() == true) {
  817.                 //     $commande->setState('emballage_caviste');
  818.                 // }
  819.                 // else {
  820.                 //     $commande->setState('preparation');
  821.                 // } 
  822.                 
  823.                 $commande->setState('attente_pec_transporteur');
  824.                 
  825.                 $dateCollecte $this->createDateCollecte($now$data['date_expedition']);
  826.                 // $nowClone = clone $now; 
  827.                 // $dateMin = $nowClone->modify("+1 days");
  828.                 // $dateMinDay = $dateMin->format('l');
  829.                 
  830.                 // //Si la date minimum tombe un week-end, on inclut le we dans les jours où on ne peut pas accepter de collecte
  831.                 // if($dateMinDay == 'Saturday') {
  832.                 //     $dateMin->modify("+2 days");
  833.                 //     $dateMinDay = $dateMin->format('l');
  834.                 // }
  835.                 // if($dateMinDay == 'Sunday') {
  836.                 //     $dateMin->modify("+1 days");
  837.                 //     $dateMinDay = $dateMin->format('l');
  838.                 // }
  839.                 // //On stocke la valeur de cette date min pour comparaison
  840.                 // $dateMinCompare = $dateMin->format('Y-m-d');
  841.                 
  842.                 // if($data['date_expedition']) {
  843.                 //     $date = str_replace("/","-", htmlspecialchars($data['date_expedition']));
  844.                 //     $dateSaisie = date('Y-m-d', strtotime($date));
  845.                 //     if($dateSaisie < $dateMinCompare) {
  846.                 //         $dateSaisie = $dateMinCompare;
  847.                 //     }
  848.                 // }
  849.                 // else {
  850.                 //     $dateSaisie = $dateMinCompare;
  851.                 // }
  852.                 
  853.                 // $dateCollecte = new DateTime($dateSaisie);
  854.                 
  855.                 $commande->setDateCollecte($dateCollecte);
  856.         
  857.                 $commande->setNombreBouteilleRouge($produits['classic']['red']);
  858.                 $commande->setNombreBouteilleBlanc($produits['classic']['white']);
  859.                 $commande->setNombreBouteillePetillant($produits['classic']['sparkling']);
  860.                 $commande->setNombreMagnumRouge($produits['magnum']['red']);
  861.                 $commande->setNombreMagnumBlanc($produits['magnum']['white']);
  862.                 $commande->setNombreMagnumPetillant($produits['magnum']['sparkling']);
  863.                 $commande->setToken('gsrefgrdsgfres');
  864.                 $commande->setFastPickup(true);
  865.                 // commande_massive 
  866.                 if($nombreBouteillesTotal 36) {
  867.                     $commande->setCommandeMassive(true);
  868.                     $this->emailGeneratorService->sendMassiveCommande($commande);
  869.                 }
  870.                 else {
  871.                     $commande->setCommandeMassive(false);
  872.                 }
  873.         
  874.                 //On change le fichier de dossier, vers upload_Hk2DvAtDeUccGXh
  875.                 $newPath 'upload_Hk2DvAtDeUccGXh/' $originalFile;
  876.                 $commande->setFichierFacture($originalFile);
  877.                 // $cmdFacture = $commandeRepository->findOneByNumeroFacture($data['facture']);    
  878.                 $cmdFacture $commandeRepository->findOneBy([
  879.                     'numeroFacture' => $data['facture'],
  880.                     'client' => $client,
  881.                 ]);              
  882.                 if($cmdFacture == null){
  883.                     $em->persist($clientFinal);
  884.                     $em->persist($commande);
  885.                     $em->flush();                    
  886.                 }
  887.             }
  888.             else {
  889.                 //On change le fichier de dossier, vers upload_commande_error_ad41Ig7A4ZBd7S7
  890.                 $newPath 'upload_commande_error_ad41Ig7A4ZBd7S7/' $originalFile;
  891.                 $createCommandeResponse['errorFound'] = true;
  892.                 $createCommandeResponse['errorDetails']  .= $erreur;
  893.                 $createCommandeResponse['excelFilePath'][] = $newPath;
  894.                 
  895.                 // $rapportErreur .= $erreur . ' La commande n\'a pas pu être générée.<br/>';
  896.             }
  897.             
  898.             rename($file$newPath);
  899.         }
  900.         return $createCommandeResponse;
  901.     }
  902.     public function searchError($fullName$telephone$email$numeroFacture$totalEuros$codePostal$ville$adresse$etatUs$cmdFacture$originalFile$sameCustomer ){
  903.         
  904.         $erreur "";
  905.         switch (true) {
  906.             case $fullName == '':
  907.                 $erreur .= 'Le <strong>nom du client</strong> du document "' $originalFile '" n\'est pas renseigné correctement.<br/>';
  908.                 break;
  909.             case $telephone == '':
  910.                 $erreur .= 'Le <strong>numéro de téléphone</strong> du document "' $originalFile '" n\'est pas renseigné correctement.<br/>';
  911.                 break;
  912.             case $email == '':
  913.                 $erreur .= 'L\' <strong>adresse mail</strong> du document "' $originalFile '" n\'est pas renseignée correctement.<br/>';
  914.                 break;
  915.             case $numeroFacture == '':
  916.                 $erreur .= 'Le <strong>numéro de facture</strong> du document "' $originalFile '" n\'est pas renseigné correctement.<br/>';
  917.                 break;
  918.             case $totalEuros == '':
  919.                 $erreur .= 'Le <strong>montant total en euros</strong> du document "' $originalFile '" n\'est pas renseigné correctement.<br/>';
  920.                 break;
  921.             case $codePostal == '':
  922.                 $erreur .= 'Le <strong>code postal de livraison</strong> du document "' $originalFile '" n\'est pas renseigné correctement.<br/>';
  923.                 break;
  924.             case $ville == '':
  925.                 $erreur .= 'La <strong>ville de livraison</strong> du document "' $originalFile '" n\'est pas renseignée correctement.<br/>';
  926.                 break;
  927.             case $adresse == '':
  928.                 $erreur .= 'L\' <strong>adresse de livraison</strong> du document "' $originalFile '" n\'est pas renseignée correctement.<br/>';
  929.                 break;
  930.             case $etatUs == '':
  931.                 $erreur .= 'L\' <strong>État de livraison</strong> du document "' $originalFile '" n\'est pas renseigné correctement.<br/>';
  932.                 break;
  933.         }
  934.         if($sameCustomer == false){
  935.             if($cmdFacture != null){
  936.                 $erreur .= 'Le numéro de facture : '$numeroFacture .'</strong> du document "' $originalFile '" est déjà présent dans la base de données pour ce client.<br/>';
  937.             }
  938.         }
  939.         return $erreur;
  940.     }
  941.     public function createDateCollecte($now$dateExpedition){
  942.         $nowClone = clone $now
  943.         $dateMin $nowClone->modify("+1 days");
  944.         $dateMinDay $dateMin->format('l');
  945.         
  946.         //Si la date minimum tombe un week-end, on inclut le we dans les jours où on ne peut pas accepter de collecte
  947.         if($dateMinDay == 'Saturday') {
  948.             $dateMin->modify("+2 days");
  949.             $dateMinDay $dateMin->format('l');
  950.         }
  951.         if($dateMinDay == 'Sunday') {
  952.             $dateMin->modify("+1 days");
  953.             $dateMinDay $dateMin->format('l');
  954.         }
  955.         //On stocke la valeur de cette date min pour comparaison
  956.         $dateMinCompare $dateMin->format('Y-m-d');
  957.         
  958.         if($dateExpedition != null) {
  959.             $date str_replace("/","-"htmlspecialchars($dateExpedition));
  960.             $dateSaisie date('Y-m-d'strtotime($date));
  961.             if($dateSaisie $dateMinCompare) {
  962.                 $dateSaisie $dateMinCompare;
  963.             }
  964.         }
  965.         else {
  966.             $dateSaisie $dateMinCompare;
  967.         }
  968.         
  969.         $dateCollecte = new DateTime($dateSaisie);
  970.         return $dateCollecte;
  971.     }            
  972.     public function create_via_import_idealwine(ClientRepository $clientRepositoryCommandeRepository $commandeRepository)//: Response
  973.     {
  974.         ini_set('memory_limit''800M');
  975.         $em $this->getDoctrine()->getManager();
  976.         $path 'VK74QTZTBQax9SkdDuax/';
  977.         
  978.         $createCommandeResponse['errorFound'] = false;
  979.         $createCommandeResponse['errorDetails'] = '';
  980.         $createCommandeResponse['excelFilePath'] = [];
  981.         $erreur '';
  982.         // echo '<pre>';
  983.         foreach(glob($path.'*.xlsx') as $file) {
  984.             
  985.             // var_dump($file);
  986.             $originalFile str_replace($path""$file);
  987.             $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
  988.             $reader->setReadDataOnly(true);
  989.             $spreadsheet $reader->load($file);
  990.     
  991.             $worksheet $spreadsheet->getActiveSheet();            
  992.             // Tableau pour stocker les fullNames déjà traités
  993.             $fullNameProcessed = [];
  994.             $newPath null;
  995.             // Parcourir chaque ligne (sauter la première ligne d'en-tête)
  996.             foreach ($worksheet->getRowIterator(2) as $row) {
  997.                 $cellIterator $row->getCellIterator();
  998.                 $cellIterator->setIterateOnlyExistingCells(false); // Permet de lire toutes les cellules, même vides
  999.                 
  1000.                 // Récupération du client IDEALWINE
  1001.                 $client $clientRepository->find(309);
  1002.                 $commande = new Commande();
  1003.                 // Récupérer les valeurs des colonnes
  1004.                 $numeroFacture $worksheet->getCellByColumnAndRow(3$row->getRowIndex())->getValue() ?? '';
  1005.                 $fullName trim($worksheet->getCellByColumnAndRow(5$row->getRowIndex())->getValue()) ?? '';
  1006.                 if(!($fullName == "" && $numeroFacture == "")){
  1007.                     if (!in_array($fullName$fullNameProcessed)) {
  1008.                         $observation $worksheet->getCellByColumnAndRow(7$row->getRowIndex())->getValue() ?? '';
  1009.                         $codePostal trim($worksheet->getCellByColumnAndRow(9$row->getRowIndex())->getValue()) ?? '';
  1010.                         $ville trim($worksheet->getCellByColumnAndRow(8$row->getRowIndex())->getValue()) ?? '';
  1011.                         $etatUs $worksheet->getCellByColumnAndRow(10$row->getRowIndex())->getValue() ?? '';
  1012.                         $adresse trim($worksheet->getCellByColumnAndRow(6$row->getRowIndex())->getValue()) ?? '';
  1013.                         $telephone $worksheet->getCellByColumnAndRow(12$row->getRowIndex())->getValue() ?? '';
  1014.                         $email trim($worksheet->getCellByColumnAndRow(13$row->getRowIndex())->getValue()) ?? '';
  1015.                         $nombreColisSouhaite $worksheet->getCellByColumnAndRow(17$row->getRowIndex())->getValue() ?? 0;
  1016.                         $totalEuros $worksheet->getCellByColumnAndRow(18$row->getRowIndex())->getValue() ?? 0;
  1017.                         $rouge $worksheet->getCellByColumnAndRow(14$row->getRowIndex())->getValue() ?? 0;
  1018.                         $rougeMagnum $worksheet->getCellByColumnAndRow(15$row->getRowIndex())->getValue() ?? 0;
  1019.                         $autre $worksheet->getCellByColumnAndRow(16$row->getRowIndex())->getValue() ?? 0;
  1020.         
  1021.                         $rouge intval($rouge) + intval($autre);
  1022.         
  1023.                         // ON VERIFIE S'IL Y A 
  1024.                         $worksheetInterne $spreadsheet->getActiveSheet();
  1025.                         
  1026.                         // Variable pour detecter si plusieurs lignes du même client
  1027.                         $sameCustomer=false;
  1028.                         $same false;
  1029.                         foreach ($worksheetInterne->getRowIterator(2) as $rowInterne) {
  1030.                             $cellIteratorInterne $rowInterne->getCellIterator();
  1031.                             $cellIteratorInterne->setIterateOnlyExistingCells(false); // Permet de lire toutes les cellules, même vides
  1032.         
  1033.                             $fullNameInterne trim($worksheet->getCellByColumnAndRow(5$rowInterne->getRowIndex())->getValue());                        
  1034.                             if($fullNameInterne == $fullName){                            
  1035.                                 // Permet juste de pas prendre la première occurence car c'est la même ligne. 
  1036.                                 if($same){
  1037.                                     $rougeInterne $worksheetInterne->getCellByColumnAndRow(14$rowInterne->getRowIndex())->getValue() ?? 0;
  1038.                                     $rougeMagnumInterne $worksheetInterne->getCellByColumnAndRow(15$rowInterne->getRowIndex())->getValue() ?? 0;
  1039.                                     $autreInterne $worksheetInterne->getCellByColumnAndRow(16$rowInterne->getRowIndex())->getValue() ?? 0;
  1040.                                     $numeroFactureInterne $worksheetInterne->getCellByColumnAndRow(3$rowInterne->getRowIndex())->getValue() ?? '';
  1041.                                     $nombreColisSouhaiteInterne $worksheetInterne->getCellByColumnAndRow(17$rowInterne->getRowIndex())->getValue() ?? 0;
  1042.                                     $totalEurosInterne $worksheetInterne->getCellByColumnAndRow(18$rowInterne->getRowIndex())->getValue() ?? 0;
  1043.                                     // On additionne avec les autres
  1044.                                     $rouge intval($rougeInterne) + intval($autreInterne) + intval($rouge);
  1045.                                     $rougeMagnum intval($rougeMagnumInterne) + intval($rougeMagnumInterne);      
  1046.                                     $nombreColisSouhaite intval($nombreColisSouhaiteInterne) + $nombreColisSouhaite;      
  1047.                                     $numeroFacture .= ", ".$numeroFactureInterne;   
  1048.                                     $totalEuros floatval($totalEuros)  + floatval($totalEurosInterne);
  1049.                                     $sameCustomer=true;           
  1050.                                 }
  1051.                                 $same true;              
  1052.                             }
  1053.         
  1054.                         }
  1055.                         // Stocker le fullName dans le tableau pour éviter les doublons
  1056.                         $fullNameProcessed[] = $fullName;
  1057.         
  1058.                         // var_dump("-------------------------");
  1059.                         // var_dump($numeroFacture);
  1060.                         // var_dump($fullName);
  1061.                         // var_dump($observation);
  1062.                         // var_dump($codePostal);
  1063.                         // var_dump($ville);
  1064.                         // var_dump($etatUs);
  1065.                         // var_dump($adresse);
  1066.                         // var_dump($telephone);
  1067.                         // var_dump($email);
  1068.                         // var_dump($totalEuros);
  1069.                         // var_dump("Nombre de colis souhaité : ".$nombreColisSouhaite);
  1070.                         // var_dump("Nombre de bouteilles : ".$rouge);
  1071.                         // var_dump("Nombre de magnum : ".$rougeMagnum);
  1072.                         // var_dump("-------------------------");
  1073.         
  1074.                         $cmdFacture null;
  1075.                         if($numeroFacture != ""){
  1076.                             $cmdFacture $commandeRepository->findOneBy([
  1077.                                 'numeroFacture' => $numeroFacture,
  1078.                                 'client' => $client,
  1079.                             ]);   
  1080.                         }
  1081.         
  1082.                         /************************************
  1083.                          * TEST SI UNE ERREUR DANS LA LIGNE *
  1084.                          ************************************/
  1085.                         $erreur .= $this->searchError(
  1086.                             $fullName
  1087.                             $telephone
  1088.                             $email
  1089.                             $numeroFacture
  1090.                             $totalEuros
  1091.                             $codePostal
  1092.                             $ville
  1093.                             $adresse
  1094.                             $etatUs
  1095.                             $cmdFacture
  1096.                             $originalFile,
  1097.                             $sameCustomer
  1098.                         );
  1099.         
  1100.         
  1101.                         if($erreur == '') {
  1102.         
  1103.                             // FOREACH POUR GENERATION COLIS
  1104.                             $rougeMagnumDouble intval($rougeMagnum) + intval($rougeMagnum);
  1105.                             $nombreBouteillesTotal intval($rouge) + $rougeMagnumDouble;
  1106.         
  1107.                             $repartitionColis $this->repartirBouteillesEnColis($nombreBouteillesTotal$nombreColisSouhaite);
  1108.                             
  1109.                             // var_dump($repartitionColis);
  1110.         
  1111.                             foreach ($repartitionColis as $keyColis => $valueColis) {
  1112.                                 $colis = new Colis();
  1113.                                 $colis->setNombreBouteille($valueColis);
  1114.                                 $em->persist($colis);
  1115.                 
  1116.                                 $commande->addColi($colis);
  1117.                             }
  1118.                             
  1119.         
  1120.                             $commande->setClient($client);
  1121.         
  1122.                             // Configurer les objets Commande et ClientFinal
  1123.                             $commande->setEtatUs($etatUs);
  1124.                             $commande->setProvince($this->utilsService->getProvinceByEtatUs($etatUs));
  1125.                             $commande->setNumeroFacture($numeroFacture);
  1126.                             $commande->setNombreColisTotal(sizeof($repartitionColis));
  1127.                             $commande->setMontantTotalFacture($totalEuros);
  1128.                             $commande->setCodePostalLivraison($codePostal);
  1129.                             $commande->setVilleLivraison($ville);
  1130.                             $commande->setAdresseLivraison($adresse);
  1131.                             $commande->setObservation($observation);
  1132.         
  1133.                             $clientFinal = new ClientFinal();
  1134.                                 $clientFinal->setFullName($fullName);
  1135.                                 $clientFinal->setEmail($email);
  1136.                                 $clientFinal->setTelephone($telephone);
  1137.                                 $clientFinal->setCommande($commande);
  1138.                             $commande->setClientFinal($clientFinal);
  1139.         
  1140.                             // Paramètres supplémentaires
  1141.                             $now = new DateTime('now', new DateTimeZone('Europe/Paris'));
  1142.         
  1143.                             $commande->setAssuranceLivraison($client->isAssuranceDefaut());
  1144.                             $commande->setEmballageLivraison($client->isEmballageDefaut());
  1145.                             $commande->setDateCommandeSoumission($now);
  1146.                             $commande->setFedexPdfGenerated(false);
  1147.                             $commande->setFedexPdfAvailable(false);
  1148.                             $commande->setIsTemporaire(false);
  1149.                             $commande->setIsValideeParClient(true);
  1150.                             $commande->setToken('gsrefgrdsgfres');
  1151.                             $commande->setFastPickup(true);
  1152.         
  1153.                             // Gestion de l'état selon l'emballage
  1154.                             // if ($client->isEmballageDefaut() == true) {
  1155.                             //     $commande->setState('emballage_caviste');
  1156.                             // } else {
  1157.                             //     $commande->setState('preparation');
  1158.                             // }
  1159.         
  1160.                             $commande->setState('attente_pec_transporteur');                    
  1161.         
  1162.                             $dateCollecte $this->createDateCollecte($nownull);
  1163.         
  1164.                             $commande->setDateCollecte($dateCollecte);
  1165.         
  1166.                             // Quantité des bouteilles
  1167.                             $commande->setNombreBouteilleRouge($rouge);
  1168.                             $commande->setNombreBouteilleBlanc(0);
  1169.                             $commande->setNombreBouteillePetillant(0);
  1170.                             $commande->setNombreMagnumRouge($rougeMagnum);
  1171.                             $commande->setNombreMagnumBlanc(0);
  1172.                             $commande->setNombreMagnumPetillant(0);
  1173.         
  1174.                             // Gestion des commandes massives
  1175.                             if ($nombreBouteillesTotal 36) {
  1176.                                 $commande->setCommandeMassive(true);
  1177.                                 $this->emailGeneratorService->sendMassiveCommande($commande);
  1178.                             } else {
  1179.                                 $commande->setCommandeMassive(false);
  1180.                             }                            
  1181.                             $commande->setFichierFacture($originalFile);
  1182.         
  1183.                             // Persister les objets
  1184.                             $em->persist($clientFinal);
  1185.                             $em->persist($commande);
  1186.                             // Flusher à la fin de la boucle
  1187.                             $em->flush();  
  1188.                         }else{
  1189.         
  1190.                             $createCommandeResponse['errorFound'] = true;
  1191.                             $createCommandeResponse['errorDetails']  .= $erreur;
  1192.                             // $createCommandeResponse['excelFilePath'][] = $newPath;
  1193.                             $createCommandeResponse['excelFilePath'][] = "";
  1194.                         }                
  1195.                     }
  1196.                 }
  1197.             }    
  1198.             
  1199.             //On change le fichier de dossier, vers upload_Hk2DvAtDeUccGXh
  1200.             $newPath 'upload_Hk2DvAtDeUccGXh/' $originalFile;
  1201.             rename($file$newPath);
  1202.             
  1203.         }
  1204.         // var_dump($createCommandeResponse);
  1205.         // echo '</pre>';        
  1206.         return $createCommandeResponse;
  1207.     }    
  1208.     function repartirBouteillesEnColis($nombreBouteilles$nombreColisSouhaite) {
  1209.         
  1210.         // Maximum de bouteilles par colis
  1211.         $maxBouteillesParColis 12;
  1212.         
  1213.         // Si le nombre de colis souhaité ne peut pas respecter la contrainte des 12 bouteilles max
  1214.         if ($nombreColisSouhaite $maxBouteillesParColis $nombreBouteilles) {
  1215.             // Calculer le nombre minimal de colis requis pour respecter la contrainte de 12 bouteilles max
  1216.             $nombreColisRequis ceil($nombreBouteilles $maxBouteillesParColis);            
  1217.             $nombreColisSouhaite $nombreColisRequis;
  1218.         }
  1219.         
  1220.         // Tableau pour stocker la répartition des bouteilles par colis
  1221.         $repartition = [];
  1222.     
  1223.         // Calcul de la répartition équitable
  1224.         $bouteillesParColis floor($nombreBouteilles $nombreColisSouhaite); // Répartition équitable dans chaque colis
  1225.         $resteBouteilles $nombreBouteilles $nombreColisSouhaite// Bouteilles restantes à répartir
  1226.     
  1227.         // Ajouter les bouteilles à chaque colis
  1228.         for ($i 0$i $nombreColisSouhaite$i++) {
  1229.             // Si il reste des bouteilles à répartir, on en ajoute 1 supplémentaire dans les premiers colis
  1230.             if ($resteBouteilles 0) {
  1231.                 $repartition[] = $bouteillesParColis 1;
  1232.                 $resteBouteilles--;
  1233.             } else {
  1234.                 $repartition[] = $bouteillesParColis;
  1235.             }
  1236.         }
  1237.     
  1238.         return $repartition;
  1239.     }
  1240.     /**
  1241.      * @Route("/kdioejfeiofjeiofesjf", name="app_commande_kdioejfeiofjeiofesjf", methods={"GET", "POST"})
  1242.      */
  1243.     public function kdioejfeiofjeiofesjf(Request $request): Response{
  1244.         set_time_limit(6000);
  1245.         // $csvPath = $this->getParameter('kernel.project_dir') . '/public/mbe_taxe.csv';
  1246.         $csvPath $this->getParameter('kernel.project_dir') . '/public/mbe_taxe_en_test.csv';
  1247.         if (!file_exists($csvPath)) {
  1248.             return new Response('Fichier non trouvé.'404);
  1249.         }
  1250.         echo '<pre>';
  1251.         $rows = [];
  1252.         if (($handle fopen($csvPath'r')) !== false) {
  1253.             $header fgetcsv($handle0";");
  1254.             $i=0;
  1255.             $errorMails null;
  1256.             while (($data fgetcsv($handle0";")) !== false) {
  1257.                 if($i>=&& $i<82){
  1258.                     $i++;
  1259.                     
  1260.                     if (isset($data[11])) {
  1261.                         // 1. Remplacer espaces multiples par un seul
  1262.                         $data[11] = preg_replace('/\s+/'' '$data[11]);
  1263.                         // 2. Supprimer les espaces au début/fin
  1264.                         $data[11] = trim($data[11]);
  1265.                     }
  1266.                     
  1267.                     $send $data[14];
  1268.                     if($send != "ok"){
  1269.                         try {
  1270.                             $res $this->emailGeneratorService->sendEmailTaxe($data);
  1271.                             if ($res) {
  1272.                                 // $success++;
  1273.                             } else {
  1274.                                 // $fail++;
  1275.                                 $errorMails[] = $data[8]; // ou ce qui correspond à l'email
  1276.                             }
  1277.                         } catch (\Exception $e) {
  1278.                             // $fail++;
  1279.                             // $errorMails[] = $data[8];
  1280.                             $errorMails[] = [
  1281.                                 'email' => $data[8],
  1282.                                 'error' => $e->getMessage()
  1283.                             ];
  1284.                             // log $e->getMessage();
  1285.                         }                    
  1286.                         // $res = $this->emailGeneratorService->sendEmailTaxe($data);
  1287.         
  1288.                         $deliveryDate   $data[0]; // Delivery Date
  1289.                         $chateauName    $data[1]; // Château Name
  1290.                         $recipientName  $data[2]; // Recipient's Name
  1291.                         $cp             $data[3]; // cp
  1292.                         $ville          $data[4]; // ville
  1293.                         $deliveryAddr   $data[5]; // Delivery Address
  1294.                         $etat           $data[6]; // etat
  1295.                         $trackingNumber $data[7]; // Tracking Number
  1296.                         $email          $data[8]; 
  1297.                         $phone          $data[9]; // Téléphone
  1298.                         $montant        $data[10]; // $XXX
  1299.                         $proforma       $data[11]; // proforma
  1300.                         $lienPaiement   $data[12]; // Lien de paiement
  1301.                         $facture        $data[13]; // facture
  1302.                         
  1303.                         var_dump("---------------------- NUMERO : ".$i." ---------------------");
  1304.                         var_dump("deliveryDate  : "$deliveryDate   );
  1305.                         var_dump("chateauName   : "$chateauName    );
  1306.                         var_dump("recipientName : "$recipientName  );
  1307.                         var_dump("cp            : "$cp             );
  1308.                         var_dump("ville         : "$ville          );
  1309.                         var_dump("deliveryAddr  : "$deliveryAddr   );
  1310.                         var_dump("etat          : "$etat           );
  1311.                         var_dump("trackingNumber: "$trackingNumber );
  1312.                         var_dump("email         : "$email          );
  1313.                         var_dump("phone         : "$phone          );
  1314.                         var_dump("montant       : "$montant        );
  1315.                         var_dump("proforma      : "$proforma       );
  1316.                         var_dump("lienPaiement  : "$lienPaiement   );
  1317.                         var_dump("facture       : "$facture        );
  1318.                     }
  1319.                     
  1320.                 }
  1321.             }
  1322.             fclose($handle);
  1323.             var_dump($errorMails);
  1324.         }
  1325.         echo '</pre>';
  1326.         exit();
  1327.     }
  1328.     /**
  1329.      * @Route("/new", name="app_commande_new", methods={"GET", "POST"})
  1330.      */
  1331.     public function new(Request $requestCommandeRepository $commandeRepositoryClientRepository $clientRepositoryColisRepository $colisRepositoryClientFinalRepository $clientFinalRepository): Response
  1332.     {
  1333.         
  1334.         // $this->addFlash("info", 'Bonjour et bienvenue sur la plateforme !');
  1335.         $user $this->getUser();
  1336.         $em $this->getDoctrine()->getManager();
  1337.         $cmdTemporaire null;
  1338.         /* $creneauxLivraison = $this->createCreneauxLivraison($commandeRepository, 30); */
  1339.         if ($this->roleAdmin) {
  1340.             $commande = new Commande();
  1341.             $form $this->createForm(CommandeAdminType::class, $commande);
  1342.             $oldFichier '';
  1343.         } else {
  1344.             $thisClient $user->getClient();
  1345.             //récupère la dernière commande si elle est temporaire
  1346.             $cmdTemporaire $commandeRepository->findOneTemporaireByClient($thisClient);
  1347.             if ($cmdTemporaire) {
  1348.                 $commande $cmdTemporaire;
  1349.                 $form $this->createForm(CommandeType::class, $cmdTemporaire);
  1350.                 $oldFichier $commande->getFichierFacture();
  1351.             } else {
  1352.                 $commande = new Commande();
  1353.                 $form $this->createForm(CommandeType::class, $commande);
  1354.                 $oldFichier '';
  1355.             }
  1356.         }
  1357.         $form->handleRequest($request);
  1358.         if ($form->isSubmitted()) {    
  1359.             $commande->setCommandeMassive(false);
  1360.             $postColis $_POST['colis'];
  1361.             if ($this->roleAdmin) {
  1362.                 $postCommande $_POST['commande_admin'];      
  1363.                           
  1364.             } else {
  1365.                 $postCommande $_POST['commande'];                
  1366.             }
  1367.             
  1368.             $nbMagnumSaisi intval($postCommande['nombreMagnumRouge']) + intval($postCommande['nombreMagnumBlanc']) + intval($postCommande['nombreMagnumPetillant']); 
  1369.             $nbBouteillesSaisi intval($postCommande['nombreBouteilleRouge']) + intval($postCommande['nombreBouteilleBlanc']) + intval($postCommande['nombreBouteillePetillant']); 
  1370.             
  1371.             $nbBouteillesTotal = ($nbMagnumSaisi 2) + $nbBouteillesSaisi;
  1372.             $nombreBouteillesRenseigneDansColis 0;
  1373.             if($this->roleAdmin) {
  1374.                 foreach ($postColis["new"] as $key => $value) {
  1375.                     $nombreBouteillesRenseigneDansColis += intval($value);
  1376.                 }
  1377.             }
  1378.             if($this->roleAdmin) {
  1379.                 // Test si le nombre de bouteilles total correspond au nombre de bouteilles dans les colis uniquement pour les admins
  1380.                 if($nbBouteillesTotal != $nombreBouteillesRenseigneDansColis){
  1381.                     $this->addFlash("error"'Le nombre de bouteilles total ne correspond au nombre de bouteilles dans les colis');
  1382.                     $colisThisCommande = [];
  1383.                     return $this->renderForm('commande/new_admin.html.twig', [
  1384.                         'commande' => $commande,
  1385.                         'form' => $form,
  1386.                         'user' => $this->getUser(),
  1387.                         /* 'creneauxLivraison' => $creneauxLivraison, */
  1388.                         'admin' => $this->roleAdmin,
  1389.                         'colisThisCommande' => $colisThisCommande,
  1390.                         'bandeau' => $this->bandeauService->displayPopup() 
  1391.                     ]);
  1392.                 }
  1393.             }
  1394.             if ($this->roleAdmin) {
  1395.                 $postCommande $_POST['commande_admin'];
  1396.                 $thisClient $clientRepository->find($postCommande['client']);
  1397.             } else {
  1398.                 $postCommande $_POST['commande'];
  1399.                 $thisClient $user->getClient();
  1400.             }
  1401.             $assuranceLivraison false;
  1402.             $emballageLivraison false;
  1403.             $assuranceLivraison $postCommande['assuranceLivraison'] == 'true' true false ;
  1404.             $emballageLivraison $postCommande['emballageLivraison'] == 'true' true false ;
  1405.             $now = new DateTime('now', new DateTimeZone('Europe/Paris'));
  1406.             $etatUs htmlspecialchars($_POST['input_etat_us']);
  1407.             if($etatUs == ''){
  1408.                 $this->addFlash("error"'Sélectionner un État pour créer une commande.');
  1409.                 if ($cmdTemporaire) {
  1410.                     $colisThisCommande $colisRepository->findColisByCommande($cmdTemporaire);
  1411.                     $cmdAEnvoyer $cmdTemporaire;
  1412.                 }
  1413.                 else {
  1414.                     $colisThisCommande = [];
  1415.                     $cmdAEnvoyer $commande;
  1416.                 }
  1417.                 $formOptions = [
  1418.                     'commande' => $cmdAEnvoyer,
  1419.                     'form' => $form,
  1420.                     'user' => $this->getUser(),
  1421.                     'admin' => $this->roleAdmin,
  1422.                     'colisThisCommande' => $colisThisCommande,
  1423.                     'bandeau' => $this->bandeauService->displayPopup()    
  1424.                 ];
  1425.                 if ($this->roleAdmin) {
  1426.                     return $this->renderForm('commande/new_admin.html.twig'$formOptions);
  1427.                 }
  1428.                 else {
  1429.                     return $this->renderForm('commande/new.html.twig'$formOptions);
  1430.                 }
  1431.             }
  1432.             
  1433.             if ($etatUs == "MS" || $etatUs == "UT") {
  1434.                 $this->addFlash("error"'Il n\'est pas possible de sélectionner une adresse dans cet État.');
  1435.                 if ($cmdTemporaire) {
  1436.                     $colisThisCommande $colisRepository->findColisByCommande($cmdTemporaire);
  1437.                     $cmdAEnvoyer $cmdTemporaire;
  1438.                 }
  1439.                 else {
  1440.                     $colisThisCommande = [];
  1441.                     $cmdAEnvoyer $commande;
  1442.                 }
  1443.                 $formOptions = [
  1444.                     'commande' => $cmdAEnvoyer,
  1445.                     'form' => $form,
  1446.                     'user' => $this->getUser(),
  1447.                     'admin' => $this->roleAdmin,
  1448.                     'colisThisCommande' => $colisThisCommande,
  1449.                     'bandeau' => $this->bandeauService->displayPopup()
  1450.                 ];
  1451.                 if ($this->roleAdmin) {
  1452.                     return $this->renderForm('commande/new_admin.html.twig'$formOptions);
  1453.                 }
  1454.                 else {
  1455.                     return $this->renderForm('commande/new.html.twig'$formOptions);
  1456.                 }
  1457.             }
  1458.             
  1459.             //_____Client final_____
  1460.             if($commande->getClientFinal()->getId()) {
  1461.                 //Update
  1462.                 $clientFinal $commande->getClientFinal();
  1463.             }else {
  1464.                 $clientFinal = new ClientFinal();
  1465.             }
  1466.             if (!filter_var($postCommande['clientFinal']['email'], FILTER_VALIDATE_EMAIL)) {
  1467.                 $this->addFlash("error"'L\'email du destinataire n\'est pas valide');
  1468.                 if ($cmdTemporaire) {
  1469.                     $colisThisCommande $colisRepository->findColisByCommande($cmdTemporaire);
  1470.                     $cmdAEnvoyer $cmdTemporaire;
  1471.                 }
  1472.                 else {
  1473.                     $colisThisCommande = [];
  1474.                     $cmdAEnvoyer $commande;
  1475.                 }
  1476.                 $formOptions = [
  1477.                     'commande' => $cmdAEnvoyer,
  1478.                     'form' => $form,
  1479.                     'user' => $this->getUser(),
  1480.                     'admin' => $this->roleAdmin,
  1481.                     'colisThisCommande' => $colisThisCommande,
  1482.                     'bandeau' => $this->bandeauService->displayPopup()   
  1483.                 ];
  1484.                 if ($this->roleAdmin) {
  1485.                     return $this->renderForm('commande/new_admin.html.twig'$formOptions);
  1486.                 }
  1487.                 else {
  1488.                     return $this->renderForm('commande/new.html.twig'$formOptions);
  1489.                 }
  1490.             }
  1491.             $clientFinal->setEmail($postCommande['clientFinal']['email']);
  1492.             if(strlen($postCommande['clientFinal']['telephone']) != 10){
  1493.                 $this->addFlash("error"'Le numéro de téléphone doit être composé de 10 chiffres.');
  1494.                 if ($cmdTemporaire) {
  1495.                     $colisThisCommande $colisRepository->findColisByCommande($cmdTemporaire);
  1496.                     $cmdAEnvoyer $cmdTemporaire;
  1497.                 }
  1498.                 else {
  1499.                     $colisThisCommande = [];
  1500.                     $cmdAEnvoyer $commande;
  1501.                 }
  1502.                 $formOptions = [
  1503.                     'commande' => $cmdAEnvoyer,
  1504.                     'form' => $form,
  1505.                     'user' => $this->getUser(),
  1506.                     'admin' => $this->roleAdmin,
  1507.                     'colisThisCommande' => $colisThisCommande,
  1508.                     'bandeau' => $this->bandeauService->displayPopup()   
  1509.                 ];
  1510.                 if ($this->roleAdmin) {
  1511.                     return $this->renderForm('commande/new_admin.html.twig'$formOptions);
  1512.                 }
  1513.                 else {
  1514.                     return $this->renderForm('commande/new.html.twig'$formOptions);
  1515.                 }
  1516.             }
  1517.             $clientFinal->setTelephone($postCommande['clientFinal']['telephone']);
  1518.             if (strlen($postCommande['clientFinal']['fullName']) > 70) {
  1519.                 $this->addFlash("error"'Le nom et prénom sont trop long');
  1520.                 if ($cmdTemporaire) {
  1521.                     $colisThisCommande $colisRepository->findColisByCommande($cmdTemporaire);
  1522.                     $cmdAEnvoyer $cmdTemporaire;
  1523.                 }
  1524.                 else {
  1525.                     $colisThisCommande = [];
  1526.                     $cmdAEnvoyer $commande;
  1527.                 }
  1528.                 $formOptions = [
  1529.                     'commande' => $cmdAEnvoyer,
  1530.                     'form' => $form,
  1531.                     'user' => $this->getUser(),
  1532.                     'admin' => $this->roleAdmin,
  1533.                     'colisThisCommande' => $colisThisCommande,
  1534.                     'bandeau' => $this->bandeauService->displayPopup()   
  1535.                 ];
  1536.                 if ($this->roleAdmin) {
  1537.                     return $this->renderForm('commande/new_admin.html.twig'$formOptions);
  1538.                 }
  1539.                 else {
  1540.                     return $this->renderForm('commande/new.html.twig'$formOptions);
  1541.                 }
  1542.             }
  1543.             $clientFinal->setFullName($postCommande['clientFinal']['fullName']);
  1544.             // $clientFinal->setPrenom($postCommande['clientFinal']['prenom']);
  1545.             // $clientFinal->setNom($postCommande['clientFinal']['nom']);
  1546.             $em->persist($clientFinal);
  1547.             $em->flush();
  1548.             $indexData = [
  1549.                 'id' => $clientFinal->getId(),
  1550.                 'full_name' => $clientFinal->getFullName()
  1551.             ];
  1552.     
  1553.             $this->utilsService->updateIndex('clientFinal'$indexData);
  1554.             //_____Fichier Facture_____
  1555.             //Si on modifie une commande temporaire
  1556.             if($commande->getId()) {
  1557.                 //On compare avec la value de l'input
  1558.                 //Si les deux valeurs sont différentes
  1559.                 if ($_POST['input_filename'] != '' && $_POST['input_filename'] !== $oldFichier) {
  1560.                   if (isset($_FILES)) {
  1561.                         
  1562.                         if ($this->roleAdmin) {
  1563.                             $fileImage $_FILES['commande_admin'];     
  1564.                         } else {
  1565.                             $fileImage $_FILES['commande'];     
  1566.                         }
  1567.                         //$fileImage = $_FILES['commande'];
  1568.                         $name $fileImage['name']['fichierFacture'];
  1569.                         $originalFilename pathinfo($namePATHINFO_FILENAME);
  1570.                         // $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
  1571.                         // $safeFilenameClean = $this->is_valid_filename($safeFilename);
  1572.                         $extension pathinfo($namePATHINFO_EXTENSION);
  1573.                         if($commande->getClient() != null ){
  1574.                             $id $commande->getClient()->getId();
  1575.                         } else {
  1576.                             $id $this->getUser()->getId();
  1577.                         }
  1578.                         
  1579.                         $newFilename 'facture_' $id '_' uniqid() . '.' $extension;
  1580.                         // Formats autorisés 
  1581.                         $allowTypes = array('pdf','jpg','png','jpeg'); 
  1582.                         if(in_array($extension$allowTypes)){ 
  1583.                             move_uploaded_file($fileImage['tmp_name']['fichierFacture'],"upload_Hk2DvAtDeUccGXh/".$newFilename);
  1584.                             $commande->setFichierFacture($newFilename);
  1585.                             $em->persist($commande);
  1586.                         }
  1587.                         //On unlink l'ancien fichier
  1588.                         if(file_exists("upload_Hk2DvAtDeUccGXh/".$oldFichier)) {
  1589.                             
  1590.                             unlink("upload_Hk2DvAtDeUccGXh/".$oldFichier);
  1591.                         }
  1592.                     }
  1593.                 }
  1594.                 //Sinon
  1595.                 else {
  1596.                     //On set fichierFacture avec l'ancienne value
  1597.                     $commande->setFichierFacture($oldFichier);
  1598.                     $em->persist($commande);
  1599.                 }
  1600.                 $commande->setIsTemporaire(false);
  1601.             }
  1602.             else {
  1603.                 
  1604.                 if( isset($_FILES)){
  1605.                     if ($this->roleAdmin) {
  1606.                         $fileImage $_FILES['commande_admin'];     
  1607.                     } else {
  1608.                         $fileImage $_FILES['commande'];     
  1609.                     }
  1610.                     //$fileImage = $_FILES;                    
  1611.                     $name $fileImage['name']['fichierFacture']; 
  1612.                     $originalFilename pathinfo($namePATHINFO_FILENAME);
  1613.                     // $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
  1614.                     // $safeFilenameClean = $this->is_valid_filename($safeFilename);
  1615.                     $extension pathinfo($namePATHINFO_EXTENSION);
  1616.                     
  1617.                     if($commande->getClient() != null ){
  1618.                         $id $commande->getClient()->getId();
  1619.                     } else {
  1620.                         $id $this->getUser()->getId();
  1621.                     }
  1622.                     $newFilename 'facture_' $id '_' uniqid() . '.' $extension;
  1623.                     
  1624.                     // Formats autorisés 
  1625.                     $allowTypes = array('pdf','jpg','png','jpeg'); 
  1626.                     if(in_array($extension$allowTypes)){ 
  1627.                         move_uploaded_file($fileImage['tmp_name']['fichierFacture'],"upload_Hk2DvAtDeUccGXh/".$newFilename);
  1628.                         $commande->setFichierFacture($newFilename);
  1629.                         $em->persist($commande);
  1630.                     }
  1631.                 }
  1632.             }
  1633.             if($this->roleAdmin){
  1634.                 $commande->setIsTemporaire(false);
  1635.             }
  1636.             else {
  1637.                 $commande->setIsTemporaire(true);
  1638.             }
  1639.             $montant $this->checkMontant($postCommande['montantTotalFacture']);
  1640.             //_____Commande_____
  1641.             $commande->setClient($thisClient);
  1642.             $commande->setClientFinal($clientFinal);
  1643.             $commande->setNombreColisTotal($postCommande['nombreColisTotal']);
  1644.             $commande->setNumeroDae($postCommande['numeroDae']);
  1645.             $commande->setAssuranceLivraison($assuranceLivraison);
  1646.             $commande->setEmballageLivraison($emballageLivraison);
  1647.             $commande->setNumeroFacture($postCommande['numeroFacture']);
  1648.             $commande->setMontantTotalFacture(floatval($montant));
  1649.             /* $commande->setDateDebutFenetre($dateDebutFenetre);
  1650.             $commande->setDateFinFenetre($dateFinFenetre); */
  1651.             $commande->setCodePostalLivraison(str_replace(' '''$postCommande['codePostalLivraison']));
  1652.             $commande->setVilleLivraison(trim($postCommande['villeLivraison']));
  1653.             $commande->setAdresseLivraison($postCommande['adresseLivraison']);
  1654.             $commande->setComplementAdresseLivraison($postCommande['complementAdresseLivraison']);
  1655.             $commande->setEtatUs($etatUs);
  1656.             $commande->setObservation($postCommande['observation']);
  1657.             $commande->setProvince($this->utilsService->getProvinceByEtatUs($etatUs));
  1658.             $commande->setNombreBouteilleRouge($postCommande['nombreBouteilleRouge']);
  1659.             $commande->setNombreBouteilleBlanc($postCommande['nombreBouteilleBlanc']);
  1660.             $commande->setNombreBouteillePetillant($postCommande['nombreBouteillePetillant']);
  1661.             $commande->setIsValideeParClient(false);
  1662.             $commande->setDateCommandeSoumission($now);
  1663.             if(isset($_POST['urgentCheckbox'])){
  1664.                 $commande->setFastPickup(true);
  1665.                 $commande->setIsValideeParClient(true);                
  1666.             }else{
  1667.                 $commande->setFastPickup(false);
  1668.             }
  1669.             if($emballageLivraison == true) {
  1670.                 $commande->setState('emballage_caviste');
  1671.             }
  1672.             else {
  1673.                 $commande->setState('preparation');
  1674.             }
  1675.             // TODO A RETIRER
  1676.             $commande->setToken("gsrefgrdsgfres");
  1677.             
  1678.             //$commande->setIsTemporaire(true);
  1679.             $commande->setFedexPdfGenerated(false);
  1680.             $commande->setFedexPdfAvailable(false);
  1681.             
  1682.             //_____Colis_____
  1683.             //Si on édite une commande temporaire
  1684.             if ($commande->getId()) {
  1685.                 //On crée un array contenant les ids de tous les colis liés à cette commande
  1686.                 $colisThisCommande $colisRepository->findColisByCommande($commande);
  1687.                 //$bddCommandes = [];
  1688.                 foreach ($colisThisCommande as $key => $colisEnBdd) {
  1689.                         $colis $colisRepository->find($colisEnBdd);
  1690.                         $colisRepository->remove($colis); 
  1691.                 }
  1692.                 
  1693.                 // if (isset($postColis['update'])) {
  1694.                 //     //On prend l'array colis[update] et pour chaque item, on update la quantité et on unset la key de l'array de colis
  1695.                 //     foreach ($postColis['update'] as $idColis => $qteBouteilles) {
  1696.                 //         $colis = $colisRepository->find($idColis);
  1697.                 //         $colis->setNombreBouteille($qteBouteilles);
  1698.                 //         $colis->setCommande($commande);
  1699.                 //         $em->persist($colis);
  1700.                 //         $em->flush();
  1701.                 //         if (($arrayKey = array_search($idColis, $bddCommandes)) !== false) {
  1702.                 //             unset($bddCommandes[$arrayKey]);
  1703.                 //         }
  1704.                 //     }
  1705.                 // }
  1706.                 // //Si il reste des keys dans l'array, on delete tout simplement les lignes concernées
  1707.                 // if (sizeof($bddCommandes) > 0) {
  1708.                 //     foreach ($bddCommandes as $key => $bddCommande) {
  1709.                 //         $colis = $colisRepository->find($bddCommande);
  1710.                 //         // $colisRepository->remove($colis);
  1711.                 //     }
  1712.                 // }
  1713.             }
  1714.             //Puis on crée de nouveaux colis pour les values de colis[new]
  1715.             if (array_key_exists("new"$postColis)) {
  1716.                 foreach ($postColis['new'] as $postColi) {
  1717.                     $colis = new Colis();
  1718.                     $colis->setNombreBouteille($postColi);
  1719.                     $colis->setCommande($commande);
  1720.                     $em->persist($colis);
  1721.                     $em->flush();
  1722.                     $commande->addColi($colis);
  1723.                 }
  1724.             }
  1725.             
  1726.             if($nbBouteillesTotal 36 && !$this->roleAdmin){
  1727.                 $commande->setCommandeMassive(true);
  1728.                 $this->emailGeneratorService->sendMassiveCommande($commande);
  1729.             }
  1730.             $em->persist($commande);
  1731.             $em->flush();
  1732.             
  1733.             $tokenPayload = [
  1734.                 "id"=> $commande->getId(),
  1735.                 /* "exp"=> strtotime("+1 week") */
  1736.             ];
  1737.             $token $this->utilsService->generateJWT($tokenPayload);
  1738.             $url $this->baseDomain $this->generateUrl('app_client_final_validate', array('token' => $token));
  1739.             
  1740.             //TODO send the validation email
  1741.             $em->persist($commande);
  1742.             $em->flush();
  1743.             
  1744.             $indexData = [
  1745.                 'id' => $commande->getId(),
  1746.                 'numero_facture' => $commande->getNumeroFacture(),
  1747.                 'code_postal_livraison' => $commande->getCodePostalLivraison(),
  1748.                 'ville_livraison' => $commande->getVilleLivraison(),
  1749.             ];
  1750.     
  1751.             $this->utilsService->updateIndex('commande'$indexData);
  1752.             if($this->roleAdmin){
  1753.                 $payload = [
  1754.                     'id' => $commande->getId(),
  1755.                     /* 'exp' => time() + 604800 // one week validation */
  1756.                 ];
  1757.                 $dateCreneau1Clone = clone $commande->getDateCollecte();
  1758.                 $dateCreneau2Clone = clone $commande->getDateCollecte();
  1759.             
  1760.         
  1761.                 if($commande->isEmballageLivraison()){
  1762.                     $dateCreneau1Brut $dateCreneau1Clone->modify("+7 days");
  1763.                     $dateCreneau2Brut $dateCreneau2Clone->modify("+12 days");
  1764.                 } else {
  1765.                     $dateCreneau1Brut $dateCreneau1Clone->modify("+22 days");
  1766.                     $dateCreneau2Brut $dateCreneau2Clone->modify("+27 days");
  1767.                 }
  1768.         
  1769.                 $dateCreneau1 $dateCreneau1Brut->format('d/m/Y');
  1770.                 $dateCreneau2 $dateCreneau2Brut->format('d/m/Y');
  1771.                 $token $this->utilsService->generateJWT($payload);
  1772.                 $url $this->baseDomain $this->generateUrl('app_client_final_validate', array('token' => $token ));
  1773.                 $res false;
  1774.                 if($commande->isFastPickup() != true){  
  1775.                     $res $this->emailGeneratorService->sendEmailToFinalCustomer(
  1776.                         $commande->getClientFinal()->getEmail(),
  1777.                         $commande->getClientFinal()->getFullName(),
  1778.                         $commande->getClient()->getRaisonSociale(),
  1779.                         $url,
  1780.                         false,
  1781.                         $dateCreneau1,
  1782.                         $dateCreneau2
  1783.                     );   
  1784.                 }
  1785.             }
  1786.             return $this->redirectToRoute("app_recapitulatif_commande", ["id" => $commande->getId()], Response::HTTP_SEE_OTHER);
  1787.         }
  1788.         //Si l'user est admin, on ne prend pas en compte les commandes temporaires
  1789.         if ($this->roleAdmin) {
  1790.             $colisThisCommande = [];
  1791.             return $this->renderForm('commande/new_admin.html.twig', [
  1792.                 'commande' => $commande,
  1793.                 'form' => $form,
  1794.                 'user' => $this->getUser(),
  1795.                 /* 'creneauxLivraison' => $creneauxLivraison, */
  1796.                 'admin' => $this->roleAdmin,
  1797.                 'colisThisCommande' => $colisThisCommande,
  1798.                 'bandeau' => $this->bandeauService->displayPopup()   
  1799.             ]);
  1800.             //Si l'user est client
  1801.         } else {
  1802.             //Si le client a une commande isTemporaire == true, on le renvoie vers le form pré-rempli
  1803.             if ($cmdTemporaire) {
  1804.                 $colisThisCommande $colisRepository->findColisByCommande($cmdTemporaire);
  1805.                 return $this->renderForm('commande/new.html.twig', [
  1806.                     'commande' => $cmdTemporaire,
  1807.                     'form' => $form,
  1808.                     'user' => $this->getUser(),
  1809.                     'packing' => $cmdTemporaire->isEmballageLivraison() ? 'yes' 'no',
  1810.                     /* 'creneauxLivraison' => $creneauxLivraison, */
  1811.                     'admin' => $this->roleAdmin,
  1812.                     'colisThisCommande' => $colisThisCommande,
  1813.                     'bandeau' => $this->bandeauService->displayPopup()   
  1814.                 ]);
  1815.             }
  1816.             //Sinon on le renvoie vers le form vide
  1817.             else {
  1818.                 $colisThisCommande = [];
  1819.                 return $this->renderForm('commande/new.html.twig', [
  1820.                     'commande' => $commande,
  1821.                     'form' => $form,
  1822.                     'user' => $this->getUser(),
  1823.                     /* 'creneauxLivraison' => $creneauxLivraison, */
  1824.                     'admin' => $this->roleAdmin,
  1825.                     'colisThisCommande' => $colisThisCommande,
  1826.                     'bandeau' => $this->bandeauService->displayPopup()   
  1827.                 ]);
  1828.             }
  1829.         }
  1830.     }
  1831.     /**
  1832.      * @Route("/exportlist_commande_dsqde8cse9dx5fe8", name="commande_export_list", methods={"GET", "POST"})
  1833.      */
  1834.     public function exportListCommand(Request $requestCommandeRepository $commandeRepository): Response
  1835.     {        
  1836.         //need to fetch the commandes that need to be prepared
  1837.         //for the admin only the one he need to pack
  1838.         //for the caviste the one he need to prepare for mbe and the one he need to pack
  1839.         $user $this->getUser(); 
  1840.         $em $this->getDoctrine()->getManager();
  1841.         
  1842.         if($this->roleAdmin){            
  1843.             $dateDebut $_POST["dateDebut"];
  1844.             $dateFin $_POST["dateFin"];            
  1845.             if($dateFin == "" || $dateDebut == ""){
  1846.                 $this->addFlash("error""La date de début ou la date de fin n'est pas correcte");
  1847.             }else{
  1848.                 $state "attente_collecte_mbe";
  1849.                 $commandes $commandeRepository->findCommandesByCreneauByState($dateDebut$dateFin$state);
  1850.                 $this->addFlash("success""Le fichier Excel a bien été généré");
  1851.                 return $this->createExcelCommandes($commandes);
  1852.                 
  1853.             }
  1854.         }else{
  1855.             $dateDebut $_POST["dateDebut"];
  1856.             $dateFin $_POST["dateFin"];            
  1857.             if($dateFin == "" || $dateDebut == ""){
  1858.                 $this->addFlash("error""La date de début ou la date de fin n'est pas correcte");
  1859.             }else{
  1860.                 $state "preparation";
  1861.                 $commandes $commandeRepository->findCommandesByCreneauByStateByClient($dateDebut$dateFin$state$user->getClient());
  1862.                 $this->addFlash("success""Le fichier Excel a bien été généré");
  1863.                 return $this->createExcelCommandes($commandes);
  1864.                 
  1865.             }            
  1866.             
  1867.         }
  1868.         $response = new Response();
  1869.         $response->setStatusCode(Response::HTTP_OK);
  1870.         
  1871.         $this->addFlash("error""Le fichier Excel n'a pas pu être généré");
  1872.         return $response;
  1873.     }
  1874.     /**
  1875.      * @Route("/exportlist_commande_emb_dsqde8cse9dx5fe8", name="commande_export_list_emb", methods={"GET", "POST"})
  1876.      */
  1877.     public function exportListCommandEmb(Request $requestCommandeRepository $commandeRepository): Response
  1878.     {        
  1879.         $user $this->getUser(); 
  1880.         $em $this->getDoctrine()->getManager();
  1881.         
  1882.         if($this->roleAdmin){            
  1883.             $dateDebut $_POST["dateDebut"];
  1884.             $dateFin $_POST["dateFin"];
  1885.             if($dateFin == "" || $dateDebut == ""){
  1886.                 $this->addFlash("error""La date de début ou la date de fin n'est pas correcte");
  1887.             }else{
  1888.                 $state "emballage_mbe";
  1889.                 $commandes $commandeRepository->findCommandesByCreneauByState($dateDebut$dateFin$state);
  1890.                 $this->addFlash("success""Le fichier Excel a bien été généré");
  1891.                 return $this->createExcelCommandes($commandes);
  1892.                 
  1893.             }
  1894.         } else {
  1895.             $dateDebut $_POST["dateDebut"];
  1896.             $dateFin $_POST["dateFin"];            
  1897.             if($dateFin == "" || $dateDebut == ""){
  1898.                 $this->addFlash("error""La date de début ou la date de fin n'est pas correcte");
  1899.             }else{
  1900.                 $state "emballage_caviste";
  1901.                 $commandes $commandeRepository->findCommandesByCreneauByStateByClient($dateDebut$dateFin$state$user->getClient());
  1902.                 $this->addFlash("success""Le fichier Excel a bien été généré");
  1903.                 return $this->createExcelCommandes($commandes);
  1904.                 
  1905.             }            
  1906.         }
  1907.         $response = new Response();
  1908.         $response->setStatusCode(Response::HTTP_OK);
  1909.         $this->addFlash("error""Le fichier Excel n'a pas pu être généré");
  1910.         return $response;
  1911.     }
  1912.     /**
  1913.      * @Route("/exportlist_commande_all_dsqde8cse9dx5fe8", name="commande_export_list_all", methods={"GET", "POST"})
  1914.      */
  1915.     public function exportListCommandAll(Request $requestCommandeRepository $commandeRepository): Response
  1916.     {
  1917.         $user $this->getUser();
  1918.         $em $this->getDoctrine()->getManager();
  1919.         
  1920.         if($this->roleAdmin){            
  1921.             $dateDebut $_POST["dateDebut"];
  1922.             $dateFin $_POST["dateFin"];
  1923.             if($dateFin == "" || $dateDebut == ""){
  1924.                 $this->addFlash("error""La date de début ou la date de fin n'est pas correcte");
  1925.             }else{
  1926.                 $state null;
  1927.                 $commandes $commandeRepository->findCommandesByCreneauByState($dateDebut$dateFin$state);
  1928.                 $this->addFlash("success""Le fichier Excel a bien été généré");
  1929.                 return $this->createExcelCommandes($commandes);                
  1930.             }
  1931.         } else {                        
  1932.             $dateDebut $_POST["dateDebut"];
  1933.             $dateFin $_POST["dateFin"];
  1934.             if($dateFin == "" || $dateDebut == ""){
  1935.                 $this->addFlash("error""La date de début ou la date de fin n'est pas correcte");
  1936.             }else{
  1937.                 $state null;
  1938.                 $commandes $commandeRepository->findCommandesByCreneauByStateByClient($dateDebut$dateFin$state$user->getClient());
  1939.                 $this->addFlash("success""Le fichier Excel a bien été généré");
  1940.                 return $this->createExcelCommandes($commandes);                
  1941.             }
  1942.         }
  1943.         $response = new Response();
  1944.         $response->setStatusCode(Response::HTTP_OK);
  1945.         $this->addFlash("error""Le fichier Excel n'a pas pu être généré");
  1946.         return $response;
  1947.     }
  1948.     /**
  1949.      * @Route("/checkDispo", name="app_check_dispo", methods={"GET", "POST"})
  1950.      */
  1951.     public function checkDispo(CommandeRepository $commandeRepository): Response
  1952.     {        
  1953.         //On recherche la date avant laquelle on ne peut pas accepter de collecte (j+2)
  1954.         $now = new DateTime('now', new DateTimeZone('Europe/Paris')); //'2023-10-26 11:38:04.646428'
  1955.         $dateMin $now->modify("+2 days");
  1956.         $dateMinDay $dateMin->format('l');
  1957.         //Si la date minimum tombe un week-end, on inclut le we dans les jours où on ne peut pas accepter de collecte
  1958.         if($dateMinDay == 'Saturday') {
  1959.             $dateMin->modify("+2 days");
  1960.             $dateMinDay $dateMin->format('l');
  1961.         }
  1962.         if($dateMinDay == 'Sunday') {
  1963.             $dateMin->modify("+1 days");
  1964.             $dateMinDay $dateMin->format('l');
  1965.         }
  1966.         //On stocke la valeur de cette date min pour comparaison
  1967.         $dateMinCompare $dateMin->format('Y-m-d');
  1968.         //Si une date est rensignée
  1969.         if (isset($_POST['datevalue'])) {
  1970.             $date str_replace("/","-"htmlspecialchars($_POST['datevalue']));
  1971.         }        
  1972.         $dateSaisie date('Y-m-d'strtotime($date));
  1973.         //On compare les dates. 
  1974.         //Si la date sélectionnée par l'utilisateur est antérieure à la date autorisée, on return une erreur.
  1975.         if($dateSaisie $dateMinCompare) {
  1976.             return $this->json([
  1977.                 'success' => false
  1978.                 'available' => false
  1979.                 'dateClean' => ''
  1980.                 'dateCreneau1' => ''
  1981.                 'dateCreneau2' => '',
  1982.                 'dateCreneau1MBE' => '',
  1983.                 'dateCreneau2MBE' => ''
  1984.             ]);
  1985.         }
  1986.         //Pas de vérification du nombre de commandes sur le créneau si l'utilisateur est admin
  1987.         $available true;
  1988.         $dateOk = new DateTime($date);
  1989.         $dateCreneau1Clone = clone $dateOk;
  1990.         $dateCreneau2Clone = clone $dateOk;
  1991.         $dateCreneau1MBEClone = clone $dateOk;
  1992.         $dateCreneau2MBEClone = clone $dateOk;
  1993.         
  1994.         $dateCreneau1Brut $dateCreneau1Clone->modify("+7 days");
  1995.         $dateCreneau2Brut $dateCreneau2Clone->modify("+12 days");
  1996.         $dateCreneau1BMBErut $dateCreneau1MBEClone->modify("+22 days");
  1997.         $dateCreneau2MEBrut $dateCreneau2MBEClone->modify("+27 days");
  1998.         $dateCreneau1 $dateCreneau1Brut->format('d/m/Y');
  1999.         $dateCreneau2 $dateCreneau2Brut->format('d/m/Y');
  2000.         $dateCreneau1MBE $dateCreneau1BMBErut->format('d/m/Y');
  2001.         $dateCreneau2MBE $dateCreneau2MEBrut->format('d/m/Y');
  2002.         if($this->roleAdmin){
  2003.             return $this->json([
  2004.                 'success' => true,
  2005.                 'available' => $available,
  2006.                 'dateClean' => $dateOk->format('Y-m-d'),
  2007.                 'dateCreneau1' => $dateCreneau1,
  2008.                 'dateCreneau2' => $dateCreneau2,
  2009.                 'dateCreneau1MBE' => $dateCreneau1MBE,
  2010.                 'dateCreneau2MBE' => $dateCreneau2MBE
  2011.             ]);
  2012.         }
  2013.         //On vérifie le nombre de commandes sur le créneau si l'utilisateur n'est pas admin
  2014.         else {
  2015.             $commandes $commandeRepository->findByDateCollecte($dateOk);
  2016.             $dateOkClean $dateOk->format('Y-m-d');
  2017.             if(count($commandes) >= 35){
  2018.                 $available false;
  2019.                 $dateOkClean '';
  2020.                 $dateCreneau1 '';
  2021.                 $dateCreneau2 '';
  2022.                 $dateCreneau1MBE '';
  2023.                 $dateCreneau2MBE '';
  2024.                 
  2025.             }
  2026.             return $this->json([
  2027.                 'success' => true,
  2028.                 'available' => $available
  2029.                 'dateClean' => $dateOkClean
  2030.                 'dateCreneau1' => $dateCreneau1
  2031.                 'dateCreneau2' => $dateCreneau2,
  2032.                 'dateCreneau1MBE' => $dateCreneau1MBE,
  2033.                 'dateCreneau2MBE' => $dateCreneau2MBE
  2034.             ]);
  2035.         }
  2036.     }
  2037.     /**
  2038.      * @Route("/checkDefault", name="app_check_default", methods={"GET", "POST"})
  2039.      */
  2040.     public function checkDefault(ClientRepository $clientRepository)
  2041.     {
  2042.         if (isset($_POST['clientId'])) {
  2043.             $clientId $_POST['clientId'];
  2044.             
  2045.             if($this->roleAdmin){
  2046.                 $data $clientRepository->findById($clientId);
  2047.                 return $this->json([
  2048.                     'defaultAssurance' => $data[0]->isAssuranceDefaut(),
  2049.                     'defaultPacking' => $data[0]->isEmballageDefaut(),
  2050.                     'fast' => $data[0]->isFastPickup()
  2051.                 ]);
  2052.             } else {
  2053.                 //TODO GET CLIENT DATA 
  2054.             }
  2055.         }
  2056.     }
  2057.     /**
  2058.      * @Route("/{id}/recapitulatif_commande", name="app_recapitulatif_commande", methods={"GET", "POST"})
  2059.      */
  2060.     public function recapitulatif_commande(Commande $commandeColisRepository $colisRepository): Response
  2061.     {
  2062.         $previDebut = clone $commande->getDateCollecte();
  2063.         $previFin = clone $commande->getDateCollecte();
  2064.         $dateLivraison $this->translateCreneauLivraison($previDebut->modify("+7 days"), $previFin->modify("+12 days"));
  2065.         /* $besoinConsentementDates = $this->besoinConsentementDates($commande->getDateDebutFenetre(), $commande->getDateFinFenetre()); */
  2066.         $besoinConsentementDates $this->besoinConsentementDates($previDebut->modify("+7 days"), $previFin->modify("+12 days"));
  2067.         $colisThisCommande $colisRepository->findColisByCommande($commande);
  2068.         $nombreBouteillesRenseigneDansColis 0;
  2069.         foreach ($colisThisCommande as $key => $colisEnBdd) {
  2070.             $nombreBouteillesRenseigneDansColis += $colisEnBdd->getNombreBouteille();
  2071.         }
  2072.         return $this->render('commande/recap_commande.html.twig', [
  2073.             'commande' => $commande,
  2074.             'admin' => $this->roleAdmin,
  2075.             'user' => $this->getUser(),
  2076.             'dateLivraison' => $dateLivraison,
  2077.             'besoinConsentementDates' => $besoinConsentementDates,
  2078.             'nombreBouteillesRenseigneDansColis' => $nombreBouteillesRenseigneDansColis
  2079.         ]);
  2080.     }
  2081.     /**
  2082.      * @Route("/{id}/valider_commande_temporaire", name="app_valider_commande_temporaire", methods={"GET", "POST"})
  2083.      */
  2084.     public function valider_commande_temporaire(string $idCommandeRepository $commandeRepositoryColisRepository $colisRepository): Response
  2085.     {
  2086.         $em $this->getDoctrine()->getManager();
  2087.         $commande $commandeRepository->find($id);
  2088.         
  2089.         $colisThisCommande $colisRepository->findColisByCommande($commande);
  2090.         $nombreBouteillesRenseigneDansColis 0;
  2091.         foreach ($colisThisCommande as $key => $colisEnBdd) {
  2092.             $nombreBouteillesRenseigneDansColis += $colisEnBdd->getNombreBouteille();
  2093.         }
  2094.         $totalMagnumsAttendu = ($commande->getNombreMagnumRouge() + $commande->getNombreMagnumBlanc() + $commande->getNombreMagnumPetillant()) * 2;
  2095.         $totalBouteillesAttendu $commande->getNombreBouteilleRouge() + $commande->getNombreBouteilleBlanc() + $commande->getNombreBouteillePetillant();
  2096.         $totalAttendu $totalMagnumsAttendu $totalBouteillesAttendu;
  2097.         if($nombreBouteillesRenseigneDansColis != $totalAttendu) {
  2098.             return new Response("ErreurColis");
  2099.         }
  2100.         $commande->setIsTemporaire(false);
  2101.         $em->persist($commande);
  2102.         $em->flush();
  2103.         //return new Response("OK");
  2104.         //return new Response("NOPE");
  2105.         //si la commande est valide on envois le mail de confirmation au client final
  2106.         $payload = [
  2107.             'id' => $commande->getId(),
  2108.             /* 'exp' => time() + 604800 // one week validation */
  2109.         ];
  2110.         $dateCreneau1Clone = clone $commande->getDateCollecte();
  2111.         $dateCreneau2Clone = clone $commande->getDateCollecte();
  2112.     
  2113.         if($commande->isEmballageLivraison()){
  2114.             $dateCreneau1Brut $dateCreneau1Clone->modify("+7 days");
  2115.             $dateCreneau2Brut $dateCreneau2Clone->modify("+12 days");
  2116.         } else {
  2117.             $dateCreneau1Brut $dateCreneau1Clone->modify("+22 days");
  2118.             $dateCreneau2Brut $dateCreneau2Clone->modify("+27 days");
  2119.         }
  2120.         $dateCreneau1 $dateCreneau1Brut->format('d/m/Y');
  2121.         $dateCreneau2 $dateCreneau2Brut->format('d/m/Y');
  2122.         if(!$this->roleAdmin){
  2123.             $token $this->utilsService->generateJWT($payload);
  2124.             $url $this->baseDomain $this->generateUrl('app_client_final_validate', array('token' => $token ));
  2125.             $res false;
  2126.             if($commande->isFastPickup() != true){  
  2127.                 $res $this->emailGeneratorService->sendEmailToFinalCustomer(
  2128.                     $commande->getClientFinal()->getEmail(),
  2129.                     $commande->getClientFinal()->getFullName(),
  2130.                     $commande->getClient()->getRaisonSociale(),
  2131.                     $url,
  2132.                     false,
  2133.                     $dateCreneau1,
  2134.                     $dateCreneau2
  2135.                 ); 
  2136.             }
  2137.             $indexData = [
  2138.                 'id' => $commande->getId(),
  2139.                 'numero_facture' => $commande->getNumeroFacture(),
  2140.                 'code_postal_livraison' => $commande->getCodePostalLivraison(),
  2141.                 'ville_livraison' => $commande->getVilleLivraison(),
  2142.             ];
  2143.     
  2144.             $this->utilsService->updateIndex('commande'$indexData$commande->getId());
  2145.     
  2146.             //var_dump($res);
  2147.             if($res) {
  2148.                 if($commande->isFastPickup()){            
  2149.                     return new JsonResponse(['message' => 'OK''fastPickup' => true,'url' => $this->generateUrl('app_commande_index')]);
  2150.                 }else{
  2151.                     return new JsonResponse(['message' => 'OK''fastPickup' => false]);
  2152.                 }
  2153.             
  2154.                 return new Response("OK");
  2155.             }
  2156.             else {
  2157.                 if($commande->isFastPickup()){                    
  2158.                     return new JsonResponse(['message' => 'OK''fastPickup' => true,'url' => $this->generateUrl('app_commande_index')]);
  2159.                 }else{
  2160.                     return new JsonResponse(['message' => 'ErreurMail''fastPickup' => false]);
  2161.                 }
  2162.                 return new Response("ErreurMail"); 
  2163.                 // return new Response("OK");
  2164.             }
  2165.         } else {
  2166.             $indexData = [
  2167.                 'id' => $commande->getId(),
  2168.                 'numero_facture' => $commande->getNumeroFacture(),
  2169.                 'code_postal_livraison' => $commande->getCodePostalLivraison(),
  2170.                 'ville_livraison' => $commande->getVilleLivraison(),
  2171.             ];
  2172.     
  2173.             $this->utilsService->updateIndex('commande'$indexData$commande->getId());
  2174.             
  2175.             if($commande->isFastPickup()){            
  2176.                 return new JsonResponse(['message' => 'OK''fastPickup' => true,'url' => $this->generateUrl('app_commande_index')]);
  2177.             }else{
  2178.                 return new JsonResponse(['message' => 'OK''fastPickup' => false]);
  2179.             }
  2180.             return new Response("OK");
  2181.         }
  2182.     }
  2183.      /**
  2184.      * @Route("/{id}/relance", name="relance_client_final", methods={"GET"})
  2185.      */
  2186.     public function relanceClientFinal(Commande $commandeCommandeRepository $commandeRepository): Response
  2187.     {
  2188.         if (!$this->roleAdmin && $this->getUser()->getClient() != $commande->getClient() ) {
  2189.             return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  2190.         }
  2191.         //send the email to client final 
  2192.         $payload = [
  2193.             'id' => $commande->getId(),
  2194.             /* 'exp' => time() + 604800 // one week validation */
  2195.         ];
  2196.         $dateCreneau1Clone = clone $commande->getDateCollecte();
  2197.         $dateCreneau2Clone = clone $commande->getDateCollecte();
  2198.     
  2199.         if($commande->isEmballageLivraison()){
  2200.             $dateCreneau1Brut $dateCreneau1Clone->modify("+7 days");
  2201.             $dateCreneau2Brut $dateCreneau2Clone->modify("+12 days");
  2202.         } else {
  2203.             $dateCreneau1Brut $dateCreneau1Clone->modify("+22 days");
  2204.             $dateCreneau2Brut $dateCreneau2Clone->modify("+27 days");
  2205.         }
  2206.         $dateCreneau1 $dateCreneau1Brut->format('d/m/Y');
  2207.         $dateCreneau2 $dateCreneau2Brut->format('d/m/Y');
  2208.         $token $this->utilsService->generateJWT($payload);
  2209.         $url =$this->baseDomain $this->generateUrl('app_client_final_validate', array('token' => $token ));
  2210.         
  2211.         $res false;
  2212.         if($commande->isFastPickup() != true){  
  2213.             $res $this->emailGeneratorService->sendEmailToFinalCustomer(
  2214.                 $commande->getClientFinal()->getEmail(),
  2215.                 $commande->getClientFinal()->getFullName(),
  2216.                 $commande->getClient()->getPrenomContact() . ' ' $commande->getClient()->getNomContact(),
  2217.                 $url,
  2218.                 true,
  2219.                 $dateCreneau1,
  2220.                 $dateCreneau2
  2221.             );
  2222.         }
  2223.         return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  2224.     }
  2225.     /**
  2226.      * @Route("/{id}", name="app_commande_show", methods={"GET"})
  2227.      */
  2228.     public function show(Commande $commande): Response
  2229.     {
  2230.         return $this->render('commande/show.html.twig', [
  2231.             'commande' => $commande,
  2232.         ]);
  2233.     }
  2234.     /**
  2235.      * @Route("/{id}/edit", name="app_commande_edit", methods={"GET", "POST"})
  2236.      */
  2237.     public function edit(Request $requestCommande $commandeCommandeRepository $commandeRepositoryColisRepository $colisRepository): Response
  2238.     {
  2239.         
  2240.         $oldFichier $commande->getFichierFacture();
  2241.         $oldFichierProForma $commande->getFichierFactureProForma();
  2242.         if ($this->roleAdmin) {
  2243.             $form $this->createForm(CommandeAdminType::class, $commande);
  2244.         } 
  2245.         else {
  2246.             $form $this->createForm(CommandeType::class, $commande);
  2247.         }
  2248.         $form->handleRequest($request);
  2249.         if ($form->isSubmitted() && $form->isValid()) {
  2250.             $postColis $_POST['colis'];
  2251.             $postCommande $_POST['commande_admin'];  
  2252.             $assuranceLivraison $postCommande['assuranceLivraison'] == 'true' true false ;
  2253.             $emballagelivraison $postCommande['emballageLivraison'] == 'true' true false ;
  2254.             $commande->setAssuranceLivraison($assuranceLivraison);
  2255.             $commande->setEmballageLivraison($emballagelivraison);
  2256.             if($emballagelivraison && $commande->getState() == 'preparation'){
  2257.                 $commande->setState('emballage_caviste');
  2258.             }
  2259.             if(!$emballagelivraison && $commande->getState() == 'emballage_caviste'){
  2260.                 $commande->setState('preparation');
  2261.             }            
  2262.             if (($_POST['input_filename'] != '') && ($_POST['input_filename'] !== $oldFichier)) {
  2263.                 
  2264.                 if (isset($_FILES)) {
  2265.                     
  2266.                     if ($this->roleAdmin) {
  2267.                         $fileImage $_FILES['commande_admin'];     
  2268.                     } else {
  2269.                         $fileImage $_FILES['commande'];     
  2270.                     }
  2271.                     //$fileImage = $_FILES['commande'];
  2272.                     $name $fileImage['name']['fichierFacture'];
  2273.                     $originalFilename pathinfo($namePATHINFO_FILENAME);
  2274.                     // $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
  2275.                     // $safeFilenameClean = $this->is_valid_filename($safeFilename);
  2276.                     $extension pathinfo($namePATHINFO_EXTENSION);
  2277.                     $newFilename 'facture_' $commande->getClient()->getId() . '_' uniqid() . '.' $extension;
  2278.                     // Formats autorisés 
  2279.                     $allowTypes = array('pdf','jpg','png','jpeg'); 
  2280.                     if(in_array($extension$allowTypes)){ 
  2281.                         move_uploaded_file($fileImage['tmp_name']['fichierFacture'],"upload_Hk2DvAtDeUccGXh/".$newFilename);
  2282.                         $commande->setFichierFacture($newFilename);
  2283.                     }
  2284.                     //On unlink l'ancien fichier
  2285.                     // if(file_exists("upload_Hk2DvAtDeUccGXh/".$oldFichier)) {
  2286.                         
  2287.                     //     unlink("upload_Hk2DvAtDeUccGXh/".$oldFichier);
  2288.                     // }
  2289.                 }
  2290.             }else{
  2291.                 $commande->setFichierFacture($oldFichier);
  2292.             }
  2293.             if (($_POST['input_filename_pro_forma'] != '') && ($_POST['input_filename_pro_forma'] !== $oldFichierProForma)) {
  2294.                 
  2295.                 if (isset($_FILES)) {
  2296.                     
  2297.                     if ($this->roleAdmin) {
  2298.                         $fileImage $_FILES['commande_admin'];     
  2299.                     } else {
  2300.                         $fileImage $_FILES['commande'];     
  2301.                     }
  2302.                     //$fileImage = $_FILES['commande'];
  2303.                     $name $fileImage['name']['fichierFactureProForma'];
  2304.                     $originalFilename pathinfo($namePATHINFO_FILENAME);
  2305.                     // $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
  2306.                     // $safeFilenameClean = $this->is_valid_filename($safeFilename);
  2307.                     $extension pathinfo($namePATHINFO_EXTENSION);
  2308.                     $newFilename 'facture_pro_forma_' $commande->getClient()->getId() . '_' uniqid() . '.' $extension;
  2309.                     // Formats autorisés 
  2310.                     $allowTypes = array('pdf','jpg','png','jpeg','xls'); 
  2311.                     if(in_array($extension$allowTypes)){ 
  2312.                         move_uploaded_file($fileImage['tmp_name']['fichierFactureProForma'],"upload_Hk2DvAtDeUccGXh/".$newFilename);
  2313.                         $commande->setFichierFactureProForma($newFilename);
  2314.                     }
  2315.                     //On unlink l'ancien fichier
  2316.                     // if(file_exists("upload_Hk2DvAtDeUccGXh/".$oldFichier)) {
  2317.                         
  2318.                     //     unlink("upload_Hk2DvAtDeUccGXh/".$oldFichier);
  2319.                     // }
  2320.                 }
  2321.             }else{
  2322.                 $commande->setFichierFactureProForma($oldFichierProForma);
  2323.             }
  2324.             $em $this->getDoctrine()->getManager();
  2325.             $colisThisCommande $colisRepository->findColisByCommande($commande);
  2326.             
  2327.             foreach ($colisThisCommande as $key => $colisEnBdd) {
  2328.                     $colis $colisRepository->find($colisEnBdd);
  2329.                     $colisRepository->remove($colis); 
  2330.             }
  2331.             if (array_key_exists("new"$postColis)) {
  2332.                 foreach ($postColis['new'] as $postColi) {
  2333.                     $colis = new Colis();
  2334.                     $colis->setNombreBouteille($postColi);
  2335.                     $colis->setCommande($commande);
  2336.                     $em->persist($colis);
  2337.                     $em->flush();
  2338.                     $commande->addColi($colis);
  2339.                 }
  2340.             }
  2341.             $nbMagnumSaisi intval($postCommande['nombreMagnumRouge']) + intval($postCommande['nombreMagnumBlanc']) + intval($postCommande['nombreMagnumPetillant']); 
  2342.             $nbBouteillesSaisi intval($postCommande['nombreBouteilleRouge']) + intval($postCommande['nombreBouteilleBlanc']) + intval($postCommande['nombreBouteillePetillant']); 
  2343.             
  2344.             $nbBouteillesTotal = ($nbMagnumSaisi 2) + $nbBouteillesSaisi;
  2345.             if($nbBouteillesTotal 36 && !$this->roleAdmin){
  2346.                 $commande->setCommandeMassive(true);
  2347.                 $this->emailGeneratorService->sendMassiveCommande($commande);
  2348.             }
  2349.             $commandeRepository->add($commandetrue);
  2350.             $indexData = [
  2351.                 'id' => $commande->getId(),
  2352.                 'numero_facture' => $commande->getNumeroFacture(),
  2353.                 'code_postal_livraison' => $commande->getCodePostalLivraison(),
  2354.                 'ville_livraison' => $commande->getVilleLivraison(),
  2355.             ];
  2356.     
  2357.             $this->utilsService->updateIndex('commande'$indexData$commande->getId());
  2358.             // exit();
  2359.             return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  2360.         }
  2361.         $colisThisCommande $colisRepository->findColisByCommande($commande);
  2362.         return $this->renderForm('commande/edit.html.twig', [
  2363.             'commande' => $commande,
  2364.             'form' => $form,
  2365.             'admin' => $this->roleAdmin,
  2366.             'user' => $this->getUser(),
  2367.             'colisThisCommande' => $colisThisCommande,
  2368.             'edit' => true
  2369.         ]);
  2370.     }
  2371.     //i think this not used anymore, need to check
  2372.     /**
  2373.      * @Route("/{id}/packing", name="packing", methods={"GET"})
  2374.      */
  2375.     public function emballageCommande(Commande $commandeCommandeRepository $commandeRepository): Response
  2376.     {
  2377.         /* if (!$this->roleAdmin) {
  2378.             return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  2379.         } */
  2380.         if ($this->roleAdmin) {
  2381.             $commande->setState("attente_pec_transporteur");
  2382.         }
  2383.         else {
  2384.             if($commande->isIsValideeParClient() == true) {
  2385.                 $commande->setState("attente_pec_transporteur");
  2386.             }
  2387.             else {
  2388.                 $commande->setState("attente_client");
  2389.             }
  2390.         }
  2391.         
  2392.         $commandeRepository->add($commandetrue);
  2393.         return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  2394.     }
  2395.     /**
  2396.      * @Route("/{id}/forcevalidate", name="validate_force", methods={"GET"})
  2397.      */
  2398.     public function forceValidate(Commande $commandeCommandeRepository $commandeRepository): Response
  2399.     {
  2400.         $oldState $commande->getState();
  2401.         $cavistePacking $commande->isEmballageLivraison();
  2402.         if($cavistePacking){
  2403.             $packing "emballage_par_caviste";
  2404.         } else {
  2405.             $packing "emballage_par_mbe";
  2406.         }
  2407.         if (!$this->roleAdmin) {
  2408.             return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  2409.         }
  2410.         $commande->setIsValideeParClient(true);
  2411.         
  2412.         if($commande->getState() == "attente_client"){
  2413.             $commande->setState($commande->isEmballageLivraison() ? "attente_pec_transporteur" "attente_collecte_mbe");
  2414.         }
  2415.         $commandeRepository->add($commandetrue);
  2416.         return $this->redirectToRoute('app_commande_index', ['state' => $oldState'packaging' => $packing], Response::HTTP_SEE_OTHER);
  2417.     }
  2418.     /**
  2419.      * @Route("/{id}/archive", name="archive", methods={"GET"})
  2420.      */
  2421.     public function archiveCommande(Commande $commandeCommandeRepository $commandeRepository): Response
  2422.     {
  2423.         /* if (!$this->roleAdmin) {
  2424.             return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  2425.         } */
  2426.         $commande->setState("archive");
  2427.         $commandeRepository->add($commandetrue);
  2428.         return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  2429.     }
  2430.     /**
  2431.      * @Route("/{id}/creneau", name="update_creno", methods={"GET", "POST"})
  2432.      */
  2433.     public function updateCreneau(Request $requestCommande $commandeCommandeRepository $commandeRepository): Response
  2434.     {
  2435.         if (!$this->roleAdmin && $this->getUser()->getClient() != $commande->getClient() ) {
  2436.             return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  2437.         }
  2438.         $form $this->createForm(CommandeCreneauType::class, $commande);
  2439.         $form->handleRequest($request);
  2440.         if ($form->isSubmitted() && $form->isValid() ) {
  2441.             $commandeRepository->add($commandetrue);
  2442.             return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  2443.         }
  2444.         return $this->renderForm('commande/creneau_update.html.twig', [
  2445.             'form' => $form,
  2446.             'user' => $this->getUser(),
  2447.             'admin' => $this->roleAdmin,
  2448.         ]);
  2449.     }
  2450.     /**
  2451.      * @Route("/{id}/client", name="app_commande_client", methods={"GET", "POST"})
  2452.      */
  2453.     public function listeCommandeClient(Request $requestClient $clientPaginatorInterface $paginatorCommandeRepository $commandeRepository): Response
  2454.     {
  2455.         $user $this->getUser();
  2456.         $data $commandeRepository->findByClient($client->getId());
  2457.         $state null;
  2458.         $commandes $paginator->paginate(
  2459.             $data,
  2460.             $request->query->getInt('page'1),
  2461.             20
  2462.         );
  2463.         return $this->render('commande/index_commandes_par_client.html.twig', [
  2464.             'nom_client' => $client->getRaisonSociale(),
  2465.             'commandes' => $commandes,
  2466.             'user' => $user,
  2467.             'admin' => $this->roleAdmin,
  2468.         ]);
  2469.         // return $this->render('commande/index.html.twig', [
  2470.         //     'commandes' => $commandes,
  2471.         //     'stateController' => $state,
  2472.         //     'user' => $this->getUser(),
  2473.         //     'admin' => $this->roleAdmin
  2474.         // ]);
  2475.     }
  2476.     /**
  2477.      * @Route("/{id}/updateState", name="app_commande_update_state", methods={"GET"})
  2478.      */
  2479.     public function updateStatusCommande(Request $requestCommande $commandeCommandeRepository $commandeRepository): Response
  2480.     {   
  2481.         //true = caviste
  2482.         //false = mbe
  2483.         $cavistePacking $commande->isEmballageLivraison();
  2484.         $clientFinalValidate $commande->isIsValideeParClient();
  2485.         $commandeState $commande->getState();
  2486.         $oldState $commande->getState();
  2487.         $newState $commande->getState();
  2488.         if($cavistePacking){
  2489.             $packing "emballage_par_caviste";
  2490.             if($commandeState == "emballage_caviste"){
  2491.                 if($clientFinalValidate){
  2492.                     $newState "attente_pec_transporteur";
  2493.                 } else {
  2494.                     $newState "attente_client";
  2495.                 }
  2496.             }
  2497.         } else {
  2498.             $packing "emballage_par_mbe";
  2499.             if($commandeState == "preparation"){
  2500.                 if($clientFinalValidate){
  2501.                     $newState "attente_collecte_mbe";
  2502.                 } else {
  2503.                     $newState "attente_client";
  2504.                 }
  2505.             }
  2506.             if($commandeState == "attente_collecte_mbe"){
  2507.                 $newState "emballage_mbe";
  2508.             }
  2509.             
  2510.             if($commandeState == "emballage_mbe"){
  2511.                 $newState "attente_pec_transporteur";
  2512.             }
  2513.         }
  2514.         if($commandeState == "attente_pec_transporteur"){
  2515.             $newState "archive";
  2516.         }
  2517.         $commande->setState($newState);
  2518.         $commandeRepository->add($commandetrue);
  2519.         $this->addFlash("success""Le statut de la commande a été modifié");
  2520.         return $this->redirectToRoute('app_commande_index', ['state' => $oldState'packaging' => $packing], Response::HTTP_SEE_OTHER);
  2521.     }
  2522.     /**
  2523.      * @Route("/{id}/undoState", name="app_commande_undo_state", methods={"GET"})
  2524.      */
  2525.     public function undoStatusArchiveCommande(Request $requestCommande $commandeCommandeRepository $commandeRepository): Response
  2526.     {   
  2527.         $commandeState $commande->getState();
  2528.         $newState $commande->getState();
  2529.         if($commandeState == "archive"){
  2530.             $newState "attente_pec_transporteur";
  2531.         }
  2532.         $commande->setState($newState);
  2533.         $commandeRepository->add($commandetrue);
  2534.         $this->addFlash("success""Le statut de la commande a été modifié");
  2535.         return $this->redirectToRoute('app_commande_index', ['state' => $newState], Response::HTTP_SEE_OTHER);
  2536.     }
  2537.     public function getFedexToken()
  2538.     {
  2539.         $url "https://apis.fedex.com/oauth/token";
  2540.         $payload "grant_type=client_credentials&client_id=l7c771e0d2fd444799b4ce63c4ccd10032&client_secret=7dacb43d3ecc4d239d27236f37a39075";
  2541.         $ch curl_init($url);
  2542.         curl_setopt($chCURLOPT_POST1);
  2543.         curl_setopt($chCURLOPT_POSTFIELDS$payload);
  2544.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  2545.         $response curl_exec($ch);
  2546.         $json json_decode($responsetrue);
  2547.         curl_close($ch);
  2548.         return $json['access_token'];
  2549.     }
  2550.     /**
  2551.      * @Route("/{id}/fedex", name="fedex_info", methods={"GET"})
  2552.      */
  2553.     public function getFedexShippingPdf(Commande $commandeCommandeRepository $commandeRepository): Response
  2554.     {
  2555.         $user $this->getUser();
  2556.         $client $commande->getClient();
  2557.         if (!$this->roleAdmin) {
  2558.             if ($user != $client->getUser()) {
  2559.                 return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  2560.             }
  2561.         }
  2562.         $accountNumber "782780123";
  2563.         $fedexToken $this->getFedexToken();
  2564.         $fedexEndpoint "https://apis.fedex.com/ship/v1/shipments";
  2565.         $totalBottles $commande->getNombreBouteilleRouge() + $commande->getNombreBouteilleBlanc() + $commande->getNombreBouteillePetillant() + ($commande->getNombreMagnumRouge() * ) + ($commande->getNombreMagnumBlanc() * ) + ($commande->getNombreMagnumPetillant() * );
  2566.         $totalPrice $commande->getMontantTotalFacture();
  2567.         $weightOfAllPackage $totalBottles 1.5;
  2568.         $bottleValue round($totalPrice $totalBottles2);
  2569.         $commodities '';
  2570.         $requestedPackageLineItems '';
  2571.         $docs '';
  2572.         // parti colis
  2573.         $colis $commande->getColis();
  2574.         $docIds $this->getDocumentId($commande);
  2575.         
  2576.         
  2577.         foreach($colis as $coli){
  2578.             $bottles $coli->getNombreBouteille();
  2579.             $weight $bottles 1.5;
  2580.             $commodities .= '{
  2581.                 "quantity": "1",
  2582.                 "unitPrice":{
  2583.                     "amount":"' $bottleValue '",
  2584.                     "currency":"EUR"
  2585.                 },
  2586.                 "customsValue": {
  2587.                     "amount": "' $bottleValue $bottles '",
  2588.                     "currency": "EUR"
  2589.                 },
  2590.                 "quantityUnits":"PCS",
  2591.                 "description": "The carton consists of bottles of wine under 14% alchohol.",
  2592.                 "name":"Wine",
  2593.                 "countryOfManufacture": "FR",
  2594.                 "weight":{
  2595.                   "units":"KG",
  2596.                   "value":"' $weight '"
  2597.                 }
  2598.             },';
  2599.             $requestedPackageLineItems .= '{
  2600.                 "groupPackageCount": "1",
  2601.                 "subPackagingType": "OTHER",
  2602.                 "weight":{
  2603.                   "units":"KG",
  2604.                   "value":"' $weight '"
  2605.                 },
  2606.                 "packageSpecialServices": {
  2607.                     "specialServiceTypes": [
  2608.                       "ALCOHOL",
  2609.                       "SIGNATURE_OPTION"
  2610.                     ],
  2611.                     "alcoholDetail": {
  2612.                       "alcoholRecipientType": "CONSUMER"
  2613.                     },
  2614.                     "signatureOptionType": "DIRECT"
  2615.                 }
  2616.             },';
  2617.         }
  2618.         foreach($docIds as $docId){
  2619.             $docs .= '{
  2620.                 "documentId": "' $docId '"
  2621.                 },';
  2622.         }
  2623.         //client final
  2624.         $recipientsName $commande->getClientFinal()->getFullName();
  2625.         $recipientsPhone $commande->getClientFinal()->getTelephone();
  2626.         $recipientsAddress $commande->getAdresseLivraison();
  2627.         $recipientsAddressCompl $commande->getComplementAdresseLivraison();
  2628.         $recipientsCity $commande->getVilleLivraison();
  2629.         $recipientsStateOrProvinceCode $commande->getEtatUs();
  2630.         $recipientsPostalCode $commande->getCodePostalLivraison();
  2631.         $recipientsEmail $commande->getClientFinal()->getEmail();
  2632.         // A SAUVEGARDER, pour système notification.
  2633.         // emailNotificationDetail: {
  2634.         //     "aggregationType": "PER_SHIPMENT",
  2635.         //     "emailNotificationRecipients": [
  2636.         //         {
  2637.         //             "name" : "' . $recipientsName . '",
  2638.         //             "emailNotificationRecipientType" : "RECIPIENT",
  2639.         //             "emailAddress" : "' . $recipientsEmail . '",
  2640.         //             "notificationFormatType" : "HTML",
  2641.         //             "locale" : "en_US",
  2642.         //             "notificationEventType" : ["ON_DELIVERY", "ON_EXCEPTION", "ON_SHIPMENT", "ON_TENDER", "ON_ESTIMATED_DELIVERY"]
  2643.         //         }
  2644.         //     ]
  2645.         // },
  2646.         if($recipientsAddressCompl && $recipientsAddressCompl != "" && $recipientsAddressCompl != " ") {
  2647.             if(strlen($recipientsAddressCompl) < 35) {
  2648.                 $recipientsAddress .= '", "' $recipientsAddressCompl;
  2649.             }
  2650.             else {
  2651.                 $partsAddressCompl explode(" "$recipientsAddressCompl);
  2652.                 $line1 $line2 "";
  2653.                 foreach ($partsAddressCompl as $key => $partAddressCompl) {
  2654.                     if((strlen($line1) + strlen($partAddressCompl)) < 35) {
  2655.                         $line1 .= $partAddressCompl " ";
  2656.                     }
  2657.                     else if((strlen($line2) + strlen($partAddressCompl)) < 35) {
  2658.                         $line2 .= $partAddressCompl " ";
  2659.                     }
  2660.     
  2661.                 }
  2662.                 if($line1 != "") {
  2663.                     $recipientsAddress .= '", "' $line1;
  2664.                 }
  2665.                 if($line2 != "") {
  2666.                     $recipientsAddress .= '", "' $line2;
  2667.                 }
  2668.             }
  2669.         }
  2670.         // var_dump($commande->isDap());
  2671.         // var_dump($commande->isServicePriority());        
  2672.         $prio "INTERNATIONAL_ECONOMY";
  2673.         if($commande->isServicePriority()){
  2674.             // var_dump("on rentre dap");
  2675.             $prio "FEDEX_INTERNATIONAL_PRIORITY";    
  2676.         }else{
  2677.             // var_dump("on rentre pas dap");
  2678.         }
  2679.         $typePayment "SENDER";
  2680.         if($commande->isDap()){     
  2681.             // var_dump("on rentre servicePriority");
  2682.             $typePayment "RECIPIENT";
  2683.         }else{
  2684.             // var_dump("on rentre pas servicePriority");
  2685.         }
  2686.         // exit();
  2687.         $post '{
  2688.             "labelResponseOptions": "URL_ONLY",
  2689.               "requestedShipment": {
  2690.                 "shipmentSpecialServices": {
  2691.                     "specialServiceTypes": [
  2692.                             "ELECTRONIC_TRADE_DOCUMENTS"
  2693.                     ],
  2694.                     "etdDetail": {
  2695.                         "attachedDocuments":['rtrim($docs',') .']
  2696.                     }
  2697.                 },
  2698.                 "customsClearanceDetail":{
  2699.                   "dutiesPayment":{
  2700.                       "paymentType":"'.$typePayment.'"
  2701.                   },
  2702.                   "commercialInvoice":{},
  2703.                   "commodities" : [' rtrim($commodities',') . '],
  2704.                   "dutiesPayment":{
  2705.                     "payor":{
  2706.                     },
  2707.                     "billingDetails":{},
  2708.                     "paymentType": "'.$typePayment.'"
  2709.                   }     
  2710.                 }, 
  2711.                 "shipper": {
  2712.                   "contact": {
  2713.                     "companyName" : "FR0011 MBE MERIGNAC VIN USA",
  2714.                     "phoneNumber": "1234567890"
  2715.                   },
  2716.                   "address": {
  2717.                     "streetLines": [
  2718.                       "FR0011 MBE MERIGNAC VIN USA",
  2719.                       "11, RUE JACQUARD"
  2720.                     ],
  2721.                     "city": "MERIGNAC",
  2722.                     "postalCode": "33700",
  2723.                     "countryCode": "FR"
  2724.                   }
  2725.                 },
  2726.                 "recipients": [
  2727.                   {
  2728.                     "contact": {
  2729.                       "personName": "' $recipientsName '",
  2730.                       "phoneNumber": "' $recipientsPhone '"
  2731.                     },
  2732.                     "address": {
  2733.                       "streetLines": [
  2734.                         "' $recipientsAddress '"
  2735.                       ],
  2736.                       "city": "' $recipientsCity '",
  2737.                       "stateOrProvinceCode": "' $recipientsStateOrProvinceCode '",
  2738.                       "postalCode": "' $recipientsPostalCode '",
  2739.                       "countryCode": "US"
  2740.                     }
  2741.                   }
  2742.                 ],
  2743.                 "pickupType" : "CONTACT_FEDEX_TO_SCHEDULE",
  2744.                 "serviceType" : "'.$prio.'",
  2745.                 "packagingType" : "YOUR_PACKAGING",
  2746.                 "blockInsightVisibility": true,
  2747.                 "shippingChargesPayment": {
  2748.                   "paymentType": "SENDER"
  2749.                 },
  2750.                 "labelSpecification": {
  2751.                   "imageType": "PDF",
  2752.                   "labelStockType": "PAPER_LETTER"
  2753.                 },
  2754.                 "totalPackageCount":' $commande->getNombreColisTotal() . ' ,
  2755.                 "requestedPackageLineItems": [' rtrim($requestedPackageLineItems',') . ']
  2756.               },
  2757.             "accountNumber": {
  2758.               "value": "' $accountNumber '"
  2759.             }
  2760.           }
  2761.         ';
  2762.         $curl curl_init();
  2763.         
  2764.         curl_setopt_array($curl, array(
  2765.             CURLOPT_URL => $fedexEndpoint,
  2766.             CURLOPT_RETURNTRANSFER => true,
  2767.             CURLOPT_ENCODING => '',
  2768.             CURLOPT_MAXREDIRS => 10,
  2769.             CURLOPT_TIMEOUT => 0,
  2770.             CURLOPT_FOLLOWLOCATION => true,
  2771.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  2772.             CURLOPT_CUSTOMREQUEST => 'POST',
  2773.             CURLOPT_POSTFIELDS => $post,
  2774.             CURLOPT_HTTPHEADER => array(
  2775.                 'x-customer-transaction-id: 624deea6-b709-470c-8c39-4b5511281492',
  2776.                 'x-locale: en_US',
  2777.                 'Content-Type: application/json',
  2778.                 'Authorization: Bearer ' $fedexToken
  2779.             ),
  2780.         ));
  2781.         $response curl_exec($curl);
  2782.         $json json_decode($responsetrue);
  2783.         if (isset($json['errors'])) {
  2784.             foreach ($json['errors'] as $error) {
  2785.                 $this->addFlash("error"$error['message'] . '(Code erreur : "' .  $error["code"] . '")');
  2786.             }
  2787.         } else {
  2788.             $url "";
  2789.             $trackingNumbers "";
  2790.             if($commande->getNombreColisTotal() > 1){
  2791.                 $url $json['output']['transactionShipments'][0]['shipmentDocuments'][0]['url'];
  2792.                 foreach($json['output']['transactionShipments'][0]['pieceResponses'] as $x ){
  2793.                     $trackingNumbers $trackingNumbers $x['trackingNumber'] . ', ' ;
  2794.                 }
  2795.                 $commande->setIndividualTrackingNumbers($trackingNumbers);
  2796.             } else {
  2797.                 $url $json['output']['transactionShipments'][0]['pieceResponses'][0]['packageDocuments'][0]['url'];
  2798.             }
  2799.             $trackingNumber $json['output']['transactionShipments'][0]['masterTrackingNumber'];
  2800.             $numFacture $this->is_valid_filename($commande->getNumeroFacture());
  2801.             $fileName 'shipping_' $trackingNumber '.pdf';
  2802.             file_put_contents('etiquette_eXfdeEI18e68F48E6f4e89/' $fileNamefopen($url'r'));
  2803.             $fileContent file_get_contents('etiquette_eXfdeEI18e68F48E6f4e89/' $fileName);
  2804.             $magicBytes substr($fileContent04); // Read the first 4 bytes
  2805.             $date = new DateTime($json['output']['transactionShipments'][0]["shipDatestamp"]);
  2806.             // Check if the first 4 bytes match the PDF file signature
  2807.             if ($magicBytes === "%PDF") {
  2808.                 $commande->setFedexPdfGenerated(true);
  2809.                 $commande->setTrackingNumber($trackingNumber);
  2810.                 $commande->setShipDate($date);
  2811.                 $commandeRepository->add($commandetrue);
  2812.                 $this->addFlash("success""PDF généré");
  2813.                 // Email envoi caviste uniquement $commande->isEmballageLivraison() == 'emballage_par_caviste' en pièce jointe le PDF
  2814.                 if($commande->isEmballageLivraison()){
  2815.                     $this->emailGeneratorService->sendFedexShippingDocument($commande$client);
  2816.                 }
  2817.                 $indexData = [
  2818.                     'id' => $commande->getId(),
  2819.                     'numero_facture' => $commande->getNumeroFacture(),
  2820.                     'code_postal_livraison' => $commande->getCodePostalLivraison(),
  2821.                     'ville_livraison' => $commande->getVilleLivraison(),
  2822.                     'tracking_number' => $trackingNumber,
  2823.                 ];
  2824.         
  2825.                 $this->utilsService->updateIndex('commande'$indexData$commande->getId());
  2826.                 
  2827.                 $dateCreneau1Clone = clone $commande->getDateCollecte();
  2828.                 $dateCreneau2Clone = clone $commande->getDateCollecte();
  2829.             
  2830.         
  2831.                 if($commande->isEmballageLivraison()){
  2832.                     $dateCreneau1Brut $dateCreneau1Clone->modify("+7 days");
  2833.                     $dateCreneau2Brut $dateCreneau2Clone->modify("+12 days");
  2834.                 } else {
  2835.                     $dateCreneau1Brut $dateCreneau1Clone->modify("+22 days");
  2836.                     $dateCreneau2Brut $dateCreneau2Clone->modify("+27 days");
  2837.                 }
  2838.         
  2839.                 $dateCreneau1 $dateCreneau1Brut->format('d/m/Y');
  2840.                 $dateCreneau2 $dateCreneau2Brut->format('d/m/Y');
  2841.                 
  2842.                 $numeroSuivi $commande->getTrackingNumber();
  2843.                 $linkTracking 'https://www.fedex.com/fedextrack/?trknbr='.$numeroSuivi.'&trkqual=2460581000~'.$numeroSuivi.'~FX';
  2844.                 $res $this->emailGeneratorService->sendEmailToFinalCustomerTrack(
  2845.                     $commande->getClientFinal()->getEmail(),
  2846.                     $commande->getClientFinal()->getFullName(),
  2847.                     $commande->getClient()->getRaisonSociale(),
  2848.                     $dateCreneau1,
  2849.                     $dateCreneau2,
  2850.                     $numeroSuivi,
  2851.                     $linkTracking
  2852.                 );
  2853.                               
  2854.                 
  2855.             } else {
  2856.                 $this->addFlash("error""PDF non généré");
  2857.                 $this->cancelFedex($trackingNumber);
  2858.             }
  2859.         }
  2860.         curl_close($curl);
  2861.         return $this->redirectToRoute('app_commande_index', ['state' => 'attente_pec_transporteur''packaging' => $commande->isEmballageLivraison() ? 'emballage_par_caviste' 'emballage_par_mbe'], Response::HTTP_SEE_OTHER);
  2862.     }
  2863.     public function getDocumentId(Commande $commande)
  2864.     {
  2865.         $this->csv_facture($commandetrue);
  2866.         $numFacture $this->is_valid_filename($commande->getNumeroFacture());
  2867.         $docIds = [];
  2868.         $docIds[] = $this->fedexService->uploadDocumentPreShipFedex('./doc_kyseUa8iCjUywtKtgu8J/CSITTBPermitCA-I-22023V2.pdf''importerPermitInfo.pdf''application/pdf''OTHER');
  2869.         
  2870.         if($commande->getFichierFactureProForma() != null){
  2871.             $docIds[] = $this->fedexService->uploadDocumentPreShipFedex('./upload_Hk2DvAtDeUccGXh/'.$commande->getFichierFactureProForma(), $commande->getFichierFactureProForma(), 'application/vnd.ms-excel''PRO_FORMA_INVOICE');
  2872.         }else{
  2873.             $docIds[] = $this->fedexService->uploadDocumentPreShipFedex('./doc_kyseUa8iCjUywtKtgu8J/'.$commande->getProForma(), 'proInvoice_' $numFacture '.xls''application/vnd.ms-excel''PRO_FORMA_INVOICE');
  2874.         }        
  2875.         if($commande->getNombreBouteilleRouge() > || $commande->getNombreMagnumRouge() > 0){
  2876.             $docIds[] = $this->fedexService->uploadDocumentPreShipFedex('./doc_kyseUa8iCjUywtKtgu8J/CSIColaVinDeFranceROUGE.pdf''CSIColaVinDeFranceROUGE.pdf''application/pdf''OTHER');
  2877.         }
  2878.         if($commande->getNombreBouteilleBlanc() > || $commande->getNombreMagnumBlanc() > 0){
  2879.             $docIds[] = $this->fedexService->uploadDocumentPreShipFedex('./doc_kyseUa8iCjUywtKtgu8J/CSIColaVinDeFranceBLANC.pdf''CSIColaVinDeFranceBLANC.pdf''application/pdf''OTHER');
  2880.         }
  2881.         if($commande->getNombreBouteillePetillant() > || $commande->getNombreMagnumPetillant() > 0){
  2882.             $docIds[] = $this->fedexService->uploadDocumentPreShipFedex('./doc_kyseUa8iCjUywtKtgu8J/CSIColaCHAMPAGNE.pdf''CSIColaCHAMPAGNE.pdf''application/pdf''OTHER');
  2883.         }
  2884.         return $docIds;
  2885.     }
  2886.     /**
  2887.      * @Route("/{id}/addDocument", name="app_commande_add_document", methods={"GET", "POST"})
  2888.      */
  2889.     public function addDocumentPostShip(Commande $commandeCommandeRepository $commandeRepositoryRequest $request) : Response
  2890.     {   
  2891.         if (!$this->roleAdmin && $this->getUser()->getClient() != $commande->getClient() ) {
  2892.             return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  2893.         }
  2894.         $form $this->createFormBuilder()
  2895.             ->add('document'FileType::class, [
  2896.                 "label" => "Choisir un fichier",
  2897.                 "required" => true,
  2898.                 "data_class" => null,
  2899.                 "attr" => ["hidden" => true"name" => "myFile""class" => "drop-zone__input"],
  2900.             ])  
  2901.             ->getForm();
  2902.         $form->handleRequest($request);
  2903.         if ($form->isSubmitted()) {    
  2904.             $file $_FILES['myFile'];
  2905.             $name $file['name'];                    
  2906.             $originalFilename pathinfo($namePATHINFO_FILENAME);
  2907.             // $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
  2908.             // $safeFilenameClean = $this->is_valid_filename($safeFilename);
  2909.             
  2910.             $extension pathinfo($namePATHINFO_EXTENSION);
  2911.                                 
  2912.             $newFilename 'prior_' $commande->getTrackingNumber() . '_' uniqid() . '.' $extension;
  2913.             
  2914.             // Formats autorisés 
  2915.             $allowTypes = array('pdf','jpg','png','jpeg'); 
  2916.             if(in_array($extension$allowTypes)){                 
  2917.                 move_uploaded_file($file['tmp_name'],"upload_Hk2DvAtDeUccGXh/".$newFilename);
  2918.             }
  2919.             $res $this->fedexService->uploadDocumentPostShipFedex("upload_Hk2DvAtDeUccGXh/".$newFilename'document.pdf''application/pdf''OTHER'$commande->getTrackingNumber(), $commande->getShipDate());
  2920.             if($res == 'error'){
  2921.                 $this->addFlash("error""Erreur Document non ajouté");
  2922.             } else {
  2923.                 $this->addFlash("success""Document ajouté");
  2924.                 $commande->setFedexPdfAvailable(true);
  2925.                 $commande->setPriorUrl($newFilename);
  2926.                 $commandeRepository->add($commandetrue);
  2927.             }
  2928.             return $this->redirectToRoute('app_commande_index', ['state' => 'attente_pec_transporteur''packaging' => $_GET['packing']], Response::HTTP_SEE_OTHER);
  2929.         }
  2930.         return $this->renderForm('commande/addDocument.html.twig', [
  2931.             'form' => $form,
  2932.             'user' => $this->getUser(),
  2933.             'admin' => $this->roleAdmin,
  2934.         ]);
  2935.     }
  2936.     /**
  2937.      * @Route("/{id}/cancelshipping", name="app_commande_cancel_shipping", methods={"GET"})
  2938.      */
  2939.     public function cancelShipping(Commande $commandeCommandeRepository $commandeRepository) : Response
  2940.     {
  2941.         $fedexCommandeTokken $commande->getTrackingNumber();
  2942.         $fileName 'etiquette_eXfdeEI18e68F48E6f4e89/shipping_' $fedexCommandeTokken '.pdf';
  2943.         $priorName $commande->getPriorUrl();
  2944.         $res $this->cancelFedex($fedexCommandeTokken);
  2945.         if($res["output"]["cancelledShipment"]){
  2946.             $commande->setFedexPdfGenerated(false);
  2947.             $commande->setTrackingNumber(NULL);
  2948.             $commande->setShipDate(NULL);
  2949.             $commande->setFedexPdfAvailable(false);
  2950.             $commande->setPriorUrl(NULL);
  2951.             $commande->setIndividualTrackingNumbers(NULL);
  2952.             $commandeRepository->add($commandetrue);
  2953.             if (file_exists($fileName)) {
  2954.                 unlink($fileName);
  2955.             }
  2956.             if (file_exists($priorName)) {
  2957.                 unlink($priorName);
  2958.             }
  2959.             $this->addFlash("success""Commande annulée");
  2960.         } else {
  2961.             $this->addFlash("error""La commande n'a pas été annulée");
  2962.         }
  2963.         return $this->redirectToRoute('app_commande_index', ['state' => 'attente_pec_transporteur'], Response::HTTP_SEE_OTHER);
  2964.     }
  2965.     /**
  2966.      * @Route("/{id}/cancelCommande", name="app_commande_cancel", methods={"GET"})
  2967.      */
  2968.     public function cancelCommande(Commande $commandeCommandeRepository $commandeRepository) : Response
  2969.     {
  2970.         $fedexCommandeTokken $commande->getTrackingNumber();
  2971.         if($fedexCommandeTokken) {
  2972.             $res $this->cancelFedex($fedexCommandeTokken);
  2973.         }
  2974.         if(!$fedexCommandeTokken || $res["output"]["cancelledShipment"]){
  2975.             $commande->setFedexPdfGenerated(false);
  2976.             $commande->setTrackingNumber(NULL);
  2977.             $commande->setShipDate(NULL);
  2978.             $commande->setFedexPdfAvailable(false);
  2979.             $commande->setState('canceled');
  2980.             $commandeRepository->add($commandetrue);
  2981.             $this->addFlash("success""Commande annulée");
  2982.         } else {
  2983.             $this->addFlash("error""La commande n'a pas été annulée");
  2984.         }
  2985.         return $this->redirectToRoute('app_commande_index', ['state' => 'attente_pec_transporteur'], Response::HTTP_SEE_OTHER);
  2986.     }
  2987.     private function cancelFedex($trackingNumber)
  2988.     {
  2989.         $fedexEndpoint 'https://apis.fedex.com/ship/v1/shipments/cancel';
  2990.         $payload '{
  2991.             "trackingNumber": " ' $trackingNumber ' ",
  2992.             "senderCountryCode": "FR",
  2993.             "deletionControl": "DELETE_ALL_PACKAGES",
  2994.             "accountNumber": {
  2995.                 "value": "782780123"
  2996.             }
  2997.         }';
  2998.         $curl curl_init();
  2999.         curl_setopt_array($curl, array(
  3000.             CURLOPT_URL => $fedexEndpoint,
  3001.             CURLOPT_RETURNTRANSFER => true,
  3002.             CURLOPT_ENCODING => '',
  3003.             CURLOPT_MAXREDIRS => 10,
  3004.             CURLOPT_TIMEOUT => 0,
  3005.             CURLOPT_FOLLOWLOCATION => true,
  3006.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  3007.             CURLOPT_CUSTOMREQUEST => 'PUT',
  3008.             CURLOPT_POSTFIELDS => $payload,
  3009.             CURLOPT_HTTPHEADER => array(
  3010.                 'x-customer-transaction-id: 624deea6-b709-470c-8c39-4b5511281492',
  3011.                 'x-locale: en_US',
  3012.                 'Content-Type: application/json',
  3013.                 'Authorization: Bearer ' $this->getFedexToken()
  3014.             ),
  3015.         ));
  3016.         $response curl_exec($curl);
  3017.         $json json_decode($responsetrue);
  3018.         return $json;
  3019.     }
  3020.     /**
  3021.      * @Route("/{id}", name="app_commande_delete", methods={"POST"})
  3022.      */
  3023.     // public function delete(Request $request, Commande $commande, CommandeRepository $commandeRepository): Response
  3024.     // {
  3025.     //     if ($this->isCsrfTokenValid('delete' . $commande->getId(), $request->request->get('_token'))) {
  3026.     //         $commandeRepository->remove($commande, true);
  3027.     //     }
  3028.     //     return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  3029.     // }
  3030.     /**
  3031.      * @Route("/{id}/csv_invoice", name="csv_invoice", methods={"GET"})
  3032.      */
  3033.     public function csv_facture(Commande $commande$internalCall false): Response
  3034.     {
  3035.         $user $this->getUser();
  3036.         $client $commande->getClient();
  3037.         if (!$this->roleAdmin) {
  3038.             if ($user != $client->getUser()) {
  3039.                 return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
  3040.             }
  3041.         }
  3042.         $spreadsheet = new Spreadsheet();
  3043.         $sheet $spreadsheet->getActiveSheet();
  3044.         $writer = new Xls($spreadsheet);
  3045.         $fileName =  $commande->getClientFinal()->getFullName() . " Invoice";
  3046.         $sheet $spreadsheet->getActiveSheet();
  3047.         //Styling the sheet
  3048.         //invoice data block
  3049.         $sheet->mergeCells('B2:C2');
  3050.         $sheet->mergeCells('B3:C3');
  3051.         //shipper block
  3052.         $sheet->mergeCells('A7:B7');
  3053.         $sheet->mergeCells('A8:B8');
  3054.         $sheet->mergeCells('A9:B9');
  3055.         $sheet->mergeCells('A10:B10');
  3056.         $sheet->mergeCells('A11:B11');
  3057.         $sheet->mergeCells('A12:B12');
  3058.         //importer/delivery block
  3059.         $sheet->mergeCells('E2:F2');
  3060.         $sheet->mergeCells('E3:F3');
  3061.         $sheet->mergeCells('E4:F4');
  3062.         $sheet->mergeCells('E5:F5');
  3063.         $sheet->mergeCells('E6:F6');
  3064.         $sheet->mergeCells('E7:F7');
  3065.         $sheet->mergeCells('E8:F8');
  3066.         $sheet->mergeCells('G2:H2');
  3067.         $sheet->mergeCells('G3:H3');
  3068.         $sheet->mergeCells('G4:H4');
  3069.         $sheet->mergeCells('G5:H5');
  3070.         $sheet->mergeCells('G6:H6');
  3071.         $sheet->mergeCells('G7:H7');
  3072.         $sheet->mergeCells('G8:H8');
  3073.         $sheet->mergeCells('G9:H9');
  3074.         $sheet->mergeCells('E10:H10');
  3075.         $sheet->mergeCells('E11:H11');
  3076.         $sheet->mergeCells('E12:H12');
  3077.         //manufacturer/producer block
  3078.         $sheet->mergeCells('A23:E23');
  3079.         $sheet->mergeCells('A25:B25');
  3080.         $sheet->mergeCells('A26:B26');
  3081.         $sheet->mergeCells('A27:B27');
  3082.         $sheet->mergeCells('A28:B28');
  3083.         $sheet->mergeCells('A29:B29');
  3084.         $sheet->mergeCells('A30:B30');
  3085.         $sheet->getColumnDimension('A')->setWidth(93'px');
  3086.         $sheet->getColumnDimension('B')->setWidth(237'px');
  3087.         $sheet->getColumnDimension('C')->setWidth(105'px');
  3088.         $sheet->getColumnDimension('D')->setWidth(88'px');
  3089.         $sheet->getColumnDimension('E')->setWidth(128'px');
  3090.         $sheet->getColumnDimension('F')->setWidth(111'px');
  3091.         $sheet->getColumnDimension('G')->setWidth(91'px');
  3092.         $sheet->getColumnDimension('H')->setWidth(217'px');
  3093.         $sheet->getColumnDimension('I')->setWidth(95'px');
  3094.         $styleBorder = [
  3095.             'borders' => [
  3096.                 'outline' => [
  3097.                     'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
  3098.                     'color' => ['argb' => '00000000'],
  3099.                 ],
  3100.             ],
  3101.         ];
  3102.         $styleBold = [
  3103.             'font' => [
  3104.                 'bold' => true,
  3105.             ],
  3106.         ];
  3107.         $styleLink = [
  3108.             'font' => [
  3109.                 'color' => array('rgb' => '006fbf'),
  3110.                 'underline' => true,
  3111.             ],
  3112.         ];
  3113.         $sheet->getStyle('A2')->applyFromArray($styleBorder);
  3114.         //$sheet->getStyle('A3:A4')->applyFromArray($styleBorder);
  3115.         $sheet->getStyle('A2:C3')->applyFromArray($styleBorder);
  3116.         //$sheet->getStyle('B3:C4')->applyFromArray($styleBorder);
  3117.         $sheet->getStyle('A7:B12')->applyFromArray($styleBorder);
  3118.         $sheet->getStyle('A25:B30')->applyFromArray($styleBorder);
  3119.         $sheet->getStyle('E2:F2')->applyFromArray($styleBorder);
  3120.         $sheet->getStyle('G2:h2')->applyFromArray($styleBorder);
  3121.         $sheet->getStyle('E3:F10')->applyFromArray($styleBorder);
  3122.         $sheet->getStyle('G3:H10')->applyFromArray($styleBorder);
  3123.         $sheet->getStyle('E10:H10')->applyFromArray($styleBorder);
  3124.         $sheet->getStyle('E11:H11')->applyFromArray($styleBorder);
  3125.         $sheet->getStyle('E12:H12')->applyFromArray($styleBorder);
  3126.         $sheet->getStyle('A15:I18')->applyFromArray($styleBorder);
  3127.         // $sheet->getStyle('A25:E25')->applyFromArray($styleBorder);
  3128.         // $sheet->getStyle('A26:E26')->applyFromArray($styleBorder);
  3129.         // $sheet->getStyle('A27:E27')->applyFromArray($styleBorder);
  3130.         $sheet->getStyle('A2:A7')->applyFromArray($styleBold);
  3131.         $sheet->getStyle('E2:H9')->applyFromArray($styleBold);
  3132.         $sheet->getStyle('E10:H13')->applyFromArray($styleBold);
  3133.         $sheet->getStyle('A23:G29')->applyFromArray($styleBold);
  3134.         $sheet->getStyle('A12')->applyFromArray($styleLink);
  3135.         $sheet->getStyle('E8:F8')->applyFromArray($styleLink);
  3136.         $sheet->getStyle('G9:H9')->applyFromArray($styleLink);
  3137.         $sheet->getStyle('A30')->applyFromArray($styleLink);
  3138.         $sheet->getStyle('G23:H25')
  3139.             ->getBorders()
  3140.             ->getAllBorders()
  3141.             ->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM)
  3142.             ->setColor(new Color('00000000'));
  3143.         $sheet->getStyle('A15:I18')
  3144.             ->getBorders()
  3145.             ->getInside()
  3146.             ->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN)
  3147.             ->setColor(new Color('00000000'));
  3148.         $sheet->getStyle('A2:C3')
  3149.             ->getBorders()
  3150.             ->getInside()
  3151.             ->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN)
  3152.             ->setColor(new Color('00000000'));
  3153.         $sheet->getStyle('A15:H18')->getAlignment()->setWrapText(true);
  3154.         $sheet->getStyle('A1:I30')->getAlignment()->setHorizontal('center');
  3155.         $sheet->getStyle('A1:I30')->getAlignment()->setVertical('center');
  3156.         $sheet->getStyle('A20:B22')->getAlignment()->setHorizontal('left');
  3157.         $sheet->setShowGridlines(false);
  3158.         $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  3159.         $drawing->setName('Paid');
  3160.         $drawing->setDescription('Paid');
  3161.         $drawing->setPath('https://wine.mbebordeaux.fr/images/PNG/mbe.png');
  3162.         $drawing->setCoordinates('G26');
  3163.         $drawing->setOffsetX(110);
  3164.         $drawing->setRotation(25);
  3165.         $drawing->getShadow()->setVisible(true);
  3166.         $drawing->setWorksheet($spreadsheet->getActiveSheet());
  3167.         //Sheet content
  3168.         //fixed value
  3169.         $sheet->setCellValue('A2''DATE');
  3170.         $sheet->setCellValue('A3''INVOICE NO.');
  3171.         //$sheet->setCellValue('A4', 'EORI ');
  3172.         $sheet->setCellValue('A7''MANUFACTURER');
  3173.         // $sheet->setCellValue('A8', 'MBE011 Mérignac');
  3174.         // $sheet->setCellValue('A9', '11, Rue Jacquard');
  3175.         // $sheet->setCellValue('A10', '33700 MERIGNAC');
  3176.         // $sheet->setCellValueExplicit('A11', '+33535546864', \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
  3177.         // $sheet->setCellValue('A12', 'mbe011@mbefrance.fr');
  3178.         // $sheet->getCell('A12')->getHyperlink()->setUrl('mailto:mbe011@mbefrance.fr');
  3179.         $sheet->setCellValue('A15''COUNTRY OF ORIGIN');
  3180.         $sheet->setCellValue('B15''DESCRIPTION');
  3181.         $sheet->setCellValue('C15''ALCOHOL %');
  3182.         $sheet->setCellValue('D15''HTS NUMBER');
  3183.         $sheet->setCellValue('E15''TTB ID NUMBER');
  3184.         $sheet->setCellValue('F15''No. Bottles');
  3185.         $sheet->setCellValue('G15''Unit Quantity');
  3186.         $sheet->setCellValue('H15''TOTAL QUANTITY (LITERS)');
  3187.         $sheet->setCellValue('I15''TOTAL VALUE');
  3188.         $sheet->setCellValue('A20''INCOTERM : ');
  3189.         
  3190.         if($commande->isDap()){
  3191.             $sheet->setCellValue('B20''DAP');
  3192.         }else{
  3193.             $sheet->setCellValue('B20''DDP');
  3194.         }
  3195.         
  3196.         $sheet->setCellValue('A21''The Exporter of the products covered by this document declares that, except where otherwise clearly indicated, these products are of European Union preferentiel origin.');
  3197.         $sheet->setCellValue('A22''Origin : ');
  3198.         $sheet->setCellValue('B22''France');
  3199.         $sheet->setCellValue('A23''Bottle with CRD Capsule - Duty free - DAE not established - Personnal Consumption');
  3200.         $sheet->setCellValue('A25''SHIPPER');
  3201.         // $sheet->setCellValue('E2', 'Bottle with CRD Capsule - Duty free - DAE not established - Personnal Consumption');
  3202.         // $sheet->setCellValue('E4', 'ISC');
  3203.         $sheet->setCellValue('E2''IMPORTER ADDRESS');
  3204.         $sheet->setCellValue('E4''Ilona Liberi DBA Chianti Services Imports');
  3205.         $sheet->setCellValue('E5''3141 Temescal Avenue');
  3206.         $sheet->setCellValue('E6''Norco, CA 92860');
  3207.         $sheet->setCellValue('E7''(949)306-3678');
  3208.         $sheet->setCellValue('E8''ilonaliberi@chiantiservicesimports.com');
  3209.         $sheet->getCell('E8')->getHyperlink()->setUrl('mailto:ilonaliberi@chiantiservicesimports.com');
  3210.         $sheet->setCellValue('G2''DELIVERY ADDRESS');
  3211.         $sheet->setCellValue('E10''TAX ID 81-5435990    ');
  3212.         $sheet->setCellValue('E11''TTB PERMIT CA - I - 22023');
  3213.         $sheet->setCellValue('E12''DUNS #08 084 6225 ');
  3214.         $sheet->setCellValue('G23''TOTAL VALUE:');
  3215.         $sheet->setCellValue('G24''TOTAL LITERS: ');
  3216.         $sheet->setCellValue('G25''TOTAL Bottles: ');
  3217.         //not fixed value
  3218.         $eori $client->getEori();
  3219.         $invoiceNo $commande->getNumeroFacture();
  3220.         $orderDate date('d-M-y');
  3221.         $finalClientName $commande->getClientFinal()->getFullName();
  3222.         $finalClientAdress $commande->getAdresseLivraison();
  3223.         $finalClientCity $commande->getVilleLivraison();
  3224.         $finalClientPhone $commande->getClientFinal()->getTelephone();
  3225.         $finalClientEmail $commande->getClientFinal()->getEmail();
  3226.         $clientInfo $client->getNomContact() . " - " $client->getAdresse() . " " $client->getCodePostal() . " " $client->getVille();
  3227.         $bottlesRed $commande->getNombreBouteilleRouge() + ( $commande->getNombreMagnumRouge() * );
  3228.         $bottlesWhite $commande->getNombreBouteilleBlanc() + ( $commande->getNombreMagnumBlanc() * );
  3229.         $bottlesSparkling $commande->getNombreBouteillePetillant() + ( $commande->getNombreMagnumPetillant() * );
  3230.         $totalBottles $bottlesRed $bottlesWhite $bottlesSparkling;
  3231.         $totalPrice $commande->getMontantTotalFacture();
  3232.         $bottlePrice $totalPrice $totalBottles;
  3233.         $sheet->setCellValue('B3'$invoiceNo);
  3234.         //$sheet->setCellValue('B4', $eori);
  3235.         $sheet->setCellValue('B2'$orderDate);
  3236.         $sheet->setCellValue('G3'$finalClientName);
  3237.         $sheet->setCellValue('G4'$finalClientAdress);
  3238.         $sheet->setCellValue('G5'$commande->getComplementAdresseLivraison());
  3239.         $sheet->setCellValue('G6'$finalClientCity ' , ' $commande->getCodePostalLivraison() . ' , ' $commande->getProvince());
  3240.         $sheet->setCellValue('G7''USA');
  3241.         $sheet->setCellValueExplicit('G8'$finalClientPhone\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
  3242.         $sheet->setCellValue('G9'$finalClientEmail);
  3243.         $sheet->getCell('G9')->getHyperlink()->setUrl('mailto:' $finalClientEmail);
  3244.         $sheet->setCellValue('H25'$totalBottles);
  3245.         $sheet->setCellValue('H24'$totalBottles 0.75);
  3246.         $sheet->setCellValue('H23'$totalPrice " €");
  3247.         $sheet->setCellValue('A26''MBE011 Mérignac');
  3248.         $sheet->setCellValue('A27''11, Rue Jacquard');
  3249.         $sheet->setCellValue('A28''33700 MERIGNAC');
  3250.         $sheet->setCellValueExplicit('A29''+33535546864'\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
  3251.         $sheet->setCellValue('A30''mbe011@mbefrance.fr');
  3252.         $sheet->getCell('A30')->getHyperlink()->setUrl('mailto:mbe011@mbefrance.fr');
  3253.         $sheet->setCellValue('A8'$client->getRaisonSociale());
  3254.         $sheet->setCellValue('A9'$client->getAdresse());
  3255.         $sheet->setCellValue('A10'$client->getVille() . " / France / " $client->getCodePostal());
  3256.         $sheet->setCellValue('A11'$eori);
  3257.         $sheet->setCellValue('A12'$client->getEmailContact());
  3258.         $sheet->getCell('A12')->getHyperlink()->setUrl('mailto:' $client->getEmailContact());
  3259.         
  3260.         $bI 16;
  3261.         if ($bottlesRed 0) {
  3262.             $sheet->setCellValue('A' $bI'FRANCE');
  3263.             $sheet->setCellValue('B' $bI'Red Table Wine - Bottle with CRD Capsule - Duty free - DAE not established ');
  3264.             $sheet->setCellValue('C' $bI'<= 14 %');
  3265.             $sheet->setCellValue('D' $bI'2204215040');
  3266.             $sheet->setCellValueExplicit('E' $bI'18216001000126'\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
  3267.             $sheet->setCellValue('F' $bI$bottlesRed);
  3268.             $sheet->setCellValue('G' $bI'0,75');
  3269.             $sheet->setCellValue('H' $bI$bottlesRed 0.75);
  3270.             $sheet->setCellValue('I' $bIround($bottlesRed $bottlePrice2) . " €");
  3271.             $bI++;
  3272.         }
  3273.         if ($bottlesWhite 0) {
  3274.             $sheet->setCellValue('A' $bI'FRANCE');
  3275.             $sheet->setCellValue('B' $bI'White Table Wine - Bottle with CRD Capsule - Duty free - DAE not established ');
  3276.             $sheet->setCellValue('C' $bI'<= 14 %');
  3277.             $sheet->setCellValue('D' $bI'2204215055');
  3278.             $sheet->setCellValueExplicit('E' $bI'18216001000127'\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
  3279.             $sheet->setCellValue('F' $bI$bottlesWhite);
  3280.             $sheet->setCellValue('G' $bI'0,75');
  3281.             $sheet->setCellValue('H' $bI$bottlesWhite 0.75);
  3282.             $sheet->setCellValue('I' $bIround($bottlesWhite $bottlePrice2) . " €");
  3283.             $bI++;
  3284.         }
  3285.         if ($bottlesSparkling 0) {
  3286.             $sheet->setCellValue('A' $bI'FRANCE');
  3287.             $sheet->setCellValue('B' $bI'Sparkling Table Wine - Bottle with CRD Capsule - Duty free - DAE not established ');
  3288.             $sheet->setCellValue('C' $bI'<= 14 %');
  3289.             $sheet->setCellValue('D' $bI'2204215075');
  3290.             $sheet->setCellValueExplicit('E' $bI'18216001000125'\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
  3291.             $sheet->setCellValue('F' $bI$bottlesSparkling);
  3292.             $sheet->setCellValue('G' $bI'0,75');
  3293.             $sheet->setCellValue('H' $bI$bottlesSparkling 0.75);
  3294.             $sheet->setCellValue('I' $bIround($bottlesSparkling $bottlePrice2) . " €");
  3295.         }  
  3296.         $unique uniqid();
  3297.         if($internalCall){
  3298.             $em $this->getDoctrine()->getManager();
  3299.             $path './doc_kyseUa8iCjUywtKtgu8J/'.$unique.'_tmp.xls';
  3300.             $writer->save($path);
  3301.             $commande->setProForma($unique.'_tmp.xls');
  3302.             $em->persist($commande);
  3303.             $em->flush();                  
  3304.         } 
  3305.         $response =  new StreamedResponse(
  3306.             function () use ($writer) {
  3307.                 $writer->save('php://output');
  3308.             }
  3309.         );
  3310.         $response->headers->set('Content-Type''application/vnd.ms-excel');
  3311.         $response->headers->set('Content-Disposition''attachment;filename="' $fileName '.xls"');
  3312.         $response->headers->set('Cache-Control''max-age=0');
  3313.         return $response;
  3314.     }
  3315.     /**
  3316.      * Si vous utilisez les annotations, activez sensio/framework-extra-bundle.
  3317.      *
  3318.      * @Route("/commande/toggle", name="commande_toggle", methods={"POST"})
  3319.      */
  3320.     public function toggle(
  3321.         Request $request,
  3322.         CsrfTokenManagerInterface $csrfManager
  3323.     ): JsonResponse {
  3324.         $em $this->getDoctrine()->getManager();
  3325.         // 1. Récupération et décodage du JSON
  3326.         $data json_decode($request->getContent(), true);
  3327.         if (!\is_array($data)) {
  3328.             return new JsonResponse([
  3329.                 'status'  => 'error',
  3330.                 'message' => 'Données JSON invalides.'
  3331.             ], 400);
  3332.         }
  3333.         // 2. Vérification du token CSRF
  3334.         $submittedToken $request->headers->get('X-CSRF-TOKEN');
  3335.         if (!$csrfManager->isTokenValid(new CsrfToken('toggle-commande'$submittedToken))) {
  3336.             return new JsonResponse([
  3337.                 'status'  => 'error',
  3338.                 'message' => 'Jeton CSRF invalide.'
  3339.             ], 400);
  3340.         }
  3341.         // 3. Validation des paramètres
  3342.         $id    $data['commandeId'] ?? null;
  3343.         $field $data['field']     ?? null;
  3344.         $value $data['value']     ?? null;
  3345.         if (null === $id || !\in_array($field, ['dap''priority'], true) || !\in_array($value, [0,1], true)) {
  3346.             return new JsonResponse([
  3347.                 'status'  => 'error',
  3348.                 'message' => 'Paramètres manquants ou invalides.'
  3349.             ], 400);
  3350.         }
  3351.         // 4. Récupération de l’entité
  3352.         /** @var Commande|null $commande */
  3353.         $commande $em->getRepository(Commande::class)->find($id);
  3354.         if (null === $commande) {
  3355.             return new JsonResponse([
  3356.                 'status'  => 'error',
  3357.                 'message' => 'Commande introuvable.'
  3358.             ], 404);
  3359.         }
  3360.         // 5. Mise à jour du champ demandé
  3361.         if ('dap' === $field) {
  3362.             $commande->setDap((bool) $value);
  3363.         } else {
  3364.             $commande->setServicePriority((bool) $value);
  3365.         }
  3366.         // 6. Persistance
  3367.         $em->persist($commande);
  3368.         $em->flush();
  3369.         // 7. Réponse JSON
  3370.         return new JsonResponse([
  3371.             'status' => 'success',
  3372.         ]);
  3373.     }
  3374.     function isCreneauActif($commandeRepository$dateCreneau)
  3375.     {
  3376.         if (intval($commandeRepository->countCommandesByCreneau($dateCreneau)) < 500000000) {
  3377.             $isCreneauActif true;
  3378.         } else {
  3379.             $isCreneauActif false;
  3380.         }
  3381.         return $isCreneauActif;
  3382.     }
  3383.     function createCreneauxLivraison($commandeRepository$nombreCreneauxACreer)
  3384.     {
  3385.         $creneauxLivraison = [];
  3386.         $jourDebut intval(date("d"));
  3387.         $moisDebut intval(date("m"));
  3388.         $anneeDebut intval(date("Y"));
  3389.         $init1 true;
  3390.         $init2 true;
  3391.         for ($i 0$i $nombreCreneauxACreer$i++) {
  3392.             switch (true) {
  3393.                     //créneau du 1er au 5
  3394.                 case $jourDebut '6':
  3395.                     $dateDebutCreneau strval($anneeDebut) . '-' sprintf('%02d'strval($moisDebut)) . '-16';
  3396.                     $dateFinCreneau strval($anneeDebut) . '-' sprintf('%02d'strval($moisDebut)) . '-' $this->utilsService->getDernierJourMois($moisDebut$anneeDebut);
  3397.                     $creneauxLivraison[$i]['creneauDebut'] = $dateDebutCreneau;
  3398.                     $creneauxLivraison[$i]['creneauFin'] = $dateFinCreneau;
  3399.                     $creneauxLivraison[$i]['creneauActif'] = $this->isCreneauActif($commandeRepository$dateDebutCreneau);
  3400.                     $creneauxLivraison[$i]['creneauToutesLettres'] = 'du <strong> 16 ' $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong><br/> au <br/><strong> ' $this->utilsService->getDernierJourMois($moisDebut$anneeDebut) . ' ' $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong>';
  3401.                     $jourDebut += 5;
  3402.                     break;
  3403.                     //créneau du 6 au 10
  3404.                 case $jourDebut '11':
  3405.                     if (intval($moisDebut) == 12) {
  3406.                         $moisSuivant '01';
  3407.                         $anneeFin $anneeDebut 1;
  3408.                     } else {
  3409.                         $moisSuivant intval($moisDebut) + 1;
  3410.                         $anneeFin $anneeDebut;
  3411.                     }
  3412.                     $dateDebutCreneau strval($anneeDebut) . '-' sprintf('%02d'strval($moisDebut)) . '-21';
  3413.                     $dateFinCreneau strval($anneeFin) . '-' sprintf('%02d'strval($moisSuivant)) . '-05';
  3414.                     $creneauxLivraison[$i]['creneauDebut'] = $dateDebutCreneau;
  3415.                     $creneauxLivraison[$i]['creneauFin'] = $dateFinCreneau;
  3416.                     $creneauxLivraison[$i]['creneauActif'] = $this->isCreneauActif($commandeRepository$dateDebutCreneau);
  3417.                     $creneauxLivraison[$i]['creneauToutesLettres'] = 'du <strong> 21 ' $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong><br/> au <br/><strong> 5 ' $this->utilsService->getMoisToutesLettres($moisSuivant) . '</strong>';
  3418.                     $jourDebut += 5;
  3419.                     break;
  3420.                     //créneau du 11 au 15
  3421.                 case $jourDebut '16':
  3422.                     if (intval($moisDebut) == 12) {
  3423.                         $moisSuivant '01';
  3424.                         $anneeFin $anneeDebut 1;
  3425.                     } else {
  3426.                         $moisSuivant intval($moisDebut) + 1;
  3427.                         $anneeFin $anneeDebut;
  3428.                     }
  3429.                     $dateDebutCreneau strval($anneeDebut) . '-' sprintf('%02d'strval($moisDebut)) . '-26';
  3430.                     $dateFinCreneau strval($anneeFin) . '-' sprintf('%02d'strval($moisSuivant)) . '-10';
  3431.                     $creneauxLivraison[$i]['creneauDebut'] = $dateDebutCreneau;
  3432.                     $creneauxLivraison[$i]['creneauFin'] = $dateFinCreneau;
  3433.                     $creneauxLivraison[$i]['creneauActif'] = $this->isCreneauActif($commandeRepository$dateDebutCreneau);
  3434.                     $creneauxLivraison[$i]['creneauToutesLettres'] = 'du <strong> 26 ' $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong><br/> au <br/><strong> 10 ' $this->utilsService->getMoisToutesLettres($moisSuivant) . '</strong>';
  3435.                     $jourDebut += 5;
  3436.                     break;
  3437.                     //créneau du 16 au 20
  3438.                 case $jourDebut '21':
  3439.                     //On vérifie le mois suivant        
  3440.                     if ($moisDebut != 12) {
  3441.                         $moisDebut += 1;
  3442.                     } else {
  3443.                         $moisDebut '01';
  3444.                         $anneeDebut += 1;
  3445.                     }
  3446.                     $init1 false;
  3447.                     $init2 false;
  3448.                     $dateDebutCreneau strval($anneeDebut) . '-' sprintf('%02d'strval($moisDebut)) . '-01';
  3449.                     $dateFinCreneau strval($anneeDebut) . '-' sprintf('%02d'strval($moisDebut)) . '-15';
  3450.                     $creneauxLivraison[$i]['creneauDebut'] = $dateDebutCreneau;
  3451.                     $creneauxLivraison[$i]['creneauFin'] = $dateFinCreneau;
  3452.                     $creneauxLivraison[$i]['creneauActif'] = $this->isCreneauActif($commandeRepository$dateDebutCreneau);
  3453.                     $creneauxLivraison[$i]['creneauToutesLettres'] = 'du <strong> 1<sup>er</sup> ' $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong><br/> au <br/><strong> 15 ' $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong>';
  3454.                     $jourDebut += 5;
  3455.                     break;
  3456.                     //créneau du 21 au 25
  3457.                 case $jourDebut '26':
  3458.                     //Calcul selon la date du mois en cours  
  3459.                     if ($init1 == true) {
  3460.                         if ($moisDebut != 12) {
  3461.                             $moisDebut += 1;
  3462.                         } else {
  3463.                             $moisDebut '01';
  3464.                             $anneeDebut += 1;
  3465.                         }
  3466.                         $init1 false;
  3467.                         $init2 false;
  3468.                     }
  3469.                     $dateDebutCreneau strval($anneeDebut) . '-' sprintf('%02d'strval($moisDebut)) . '-06';
  3470.                     $dateFinCreneau strval($anneeDebut) . '-' sprintf('%02d'strval($moisDebut)) . '-20';
  3471.                     $creneauxLivraison[$i]['creneauDebut'] = $dateDebutCreneau;
  3472.                     $creneauxLivraison[$i]['creneauFin'] = $dateFinCreneau;
  3473.                     $creneauxLivraison[$i]['creneauActif'] = $this->isCreneauActif($commandeRepository$dateDebutCreneau);
  3474.                     $creneauxLivraison[$i]['creneauToutesLettres'] = 'du <strong> 6 ' $this->getMoisToutesLettres($moisDebut) . '</strong><br/> au <br/><strong> 20 ' $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong>';
  3475.                     $jourDebut += 5;
  3476.                     break;
  3477.                     //créneau du 26 à la fin du mois
  3478.                 default:
  3479.                     //Calcul selon la date du mois en cours
  3480.                     if ($init2 == true) {
  3481.                         if ($moisDebut != 12) {
  3482.                             $moisDebut += 1;
  3483.                         } else {
  3484.                             $moisDebut '01';
  3485.                             $anneeDebut += 1;
  3486.                         }
  3487.                         $init1 false;
  3488.                         $init2 false;
  3489.                     }
  3490.                     $jourDebut 1;
  3491.                     $dateDebutCreneau strval($anneeDebut) . '-' sprintf('%02d'strval($moisDebut)) . '-11';
  3492.                     $dateFinCreneau strval($anneeDebut) . '-' sprintf('%02d'strval($moisDebut)) . '-25';
  3493.                     $creneauxLivraison[$i]['creneauDebut'] = $dateDebutCreneau;
  3494.                     $creneauxLivraison[$i]['creneauFin'] = $dateFinCreneau;
  3495.                     $creneauxLivraison[$i]['creneauActif'] = $this->isCreneauActif($commandeRepository$dateDebutCreneau);
  3496.                     $creneauxLivraison[$i]['creneauToutesLettres'] = 'du <strong> 11 ' $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong><br/> au <br/><strong> 25 ' $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong>';
  3497.                     break;
  3498.             }
  3499.         }
  3500.         return $creneauxLivraison;
  3501.     }
  3502.     function translateCreneauLivraison($dateDebut$dateFin)
  3503.     {
  3504.         $dateDebut $dateDebut->format('Y-m-d');
  3505.         $dateDebutPieces explode("-"$dateDebut);
  3506.         $dateFin $dateFin->format('Y-m-d');
  3507.         $dateFinPieces explode("-"$dateFin);
  3508.         $dateString "du <strong>" $dateDebutPieces[2] . " " $this->utilsService->getMoisToutesLettres($dateDebutPieces[1]) . "</strong> au <strong>" $dateFinPieces[2] . " " $this->utilsService->getMoisToutesLettres($dateFinPieces[1]) . "</strong>";
  3509.         return $dateString;
  3510.     }
  3511.     function besoinConsentementDates($dateDebut$dateFin)
  3512.     {
  3513.         $dateDebut $dateDebut->format('md');
  3514.         $dateFin $dateFin->format('md');
  3515.         $dateDebutIndispo "0615";
  3516.         $dateFinIndispo "1015";
  3517.         if ($dateDebut >= $dateDebutIndispo && $dateDebut <= $dateFinIndispo) {
  3518.             $besoinConsentementDates true;
  3519.         } else if ($dateFin >= $dateDebutIndispo && $dateFin <= $dateFinIndispo) {
  3520.             $besoinConsentementDates true;
  3521.         } else {
  3522.             $besoinConsentementDates false;
  3523.         }
  3524.         return $besoinConsentementDates;
  3525.     }
  3526.     function createExcelCommandes($commandes){
  3527.         $telAlphabet = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z');            
  3528.         
  3529.         $spreadsheet = new Spreadsheet();
  3530.         $sheet $spreadsheet->getActiveSheet();
  3531.         foreach(range('A','Z') as $columnID) {
  3532.             $sheet->getColumnDimension($columnID)->setAutoSize(true);
  3533.             $sheet->getColumnDimension('A'.$columnID)->setAutoSize(true);
  3534.         }
  3535.         $writer = new Xls($spreadsheet);
  3536.         $fileName "export";
  3537.         $fileName .= date("Y-m-d_H:i:s"); 
  3538.         $sheet->setCellValue('A1''Numéro commande');
  3539.         $sheet->setCellValue('B1''Date de création');
  3540.         $sheet->setCellValue('C1''Statut de la commande');
  3541.         $sheet->setCellValue('D1''Raison sociale');
  3542.         $sheet->setCellValue('E1''Identifiant client MBE');
  3543.         $sheet->setCellValue('F1''Nom du client');
  3544.         $sheet->setCellValue('G1''Prénom du client');
  3545.         $sheet->setCellValue('H1''Email du client');
  3546.         $sheet->setCellValue('I1''Téléphone du client');
  3547.         $sheet->setCellValue('J1''Adresse du client');
  3548.         $sheet->setCellValue('K1''Code postal du client');
  3549.         $sheet->setCellValue('L1''Ville du client');
  3550.         $sheet->setCellValue('M1''Eori');
  3551.         $sheet->setCellValue('N1''Nombre de colis');
  3552.         $sheet->setCellValue('O1''Nombre de bouteille rouge');
  3553.         $sheet->setCellValue('P1''Nombre de bouteille blanc');
  3554.         $sheet->setCellValue('Q1''Nombre de bouteille pétillant');
  3555.         $sheet->setCellValue('R1''Numéro DAE');
  3556.         $sheet->setCellValue('S1''Assurance livraison');
  3557.         $sheet->setCellValue('T1''Emballage livraison');
  3558.         $sheet->setCellValue('U1''Facture client final');
  3559.         $sheet->setCellValue('V1''Numéro facture client final');
  3560.         $sheet->setCellValue('W1''Montant total facture');
  3561.         $sheet->setCellValue('X1''Date de collecte');
  3562.         $sheet->setCellValue('Y1''Créneau début');
  3563.         $sheet->setCellValue('Z1''Créneau fin');
  3564.         $sheet->setCellValue('AA1''Code postal livraison');
  3565.         $sheet->setCellValue('AB1''Ville livraison');
  3566.         $sheet->setCellValue('AC1''Adresse livraison');
  3567.         $sheet->setCellValue('AD1''CPL Adresse livraison');
  3568.         $sheet->setCellValue('AE1''Etat US');
  3569.         $sheet->setCellValue('AF1''Observation');        
  3570.         $sheet->setCellValue('AG1''Numéro de suivi');        
  3571.         $sheet->setCellValue('AH1''Nom du destinataire');    
  3572.         $sheet->setCellValue('AI1''total de bouteilles');    
  3573.         $sheet->setCellValue('AJ1''Type d\'emballage');
  3574.         $sheet->setCellValue('AK1''tracking numbers');    
  3575.         $sheet->setCellValue('AL1''Magnum rouge');    
  3576.         $sheet->setCellValue('AM1''Magnum blanc');    
  3577.         $sheet->setCellValue('AN1''Magnum pétillant');    
  3578.         $sheet->setCellValue('AO1''DAP');    
  3579.         $sheet->setCellValue('AP1''Service priority');    
  3580.         $sheet->setCellValue('AQ1''Destinataire Email');    
  3581.         $sheet->setCellValue('AR1''Destinataire Telephone');    
  3582.         $index 2;
  3583.         foreach ($commandes as $keyCommande => $commandeValue) {
  3584.             $totalBottles $commandeValue->getNombreBouteillePetillant() + $commandeValue->getNombreBouteilleBlanc() + $commandeValue->getNombreBouteilleRouge() ;
  3585.             $previDebut = clone $commandeValue->getDateCollecte();
  3586.             $previFin = clone $commandeValue->getDateCollecte();
  3587.             
  3588.             $finalClientPhone $commandeValue->getClientFinal()->getTelephone();
  3589.             $finalClientEmail $commandeValue->getClientFinal()->getEmail();
  3590.             $sheet->setCellValue('A'.$index$commandeValue->getId());
  3591.             $sheet->setCellValue('B'.$index$commandeValue->getDateCommandeSoumission()->format('d/m/Y'));
  3592.             $sheet->setCellValue('C'.$index$this->convertStateToHuman($commandeValue->getState(), $commandeValue->isEmballageLivraison()));
  3593.             $sheet->setCellValue('D'.$index$commandeValue->getClient()->getRaisonSociale());
  3594.             $sheet->setCellValue('E'.$index$commandeValue->getClient()->getIdClientMBEHub());
  3595.             $sheet->setCellValue('F'.$index$commandeValue->getClient()->getNomContact());
  3596.             $sheet->setCellValue('G'.$index$commandeValue->getClient()->getPrenomContact());
  3597.             $sheet->setCellValue('H'.$index$commandeValue->getClient()->getEmailContact());
  3598.             $sheet->setCellValue('I'.$index$commandeValue->getClient()->getTelephoneContact());
  3599.             $sheet->setCellValue('J'.$index$commandeValue->getClient()->getAdresse());
  3600.             $sheet->setCellValue('K'.$index$commandeValue->getClient()->getCodePostal());
  3601.             $sheet->setCellValue('L'.$index$commandeValue->getClient()->getVille());
  3602.             $sheet->setCellValue('M'.$index$commandeValue->getClient()->getEori());
  3603.             $sheet->setCellValue('N'.$index$commandeValue->getNombreColisTotal());
  3604.             $sheet->setCellValue('O'.$index$commandeValue->getNombreBouteilleRouge());
  3605.             $sheet->setCellValue('P'.$index$commandeValue->getNombreBouteilleBlanc());
  3606.             $sheet->setCellValue('Q'.$index$commandeValue->getNombreBouteillePetillant());
  3607.             $sheet->setCellValue('R'.$index$commandeValue->getNumeroDae());
  3608.             if($commandeValue->isAssuranceLivraison()){
  3609.                 $sheet->setCellValue('S'.$index"OUI");    
  3610.             }else{
  3611.                 $sheet->setCellValue('S'.$index"NON");    
  3612.             }
  3613.             if($commandeValue->isEmballageLivraison()){
  3614.                 $sheet->setCellValue('T'.$index"OUI");    
  3615.             }else{
  3616.                 $sheet->setCellValue('T'.$index"NON");    
  3617.             }
  3618.             // $sheet->setCellValue('R'.$index, $commandeValue->isAssuranceLivraison());
  3619.             // $sheet->setCellValue('S'.$index, $commandeValue->isEmballageLivraison());
  3620.             $sheet->setCellValue('U'.$index$commandeValue->getFichierFacture());
  3621.             $sheet->setCellValue('V'.$index' '.$commandeValue->getNumeroFacture());
  3622.             $sheet->setCellValue('W'.$index$commandeValue->getMontantTotalFacture());
  3623.             $sheet->setCellValue('X'.$index$commandeValue->getDateCollecte()->format('d/m/Y'));
  3624.             $sheet->setCellValue('Y'.$index$previDebut->modify("+7 days")->format('d/m/Y'));
  3625.             $sheet->setCellValue('Z'.$index$previFin->modify("+12 days")->format('d/m/Y'));
  3626.             /* $sheet->setCellValue('V'.$index, $commandeValue->getDateDebutFenetre()->format('d/m/Y'));
  3627.             $sheet->setCellValue('W'.$index, $commandeValue->getDateFinFenetre()->format('d/m/Y')); */
  3628.             $sheet->setCellValue('AA'.$index$commandeValue->getCodePostalLivraison());
  3629.             $sheet->setCellValue('AB'.$index$commandeValue->getVilleLivraison());
  3630.             $sheet->setCellValue('AC'.$index$commandeValue->getAdresseLivraison());
  3631.             $sheet->setCellValue('AD'.$index$commandeValue->getComplementAdresseLivraison());
  3632.             $sheet->setCellValue('AE'.$index$commandeValue->getEtatUs());
  3633.             $sheet->setCellValue('AF'.$index$commandeValue->getObservation());
  3634.             $sheet->setCellValue('AG'.$index' '.$commandeValue->getTrackingNumber());            
  3635.             $sheet->setCellValue('AH'.$index$commandeValue->getClientFinal()->getFullName());
  3636.             $calcMagnum 0;
  3637.             $calcMagnum intval($commandeValue->getNombreMagnumRouge()) + intval($commandeValue->getNombreMagnumBlanc()) + intval($commandeValue->getNombreMagnumPetillant());
  3638.             $sheet->setCellValue('AI'.$index$commandeValue->getNombreBouteillePetillant() + $commandeValue->getNombreBouteilleBlanc() + $commandeValue->getNombreBouteilleRouge() + $calcMagnum);
  3639.             $sheet->setCellValue('AJ'.$index$commandeValue->getTypeEmballage());
  3640.             $sheet->setCellValue('AK'.$index' '.$commandeValue->getIndividualTrackingNumbers());                  
  3641.             $sheet->setCellValue('AL'.$index' '.$commandeValue->getNombreMagnumRouge());                  
  3642.             $sheet->setCellValue('AM'.$index' '.$commandeValue->getNombreMagnumBlanc());                  
  3643.             $sheet->setCellValue('AN'.$index' '.$commandeValue->getNombreMagnumPetillant());
  3644.             
  3645.             if($commandeValue->isDap()){
  3646.                 $sheet->setCellValue('AO'.$index"OUI");    
  3647.             }else{
  3648.                 $sheet->setCellValue('AO'.$index"NON");    
  3649.             }
  3650.             if($commandeValue->isServicePriority()){
  3651.                 $sheet->setCellValue('AP'.$index"OUI");    
  3652.             }else{
  3653.                 $sheet->setCellValue('AP'.$index"NON");    
  3654.             }
  3655.             $sheet->setCellValue('AQ'.$index' '.$finalClientPhone);
  3656.             $sheet->setCellValue('AR'.$index' '.$finalClientEmail);
  3657.             
  3658.             $indexAlphabet=19;
  3659.             $indexColis 1;
  3660.             foreach ($commandeValue->getColis() as $keyColis => $valueColis) {   
  3661.                 
  3662.                 $sheet->setCellValue('A'.$telAlphabet[$indexAlphabet].$index"Colis n°".$indexColis." Nombre bouteilles : ".$valueColis->getNombreBouteille());
  3663.                 $indexAlphabet++;
  3664.                 $indexColis++;
  3665.             }                
  3666.                     
  3667.             $index++;
  3668.         }
  3669.         $response =  new StreamedResponse(function () use ($writer) {
  3670.                 $writer->save('php://output');
  3671.             }
  3672.         );
  3673.         $response->headers->set('Content-Type''application/vnd.ms-excel');
  3674.         $response->headers->set('Content-Disposition''attachment;filename="' $fileName '.xls"');
  3675.         $response->headers->set('Cache-Control','max-age=0');
  3676.         return $response ;
  3677.     }
  3678.     function convertStateToHuman($state$cavistePacking){
  3679.         switch ($state) {
  3680.             case 'preparation':
  3681.                 return 'préparation';
  3682.                 break;
  3683.             case 'emballage_caviste':
  3684.                 return 'Emballage caviste';
  3685.                 break;    
  3686.             case 'attente_client':
  3687.                 return 'Attente validation client';
  3688.                 break;      
  3689.             case 'attente_collecte_mbe':
  3690.                 return 'Collecte MBE';
  3691.                 break;
  3692.             case 'attente_pec_transporteur':
  3693.                 if($cavistePacking){
  3694.                     return 'Attente collecte Fedex(Caviste)';    
  3695.                 } else {
  3696.                     if($this->roleAdmin){
  3697.                         return 'Attente collecte Fedex(MBE)';
  3698.                     } else {
  3699.                         return 'En cours de traitement (MBE)';
  3700.                     }
  3701.                 }
  3702.                 break;
  3703.             case 'emballage_mbe':
  3704.                 if($this->roleAdmin){
  3705.                     return 'Emballage MBE';
  3706.                 } else {
  3707.                     return 'En cours de traitement (MBE)';
  3708.                 }
  3709.                 
  3710.                 break;
  3711.             case 'archive':
  3712.                 return 'Archivée';
  3713.                 break;
  3714.             default:
  3715.                 'N/A';
  3716.                 break;
  3717.         }
  3718.     }
  3719.     
  3720.     function is_valid_filename($filename) {
  3721.         // Liste des caractères interdits dans les noms de fichiers sur la plupart des systèmes de fichiers
  3722.         $forbidden_chars = array("/""\\"":""*""?""\"""<"">""|""#""&""=""%""+"";"" ");
  3723.         // Remplacer les caractères interdits par "_"
  3724.         $filename str_replace($forbidden_chars'_'$filename);
  3725.         // Vérifie si le nom de fichier est vide après remplacement
  3726.         if (trim($filename) == '') {
  3727.             return false// Le nom de fichier est vide
  3728.         }
  3729.         // Le nom de fichier est valide
  3730.         return $filename;
  3731.     }
  3732.     function checkMontant($montant) {
  3733.         $montant str_replace(',''.'$montant);
  3734.         $montant preg_replace('/[^0-9,.]/'''$montant);    
  3735.         return $montant;
  3736.     }
  3737.     
  3738. }