src/Controller/DefaultController.php line 63

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use DateTime;
  4. use PDO;
  5. use PDOException;
  6. use PhpImap\Mailbox;
  7. use App\Service\MBEClient;
  8. use App\Service\UtilsService;
  9. use App\Form\ResetPasswordType;
  10. use App\Service\BandeauService;
  11. use App\Service\EmailGenerator;
  12. use TeamTNT\TNTSearch\TNTSearch;
  13. use App\Repository\UserRepository;
  14. use Symfony\Component\Mime\Address;
  15. use App\Repository\ClientRepository;
  16. use App\Form\ClientFinalValidateType;
  17. use App\Repository\BandeauRepository;
  18. use App\Controller\CommandeController;
  19. use App\Form\ResetPasswordRequestType;
  20. use App\Repository\CommandeRepository;
  21. use Doctrine\ORM\EntityManagerInterface;
  22. use App\Repository\ClientFinalRepository;
  23. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  24. use Symfony\Component\HttpFoundation\Cookie;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\Mailer\MailerInterface;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\Routing\Annotation\Route;
  29. use Symfony\Component\HttpFoundation\JsonResponse;
  30. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  31. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  32. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  33. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  34. class DefaultController extends AbstractController
  35. {
  36.     private $utilsService;
  37.     private $emailGeneratorService;
  38.     private $roleAdmin;
  39.     private $baseDomain 'https://wine.mbebordeaux.fr';
  40.     private $fuzzy_storage "/home/mbe/public_html/www";
  41.     private $mailer;
  42.     private $bandeauService;
  43.     //private $fuzzy_storage = "/Users/mbk15/Documents/aSchone/mbeplateforme";
  44.     //private $fuzzy_storage = "C:\wamp64\www\mbeplateforme";
  45.     //private $fuzzy_storage = "C:\Users\bleu-\OneDrive\Bureau\aschone\mbeplateforme";
  46.     public function __construct(UtilsService $utilsServiceBandeauService $bandeauServiceEmailGenerator $emailGeneratorServiceMailerInterface $mailer)
  47.     {
  48.         $this->utilsService $utilsService;
  49.         $this->emailGeneratorService $emailGeneratorService;
  50.         $this->roleAdmin $this->utilsService->isAdmin();
  51.         $this->mailer $mailer;
  52.         $this->bandeauService $bandeauService;
  53.     }
  54.     /**
  55.      * @Route("/", name="default")
  56.      */
  57.     public function index(BandeauRepository $BandeauRepositoryRequest $request): Response
  58.     {
  59.         return $this->render('default/index.html.twig'
  60.             array('controller_name' => 'DefaultController',
  61.             'bandeau' => $this->bandeauService->displayPopup()
  62.         ));
  63.     }
  64.     private function sendErrorEmail($errorDetails$excelFilePath)
  65.     {
  66.         $email = (new TemplatedEmail())
  67.             ->from('no-reply@mbe.vent-en-poupe.fr')
  68.             ->to(new Address('linnea.cederblad@mbebordeaux.fr'))
  69.             ->bcc(new Address('bpouverel@mbefrance.fr'))
  70.             ->bcc(new Address('support@bleu-digital.fr'))
  71.             ->subject('MBE - Problème import script')
  72.             ->htmlTemplate('emails/error_template.html.twig'// Assurez-vous d'avoir ce template Twig
  73.             ->context([
  74.                 'errorDetails' => $errorDetails,
  75.             ]);
  76.         foreach ($excelFilePath as $key => $file) {
  77.             $email->attachFromPath($file);
  78.         }
  79.         try {
  80.             $this->mailer->send($email);
  81.             echo "E-mail envoyé avec succès.";
  82.         } catch (TransportExceptionInterface $e) {
  83.             echo "L'e-mail n'a pas pu être envoyé. Erreur: {$e->getMessage()}";
  84.         }
  85.     }
  86.     private function sendErrorEmailIdealWine($errorDetails$excelFilePath)
  87.     {
  88.         $email = (new TemplatedEmail())
  89.             ->from('no-reply@mbe.vent-en-poupe.fr')
  90.             ->to(new Address('linnea.cederblad@mbebordeaux.fr'))
  91.             ->bcc(new Address('bpouverel@mbefrance.fr'))
  92.             ->bcc(new Address('support@bleu-digital.fr'))
  93.             ->subject('MBE - Problème import script')
  94.             ->htmlTemplate('emails/error_template.html.twig'// Assurez-vous d'avoir ce template Twig
  95.             ->context([
  96.                 'errorDetails' => $errorDetails,
  97.             ]);
  98.         foreach ($excelFilePath as $key => $file) {
  99.             $email->attachFromPath($file);
  100.         }
  101.         try {
  102.             $this->mailer->send($email);
  103.             echo "E-mail envoyé avec succès.";
  104.         } catch (TransportExceptionInterface $e) {
  105.             echo "L'e-mail n'a pas pu être envoyé. Erreur: {$e->getMessage()}";
  106.         }
  107.     }
  108.     /**
  109.      * @Route("/create_commande_par_email_Wf74oVv7WY4QLu1YqSad ", name="create_commande_par_email", methods={"GET", "POST"})
  110.      */
  111.     public function createCommandeParEmail(CommandeController $commandeControllerClientRepository $clientRepositoryCommandeRepository $commandeRepository)
  112.     {
  113.         // Paramètres de connexion IMAP
  114.         $server '{ssl0.ovh.net:993/imap/ssl}INBOX';
  115.         $username 'usa@mbebordeaux.fr';
  116.         $password 'R2rFMxYgN5dw5cMMbpta';
  117.         //https://mail.ovh.net/roundcube/
  118.         // Créer une instance de la boîte aux lettres
  119.         $mailbox = new Mailbox($server$username$password);
  120.         // Récupérer tous les e-mails
  121.         $emails $mailbox->searchMailbox('UNSEEN');
  122.         // $emails = $mailbox->searchMailbox('ALL');                    
  123.         // Parcourir les e-mails
  124.         foreach ($emails as $emailUid) {
  125.             $email $mailbox->getMail($emailUid);
  126.             // Vérifier si le from est Charlotte ou Florian ou Benoit ou Lilly (Après, les adresses du client )
  127.             if ($email->fromAddress === 'cbrisson@bleu-digital.fr' || $email->fromAddress === 'fdieu@bleu-digital.fr' || $email->fromAddress === 'linnea.cederblad@mbebordeaux.fr' || $email->fromAddress === 'bpouverel@mbefrance.fr' || $email->fromAddress === 'aschone@bleu-digital.fr' || $email->fromAddress == 'mbe011@mbefrance.fr') {
  128.                 // Vérifier s'il existe des pièces jointes
  129.                 if ($email->hasAttachments()) {
  130.                     // Parcourir les pièces jointes
  131.                     foreach ($email->getAttachments() as $attachment) {
  132.                         // Vérifier si la pièce jointe est un fichier Excel
  133.                         $mimeType $attachment->mime;
  134.                         $fileName $attachment->name;
  135.                         if ($mimeType === 'application/vnd.ms-excel; charset=binary' || $mimeType "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=binary" || $mimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || $mimeType === 'application/vnd.ms-excel') {
  136.                             // Déterminez l'encodage manuellement si mb_detect_encoding() échoue
  137.                             $current_encoding 'ISO-8859-1'// Par exemple, supposons que l'encodage est ISO-8859-1                            
  138.                             // Conversion de l'encodage si nécessaire (ex. vers UTF-8)
  139.                             if ($current_encoding !== 'UTF-8') {
  140.                                 $filename mb_convert_encoding($fileName'UTF-8'$current_encoding);
  141.                             }
  142.                             // Suppression des caractères non valides
  143.                             $filenameNew preg_replace('/[^\p{L}\p{N}\s\-_\.]/u'''$filename);
  144.                             // Vérifier si l'objet de l'email contient le mot "IDEALWINE"
  145.                             if (strpos(strtolower($email->subject), 'idealwine') !== false) {
  146.                                 file_put_contents(__DIR__ "/../../public/VK74QTZTBQax9SkdDuax/" $filenameNew$attachment->getContents());
  147.                             } else {
  148.                                 file_put_contents(__DIR__ "/../../public/xdeUEDJuejUDEiduhEDIOehdEUDHe/" $filenameNew$attachment->getContents());
  149.                             }
  150.                             // Chemin vers le fichier Excel
  151.                             // $excelFilePath = __DIR__."/../../public/xdeUEDJuejUDEiduhEDIOehdEUDHe/".$filenameNew;
  152.                         }
  153.                     }
  154.                 }
  155.                 $mailbox->markMailAsRead($emailUid);
  156.             }
  157.         }
  158.         $createCommandeResponse $commandeController->create_via_import($clientRepository$commandeRepository);
  159.         $createCommandeResponseIdealWine $commandeController->create_via_import_idealwine($clientRepository$commandeRepository);
  160.         $errorFound $createCommandeResponse['errorFound'];
  161.         // Si le script merde alors on send un email pour expliquer l'erreur
  162.         if ($errorFound) {
  163.             $errorDetails $createCommandeResponse['errorDetails'];
  164.             $excelFilePath $createCommandeResponse['excelFilePath'];
  165.             $this->sendErrorEmail($errorDetails$excelFilePath);
  166.         } else {
  167.             echo "Aucune erreur trouvée dans le fichier Excel Martin.";
  168.         }
  169.         $errorFound $createCommandeResponseIdealWine['errorFound'];
  170.         // Si le script merde alors on send un email pour expliquer l'erreur pour IDEALWINE
  171.         if ($errorFound) {
  172.             $errorDetails $createCommandeResponseIdealWine['errorDetails'];
  173.             $excelFilePath $createCommandeResponseIdealWine['excelFilePath'];
  174.             $this->sendErrorEmailIdealWine($errorDetails$excelFilePath);
  175.         } else {
  176.             echo "Aucune erreur trouvée dans le fichier Excel IDEALWINE.";
  177.         }
  178.         return new Response("OK");
  179.     }
  180.     /**
  181.      * @Route("/admin", name="admin_default")
  182.      */
  183.     public function indexAdmin(): Response
  184.     {
  185.         if ($this->roleAdmin) {
  186.             return $this->render('default/indexAdmin.html.twig', [
  187.                 'controller_name' => 'DefaultController',
  188.             ]);
  189.         }
  190.         return $this->redirectToRoute('app_commande_new', [], Response::HTTP_SEE_OTHER);
  191.     }
  192.     /**
  193.      * @Route("/mdpoublier ", name="app_client_forgot_pwd", methods={"GET", "POST"})
  194.      */
  195.     public function askResetPassword(Request $requestUserRepository $userRepository): Response
  196.     {
  197.         $form $this->createForm(ResetPasswordRequestType::class);
  198.         $form->handleRequest($request);
  199.         if ($form->isSubmitted()) {
  200.             $email $_POST['reset_password_request']['email'];
  201.             $user $userRepository->findByEmail($email);
  202.             if (count($user) > 0) {
  203.                 $payload = [
  204.                     'id' => $user[0]->getId(),
  205.                     'exp' => time() + 900
  206.                 ];
  207.                 $token $this->utilsService->generateJWT($payload);
  208.                 $url $this->baseDomain $this->generateUrl('reset_password', array('token' => $token));
  209.                 // TODO send the link by email
  210.                 $this->emailGeneratorService->sendResetPassword($user[0], $url);
  211.             }
  212.             $this->addFlash(
  213.                 'info',
  214.                 'Si votre email est lié à un compte nous vous avons envoyé un lien par mail'
  215.             );
  216.         }
  217.         return $this->render('client/forgot_password.html.twig', [
  218.             'form' => $form->createView(),
  219.         ]);
  220.     }
  221.     /**
  222.      * @Route("/changermdp", name="reset_password", methods={"GET", "POST"})
  223.      */
  224.     public function resetPassword(Request $requestUserRepository $userRepositoryUserPasswordHasherInterface $userPasswordHasherEntityManagerInterface $entityManager)
  225.     {
  226.         $token $request->query->get('token');
  227.         if ($token == null) {
  228.             return $this->redirectToRoute('default', [], Response::HTTP_SEE_OTHER);
  229.         }
  230.         $payload $this->utilsService->validateJWT($token);
  231.         //TODO decode the token present in the get request
  232.         $user $userRepository->find($payload['id']);
  233.         $form $this->createForm(ResetPasswordType::class);
  234.         $form->handleRequest($request);
  235.         if ($form->isSubmitted() && $form->isValid()) {
  236.             $user->setPassword(
  237.                 $userPasswordHasher->hashPassword(
  238.                     $user,
  239.                     $form->get('plainPassword')->getData()
  240.                 )
  241.             );
  242.             $entityManager->persist($user);
  243.             $entityManager->flush();
  244.             return $this->redirectToRoute('login');
  245.         }
  246.         return $this->render('client/reset_password.html.twig', [
  247.             'form' => $form->createView(),
  248.         ]);
  249.     }
  250.     /**
  251.      * @Route("/validate", name="app_client_final_validate", methods={"GET", "POST"})
  252.      */
  253.     public function validate(CommandeRepository $commandeRepository,  Request $request)
  254.     {
  255.         $token $request->query->get('token');
  256.         if ($token == null) {
  257.             return $this->redirectToRoute('default', [], Response::HTTP_SEE_OTHER);
  258.         }
  259.         $payload $this->utilsService->validateJWT($token);
  260.         $commande $commandeRepository->find($payload['id']);
  261.         if ($commande->isIsValideeParClient() == true) {
  262.             //Le client a déjà validé ses infos et revient sur le lien, on redirige direct vers la page "Vos informations ont bien été validées"
  263.             return $this->render('client_final/informations_validees.html.twig');
  264.         }
  265.         /* if($commande->getState() == 'valide' 
  266.         || $commande->getState() == 'emballage' 
  267.         || $commande->getState() == 'archive'){
  268.             return $this->redirectToRoute('default', [], Response::HTTP_SEE_OTHER); 
  269.         } */
  270.         $em $this->getDoctrine()->getManager();
  271.         $form $this->createForm(ClientFinalValidateType::class, $commande);
  272.         $form->handleRequest($request);
  273.         $dateCreneau1Clone = clone $commande->getDateCollecte();
  274.         $dateCreneau2Clone = clone $commande->getDateCollecte();
  275.         if ($commande->isEmballageLivraison()) {
  276.             $dateCreneau1Brut $dateCreneau1Clone->modify("+7 days");
  277.             $dateCreneau2Brut $dateCreneau2Clone->modify("+12 days");
  278.         } else {
  279.             $dateCreneau1Brut $dateCreneau1Clone->modify("+22 days");
  280.             $dateCreneau2Brut $dateCreneau2Clone->modify("+27 days");
  281.         }
  282.         $dateCreneau1 $dateCreneau1Brut->format('d/m/Y');
  283.         $dateCreneau2 $dateCreneau2Brut->format('d/m/Y');
  284.         if ($form->isSubmitted() && $form->isValid()) {
  285.             $postCommande $_POST['client_final_validate'];
  286.             $etatUs $_POST['input_etat_us'];
  287.             //Client final
  288.             $clientFinal $commande->getClientFinal();
  289.             $clientFinal->setTelephone($postCommande['telephone']);
  290.             if (strlen($postCommande['fullName']) > 70) {
  291.                 $this->addFlash("error"'The fullname is too long');
  292.                 return $this->render('client_final/validate.html.twig', [
  293.                     'commande' => $commande,
  294.                     'form' => $form->createView(),
  295.                     'dateCreneau1' => $dateCreneau1,
  296.                     'dateCreneau2' => $dateCreneau2,
  297.                 ]);
  298.             }
  299.             if (strlen($postCommande['telephone']) != 10) {
  300.                 $this->addFlash("error"'The phone number must be composed of 10 digits.');
  301.                 return $this->render('client_final/validate.html.twig', [
  302.                     'commande' => $commande,
  303.                     'form' => $form->createView(),
  304.                     'dateCreneau1' => $dateCreneau1,
  305.                     'dateCreneau2' => $dateCreneau2,
  306.                 ]);
  307.             }
  308.             $clientFinal->setFullName($postCommande['fullName']);
  309.             // $clientFinal->setPrenom($postCommande['clientFinal']['prenom']);
  310.             // $clientFinal->setNom($postCommande['clientFinal']['nom']);
  311.             $em->persist($clientFinal);
  312.             $em->flush();
  313.             //Commande
  314.             $commande->setCodePostalLivraison(str_replace(' '''$postCommande['codePostalLivraison']));
  315.             $commande->setVilleLivraison(trim($postCommande['villeLivraison']));
  316.             $commande->setAdresseLivraison($postCommande['adresseLivraison']);
  317.             $commande->setComplementAdresseLivraison($postCommande['complementAdresseLivraison']);
  318.             $commande->setEtatUs($etatUs);
  319.             $commande->setProvince($this->utilsService->getProvinceByEtatUs($etatUs));
  320.             //Si le statut de la commande a déjà avancé et que la suite était conditionnée à la validation des infos du client, on passe au state suivant
  321.             if ($commande->getState() == "attente_client") {
  322.                 if ($commande->isEmballageLivraison() == true) {
  323.                     $commande->setState('attente_pec_transporteur');
  324.                 } else {
  325.                     $commande->setState('attente_collecte_mbe');
  326.                 }
  327.             }
  328.             /* $commande->setState($commande->isEmballageLivraison() ? 'valide' : 'emballage'); */
  329.             $commande->setIsValideeParClient(true);
  330.             $em->persist($commande);
  331.             $em->flush();
  332.             $this->addFlash(
  333.                 'info',
  334.                 'Order validated'
  335.             );
  336.             //On redirige direct vers la page "Vos informations ont bien été validées"
  337.             /* return $this->redirectToRoute('default', [], Response::HTTP_SEE_OTHER);  */
  338.             return $this->render('client_final/informations_validees.html.twig');
  339.         }
  340.         return $this->render('client_final/validate.html.twig', [
  341.             'commande' => $commande,
  342.             'form' => $form->createView(),
  343.             'dateCreneau1' => $dateCreneau1,
  344.             'dateCreneau2' => $dateCreneau2,
  345.         ]);
  346.     }
  347.     /**
  348.      * @Route("/updateFirstConnexion", name="update_first_connexion")
  349.      */
  350.     public function updateFirstConnexion(): Response
  351.     {
  352.         $user $this->getUser();
  353.         $em $this->getDoctrine()->getManager();
  354.         $user->setIsFirstConnexion(false);
  355.         $em->persist($user);
  356.         $em->flush();
  357.         return new Response("OK");
  358.     }
  359.     /**
  360.      * @Route("/cron_BJbOT7r0aa/adminEmballages", name="admin_emballages")
  361.      */
  362.     public function adminEmballages(CommandeRepository $commandeRepository): Response
  363.     {
  364.         //On recup la valeur de today
  365.         $jourDebut intval(date("d"));
  366.         $moisDebut intval(date("m"));
  367.         $anneeDebut intval(date("Y"));
  368.         if (intval($moisDebut) == 12) {
  369.             $moisSuivant '01';
  370.             $anneeFin $anneeDebut 1;
  371.         } else {
  372.             $moisSuivant intval($moisDebut) + 1;
  373.             $anneeFin $anneeDebut;
  374.         }
  375.         switch (true) {
  376.             case $jourDebut == 5:
  377.                 $dateFinCreneau strval($anneeDebut) . '-' sprintf('%02d'strval($moisDebut)) . '-' $this->utilsService->getDernierJourMois($moisDebut$anneeDebut);
  378.                 break;
  379.             case $jourDebut == 10:
  380.                 $dateFinCreneau strval($anneeFin) . '-' sprintf('%02d'strval($moisSuivant)) . '-05';
  381.                 break;
  382.             case $jourDebut == 15:
  383.                 $dateFinCreneau strval($anneeFin) . '-' sprintf('%02d'strval($moisSuivant)) . '-10';
  384.                 break;
  385.             case $jourDebut == 20:
  386.                 $dateFinCreneau strval($anneeFin) . '-' sprintf('%02d'strval($moisSuivant)) . '-15';
  387.                 break;
  388.             case $jourDebut == 25:
  389.                 $dateFinCreneau strval($anneeFin) . '-' sprintf('%02d'strval($moisSuivant)) . '-20';
  390.                 break;
  391.             case $jourDebut == 30:
  392.                 $dateFinCreneau strval($anneeFin) . '-' sprintf('%02d'strval($moisSuivant)) . '-25';
  393.                 break;
  394.             default:
  395.                 $dateFinCreneau '';
  396.                 break;
  397.         }
  398.         //If today ne correspond pas aux jours, on ne lance pas le script 
  399.         if ($dateFinCreneau != '') {
  400.             $commandes $commandeRepository->findCommandesAEmballerParCreneau($dateFinCreneau);
  401.             if ($commandes) {
  402.                 $res $this->emailGeneratorService->sendEmailPrepareEmballage($commandes);
  403.                 if ($res) {
  404.                     return new Response("OK");
  405.                 } else {
  406.                     return new Response("ErreurMail");
  407.                 }
  408.                 exit();
  409.             }
  410.             return new Response("Pas d'\'envoi ce jour");
  411.             die();
  412.         }
  413.         return new Response("Pas d'\'envoi ce jour");
  414.         die();
  415.     }
  416.     /**
  417.      * @Route("/cron_BJbOT7r0aa/preparationColisCavistes", name="preparation_colis_cavistes")
  418.      */
  419.     public function preparationColisCavistes(ClientRepository $clientRepositoryCommandeRepository $commandeRepository): Response
  420.     {
  421.         //On recup la valeur de today
  422.         $jourDebut intval(date("d"));
  423.         $moisDebut intval(date("m"));
  424.         $anneeDebut intval(date("Y"));
  425.         if (intval($moisDebut) == 12) {
  426.             $moisSuivant '01';
  427.             $anneeFin $anneeDebut 1;
  428.         } else {
  429.             $moisSuivant intval($moisDebut) + 1;
  430.             $anneeFin $anneeDebut;
  431.         }
  432.         switch (true) {
  433.             case $jourDebut == 5:
  434.                 $dateFinCreneau strval($anneeFin) . '-' sprintf('%02d'strval($moisDebut)) . '-25';
  435.                 break;
  436.             case $jourDebut == 10:
  437.                 $dateFinCreneau strval($anneeDebut) . '-' sprintf('%02d'strval($moisDebut)) . '-' $this->utilsService->getDernierJourMois($moisDebut$anneeDebut);
  438.                 break;
  439.             case $jourDebut == 15:
  440.                 $dateFinCreneau strval($anneeFin) . '-' sprintf('%02d'strval($moisSuivant)) . '-05';
  441.                 break;
  442.             case $jourDebut == 20:
  443.                 $dateFinCreneau strval($anneeFin) . '-' sprintf('%02d'strval($moisSuivant)) . '-10';
  444.                 break;
  445.             case $jourDebut == 25:
  446.                 $dateFinCreneau strval($anneeFin) . '-' sprintf('%02d'strval($moisSuivant)) . '-15';
  447.                 break;
  448.             case $jourDebut == 30:
  449.                 $dateFinCreneau strval($anneeFin) . '-' sprintf('%02d'strval($moisSuivant)) . '-20';
  450.                 break;
  451.             default:
  452.                 $dateFinCreneau '';
  453.                 break;
  454.         }
  455.         //If today ne correspond pas aux jours, on ne lance pas le script 
  456.         if ($dateFinCreneau != '') {
  457.             $clients $clientRepository->findAll();
  458.             $mailsEnvoyes = [];
  459.             $mailsErreur = [];
  460.             foreach ($clients as $key => $client) {
  461.                 //Pour chaque client, on recherche si il a des commandes à envoyer avant la date de fin
  462.                 $commandes $commandeRepository->findCommandesAEnvoyerCaviste($dateFinCreneau$client);
  463.                 if ($commandes) {
  464.                     $res $this->emailGeneratorService->sendEmailPrepareCommandesCaviste($client$commandes);
  465.                     if ($res) {
  466.                         $mailsEnvoyes[] = $client->getId();
  467.                     } else {
  468.                         $mailsErreur[] = $client->getId();
  469.                     }
  470.                 }
  471.             }
  472.             if ($mailsErreur) {
  473.                 $response = new Response();
  474.                 $response->setContent(json_encode([
  475.                     '$mailsErreur' => $mailsErreur,
  476.                 ]));
  477.                 $response->headers->set('Content-Type''application/json');
  478.                 return $response;
  479.             }
  480.             return new Response("OK");
  481.             exit();
  482.         }
  483.         return new Response("Pas d'\'envoi ce jour");
  484.         die();
  485.     }
  486.     private function getTNTSearchConfiguration()
  487.     {
  488.         $databaseURL $_ENV['DATABASE_URL'];
  489.         $databaseParameters parse_url($databaseURL);
  490.         $config = [
  491.             'driver'    => $databaseParameters["scheme"],
  492.             'host'      => $databaseParameters["host"],
  493.             'database'  => str_replace("/"""$databaseParameters["path"]),
  494.             'username'  => $databaseParameters["user"],
  495.             'password'  => $databaseParameters["pass"],
  496.             'storage'   => $this->fuzzy_storage '/fuzzy_storage_aeZAdJfvVpgZGTvh/',
  497.             'stemmer'   => \TeamTNT\TNTSearch\Stemmer\PorterStemmer::class
  498.         ];
  499.         return $config;
  500.     }
  501.     /**
  502.      * @Route("/generate-index_AiNnDiIPx7C9ZcWmoiO4", name="app_generate-index")
  503.      */
  504.     public function generate_index(): JsonResponse
  505.     {
  506.         $tnt = new TNTSearch;
  507.         // Obtain and load the configuration that can be generated with the previous described method
  508.         $configuration $this->getTNTSearchConfiguration();
  509.         $tnt->loadConfig($configuration);
  510.         $indexerCommande $tnt->createIndex('commande.index');
  511.         $indexerCommande->query('SELECT id, numero_facture, code_postal_livraison, ville_livraison, tracking_number FROM commande');
  512.         $indexerCommande->run();
  513.         $indexerClientFinal $tnt->createIndex('clientFinal.index');
  514.         $indexerClientFinal->query('SELECT id, full_name FROM client_final');
  515.         $indexerClientFinal->run();
  516.         $indexerClient $tnt->createIndex('client.index');
  517.         $indexerClient->query('SELECT id, raison_sociale FROM client');
  518.         $indexerClient->run();
  519.         return new JsonResponse('done');
  520.     }
  521.     /**
  522.      * @route("/fedexTest", name="instable")
  523.      */
  524.     public function cancelFedex()
  525.     {
  526.         $trackingNumber '773704227696';
  527.         $fedexEndpoint 'https://apis.fedex.com/ship/v1/shipments/cancel';
  528.         $payload '{
  529.             "trackingNumber": " ' $trackingNumber ' ",
  530.             "senderCountryCode": "FR",
  531.             "deletionControl": "DELETE_ALL_PACKAGES",
  532.             "accountNumber": {
  533.                 "value": "782780123"
  534.             }
  535.         }';
  536.         $curl curl_init();
  537.         curl_setopt_array($curl, array(
  538.             CURLOPT_URL => $fedexEndpoint,
  539.             CURLOPT_RETURNTRANSFER => true,
  540.             CURLOPT_ENCODING => '',
  541.             CURLOPT_MAXREDIRS => 10,
  542.             CURLOPT_TIMEOUT => 0,
  543.             CURLOPT_FOLLOWLOCATION => true,
  544.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  545.             CURLOPT_CUSTOMREQUEST => 'PUT',
  546.             CURLOPT_POSTFIELDS => $payload,
  547.             CURLOPT_HTTPHEADER => array(
  548.                 'x-customer-transaction-id: 624deea6-b709-470c-8c39-4b5511281492',
  549.                 'x-locale: en_US',
  550.                 'Content-Type: application/json',
  551.                 'Authorization: Bearer ' $this->getFedexToken()
  552.             ),
  553.         ));
  554.         $response curl_exec($curl);
  555.         $json json_decode($responsetrue);
  556.         var_dump($response);
  557.     }
  558.     public function getFedexToken()
  559.     {
  560.         $url "https://apis.fedex.com/oauth/token";
  561.         $payload "grant_type=client_credentials&client_id=l7c771e0d2fd444799b4ce63c4ccd10032&client_secret=7dacb43d3ecc4d239d27236f37a39075";
  562.         $ch curl_init($url);
  563.         curl_setopt($chCURLOPT_POST1);
  564.         curl_setopt($chCURLOPT_POSTFIELDS$payload);
  565.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  566.         $response curl_exec($ch);
  567.         $json json_decode($responsetrue);
  568.         curl_close($ch);
  569.         return $json['access_token'];
  570.     }
  571.     /**
  572.      * @route("/recapFedex_zS4DvryqHjVQdXCeRsgpP5JWc9tKn32Af8bLxE7B", name="recapFedex")
  573.      */
  574.     public function testDateCondition(CommandeRepository $commandeRepository): JsonResponse
  575.     {
  576.         $currentDayOfWeek date("w");
  577.         if ($currentDayOfWeek == || $currentDayOfWeek == 6) {
  578.             return new JsonResponse('ok');
  579.         }
  580.         // Iterate over the next seven days
  581.         for ($i 0$i 9$i++) {
  582.             if (intval(date('w'strtotime("+$i days"))) != && intval(date('w'strtotime("+$i days"))) != 0) {
  583.                 $dayName date("D"strtotime("+$i days"));
  584.                 switch ($dayName) {
  585.                     case 'Mon':
  586.                         $day 'Lundi';
  587.                         break;
  588.                     case 'Tue':
  589.                         $day 'Mardi';
  590.                         break;
  591.                     case 'Wed':
  592.                         $day 'Mercredi';
  593.                         break;
  594.                     case 'Thu':
  595.                         $day 'Jeudi';
  596.                         break;
  597.                     case 'Fri':
  598.                         $day 'Vendredi';
  599.                         break;
  600.                     default:
  601.                         $day '';
  602.                         break;
  603.                 }
  604.                 $mmddyyyyValue date("Y-m-d"strtotime("+$i days"));
  605.                 $days[] = array('name' => $day'mmddyyyy' => $mmddyyyyValue);
  606.             }
  607.         }
  608.         $daysInfo = [];
  609.         for ($i 0$i 5$i++) {
  610.             $datas $commandeRepository->findBy([
  611.                 'dateCollecte' => new DateTime($days[$i]['mmddyyyy']),
  612.                 'fedexPdfAvailable' => '0',
  613.                 'state' => 'attente_pec_transporteur'
  614.             ]);
  615.             $x 0;
  616.             foreach ($datas as $data) {
  617.                 $x++;
  618.             }
  619.             $daysInfo[] = array('dayDate' => $days[$i]['mmddyyyy'], 'dayName' => $days[$i]['name'], 'total' => $x);
  620.         }
  621.         $this->emailGeneratorService->sendFedexRecap($daysInfo);
  622.         return new JsonResponse('ok');
  623.     } 
  624.     /**
  625.      * @Route("/updatepresta", name="update_presta", methods={"POST", "GET"})
  626.      */
  627.     public function updatepresta(Request $requestEntityManagerInterface $emClientRepository $clientRepoMBEClient $mbe): JsonResponse
  628.     {
  629.         // paramètres à définir selon tes besoins
  630.         $internalReferenceID uniqid(); // identifiant unique de ta requête
  631.         $dateFrom '2023-01-01'// Date de début
  632.         $dateTo   date('Y-m-d'); // Date de fin (aujourd’hui par exemple)
  633.         $page     1// Première page
  634.         $toBeClosed null// true ou false, si tu veux filtrer
  635.         $departmentID null// Si nécessaire
  636.         // Appel à la méthode
  637.         $response $mbe->getShipmentsList(
  638.             $internalReferenceID,
  639.             $dateFrom,
  640.             $dateTo,
  641.             $page,
  642.             $toBeClosed,
  643.             $departmentID
  644.         );
  645.         // Supposons que $json contient la réponse de getShipmentsList
  646.         $shipments $response->ShipmentsFullInfo->ShipmentFullInfo// tableau d'expés
  647.         echo '<pre>';
  648.         foreach ($shipments as $shipment) {
  649.             // Récupérer la référence interne
  650.             $reference null;
  651.             $reference $shipment->ShipmentInfo->Referring ?? null;
  652.             
  653.             // On récupère le tracking MBE principal
  654.             $trackingMBE null;
  655.             if (isset($shipment->TrackingInfo->MasterTrackingMBE)) {
  656.                 $trackingMBE $shipment->TrackingInfo->MasterTrackingMBE;
  657.             } elseif (isset($shipment->TrackingInfo->TrackingsMBE->TrackingMBE)) {
  658.                 $trackingMBE $shipment->TrackingInfo->TrackingsMBE->TrackingMBE;
  659.             }
  660.             // On saute s'il n'y a pas de tracking
  661.             if (!$trackingMBE) continue;
  662.             // L'identifiant interne (peut être utilisé pour l'appel tracking)
  663.             $internalReferenceID $response->InternalReferenceID ?? uniqid();
  664.             // Appel à la méthode de tracking (ton wrapper PHP)
  665.             $trackingResponse $mbe->Tracking($internalReferenceID$trackingMBE);
  666.             $statut null;
  667.             if (isset($trackingResponse->TrackingStatus)) {
  668.                 $statut $trackingResponse->TrackingStatus;
  669.             } elseif (isset($trackingResponse->RequestContainer->TrackingStatus)) {
  670.                 $statut $trackingResponse->RequestContainer->TrackingStatus;
  671.             }
  672.             if($statut != null){
  673.                 
  674.                 if($statut == "WAITING_DELIVERY"){
  675.                                         
  676.                     
  677.                     if($reference != null && $reference != "0"){                        
  678.                         $host $_ENV['PRESTA_DB_HOST'] ?? getenv('PRESTA_DB_HOST');
  679.                         $db $_ENV['PRESTA_DB_NAME'] ?? getenv('PRESTA_DB_NAME');
  680.                         $user $_ENV['PRESTA_DB_USER'] ?? getenv('PRESTA_DB_USER');
  681.                         $pass $_ENV['PRESTA_DB_PASSWORD'] ?? getenv('PRESTA_DB_PASSWORD');
  682.                         $port $_ENV['PRESTA_DB_PORT'] ?? getenv('PRESTA_DB_PORT');
  683.     
  684.                         $charset 'utf8mb4';
  685.     
  686.                         $dsn "mysql:host=$host;dbname=$db;charset=$charset";
  687.     
  688.                         try {
  689.                             $pdoPresta = new PDO($dsn$user$pass, [
  690.                                 PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
  691.                                 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  692.                                 PDO::ATTR_EMULATE_PREPARES   => false,
  693.                             ]);
  694.     
  695.                             $stmt2 $pdoPresta->prepare("
  696.                                 UPDATE mbe_orders SET current_state = :new_state WHERE id_order = :id_order
  697.                             ");
  698.                             $save $stmt2->execute([
  699.                                 'new_state' => 4,
  700.                                 'id_order' => $reference,
  701.                             ]);
  702.                             $stmt3 $pdoPresta->prepare("
  703.                                 INSERT INTO mbe_order_history (id_employee, id_order, id_order_state, date_add)
  704.                                 VALUES (:id_employee, :id_order, :id_order_state, NOW())
  705.                             ");
  706.                             $stmt3->execute([
  707.                                 'id_employee'     => 0,
  708.                                 'id_order'        => $reference,
  709.                                 'id_order_state'  => 
  710.                             ]);                            
  711.     
  712.                         } catch (\PDOException $e) {
  713.                             throw new \RuntimeException('Erreur de connexion à la base Prestashop : ' $e->getMessage());
  714.                         } 
  715.                     }
  716.                 }
  717.             }
  718.             
  719.         }
  720.         echo '</pre>';
  721.         exit();
  722.     }
  723. }