src/Controller/CommandeController.php line 275

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