<?php
namespace App\Twig;
use App\Entity\Admin;
use App\Entity\Child;
use App\Entity\ChildPreference;
use App\Entity\Guardian;
use App\Entity\Lesson;
use App\Entity\Teacher;
use App\Entity\TeacherSurveyResponse;
use App\Repository\AdminRepository;
use App\Repository\ChildRepository;
use App\Repository\GuardianRepository;
use App\Repository\InfoLineRepository;
use App\Repository\LessonRepository;
use App\Repository\Notification\NotificationRepository;
use App\Repository\Notification\UserNotificationRepository;
use App\Repository\TeacherRepository;
use App\Repository\TeacherSurveyResponseRepository;
use App\Service\LearnCubeService;
use App\Service\TeacherFirstLessonReviewService;
use Symfony\Component\Asset\Packages;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Twig\Extension\RuntimeExtensionInterface;
class NotificationExtensionRuntime implements RuntimeExtensionInterface
{
private TokenStorageInterface $tokenStorage;
private LessonRepository $lessonRepository;
private LearnCubeService $learnCubeService;
private NotificationRepository $notificationRepository;
private UserNotificationRepository $userNotificationRepository;
private AdminRepository $adminRepository;
private TeacherRepository $teacherRepository;
private ChildRepository $childRepository;
private GuardianRepository $guardianRepository;
private Packages $assetsManager;
private TeacherSurveyResponseRepository $teacherSurveyResponseRepository;
private InfoLineRepository $infoLineRepository;
private TeacherFirstLessonReviewService $teacherFirstLessonReviewService;
public function __construct(TokenStorageInterface $tokenStorage,
LessonRepository $lessonRepository,
LearnCubeService $learnCubeService,
NotificationRepository $notificationRepository,
UserNotificationRepository $userNotificationRepository,
AdminRepository $adminRepository,
TeacherRepository $teacherRepository,
ChildRepository $childRepository,
GuardianRepository $guardianRepository,
Packages $assetsManager,
TeacherSurveyResponseRepository $teacherSurveyResponseRepository,
InfoLineRepository $infoLineRepository,
TeacherFirstLessonReviewService $teacherFirstLessonReviewService
)
{
$this->tokenStorage = $tokenStorage;
$this->lessonRepository = $lessonRepository;
$this->learnCubeService = $learnCubeService;
$this->notificationRepository = $notificationRepository;
$this->userNotificationRepository = $userNotificationRepository;
$this->adminRepository = $adminRepository;
$this->teacherRepository = $teacherRepository;
$this->childRepository = $childRepository;
$this->guardianRepository = $guardianRepository;
$this->assetsManager = $assetsManager;
$this->teacherSurveyResponseRepository = $teacherSurveyResponseRepository;
$this->infoLineRepository = $infoLineRepository;
$this->teacherFirstLessonReviewService = $teacherFirstLessonReviewService;
}
public function getInfoLines()
{
$user = $this->tokenStorage->getToken()->getUser();
$infoLines = $this->infoLineRepository->findBy(['active' => true], ['id' => 'DESC']);
foreach ($infoLines as $key => $infoLine) {
if($user instanceof Admin && !in_array('admin',$infoLine->getReceivers())) {
unset($infoLines[$key]);
}
if($user instanceof Guardian && !in_array('guardian',$infoLine->getReceivers())) {
unset($infoLines[$key]);
}
if($user instanceof Child && !in_array('child',$infoLine->getReceivers())) {
unset($infoLines[$key]);
}
if($user instanceof Teacher && !in_array('teacher',$infoLine->getReceivers())) {
unset($infoLines[$key]);
}
}
return $infoLines;
}
public function getTeacherFirstLessonSurveyData()
{
/** @var Teacher $teacher */
$teacher = $this->tokenStorage->getToken()->getUser();
foreach ($teacher->getChildPreferences() as $childPreference)
{
// dump($childPreference->getDiscipline());
// die();
$surveyAnswered = false;
/** @var Lesson $lesson */
$lesson = $this->teacherFirstLessonReviewService->findFirstActualLesson(
$teacher,
$childPreference->getChild(),
$childPreference->getDiscipline()
);
// if(!$lesson || $lesson->getStartTime()->format('Y-m-d') != (new \DateTime('now'))->format('Y-m-d'))
// {
// continue;
// }
if(!$lesson || $lesson->getStartTime() <= (new \DateTime('-2 days')))
{
continue;
}
// dump($lesson->getStartTime());
// dump((new \DateTime('-2 days')));
// dump($lesson);
// die();
$firstDayComments = $this->teacherFirstLessonReviewService->findReviewsAfterLesson(
$teacher,
$lesson->getChild(),
$lesson->getStartTime()
);
$filled = '';
foreach ($firstDayComments as $comment)
{
if($this->teacherFirstLessonReviewService->isReviewFilled($comment))
{
$surveyAnswered = true;
}
$filled = $comment->getComment();
}
if($lesson && !$surveyAnswered)
{
// dump($lesson);die();
$surveyData = [];
$identifier = $childPreference->getChild()->getId() . '-' . $childPreference->getDiscipline()->getId();
$surveyData[$identifier] = [
'child' => ['id' => $childPreference->getChild()->getId(), 'name' => $childPreference->getChild()->getFullname(), 'class' => $childPreference->getChild()->getClass()],
'discipline' => ['id' => $childPreference->getDiscipline()->getId(), 'name' => $childPreference->getDiscipline()->getName(), 'displayName' => $childPreference->getDiscipline()->getDisplayName()],
'guardian' => ['id' => $childPreference->getChild()->getGuardian()->getId(), 'phone' => $childPreference->getChild()->getGuardian()->getPhoneNumber()],
'filled' => $filled,
'filled_count' => count(array_filter(explode(' ', $filled)))
];
return $surveyData;
}
}
// die();
return [];
}
public function getTeacherLastLessonSurveyData()
{
/** @var Teacher $teacher */
$teacher = $this->tokenStorage->getToken()->getUser();
$query = $this->teacherSurveyResponseRepository->createQueryBuilder('s');
$lastDayLessons = $query
->where('s.teacher = :teacher')
->setParameter('teacher', $teacher)
->andWhere('s.lastLesson = 1')
->andWhere('s.comment IS NULL')
->andWhere('s.dateTo >= :current')
->andWhere('s.dateFrom <= :current')
->setParameter('current', new \DateTime())
->orderBy('s.createdAt', 'ASC')
->setMaxResults(1)
->getQuery()
->getResult();
$surveyData = [];
/**
* @var TeacherSurveyResponse $item
*/
foreach ($lastDayLessons as $item) {
$identifier = $item->getChild()->getId() . '-' . $item->getDiscipline()->getId();
$surveyData[$identifier] = [
'child' => ['id' => $item->getChild()->getId(), 'name' => $item->getChild()->getFullname(), 'class' => $item->getChild()->getClass()],
'discipline' => ['id' => $item->getDiscipline()->getId(), 'name' => $item->getDiscipline()->getName()],
'guardian' => ['id' => $item->getChild()->getGuardian()->getId()],
'filled' => '',
'filled_count' => 0
];
}
return $surveyData;
}
public function getNewestLessons()
{
$user = $this->tokenStorage->getToken()->getUser();
$query = $this->lessonRepository->createQueryBuilder('l');
//Disable all lessons exept allowed oned
$query
->leftJoin('l.teacher', 'teacher')
->andWhere('teacher.unickoFunction = :unickoFunction')
->setParameter('unickoFunction', 1);
if (!$user || in_array('ROLE_TEACHER_REGISTER',$user->getRoles())) {
return ['lessons'=>[], 'learncubeUser' => null];
}
if (in_array('ROLE_GUARDIAN', $user->getRoles())) {
$learnCubeUser = $this->learnCubeService->tag_child;
$query
->leftJoin('l.children', 'c')
->andWhere('c.guardian = :guardian')
->setParameter('guardian', $user);
}
if (in_array('ROLE_TEACHER', $user->getRoles())) {
$learnCubeUser = $this->learnCubeService->tag_teacher;
$query
->andWhere('l.teacher = :teacher')
->setParameter('teacher', $user)
->setMaxResults(1);
}
if (in_array('ROLE_ADMIN', $user->getRoles())) {
return ['lessons'=>[]];
}
if (in_array('ROLE_CHILD', $user->getRoles())) {
$learnCubeUser = $this->learnCubeService->tag_child;
/**
* @var Child $child
*/
$query
->andWhere(':children member of l.children')
->setParameter('children', $user)
->setMaxResults(1);
}
$dateNow = new \DateTime();
$dateNow->modify('-4 hour');
$dateEnd = new \DateTime();
$dateEnd->modify('+4 hour');
$dateEnd->modify('+1 minutes');
$dateDeadline = new \DateTime();
$dateDeadline->modify('-5 minutes');
$lessons = $query
->andWhere('l.startTime >= :startTime')
->setParameter('startTime', $dateNow)
->andWhere("DATE_SUB(l.endTime, l.duration, 'MINUTE') <= :endTime")
->andWhere("l.endTime >= :dateDeadline")
->andWhere("l.childMissed = 0")
->andWhere("l.teacherMissed = 0")
->setParameter('endTime', $dateEnd)
->setParameter('dateDeadline', $dateDeadline)
->orderBy('l.startTime')
->getQuery()
->getResult();
if($lessons && count($lessons) > 1) {
$addedChilds = [];
$lessonsToShow = [];
foreach ($lessons as $lesson)
{
if(!in_array($lesson->getChild()->getId(), $addedChilds))
{
$addedChilds[] = $lesson->getChild()->getId();
$lessonsToShow[] = $lesson;
}
}
$lessons = $lessonsToShow;
}
return [
'lessons' => $lessons,
'learncubeUser' => $learnCubeUser,
'learncubeTagLesson' => $this->learnCubeService->tag_lesson,
'learncubePublicKey' => $this->learnCubeService->publicKey,
];
}
public function getNotificationCount()
{
if (!$token = $this->tokenStorage->getToken()) {
return;
}
if (!$token->isAuthenticated()) {
return;
}
if (!$user = $token->getUser()) {
return;
}
if ($user instanceof Teacher) {
/**
* @var Teacher $teacher
*/
$teacher = $user;
$count = 0;
foreach ($teacher->getChildPreferences() as $childPreference) {
if ($childPreference->getStatus() == ChildPreference::STATUS_ASSIGNED['value']) {
$count++;
}
}
return $count;
}
}
public function getNewNotificationCount()
{
if (!$token = $this->tokenStorage->getToken()) {
return;
}
if (!$token->isAuthenticated()) {
return;
}
if (!$user = $token->getUser()) {
return;
}
if ($user instanceof Teacher) {
/**
* @var Teacher $teacher
*/
$teacher = $user;
$count = 0;
foreach ($teacher->getChildPreferences() as $childPreference) {
if ($childPreference->getAcceptedAt() >= (new \DateTime())->modify('-72 hours')) {
$count++;
}
}
return $count;
}
}
public function getUserNotificationData()
{
if (!$token = $this->tokenStorage->getToken()) {
return;
}
if (!$token->isAuthenticated()) {
return;
}
if (!$user = $token->getUser()) {
return;
}
$userType = null;
if ($user instanceof Teacher) {
$userType = 'teacher';
}
if ($user instanceof Admin) {
$userType = 'admin';
}
if ($user instanceof Guardian) {
$userType = 'guardian';
}
if ($user instanceof Child) {
$userType = 'child';
}
$query = $this->userNotificationRepository->createQueryBuilder('n');
$newCount = $query
->select('count(n.id)')
->andWhere('n.userType = :userType')
->setParameter('userType', $userType)
->andWhere('n.userId = :userId')
->setParameter('userId', $user->getId())
->andWhere('n.seen = :seen')
->setParameter('seen', 0)
->leftJoin('n.notification', 'notification')
->andWhere('notification.isDeleted = :isDeleted')
->setParameter('isDeleted', 0)
->getQuery()
->getSingleScalarResult();
$query = $this->notificationRepository->createQueryBuilder('n');
$notifications = $query
->leftJoin('n.users', 'u')
->andWhere('u.userType = :userType')
->setParameter('userType', $userType)
->andWhere('u.userId = :userId')
->setParameter('userId', $user->getId())
->setMaxResults(5)
->orderBy('n.dateAdd', 'DESC')
->getQuery()
->getResult();
foreach ($notifications as $key => $notificationItem)
{
$query = $this->userNotificationRepository->createQueryBuilder('u');
$userNotification = $query
->andWhere('u.userType = :userType')
->setParameter('userType', $userType)
->andWhere('u.userId = :userId')
->setParameter('userId', $user->getId())
->andWhere('u.notification = :notification')
->setParameter('notification', $notificationItem->getId())
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
if($userNotification->isSeen()) {
$notifications[$key]->seen = true;
}
$createdByUserType = $notificationItem->getCreatedByUserType();
$createdByUserId = $notificationItem->getCreatedByUserId();
$createdBy = null;
if ($createdByUserType == 'admin') {
$createdBy = $this->adminRepository->find($createdByUserId);
}
elseif ($createdByUserType == 'teacher') {
$createdBy = $this->teacherRepository->find($createdByUserId);
}
elseif ($createdByUserType == 'guardian') {
$createdBy = $this->guardianRepository->find($createdByUserId);
}
elseif ($createdByUserType == 'child') {
$createdBy = $this->childRepository->find($createdByUserId);
}
if($createdByUserType == 'admin')
{
$notifications[$key]->{'createdBy'} = [
'fullname' => 'Administracija',
'email' => 'info@corepetitus.lt',
'profileImagePath' => $this->assetsManager->getUrl('assets/images/core-logo-min.png')
];
} else {
$notifications[$key]->{'createdBy'} = [
'fullname' => $createdBy->getFullname(),
'email' => $createdBy->getEmail(),
'profileImagePath' => $createdBy->getProfileImagePath()
];
}
if(!$notifications[$key]->createdBy['profileImagePath'])
{
$notifications[$key]->createdBy['profileImagePath'] = '/uploads/profile-placeholder.png';
}
}
$notificationsData = [
'new_count' => $newCount,
'notifications' => $notifications
];
return $notificationsData;
}
public function getUserNotificationCount()
{
if (!$token = $this->tokenStorage->getToken()) {
return;
}
if (!$token->isAuthenticated()) {
return;
}
if (!$user = $token->getUser()) {
return;
}
$userType = null;
if ($user instanceof Teacher) {
$userType = 'teacher';
}
if ($user instanceof Admin) {
$userType = 'admin';
}
if ($user instanceof Guardian) {
$userType = 'guardian';
}
if ($user instanceof Child) {
$userType = 'child';
}
$query = $this->userNotificationRepository->createQueryBuilder('n');
$newCount = $query
->select('count(n.id)')
->andWhere('n.userType = :userType')
->setParameter('userType', $userType)
->andWhere('n.userId = :userId')
->setParameter('userId', $user->getId())
->andWhere('n.seen = :seen')
->setParameter('seen', 0)
->leftJoin('n.notification', 'notification')
->andWhere('notification.isDeleted = :isDeleted')
->setParameter('isDeleted', 0)
->getQuery()
->getSingleScalarResult();
return $newCount;
}
}