src/Controller/Cronjobs/NotificationsController.php line 244

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Cronjobs;
  3. use App\Controller\Response;
  4. use App\Entity\FavouriteMenus;
  5. use App\Entity\FavouriteMenusSessions;
  6. use App\Entity\Language;
  7. use App\Entity\NotificationTemplates;
  8. use App\Entity\Objectives;
  9. use App\Entity\ScheduledNotifications;
  10. use App\Entity\UserFcmTokens;
  11. use App\Entity\UserNotifications;
  12. use App\Entity\Users;
  13. use App\Services\Notifications\ComposedNotification;
  14. use App\Services\Notifications\FcmNotifications;
  15. use App\Services\Objectives\ObjectiveSetter;
  16. use App\Traits\TextTrait;
  17. use DateTime;
  18. use Doctrine\ORM\EntityManagerInterface;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use Symfony\Component\Routing\Annotation\Route;
  21. use Symfony\Contracts\Translation\TranslatorInterface;
  22. /**
  23.  * @Route("/cronjobs/notifications", name="cronjobs_notifications_")
  24.  */
  25. class NotificationsController extends AbstractController
  26. {
  27.     use Response;
  28.     use TextTrait;
  29.     /**
  30.      * @Route("/next_day_menu", name="next_day_menu", methods={"GET"})
  31.      */
  32.     public function nextDayMenuAction(
  33.         FcmNotifications $fcmNotification,
  34.         TranslatorInterface $translator,
  35.         EntityManagerInterface $em
  36.     )
  37.     {
  38.         $sessions $em->getRepository(FavouriteMenusSessions::class)
  39.             ->findLastUserSessions();
  40.         if ($sessions) {
  41.             foreach ($sessions as $session) {
  42.                 $menu $em->getRepository(FavouriteMenus::class)
  43.                     ->findNextDayMenuNotification($session['userId'], $session['id']);
  44.                 if ($menu) {
  45.                     $listTokens $em->getRepository(UserFcmTokens::class)->findUserTokensList(
  46.                         $session['userId']
  47.                     );
  48.                     $fcmNotification->init(
  49.                         $listTokens,
  50.                         [
  51.                             'title' => $translator->trans('Information', [], 'messages'$session['lang']),
  52.                             'body' => $translator->trans('Next day notification', [], 'messages'$session['lang']),
  53.                             'data' => [
  54.                                 'menuID' => $menu->getMenuId(),
  55.                             ],
  56.                         ]
  57.                     );
  58.                     $fcmNotification->send();
  59.                     $menu->setNotifiedAt(new DateTime());
  60.                     $em->persist($menu);
  61.                 }
  62.             }
  63.             $em->flush();
  64.         }
  65.         return $this->jsonResponse();
  66.     }
  67.     /**
  68.      * @Route("/buy_now", name="buy_now", methods={"GET"})
  69.      */
  70.     public function buyNowAction(
  71.         FcmNotifications $fcmNotification,
  72.         TranslatorInterface $translator,
  73.         EntityManagerInterface $em
  74.     )
  75.     {
  76.         $users $em->getRepository(Users::class)
  77.             ->getUsersByRegistrationDate(3);
  78.         if ($users) {
  79.             foreach ($users as $user) {
  80.                 $listTokens $em->getRepository(UserFcmTokens::class)->findUserTokensList(
  81.                     $user->getId()
  82.                 );
  83.                 $fcmNotification->init(
  84.                     $listTokens,
  85.                     [
  86.                         'title' => $translator->trans('Information', [], 'messages'$user->getLang()),
  87.                         'body' => $translator->trans('Buy now notification', [], 'messages'$user->getLang()),
  88.                         'data' => [
  89.                             'menuID' => -1,
  90.                         ],
  91.                     ]
  92.                 );
  93.                 $fcmNotification->send();
  94.             }
  95.         }
  96.         return $this->jsonResponse();
  97.     }
  98.     /**
  99.      * @Route("/video", name="video", methods={"GET"})
  100.      */
  101.     public function videoNotificationAction(
  102.         FcmNotifications $fcmNotification,
  103.         TranslatorInterface $translator,
  104.         EntityManagerInterface $em
  105.     )
  106.     {
  107.         $users $em->getRepository(Users::class)
  108.             ->getUsersCreatedByInterval(3);
  109.         if ($users) {
  110.             $today = new DateTime(\date("Y-m-d"));
  111.             foreach ($users as $user) {
  112.                 if (!$user->getLastNotification() || $user->getLastNotification() < $today) {
  113.                     $listTokens $em->getRepository(UserFcmTokens::class)->findUserTokensList(
  114.                         $user->getId()
  115.                     );
  116.                     $fcmNotification->init(
  117.                         $listTokens,
  118.                         [
  119.                             'title' => $translator->trans('Information', [], 'messages'$user->getLang()),
  120.                             'body' => $translator->trans('Video Notification', [], 'messages'$user->getLang()),
  121.                             'data' => [
  122.                                 'notification_type' => 3// video
  123.                             ],
  124.                         ]
  125.                     );
  126.                     $fcmNotification->send();
  127.                     // save last notification date
  128.                     $user->setLastNotification(new DateTime());
  129.                     $em->persist($user);
  130.                     $em->flush();
  131.                 }
  132.             }
  133.         }
  134.         return $this->jsonResponse();
  135.     }
  136.     /**
  137.      * @Route("/scheduled_notifications", name="scheduled_notifications", methods={"GET"})
  138.      */
  139.     public function scheduledNotificationsAction(
  140.         FcmNotifications $fcmNotification,
  141.         EntityManagerInterface $em
  142.     )
  143.     {
  144.         $languageRo $em->getRepository(Language::class)->findOneBy(['language_shortname' => 'ro']);
  145.         $languageEn $em->getRepository(Language::class)->findOneBy(['language_shortname' => 'en']);
  146.         $notification $em->createQueryBuilder()
  147.             ->select('sn')
  148.             ->from(ScheduledNotifications::class, 'sn')
  149.             ->where('sn.removedAt IS NULL AND sn.runnedAt IS NULL AND sn.scheduledAt <= :scheduled AND sn.pro_users = 0')
  150.             ->setParameter('scheduled', (new DateTime())->format('Y-m-d H:i:s'))
  151.             ->orderBy('sn.scheduledAt''ASC')
  152.             ->setMaxResults(1)
  153.             ->getQuery()
  154.             ->getOneOrNullResult();
  155.         if ($notification) {
  156.             /*
  157.              * +-----------------------------------------
  158.              * | RO Notifications
  159.              * +-----------------------------------------
  160.              */
  161.             $fcmNotification->init(
  162.                 [],
  163.                 [
  164.                     'title' => $notification->getNotificationTitle(),
  165.                     'body' => $notification->getNotificationPreview(),
  166.                     'data' => [
  167.                         'notification_type' => 4,
  168.                         'notification_id' => $notification->getId(),
  169.                         'page' => ($notification->getForwardTo() ? $notification->getForwardTo() : 0),
  170.                         'menuID' => 0,
  171.                     ],
  172.                 ],
  173.                 sprintf($this->getParameter('notifications_topic_post_basic'), $languageRo->getLanguageShortname()),
  174.                 true
  175.             );
  176.             $fcmNotification->send();
  177.             /*
  178.              * +-----------------------------------------
  179.              * | EN Notifications
  180.              * +-----------------------------------------
  181.              */
  182.             $fcmNotification->init(
  183.                 [],
  184.                 [
  185.                     'title' => $notification->getNotificationTitleEn(),
  186.                     'body' => $notification->getNotificationPreviewEn(),
  187.                     'data' => [
  188.                         'notification_type' => 4,
  189.                         'notification_id' => $notification->getId(),
  190.                         'page' => ($notification->getForwardTo() ? $notification->getForwardTo() : 0),
  191.                         'menuID' => 0,
  192.                     ],
  193.                 ],
  194.                 sprintf($this->getParameter('notifications_topic_post_basic'), $languageEn->getLanguageShortname()),
  195.                 true
  196.             );
  197.             $fcmNotification->send();
  198.             /*
  199.              * +-----------------------------------------
  200.              * | Mark notification as runned
  201.              * +-----------------------------------------
  202.              */
  203.             $notification->setRunnedAt(new DateTime());
  204.             $em->persist($notification);
  205.             $em->flush();
  206.         }
  207.         return $this->jsonResponse();
  208.     }
  209.     /**
  210.      * @Route("/objective_notifications", name="objective_notifications", methods={"GET"})
  211.      */
  212.     public function objectiveNotificationsAction(
  213.         FcmNotifications $fcmNotification,
  214.         ObjectiveSetter        $objectiveSetter,
  215.         EntityManagerInterface $em
  216.     )
  217.     {
  218.         $hour date('G');
  219.         if ($hour || $hour 19) {
  220.             return $this->errorJsonResponse(
  221.                 [
  222.                     'message' => 'Out of program',
  223.                 ]
  224.             );
  225.         }
  226.         $notifications $em
  227.             ->getRepository(Objectives::class)
  228.             ->findNotificationsToBeSent();
  229.         if (count($notifications)) {
  230.             foreach ($notifications as $notification) {
  231.                 $user $em->getRepository(Users::class)->findOneBy(['id' => $notification['userId']]);
  232.                 $template $em
  233.                     ->getRepository(NotificationTemplates::class)
  234.                     ->findOneBy(
  235.                         [
  236.                             'notificationType' => 1,
  237.                             'category' => $notification['notificationCategory'],
  238.                             'removedAt' => null,
  239.                         ]
  240.                     );
  241.                 if ($template) {
  242.                     $title = ($user->getLang() == 'ro' $template->getNotificationTitle() : $template->getNotificationTitleEn());
  243.                     $tokens $em->getRepository(UserFcmTokens::class)->findUserTokensList(
  244.                         $notification['userId']
  245.                     );
  246.                     // parse template
  247.                     $template $this->parseTemplate(
  248.                         $user->getLang() == 'ro' $template->getNotificationBody() : $template->getNotificationBodyEn(),
  249.                         $notification
  250.                     );
  251.                     // save history
  252.                     $uNotification = new UserNotifications();
  253.                     $uNotification->setUserId($user->getId());
  254.                     $uNotification->setNotificationTitle($title);
  255.                     $uNotification->setNotificationBody($template);
  256.                     $uNotification->setNotificationPreview($this->clearPreviewText($template110));
  257.                     $uNotification->setCreatedAt(new DateTime());
  258.                     $em->persist($uNotification);
  259.                     $em->flush();
  260.                     $fcmNotification->init(
  261.                         $tokens,
  262.                         [
  263.                             'title' => $title,
  264.                             'body' => $this->clearPreviewText($templatenull),
  265.                             'data' => [
  266.                                 'notification_id' => $uNotification->getId(),
  267.                                 'notification_type' => 4,
  268.                                 'menuID' => 0,
  269.                                 'page' => 999,
  270.                             ],
  271.                         ]
  272.                     );
  273.                     $fcmNotification->send();
  274.                     // set notification as sent
  275.                     $objectiveSetter->notificationSent($notification['userId']);
  276.                 }
  277.             }
  278.         }
  279.         return $this->jsonResponse();
  280.     }
  281.     private function parseTemplate($template$objective)
  282.     {
  283.         $weight $objective['weight'] - $objective['objectiveWeight'];
  284.         $template html_entity_decode($templateENT_QUOTES'UTF-8');
  285.         return str_replace('%weeks%'$weight$template);
  286.     }
  287.     private function clearPreviewText($text$numchars$addElipsis false)
  288.     {
  289.         // Remove the HTML tags
  290.         $html strip_tags($text);
  291.         // Convert HTML entities to single characters
  292.         //        $html = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
  293.         // Make the string the desired number of characters
  294.         // Note that substr is not good as it counts by bytes and not characters
  295.         $html mb_substr($html0$numchars'UTF-8');
  296.         $html preg_replace('/\s+/'' 'trim($html));
  297.         $html html_entity_decode($html);
  298.         // Add an elipsis
  299.         $html .= ($addElipsis "…" '');
  300.         return $html;
  301.     }
  302.     /**
  303.      * @Route("/composed_notifications", name="composed_notifications", methods={"GET"})
  304.      */
  305.     public function composedNotificationsAction(
  306.         FcmNotifications $fcmNotification,
  307.         ComposedNotification $composer,
  308.         EntityManagerInterface $em
  309.     )
  310.     {
  311.         $languageRo $em->getRepository(Language::class)->findOneBy(['language_shortname' => 'ro']);
  312.         $languageEn $em->getRepository(Language::class)->findOneBy(['language_shortname' => 'en']);
  313.         $composed $composer->prepareNotification($languageRo);
  314.         $translated $composer->prepareTranslatedNotification($languageEn);
  315.         $notification = new ScheduledNotifications();
  316.         $notification->setNotificationTitle($composed->getTitle());
  317.         $notification->setNotificationTitleEn($translated->getTitle());
  318.         $notification->setNotificationBody($composed->getBody());
  319.         $notification->setNotificationBodyEn($translated->getBody());
  320.         $notification->setNotificationPreview($this->clearPreviewText($composed->getBody(), 110));
  321.         $notification->setNotificationPreviewEn($this->clearPreviewText($translated->getBody(), 110));
  322.         $notification->setForwardTo(null);
  323.         $notification->setCreatedAt(new DateTime());
  324.         $notification->setScheduledAt(new DateTime());
  325.         $notification->setRunnedAt(new DateTime());
  326.         $notification->setRemovedAt(null);
  327.         $notification->setProUsers(true);
  328.         $em->persist($notification);
  329.         $em->flush();
  330.         dd($notification);
  331.         /*
  332.          * +-----------------------------------------
  333.          * | RO Notifications
  334.          * +-----------------------------------------
  335.          */
  336.         $fcmNotification->init(
  337.             [],
  338.             [
  339.                 'title' => $composed->getTitle(),
  340.                 'body' => $composed->getTitle(),
  341.                 'data' => [
  342.                     'notification_type' => 4,
  343.                     'notification_id' => $notification->getId(),
  344.                     'page' => 0,
  345.                     'menuID' => 0,
  346.                 ],
  347.             ],
  348.             sprintf($this->getParameter('notifications_topic_post_pro'), $languageRo->getLanguageShortname()),
  349.             true
  350.         );
  351.         $fcmNotification->send();
  352.         /*
  353.          * +-----------------------------------------
  354.          * | EN Notifications
  355.          * +-----------------------------------------
  356.          */
  357.         $fcmNotification->init(
  358.             [],
  359.             [
  360.                 'title' => $composed->getTitle(),
  361.                 'body' => $composed->getTitle(),
  362.                 'data' => [
  363.                     'notification_type' => 4,
  364.                     'notification_id' => $notification->getId(),
  365.                     'page' => 0,
  366.                     'menuID' => 0,
  367.                 ],
  368.             ],
  369.             sprintf($this->getParameter('notifications_topic_post_pro'), $languageEn->getLanguageShortname()),
  370.             true
  371.         );
  372.         $fcmNotification->send();
  373.         return $this->jsonResponse();
  374.     }
  375. }