src/Controller/Front/NotificationsController.php line 65

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Front;
  3. use App\Entity\Notification;
  4. use App\Entity\NotificationStatistics;
  5. use App\Repository\App\NotificationRepository;
  6. use App\Repository\App\NotificationStatisticsRepository;
  7. use App\Security\RoleInterface;
  8. use App\Traits\DonneeCompteClientAvailableTrait;
  9. use DateTime;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\HttpFoundation\RequestStack;
  17. class NotificationsController extends AbstractController
  18. {
  19.     /**
  20.      * Injecte DonneeCompteClientManager dans le controlleur
  21.      * Ajoute automatiquement la variable donneeCompteClient aux paramètres de la méthode render
  22.      */
  23.     use DonneeCompteClientAvailableTrait;
  24.     /** @var NotificationRepository */
  25.     protected NotificationRepository $notificationRepository;
  26.     /** @var NotificationStatisticsRepository */
  27.     protected NotificationStatisticsRepository $notificationStatisticsRepository;
  28.     protected $session;
  29.     /** @var EntityManagerInterface */
  30.     protected EntityManagerInterface $em;
  31.     /** @var RequestStack */
  32.     protected RequestStack $requestStack;
  33.     public function __construct(
  34.         NotificationRepository           $notificationRepository,
  35.         NotificationStatisticsRepository $notificationStatisticsRepository,
  36.         RequestStack                     $requestStack,
  37.         EntityManagerInterface                    $em,
  38.     )
  39.     {
  40.         $this->notificationRepository $notificationRepository;
  41.         $this->notificationStatisticsRepository $notificationStatisticsRepository;
  42.         $this->requestStack $requestStack;
  43.         $this->session $this->requestStack->getSession();
  44.         $this->em $em;
  45.     }
  46.     /**
  47.      * Returns the number of unread notifications by the user
  48.      *
  49.      * @return JsonResponse
  50.      * @Route("/notifications/counter", name="notification_counter")
  51.      */
  52.     public function getUnreadNotificationCounter(): JsonResponse
  53.     {
  54.         $counter $this->notificationRepository->countUnreadByUser($this->getUser());
  55.         if (is_numeric($counter)) {
  56.             return new JsonResponse([
  57.                 'status' => 'success',
  58.                 'message' => 'Success',
  59.                 'data' => ['count' => $counter]
  60.             ],
  61.                 Response::HTTP_OK
  62.             );
  63.         }
  64.         return new JsonResponse([
  65.             'status' => 'error',
  66.             'message' => 'No data given'
  67.         ],
  68.             Response::HTTP_BAD_REQUEST
  69.         );
  70.     }
  71.     /**
  72.      * Returns an array of unread notifications by the user
  73.      * Used in ajax menu update
  74.      *
  75.      * @param Request $request
  76.      * @return JsonResponse
  77.      * @Route("/notifications/notread", name="notification_unread")
  78.      */
  79.     public function getUnreadNotificationsForMenu(Request $request): JsonResponse
  80.     {
  81.         $notifications $request->get('notifications', []);
  82.         $notifications $this->notificationRepository->findUnreadByUserWithoutGivenArray($this->getUser(), $notifications);
  83.         if (is_array($notifications)) {
  84.             return new JsonResponse([
  85.                 'status' => 'success',
  86.                 'message' => 'Success',
  87.                 'data' => ['notifications' => $notifications]
  88.             ],
  89.                 Response::HTTP_OK
  90.             );
  91.         }
  92.         return new JsonResponse([
  93.             'status' => 'error',
  94.             'message' => 'No data given'
  95.         ],
  96.             Response::HTTP_BAD_REQUEST
  97.         );
  98.     }
  99.     /**
  100.      * @param Notification $notification
  101.      * @return JsonResponse
  102.      *
  103.      * @Route(path="/notifications/read/{notification}")
  104.      */
  105.     public function markAsRead(Notification $notification): JsonResponse
  106.     {
  107.         if ($this->isGranted(RoleInterface::ROLE_PREVIOUS_ADMIN)) {
  108.             return new JsonResponse([
  109.                 'status' => 'error',
  110.                 'message' => 'Interdit pour cet utilisateur',
  111.             ], Response::HTTP_UNAUTHORIZED);
  112.         }
  113.         try {
  114.             $statistics $this->_findStatistic($notification);
  115.             $statistics->setLastSeenDate(new DateTime());
  116.             $statistics->setReadLater(false);
  117.             // increase count read for notification popup
  118.             if($notification->getSetPopUp()){
  119.                 $statistics->incrementCountRead();
  120.             }
  121.             $this->em->flush();
  122.             return new JsonResponse(nullResponse::HTTP_OK);
  123.         } catch (\Exception $e) {
  124.             return new JsonResponse([
  125.                 'status' => 'error',
  126.                 'message' => $e->getMessage(),
  127.             ], Response::HTTP_BAD_REQUEST);
  128.         }
  129.     }
  130.     /**
  131.      * @param Notification $notification
  132.      * @return NotificationStatistics|null
  133.      * @throws \Exception
  134.      */
  135.     public function _findStatistic(Notification $notification): ?NotificationStatistics
  136.     {
  137.         if (!$statistics $this->notificationStatisticsRepository->findOneBy([
  138.             'customerNumber' => $this->getUser()->getCustomerNumber(),
  139.             'notification' => $notification
  140.         ])) {
  141.             throw new \Exception('No valid statistic');
  142.         }
  143.         return $statistics;
  144.     }
  145.     /**
  146.      * Returns the view of all the notifications addressed to the user.
  147.      * NB: The ID is used in Javascript to scroll to the selected notification if set
  148.      *
  149.      * @param int|null $id
  150.      * @return Response
  151.      *
  152.      * @Route("/notifications/{id}", name="notifications_list")
  153.      */
  154.     public function list(int $id null): Response
  155.     {
  156.         $user $this->getUser();
  157.         return $this->render('front/notifications/list.html.twig', [
  158.             'notifications' => $this->notificationRepository->findActiveNotificationsByUser($user),
  159.         ]);
  160.     }
  161.     /**
  162.      * Show the list of notifications in the menu
  163.      * @param Request $request
  164.      * @param int $max
  165.      * @return Response
  166.      */
  167.     public function menu(Request $request): Response
  168.     {
  169.         $user $this->getUser();
  170.         return $this->render('front/notifications/menu.html.twig', [
  171.             'notifications' => $this->notificationRepository->findActiveNotificationsByUser($usertrue),
  172.             'active_route' => $request->get('active_route')
  173.         ]);
  174.     }
  175.     /**
  176.      * Returns all the popups not displayed yet
  177.      *
  178.      * @return Response
  179.      */
  180.     public function getPopup(): Response
  181.     {
  182.         $user $this->getUser();
  183.         $seenPopUps $this->session->get('seenPopUps', []);
  184.         return $this->render('front/notifications/popup.html.twig', [
  185.             'notifications' => $this->notificationRepository->findPopUpNotificationsByUser($user$seenPopUps)
  186.         ]);
  187.     }
  188.     /**
  189.      * Store the answer to a notification
  190.      *
  191.      * @param Notification $notification
  192.      * @param Request $request
  193.      * @return JsonResponse
  194.      *
  195.      * @Route("notifications/input/{id}", name="notification_store_userInput")
  196.      */
  197.     public function storeNotificationUserInput(Notification $notificationRequest $request): JsonResponse
  198.     {
  199.         if ($this->isGranted(RoleInterface::ROLE_PREVIOUS_ADMIN)) {
  200.             return new JsonResponse([
  201.                 'status' => 'error',
  202.                 'message' => 'Interdit pour cet utilisateur',
  203.             ], Response::HTTP_UNAUTHORIZED);
  204.         }
  205.         $answer $request->get('answer');
  206.         try {
  207.             $statistics $this->_findStatistic($notification);
  208.             $this->_checkIfAnswerIsValid($notification$answer);
  209.         } catch (\Exception $e) {
  210.             return new JsonResponse([
  211.                 'status' => 'error',
  212.                 'message' => $e->getMessage(),
  213.             ], Response::HTTP_BAD_REQUEST);
  214.         }
  215.         if ($notification->getRequiredCheckboxToggle()) {
  216.             $statistics->setCheckboxIsChecked($answer['userAgreement'] === 'true');
  217.         }
  218.         $statistics->setAnswer($answer['choice'] === NotificationStatistics::ANSWER_ACCEPTED);
  219.         $this->em->flush();
  220.         return new JsonResponse([
  221.             'status' => 'success',
  222.             'message' => 'Success',
  223.             'answer' => $statistics->getAnswer()
  224.         ],
  225.             Response::HTTP_OK
  226.         );
  227.     }
  228.     /**
  229.      * @param Notification $notification
  230.      * @param $answer
  231.      * @throws \Exception
  232.      */
  233.     public function _checkIfAnswerIsValid(Notification $notification$answer): void
  234.     {
  235.         $choice $answer['choice'];
  236.         // Throws an error if the answer is not one of the options
  237.         if (!in_array($choice, [NotificationStatistics::ANSWER_REFUSEDNotificationStatistics::ANSWER_ACCEPTED])) {
  238.             throw new \Exception('La réponse n\'est pas valide');
  239.         }
  240.         if ((!isset($answer['userAgreement']) || $answer['userAgreement'] === 'false') && $notification->getRequiredCheckboxToggle()) {
  241.             throw new \Exception('La réponse n\'est pas valide');
  242.         }
  243.     }
  244.     /**
  245.      * @param Notification $notification
  246.      * @return JsonResponse
  247.      *
  248.      * @Route("/notifications/popup/readLater/{notification}", name="notifications_popup_readLater")
  249.      */
  250.     public function setReadLaterPopUp(Notification $notification): JsonResponse
  251.     {
  252.         if ($this->isGranted(RoleInterface::ROLE_PREVIOUS_ADMIN)) {
  253.             return new JsonResponse([
  254.                 'status' => 'error',
  255.                 'message' => 'Interdit pour cet utilisateur',
  256.             ], Response::HTTP_UNAUTHORIZED);
  257.         }
  258.         $stat $this->notificationStatisticsRepository->findOneBy([
  259.             'notification' => $notification,
  260.             'customerNumber' => $this->getUser()->getCustomerNumber()
  261.         ]);
  262.         if (!$stat) {
  263.             return new JsonResponse(['error' => 'not found'], 404);
  264.         }
  265.         $this->_saveSeenPopUpToSession($notification);
  266.         $stat->setReadLater(true);
  267.         $this->em->flush();
  268.         return new JsonResponse([
  269.             'status' => 'success',
  270.             'message' => 'Success'
  271.         ],
  272.             Response::HTTP_OK
  273.         );
  274.     }
  275.     /**
  276.      * @param Notification $notification
  277.      */
  278.     private function _saveSeenPopUpToSession(Notification $notification): void
  279.     {
  280.         $seenPopUps $this->session->get('seenPopUps', []);
  281.         $id $notification->getId();
  282.         if (!in_array($id$seenPopUps)) {
  283.             $seenPopUps[] = $id;
  284.         }
  285.         $this->session->set('seenPopUps'$seenPopUps);
  286.     }
  287.     /**
  288.      * Save popup as unread in session, increment insistence coefficient
  289.      *
  290.      * @param Notification $notification
  291.      * @return JsonResponse
  292.      *
  293.      * @Route("/notifications/popup/closed/{notification}", name="notifications_popup_closed")
  294.      */
  295.     public function setClosedPopUp(Notification $notification): JsonResponse
  296.     {
  297.         $this->_saveSeenPopUpToSession($notification);
  298.         if ($this->isGranted(RoleInterface::ROLE_PREVIOUS_ADMIN)) {
  299.             return new JsonResponse([
  300.                 'status' => 'success',
  301.                 'message' => 'success',
  302.             ], Response::HTTP_OK);
  303.         }
  304.         return new JsonResponse([
  305.             'status' => 'success',
  306.             'message' => 'Success'
  307.         ],
  308.             Response::HTTP_OK
  309.         );
  310.     }
  311. }