<?php
namespace App\Controller\Cronjobs;
use App\Controller\Response;
use App\Entity\FavouriteMenus;
use App\Entity\FavouriteMenusSessions;
use App\Entity\Language;
use App\Entity\NotificationTemplates;
use App\Entity\Objectives;
use App\Entity\ScheduledNotifications;
use App\Entity\UserFcmTokens;
use App\Entity\UserNotifications;
use App\Entity\Users;
use App\Services\Notifications\ComposedNotification;
use App\Services\Notifications\FcmNotifications;
use App\Services\Objectives\ObjectiveSetter;
use App\Traits\TextTrait;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* @Route("/cronjobs/notifications", name="cronjobs_notifications_")
*/
class NotificationsController extends AbstractController
{
use Response;
use TextTrait;
/**
* @Route("/next_day_menu", name="next_day_menu", methods={"GET"})
*/
public function nextDayMenuAction(
FcmNotifications $fcmNotification,
TranslatorInterface $translator,
EntityManagerInterface $em
)
{
$sessions = $em->getRepository(FavouriteMenusSessions::class)
->findLastUserSessions();
if ($sessions) {
foreach ($sessions as $session) {
$menu = $em->getRepository(FavouriteMenus::class)
->findNextDayMenuNotification($session['userId'], $session['id']);
if ($menu) {
$listTokens = $em->getRepository(UserFcmTokens::class)->findUserTokensList(
$session['userId']
);
$fcmNotification->init(
$listTokens,
[
'title' => $translator->trans('Information', [], 'messages', $session['lang']),
'body' => $translator->trans('Next day notification', [], 'messages', $session['lang']),
'data' => [
'menuID' => $menu->getMenuId(),
],
]
);
$fcmNotification->send();
$menu->setNotifiedAt(new DateTime());
$em->persist($menu);
}
}
$em->flush();
}
return $this->jsonResponse();
}
/**
* @Route("/buy_now", name="buy_now", methods={"GET"})
*/
public function buyNowAction(
FcmNotifications $fcmNotification,
TranslatorInterface $translator,
EntityManagerInterface $em
)
{
$users = $em->getRepository(Users::class)
->getUsersByRegistrationDate(3);
if ($users) {
foreach ($users as $user) {
$listTokens = $em->getRepository(UserFcmTokens::class)->findUserTokensList(
$user->getId()
);
$fcmNotification->init(
$listTokens,
[
'title' => $translator->trans('Information', [], 'messages', $user->getLang()),
'body' => $translator->trans('Buy now notification', [], 'messages', $user->getLang()),
'data' => [
'menuID' => -1,
],
]
);
$fcmNotification->send();
}
}
return $this->jsonResponse();
}
/**
* @Route("/video", name="video", methods={"GET"})
*/
public function videoNotificationAction(
FcmNotifications $fcmNotification,
TranslatorInterface $translator,
EntityManagerInterface $em
)
{
$users = $em->getRepository(Users::class)
->getUsersCreatedByInterval(3);
if ($users) {
$today = new DateTime(\date("Y-m-d"));
foreach ($users as $user) {
if (!$user->getLastNotification() || $user->getLastNotification() < $today) {
$listTokens = $em->getRepository(UserFcmTokens::class)->findUserTokensList(
$user->getId()
);
$fcmNotification->init(
$listTokens,
[
'title' => $translator->trans('Information', [], 'messages', $user->getLang()),
'body' => $translator->trans('Video Notification', [], 'messages', $user->getLang()),
'data' => [
'notification_type' => 3, // video
],
]
);
$fcmNotification->send();
// save last notification date
$user->setLastNotification(new DateTime());
$em->persist($user);
$em->flush();
}
}
}
return $this->jsonResponse();
}
/**
* @Route("/scheduled_notifications", name="scheduled_notifications", methods={"GET"})
*/
public function scheduledNotificationsAction(
FcmNotifications $fcmNotification,
EntityManagerInterface $em
)
{
$languageRo = $em->getRepository(Language::class)->findOneBy(['language_shortname' => 'ro']);
$languageEn = $em->getRepository(Language::class)->findOneBy(['language_shortname' => 'en']);
$notification = $em->createQueryBuilder()
->select('sn')
->from(ScheduledNotifications::class, 'sn')
->where('sn.removedAt IS NULL AND sn.runnedAt IS NULL AND sn.scheduledAt <= :scheduled AND sn.pro_users = 0')
->setParameter('scheduled', (new DateTime())->format('Y-m-d H:i:s'))
->orderBy('sn.scheduledAt', 'ASC')
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
if ($notification) {
/*
* +-----------------------------------------
* | RO Notifications
* +-----------------------------------------
*/
$fcmNotification->init(
[],
[
'title' => $notification->getNotificationTitle(),
'body' => $notification->getNotificationPreview(),
'data' => [
'notification_type' => 4,
'notification_id' => $notification->getId(),
'page' => ($notification->getForwardTo() ? $notification->getForwardTo() : 0),
'menuID' => 0,
],
],
sprintf($this->getParameter('notifications_topic_post_basic'), $languageRo->getLanguageShortname()),
true
);
$fcmNotification->send();
/*
* +-----------------------------------------
* | EN Notifications
* +-----------------------------------------
*/
$fcmNotification->init(
[],
[
'title' => $notification->getNotificationTitleEn(),
'body' => $notification->getNotificationPreviewEn(),
'data' => [
'notification_type' => 4,
'notification_id' => $notification->getId(),
'page' => ($notification->getForwardTo() ? $notification->getForwardTo() : 0),
'menuID' => 0,
],
],
sprintf($this->getParameter('notifications_topic_post_basic'), $languageEn->getLanguageShortname()),
true
);
$fcmNotification->send();
/*
* +-----------------------------------------
* | Mark notification as runned
* +-----------------------------------------
*/
$notification->setRunnedAt(new DateTime());
$em->persist($notification);
$em->flush();
}
return $this->jsonResponse();
}
/**
* @Route("/objective_notifications", name="objective_notifications", methods={"GET"})
*/
public function objectiveNotificationsAction(
FcmNotifications $fcmNotification,
ObjectiveSetter $objectiveSetter,
EntityManagerInterface $em
)
{
$hour = date('G');
if ($hour < 8 || $hour > 19) {
return $this->errorJsonResponse(
[
'message' => 'Out of program',
]
);
}
$notifications = $em
->getRepository(Objectives::class)
->findNotificationsToBeSent();
if (count($notifications)) {
foreach ($notifications as $notification) {
$user = $em->getRepository(Users::class)->findOneBy(['id' => $notification['userId']]);
$template = $em
->getRepository(NotificationTemplates::class)
->findOneBy(
[
'notificationType' => 1,
'category' => $notification['notificationCategory'],
'removedAt' => null,
]
);
if ($template) {
$title = ($user->getLang() == 'ro' ? $template->getNotificationTitle() : $template->getNotificationTitleEn());
$tokens = $em->getRepository(UserFcmTokens::class)->findUserTokensList(
$notification['userId']
);
// parse template
$template = $this->parseTemplate(
$user->getLang() == 'ro' ? $template->getNotificationBody() : $template->getNotificationBodyEn(),
$notification
);
// save history
$uNotification = new UserNotifications();
$uNotification->setUserId($user->getId());
$uNotification->setNotificationTitle($title);
$uNotification->setNotificationBody($template);
$uNotification->setNotificationPreview($this->clearPreviewText($template, 110));
$uNotification->setCreatedAt(new DateTime());
$em->persist($uNotification);
$em->flush();
$fcmNotification->init(
$tokens,
[
'title' => $title,
'body' => $this->clearPreviewText($template, null),
'data' => [
'notification_id' => $uNotification->getId(),
'notification_type' => 4,
'menuID' => 0,
'page' => 999,
],
]
);
$fcmNotification->send();
// set notification as sent
$objectiveSetter->notificationSent($notification['userId']);
}
}
}
return $this->jsonResponse();
}
private function parseTemplate($template, $objective)
{
$weight = $objective['weight'] - $objective['objectiveWeight'];
$template = html_entity_decode($template, ENT_QUOTES, 'UTF-8');
return str_replace('%weeks%', $weight, $template);
}
private function clearPreviewText($text, $numchars, $addElipsis = false)
{
// Remove the HTML tags
$html = strip_tags($text);
// Convert HTML entities to single characters
// $html = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
// Make the string the desired number of characters
// Note that substr is not good as it counts by bytes and not characters
$html = mb_substr($html, 0, $numchars, 'UTF-8');
$html = preg_replace('/\s+/', ' ', trim($html));
$html = html_entity_decode($html);
// Add an elipsis
$html .= ($addElipsis ? "…" : '');
return $html;
}
/**
* @Route("/composed_notifications", name="composed_notifications", methods={"GET"})
*/
public function composedNotificationsAction(
FcmNotifications $fcmNotification,
ComposedNotification $composer,
EntityManagerInterface $em
)
{
$languageRo = $em->getRepository(Language::class)->findOneBy(['language_shortname' => 'ro']);
$languageEn = $em->getRepository(Language::class)->findOneBy(['language_shortname' => 'en']);
$composed = $composer->prepareNotification($languageRo);
$translated = $composer->prepareTranslatedNotification($languageEn);
$notification = new ScheduledNotifications();
$notification->setNotificationTitle($composed->getTitle());
$notification->setNotificationTitleEn($translated->getTitle());
$notification->setNotificationBody($composed->getBody());
$notification->setNotificationBodyEn($translated->getBody());
$notification->setNotificationPreview($this->clearPreviewText($composed->getBody(), 110));
$notification->setNotificationPreviewEn($this->clearPreviewText($translated->getBody(), 110));
$notification->setForwardTo(null);
$notification->setCreatedAt(new DateTime());
$notification->setScheduledAt(new DateTime());
$notification->setRunnedAt(new DateTime());
$notification->setRemovedAt(null);
$notification->setProUsers(true);
$em->persist($notification);
$em->flush();
dd($notification);
/*
* +-----------------------------------------
* | RO Notifications
* +-----------------------------------------
*/
$fcmNotification->init(
[],
[
'title' => $composed->getTitle(),
'body' => $composed->getTitle(),
'data' => [
'notification_type' => 4,
'notification_id' => $notification->getId(),
'page' => 0,
'menuID' => 0,
],
],
sprintf($this->getParameter('notifications_topic_post_pro'), $languageRo->getLanguageShortname()),
true
);
$fcmNotification->send();
/*
* +-----------------------------------------
* | EN Notifications
* +-----------------------------------------
*/
$fcmNotification->init(
[],
[
'title' => $composed->getTitle(),
'body' => $composed->getTitle(),
'data' => [
'notification_type' => 4,
'notification_id' => $notification->getId(),
'page' => 0,
'menuID' => 0,
],
],
sprintf($this->getParameter('notifications_topic_post_pro'), $languageEn->getLanguageShortname()),
true
);
$fcmNotification->send();
return $this->jsonResponse();
}
}