src/Controller/UserController.php line 300

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\UserType;
  5. use App\Entity\Mailling;
  6. use App\Entity\Dashboard;
  7. use App\Form\DashboardType;
  8. use App\Notification\MaillingNotification;
  9. use App\Repository\NoteRepository;
  10. use App\Repository\UserRepository;
  11. use App\Service\Calendar;
  12. use DateTime;
  13. use DateTimeInterface;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use Dotenv\Dotenv;
  16. use Knp\Component\Pager\PaginatorInterface;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Symfony\Component\Form\Extension\Core\Type\TextType;
  22. use Symfony\Component\Form\Extension\Core\Type\EmailType;
  23. use Symfony\Component\Form\Extension\Core\Type\IntegerType;
  24. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  25. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  26. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  27. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  28. /**
  29.  * @Route("/user")
  30.  */
  31. class UserController extends AbstractController
  32. {
  33.     public $passwordHasher;
  34.     public $maillingNotification;
  35.     public $em;
  36.     public function __construct(UserPasswordHasherInterface $passwordHasherMaillingNotification $maillingNotificationEntityManagerInterface $em)
  37.     {
  38.         $this->passwordHasher $passwordHasher;
  39.         $this->em $em;
  40.         $this->maillingNotification $maillingNotification;
  41.     }
  42.     /**
  43.      *@Route("/", name="user.index", methods={"GET", "POST"})
  44.      */
  45.     public function index(Request $requestUserRepository $userRepositoryPaginatorInterface $paginator)
  46.     {
  47.         if (!in_array('ROLE_MASTER'$this->getUser()->getRoles())) {
  48.             return $this->redirectToRoute('dashboard.index', [], Response::HTTP_SEE_OTHER);
  49.         }
  50.         $search trim($request->query->get('search') ?? '');
  51.         if ($request->request->get('search')) {
  52.             $search trim($request->request->get('search'));
  53.         }
  54.         $users $paginator->paginate(
  55.             $userRepository->findAllUsers($search),
  56.             $request->query->getInt('page'1),
  57.             20
  58.         );
  59.         if ($request->isXmlHttpRequest()) {
  60.             return new JsonResponse([
  61.                 'users' => $this->renderView('user/user_tab.html.twig', ['users' => $users]),
  62.             ]);
  63.         }
  64.         return $this->render('user/index.html.twig', [
  65.             'users' => $users,
  66.             'current_page' => 'user'
  67.         ]);
  68.     }
  69.     /**
  70.      *@Route("/analytics", name="user.analytics")
  71.      */
  72.     public function analytics(Request $requestUserRepository $userRepository)
  73.     {
  74.         $userID $request->query->get('user') ?? null;
  75.         $users $userRepository->getStatsInfo($userID);
  76.         $pages = [];
  77.         extract($this->getStats($users'all'));
  78.         $pages = [];
  79.         foreach ($users_stats as $stats) {
  80.             $sums = array();
  81.             foreach (array_keys($pages $stats) as $key) {
  82.                 if (array_key_exists($key$pages) and $pages[$key] != null) {
  83.                     if (!is_string($pages[$key])) {
  84.                         $sums[$key] = @($pages[$key] + $stats[$key]);
  85.                     }
  86.                 } else {
  87.                     $sums[$key] = $stats[$key];
  88.                 }
  89.             }
  90.             $pages $sums;
  91.         }
  92.         $name '';
  93.         if ($userID != null && !empty($pages)) {
  94.             $name $pages['firstName'] . ' ' $pages['name'];
  95.         }
  96.         unset($pages['firstName']);
  97.         unset($pages['name']);
  98.         unset($pages['company_name']);
  99.         unset($pages['email']);
  100.         unset($pages['phone']);
  101.         arsort($pages);
  102.         return $this->render('user/analytics.html.twig', [
  103.             'name' => $name,
  104.             'pages' => $pages,
  105.             'current_page' => 'stats'
  106.         ]);
  107.     }
  108.     /**
  109.      *@Route("/analytics-user/", name="user.analytics_user")
  110.      */
  111.     public function analytics_user(Request $requestUserRepository $userRepository)
  112.     {
  113.         $page $request->query->get('page');
  114.         $users $userRepository->getStatsInfo();
  115.         $defaultMonth $request->request->get('periodeSelect') ?? 'all';
  116.         extract($this->getStats($users$defaultMonth));
  117.         return $this->render('user/analytics-user.html.twig', [
  118.             'users_stats'   => $users_stats,
  119.             'all_mois'      => $all_mois,
  120.             'defaultMonth'  => $defaultMonth,
  121.             'page'          => $page,
  122.             'current_page'  => 'stats'
  123.         ]);
  124.     }
  125.     private function getStats($users$defaultMonth)
  126.     {
  127.         $users_stats = [];
  128.         $all_mois = [];
  129.         $i 0;
  130.         foreach ($users as $user) {
  131.             if (array_key_exists('mois'$user['dashboard_info'])) {
  132.                 foreach ($user['dashboard_info']['mois'] as $mois => $value) {
  133.                     $all_mois[$mois] = 1;
  134.                     if ($mois != $defaultMonth && $defaultMonth != 'all') {
  135.                         continue;
  136.                     }
  137.                     $value['firstName'] = $user['firstName'];
  138.                     $value['name'] = $user['name'];
  139.                     $value['company_name'] = $user['company_name'];
  140.                     $value['email'] = $user['email'];
  141.                     $value['phone'] = $user['phone'];
  142.                     if ($defaultMonth == 'all') {
  143.                         $sums = array();
  144.                         if (array_key_exists($i$users_stats)) {
  145.                             foreach (array_keys($users_stats[$i] + $value) as $key) {
  146.                                 $sums[$key] = @(intval($users_stats[$i][$key]) + intval($value[$key]));
  147.                             }
  148.                             $sums['firstName'] = $user['firstName'];
  149.                             $sums['name'] = $user['name'];
  150.                             $sums['company_name'] = $user['company_name'];
  151.                             $sums['email'] = $user['email'];
  152.                             $sums['phone'] = $user['phone'];
  153.                             $users_stats[$i] = $sums;
  154.                         } else {
  155.                             $users_stats[$i] = $value;
  156.                         }
  157.                     } else {
  158.                         $users_stats[$mois][] = $value;
  159.                     }
  160.                 }
  161.             }
  162.             $i++;
  163.         }
  164.         return ['users_stats' => $users_stats'all_mois' => $all_mois'defaultMonth' => $defaultMonth];
  165.     }
  166.     /**
  167.      *@Route("/add", name="user.add")
  168.      */
  169.     public function add(Request $requestUserRepository $userRepository)
  170.     {
  171.         if (!in_array('ROLE_MASTER'$this->getUser()->getRoles())) {
  172.             return $this->redirectToRoute('dashboard.index', [], Response::HTTP_SEE_OTHER);
  173.         }
  174.         $user = new User();
  175.         $form $this->createForm(UserType::class, $user);
  176.         $requestData $request->request->get('user');
  177.         if ($requestData != null) {
  178.             switch ($requestData['account_type']) {
  179.                 case 0:
  180.                     $user->setParentId(0);
  181.                     $user->setRoles(['ROLE_USER''ROLE_SUPER_ADMIN']);
  182.                     $user->setApiKey(base_convert(hash('sha256'time() . mt_rand()), 1636));
  183.                     break;
  184.                 case 1:
  185.                     $user->setParentId($requestData['parent']);
  186.                     $user->setRoles(['ROLE_USER']);
  187.                     $user->setApiKey($userRepository->find($requestData['parent'])->getApiKey());
  188.                     break;
  189.                 case 2:
  190.                     $user->setParentId($requestData['parent']);
  191.                     $user->setRoles(['ROLE_USER''ROLE_MANDATAIRE']);
  192.                     $user->setApiKey(base_convert(hash('sha256'time() . mt_rand()), 1636));
  193.                     break;
  194.             }
  195.             $user->setDashboardInfo(json_decode(
  196.                 '{
  197.                     "rdv": 0,
  198.                     "mandats": 0,
  199.                     "ca_genere": 0,
  200.                     "ca_potentiel": 0,
  201.                     "ca_previsionnel": 0
  202.                 }',
  203.                 true
  204.             ));
  205.             $user->setPlainPassword($this->setPassword())
  206.                 ->setPassword($this->passwordHasher->hashPassword($user$user->getPlainPassword()));
  207.             $password $user->getPlainPassword();
  208.         }
  209.         $form->handleRequest($request);
  210.         if ($form->isSubmitted() && $form->isValid()) {
  211.             $this->em->persist($user);
  212.             $this->em->flush();
  213.             if ($user->getParentId() == 0) {
  214.                 $user->setParentId($user->getId());
  215.                 $this->em->flush($user);
  216.             }
  217.             $mailling = new Mailling();
  218.             $mailling->setSubject('Votre compte Integraal');
  219.             $mailling->setMessage('
  220.                 <h3>Bienvenue sur Integraal</h3>
  221.                 <p>Voici vos identifiants pour vous connecter à la plateforme : </p>
  222.                 <p>
  223.                     Adresse email : ' $user->getEmail() . '<br>
  224.                     Mot de passe : ' $password '<br>
  225.                     ' $this->generateUrl('app.login', [], UrlGeneratorInterface::ABSOLUTE_URL) . '
  226.                 </p>');
  227.             $mailling->setEmailFrom('no-reply@integraal.io');
  228.             $mailling->setEmailTo($user->getEmail());
  229.             $this->maillingNotification->notify($mailling);
  230.             return $this->redirectToRoute('user.index', [], Response::HTTP_SEE_OTHER);
  231.         }
  232.         return $this->render('user/add.html.twig', [
  233.             'form' => $form->createView(),
  234.             'current_page' => 'user'
  235.         ]);
  236.     }
  237.     /**
  238.      *@Route("/{id}/edit", name="user.edit", methods={"GET", "POST"})
  239.      */
  240.     public function edit(User $userRequest $request)
  241.     {
  242.         if (!in_array('ROLE_MASTER'$this->getUser()->getRoles())) {
  243.             return $this->redirectToRoute('dashboard.index', [], Response::HTTP_SEE_OTHER);
  244.         }
  245.         $sendNewId false;
  246.         if ($request->request->get('user') != null && $user->getEmail() != $request->request->get('user')['email']) {
  247.             $sendNewId true;
  248.         }
  249.         $form $this->createForm(UserType::class, $user);
  250.         $form->handleRequest($request);
  251.         if ($form->isSubmitted() && $form->isValid()) {
  252.             $this->em->flush($user);
  253.             if ($sendNewId$this->sendNewIdentifiant($user'<i>Le mot de passe que vous avez défini.</i>');
  254.             return $this->redirectToRoute('user.index', [], Response::HTTP_SEE_OTHER);
  255.         }
  256.         return $this->render('user/add.html.twig', [
  257.             'form' => $form->createView(),
  258.             'button_label' => 'Editer l\'utilisateur',
  259.             'edit'  => true,
  260.             'current_page' => 'user'
  261.         ]);
  262.     }
  263.     /**
  264.      *@Route("/{id}/resetpwd", name="user.resetPassword")
  265.      */
  266.     public function resetPassword(User $userRequest $request)
  267.     {
  268.         if ($this->isCsrfTokenValid('reset-password' $user->getId(), $request->get('_token'))) {
  269.             $user->setPlainPassword($this->setPassword())
  270.                 ->setPassword($this->passwordHasher->hashPassword($user$user->getPlainPassword()));
  271.             $password $user->getPlainPassword();
  272.             $this->em->flush($user);
  273.             $this->sendNewIdentifiant($user$password);
  274.         }
  275.         return $this->redirectToRoute('user.index', [], Response::HTTP_SEE_OTHER);
  276.     }
  277.     /**
  278.      *@Route("/forgotPassword", name="user.forgotPassword", methods={"GET", "POST"})
  279.      */
  280.     public function forgotPassword(Request $requestUserRepository $userRepository)
  281.     {
  282.         if ($request->request->get('email')) {
  283.             if ($this->isCsrfTokenValid('reset-pwd'$request->get('_token'))) {
  284.                 $users $userRepository->findBy(['email' => $request->request->get('email')]);
  285.                 if ($users) {
  286.                     $user $users[0];
  287.                     $user->setPlainPassword($this->setPassword())
  288.                         ->setPassword($this->passwordHasher->hashPassword($user$user->getPlainPassword()));
  289.                     $password $user->getPlainPassword();
  290.                     $this->em->flush($user);
  291.                     $this->sendNewIdentifiant($user$password);
  292.                     return $this->render('user/forgot_finish.html.twig');
  293.                 }
  294.             }
  295.         }
  296.         // if($request->request)
  297.         return $this->render('user/forgot.html.twig');
  298.     }
  299.     private function sendNewIdentifiant(User $userstring $password)
  300.     {
  301.         $mailling = new Mailling();
  302.         $mailling->setSubject('Vos identifiants Integraal');
  303.         $mailling->setMessage('
  304.             <h3>Vos identifiant sur Integraal ont changé</h3>
  305.             <p>Voici vos nouveaux identifiant pour vous connecter à la plateforme :</p>
  306.             <p>
  307.                 Adresse email : ' $user->getEmail() . '<br>
  308.                 Mot de passe : ' $password ' <br>
  309.                 ' $this->generateUrl('app.login', [], UrlGeneratorInterface::ABSOLUTE_URL) . '
  310.             </p>');
  311.         $mailling->setEmailFrom('no-reply@integraal.io');
  312.         $mailling->setEmailTo($user->getEmail());
  313.         $this->maillingNotification->notify($mailling);
  314.     }
  315.     private function setPassword()
  316.     {
  317.         $comb 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
  318.         $pass = array();
  319.         $combLen strlen($comb) - 1;
  320.         for ($i 0$i 8$i++) {
  321.             $n rand(0$combLen);
  322.             $pass[] = $comb[$n];
  323.         }
  324.         return implode($pass);
  325.     }
  326.     private function verifyPassword($data)
  327.     {
  328.         $password $data['new_password'];
  329.         $uppercase preg_match('@[A-Z]@'$password);
  330.         $lowercase preg_match('@[a-z]@'$password);
  331.         $number    preg_match('@[0-9]@'$password);
  332.         $specialChars preg_match('@[^a-z^0-9^A-Z]@'$password);
  333.         if (!$uppercase || !$lowercase || !$number || !$specialChars || strlen($password) < 8) {
  334.             return ['<div class="col-12 alert alert-warning">Le mot de passe doit comporter au moins 8 caractères et doit inclure au moins une lettre minuscule, une lettre majuscule, un chiffre et un caractère spécial</div>'];
  335.         }
  336.         return true;
  337.     }
  338.     /**
  339.      *@Route("/settings", name="user.settings")
  340.      */
  341.     public function settingsAccount(Request $request)
  342.     {
  343.         if ($request->query->get('code')) {
  344.             return $this->setAgendaSync($request->query->get('code'));
  345.         }
  346.         $user $this->getUser();
  347.         $calendar = new Calendar($user$this->em);
  348.         $form $this->createFormBuilder($user)
  349.             ->add('email'EmailType::class, ['label' => 'Email'])
  350.             ->add('first_name'TextType::class, ['label' => 'Prénom'])
  351.             ->add('name'TextType::class, ['label' => 'Nom'])
  352.             ->add('new_password'PasswordType::class, ['mapped' => false'label' => 'Nouveau mot de passe'])
  353.             ->add('street'TextType::class, ['label' => 'Adresse'])
  354.             ->add('street_number'IntegerType::class, ['label' => 'N°'])
  355.             ->add('zipcode'TextType::class, ['label' => 'Code postal'])
  356.             ->add('city'TextType::class, ['label' => 'Ville'])
  357.             ->add('phone'TextType::class, ['label' => 'Téléphone'])
  358.             ->add('company_name'TextType::class, ['label' => 'Nom de société (Nom affiché en émetteur d\'email)'])
  359.             ->getForm();
  360.         // $form = $this->createForm(UserType::class, $user);
  361.         $form->handleRequest($request);
  362.         $requestData $request->request->get('form');
  363.         if ($form->isSubmitted() && $form->isValid()) {
  364.             if (strlen($requestData['new_password']) > 0) {
  365.                 if ($this->verifyPassword($requestData) === true) {
  366.                     $user->setPlainPassword($requestData['new_password'])
  367.                         ->setPassword($this->passwordHasher->hashPassword($user$user->getPlainPassword()));
  368.                     $password $user->getPlainPassword();
  369.                     $this->sendNewIdentifiant($user$password);
  370.                 } else {
  371.                     return $this->render('user/settings.html.twig', [
  372.                         'form' => $form->createView(),
  373.                         'current_sub_page' => 'account_settings',
  374.                         'current_page' => 'user',
  375.                         'error' => $this->verifyPassword($requestData) ?? '',
  376.                         'syncLink' => $calendar->getAuthLink($this->generateUrl('user.settings', [], UrlGeneratorInterface::ABSOLUTE_URL))
  377.                     ]);
  378.                 }
  379.                 $this->em->flush($user);
  380.             } else {
  381.                 $this->em->flush($user);
  382.             }
  383.             $this->addFlash(
  384.                 'notice',
  385.                 'Les changements ont été sauvegardé.'
  386.             );
  387.             return $this->redirectToRoute('user.settings', [], Response::HTTP_SEE_OTHER);
  388.         }
  389.         return $this->render('user/settings.html.twig', [
  390.             'form' => $form->createView(),
  391.             'current_sub_page' => 'account_settings',
  392.             'current_page' => 'user',
  393.             'error' => $error ?? '',
  394.             'syncLink' => $calendar->getAuthLink($this->generateUrl('user.settings', [], UrlGeneratorInterface::ABSOLUTE_URL))
  395.         ]);
  396.     }
  397.     private function setAgendaSync($code ''$reset false)
  398.     {
  399.         $user $this->getUser();
  400.         $calendar = new Calendar($this->getUser(), $this->em);
  401.         if ($reset) {
  402.             $user->setAgendaToken(NULL);
  403.             $user->setAgendaRefreshToken(NULL);
  404.             $user->setAgendaExpireIn(NULL);
  405.             $user->setAgendaProfile(NULL);
  406.             $this->em->flush($user);
  407.         }
  408.         if ($code != '') {
  409.             $token $calendar->getUserToken($this->generateUrl('user.settings', [], UrlGeneratorInterface::ABSOLUTE_URL), $code);
  410.             $user->setAgendaToken($token['access']);
  411.             $user->setAgendaRefreshToken($token['refresh']);
  412.             $user->setAgendaExpireIn(time() + $token['expireIn']);
  413.             $user->setAgendaProfile($token['profile']);
  414.             $this->em->flush($user);
  415.         }
  416.         return $this->redirectToRoute('user.settings', [], Response::HTTP_SEE_OTHER);
  417.     }
  418.     /**
  419.      * @Route("/unsync", name="user.settings.unsync", methods={"GET"})
  420.      */
  421.     public function unsync(UserRepository $userRepository)
  422.     {
  423.         return $this->setAgendaSync(''true);
  424.     }
  425.     /**
  426.      * @Route("/change-user", name="user.changeUser", methods={"POST"})
  427.      */
  428.     public function changeUser(Request $requestUserRepository $userRepository): Response
  429.     {
  430.         if ($request->isXmlHttpRequest()) {
  431.             if ($request->request->get('PossessUser') == 'all') {
  432.                 $request->getSession()->set('userPossess''all');
  433.             } else {
  434.                 $request->getSession()->set('userPossess'$userRepository->find($request->request->get('PossessUser')));
  435.             }
  436.             return new JsonResponse([
  437.                 'redirect' => $request->headers->get('referer')
  438.             ]);
  439.         }
  440.     }
  441.     /**
  442.      * @Route("/delete/{id}", name="user.delete", methods={"POST"})
  443.      */
  444.     public function delete(Request $requestUser $userUserRepository $userRepositoryNoteRepository $noteRepository): Response
  445.     {
  446.         $remove_id $user->getId();
  447.         if ($this->isCsrfTokenValid('delete' $remove_id$request->request->get('_token'))) {
  448.             $parent $userRepository->findBy(['id' => $user->getParentId()])[0];
  449.             $notes $noteRepository->findBy(['user' => $user->getId()]);
  450.             if ($parent == $user) {
  451.                 $users $userRepository->getAllAgent($parent->getId());
  452.                 foreach ($users as $userRelation) {
  453.                     if ($userRelation != $parent) {
  454.                         $this->removeUserRelation($userRelation$userRepository$noteRepository);
  455.                         $this->em->remove($userRelation);
  456.                     }
  457.                 }
  458.                 foreach ($user->getTasksActor() as $item) {
  459.                     $this->em->remove($item);
  460.                     $this->em->flush();
  461.                 }
  462.                 foreach ($user->getTasks() as $item) {
  463.                     $this->em->remove($item);
  464.                     $this->em->flush();
  465.                 }
  466.                 foreach ($user->getMaillings() as $item) {
  467.                     $this->em->remove($item);
  468.                     $this->em->flush();
  469.                 }
  470.                 foreach ($user->getMarkers() as $item) {
  471.                     $this->em->remove($item);
  472.                     $this->em->flush();
  473.                 }
  474.                 foreach ($user->getNotifications() as $item) {
  475.                     $this->em->remove($item);
  476.                     $this->em->flush();
  477.                 }
  478.                 foreach ($notes as $item) {
  479.                     $this->em->remove($item);
  480.                     $this->em->flush();
  481.                 }
  482.                 foreach ($user->getLeadsByPossessor() as $item) {
  483.                     $this->em->remove($item);
  484.                     $this->em->flush();
  485.                 }
  486.             } else {
  487.                 $this->removeUserRelation($user$userRepository$noteRepository);
  488.             }
  489.             $this->em->remove($user);
  490.             $this->em->flush();
  491.             if ($request->isXmlHttpRequest()) {
  492.                 return new JsonResponse([
  493.                     'remove' => 'true'
  494.                 ]);
  495.             }
  496.         }
  497.         return $this->redirectToRoute('user.index', [], Response::HTTP_SEE_OTHER);
  498.     }
  499.     private function removeUserRelation(User $userUserRepository $userRepositoryNoteRepository $noteRepository)
  500.     {
  501.         $parent $userRepository->findBy(['id' => $user->getParentId()])[0];
  502.         $notes $noteRepository->findBy(['user' => $user->getId()]);
  503.         foreach ($user->getTasksActor() as $item) {
  504.             $item->setUser($parent);
  505.             $item->setUserAction($parent);
  506.             $this->em->flush();
  507.         }
  508.         foreach ($user->getTasks() as $item) {
  509.             $item->setUser($parent);
  510.             $item->setUserAction($parent);
  511.             $this->em->flush();
  512.         }
  513.         foreach ($user->getMaillings() as $item) {
  514.             $item->setUser($parent);
  515.             $this->em->flush();
  516.         }
  517.         foreach ($user->getMarkers() as $item) {
  518.             $item->setUser($parent);
  519.             $this->em->flush();
  520.         }
  521.         foreach ($user->getNotifications() as $item) {
  522.             $item->setUser($parent);
  523.             $item->setIsSeen(0);
  524.             $this->em->flush();
  525.         }
  526.         foreach ($notes as $item) {
  527.             $item->setUser($parent);
  528.             $this->em->flush();
  529.         }
  530.         foreach ($user->getLeads() as $item) {
  531.             $item->setUser($parent);
  532.             $this->em->flush();
  533.         }
  534.     }
  535. }