src/Controller/Front/FrontCustomerAccountController.php line 601

Open in your IDE?
  1. <?php
  2. namespace Acme\SudcmsBundle\Controller\Front;
  3. use Acme\SudcmsBundle\Entity\AuthUser;
  4. use Acme\SudcmsBundle\Entity\EcoCustomers;
  5. use Acme\SudcmsBundle\Entity\EcoCustomersAddresses;
  6. use Acme\SudcmsBundle\Entity\Newsletter;
  7. use Acme\SudcmsBundle\Entity\Tchat;
  8. use Acme\SudcmsBundle\Entity\TchatMessages;
  9. use Acme\SudcmsBundle\Entity\TchatProducts;
  10. use Acme\SudcmsBundle\Form\Ecommerce\CustomerFrontType;
  11. use Acme\SudcmsBundle\Form\Ecommerce\CustomerResetPasswordType;
  12. use Acme\SudcmsBundle\Repository\AuthUserRepository;
  13. use Acme\SudcmsBundle\Repository\EcoCustomersAddressesRepository;
  14. use Acme\SudcmsBundle\Repository\EcoCustomersRepository;
  15. use Acme\SudcmsBundle\Repository\EcoInvoicesRepository;
  16. use Acme\SudcmsBundle\Repository\EcoOrdersRepository;
  17. use Acme\SudcmsBundle\Repository\EcoPlanningRepository;
  18. use Acme\SudcmsBundle\Repository\EcoProductsReferencesRepository;
  19. use Acme\SudcmsBundle\Repository\EcoShippingfeesCountryRepository;
  20. use Acme\SudcmsBundle\Repository\EcoShippingOrdersRepository;
  21. use Acme\SudcmsBundle\Repository\SiteRepository;
  22. use Acme\SudcmsBundle\Repository\TchatMessagesRepository;
  23. use Acme\SudcmsBundle\Repository\TchatProductsRepository;
  24. use Acme\SudcmsBundle\Repository\TchatRepository;
  25. use Acme\SudcmsBundle\Service\ApiService;
  26. use Acme\SudcmsBundle\Service\Ecommerce\LoyaltySystemService;
  27. use Acme\SudcmsBundle\Service\FileService;
  28. use Acme\SudcmsBundle\Service\MailerService;
  29. use Acme\SudcmsBundle\Service\OtideaUtils;
  30. use Doctrine\ORM\EntityManagerInterface;
  31. use Exception;
  32. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  33. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  34. use Symfony\Component\HttpFoundation\JsonResponse;
  35. use Symfony\Component\HttpFoundation\Request;
  36. use Symfony\Component\HttpFoundation\RequestStack;
  37. use Symfony\Component\HttpFoundation\Response;
  38. use Symfony\Component\HttpKernel\KernelInterface;
  39. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  40. use Symfony\Component\Routing\Annotation\Route;
  41. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  42. use Throwable;
  43. use const SITE_NAME;
  44. class FrontCustomerAccountController extends AbstractController
  45. {
  46.     private $session;
  47.     private $otideaUtils;
  48.     private $mailerService;
  49.     private $autorizedFiles = ['jpg''jpeg''png''pdf''doc''docx''xls''xlsx''ppt''pptx'];
  50.     private $fileService;
  51.     private $isEcommerce;
  52.     private $currentUserConnected;
  53.     private ApiService $apiService;
  54.     public function __construct(RequestStack   $requestStackEntityManagerInterface $entityManager,
  55.                                 OtideaUtils    $otideaUtilsMailerService $mailerServiceFileService $fileService,
  56.                                 SiteRepository $siteRepositoryApiService $apiService)
  57.     {
  58.         $this->session $requestStack->getCurrentRequest()->getSession();
  59.         $this->apiService $apiService;
  60.         $this->entityManager $entityManager;
  61.         $this->otideaUtils $otideaUtils;
  62.         $this->mailerService $mailerService;
  63.         $this->fileService $fileService;
  64.         $this->isEcommerce $siteRepository->find($this->session->get('admin_site_uid'))->getIsEcommerce();
  65.         $this->currentUserConnected $otideaUtils->getUserConnected();
  66.         if (!IS_ECOMMERCE) {
  67.             header('Location: ' WEBSITEROOT);
  68.             exit;
  69.         }
  70.         if (!$this->apiService->testConnexion()) {
  71.             $this->addFlash('danger''Une erreur est survenue, veuillez réessayer ultérieurement.');
  72.             return $this->redirectToRoute('front_home');
  73.         }
  74.     }
  75.     /**
  76.      * Envoi un mail avec un nouveau mot de passe
  77.      * @param int $authUser_id
  78.      */
  79.     private function sendNotificationNewPassword($authUser_id)
  80.     {
  81.         $this->mailerService->fromName SITE_NAME;
  82.         $this->mailerService->subject SITE_NAME " - Mot de passe oublié";
  83.         $authUser $this->entityManager->getRepository(AuthUser::class)->find($authUser_id);
  84.         //Enregistrement du nouveau mot de passe
  85.         $newPassword uniqid();
  86.         $password_hash password_hash($newPasswordPASSWORD_DEFAULT);
  87.         $authUser->setPassword($password_hash);
  88.         $this->entityManager->persist($authUser);
  89.         $this->entityManager->flush();
  90.         $customer $this->entityManager->getRepository(EcoCustomers::class)->findOneBy(['authUserId' => $authUser_id]);
  91.         $allRecipients[] = [
  92.             "nom" => $customer->getCustLastname(),
  93.             "prenom" => $customer->getCustFirstname(),
  94.             "email" => $customer->getAuthUserId()->getEmail(),
  95.             "type" => 'to'
  96.         ];
  97.         $htmlContent $this->renderView('layouts/layouts_emails/notification_new_password.html.twig', [
  98.             'password' => $newPassword,
  99.         ]);
  100.         $this->mailerService->sendMail($allRecipients$htmlContent);
  101.     }
  102.     #[Route(path'/inscription'name'front_customer_registration')]
  103.     public function inscription(Request                     $request,
  104.                                 AuthUserRepository          $repoAuthUser,
  105.                                 EcoCustomersRepository      $ecoCustomersRepository,
  106.                                 UserPasswordHasherInterface $passwordHasher,
  107.                                 ApiService                  $api): Response
  108.     {
  109.         //Verification Recaptcha
  110.         $recaptcha_url 'https://www.google.com/recaptcha/api/siteverify';
  111.         $recaptcha_secret '6LfFKr0qAAAAAO8QfV8HQcPKViozt2RGLY7A2ORL';
  112.         $recaptcha_response $_POST['g-recaptcha-response'];
  113.         // Make and decode POST request:
  114.         $recaptcha file_get_contents($recaptcha_url '?secret=' $recaptcha_secret '&response=' $recaptcha_response);
  115.         $recaptcha json_decode($recaptcha);
  116.         if ($recaptcha->score >= 0.5) {
  117.             // Récupération du formulaire d'inscription
  118.             $newCustomer $request->request->get('customer_front');
  119.             // Vérification si l'utilisateur existe déjà en BDD
  120.             if ($repoAuthUser->findOneBy(['email' => $newCustomer['AdrCourriel']])) {
  121.                 $this->addFlash('danger''Cet utilisateur existe déjà');
  122.                 return $this->redirectToRoute('front_app_login');
  123.             }
  124.             // Création du ECO_CUSTOMER et du AUTH_USER en BDD
  125.             $addCustomer = new EcoCustomers();
  126.             $addAuthUser = new AuthUser();
  127.             $addCustomer->setCustCreationDate(new \DateTime());
  128.             $addCustomer->setAuthUserId($addAuthUser);
  129.             $addCustomer->setOdysseeReference(0);
  130.             $addAuthUser->setCreationDatetime(new \DateTime());
  131.             $addAuthUser->setRoles(["ROLE_USER""ROLE_CUSTOMER"]);
  132.             $addAuthUser->setEmail($newCustomer['AdrCourriel']);
  133.             if ($newCustomer['password']['first'] != null) {
  134.                 $hashedPassword $passwordHasher->hashPassword(
  135.                     $addAuthUser,
  136.                     $newCustomer['password']['first']
  137.                 );
  138.                 $addAuthUser->setPassword($hashedPassword);
  139.             } else {
  140.                 $this->addFlash('danger''Un mot de passe conforme est requis');
  141.                 return $this->redirectToRoute('front_app_login');
  142.             }
  143.             if (!filter_var($newCustomer['AdrCourriel'], FILTER_VALIDATE_EMAIL) && strlen($newCustomer['AdrCourriel']) < 6) {
  144.                 $this->addFlash('danger''Veuillez entrer une adresse email valide.');
  145.                 return $this->redirectToRoute('front_app_login');
  146.             }
  147.             $this->entityManager->persist($addCustomer);
  148.             $this->entityManager->persist($addAuthUser);
  149.             $this->entityManager->flush();
  150.             $result $this->editCustomer($newCustomer$addCustomer$addAuthUser$api);
  151.             if ($result == 'ok') {
  152.                 $this->addFlash('success''Votre compte a bien été créé');
  153.                 $this->authenticateUser($addAuthUser);
  154.                 if ($request->getSession()->get('_security.main.target_path')) {
  155.                     return $this->redirect($request->getSession()->get('_security.main.target_path'));
  156.                 }
  157.             } else {
  158.                 $this->addFlash('danger'$result);
  159.             }
  160.         } else {
  161.             $this->addFlash('danger''Vous êtes un robots');
  162.             return $this->redirectToRoute('front_app_login');
  163.         }
  164.         return $this->redirectToRoute('front_app_login');
  165.     }
  166.     //Fonction de connexion automatique après inscription
  167.     private function authenticateUser(AuthUser $user)
  168.     {
  169.         $providerKey 'main'// your firewall name
  170.         $token = new UsernamePasswordToken($usernull$providerKey$user->getRoles());
  171.         $this->container->get('security.token_storage')->setToken($token);
  172.     }
  173.     //Fonction d'édition des utilisateurs
  174.     private function editCustomer($newCustomer$addCustomer$addAuthUser$api): string
  175.     {
  176.         if (is_object($newCustomer)) {
  177.             $newCustomer = (array)$newCustomer;
  178.         }
  179.         // On définie les valeurs par défaut si elles ne sont pas définies
  180.         $newCustomer['IdOdysseeClient'] = $newCustomer['IdOdysseeClient'] ?? 0;
  181.         $newCustomer['IdExterneClient'] = $newCustomer['IdExterneClient'] ?? 0;
  182.         // On recherche dans ODYSSEE si un client existe déjà avec cet email
  183.         $searchCustomer $api->rechercherClient(idOdyssee$newCustomer['IdOdysseeClient'],
  184.             adrCourriel$newCustomer['AdrCourriel']);
  185.         // On transforme la date d'anniversaire
  186.         $birthday = new \DateTime($newCustomer->{'DateNaissance'} ?? $newCustomer['DateNaissance']);
  187.         // On modifie l'ID ODYSSEE si l'utilisateur existe déjà
  188.         $idOdyssee = (!isset($searchCustomer->{'status'}) && !empty($searchCustomer)) ? $searchCustomer[0]->{'IdOdysseeClient'} : $newCustomer['IdOdysseeClient'];
  189.         $addInOdyssee null;
  190.         if (!isset($searchCustomer->{'status'}) && !empty($searchCustomer)) {
  191.             foreach ($searchCustomer as $customer) {
  192.                 if ($newCustomer['Nom'] == $customer->{'Nom'} && $newCustomer['Prenom'] == $customer->{'Prenom'}) {
  193.                     $addInOdyssee $api->editFicheOdyssee(
  194.                         $idOdyssee,
  195.                         "" $addCustomer->getId(),
  196.                         $newCustomer['Civilite'],
  197.                         $newCustomer['Nom'],
  198.                         $newCustomer['Prenom'],
  199.                         $birthday->format('Y-m-d\T00:00:00'),
  200.                         $newCustomer['Sexe'],
  201.                         $newCustomer['Adresse1'],
  202.                         $newCustomer['Adresse2'],
  203.                         $newCustomer['Adresse3'],
  204.                         $newCustomer['CodePostal'],
  205.                         $newCustomer['Ville'],
  206.                         $newCustomer['Pays'],
  207.                         $newCustomer['TelFixe'],
  208.                         $newCustomer['TelMobile'],
  209.                         $newCustomer['AdrCourriel'],
  210.                         isset($newCustomer['RefusComCom']) ? (int)$newCustomer['RefusComCom'] : 0,
  211.                         "update"
  212.                     );
  213.                     break;
  214.                 }
  215.             }
  216.         } else {
  217.             $addInOdyssee $api->editFicheOdyssee(
  218.                 $idOdyssee,
  219.                 "" $addCustomer->getId(),
  220.                 $newCustomer['Civilite'],
  221.                 $newCustomer['Nom'],
  222.                 $newCustomer['Prenom'],
  223.                 $birthday->format('Y-m-d\T00:00:00'),
  224.                 $newCustomer['Sexe'],
  225.                 $newCustomer['Adresse1'],
  226.                 $newCustomer['Adresse2'],
  227.                 $newCustomer['Adresse3'],
  228.                 $newCustomer['CodePostal'],
  229.                 $newCustomer['Ville'],
  230.                 $newCustomer['Pays'],
  231.                 $newCustomer['TelFixe'],
  232.                 $newCustomer['TelMobile'],
  233.                 $newCustomer['AdrCourriel'],
  234.                 isset($newCustomer['RefusComCom']) ? (int)$newCustomer['RefusComCom'] : 0
  235.             );
  236.         }
  237.         // On met a jour en BDD
  238.         $addCustomer->setOdysseeReference((!isset($searchCustomer->{'status'}) && !empty($searchCustomer) && $searchCustomer != 0) ? $searchCustomer[0]->{'IdOdysseeClient'} : (int)$addInOdyssee[0]->{'IdOdysseeClient'});
  239.         $this->entityManager->persist($addCustomer);
  240.         $this->entityManager->flush();
  241.         // Si on trouve plusieurs compte associés à l'email, on les créer
  242.         if (!isset($searchCustomer->{'status'}) && !empty($searchCustomer)) {
  243.             foreach ($searchCustomer as $cust) {
  244.                 if (!$this->entityManager->getRepository(EcoCustomers::class)->findOneBy(['odyssee_reference' => $cust->{'IdOdysseeClient'}])) {
  245.                     $addOtherCustomer = new EcoCustomers();
  246.                     $addOtherCustomer->setAuthUserId($addAuthUser);
  247.                     $addOtherCustomer->setOdysseeReference($cust->{'IdOdysseeClient'});
  248.                     $addOtherCustomer->setCustCreationDate(new \DateTime());
  249.                     $this->entityManager->persist($addOtherCustomer);
  250.                     $this->entityManager->flush();
  251.                 }
  252.             }
  253.         }
  254.         return 'ok';
  255.     }
  256.     /*
  257.      * Permet la création et la modification d'un compte client
  258.      * ainsi que la création de l'utilisateur
  259.      * @param $params array
  260.      * @return null
  261.      */
  262.     private function setCustomerAccount($params = [])
  263.     {
  264.         $form = isset($params['form']) ? $params['form'] : null;
  265.         $customer = isset($params['customer']) ? $params['customer'] : null;
  266.         $repoAuthUser = isset($params['repoAuthUser']) ? $params['repoAuthUser'] : null;
  267.         $repoNews = isset($params['repoNews']) ? $params['repoNews'] : null;
  268.         $passwordHasher = isset($params['passwordHasher']) ? $params['passwordHasher'] : null;
  269.         $repoEcoCustomerAddresses = isset($params['repoAddress']) ? $params['repoAddress'] : null;
  270.         if ($repoAuthUser !== null && $repoNews !== null && $passwordHasher !== null) {
  271.             // vérification de la validité de l'adresse email
  272.             if (!$this->validateEmails($form->get('email')->getData())) {
  273.                 $this->session->set('displayPopup''email-not-good');
  274.                 return $this->redirectToRoute('front_customer_registration');
  275.             }
  276.             // vérification que le compte client n'existe pas déjà
  277.             $emailSearch $repoAuthUser->findOneBy(['email' => $form->get('email')->getData()]);
  278.             if ($emailSearch !== null && $customer->getId() == 0) {
  279.                 $this->session->set('displayPopup''email-exist');
  280.                 return $this->redirectToRoute('front_customer_registration');
  281.             }
  282.             $newCustomer $customer->getAuthUserId() == null;
  283.             $user $this->setUserAccount(!$newCustomer $customer->getAuthUserId()->getId() : null$passwordHasher,
  284.                 $form$repoAuthUser);
  285.             // @TODO connexion de l'utilisateur après sa création de compte
  286.             //                    $userAuthenticator->authenticateUser($user);
  287.             if ($customer->getId() == 0) {
  288.                 // liaison entre le compte utilisateur et le client
  289.                 $customer->setAuthUserId($user);
  290.                 $customer->setCustCreationDate(new \DateTime());
  291.                 // reference par defaut qui sera maj après l'enregistrement
  292.                 $customer->setCustReference("CLI");
  293.                 // pour la création d'un compte entreprise est confirmée par défaut
  294.                 $customer->setcustAccountStatus('confirmed');
  295.                 $customer->setCustAccountType('company');
  296.                 // FRANCE par défaut
  297.                 $customer->setCustCountryId(1);
  298.             }
  299.             // enregistrement du client
  300.             try {
  301.                 $this->entityManager->persist($customer);
  302.                 $this->entityManager->flush();
  303.             } catch (Exception $ex) {
  304.                 $this->addFlash('danger'"Une erreur s'est produite lors de l'enregistrement du compte");
  305.             }
  306.             // nouveau client,  definition du numéro client + maj
  307.             if ($newCustomer) {
  308.                 $ref $customer->getId() + 1000;
  309.                 $customer->setCustReference("CLI" $ref);
  310.                 try {
  311.                     $this->entityManager->persist($customer);
  312.                     $this->entityManager->flush();
  313.                 } catch (Exception $ex) {
  314.                     $this->addFlash('danger'"Une erreur s'est produite lors de la définition du numéro client");
  315.                 }
  316.             }
  317.             // enregistrement de l'adresse de livraison
  318.             if ($customer->getCustAccountType() == 'company') {
  319.                 $address null;
  320.                 $addresses $customer->getAddressesId();
  321.                 if (sizeof($addresses->getValues()) > 0) {
  322.                     foreach ($addresses as $add) {
  323.                         $address $add;
  324.                         break;
  325.                     }
  326.                 }
  327.                 $this->setDeliveryAddress($customer$form$address);
  328.             }
  329.             // connexion auto du client après la creation du compte
  330.             //                $this->setCustomerConnection($customer->getId());
  331.             // inscription à la newsletter
  332.             $mailResult $repoNews->findOneBy(['nlEmail' => $form->get('email')->getData()]);
  333.             if ($form->get('accept_newsletter')->getData() && $mailResult == NULL) {
  334.                 $this->subscriptionNewsletter($form->get('email')->getData());
  335.             }
  336.             // envoi du mail de confirmation de création de compte
  337.             if ($newCustomer) {
  338.                 $this->sendConfirmationNewAccount($form->get('email')->getData(), $form->getData());
  339.             }
  340.             $this->addFlash('success'"enregistré avec succès");
  341.             if ($this->session->has('returnToBasket')) {
  342.                 $this->session->remove('returnToBasket');
  343.                 return $this->redirectToRoute('front_basket_index');
  344.             }
  345.             return $this->redirectToRoute('front_customer_account');
  346.         }
  347.     }
  348.     /*
  349.      * Permet d'ajouter un nouveau compte client
  350.      * avec le role de client
  351.      * @return bool
  352.      */
  353.     private function setUserAccount($authUserId 0$passwordHasher null$form null$repoAuthUser null)
  354.     {
  355.         if ($form->get('email')->getData() !== null) {
  356.             if ($authUserId 0) {
  357.                 $user $repoAuthUser->find($authUserId);
  358.             } else {
  359.                 $user = new AuthUser();
  360.             }
  361.             $user->setEmail($form->get('email')->getData());
  362.             // modification du mot de passe
  363.             if ($form->has('password') && $form->get('password')->getData() !== null && trim($form->get('password')->getData()) != "") {
  364.                 // hash the password (based on the security.yaml config for the $user class)
  365.                 $hashedPassword $passwordHasher->hashPassword(
  366.                     $user,
  367.                     $form->get('password')->getData()
  368.                 );
  369.                 $user->setPassword($hashedPassword);
  370.             }
  371.             if ($user->getId() == 0) {
  372.                 $user->setRoles(array_merge($user->getRoles(), ['ROLE_CUSTOMER']));
  373.                 $user->setCreationDatetime(new \DateTime());
  374.             }
  375.             $this->entityManager->persist($user);
  376.             $this->entityManager->flush();
  377.             return $user;
  378.         }
  379.         return false;
  380.     }
  381.     /*
  382.      * Permet d'ajouter une adresse de livraison pour un client
  383.      * @param $customerId int identifiant du client dans eco_customer
  384.      * @param $form array les données du formulaire de compte
  385.      * @return void
  386.      */
  387.     private function setDeliveryAddress($customer null$form null$address null)
  388.     {
  389.         if ($customer !== null && $form != null) {
  390.             if ($address !== null) {
  391.                 $deliveryAddress $address;
  392.             } else {
  393.                 $deliveryAddress = new EcoCustomersAddresses();
  394.             }
  395.             $deliveryAddress->setCountryId(1); // PAR DEFAUT : FRANCE
  396.             $deliveryAddress->setCustomersId($customer);
  397.             $deliveryAddress->setAddressFirstname($form->get('cust_firstname')->getData());
  398.             $deliveryAddress->setAddressLastname($form->get('cust_lastname')->getData());
  399.             $deliveryAddress->setAddressCivility($form->get('cust_civility')->getData());
  400.             // address est null = nouveau compte
  401.             // address n'est pas null = compte existant maj des données
  402.             // nouveau compte : on verifie que le choix d'adresse identique entre facturation et livraison
  403.             if ($address !== null || ($form->has('same_billing_delivery') && !$form->get('same_billing_delivery')->getData())) {
  404.                 $deliveryAddress->setAddressPostal($form->get('address')->getData()->getAddressPostal());
  405.                 $deliveryAddress->setAddressAdditional($form->get('address')->getData()->getAddressAdditional());
  406.                 $deliveryAddress->setAddressDoor($form->get('address')->getData()->getAddressDoor());
  407.                 $deliveryAddress->setAddressBuilding($form->get('address')->getData()->getAddressBuilding());
  408.                 $deliveryAddress->setAddressFloor($form->get('address')->getData()->getAddressFloor());
  409.                 $deliveryAddress->setAddressPostalCode($form->get('address')->getData()->getAddressPostalCode());
  410.                 $deliveryAddress->setAddressCity($form->get('address')->getData()->getAddressCity());
  411.                 $deliveryAddress->setAddressSociety($form->get('address')->getData()->getAddressSociety());
  412.             } // adresse identique entre facturation et livraison
  413.             else {
  414.                 $deliveryAddress->setAddressPostal($form->get('cust_address')->getData());
  415.                 $deliveryAddress->setAddressAdditional($form->get('cust_additional_address')->getData());
  416.                 $deliveryAddress->setAddressDoor($form->get('cust_door')->getData());
  417.                 $deliveryAddress->setAddressBuilding($form->get('cust_building')->getData());
  418.                 $deliveryAddress->setAddressFloor($form->get('cust_floor')->getData());
  419.                 $deliveryAddress->setAddressPostalCode($form->get('cust_postal_code')->getData());
  420.                 $deliveryAddress->setAddressCity($form->get('cust_city')->getData());
  421.                 $deliveryAddress->setAddressSociety($form->get('cust_society')->getData());
  422.             }
  423.             try {
  424.                 $this->entityManager->persist($deliveryAddress);
  425.                 $this->entityManager->flush();
  426.             } catch (Exception $ex) {
  427.                 $this->addFlash('danger',
  428.                     "Une erreur s'est produite lors de l'enregistrement de l'adresse de livraison");
  429.             }
  430.         }
  431.     }
  432.     /*
  433.      * Permet d'envoyer le mail de confirmation
  434.      * de création de compte
  435.      * @param $email string l'email destinataire
  436.      * @param $formData array les données du form de création de compte
  437.      * @return void
  438.      */
  439.     private function sendConfirmationNewAccount($email null$formData null)
  440.     {
  441.         if (isset($email) && isset($formData)) {
  442.             $this->mailerService->subject "Demande d'adhésion sur " SITE_NAME;
  443.             $htmlContent $this->renderView('layouts/layouts_emails/notification_request_company.html.twig', [
  444.                 'formData' => $formData,
  445.                 'email' => $email,
  446.             ]);
  447.             $this->mailerService->sendMail([], $htmlContentNULL'request-company');
  448.         }
  449.     }
  450.     /*
  451.      * Permet d'inscrire un nouveau mail à la newsletter
  452.      * @param $email string l'email à inscrire
  453.      * @return void
  454.      */
  455.     private function subscriptionNewsletter($email "")
  456.     {
  457.         if ($email != "") {
  458.             $mail = new Newsletter();
  459.             $mail->setNlCreationDatetime(new \DateTime());
  460.             $mail->setNlEmail($email);
  461.             $mail->setNlRgpdChecked(true);
  462.             $this->entityManager->persist($mail);
  463.             $this->entityManager->flush();
  464.             try {
  465.                 $this->entityManager->persist($mail);
  466.                 $this->entityManager->flush();
  467.             } catch (Exception $ex) {
  468.                 $this->addFlash('danger',
  469.                     "Une erreur s'est produite lors de l'enregistrement de l'inscription à la newsletter");
  470.             }
  471.         }
  472.     }
  473.     /**
  474.      * Permet de redéfinir le mot de passe depuis le compte client
  475.      */
  476.     #[Route(path'/compte-client/modifier-mot-de-passe'name'front_customer_edit_password')]
  477.     public function setUserPassword(Request            $requestUserPasswordHasherInterface $passwordHasher,
  478.                                     AuthUserRepository $repoAuthUser)
  479.     {
  480.         $form $this->createForm(CustomerResetPasswordType::class);
  481.         $form->handleRequest($request);
  482.         if ($form->isSubmitted() && $form->isValid()) {
  483.             $user $repoAuthUser->find($this->getUser()->getId());
  484.             // vérification du mot de passe actuel rentré avec celui dans la bdd
  485.             if (!$passwordHasher->isPasswordValid($user$form->get('actualPassword')->getData())) {
  486.                 $this->addFlash('danger''Le mot de passe ne correspond pas à votre mot de passe actuel.');
  487.                 return $this->redirectToRoute('front_customer_account');
  488.             }
  489.             $hashedPassword $passwordHasher->hashPassword(
  490.                 $user,
  491.                 $form->get('password')->getData()
  492.             );
  493.             $user->setPassword($hashedPassword);
  494.             $this->entityManager->persist($user);
  495.             $this->entityManager->flush();
  496.             $this->addFlash('success''Votre mot de passe a été changé. Veuillez vous reconnecter.');
  497.             return $this->redirectToRoute('front_app_logout');
  498.         }
  499.         return $this->redirectToRoute('front_customer_account');
  500.     }
  501.     /**
  502.      * @throws Throwable
  503.      */
  504.     #[Route(path'/compte-client/mes-coordonnees/{refOdyssee}'name'front_customer_account')]
  505.     public function account(Request                     $request,
  506.                             EcoCustomersRepository      $ecoCustomersRepository,
  507.                             UserPasswordHasherInterface $passwordHasher,
  508.                             ApiService                  $api,
  509.                                                         $refOdyssee null): Response
  510.     {
  511.         $previousRoute $request->getSession()->get('previous_route');
  512.         if ($previousRoute === 'front_app_login') {
  513.             $request->getSession()->remove('previous_route');
  514.             return $this->redirectToRoute('front_shopping_categorie');
  515.         }
  516.         if ($this->currentUserConnected) {
  517.             $this->redirectToRoute('front_home');
  518.         }
  519.         $ecoCustomer $refOdyssee $ecoCustomersRepository->findOneBy(['odyssee_reference' => $refOdyssee]) : $this->currentUserConnected;
  520.         $form $this->createForm(CustomerFrontType::class, $ecoCustomer, [
  521.             'odysseeClient' => $api->rechParIdOdyssee($refOdyssee ?: $ecoCustomer->getOdysseeReference())[0],
  522.             'type' => $refOdyssee 'refOdyssee' 'account'
  523.         ]);
  524.         $form->handleRequest($request);
  525.         if ($refOdyssee && !$ecoCustomersRepository->findOneBy(['odyssee_reference' => $refOdyssee])) {
  526.             $addCustomer = new EcoCustomers();
  527.             $addCustomer->setCustCreationDate(new \DateTime());
  528.             $addCustomer->setAuthUserId($this->currentUserConnected->getAuthUserId());
  529.             $addCustomer->setOdysseeReference(0);
  530.             $this->entityManager->persist($addCustomer);
  531.             $this->entityManager->flush();
  532.             $newCustomer $form->getConfig()->getOptions()['odysseeClient'];
  533.             $this->editCustomer($newCustomer$addCustomer$this->currentUserConnected->getAuthUserId(), $api);
  534.             return $this->redirectToRoute('front_customer_account',
  535.                 ['refOdyssee' => $form->getConfig()->getOptions()['odysseeClient']->{'IdOdysseeClient'}]);
  536.         }
  537.         if ($form->isSubmitted() && $form->isValid()) {
  538.             try {
  539.                 $customer $request->request->get('customer_front');
  540.                 if (!$refOdyssee) {
  541.                     $this->currentUserConnected->getAuthUserId()->setEmail($customer['AdrCourriel']);
  542.                     if ($customer['password']['first'] != null) {
  543.                         $hashedPassword $passwordHasher->hashPassword(
  544.                             $this->currentUserConnected->getAuthUserId(),
  545.                             $customer['password']['first']
  546.                         );
  547.                         $this->currentUserConnected->getAuthUserId()->setPassword($hashedPassword);
  548.                     }
  549.                     $this->entityManager->persist($this->currentUserConnected->getAuthUserId());
  550.                     $this->entityManager->flush();
  551.                     foreach ($this->currentUserConnected->getAuthUserId()->getCustomer() as $cust) {
  552.                         $customerPush $api->rechercherClient(idOdyssee: (int)$cust->getOdysseeReference());
  553.                         $this->editCustomer($customerPush[0], $cust,
  554.                             $this->currentUserConnected->getAuthUserId(),
  555.                             $api);
  556.                     }
  557.                 } else {
  558.                     $cust $ecoCustomersRepository->findOneBy(['odyssee_reference' => $refOdyssee]);
  559.                     $customer['IdOdysseeClient'] = $refOdyssee;
  560.                     $customer['IdExterneClient'] = $cust->getId();
  561.                     $customer['AdrCourriel'] = $this->currentUserConnected->getAuthUserId()->getEmail();
  562.                     $this->editCustomer($customer$cust,
  563.                         $this->currentUserConnected->getAuthUserId(),
  564.                         $api);
  565.                 }
  566.                 $this->addFlash('success'"enregistré avec succès");
  567.             } catch (Exception $ex) {
  568.                 $this->addFlash('danger'"Une erreur s'est produite lors de l'enregistrement ");
  569.             }
  570.             if ($request->query->get("from") !== null && $request->query->get("from") == "delivery") {
  571.                 return $this->redirectToRoute('front_basket_delivery');
  572.             } else {
  573.                 return $this->redirectToRoute('front_customer_account', ['refOdyssee' => $refOdyssee]);
  574.             }
  575.         }
  576.         $allOdysseeCustomers = [];
  577.         foreach ($this->currentUserConnected->getAuthUserId()->getCustomer() as $cust) {
  578.             $allOdysseeCustomers[] = $api->rechParIdOdyssee($cust->getOdysseeReference());
  579.         }
  580.         $allOdysseeCustomers $api->rechercherClient(adrCourriel$this->currentUserConnected->getAuthUserId()->getEmail());
  581.         $template $refOdyssee 'ref_odyssee' 'account';
  582.         $pageAccount 'coordonnees';
  583.         $selectedMenu $refOdyssee ?: 'email';
  584.         return $this->render('@main-app/front/front_customer_account/' $template '.html.twig', [
  585.             'form' => $form->createView(),
  586.             'pageAccount' => $pageAccount,
  587.             'selectedMenu' => $selectedMenu,
  588.             'customer' => $refOdyssee $ecoCustomersRepository->findOneBy(['odyssee_reference' => $refOdyssee]) : $this->currentUserConnected,
  589.             'user' => $this->currentUserConnected->getAuthUserId(),
  590.             'allOdysseeCustomers' => $allOdysseeCustomers
  591.         ]);
  592.     }
  593.     #[Route(path'/compte-client/save-delivery'name'front_customer_save_delivery_address')]
  594.     public function saveDeliveryAddress(Request $requestEcoCustomersAddressesRepository $repoCustomersAddresses)
  595.     {
  596.         if ($request->isMethod('POST')) {
  597.             $deliveryAddress $repoCustomersAddresses->find($request->get('delivery_id'));
  598.             if ($request->get('delivery_id') == 0) {
  599.                 $deliveryAddress = new EcoCustomersAddresses;
  600.                 $deliveryAddress->setCustomerId($this->currentUserConnected->getId());
  601.             }
  602.             //Enregistrement de l'adresse de livraison
  603.             $deliveryAddress->setCountryId($request->get('country_id'));
  604.             $deliveryAddress->setAddressCivility($request->get('address_civility'));
  605.             $deliveryAddress->setAddressFirstname($request->get('address_firstname'));
  606.             $deliveryAddress->setAddressLastname($request->get('address_lastname'));
  607.             $deliveryAddress->setAddressSociety($request->get('address_society'));
  608.             $deliveryAddress->setAddressPostalCode($request->get('address_postal_code'));
  609.             $deliveryAddress->setAddressCity($request->get('address_city'));
  610.             $deliveryAddress->setAddressPhone($request->get('address_phone'));
  611.             $deliveryAddress->setAddressEntitled($request->get('address_entitled'));
  612.             $this->entityManager->persist($deliveryAddress);
  613.             $this->entityManager->flush();
  614.             $this->addFlash('success'"enregistré avec succès");
  615.             if ($request->query->get("from") !== null && $request->query->get("from") == "delivery") {
  616.                 return $this->redirectToRoute('front_basket_delivery');
  617.             } else {
  618.                 return $this->redirectToRoute('front_customer_account');
  619.             }
  620.         }
  621.     }
  622.     /**
  623.      * @throws Throwable
  624.      */
  625.     #[Route(path'/compte-client/mes-commandes'name'front_customer_orders')]
  626.     public function orders(Request                     $request,
  627.                            EcoOrdersRepository         $repoOrders,
  628.                            EcoShippingOrdersRepository $repoShippingOrders,
  629.                            LoyaltySystemService        $loyaltySystem,
  630.                            ApiService                  $api): Response
  631.     {
  632.         $customers $this->currentUserConnected->getAuthUserId()->getCustomer();
  633.         $allAvailablesResaCures = [];
  634.         // On parcourt tous les clients attachés à ce compte
  635.         $orders = [];
  636.         foreach ($customers as $customer) {
  637.             // Récupération des commandes du client
  638.             $order $api->rechercherResaCure(idOdysseeClient: (int)$customer->getOdysseeReference());
  639.             if (!isset($order->status)) {
  640.                 $orders[$customer->getOdysseeReference()] = $order;
  641.             }
  642.             // On parcours les cures, on ne garde que celles dont la date de début est supérieure à la date du jour
  643.             foreach ($orders as $patient) {
  644.                 foreach ($patient as $cure) {
  645.                     $dateDebut = new \DateTime($cure->{'Date_Debut_Resa'});
  646.                     $dateFin = new \DateTime($cure->{'Date_Fin_Resa'});
  647.                     $dateJour = new \DateTime();
  648.                     if ($dateDebut $dateJour || $dateFin $dateJour) {
  649.                         $allAvailablesResaCures[] = $cure;
  650.                     }
  651.                 }
  652.             }
  653.         }
  654.         $allOdysseeCustomers $api->rechercherClient(adrCourriel$this->currentUserConnected->getAuthUserId()->getEmail());
  655.         //TODO : si le site est un SPA, récupérer les résa et ventes SPA (non disponible dans l'API à ce jour)
  656.         if (ODYSSEE_TYPE == 'SPA') {
  657.             $allAvailablesResaCures = [];
  658.         }
  659.         return $this->render('@main-app/front/front_customer_account/orders.html.twig', [
  660.             'orders' => $allAvailablesResaCures,
  661.             'indicationsPrincipales' => $api->listerItp(),
  662.             'indicationsSecondaires' => $api->listerIts(),
  663.             'pageAccount' => 'commandes',
  664.             'allOdysseeCustomers' => $allOdysseeCustomers
  665.         ]);
  666.     }
  667.     /**
  668.      * @throws Throwable
  669.      */
  670.     #[Route(path'/compte-client/ma-cure/{cure_id}'name'front_customer_order_cure')]
  671.     public function orderCure(Request                     $requestEcoOrdersRepository $repoOrders,
  672.                               EcoShippingOrdersRepository $repoShippingOrders,
  673.                               LoyaltySystemService        $loyaltySystem,
  674.                               ApiService                  $api$cure_id 0): Response
  675.     {
  676.         $customers $this->currentUserConnected->getAuthUserId()->getCustomer();
  677.         if ($cure_id == 0) {
  678.             return $this->redirectToRoute('front_customer_orders');
  679.         }
  680.         // Récupération des commandes du client
  681.         $order $api->rechercherResaCure(idOdysseeResa: (int)$cure_id);
  682.         if (!$order) {
  683.             return $this->redirectToRoute('front_customer_orders');
  684.         }
  685.         $medecinsPresc = [];
  686.         // Récupération du médecin prescripteur
  687.         if ($api->rechercherMedPrParCode($order[0]->{'Medecin_Prescripteur'})) {
  688.             $medecinsPresc $api->rechercherMedPrParCode($order[0]->{'Medecin_Prescripteur'});
  689.         }
  690.         $curiste $api->rechParIdOdyssee($order[0]->{'IdOdysseeClient'});
  691.         // Si il y a plusieurs curistes, on récupère le premier
  692.         if (is_array($curiste)) {
  693.             $curiste $curiste[0];
  694.         }
  695.         return $this->render('@main-app/front/front_customer_account/order_cure.html.twig', [
  696.             'order' => $order[0],
  697.             'curiste' => $curiste,
  698.             'indicationsPrincipales' => $api->listerItp(),
  699.             'indicationsSecondaires' => $api->listerIts(),
  700.             'medecinsTherm' => $api->listerMedTh(),
  701.             'medecinsPresc' => $medecinsPresc,
  702.             'plagesHoraires' => $api->listerPlageHoraire(),
  703.             'etablissements' => $api->listerEtabResaCure(),
  704.             'pointsDeVente' => $api->listerPvResaCure(),
  705.             'pageAccount' => 'ma-cure'
  706.         ]);
  707.     }
  708.     #[Route(path'/compte-client/ma-commande/{order_id}'name'front_customer_order_detail'defaults: ['order_id' => ''])]
  709.     public function order_detail(Request                         $requestEcoOrdersRepository $repoOrders,
  710.                                  EcoShippingOrdersRepository     $repoShippingOrders,
  711.                                  EcoProductsReferencesRepository $repoRef$order_id,
  712.                                  EcoInvoicesRepository           $repoInvoices): Response
  713.     {
  714.         //Vérification que l'utilisateur est bien connecté
  715.         if (!$this->currentUserConnected || $this->currentUserConnected == null) {
  716.             return $this->redirectToRoute('front_customer_registration');
  717.         }
  718.         $order $repoOrders->find($order_id);
  719.         //Vérification que la commande est bien la sienne 
  720.         if ($order == null || $order->getCustomerId() != $this->currentUserConnected->getId()) {
  721.             return $this->redirectToRoute('front_customer_orders');
  722.         }
  723.         return $this->render('@main-app/front/front_customer_account/order_detail.html.twig', [
  724.             'order' => $order,
  725.             'shipment' => $repoShippingOrders->findByShipmentOrders($this->currentUserConnected->getId()),
  726.             'references' => $repoRef->findByProductReferencesOrder($order_id$isCanceled 0),
  727.             'referencesCanceled' => $repoRef->findByProductReferencesOrder($order_id$isCanceled 1),
  728.             'invoices' => $repoInvoices->findByInvoices($this->currentUserConnected->getId(), 'invoice',
  729.                 $order_id),
  730.             'credit_note' => $repoInvoices->findByInvoices($this->currentUserConnected->getId(), 'credit_note',
  731.                 $order_id),
  732.             'pageAccount' => 'commande'
  733.         ]);
  734.     }
  735.     #[Route(path'/compte-client/telecharger/{invoice_id}'name'front_customer_invoices_download'defaults: ['invoice_id' => 0])]
  736.     public function download(Request             $requestEcoInvoicesRepository $repoInvoices,
  737.                              EcoOrdersRepository $repoOrdersKernelInterface $appKernel$invoice_id 0)
  738.     {
  739.         if (!$this->currentUserConnected || $this->currentUserConnected == null) {
  740.             return $this->redirectToRoute('front_customer_registration');
  741.         }
  742.         //Vérification que la facture est bien la sienne 
  743.         $invoice $repoInvoices->find($invoice_id);
  744.         if ($invoice !== null) {
  745.             $order $repoOrders->find($invoice->getOrderId());
  746.             if ($order->getCustomerId() != $this->currentUserConnected->getId()) {
  747.                 return $this->redirectToRoute('front_customer_invoices');
  748.             }
  749.         } else {
  750.             return $this->redirectToRoute('front_customer_invoices');
  751.         }
  752.         //Téléchargement du fichier
  753.         $fileName $invoice->getInvoiceFilename() != null $invoice->getInvoiceFilename() : 'walouuu.pdf';
  754.         $file $appKernel->getProjectDir() . '/public/medias_front/orders/' $fileName;
  755.         if (file_exists($file)) {
  756.             return new BinaryFileResponse($file);
  757.         } else {
  758.             return $this->redirectToRoute('front_customer_invoices');
  759.         }
  760.     }
  761.     #[Route(path'/compte-client/mes-messages'name'front_customer_tchat')]
  762.     public function tchat(Request         $requestEcoCustomersRepository $repoCustomers,
  763.                           TchatRepository $repoTchat): Response
  764.     {
  765.         if (!$this->currentUserConnected || $this->currentUserConnected == null) {
  766.             return $this->redirectToRoute('front_customer_registration');
  767.         }
  768.         return $this->render('@main-app/front/front_customer_account/tchat.html.twig', [
  769.             'pageAccount' => 'messages',
  770.             'discussions' => $repoTchat->findByCustomerDiscussion($this->currentUserConnected->getId()),
  771.             'unreadMessages' => $repoTchat->controlIfDiscussionUnread($this->currentUserConnected->getId()),
  772.         ]);
  773.     }
  774.     #[Route(path'/compte-client/nouveau-ticket'name'front_tchat_ticket')]
  775.     public function tchat_ticket(Request         $requestEcoCustomersRepository $repoCustomers,
  776.                                  TchatRepository $repoTchatEcoOrdersRepository $repoOrders): Response
  777.     {
  778.         if (!$this->currentUserConnected || $this->currentUserConnected == null) {
  779.             return $this->redirectToRoute('front_customer_registration');
  780.         }
  781.         return $this->render('@main-app/front/front_customer_account/tchat_ticket.html.twig', [
  782.             'pageAccount' => 'messages',
  783.             'customer_id' => $this->currentUserConnected->getId(),
  784.             'orders' => $repoOrders->findBy(['order_status' => array('valid''partial-shipment''shipment'),
  785.                 'customer_id' => $this->currentUserConnected->getId()],
  786.                 ['order_date' => 'DESC'])
  787.         ]);
  788.     }
  789.     /**
  790.      * @param Request $request
  791.      */
  792.     #[Route(path'/compte-client/axDisplayProductOrder'name'front_tchat_axDisplayProductOrder'options: ['expose' => true])]
  793.     public function axDisplayProductOrder(Request $requestEcoProductsReferencesRepository $repoProdRef)
  794.     {
  795.         if ($request->isXmlHttpRequest()) {
  796.             $renderList $this->renderView('admin/admin_tchat/tpl_display_products.html.twig', [
  797.                 'references' => $repoProdRef->findByProductReferencesByOrder($request->get('order_id')),
  798.             ]);
  799.             $script '';
  800.             $script .= " $('#products-list').html('" str_replace(array("\n""\r"), '',
  801.                     html_entity_decode(addslashes($renderList),
  802.                         ENT_QUOTES)) . "'); ";
  803.             return new JsonResponse([
  804.                 'status' => true,
  805.                 'script' => $script,
  806.             ]);
  807.         }
  808.         return new JsonResponse([
  809.             'status' => false,
  810.         ]);
  811.     }
  812.     #[Route(path'/compte-client/open-ticket'name'front_tchat_open_conversation')]
  813.     public function openTicket(Request $request)
  814.     {
  815.         if ($request->get('customer_id') > 0) {
  816.             //Ouverture d'une conversation
  817.             $tchat = new Tchat();
  818.             $tchat->setUserId(0);
  819.             $tchat->setCustomerId($request->get('customer_id'));
  820.             $tchat->setTchatObject($request->get('tchat_object'));
  821.             $tchat->setTchatDatetime(new \DateTime());
  822.             $tchat->setTchatStatus('open');
  823.             $this->entityManager->persist($tchat);
  824.             $this->entityManager->flush();
  825.             //Ajout du message
  826.             $mess = new TchatMessages;
  827.             $mess->setTchatId($tchat->getId());
  828.             $mess->setUserId(0);
  829.             $mess->setMessDatetime(new \DateTime());
  830.             $mess->setMessage($request->get('message'));
  831.             $mess->setMessRead(false);
  832.             //Ajout d'une pièce jointe
  833.             if ($request->files->get("mess_file")) {
  834.                 $fileName $this->fileService->startUpload([
  835.                     "fileData" => $request->files->get("mess_file"),
  836.                     "oldFileName" => NULL,
  837.                     "fileDestination" => $this->getParameter("upload_tchat_" CURRENT_SITE_ID),
  838.                     "autorizedExtensions" => $this->autorizedFiles,
  839.                     "createWebp" => false
  840.                 ]);
  841.                 $mess->setMessFile($fileName);
  842.             }
  843.             $this->entityManager->persist($mess);
  844.             $this->entityManager->flush();
  845.             //Liaison produits
  846.             if ($request->get('references')) {
  847.                 foreach ($request->get('references') as $op_id) {
  848.                     $prodLink = new TchatProducts();
  849.                     $prodLink->setTchatId($tchat->getId());
  850.                     $prodLink->setOrderpId($op_id);
  851.                     $this->entityManager->persist($prodLink);
  852.                 }
  853.                 $this->entityManager->flush();
  854.             }
  855.             $this->session->set('displayPopup''open-ticket');
  856.             return $this->redirectToRoute('front_tchat_discussion', ['tchat_id' => $tchat->getId()]);
  857.         }
  858.         return $this->redirectToRoute('front_tchat_ticket');
  859.     }
  860.     #[Route(path'/compte-client/discussion/{tchat_id}'name'front_tchat_discussion'defaults: ['tchat_id' => ''])]
  861.     public function discussion(Request                 $requestTchatRepository $repoTchat,
  862.                                TchatMessagesRepository $repoTchatMessEcoCustomersRepository $repoCustomer,
  863.                                AuthUserRepository      $repoUsersTchatProductsRepository $repoTchatProds,
  864.                                                        $tchat_id): Response
  865.     {
  866.         //Affichage popup
  867.         $this->displayPopup();
  868.         if ($tchat_id 0) {
  869.             $tchat $repoTchat->find($tchat_id);
  870.             //Access control
  871.             if ($this->currentUserConnected == null || $this->currentUserConnected == false || $tchat->getCustomerId() != $this->currentUserConnected->getId()) {
  872.                 return $this->redirectToRoute('front_customer_registration');
  873.             }
  874.         } else {
  875.             return $this->redirectToRoute('front_customer_registration');
  876.         }
  877.         //Marquer les messages non lus
  878.         $messages $repoTchatMess->getAdminMessages();
  879.         if (is_array($messages)) {
  880.             foreach ($messages as $mess) {
  881.                 if ($mess->getTchatId() == $tchat_id) {
  882.                     $mess->setMessRead(true);
  883.                     $this->entityManager->persist($mess);
  884.                     $this->entityManager->flush();
  885.                 }
  886.             }
  887.         }
  888.         return $this->render('@main-app/front/front_customer_account/tchat_discussion.html.twig', [
  889.             'pageAccount' => 'messages',
  890.             'discussion' => $discussion $repoTchat->find($tchat_id),
  891.             'customer' => $repoCustomer->find($discussion->getCustomerId()),
  892.             'messages' => $repoTchatMess->findBy(['tchat_id' => $tchat_id], ['mess_datetime' => 'DESC']),
  893.             'users' => $repoUsers->findAll(),
  894.             'products' => $repoTchatProds->findByTchatProducts($tchat_id),
  895.             "autorizedExtensions" => $this->autorizedFiles,
  896.         ]);
  897.     }
  898.     #[Route(path'/compte-client/repondre'name'front_tchat_response')]
  899.     public function response(Request $request): Response
  900.     {
  901.         if ($request->isMethod('POST')) {
  902.             //Ajout du message
  903.             $mess = new TchatMessages;
  904.             $mess->setTchatId($request->get('tchat_id'));
  905.             $mess->setUserId(0);
  906.             $mess->setMessDatetime(new \DateTime());
  907.             $mess->setMessage($request->get('message'));
  908.             $mess->setMessFile(NULL);
  909.             $mess->setMessRead(false);
  910.             //Ajout d'une pièce jointe
  911.             if ($request->files->get("mess_file")) {
  912.                 $fileName $this->fileService->startUpload(
  913.                     [
  914.                         "fileData" => $request->files->get("mess_file"),
  915.                         "oldFileName" => NULL,
  916.                         "fileDestination" => $this->getParameter("upload_tchat_" CURRENT_SITE_ID),
  917.                         "autorizedExtensions" => $this->autorizedFiles,
  918.                         "createWebp" => false
  919.                     ]
  920.                 );
  921.                 $mess->setMessFile($fileName);
  922.             }
  923.             $this->entityManager->persist($mess);
  924.             $this->entityManager->flush();
  925.             $this->session->set('displayPopup''send-message');
  926.             //Envoyer un mail de notification à l'administrateur
  927.             $this->newAdminMessageNotification($request->get('tchat_id'), $request->get('message'));
  928.             return $this->redirectToRoute('front_tchat_discussion', ['tchat_id' => $request->get('tchat_id')]);
  929.         }
  930.         return $this->redirectToRoute('front_tchat');
  931.     }
  932.     /**
  933.      * Notification à l'administrateur d'un nouveau message
  934.      * @param int $tchat_id
  935.      */
  936.     private function newAdminMessageNotification($tchat_id$message)
  937.     {
  938.         $tchat $this->entityManager->getRepository(Tchat::class)->find($tchat_id);
  939.         $customer $this->entityManager->getRepository(EcoCustomers::class)->find($tchat->getCustomerId());
  940.         $this->mailerService->fromEmail $customer->getAuthUserId()->getEmail();
  941.         $this->mailerService->fromName $customer->getCustLastName() . ' ' $customer->getCustFirstName();
  942.         $this->mailerService->subject SITE_NAME " - Nouveau message dans votre outil de messagerie";
  943.         $allRecipients = array();
  944.         //        $allRecipients[] = [
  945.         //            "nom" => SITE_NAME,
  946.         //            "prenom" => '',
  947.         //            "email" => 'stephen@otidea.com',
  948.         //            "type" => 'to'
  949.         //        ];
  950.         $htmlContent $this->renderView('layouts/layouts_emails/notification_tchat_admin.html.twig', [
  951.             'tchat' => $tchat,
  952.             'customer' => $customer,
  953.             'message' => $message,
  954.         ]);
  955.         $this->mailerService->sendMail($allRecipients$htmlContentNULL'admin-notification');
  956.     }
  957.     #[Route(path'/compte-client/download_attachment/{tchat_id}/{mess_id}'name'front_tchat_download_attachment'defaults: ['tchat_id' => '',
  958.         'mess_id' => ''])]
  959.     public function download_attachment(Request                 $requestTchatRepository $repoTchat,
  960.                                         TchatMessagesRepository $repoMessKernelInterface $appKernel$tchat_id,
  961.                                                                 $mess_id): Response
  962.     {
  963.         //Access control
  964.         $tchat $repoTchat->find($tchat_id);
  965.         if ($tchat->getCustomerId() != $this->currentUserConnected->getId()) {
  966.             return $this->redirectToRoute('front_customer_registration');
  967.         }
  968.         $message $repoMess->find($mess_id);
  969.         //Téléchargement du fichier
  970.         $fileName $message->getMessFile() != null $message->getMessFile() : 'nada.pdf';
  971.         $file $appKernel->getProjectDir() . '/public/medias_front/tchat/' $fileName;
  972.         if (file_exists($file)) {
  973.             return new BinaryFileResponse($file);
  974.         } else {
  975.             return $this->redirectToRoute('front_tchat_discussion', ['tchat_id' => $tchat_id]);
  976.         }
  977.     }
  978.     private function displayPopup()
  979.     {
  980.         if ($this->session->has('displayPopup')) {
  981.             //Erreur de connexion
  982.             if ($this->session->get('displayPopup') == 'connection-error') {
  983.                 $this->otideaUtils->createPopup(["title" => 'Attention',
  984.                         "message" => 'Votre identifiant ou votre mot de passe est incorrect',
  985.                         "btn2" => null]
  986.                 );
  987.             }
  988.             //L'adresse mail existe déjà
  989.             if ($this->session->get('displayPopup') == 'email-exist') {
  990.                 $this->otideaUtils->createPopup(["title" => 'Attention',
  991.                         "message" => "L'adresse e-mail que vous voulez utiliser existe déjà. Veuillez utiliser 'Mot de passe oublié' pour récupérer votre mot de passe si vous l'avez perdu",
  992.                         "btn2" => null]
  993.                 );
  994.             }
  995.             //L'adresse mail n'est pas au bon format
  996.             if ($this->session->get('displayPopup') == 'email-not-good') {
  997.                 $this->otideaUtils->createPopup(["title" => 'Attention',
  998.                         "message" => "L'adresse e-mail que vous voulez utiliser ne semble pas conforme, merci de vérifier votre saisie ou d'utiliser une autre adresse.",
  999.                         "btn2" => null]
  1000.                 );
  1001.             }
  1002.             //Envoi d'un message
  1003.             if ($this->session->get('displayPopup') == 'send-message') {
  1004.                 $this->otideaUtils->createPopup(["title" => 'Information',
  1005.                         "message" => 'Message envoyé avec succès',
  1006.                         "btn2" => null]
  1007.                 );
  1008.             }
  1009.             //Ouverture d'un nouveau ticket
  1010.             if ($this->session->get('displayPopup') == 'open-ticket') {
  1011.                 $this->otideaUtils->createPopup(["title" => 'Information',
  1012.                         "message" => 'Ticket ouvert avec succès',
  1013.                         "btn2" => null]
  1014.                 );
  1015.             }
  1016.             $this->session->set('displayPopup'NULL);
  1017.         }
  1018.     }
  1019.     /**
  1020.      * Validates a single email address (or an array of email addresses)
  1021.      *
  1022.      * @param array|string $emails
  1023.      *
  1024.      * @return bool
  1025.      */
  1026.     public function validateEmails($emails): bool
  1027.     {
  1028.         $emails filter_var($emailsFILTER_SANITIZE_EMAIL);
  1029.         if (filter_var($emailsFILTER_VALIDATE_EMAIL)) {
  1030.             return true;
  1031.         } else {
  1032.             return false;
  1033.         }
  1034.     }
  1035.     #[Route(path'/compte-client/planning'name'front_customer_planning')]
  1036.     public function planning(Request $requestEcoPlanningRepository $planningRepository): Response
  1037.     {
  1038.         if ($this->currentUserConnected->getCustAccountType() == 'company') {
  1039.             $plannings $planningRepository->findBy(['societyId' => $this->currentUserConnected->getId()],
  1040.                 ['deliveryStartDate' => 'ASC']);
  1041.         } else if ($this->currentUserConnected->getCustAccountType() == 'employee') {
  1042.             $plannings $planningRepository->findBy(['societyId' => $this->currentUserConnected->getCompany()->getId()],
  1043.                 ['deliveryStartDate' => 'ASC']);
  1044.         }
  1045.         return $this->render('@main-app/front/front_customer_account/planning.html.twig', [
  1046.             'pageAccount' => 'planning',
  1047.             'plannings' => $plannings,
  1048.         ]);
  1049.     }
  1050.     #[Route(path'/compte-client/salaries'name'front_customer_employee')]
  1051.     public function employee(Request $requestEcoCustomersRepository $customersRepository): Response
  1052.     {
  1053.         $employees $customersRepository->findBy(['cust_society' => $this->currentUserConnected->getCustSociety()]);
  1054.         return $this->render('@main-app/front/front_customer_account/employee.html.twig', [
  1055.             'pageAccount' => 'employee',
  1056.             'employees' => $employees,
  1057.             'currentUser' => $this->currentUserConnected
  1058.         ]);
  1059.     }
  1060.     #[Route(path'/inscription-salarie/{companyId}/{campanyCode}'name'front_customer_registration_employee'defaults: ['companyId' => '',
  1061.         'campanyCode' => ''])]
  1062.     public function inscriptionEmployee($companyId$campanyCodeRequest $request,
  1063.                                         UserPasswordHasherInterface $passwordHasher,
  1064.                                         EcoShippingfeesCountryRepository $repoCountry,
  1065.                                         EcoCustomersRepository $customersRepository): Response
  1066.     {
  1067.         if ($this->getUser()) {
  1068.             return $this->redirectToRoute('front_customer_account');
  1069.         }
  1070.         $company $customersRepository->findOneBy(['id' => $companyId'custSocietyCode' => $campanyCode]);
  1071.         if ($company == null) {
  1072.             return $this->redirectToRoute('front_home');
  1073.         }
  1074.         $authUser = new AuthUser();
  1075.         $customer = new EcoCustomers();
  1076.         $form $this->createForm(CustomerFrontType::class, $customer, [
  1077.             'authUser' => $customer->getAuthUserId(),
  1078.             'countryList' => $repoCountry->findBygCountriesOrderByFrance(),
  1079.             'userType' => 'employee',
  1080.             'newsletter' => true,
  1081.             'formType' => "newAccount",
  1082.         ]);
  1083.         $form->handleRequest($request);
  1084.         if ($form->isSubmitted() && $form->isValid()) {
  1085.             $existUser $this->entityManager->getRepository(AuthUser::class)->findBy(['email' => $form->get('email')->getData()]);
  1086.             if ($existUser != null) {
  1087.                 $this->addFlash('danger'"Une erreur s'est produite lors de l'enregistrement");
  1088.                 return $this->redirectToRoute('front_customer_registration_employee',
  1089.                     ['companyId' => $companyId'campanyCode' => $campanyCode]);
  1090.             }
  1091.             $customer->setCustCreationDate(new \DateTime());
  1092.             $customer->setCustReference(uniqid());
  1093.             //Enregistrement du mot de passe
  1094.             if ($form->has('password') && $form->get('password')->getData() != "" && $form->get('password')->getData() != null) {
  1095.                 $user $this->setEmployeeAccount($authUser->getId(), $passwordHasher$form);
  1096.                 $customer->setAuthUserId($user);
  1097.                 // Le mot de passe n'a pas été modifié
  1098.             }
  1099.             // Compte salarié
  1100.             $customer->setCustAccountType('employee');
  1101.             // Compte confirmé
  1102.             $customer->setcustAccountStatus('confirmed');
  1103.             // FRANCE par défaut
  1104.             $customer->setCustCountryId(1);
  1105.             // reference client par défaut
  1106.             $customer->setCustReference("CLI");
  1107.             // liaison avec l'entreprise
  1108.             $customer->setCompany($company);
  1109.             $customer->setCustSociety($company->getCustSociety());
  1110.             try {
  1111.                 $this->entityManager->persist($customer);
  1112.                 $this->entityManager->flush();
  1113.                 $this->addFlash('success'"enregistré avec succès");
  1114.             } catch (Exception $ex) {
  1115.                 $this->addFlash('danger'"Cet utilisateur existe déjà");
  1116.             }
  1117.             try {
  1118.                 $ref $customer->getId() + 1000;
  1119.                 $customer->setCustReference("CLI" $ref);
  1120.                 $this->entityManager->persist($customer);
  1121.                 $this->entityManager->flush();
  1122.             } catch (Exception $ex) {
  1123.                 $this->addFlash('danger'"Une erreur s'est produite lors de la modification de la référence client");
  1124.             }
  1125.             return $this->redirectToRoute('front_customer_account', array('id' => $customer->getId()));
  1126.         }
  1127.         return $this->render('@main-app/security_front/registration_employee.html.twig', [
  1128.             'form' => $form->createView(),
  1129.             'company' => $company,
  1130.         ]);
  1131.     }
  1132.     /*
  1133.      * Permet d'ajouter un nouveau compte client
  1134.      * avec le role de client
  1135.      * @return bool
  1136.      */
  1137.     private function setEmployeeAccount($authUserId 0$passwordHasher null$form null$repoAuthUser null)
  1138.     {
  1139.         if ($form->get('email')->getData() !== null && $form->get('password')->getData() !== null) {
  1140.             if ($authUserId 0) {
  1141.                 $user $repoAuthUser->find($authUserId);
  1142.             } else {
  1143.                 $user = new AuthUser();
  1144.             }
  1145.             $user->setEmail($form->get('email')->getData());
  1146.             // modification du mot de passe
  1147.             if ($form->get('password')->getData() !== null && trim($form->get('password')->getData()) != "") {
  1148.                 // hash the password (based on the security.yaml config for the $user class)
  1149.                 $hashedPassword $passwordHasher->hashPassword(
  1150.                     $user,
  1151.                     $form->get('password')->getData()
  1152.                 );
  1153.                 $user->setPassword($hashedPassword);
  1154.             }
  1155.             if ($user->getId() == 0) {
  1156.                 $user->setRoles(array_merge($user->getRoles(), ['ROLE_CUSTOMER']));
  1157.                 $user->setCreationDatetime(new \DateTime());
  1158.             }
  1159.             $this->entityManager->persist($user);
  1160.             $this->entityManager->flush();
  1161.             return $user;
  1162.         }
  1163.         return false;
  1164.     }
  1165. }