<?php
namespace Acme\SudcmsBundle\Controller\Front;
use Acme\SudcmsBundle\Entity\AuthUser;
use Acme\SudcmsBundle\Entity\EcoCustomers;
use Acme\SudcmsBundle\Entity\EcoCustomersAddresses;
use Acme\SudcmsBundle\Entity\Newsletter;
use Acme\SudcmsBundle\Entity\Tchat;
use Acme\SudcmsBundle\Entity\TchatMessages;
use Acme\SudcmsBundle\Entity\TchatProducts;
use Acme\SudcmsBundle\Form\Ecommerce\CustomerFrontType;
use Acme\SudcmsBundle\Form\Ecommerce\CustomerResetPasswordType;
use Acme\SudcmsBundle\Repository\AuthUserRepository;
use Acme\SudcmsBundle\Repository\EcoCustomersAddressesRepository;
use Acme\SudcmsBundle\Repository\EcoCustomersRepository;
use Acme\SudcmsBundle\Repository\EcoInvoicesRepository;
use Acme\SudcmsBundle\Repository\EcoOrdersRepository;
use Acme\SudcmsBundle\Repository\EcoPlanningRepository;
use Acme\SudcmsBundle\Repository\EcoProductsReferencesRepository;
use Acme\SudcmsBundle\Repository\EcoShippingfeesCountryRepository;
use Acme\SudcmsBundle\Repository\EcoShippingOrdersRepository;
use Acme\SudcmsBundle\Repository\SiteRepository;
use Acme\SudcmsBundle\Repository\TchatMessagesRepository;
use Acme\SudcmsBundle\Repository\TchatProductsRepository;
use Acme\SudcmsBundle\Repository\TchatRepository;
use Acme\SudcmsBundle\Service\ApiService;
use Acme\SudcmsBundle\Service\Ecommerce\LoyaltySystemService;
use Acme\SudcmsBundle\Service\FileService;
use Acme\SudcmsBundle\Service\MailerService;
use Acme\SudcmsBundle\Service\OtideaUtils;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Throwable;
use const SITE_NAME;
class FrontCustomerAccountController extends AbstractController
{
private $session;
private $otideaUtils;
private $mailerService;
private $autorizedFiles = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];
private $fileService;
private $isEcommerce;
private $currentUserConnected;
private ApiService $apiService;
public function __construct(RequestStack $requestStack, EntityManagerInterface $entityManager,
OtideaUtils $otideaUtils, MailerService $mailerService, FileService $fileService,
SiteRepository $siteRepository, ApiService $apiService)
{
$this->session = $requestStack->getCurrentRequest()->getSession();
$this->apiService = $apiService;
$this->entityManager = $entityManager;
$this->otideaUtils = $otideaUtils;
$this->mailerService = $mailerService;
$this->fileService = $fileService;
$this->isEcommerce = $siteRepository->find($this->session->get('admin_site_uid'))->getIsEcommerce();
$this->currentUserConnected = $otideaUtils->getUserConnected();
if (!IS_ECOMMERCE) {
header('Location: ' . WEBSITEROOT);
exit;
}
if (!$this->apiService->testConnexion()) {
$this->addFlash('danger', 'Une erreur est survenue, veuillez réessayer ultérieurement.');
return $this->redirectToRoute('front_home');
}
}
/**
* Envoi un mail avec un nouveau mot de passe
* @param int $authUser_id
*/
private function sendNotificationNewPassword($authUser_id)
{
$this->mailerService->fromName = SITE_NAME;
$this->mailerService->subject = SITE_NAME . " - Mot de passe oublié";
$authUser = $this->entityManager->getRepository(AuthUser::class)->find($authUser_id);
//Enregistrement du nouveau mot de passe
$newPassword = uniqid();
$password_hash = password_hash($newPassword, PASSWORD_DEFAULT);
$authUser->setPassword($password_hash);
$this->entityManager->persist($authUser);
$this->entityManager->flush();
$customer = $this->entityManager->getRepository(EcoCustomers::class)->findOneBy(['authUserId' => $authUser_id]);
$allRecipients[] = [
"nom" => $customer->getCustLastname(),
"prenom" => $customer->getCustFirstname(),
"email" => $customer->getAuthUserId()->getEmail(),
"type" => 'to'
];
$htmlContent = $this->renderView('layouts/layouts_emails/notification_new_password.html.twig', [
'password' => $newPassword,
]);
$this->mailerService->sendMail($allRecipients, $htmlContent);
}
#[Route(path: '/inscription', name: 'front_customer_registration')]
public function inscription(Request $request,
AuthUserRepository $repoAuthUser,
EcoCustomersRepository $ecoCustomersRepository,
UserPasswordHasherInterface $passwordHasher,
ApiService $api): Response
{
//Verification Recaptcha
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '6LfFKr0qAAAAAO8QfV8HQcPKViozt2RGLY7A2ORL';
$recaptcha_response = $_POST['g-recaptcha-response'];
// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
if ($recaptcha->score >= 0.5) {
// Récupération du formulaire d'inscription
$newCustomer = $request->request->get('customer_front');
// Vérification si l'utilisateur existe déjà en BDD
if ($repoAuthUser->findOneBy(['email' => $newCustomer['AdrCourriel']])) {
$this->addFlash('danger', 'Cet utilisateur existe déjà');
return $this->redirectToRoute('front_app_login');
}
// Création du ECO_CUSTOMER et du AUTH_USER en BDD
$addCustomer = new EcoCustomers();
$addAuthUser = new AuthUser();
$addCustomer->setCustCreationDate(new \DateTime());
$addCustomer->setAuthUserId($addAuthUser);
$addCustomer->setOdysseeReference(0);
$addAuthUser->setCreationDatetime(new \DateTime());
$addAuthUser->setRoles(["ROLE_USER", "ROLE_CUSTOMER"]);
$addAuthUser->setEmail($newCustomer['AdrCourriel']);
if ($newCustomer['password']['first'] != null) {
$hashedPassword = $passwordHasher->hashPassword(
$addAuthUser,
$newCustomer['password']['first']
);
$addAuthUser->setPassword($hashedPassword);
} else {
$this->addFlash('danger', 'Un mot de passe conforme est requis');
return $this->redirectToRoute('front_app_login');
}
if (!filter_var($newCustomer['AdrCourriel'], FILTER_VALIDATE_EMAIL) && strlen($newCustomer['AdrCourriel']) < 6) {
$this->addFlash('danger', 'Veuillez entrer une adresse email valide.');
return $this->redirectToRoute('front_app_login');
}
$this->entityManager->persist($addCustomer);
$this->entityManager->persist($addAuthUser);
$this->entityManager->flush();
$result = $this->editCustomer($newCustomer, $addCustomer, $addAuthUser, $api);
if ($result == 'ok') {
$this->addFlash('success', 'Votre compte a bien été créé');
$this->authenticateUser($addAuthUser);
if ($request->getSession()->get('_security.main.target_path')) {
return $this->redirect($request->getSession()->get('_security.main.target_path'));
}
} else {
$this->addFlash('danger', $result);
}
} else {
$this->addFlash('danger', 'Vous êtes un robots');
return $this->redirectToRoute('front_app_login');
}
return $this->redirectToRoute('front_app_login');
}
//Fonction de connexion automatique après inscription
private function authenticateUser(AuthUser $user)
{
$providerKey = 'main'; // your firewall name
$token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
$this->container->get('security.token_storage')->setToken($token);
}
//Fonction d'édition des utilisateurs
private function editCustomer($newCustomer, $addCustomer, $addAuthUser, $api): string
{
if (is_object($newCustomer)) {
$newCustomer = (array)$newCustomer;
}
// On définie les valeurs par défaut si elles ne sont pas définies
$newCustomer['IdOdysseeClient'] = $newCustomer['IdOdysseeClient'] ?? 0;
$newCustomer['IdExterneClient'] = $newCustomer['IdExterneClient'] ?? 0;
// On recherche dans ODYSSEE si un client existe déjà avec cet email
$searchCustomer = $api->rechercherClient(idOdyssee: $newCustomer['IdOdysseeClient'],
adrCourriel: $newCustomer['AdrCourriel']);
// On transforme la date d'anniversaire
$birthday = new \DateTime($newCustomer->{'DateNaissance'} ?? $newCustomer['DateNaissance']);
// On modifie l'ID ODYSSEE si l'utilisateur existe déjà
$idOdyssee = (!isset($searchCustomer->{'status'}) && !empty($searchCustomer)) ? $searchCustomer[0]->{'IdOdysseeClient'} : $newCustomer['IdOdysseeClient'];
$addInOdyssee = null;
if (!isset($searchCustomer->{'status'}) && !empty($searchCustomer)) {
foreach ($searchCustomer as $customer) {
if ($newCustomer['Nom'] == $customer->{'Nom'} && $newCustomer['Prenom'] == $customer->{'Prenom'}) {
$addInOdyssee = $api->editFicheOdyssee(
$idOdyssee,
"" . $addCustomer->getId(),
$newCustomer['Civilite'],
$newCustomer['Nom'],
$newCustomer['Prenom'],
$birthday->format('Y-m-d\T00:00:00'),
$newCustomer['Sexe'],
$newCustomer['Adresse1'],
$newCustomer['Adresse2'],
$newCustomer['Adresse3'],
$newCustomer['CodePostal'],
$newCustomer['Ville'],
$newCustomer['Pays'],
$newCustomer['TelFixe'],
$newCustomer['TelMobile'],
$newCustomer['AdrCourriel'],
isset($newCustomer['RefusComCom']) ? (int)$newCustomer['RefusComCom'] : 0,
"update"
);
break;
}
}
} else {
$addInOdyssee = $api->editFicheOdyssee(
$idOdyssee,
"" . $addCustomer->getId(),
$newCustomer['Civilite'],
$newCustomer['Nom'],
$newCustomer['Prenom'],
$birthday->format('Y-m-d\T00:00:00'),
$newCustomer['Sexe'],
$newCustomer['Adresse1'],
$newCustomer['Adresse2'],
$newCustomer['Adresse3'],
$newCustomer['CodePostal'],
$newCustomer['Ville'],
$newCustomer['Pays'],
$newCustomer['TelFixe'],
$newCustomer['TelMobile'],
$newCustomer['AdrCourriel'],
isset($newCustomer['RefusComCom']) ? (int)$newCustomer['RefusComCom'] : 0
);
}
// On met a jour en BDD
$addCustomer->setOdysseeReference((!isset($searchCustomer->{'status'}) && !empty($searchCustomer) && $searchCustomer != 0) ? $searchCustomer[0]->{'IdOdysseeClient'} : (int)$addInOdyssee[0]->{'IdOdysseeClient'});
$this->entityManager->persist($addCustomer);
$this->entityManager->flush();
// Si on trouve plusieurs compte associés à l'email, on les créer
if (!isset($searchCustomer->{'status'}) && !empty($searchCustomer)) {
foreach ($searchCustomer as $cust) {
if (!$this->entityManager->getRepository(EcoCustomers::class)->findOneBy(['odyssee_reference' => $cust->{'IdOdysseeClient'}])) {
$addOtherCustomer = new EcoCustomers();
$addOtherCustomer->setAuthUserId($addAuthUser);
$addOtherCustomer->setOdysseeReference($cust->{'IdOdysseeClient'});
$addOtherCustomer->setCustCreationDate(new \DateTime());
$this->entityManager->persist($addOtherCustomer);
$this->entityManager->flush();
}
}
}
return 'ok';
}
/*
* Permet la création et la modification d'un compte client
* ainsi que la création de l'utilisateur
* @param $params array
* @return null
*/
private function setCustomerAccount($params = [])
{
$form = isset($params['form']) ? $params['form'] : null;
$customer = isset($params['customer']) ? $params['customer'] : null;
$repoAuthUser = isset($params['repoAuthUser']) ? $params['repoAuthUser'] : null;
$repoNews = isset($params['repoNews']) ? $params['repoNews'] : null;
$passwordHasher = isset($params['passwordHasher']) ? $params['passwordHasher'] : null;
$repoEcoCustomerAddresses = isset($params['repoAddress']) ? $params['repoAddress'] : null;
if ($repoAuthUser !== null && $repoNews !== null && $passwordHasher !== null) {
// vérification de la validité de l'adresse email
if (!$this->validateEmails($form->get('email')->getData())) {
$this->session->set('displayPopup', 'email-not-good');
return $this->redirectToRoute('front_customer_registration');
}
// vérification que le compte client n'existe pas déjà
$emailSearch = $repoAuthUser->findOneBy(['email' => $form->get('email')->getData()]);
if ($emailSearch !== null && $customer->getId() == 0) {
$this->session->set('displayPopup', 'email-exist');
return $this->redirectToRoute('front_customer_registration');
}
$newCustomer = $customer->getAuthUserId() == null;
$user = $this->setUserAccount(!$newCustomer ? $customer->getAuthUserId()->getId() : null, $passwordHasher,
$form, $repoAuthUser);
// @TODO connexion de l'utilisateur après sa création de compte
// $userAuthenticator->authenticateUser($user);
if ($customer->getId() == 0) {
// liaison entre le compte utilisateur et le client
$customer->setAuthUserId($user);
$customer->setCustCreationDate(new \DateTime());
// reference par defaut qui sera maj après l'enregistrement
$customer->setCustReference("CLI");
// pour la création d'un compte entreprise est confirmée par défaut
$customer->setcustAccountStatus('confirmed');
$customer->setCustAccountType('company');
// FRANCE par défaut
$customer->setCustCountryId(1);
}
// enregistrement du client
try {
$this->entityManager->persist($customer);
$this->entityManager->flush();
} catch (Exception $ex) {
$this->addFlash('danger', "Une erreur s'est produite lors de l'enregistrement du compte");
}
// nouveau client, definition du numéro client + maj
if ($newCustomer) {
$ref = $customer->getId() + 1000;
$customer->setCustReference("CLI" . $ref);
try {
$this->entityManager->persist($customer);
$this->entityManager->flush();
} catch (Exception $ex) {
$this->addFlash('danger', "Une erreur s'est produite lors de la définition du numéro client");
}
}
// enregistrement de l'adresse de livraison
if ($customer->getCustAccountType() == 'company') {
$address = null;
$addresses = $customer->getAddressesId();
if (sizeof($addresses->getValues()) > 0) {
foreach ($addresses as $add) {
$address = $add;
break;
}
}
$this->setDeliveryAddress($customer, $form, $address);
}
// connexion auto du client après la creation du compte
// $this->setCustomerConnection($customer->getId());
// inscription à la newsletter
$mailResult = $repoNews->findOneBy(['nlEmail' => $form->get('email')->getData()]);
if ($form->get('accept_newsletter')->getData() && $mailResult == NULL) {
$this->subscriptionNewsletter($form->get('email')->getData());
}
// envoi du mail de confirmation de création de compte
if ($newCustomer) {
$this->sendConfirmationNewAccount($form->get('email')->getData(), $form->getData());
}
$this->addFlash('success', "enregistré avec succès");
if ($this->session->has('returnToBasket')) {
$this->session->remove('returnToBasket');
return $this->redirectToRoute('front_basket_index');
}
return $this->redirectToRoute('front_customer_account');
}
}
/*
* Permet d'ajouter un nouveau compte client
* avec le role de client
* @return bool
*/
private function setUserAccount($authUserId = 0, $passwordHasher = null, $form = null, $repoAuthUser = null)
{
if ($form->get('email')->getData() !== null) {
if ($authUserId > 0) {
$user = $repoAuthUser->find($authUserId);
} else {
$user = new AuthUser();
}
$user->setEmail($form->get('email')->getData());
// modification du mot de passe
if ($form->has('password') && $form->get('password')->getData() !== null && trim($form->get('password')->getData()) != "") {
// hash the password (based on the security.yaml config for the $user class)
$hashedPassword = $passwordHasher->hashPassword(
$user,
$form->get('password')->getData()
);
$user->setPassword($hashedPassword);
}
if ($user->getId() == 0) {
$user->setRoles(array_merge($user->getRoles(), ['ROLE_CUSTOMER']));
$user->setCreationDatetime(new \DateTime());
}
$this->entityManager->persist($user);
$this->entityManager->flush();
return $user;
}
return false;
}
/*
* Permet d'ajouter une adresse de livraison pour un client
* @param $customerId int identifiant du client dans eco_customer
* @param $form array les données du formulaire de compte
* @return void
*/
private function setDeliveryAddress($customer = null, $form = null, $address = null)
{
if ($customer !== null && $form != null) {
if ($address !== null) {
$deliveryAddress = $address;
} else {
$deliveryAddress = new EcoCustomersAddresses();
}
$deliveryAddress->setCountryId(1); // PAR DEFAUT : FRANCE
$deliveryAddress->setCustomersId($customer);
$deliveryAddress->setAddressFirstname($form->get('cust_firstname')->getData());
$deliveryAddress->setAddressLastname($form->get('cust_lastname')->getData());
$deliveryAddress->setAddressCivility($form->get('cust_civility')->getData());
// address est null = nouveau compte
// address n'est pas null = compte existant maj des données
// nouveau compte : on verifie que le choix d'adresse identique entre facturation et livraison
if ($address !== null || ($form->has('same_billing_delivery') && !$form->get('same_billing_delivery')->getData())) {
$deliveryAddress->setAddressPostal($form->get('address')->getData()->getAddressPostal());
$deliveryAddress->setAddressAdditional($form->get('address')->getData()->getAddressAdditional());
$deliveryAddress->setAddressDoor($form->get('address')->getData()->getAddressDoor());
$deliveryAddress->setAddressBuilding($form->get('address')->getData()->getAddressBuilding());
$deliveryAddress->setAddressFloor($form->get('address')->getData()->getAddressFloor());
$deliveryAddress->setAddressPostalCode($form->get('address')->getData()->getAddressPostalCode());
$deliveryAddress->setAddressCity($form->get('address')->getData()->getAddressCity());
$deliveryAddress->setAddressSociety($form->get('address')->getData()->getAddressSociety());
} // adresse identique entre facturation et livraison
else {
$deliveryAddress->setAddressPostal($form->get('cust_address')->getData());
$deliveryAddress->setAddressAdditional($form->get('cust_additional_address')->getData());
$deliveryAddress->setAddressDoor($form->get('cust_door')->getData());
$deliveryAddress->setAddressBuilding($form->get('cust_building')->getData());
$deliveryAddress->setAddressFloor($form->get('cust_floor')->getData());
$deliveryAddress->setAddressPostalCode($form->get('cust_postal_code')->getData());
$deliveryAddress->setAddressCity($form->get('cust_city')->getData());
$deliveryAddress->setAddressSociety($form->get('cust_society')->getData());
}
try {
$this->entityManager->persist($deliveryAddress);
$this->entityManager->flush();
} catch (Exception $ex) {
$this->addFlash('danger',
"Une erreur s'est produite lors de l'enregistrement de l'adresse de livraison");
}
}
}
/*
* Permet d'envoyer le mail de confirmation
* de création de compte
* @param $email string l'email destinataire
* @param $formData array les données du form de création de compte
* @return void
*/
private function sendConfirmationNewAccount($email = null, $formData = null)
{
if (isset($email) && isset($formData)) {
$this->mailerService->subject = "Demande d'adhésion sur " . SITE_NAME;
$htmlContent = $this->renderView('layouts/layouts_emails/notification_request_company.html.twig', [
'formData' => $formData,
'email' => $email,
]);
$this->mailerService->sendMail([], $htmlContent, NULL, 'request-company');
}
}
/*
* Permet d'inscrire un nouveau mail à la newsletter
* @param $email string l'email à inscrire
* @return void
*/
private function subscriptionNewsletter($email = "")
{
if ($email != "") {
$mail = new Newsletter();
$mail->setNlCreationDatetime(new \DateTime());
$mail->setNlEmail($email);
$mail->setNlRgpdChecked(true);
$this->entityManager->persist($mail);
$this->entityManager->flush();
try {
$this->entityManager->persist($mail);
$this->entityManager->flush();
} catch (Exception $ex) {
$this->addFlash('danger',
"Une erreur s'est produite lors de l'enregistrement de l'inscription à la newsletter");
}
}
}
/**
* Permet de redéfinir le mot de passe depuis le compte client
*/
#[Route(path: '/compte-client/modifier-mot-de-passe', name: 'front_customer_edit_password')]
public function setUserPassword(Request $request, UserPasswordHasherInterface $passwordHasher,
AuthUserRepository $repoAuthUser)
{
$form = $this->createForm(CustomerResetPasswordType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user = $repoAuthUser->find($this->getUser()->getId());
// vérification du mot de passe actuel rentré avec celui dans la bdd
if (!$passwordHasher->isPasswordValid($user, $form->get('actualPassword')->getData())) {
$this->addFlash('danger', 'Le mot de passe ne correspond pas à votre mot de passe actuel.');
return $this->redirectToRoute('front_customer_account');
}
$hashedPassword = $passwordHasher->hashPassword(
$user,
$form->get('password')->getData()
);
$user->setPassword($hashedPassword);
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->addFlash('success', 'Votre mot de passe a été changé. Veuillez vous reconnecter.');
return $this->redirectToRoute('front_app_logout');
}
return $this->redirectToRoute('front_customer_account');
}
/**
* @throws Throwable
*/
#[Route(path: '/compte-client/mes-coordonnees/{refOdyssee}', name: 'front_customer_account')]
public function account(Request $request,
EcoCustomersRepository $ecoCustomersRepository,
UserPasswordHasherInterface $passwordHasher,
ApiService $api,
$refOdyssee = null): Response
{
$previousRoute = $request->getSession()->get('previous_route');
if ($previousRoute === 'front_app_login') {
$request->getSession()->remove('previous_route');
return $this->redirectToRoute('front_shopping_categorie');
}
if ($this->currentUserConnected) {
$this->redirectToRoute('front_home');
}
$ecoCustomer = $refOdyssee ? $ecoCustomersRepository->findOneBy(['odyssee_reference' => $refOdyssee]) : $this->currentUserConnected;
$form = $this->createForm(CustomerFrontType::class, $ecoCustomer, [
'odysseeClient' => $api->rechParIdOdyssee($refOdyssee ?: $ecoCustomer->getOdysseeReference())[0],
'type' => $refOdyssee ? 'refOdyssee' : 'account'
]);
$form->handleRequest($request);
if ($refOdyssee && !$ecoCustomersRepository->findOneBy(['odyssee_reference' => $refOdyssee])) {
$addCustomer = new EcoCustomers();
$addCustomer->setCustCreationDate(new \DateTime());
$addCustomer->setAuthUserId($this->currentUserConnected->getAuthUserId());
$addCustomer->setOdysseeReference(0);
$this->entityManager->persist($addCustomer);
$this->entityManager->flush();
$newCustomer = $form->getConfig()->getOptions()['odysseeClient'];
$this->editCustomer($newCustomer, $addCustomer, $this->currentUserConnected->getAuthUserId(), $api);
return $this->redirectToRoute('front_customer_account',
['refOdyssee' => $form->getConfig()->getOptions()['odysseeClient']->{'IdOdysseeClient'}]);
}
if ($form->isSubmitted() && $form->isValid()) {
try {
$customer = $request->request->get('customer_front');
if (!$refOdyssee) {
$this->currentUserConnected->getAuthUserId()->setEmail($customer['AdrCourriel']);
if ($customer['password']['first'] != null) {
$hashedPassword = $passwordHasher->hashPassword(
$this->currentUserConnected->getAuthUserId(),
$customer['password']['first']
);
$this->currentUserConnected->getAuthUserId()->setPassword($hashedPassword);
}
$this->entityManager->persist($this->currentUserConnected->getAuthUserId());
$this->entityManager->flush();
foreach ($this->currentUserConnected->getAuthUserId()->getCustomer() as $cust) {
$customerPush = $api->rechercherClient(idOdyssee: (int)$cust->getOdysseeReference());
$this->editCustomer($customerPush[0], $cust,
$this->currentUserConnected->getAuthUserId(),
$api);
}
} else {
$cust = $ecoCustomersRepository->findOneBy(['odyssee_reference' => $refOdyssee]);
$customer['IdOdysseeClient'] = $refOdyssee;
$customer['IdExterneClient'] = $cust->getId();
$customer['AdrCourriel'] = $this->currentUserConnected->getAuthUserId()->getEmail();
$this->editCustomer($customer, $cust,
$this->currentUserConnected->getAuthUserId(),
$api);
}
$this->addFlash('success', "enregistré avec succès");
} catch (Exception $ex) {
$this->addFlash('danger', "Une erreur s'est produite lors de l'enregistrement ");
}
if ($request->query->get("from") !== null && $request->query->get("from") == "delivery") {
return $this->redirectToRoute('front_basket_delivery');
} else {
return $this->redirectToRoute('front_customer_account', ['refOdyssee' => $refOdyssee]);
}
}
$allOdysseeCustomers = [];
foreach ($this->currentUserConnected->getAuthUserId()->getCustomer() as $cust) {
$allOdysseeCustomers[] = $api->rechParIdOdyssee($cust->getOdysseeReference());
}
$allOdysseeCustomers = $api->rechercherClient(adrCourriel: $this->currentUserConnected->getAuthUserId()->getEmail());
$template = $refOdyssee ? 'ref_odyssee' : 'account';
$pageAccount = 'coordonnees';
$selectedMenu = $refOdyssee ?: 'email';
return $this->render('@main-app/front/front_customer_account/' . $template . '.html.twig', [
'form' => $form->createView(),
'pageAccount' => $pageAccount,
'selectedMenu' => $selectedMenu,
'customer' => $refOdyssee ? $ecoCustomersRepository->findOneBy(['odyssee_reference' => $refOdyssee]) : $this->currentUserConnected,
'user' => $this->currentUserConnected->getAuthUserId(),
'allOdysseeCustomers' => $allOdysseeCustomers
]);
}
#[Route(path: '/compte-client/save-delivery', name: 'front_customer_save_delivery_address')]
public function saveDeliveryAddress(Request $request, EcoCustomersAddressesRepository $repoCustomersAddresses)
{
if ($request->isMethod('POST')) {
$deliveryAddress = $repoCustomersAddresses->find($request->get('delivery_id'));
if ($request->get('delivery_id') == 0) {
$deliveryAddress = new EcoCustomersAddresses;
$deliveryAddress->setCustomerId($this->currentUserConnected->getId());
}
//Enregistrement de l'adresse de livraison
$deliveryAddress->setCountryId($request->get('country_id'));
$deliveryAddress->setAddressCivility($request->get('address_civility'));
$deliveryAddress->setAddressFirstname($request->get('address_firstname'));
$deliveryAddress->setAddressLastname($request->get('address_lastname'));
$deliveryAddress->setAddressSociety($request->get('address_society'));
$deliveryAddress->setAddressPostalCode($request->get('address_postal_code'));
$deliveryAddress->setAddressCity($request->get('address_city'));
$deliveryAddress->setAddressPhone($request->get('address_phone'));
$deliveryAddress->setAddressEntitled($request->get('address_entitled'));
$this->entityManager->persist($deliveryAddress);
$this->entityManager->flush();
$this->addFlash('success', "enregistré avec succès");
if ($request->query->get("from") !== null && $request->query->get("from") == "delivery") {
return $this->redirectToRoute('front_basket_delivery');
} else {
return $this->redirectToRoute('front_customer_account');
}
}
}
/**
* @throws Throwable
*/
#[Route(path: '/compte-client/mes-commandes', name: 'front_customer_orders')]
public function orders(Request $request,
EcoOrdersRepository $repoOrders,
EcoShippingOrdersRepository $repoShippingOrders,
LoyaltySystemService $loyaltySystem,
ApiService $api): Response
{
$customers = $this->currentUserConnected->getAuthUserId()->getCustomer();
$allAvailablesResaCures = [];
// On parcourt tous les clients attachés à ce compte
$orders = [];
foreach ($customers as $customer) {
// Récupération des commandes du client
$order = $api->rechercherResaCure(idOdysseeClient: (int)$customer->getOdysseeReference());
if (!isset($order->status)) {
$orders[$customer->getOdysseeReference()] = $order;
}
// On parcours les cures, on ne garde que celles dont la date de début est supérieure à la date du jour
foreach ($orders as $patient) {
foreach ($patient as $cure) {
$dateDebut = new \DateTime($cure->{'Date_Debut_Resa'});
$dateFin = new \DateTime($cure->{'Date_Fin_Resa'});
$dateJour = new \DateTime();
if ($dateDebut > $dateJour || $dateFin > $dateJour) {
$allAvailablesResaCures[] = $cure;
}
}
}
}
$allOdysseeCustomers = $api->rechercherClient(adrCourriel: $this->currentUserConnected->getAuthUserId()->getEmail());
//TODO : si le site est un SPA, récupérer les résa et ventes SPA (non disponible dans l'API à ce jour)
if (ODYSSEE_TYPE == 'SPA') {
$allAvailablesResaCures = [];
}
return $this->render('@main-app/front/front_customer_account/orders.html.twig', [
'orders' => $allAvailablesResaCures,
'indicationsPrincipales' => $api->listerItp(),
'indicationsSecondaires' => $api->listerIts(),
'pageAccount' => 'commandes',
'allOdysseeCustomers' => $allOdysseeCustomers
]);
}
/**
* @throws Throwable
*/
#[Route(path: '/compte-client/ma-cure/{cure_id}', name: 'front_customer_order_cure')]
public function orderCure(Request $request, EcoOrdersRepository $repoOrders,
EcoShippingOrdersRepository $repoShippingOrders,
LoyaltySystemService $loyaltySystem,
ApiService $api, $cure_id = 0): Response
{
$customers = $this->currentUserConnected->getAuthUserId()->getCustomer();
if ($cure_id == 0) {
return $this->redirectToRoute('front_customer_orders');
}
// Récupération des commandes du client
$order = $api->rechercherResaCure(idOdysseeResa: (int)$cure_id);
if (!$order) {
return $this->redirectToRoute('front_customer_orders');
}
$medecinsPresc = [];
// Récupération du médecin prescripteur
if ($api->rechercherMedPrParCode($order[0]->{'Medecin_Prescripteur'})) {
$medecinsPresc = $api->rechercherMedPrParCode($order[0]->{'Medecin_Prescripteur'});
}
$curiste = $api->rechParIdOdyssee($order[0]->{'IdOdysseeClient'});
// Si il y a plusieurs curistes, on récupère le premier
if (is_array($curiste)) {
$curiste = $curiste[0];
}
return $this->render('@main-app/front/front_customer_account/order_cure.html.twig', [
'order' => $order[0],
'curiste' => $curiste,
'indicationsPrincipales' => $api->listerItp(),
'indicationsSecondaires' => $api->listerIts(),
'medecinsTherm' => $api->listerMedTh(),
'medecinsPresc' => $medecinsPresc,
'plagesHoraires' => $api->listerPlageHoraire(),
'etablissements' => $api->listerEtabResaCure(),
'pointsDeVente' => $api->listerPvResaCure(),
'pageAccount' => 'ma-cure'
]);
}
#[Route(path: '/compte-client/ma-commande/{order_id}', name: 'front_customer_order_detail', defaults: ['order_id' => ''])]
public function order_detail(Request $request, EcoOrdersRepository $repoOrders,
EcoShippingOrdersRepository $repoShippingOrders,
EcoProductsReferencesRepository $repoRef, $order_id,
EcoInvoicesRepository $repoInvoices): Response
{
//Vérification que l'utilisateur est bien connecté
if (!$this->currentUserConnected || $this->currentUserConnected == null) {
return $this->redirectToRoute('front_customer_registration');
}
$order = $repoOrders->find($order_id);
//Vérification que la commande est bien la sienne
if ($order == null || $order->getCustomerId() != $this->currentUserConnected->getId()) {
return $this->redirectToRoute('front_customer_orders');
}
return $this->render('@main-app/front/front_customer_account/order_detail.html.twig', [
'order' => $order,
'shipment' => $repoShippingOrders->findByShipmentOrders($this->currentUserConnected->getId()),
'references' => $repoRef->findByProductReferencesOrder($order_id, $isCanceled = 0),
'referencesCanceled' => $repoRef->findByProductReferencesOrder($order_id, $isCanceled = 1),
'invoices' => $repoInvoices->findByInvoices($this->currentUserConnected->getId(), 'invoice',
$order_id),
'credit_note' => $repoInvoices->findByInvoices($this->currentUserConnected->getId(), 'credit_note',
$order_id),
'pageAccount' => 'commande'
]);
}
#[Route(path: '/compte-client/telecharger/{invoice_id}', name: 'front_customer_invoices_download', defaults: ['invoice_id' => 0])]
public function download(Request $request, EcoInvoicesRepository $repoInvoices,
EcoOrdersRepository $repoOrders, KernelInterface $appKernel, $invoice_id = 0)
{
if (!$this->currentUserConnected || $this->currentUserConnected == null) {
return $this->redirectToRoute('front_customer_registration');
}
//Vérification que la facture est bien la sienne
$invoice = $repoInvoices->find($invoice_id);
if ($invoice !== null) {
$order = $repoOrders->find($invoice->getOrderId());
if ($order->getCustomerId() != $this->currentUserConnected->getId()) {
return $this->redirectToRoute('front_customer_invoices');
}
} else {
return $this->redirectToRoute('front_customer_invoices');
}
//Téléchargement du fichier
$fileName = $invoice->getInvoiceFilename() != null ? $invoice->getInvoiceFilename() : 'walouuu.pdf';
$file = $appKernel->getProjectDir() . '/public/medias_front/orders/' . $fileName;
if (file_exists($file)) {
return new BinaryFileResponse($file);
} else {
return $this->redirectToRoute('front_customer_invoices');
}
}
#[Route(path: '/compte-client/mes-messages', name: 'front_customer_tchat')]
public function tchat(Request $request, EcoCustomersRepository $repoCustomers,
TchatRepository $repoTchat): Response
{
if (!$this->currentUserConnected || $this->currentUserConnected == null) {
return $this->redirectToRoute('front_customer_registration');
}
return $this->render('@main-app/front/front_customer_account/tchat.html.twig', [
'pageAccount' => 'messages',
'discussions' => $repoTchat->findByCustomerDiscussion($this->currentUserConnected->getId()),
'unreadMessages' => $repoTchat->controlIfDiscussionUnread($this->currentUserConnected->getId()),
]);
}
#[Route(path: '/compte-client/nouveau-ticket', name: 'front_tchat_ticket')]
public function tchat_ticket(Request $request, EcoCustomersRepository $repoCustomers,
TchatRepository $repoTchat, EcoOrdersRepository $repoOrders): Response
{
if (!$this->currentUserConnected || $this->currentUserConnected == null) {
return $this->redirectToRoute('front_customer_registration');
}
return $this->render('@main-app/front/front_customer_account/tchat_ticket.html.twig', [
'pageAccount' => 'messages',
'customer_id' => $this->currentUserConnected->getId(),
'orders' => $repoOrders->findBy(['order_status' => array('valid', 'partial-shipment', 'shipment'),
'customer_id' => $this->currentUserConnected->getId()],
['order_date' => 'DESC'])
]);
}
/**
* @param Request $request
*/
#[Route(path: '/compte-client/axDisplayProductOrder', name: 'front_tchat_axDisplayProductOrder', options: ['expose' => true])]
public function axDisplayProductOrder(Request $request, EcoProductsReferencesRepository $repoProdRef)
{
if ($request->isXmlHttpRequest()) {
$renderList = $this->renderView('admin/admin_tchat/tpl_display_products.html.twig', [
'references' => $repoProdRef->findByProductReferencesByOrder($request->get('order_id')),
]);
$script = '';
$script .= " $('#products-list').html('" . str_replace(array("\n", "\r"), '',
html_entity_decode(addslashes($renderList),
ENT_QUOTES)) . "'); ";
return new JsonResponse([
'status' => true,
'script' => $script,
]);
}
return new JsonResponse([
'status' => false,
]);
}
#[Route(path: '/compte-client/open-ticket', name: 'front_tchat_open_conversation')]
public function openTicket(Request $request)
{
if ($request->get('customer_id') > 0) {
//Ouverture d'une conversation
$tchat = new Tchat();
$tchat->setUserId(0);
$tchat->setCustomerId($request->get('customer_id'));
$tchat->setTchatObject($request->get('tchat_object'));
$tchat->setTchatDatetime(new \DateTime());
$tchat->setTchatStatus('open');
$this->entityManager->persist($tchat);
$this->entityManager->flush();
//Ajout du message
$mess = new TchatMessages;
$mess->setTchatId($tchat->getId());
$mess->setUserId(0);
$mess->setMessDatetime(new \DateTime());
$mess->setMessage($request->get('message'));
$mess->setMessRead(false);
//Ajout d'une pièce jointe
if ($request->files->get("mess_file")) {
$fileName = $this->fileService->startUpload([
"fileData" => $request->files->get("mess_file"),
"oldFileName" => NULL,
"fileDestination" => $this->getParameter("upload_tchat_" . CURRENT_SITE_ID),
"autorizedExtensions" => $this->autorizedFiles,
"createWebp" => false
]);
$mess->setMessFile($fileName);
}
$this->entityManager->persist($mess);
$this->entityManager->flush();
//Liaison produits
if ($request->get('references')) {
foreach ($request->get('references') as $op_id) {
$prodLink = new TchatProducts();
$prodLink->setTchatId($tchat->getId());
$prodLink->setOrderpId($op_id);
$this->entityManager->persist($prodLink);
}
$this->entityManager->flush();
}
$this->session->set('displayPopup', 'open-ticket');
return $this->redirectToRoute('front_tchat_discussion', ['tchat_id' => $tchat->getId()]);
}
return $this->redirectToRoute('front_tchat_ticket');
}
#[Route(path: '/compte-client/discussion/{tchat_id}', name: 'front_tchat_discussion', defaults: ['tchat_id' => ''])]
public function discussion(Request $request, TchatRepository $repoTchat,
TchatMessagesRepository $repoTchatMess, EcoCustomersRepository $repoCustomer,
AuthUserRepository $repoUsers, TchatProductsRepository $repoTchatProds,
$tchat_id): Response
{
//Affichage popup
$this->displayPopup();
if ($tchat_id > 0) {
$tchat = $repoTchat->find($tchat_id);
//Access control
if ($this->currentUserConnected == null || $this->currentUserConnected == false || $tchat->getCustomerId() != $this->currentUserConnected->getId()) {
return $this->redirectToRoute('front_customer_registration');
}
} else {
return $this->redirectToRoute('front_customer_registration');
}
//Marquer les messages non lus
$messages = $repoTchatMess->getAdminMessages();
if (is_array($messages)) {
foreach ($messages as $mess) {
if ($mess->getTchatId() == $tchat_id) {
$mess->setMessRead(true);
$this->entityManager->persist($mess);
$this->entityManager->flush();
}
}
}
return $this->render('@main-app/front/front_customer_account/tchat_discussion.html.twig', [
'pageAccount' => 'messages',
'discussion' => $discussion = $repoTchat->find($tchat_id),
'customer' => $repoCustomer->find($discussion->getCustomerId()),
'messages' => $repoTchatMess->findBy(['tchat_id' => $tchat_id], ['mess_datetime' => 'DESC']),
'users' => $repoUsers->findAll(),
'products' => $repoTchatProds->findByTchatProducts($tchat_id),
"autorizedExtensions" => $this->autorizedFiles,
]);
}
#[Route(path: '/compte-client/repondre', name: 'front_tchat_response')]
public function response(Request $request): Response
{
if ($request->isMethod('POST')) {
//Ajout du message
$mess = new TchatMessages;
$mess->setTchatId($request->get('tchat_id'));
$mess->setUserId(0);
$mess->setMessDatetime(new \DateTime());
$mess->setMessage($request->get('message'));
$mess->setMessFile(NULL);
$mess->setMessRead(false);
//Ajout d'une pièce jointe
if ($request->files->get("mess_file")) {
$fileName = $this->fileService->startUpload(
[
"fileData" => $request->files->get("mess_file"),
"oldFileName" => NULL,
"fileDestination" => $this->getParameter("upload_tchat_" . CURRENT_SITE_ID),
"autorizedExtensions" => $this->autorizedFiles,
"createWebp" => false
]
);
$mess->setMessFile($fileName);
}
$this->entityManager->persist($mess);
$this->entityManager->flush();
$this->session->set('displayPopup', 'send-message');
//Envoyer un mail de notification à l'administrateur
$this->newAdminMessageNotification($request->get('tchat_id'), $request->get('message'));
return $this->redirectToRoute('front_tchat_discussion', ['tchat_id' => $request->get('tchat_id')]);
}
return $this->redirectToRoute('front_tchat');
}
/**
* Notification à l'administrateur d'un nouveau message
* @param int $tchat_id
*/
private function newAdminMessageNotification($tchat_id, $message)
{
$tchat = $this->entityManager->getRepository(Tchat::class)->find($tchat_id);
$customer = $this->entityManager->getRepository(EcoCustomers::class)->find($tchat->getCustomerId());
$this->mailerService->fromEmail = $customer->getAuthUserId()->getEmail();
$this->mailerService->fromName = $customer->getCustLastName() . ' ' . $customer->getCustFirstName();
$this->mailerService->subject = SITE_NAME . " - Nouveau message dans votre outil de messagerie";
$allRecipients = array();
// $allRecipients[] = [
// "nom" => SITE_NAME,
// "prenom" => '',
// "email" => 'stephen@otidea.com',
// "type" => 'to'
// ];
$htmlContent = $this->renderView('layouts/layouts_emails/notification_tchat_admin.html.twig', [
'tchat' => $tchat,
'customer' => $customer,
'message' => $message,
]);
$this->mailerService->sendMail($allRecipients, $htmlContent, NULL, 'admin-notification');
}
#[Route(path: '/compte-client/download_attachment/{tchat_id}/{mess_id}', name: 'front_tchat_download_attachment', defaults: ['tchat_id' => '',
'mess_id' => ''])]
public function download_attachment(Request $request, TchatRepository $repoTchat,
TchatMessagesRepository $repoMess, KernelInterface $appKernel, $tchat_id,
$mess_id): Response
{
//Access control
$tchat = $repoTchat->find($tchat_id);
if ($tchat->getCustomerId() != $this->currentUserConnected->getId()) {
return $this->redirectToRoute('front_customer_registration');
}
$message = $repoMess->find($mess_id);
//Téléchargement du fichier
$fileName = $message->getMessFile() != null ? $message->getMessFile() : 'nada.pdf';
$file = $appKernel->getProjectDir() . '/public/medias_front/tchat/' . $fileName;
if (file_exists($file)) {
return new BinaryFileResponse($file);
} else {
return $this->redirectToRoute('front_tchat_discussion', ['tchat_id' => $tchat_id]);
}
}
private function displayPopup()
{
if ($this->session->has('displayPopup')) {
//Erreur de connexion
if ($this->session->get('displayPopup') == 'connection-error') {
$this->otideaUtils->createPopup(["title" => 'Attention',
"message" => 'Votre identifiant ou votre mot de passe est incorrect',
"btn2" => null]
);
}
//L'adresse mail existe déjà
if ($this->session->get('displayPopup') == 'email-exist') {
$this->otideaUtils->createPopup(["title" => 'Attention',
"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",
"btn2" => null]
);
}
//L'adresse mail n'est pas au bon format
if ($this->session->get('displayPopup') == 'email-not-good') {
$this->otideaUtils->createPopup(["title" => 'Attention',
"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.",
"btn2" => null]
);
}
//Envoi d'un message
if ($this->session->get('displayPopup') == 'send-message') {
$this->otideaUtils->createPopup(["title" => 'Information',
"message" => 'Message envoyé avec succès',
"btn2" => null]
);
}
//Ouverture d'un nouveau ticket
if ($this->session->get('displayPopup') == 'open-ticket') {
$this->otideaUtils->createPopup(["title" => 'Information',
"message" => 'Ticket ouvert avec succès',
"btn2" => null]
);
}
$this->session->set('displayPopup', NULL);
}
}
/**
* Validates a single email address (or an array of email addresses)
*
* @param array|string $emails
*
* @return bool
*/
public function validateEmails($emails): bool
{
$emails = filter_var($emails, FILTER_SANITIZE_EMAIL);
if (filter_var($emails, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
#[Route(path: '/compte-client/planning', name: 'front_customer_planning')]
public function planning(Request $request, EcoPlanningRepository $planningRepository): Response
{
if ($this->currentUserConnected->getCustAccountType() == 'company') {
$plannings = $planningRepository->findBy(['societyId' => $this->currentUserConnected->getId()],
['deliveryStartDate' => 'ASC']);
} else if ($this->currentUserConnected->getCustAccountType() == 'employee') {
$plannings = $planningRepository->findBy(['societyId' => $this->currentUserConnected->getCompany()->getId()],
['deliveryStartDate' => 'ASC']);
}
return $this->render('@main-app/front/front_customer_account/planning.html.twig', [
'pageAccount' => 'planning',
'plannings' => $plannings,
]);
}
#[Route(path: '/compte-client/salaries', name: 'front_customer_employee')]
public function employee(Request $request, EcoCustomersRepository $customersRepository): Response
{
$employees = $customersRepository->findBy(['cust_society' => $this->currentUserConnected->getCustSociety()]);
return $this->render('@main-app/front/front_customer_account/employee.html.twig', [
'pageAccount' => 'employee',
'employees' => $employees,
'currentUser' => $this->currentUserConnected
]);
}
#[Route(path: '/inscription-salarie/{companyId}/{campanyCode}', name: 'front_customer_registration_employee', defaults: ['companyId' => '',
'campanyCode' => ''])]
public function inscriptionEmployee($companyId, $campanyCode, Request $request,
UserPasswordHasherInterface $passwordHasher,
EcoShippingfeesCountryRepository $repoCountry,
EcoCustomersRepository $customersRepository): Response
{
if ($this->getUser()) {
return $this->redirectToRoute('front_customer_account');
}
$company = $customersRepository->findOneBy(['id' => $companyId, 'custSocietyCode' => $campanyCode]);
if ($company == null) {
return $this->redirectToRoute('front_home');
}
$authUser = new AuthUser();
$customer = new EcoCustomers();
$form = $this->createForm(CustomerFrontType::class, $customer, [
'authUser' => $customer->getAuthUserId(),
'countryList' => $repoCountry->findBygCountriesOrderByFrance(),
'userType' => 'employee',
'newsletter' => true,
'formType' => "newAccount",
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$existUser = $this->entityManager->getRepository(AuthUser::class)->findBy(['email' => $form->get('email')->getData()]);
if ($existUser != null) {
$this->addFlash('danger', "Une erreur s'est produite lors de l'enregistrement");
return $this->redirectToRoute('front_customer_registration_employee',
['companyId' => $companyId, 'campanyCode' => $campanyCode]);
}
$customer->setCustCreationDate(new \DateTime());
$customer->setCustReference(uniqid());
//Enregistrement du mot de passe
if ($form->has('password') && $form->get('password')->getData() != "" && $form->get('password')->getData() != null) {
$user = $this->setEmployeeAccount($authUser->getId(), $passwordHasher, $form);
$customer->setAuthUserId($user);
// Le mot de passe n'a pas été modifié
}
// Compte salarié
$customer->setCustAccountType('employee');
// Compte confirmé
$customer->setcustAccountStatus('confirmed');
// FRANCE par défaut
$customer->setCustCountryId(1);
// reference client par défaut
$customer->setCustReference("CLI");
// liaison avec l'entreprise
$customer->setCompany($company);
$customer->setCustSociety($company->getCustSociety());
try {
$this->entityManager->persist($customer);
$this->entityManager->flush();
$this->addFlash('success', "enregistré avec succès");
} catch (Exception $ex) {
$this->addFlash('danger', "Cet utilisateur existe déjà");
}
try {
$ref = $customer->getId() + 1000;
$customer->setCustReference("CLI" . $ref);
$this->entityManager->persist($customer);
$this->entityManager->flush();
} catch (Exception $ex) {
$this->addFlash('danger', "Une erreur s'est produite lors de la modification de la référence client");
}
return $this->redirectToRoute('front_customer_account', array('id' => $customer->getId()));
}
return $this->render('@main-app/security_front/registration_employee.html.twig', [
'form' => $form->createView(),
'company' => $company,
]);
}
/*
* Permet d'ajouter un nouveau compte client
* avec le role de client
* @return bool
*/
private function setEmployeeAccount($authUserId = 0, $passwordHasher = null, $form = null, $repoAuthUser = null)
{
if ($form->get('email')->getData() !== null && $form->get('password')->getData() !== null) {
if ($authUserId > 0) {
$user = $repoAuthUser->find($authUserId);
} else {
$user = new AuthUser();
}
$user->setEmail($form->get('email')->getData());
// modification du mot de passe
if ($form->get('password')->getData() !== null && trim($form->get('password')->getData()) != "") {
// hash the password (based on the security.yaml config for the $user class)
$hashedPassword = $passwordHasher->hashPassword(
$user,
$form->get('password')->getData()
);
$user->setPassword($hashedPassword);
}
if ($user->getId() == 0) {
$user->setRoles(array_merge($user->getRoles(), ['ROLE_CUSTOMER']));
$user->setCreationDatetime(new \DateTime());
}
$this->entityManager->persist($user);
$this->entityManager->flush();
return $user;
}
return false;
}
}