<?php
namespace EADPlataforma\Repository;
use EADPlataforma\Entity\Enrollment;
use EADPlataforma\Entity\Course;
use EADPlataforma\Entity\Library;
use EADPlataforma\Entity\Lesson;
use EADPlataforma\Entity\LessonLog;
use EADPlataforma\Entity\LessonLogOrigin;
use EADPlataforma\Entity\LessonModule;
use EADPlataforma\Entity\LessonSupport;
use EADPlataforma\Entity\LessonAnnotation;
use EADPlataforma\Entity\Exam;
use EADPlataforma\Entity\ExamUser;
use EADPlataforma\Entity\CourseTeam;
use EADPlataforma\Entity\CourseTestimonial;
use EADPlataforma\Entity\CourseCertificate;
use EADPlataforma\Entity\UserSubscription;
use EADPlataforma\Entity\Product;
use EADPlataforma\Entity\ProductOffer;
use EADPlataforma\Entity\User;
use EADPlataforma\Entity\Trash;
use EADPlataforma\Enum\ExamEnum;
use EADPlataforma\Enum\CourseEnum;
use EADPlataforma\Enum\CourseTestimonialEnum;
use EADPlataforma\Enum\CourseCertificateEnum;
use EADPlataforma\Enum\ExamUserEnum;
use EADPlataforma\Enum\GroupEnum;
use EADPlataforma\Enum\LessonEnum;
use EADPlataforma\Enum\EnrollmentEnum;
use EADPlataforma\Enum\UserSubscriptionEnum;
use EADPlataforma\Enum\LessonAnnotationEnum;
use EADPlataforma\Enum\LessonSupportEnum;
use EADPlataforma\Enum\ProductEnum;
use EADPlataforma\Enum\NotificationEnum;
use EADPlataforma\Enum\UserEnum;
use EADPlataforma\Enum\TagsMarketingEnum;
use EADPlataforma\Enum\WebhookEnum;
/**
* @method Enrollment|null find($id, $lockMode = null, $lockVersion = null)
* @method Enrollment|null findOneBy(array $criteria, array $orderBy = null)
* @method Enrollment[] findAll()
* @method Enrollment[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class EnrollmentRepository extends AbstractRepository
{
public function getEntityClass(){
return Enrollment::class;
}
public function getConnectionName(){
return "school";
}
public function findItems()
{
return $this->createQueryBuilder('e')->getQuery()->getResult();
}
public function getStringStatus($status){
$string = '';
switch ($status) {
case EnrollmentEnum::STATUS_ACTIVE:
$string = $this->configuration->getLanguage('active', 'enrollments');
break;
case EnrollmentEnum::STATUS_EXPIRED:
$string = $this->configuration->getLanguage('expired', 'enrollments');
break;
case EnrollmentEnum::STATUS_SUSPENDED:
$string = $this->configuration->getLanguage('suspended', 'enrollments');
break;
case EnrollmentEnum::STATUS_CANCELED:
$string = $this->configuration->getLanguage('canceled', 'enrollments');
break;
}
return $string;
}
public function getOriginString($origin){
$string = '';
switch ($origin) {
case EnrollmentEnum::ORIGIN_FREE:
$string = $this->configuration->getLanguage('free', 'enrollments');
break;
case EnrollmentEnum::ORIGIN_SALE:
$string = $this->configuration->getLanguage('sale', 'enrollments');
break;
case EnrollmentEnum::ORIGIN_SUBSCRIPTION:
$string = $this->configuration->getLanguage('subscription', 'enrollments');
break;
case EnrollmentEnum::ORIGIN_GROUP:
$string = $this->configuration->getLanguage('group', 'enrollments');
break;
case EnrollmentEnum::ORIGIN_COUPOM:
$string = $this->configuration->getLanguage('coupom', 'enrollments');
break;
case EnrollmentEnum::ORIGIN_API:
$string = 'API';
break;
case EnrollmentEnum::ORIGIN_CHARGE:
$string = $this->configuration->getLanguage('charge', 'enrollments');
break;
}
return $string;
}
public function getEnrollmentOrigins(){
$data = [
(object)[
"id" => EnrollmentEnum::ORIGIN_FREE,
"title" => $this->configuration->getLanguage('free', 'enrollments'),
"selected" => EnrollmentEnum::NO,
],
(object)[
"id" => EnrollmentEnum::ORIGIN_SALE,
"title" => $this->configuration->getLanguage('sale', 'enrollments'),
"selected" => EnrollmentEnum::NO,
],
(object)[
"id" => EnrollmentEnum::ORIGIN_SUBSCRIPTION,
"title" => $this->configuration->getLanguage('subscription', 'enrollments'),
"selected" => EnrollmentEnum::NO,
],
(object)[
"id" => EnrollmentEnum::ORIGIN_GROUP,
"title" => $this->configuration->getLanguage('group', 'enrollments'),
"selected" => EnrollmentEnum::NO,
],
(object)[
"id" => EnrollmentEnum::ORIGIN_COUPOM,
"title" => $this->configuration->getLanguage('coupom', 'enrollments'),
"selected" => EnrollmentEnum::NO,
],
(object)[
"id" => EnrollmentEnum::ORIGIN_API,
"title" => "API",
"selected" => EnrollmentEnum::NO,
],
(object)[
"id" => EnrollmentEnum::ORIGIN_CHARGE,
"title" => $this->configuration->getLanguage('charge', 'enrollments'),
"selected" => EnrollmentEnum::NO,
],
];
return $data;
}
public function sendWebhook(Enrollment $enrollment)
{
$user = $enrollment->getUser();
$course = $enrollment->getCourse();
$userWebhook = $this->em->getRepository(User::class)->getToWebhook($user);
$dataObj = (object)[
"user" => $userWebhook,
"course" => (object)[
"id" => (string)$course->getId(),
"name" => $course->getTitle(),
"workload" => $course->getWorkload(),
],
"enrollment" => $enrollment->toWebhook(),
];
if ($enrollment->getGroup()) {
$dataObj->group = (object)[
"id" => (string)$enrollment->getGroup()->getId(),
"name" => $enrollment->getGroup()->getName(),
];
};
$webhookService = $this->generalService->getService('WebhookService');
$webhookService->addItemList(WebhookEnum::ENROLLMENT, $dataObj);
return;
}
public function getPublicEnrollments(
$userId,
bool $onlyStarted = false,
$notCompleted = false
)
{
$query = $this->createQueryBuilder('e');
$query->innerJoin(
'EADPlataforma:Course', 'c', 'WITH', 'e.course = c AND c.deleted = 0'
);
$query->andWhere('e.user = :userId');
$query->andWhere('e.deleted = 0');
$query->setParameter('userId', $userId);
if($onlyStarted){
$query->andWhere('e.lessonNumberComplete != 0');
}
$query->addOrderBy('e.id', 'DESC');
$data = $query->getQuery()->execute();
if($notCompleted){
$dataNotCompleted = [];
foreach ($data as $key => $enrollment) {
$historyMetrics = $this->getHistoryMetricsByEnrollment($enrollment->id);
if($historyMetrics->progress < 100){
$dataNotCompleted[] = $enrollment;
}
}
$data = $dataNotCompleted;
}
return $data;
}
public function getResumeEnrollment(
int $userId,
?array $situation = [],
?int $status = null,
?string $searchText = null,
?string $categories = null,
?int $offset = 0,
?int $limit = 10
)
{
$query = $this->createQueryBuilder('e');
$query->innerJoin(
'EADPlataforma:Course',
'c',
'WITH',
'e.course = c
AND c.deleted = :courseDeleted
AND c.status = :courseStatus
AND c.dateRelease <= :now'
);
$query->andWhere('e.user = :userId');
$query->andWhere('e.deleted = 0');
$situationWhere = [];
if(in_array(EnrollmentEnum::SITUATION_STARTED, $situation)){
$situationWhere[] = '
(
(e.lessonNumberComplete * 100)/c.numberLesson < 100
AND (e.lessonNumberComplete * 100)/c.numberLesson > 0
)';
}
if(in_array(EnrollmentEnum::SITUATION_NOT_STARTED, $situation)){
$situationWhere[] = '(
c.numberLesson = 0
OR (e.lessonNumberComplete * 100)/c.numberLesson <= 0
)';
}
if(in_array(EnrollmentEnum::SITUATION_COMPLETED, $situation)){
$situationWhere[] = '((e.lessonNumberComplete * 100)/c.numberLesson >= 100)';
}
$situationWhereString = "";
foreach ($situationWhere as $key => $value) {
$situationWhereString .= (empty($situationWhereString) ? $value : " OR {$value} " );
}
if(!empty($situationWhereString)){
$query->andWhere("({$situationWhereString})");
}
if(!empty($searchText)){
$query->andWhere('c.title LIKE :searchText');
$query->setParameter('searchText', '%'.$searchText.'%');
}
if(!empty($categories)){
$query->andWhere('c.category IN (:categories) ');
$query->setParameter('categories', $categories);
}
if(!empty($status)){
$query->andWhere('e.status = :status');
$query->andWhere('e.datePeriod >= :now');
$query->setParameter('status', $status);
$query->setParameter('now', date("Y-m-d H:i:s"));
}else{
$query->andWhere('e.status = :status');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
$courseRepository = $this->em->getRepository(Course::class);
$subQuery = $courseRepository->createQueryBuilder('c1');
$subQuery->select('c1.id');
$subQuery->innerJoin(
'EADPlataforma:Product',
'p',
'WITH',
'c1 MEMBER OF p.course'
);
$subQuery->andWhere('p.deleted = :productDeleted ');
$subQuery->andWhere('p.status = :productStatus');
$subQuery->andWhere('(
p.type = :productTypePeriod OR p.type = :productTypePeriodSupport
)');
$subQuery->andWhere('c1.deleted = :c1Deleted');
$subQuery->andWhere('c1.status = :c1Status');
$query->setParameter('c1Deleted', CourseEnum::ITEM_NO_DELETED);
$query->setParameter('c1Status', CourseEnum::PUBLISHED);
$query->setParameter('productDeleted', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('productStatus', ProductEnum::PUBLISHED);
$query->setParameter('productTypePeriod', ProductEnum::PERIOD);
$query->setParameter('productTypePeriodSupport', ProductEnum::PERIOD_SUPORT);
$subQuery = $subQuery->getDQL();
$exp = $query->expr()->in('e.course', $subQuery);
$query->andWhere("(e.datePeriod >= :now OR {$exp})");
$query->setParameter('now', date("Y-m-d H:i:s"));
}
$query->setParameter('userId', $userId);
$query->setParameter('courseStatus', CourseEnum::PUBLISHED);
$query->setParameter('courseDeleted', CourseEnum::ITEM_NO_DELETED);
$query->setFirstResult($offset);
if($limit != 0){
$query->setMaxResults($limit);
}
$query->addOrderBy('e.dateLastAccess', 'DESC');
$data = $query->getQuery()->execute();
return $data;
}
public function countResumeEnrollment(
int $userId,
?array $situation = [],
?int $status = null,
?string $searchText = null,
?string $categories = null
)
{
$query = $this->createQueryBuilder('e');
$query->select("count(e.id) AS total");
$query->innerJoin(
'EADPlataforma:Course',
'c',
'WITH',
'e.course = c
AND c.deleted = 0
AND c.status = :courseStatus
AND c.dateRelease <= :now'
);
$query->andWhere('e.user = :userId');
$query->andWhere('e.deleted = 0');
$situationWhere = [];
if(in_array(EnrollmentEnum::SITUATION_STARTED, $situation)){
$situationWhere[] = '
(
(e.lessonNumberComplete * 100)/c.numberLesson < 100
AND (e.lessonNumberComplete * 100)/c.numberLesson > 0
)';
}
if(in_array(EnrollmentEnum::SITUATION_NOT_STARTED, $situation)){
$situationWhere[] = '((e.lessonNumberComplete * 100)/c.numberLesson <= 0)';
}
if(in_array(EnrollmentEnum::SITUATION_COMPLETED, $situation)){
$situationWhere[] = '((e.lessonNumberComplete * 100)/c.numberLesson >= 100)';
}
$situationWhereString = "";
foreach ($situationWhere as $key => $value) {
$situationWhereString .= (empty($situationWhereString) ? $value : " OR {$value} " );
}
if(!empty($situationWhereString)){
$query->andWhere("({$situationWhereString})");
}
if(!empty($searchText)){
$query->andWhere('c.title LIKE :searchText');
$query->setParameter('searchText', '%'.$searchText.'%');
}
if(!empty($categories)){
$query->andWhere('c.category IN (:categories) ');
$query->setParameter('categories', $categories);
}
if(!empty($status)){
$query->andWhere('e.status = :status');
$query->andWhere('e.datePeriod >= :now');
$query->setParameter('status', $status);
$query->setParameter('now', date("Y-m-d H:i:s"));
}else{
$query->andWhere('e.status = :status');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
$courseRepository = $this->em->getRepository(Course::class);
$subQuery = $courseRepository->createQueryBuilder('c1');
$subQuery->select('c1.id');
$subQuery->innerJoin(
'EADPlataforma:Product',
'p',
'WITH',
'c1 MEMBER OF p.course'
);
$subQuery->andWhere('p.deleted = :productDeleted ');
$subQuery->andWhere('p.status = :productStatus');
$subQuery->andWhere('(
p.type = :productTypePeriod OR p.type = :productTypePeriodSupport
)');
$subQuery->andWhere('c1.deleted = :c1Deleted');
$subQuery->andWhere('c1.status = :c1Status');
$query->setParameter('c1Deleted', CourseEnum::ITEM_NO_DELETED);
$query->setParameter('c1Status', CourseEnum::PUBLISHED);
$query->setParameter('productDeleted', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('productStatus', ProductEnum::PUBLISHED);
$query->setParameter('productTypePeriod', ProductEnum::PERIOD);
$query->setParameter('productTypePeriodSupport', ProductEnum::PERIOD_SUPORT);
$subQuery = $subQuery->getDQL();
$exp = $query->expr()->in('e.course', $subQuery);
$query->andWhere("(e.datePeriod >= :now OR {$exp})");
$query->setParameter('now', date("Y-m-d H:i:s"));
}
$query->setParameter('userId', $userId);
$query->setParameter('courseStatus', CourseEnum::PUBLISHED);
$query->addOrderBy('e.dateLastAccess', 'DESC');
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->total;
}
public function countUserEnrollment(int $userId, ?bool $all = false)
{
$query = $this->createQueryBuilder('e');
$query->select("count(e.id) AS total");
$query->innerJoin(
'EADPlataforma:Course',
'c',
'WITH',
'e.course = c
AND c.deleted = 0
AND c.status = :courseStatus'
);
$query->andWhere('e.user = :userId');
$query->andWhere('e.deleted = 0');
if($all){
$query->andWhere('e.status = :status');
$query->andWhere('e.datePeriod >= :now');
$query->andWhere('c.dateRelease <= :now');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
$query->setParameter('now', date("Y-m-d H:i:s"));
}
$query->setParameter('userId', $userId);
$query->setParameter('courseStatus', CourseEnum::PUBLISHED);
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->total;
}
public function getEnrollmentNumber(
?string $dateStart = null,
?string $dateEnd = null,
?int $userId = null,
?int $status = null
)
{
$query = $this->createQueryBuilder('e');
$query->select("COUNT(0) AS total");
$query->andWhere('e.deleted = :deleted');
if($userId > 0){
$subQuery = $this->createQueryBuilder('course_team');
$subQuery->select('IDENTITY(ct.course)');
$subQuery->from('EADPlataforma:CourseTeam', 'ct');
$subQuery->andWhere('ct.user = :userId');
$subQuery = $subQuery->getDQL();
$query->andWhere($query->expr()->in('e.course', $subQuery));
$query->setParameter('userId', $userId);
}
if(!is_null($dateStart) && !is_null($dateEnd)){
$query->andWhere('DATE(e.dateRegister) BETWEEN :dateStart AND :dateEnd');
$query->setParameter('dateStart', $dateStart);
$query->setParameter('dateEnd', $dateEnd);
}
if(!empty($status)){
$query->andWhere('e.status = :status');
$query->setParameter('status', $status);
}
$query->setParameter('deleted', EnrollmentEnum::ITEM_NO_DELETED);
$query->setMaxResults(1);
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->total;
}
public function checkFinishCourseByEnrollment(Enrollment $enrollment)
{
$historyMetrics = $this->getHistoryMetricsByEnrollment($enrollment->getId());
$progress = $historyMetrics->progress;
if($progress < 100 || !empty($enrollment->getDateConclusion())){
return;
}
$user = $enrollment->getUser();
$course = $enrollment->getCourse();
if($course->getStatus() == CourseEnum::DRAFT){
return;
}
$marketingService = $this->generalService->getService(
'Marketing\\MarketingService'
);
if(
$this->configuration->isModuleActive("exam_module") &&
$this->configuration->checkModuleIsAbleOnPlan("examFunction")
){
$examRepository = $this->em->getRepository(Exam::class);
$examUserRepository = $this->em->getRepository(ExamUser::class);
$numberExamConfig = $examRepository->countValidExamByCourse($course->getId());
$numberExamUserConfig = $examUserRepository->countValidExamUserByCourse(
$course->getId(),
$user->getId()
);
if(empty($numberExamConfig)){
$enrollment->setDateConclusion(date('Y-m-d H:i:s'));
$marketingService->setTag(TagsMarketingEnum::TAG_FINISH_COURSE);
$marketingService->setTextComplement($course->getTitle());
$marketingService->setUser($this->getUser());
$marketingService->send();
}else if($numberExamConfig == $numberExamUserConfig){
$finalAverage = $examUserRepository->getFinalAvarege(
$user->getId(),
$course->getId()
);
$certificateAverage = $course->getCertificateAverage();
if($finalAverage >= $certificateAverage){
$enrollment->setDateConclusion(date('Y-m-d H:i:s'));
$marketingService->setTag(TagsMarketingEnum::TAG_FINISH_COURSE);
$marketingService->setTextComplement($course->getTitle());
$marketingService->setUser($this->getUser());
$marketingService->send();
}
}
}else{
$enrollment->setDateConclusion(date('Y-m-d H:i:s'));
$marketingService->setTag(TagsMarketingEnum::TAG_FINISH_COURSE);
$marketingService->setTextComplement($course->getTitle());
$marketingService->setUser($this->getUser());
$marketingService->send();
}
$this->em->flush();
return;
}
public function checkAndIssueCertificate(Enrollment $enrollment, $finalAverage = null)
{
if(!$this->configuration->isModuleActive("course_certificate_module")){
return;
}
if(!$this->configuration->checkModuleIsAbleOnPlan("certificateFunction")){
return;
}
if($enrollment->getCertificate() == EnrollmentEnum::NO){
return;
}
$historyMetrics = $this->getHistoryMetricsByEnrollment($enrollment->getId());
$progress = $historyMetrics->progress;
if($progress < 100){
return;
}
$user = $enrollment->getUser();
$course = $enrollment->getCourse();
if($course->getStatus() == CourseEnum::DRAFT){
return;
}
$courseCertificateTemplate = $course->getCourseCertificateTemplate();
if(!$courseCertificateTemplate){
return;
}
$courseCertificateRepository = $this->em->getRepository(CourseCertificate::class);
$certificate = $courseCertificateRepository->findOneBy([
"course" => $enrollment->getCourse()->getId(),
"user" => $enrollment->getUser()->getId(),
"deleted" => CourseCertificateEnum::ITEM_NO_DELETED
]);
if($certificate){
return $certificate;
}
$create = false;
if(
$this->configuration->isModuleActive("exam_module") &&
$this->configuration->checkModuleIsAbleOnPlan("examFunction")
){
$examUserRepository = $this->em->getRepository(ExamUser::class);
$examRepository = $this->em->getRepository(Exam::class);
$numberExamConfig = $examRepository->countValidExamByCourse($course->getId());
/*$numberExamUserConfig = $examUserRepository->countValidExamUserByCourse(
$course->getId(),
$user->getId()
);*/
if(empty($finalAverage)){
$finalAverage = $examUserRepository->getFinalAvarege(
$user->getId(),
$course->getId()
);
}
$certificateAverage = $course->getCertificateAverage();
if(empty($numberExamConfig)){
$finalAverage = 10;
$create = true;
}else if($finalAverage >= $certificateAverage){
$create = true;
}
}else{
$finalAverage = 10;
$create = true;
}
if($create){
$info = $courseCertificateRepository->createCertificate(
$enrollment,
$courseCertificateTemplate,
$finalAverage
);
$certificate = $info->courseCertificate;
}
$this->em->flush();
return $certificate;
}
public function getCourseIndexByEnrollmentNew(Enrollment $enrollment)
{
$enrollment = $this->updateDataAccessLog($enrollment);
$certificate = $this->checkAndIssueCertificate($enrollment);
$this->checkFinishCourseByEnrollment($enrollment);
$addExams = true;
if(
!$this->configuration->isModuleActive("exam_module") ||
!$this->configuration->checkModuleIsAbleOnPlan("examFunction")
){
$addExams = false;
}
$course = $enrollment->getCourse();
$user = $enrollment->getUser();
$lessonRepository = $this->em->getRepository(Lesson::class);
$logOriginRepository = $this->em->getRepository(LessonLogOrigin::class);
$courseRepository = $this->em->getRepository(Course::class);
$isStudent = $courseRepository->isStudent($course);
$lessonModules = $this->getModulesByEnrollment($enrollment);
$courseTestimonialRepository = $this->em->getRepository(CourseTestimonial::class);
$courseTestimonial = $courseTestimonialRepository->findOneBy([
"user" => $user->getId(),
"course" => $course->getId(),
"deleted" => CourseTestimonialEnum::ITEM_NO_DELETED
]);
$testimonial = null;
if($courseTestimonial){
$testimonial = (object)[
"id" => $courseTestimonial->getId(),
"score" => $courseTestimonial->getScore(),
"testimonial" => $courseTestimonial->getTestimonial(),
];
}
$certificateLink = null;
if($certificate){
$certificateLink = $this->generalService->generateUrl("viewCertificate", [
"code" => $certificate->getNewCode() ?? $certificate->getCode(),
"date" => $certificate->getDateEnd('Y-m-d'),
]);
}
$allowCertificate = true;
if($enrollment->getCertificate() == EnrollmentEnum::NO){
$poRepository = $this->em->getRepository(ProductOffer::class);
$certificateOffer = $poRepository->getProductOfferCertificateByCourse(
$course
);
$allowCertificate = ($certificateOffer ? true : false);
}
$allowSupport = ($course->getSupport() == CourseEnum::YES);
$dateSupport = $enrollment->getDateSupport();
$date = date('Y-m-d H:i:s');
$data = (object)[
"id" => $course->getId(),
"status" => $course->getStatus(),
"title" => $course->getTitle(),
"allowSupport" => $allowSupport,
"supportDate" => ($allowSupport ? $dateSupport : null),
"supportExpired" => ($allowSupport && $dateSupport > $date ? false : true),
"exam" => null,
"testimonial" => $testimonial,
"modules" => $lessonModules,
"lessonCompleted" => (int)$logOriginRepository->countLessonLogCompleteByUser(
$course,
$user
),
"lessonTotal" => (int)$lessonRepository->countCourseLessons($course, $user->getId()),
"allowCertificate" => $allowCertificate,
"certificateLink" => $certificateLink,
];
if($addExams){
$examRepository = $this->em->getRepository(Exam::class);
$data->exam = $examRepository->getExamToIndexNew(
$isStudent,
ExamEnum::COURSE,
$course
);
}
return $data;
}
public function getCourseIndexByEnrollment(Enrollment $enrollment, $addExams = false)
{
$enrollment = $this->updateDataAccessLog($enrollment);
$this->checkAndIssueCertificate($enrollment);
$this->checkFinishCourseByEnrollment($enrollment);
$addExamsLimited = $addExams;
if($addExams){
if(
!$this->configuration->isModuleActive("exam_module") ||
!$this->configuration->checkModuleIsAbleOnPlan("examFunction")
){
$addExams = false;
$addExamsLimited = false;
}else{
$addExamsLimited = $this->configuration->checkModuleIsAbleOnPlan(
"unlimitedExamFunction"
);
}
}
$certificate = $this->checkAndIssueCertificate($enrollment);
$course = $enrollment->getCourse();
$courseCoord = $course->getUser();
$courseRepository = $this->em->getRepository(Course::class);
$isStudent = $courseRepository->isStudent($course);
$lessonModules = $this->getHistoryByEnrollment(
$enrollment,
$addExamsLimited,
$isStudent
);
$today = date('Y-m-d H-i-s');
$courseTestimonialRepository = $this->em->getRepository(CourseTestimonial::class);
$courseTestimonial = $courseTestimonialRepository->findOneBy([
"user" => $enrollment->getUser()->getId(),
"course" => $course->getId(),
"deleted" => CourseTestimonialEnum::ITEM_NO_DELETED
]);
$timeToday = strtotime(date('Y-m-d H:i:s'));
$courseDateRelease = strtotime($course->getDateRelease());
$courseHasRelease = !($courseDateRelease >= $timeToday);
$courseHasCertificate = ($course->getCertificate() == CourseEnum::YES);
$certificateSale = false;
$linkPdf = null;
$linkBuy = null;
if($courseHasCertificate){
if(!$certificate && $enrollment->getCertificate() == EnrollmentEnum::NO){
$poRepository = $this->em->getRepository(ProductOffer::class);
$certificateOffer = $poRepository->getProductOfferCertificateByCourse(
$course
);
if($certificateOffer){
$certificateSale = true;
$linkBuy = $this->generalService->generateUrl("cartAdd", [
"poID" => $certificateOffer->getId(),
"courseId" => $course->getId(),
]);
}
}
}
if($certificate){
$linkPdf = $this->generalService->generateUrl("viewCertificate", [
"code" => $certificate->getCode(),
"date" => $certificate->getDateEnd('Y-m-d'),
]);
}
$accessExpired = CourseEnum::NO;
if(strtotime($enrollment->getDatePeriod()) < time()){
$accessExpired = CourseEnum::YES;
}
$lessonSupport = $course->getSupport();
$supportExpired = CourseEnum::NO;
//check user has active support
if($lessonSupport == CourseEnum::YES && $isStudent){
$userDateSupport = $enrollment->getDateSupport();
$userDateSupport = strtotime($userDateSupport);
if($timeToday > $userDateSupport){
$supportExpired = CourseEnum::YES;
}
}
$historyMetrics = $this->getHistoryMetricsByEnrollment($enrollment->getId());
$data = (object)[
"id" => $course->getId(),
"status" => $course->getStatus(),
"courseTitle" => $course->getTitle(),
"courseTime" => $course->getWorkload(),
"courseDateRelease" => $course->getDateRelease(),
"courseHasRelease" => $courseHasRelease,
"courseHasCertificate" => $courseHasCertificate,
"courseAllowSupport" => $course->getSupport(),
"coorName" => $courseCoord->getName(),
"coorPhoto" => $courseCoord->getPhoto(),
"coorUsername" => $courseCoord->getUsername(),
"courseExam" => null,
"courseLessonTotal" => $historyMetrics->lessonTotal,
"enrollmentPercent" => $historyMetrics->progress,
"enrollmentLessonView" => $historyMetrics->lessonCompleted,
"enrollmentDatePeriod" => $enrollment->getDatePeriod(),
"enrollmentAllowAccess" => ($enrollment->getDatePeriod() >= $today),
"enrollmentDateSupport" => $enrollment->getDateSupport(),
"enrollmentAllowSupport" => ($enrollment->getDateSupport() >= $today),
"courseTestimonial" => (
$courseTestimonial ? $courseTestimonial->toReturn() : null
),
"lessonModules" => $lessonModules,
"certificateIssue" => ($certificate ? true : false),
"certificateLink" => $linkPdf,
"certificateSale" => $certificateSale,
"certificateLinkBuy" => $linkBuy,
"isStudent" => $isStudent,
"accessExpired" => $accessExpired,
"supportExpired" => $supportExpired,
"lessonSupport" => $lessonSupport,
];
if($addExams){
$examRepository = $this->em->getRepository(Exam::class);
$data->courseExam = $examRepository->getExamToIndex(ExamEnum::COURSE, $course);
}
return $data;
}
public function getModulesByEnrollmentNew(
Enrollment $enrollment,
?bool $isStudent = true,
?string $searchText = null
)
{
$addExams = false;
if(
$this->configuration->isModuleActive("exam_module") &&
$this->configuration->checkModuleIsAbleOnPlan("examFunction") &&
$this->configuration->checkModuleIsAbleOnPlan("unlimitedExamFunction")
){
$addExams = true;
}
$course = $enrollment->getCourse();
$user = $enrollment->getUser();
$data = [];
$logOriginRepository = $this->em->getRepository(LessonLogOrigin::class);
$lessonRepository = $this->em->getRepository(Lesson::class);
$examRepository = $this->em->getRepository(Exam::class);
$lessonModuleRepository = $this->em->getRepository(LessonModule::class);
$lessonModules = $lessonModuleRepository->getCourseLessonModules($course);
foreach ($lessonModules as $keyModule => $lessonModule) {
$lessonsSearch = $this->getHistoryByEnrollmentModuleNew(
$enrollment,
$lessonModule,
$addExams,
$isStudent,
$searchText
);
if(!empty($lessonsSearch)){
$lessonModuleObj = (object)[
"id" => $lessonModule->getId(),
"title" => $lessonModule->getTitle(),
"description" => $lessonModule->getDescription(),
"status" => $lessonModule->getStatus(),
"lessonCompleted" => (int)$logOriginRepository->countLessonLogCompleteByUser(
$course,
$user,
$lessonModule
),
"lessonTotal" => (int)$lessonRepository->countCourseLessons(
$course,
$user->getId(),
$lessonModule
),
"exam" => null,
"lessons" => $lessonsSearch,
];
if($addExams){
$lessonModuleObj->exam = $examRepository->getExamToIndexNew(
$isStudent,
ExamEnum::MODULE,
$course,
$lessonModule
);
}
$data[] = $lessonModuleObj;
}
}
return $data;
}
public function getModuleIndexByEnrollmentNew(
Enrollment $enrollment,
LessonModule $lessonModule,
?bool $isStudent = true
)
{
$addExams = false;
if(
$this->configuration->isModuleActive("exam_module") &&
$this->configuration->checkModuleIsAbleOnPlan("examFunction") &&
$this->configuration->checkModuleIsAbleOnPlan("unlimitedExamFunction")
){
$addExams = true;
}
$course = $enrollment->getCourse();
$data = (object)[
"id" => $lessonModule->getId(),
"title" => $lessonModule->getTitle(),
"description" => $lessonModule->getDescription(),
"status" => $lessonModule->getStatus(),
"exam" => null,
"lessons" => $this->getHistoryByEnrollmentModuleNew(
$enrollment,
$lessonModule,
$addExams,
$isStudent
),
];
if($addExams){
$examRepository = $this->em->getRepository(Exam::class);
$data->exam = $examRepository->getExamToIndexNew(
$isStudent,
ExamEnum::MODULE,
$course,
$lessonModule
);
}
return $data;
}
public function getModulesByEnrollment(Enrollment $enrollment)
{
$lessonModuleRepository = $this->em->getRepository(LessonModule::class);
$lessonRepository = $this->em->getRepository(Lesson::class);
$logOriginRepository = $this->em->getRepository(LessonLogOrigin::class);
$examRepository = $this->em->getRepository(Exam::class);
$course = $enrollment->getCourse();
$user = $enrollment->getUser();
$data = [];
$lessonModules = $lessonModuleRepository->getCourseLessonModules($course);
foreach ($lessonModules as $keyModule => $lessonModule) {
$lessonModuleObj = (object)[
"id" => $lessonModule->getId(),
"title" => $lessonModule->getTitle(),
"description" => $lessonModule->getDescription(),
"status" => $lessonModule->getStatus(),
"lessonCompleted" => (int)$logOriginRepository->countLessonLogCompleteByUser(
$course,
$user,
$lessonModule
),
"lessonTotal" => (int)$lessonRepository->countCourseLessons(
$course,
$user->getId(),
$lessonModule
),
];
if($lessonModuleObj->lessonCompleted > $lessonModuleObj->lessonTotal){
$lessonModuleObj->lessonCompleted = $lessonModuleObj->lessonTotal;
}
$data[] = $lessonModuleObj;
}
return $data;
}
public function getHistoryMetricsByEnrollment($enrollmentId)
{
$lessonModuleRepository = $this->em->getRepository(LessonModule::class);
$lessonRepository = $this->em->getRepository(Lesson::class);
$lessonLogRepository = $this->emEadmin->getRepository(LessonLog::class);
$lessonSupportRepository = $this->em->getRepository(LessonSupport::class);
$dateTimeUtil = $this->generalService->getUtil('DateTimeUtil');
$enrollment = $this->findOneBy([
"id" => $enrollmentId,
"deleted" => EnrollmentEnum::ITEM_NO_DELETED
]);
$course = $enrollment->getCourse();
$user = $enrollment->getUser();
$lessonModules = $lessonModuleRepository->getCourseLessonModules($course);
$lessons = $lessonRepository->getCourseLessons($course);
$auxLogs = [];
$dataLesson = [];
$dataModule = [];
$lessonLogs = $lessonLogRepository->findBy(
[
"user" => $user->getId(),
"course" => $course->getId(),
],
null,
null,
null,
[ $course->getId(), "{$user->getId()}#" ]
);
foreach ($lessonLogs as $key => $log) {
if($log->getLesson()){
$auxLogs[$log->getLesson()->getId()] = $log;
}
}
foreach ($lessonModules as $keyModule => $lessonModule) {
$lessonModuleObj = (object)[
"id" => $lessonModule->getId(),
"lessonCompleted" => 0,
"lessonTotal" => 0
];
foreach ($lessons as $keyLesson => $lesson) {
if($lessonModuleObj->id == $lesson->getLessonModule()->getId()){
if($lesson->getStatus() == LessonEnum::PUBLISHED){
$lessonModuleObj->lessonTotal = $lessonModuleObj->lessonTotal + 1;
}
$lessonObj = (object)[
"timeWatch" => null,
"numberAccess" => null,
"numberSupport" => null,
];
$lessonLog = (
isset($auxLogs[$lesson->getId()]) ?
$auxLogs[$lesson->getId()] :
null
);
if($lessonLog){
if($lessonLog->getComplete() == LessonEnum::YES){
$lessonModuleObj->lessonCompleted = $lessonModuleObj->lessonCompleted + 1;
}
$lessonObj->numberSupport = $lessonSupportRepository->count([
"user" => $user->getId(),
"lesson" => $lesson->getId(),
"lessonSupport" => null,
]);
$lessonObj->timeWatch = $lessonLog->getTimeWatch();
$lessonObj->numberAccess = $lessonLog->getNumberAccess();
}
$dataLesson[] = $lessonObj;
}
}
if($lessonModuleObj->lessonCompleted > $lessonModuleObj->lessonTotal){
$lessonModuleObj->lessonCompleted = $lessonModuleObj->lessonTotal;
}
$dataModule[] = $lessonModuleObj;
}
$timeWatch = 0;
$numberAccess = 0;
$numberSupport = 0;
$lessonCompleted = 0;
$lessonTotal = 0;
$progress = 0;
foreach ($dataLesson as $key => $value) {
$seconds = $dateTimeUtil->timeToSec($value->timeWatch);
$timeWatch = $timeWatch + $seconds;
$numberAccess = $numberAccess + $value->numberAccess;
$numberSupport = $numberSupport + $value->numberSupport;
}
foreach ($dataModule as $key => $value) {
$lessonCompleted = $lessonCompleted + $value->lessonCompleted;
$lessonTotal = $lessonTotal + $value->lessonTotal;
}
$timeWatch = $dateTimeUtil->secToTime($timeWatch);
if(!empty($lessonTotal)){
$progress = round(($lessonCompleted / $lessonTotal) * 100, 0);
}
return (object)[
"timeWatch" => $timeWatch,
"numberAccess" => $numberAccess,
"numberSupport" => $numberSupport,
"lessonCompleted" => $lessonCompleted,
"lessonTotal" => $lessonTotal,
"progress" => $progress
];
}
public function getHistoryByEnrollment(
Enrollment $enrollment,
?bool $addExams = false,
?bool $isStudent = true
)
{
$lessonModuleRepository = $this->em->getRepository(LessonModule::class);
$lessonRepository = $this->em->getRepository(Lesson::class);
$lessonLogRepository = $this->emEadmin->getRepository(LessonLog::class);
$lessonSupportRepository = $this->em->getRepository(LessonSupport::class);
$lessonAnnotationRepository = $this->em->getRepository(LessonAnnotation::class);
$examRepository = $this->em->getRepository(Exam::class);
$stringUtil = $this->generalService->getUtil('StringUtil');
$course = $enrollment->getCourse();
$user = $enrollment->getUser();
$data = [];
$lessonModules = $lessonModuleRepository->getCourseLessonModules($course);
$lessons = $lessonRepository->getCourseLessons($course);
$auxLogs = [];
$lessonLogs = $lessonLogRepository->findBy(
[
"user" => $user->getId(),
"course" => $course->getId(),
],
null,
null,
null,
[ $course->getId(), "{$user->getId()}#" ]
);
foreach ($lessonLogs as $key => $log) {
$auxLogs[$log->getLesson()->getId()] = $log;
}
$examModule = $this->configuration->isModuleActive("exam_module");
$blockNextLesson = false;
$lessonIdBefore = null;
foreach ($lessonModules as $keyModule => $lessonModule) {
$lessonModuleObj = (object)[
"id" => $lessonModule->getId(),
"courseId" => $course->getId(),
"title" => $lessonModule->getTitle(),
"order" => $lessonModule->getOrder(),
"status" => $lessonModule->getStatus(),
"controlRequirement" => $lessonModule->getControlRequirement(),
"controlReleaseType" => $lessonModule->getControlReleaseType(),
"controlReleaseAfterType" => $lessonModule->getControlReleaseAfterType(),
"controlDateRelease" => $lessonModule->getControlDateRelease(),
"controlReleasePeriod" => $lessonModule->getControlReleasePeriod(),
"controlClosePeriod" => $lessonModule->getControlClosePeriod(),
"moduleIsAccessible" => false,
"lessonCompleted" => 0,
"lessonTotal" => 0,
"exam" => null,
"lessons" => [],
];
if($addExams){
$lessonModuleObj->exam = $examRepository->getExamToIndex(
ExamEnum::MODULE, $course, $lessonModule
);
}
foreach ($lessons as $keyLesson => $lesson) {
if($lessonModuleObj->id == $lesson->getLessonModule()->getId()){
if($lesson->getStatus() == LessonEnum::PUBLISHED){
$lessonModuleObj->lessonTotal = $lessonModuleObj->lessonTotal + 1;
}
$lessonLog = (
isset($auxLogs[$lesson->getId()]) ?
$auxLogs[$lesson->getId()] :
null
);
$lessonIsAccessible = $lessonRepository->checkLessonIsAccessibleToUser(
$lesson,
$enrollment,
$lessonLog,
$isStudent,
$lessonIdBefore,
$blockNextLesson
);
if(
!$lessonIsAccessible->isAccessible &&
$lesson->getControlRequirement() == LessonEnum::YES
){
$blockNextLesson = true;
}
if(empty($lessonModuleObj->lessons)){
$lessonModuleObj->moduleIsAccessible = $lessonIsAccessible->isAccessible;
}
$dateReleaseAccess = $lessonRepository->getLessonDateReleaseAccess(
$lesson,
$enrollment,
$isStudent,
$lessonIdBefore
);
$lessonIdBefore = $lesson->getId();
$contentPagesNumber = null;
$contentDuration = null;
$contentType = null;
$library = $lesson->getLibrary();
if($library){
$contentPagesNumber = $library->getPagesNumber();
$contentDuration = $library->getDuration();
$contentType = $library->getType();
}
$lessonObj = (object)[
"id" => $lesson->getId(),
"courseId" => $course->getId(),
"lessonModuleId" => $lessonModuleObj->id,
"title" => $lesson->getTitle(),
"order" => $lesson->getOrder(),
"status" => $lesson->getStatus(),
"lessonIsAccessible" => $lessonIsAccessible->isAccessible,
"dateReleaseAccess" => $dateReleaseAccess,
"exam" => null,
"quiz" => null,
"timeWatch" => null,
"numberAccess" => null,
"numberSupport" => null,
"dateLastAccess" => null,
"dateConclusion" => null,
"contentPagesNumber" => $contentPagesNumber,
"contentDuration" => $contentDuration,
"contentType" => $contentType,
"allowCheck" => EnrollmentEnum::YES,
"controlRequirement" => $lesson->getControlRequirement(),
"controlReleaseType" => $lesson->getControlReleaseType(),
"controlReleaseAfterType" => $lesson->getControlReleaseAfterType(),
"controlDateRelease" => $lesson->getControlDateRelease(),
"controlReleasePeriod" => $lesson->getControlReleasePeriod(),
"controlClosePeriod" => $lesson->getControlClosePeriod(),
"controlTime" => (
$lesson->getControlRequirement() ?
$lesson->getControlTime() :
LessonEnum::NO
),
"controlTimeStay" => $lesson->getControlTimeStay(),
"controlViewLimit" => $lesson->getControlViewLimit(),
"controlViewNumber" => $lesson->getControlViewNumber(),
"controlPauseNumber" => $lesson->getControlPauseNumber(),
];
if($lesson->getControlRequirement() == LessonEnum::YES){
$lessonObj->allowCheck = LessonEnum::NO;
}
if(
!empty($lesson->getControlTimeStay()) &&
$lesson->getControlTimeStay() != '00:00:00'
){
$lessonObj->allowCheck = LessonEnum::NO;
}
if($addExams){
$lessonObj->exam = $examRepository->getExamToIndex(
ExamEnum::LESSON,
$course,
$lessonModule,
$lesson
);
}
$lessonObj->quiz = $examRepository->getExamToIndex(
ExamEnum::QUIZ,
$course,
$lessonModule,
$lesson
);
$lessonObj->numberSupport = $lessonSupportRepository->count([
"user" => $user->getId(),
"lesson" => $lesson->getId(),
"lessonSupport" => null,
]);
$lessonObj->supports = [];
if(!empty($lessonObj->numberSupport)){
$supports = $lessonSupportRepository->findBy([
"user" => $user->getId(),
"lesson" => $lesson->getId(),
"lessonSupport" => null,
"deleted" => LessonSupportEnum::ITEM_NO_DELETED
]);
foreach ($supports as $key => $support) {
$txt = strip_tags(html_entity_decode($support->getSupport()));
$txt = str_replace("\xc2\xa0", '', $txt);
$lessonObj->supports[] = (object)[
"id" => $support->getId(),
"date" => $support->getDate(),
"support" => $stringUtil->shortTextCleanNew($txt),
];
}
}
$lessonObj->notes = [];
$lessonNotes = $lessonAnnotationRepository->findBy([
"user" => $user->getId(),
"lesson" => $lesson->getId(),
"deleted" => LessonAnnotationEnum::ITEM_NO_DELETED
], [ "id" => "DESC" ]);
if(!empty($lessonNotes)){
foreach ($lessonNotes as $key => $note) {
$lessonObj->notes[] = (object)[
"id" => $note->getId(),
"date" => $note->getDate(),
"time" => $note->getTime(),
"note" => $note->getAnnotation(),
"options" => $note->getOptions()
];
}
}
if($lessonLog){
if($lessonLog->getComplete() == LessonEnum::YES){
$lessonModuleObj->lessonCompleted = $lessonModuleObj->lessonCompleted + 1;
}
$lessonObj->complete = $lessonLog->getComplete();
$lessonObj->favorite = $lessonLog->getFavorite();
$lessonObj->timeWatch = $lessonLog->getTimeWatch();
$lessonObj->numberAccess = $lessonLog->getNumberAccess();
$lessonObj->dateLastAccess = $lessonLog->getDateAccess();
$lessonObj->dateConclusion = $lessonLog->getDateConclusion();
if(!empty($lessonObj->dateConclusion)){
$lessonObj->allowCheck = LessonEnum::YES;
}
}
$lessonModuleObj->lessons[] = $lessonObj;
}
}
if($lessonModuleObj->lessonCompleted > $lessonModuleObj->lessonTotal){
$lessonModuleObj->lessonCompleted = $lessonModuleObj->lessonTotal;
}
$data[] = $lessonModuleObj;
}
return $data;
}
public function getHistoryByEnrollmentModuleNew(
Enrollment $enrollment,
LessonModule $lessonModule,
?bool $addExams = false,
?bool $isStudent = true,
?string $searchText = null
)
{
$lessonRepository = $this->em->getRepository(Lesson::class);
$libraryRepository = $this->em->getRepository(Library::class);
$lessonLogRepository = $this->emEadmin->getRepository(LessonLog::class);
$examRepository = $this->em->getRepository(Exam::class);
$stringUtil = $this->generalService->getUtil('StringUtil');
$course = $enrollment->getCourse();
$user = $enrollment->getUser();
$data = [];
$lessons = $lessonRepository->getCourseLessons(
$course,
$lessonModule,
null,
$searchText
);
$blockNextLesson = false;
$lessonIdBefore = null;
$timeUtil = $this->generalService->getUtil('DateTimeUtil');
foreach ($lessons as $keyLesson => $lesson) {
$logId = "{$course->getId()}#{$user->getId()}#{$lesson->getId()}";
$lessonLog = $lessonLogRepository->find($logId);
$lessonIsAccessible = $lessonRepository->checkLessonIsAccessibleToUser(
$lesson,
$enrollment,
$lessonLog,
$isStudent,
$lessonIdBefore,
$blockNextLesson
);
if($lessonIsAccessible->isAccessPeriodExpired){
continue;
}
if(
!$lessonIsAccessible->isAccessible &&
$lesson->getControlRequirement() == LessonEnum::YES
){
$blockNextLesson = true;
}
/*$dateReleaseAccess = $lessonRepository->getLessonDateReleaseAccess(
$lesson,
$enrollment,
$isStudent,
$lessonIdBefore
);*/
$lessonIdBefore = $lesson->getId();
$contentPagesNumber = null;
$contentDuration = null;
$contentType = null;
$contentThumb = null;
$library = $lesson->getLibrary();
if($library){
$contentPagesNumber = $library->getPagesNumber();
$contentDuration = $library->getDuration();
$contentType = $library->getType();
$contentThumb = $libraryRepository->getCover($library);
}
$lessonObj = (object)[
"id" => $lesson->getId(),
"title" => $lesson->getTitle(),
"status" => $lesson->getStatus(),
"required" => $lesson->getControlRequirement(),
"lessonIsAccessible" => $lessonIsAccessible->isAccessible,
"acessMessage" => $lessonIsAccessible->message,
"contentPagesNumber" => $contentPagesNumber,
"contentDuration" => (
$contentDuration ? $timeUtil->timeToSec($contentDuration) : null
),
"contentType" => $contentType,
"contentThumb" => $contentThumb,
"exam" => null,
"quiz" => null,
"allowCheck" => EnrollmentEnum::YES,
"completed" => LessonEnum::NO,
];
if($lessonLog && $lessonLog->getComplete() == LessonEnum::YES){
$lessonObj->completed = $lessonLog->getViewed();
}
if($lesson->getControlRequirement() == LessonEnum::YES){
$lessonObj->allowCheck = LessonEnum::NO;
}
if(
!empty($lesson->getControlTimeStay()) &&
$lesson->getControlTimeStay() != '00:00:00'
){
$lessonObj->allowCheck = LessonEnum::NO;
}
if($addExams){
$lessonObj->exam = $examRepository->getExamToIndexNew(
$isStudent,
ExamEnum::LESSON,
$course,
$lessonModule,
$lesson
);
}
$lessonObj->quiz = $examRepository->getExamToIndexNew(
$isStudent,
ExamEnum::QUIZ,
$course,
$lessonModule,
$lesson
);
$data[] = $lessonObj;
}
return $data;
}
public function getExpiredEnrollmentsByDate($date)
{
$query = $this->createQueryBuilder('e');
$query->andWhere('e.deleted = 0');
$query->andWhere('e.datePeriod = :date');
$query->setParameter('date', $date);
$query->andWhere('e.status = :status');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
return $query->getQuery()->execute();
}
public function isValidEnrollmentByUser($userId, $courseId)
{
$query = $this->createQueryBuilder('e');
$query->innerJoin(
'EADPlataforma:Course', 'c',
'WITH', 'e.course = c AND c.deleted = :deletedCourse'
);
$query->andWhere('e.deleted = :deleted');
$query->andWhere('e.user = :userId');
$query->andWhere('e.course = :courseId');
if($userId != EnrollmentEnum::YES){
$query->andWhere('e.status = :status');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
$query->andWhere('e.datePeriod >= :now');
$query->setParameter('now', date('Y-m-d H:i:s'));
}
$query->setParameter('deletedCourse', CourseEnum::ITEM_NO_DELETED);
$query->setParameter('deleted', EnrollmentEnum::ITEM_NO_DELETED);
$query->setParameter('userId', $userId);
$query->setParameter('courseId', $courseId);
$query->select('COUNT(0) AS total');
$result = (object)$query->getQuery()->getOneOrNullResult();
return ($result->total > 0);
}
public function isEnrollment($userId, $courseId)
{
$query = $this->createQueryBuilder('e');
$query->innerJoin(
'EADPlataforma:Course', 'c',
'WITH', 'e.course = c AND c.deleted = :deletedCourse'
);
$query->andWhere('e.deleted = :deleted');
$query->andWhere('e.user = :userId');
$query->andWhere('e.course = :courseId');
$query->andWhere('e.status = :status');
$query->setParameter('deletedCourse', CourseEnum::ITEM_NO_DELETED);
$query->setParameter('deleted', EnrollmentEnum::ITEM_NO_DELETED);
$query->setParameter('userId', $userId);
$query->setParameter('courseId', $courseId);
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
$query->select('COUNT(0) AS total');
$result = (object)$query->getQuery()->getOneOrNullResult();
return ($result->total > 0);
}
public function countEnrollmentsByCourse(
int $courseId,
?int $status = null,
?int $startType = null
)
{
$query = $this->createQueryBuilder('e');
$query->select("count(e.id) AS total");
$query->andWhere('e.deleted = 0');
$query->andWhere('e.course = :courseId');
$query->setParameter('courseId', $courseId);
if(!empty($status)){
if($status == EnrollmentEnum::STATUS_EXPIRED){
$query->andWhere('e.status = :status');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
$query->andWhere('e.datePeriod <= :now');
$query->setParameter('now', date('Y-m-d H:i:s'));
}else if($status == EnrollmentEnum::STATUS_ACTIVE){
$query->andWhere('e.status = :status');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
$query->andWhere('e.datePeriod >= :now');
$query->setParameter('now', date('Y-m-d H:i:s'));
}else{
$query->andWhere('e.status = :status');
$query->setParameter('status', $status);
}
}
if($startType == EnrollmentEnum::SITUATION_STARTED){
$query->andWhere('e.dateStart IS NOT NULL');
}else if($startType == EnrollmentEnum::SITUATION_NOT_STARTED){
$query->andWhere('e.dateStart IS NULL');
}
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->total;
}
public function getEnrollmentsByCourse(
int $courseId,
?int $status = null,
$startType = null
)
{
$query = $this->createQueryBuilder('e');
$query->andWhere('e.deleted = 0');
$query->andWhere('e.course = :courseId');
$query->setParameter('courseId', $courseId);
if(!empty($status)){
if($status == EnrollmentEnum::STATUS_EXPIRED){
$query->andWhere('e.status = :status');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
$query->andWhere('e.datePeriod <= :now');
$query->setParameter('now', date('Y-m-d H:i:s'));
}else if($status == EnrollmentEnum::STATUS_ACTIVE){
$query->andWhere('e.status = :status');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
$query->andWhere('e.datePeriod >= :now');
$query->setParameter('now', date('Y-m-d H:i:s'));
}else{
$query->andWhere('e.status = :status');
$query->setParameter('status', $status);
}
}
if($startType == EnrollmentEnum::SITUATION_STARTED){
$query->andWhere('e.dateStart IS NOT NULL');
}else if($startType == EnrollmentEnum::SITUATION_NOT_STARTED){
$query->andWhere('e.dateStart IS NULL');
}
return $query->getQuery()->execute();
}
public function getEnrollmentsByGroup(
int $groupId,
?int $status = null,
?int $userId = null,
?int $courseId = null
)
{
$query = $this->createQueryBuilder('e');
$query->innerJoin(
'EADPlataforma:Group', 'g', 'WITH',
'e.course MEMBER OF g.course AND e.user MEMBER OF g.user'
);
$query->andWhere('e.deleted = :deleted');
$query->andWhere('g.id = :groupId');
$query->setParameter('groupId', $groupId);
$query->setParameter('deleted', EnrollmentEnum::ITEM_NO_DELETED);
if(!empty($status)){
if($status == EnrollmentEnum::STATUS_EXPIRED){
$query->andWhere('e.datePeriod < :now');
$query->setParameter('now', date('Y-m-d H:i:s'));
$query->andWhere('e.status = :status');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
}else{
$query->andWhere('e.status = :status');
$query->setParameter('status', $status);
}
}
if($userId > 0){
$query->andWhere('e.user = :userId');
$query->setParameter('userId', $userId);
}
if($courseId > 0){
$query->andWhere('e.course = :courseId');
$query->setParameter('courseId', $courseId);
}
return $query->getQuery()->execute();
}
public function getEnrollmentsToEditMany(
?array $users = null,
$courseId = null,
$groupId = null,
$productId = null,
$teacherId = null,
$applyTo = null
)
{
$query = $this->createQueryBuilder('e');
$query->andWhere('e.deleted = 0');
if(!empty($users) && is_array($users)){
$users = implode(',', $users);
$query->andWhere("e.user IN ({$users})");
}
if($courseId > 0){
$query->andWhere('e.course = :courseId')->setParameter('courseId', $courseId);
}
if($groupId > 0){
$query->innerJoin(
'EADPlataforma:Group', 'g', 'WITH',
'e.course MEMBER OF g.course AND e.user MEMBER OF g.user'
);
$query->andWhere('g.id = :groupId');
$query->setParameter('groupId', $groupId);
}
if($productId > 0){
$query->innerJoin(
'EADPlataforma:Product', 'p', 'WITH', 'e.course MEMBER OF p.course '
);
$query->andWhere('p.id = :productId');
$query->setParameter('productId', $productId);
}
if($teacherId > 0){
$subQuery = $this->createQueryBuilder('course_team');
$subQuery->select('IDENTITY(ct.course)');
$subQuery->from('EADPlataforma:CourseTeam', 'ct');
$subQuery->andWhere('ct.user = :teacherId');
$subQuery = $subQuery->getDQL();
$query->andWhere($query->expr()->in('e.course', $subQuery));
$query->setParameter('teacherId', $teacherId);
}
if(empty($applyTo)){
$apply = EnrollmentEnum::APPLY_TO_ALL;
}
switch ($applyTo) {
case EnrollmentEnum::APPLY_TO_EXPIRED:
$query->andWhere('e.datePeriod < :now');
$query->setParameter('now', date('Y-m-d H:i:s'));
break;
case EnrollmentEnum::APPLY_TO_VALID_PERIOD:
$query->andWhere('e.datePeriod >= :now');
$query->setParameter('now', date('Y-m-d H:i:s'));
break;
case EnrollmentEnum::APPLY_TO_SUPPORT_EXPIRED:
$query->andWhere('e.dateSupport < :now');
$query->setParameter('now', date('Y-m-d H:i:s'));
break;
case EnrollmentEnum::APPLY_TO_CANCELED:
$query->andWhere('e.status = :statusCanceled');
$query->setParameter('statusCanceled', EnrollmentEnum::STATUS_CANCELED);
break;
}
return $query->getQuery()->execute();
}
public function updateEnrollmentMany(
array $enrollmentsIds = [],
?int $status = null,
?int $access = null,
?int $support = null,
?int $certificate = null
)
{
$upStatus = "";
if(!is_null($status)){
$upStatus = " e.status = :status ";
}
if($access == EnrollmentEnum::ENROLL_ORIGINAL){
$lifetimePeriod = $enrollment->getCourse()->getLifetimePeriod();
if($lifetimePeriod == CourseEnum::YES){
$datePeriod = "9999-09-09 00:00:00";
}else{
$accessPeriod = $enrollment->getCourse()->getAccessPeriod();
$dateRegister = $enrollment->getDateRegister();
$datePeriod = strtotime("+ {$accessPeriod} day", strtotime($dateRegister));
$datePeriod = date('Y-m-d H:i:s', $datePeriod);
}
$enrollment->setDatePeriod($datePeriod);
}elseif($access == EnrollmentEnum::ENROLL_CHANGE){
if(!empty($dateAccess)){
$enrollment->setDatePeriod($dateAccess);
}
}elseif($access == EnrollmentEnum::ENROLL_LIFETIME){
if($accessLifetimePeriod == EnrollmentEnum::YES){
$dateAccess = "9999-09-09 00:00:00";
$enrollment->setDatePeriod($dateAccess);
}
}
if($support == EnrollmentEnum::ENROLL_ORIGINAL){
$supportCourse = $enrollment->getCourse()->getSupport();
if($supportCourse == CourseEnum::YES){
$lifetimeSupport = $enrollment->getCourse()->getLifetimeSupport();
if($lifetimeSupport == CourseEnum::YES){
$dateSupport = "9999-09-09 00:00:00";
}else{
$supportPeriod = $enrollment->getCourse()->getSupportPeriod();
$dateRegister = $enrollment->getDateRegister();
$dateSupport = strtotime("+ {$supportPeriod} day", strtotime($dateRegister));
$dateSupport = date('Y-m-d H:i:s', $dateSupport);
}
}else{
$dateSupport = "0000-00-00 00:00:00";
}
$enrollment->setDateSupport($dateSupport);
}elseif($support == EnrollmentEnum::ENROLL_CHANGE){
if(!empty($dateSupport)){
$enrollment->setDateSupport($dateSupport);
}
}elseif($support == EnrollmentEnum::ENROLL_LIFETIME){
if($supportLifetimePeriod == EnrollmentEnum::YES){
$dateSupport = "9999-09-09 00:00:00";
$enrollment->setDateSupport($dateSupport);
}
}
if($certificate == EnrollmentEnum::ENROLL_CHANGE){
$enrollment->setCertificate(EnrollmentEnum::YES);
}elseif($certificate == EnrollmentEnum::ENROLL_ORIGINAL){
$enrollment->setCertificate(EnrollmentEnum::NO);
}
$sql = "UPDATE EADPlataforma:Enrollment AS e
SET e.deleted = :deleted, e.typeDelete = :typeDelete,
e.userDelete = :userDelete, e.dateDelete = :dateNow
WHERE e.deleted = (:deleted - 1)
AND e.user = :userId";
$query = $this->em->createQuery($sql);
$query->setParameter('userId', $userId);
$query->setParameter('deleted', $deleted);
$query->setParameter('typeDelete', $typeDelete);
$query->setParameter('userDelete', $userDelete);
$query->setParameter('dateNow', $dateNow);
$query->execute();
}
public function getEnrollmentsByUserSubscription(UserSubscription $userSubscription)
{
$query = $this->createQueryBuilder('e');
$query->innerJoin(
'EADPlataforma:UserSubscription', 'us', 'WITH', 'e.user = us.user'
);
$query->innerJoin(
'EADPlataforma:Product', 'p', 'WITH', 'e.course MEMBER OF p.course '
);
$query->andWhere('e.deleted = 0');
$query->andWhere('us.id = :userSubscriptionId');
$query->andWhere('p.id = :productId');
$query->andWhere('e.user = :userId');
$query->setParameter('userSubscriptionId', $userSubscription->getId());
$query->setParameter('productId', $userSubscription->getProduct()->getId());
$query->setParameter('userId', $userSubscription->getUser()->getId());
return $query->getQuery()->execute();
}
public function notify(Enrollment $enrollment)
{
//send email
$emailService = $this->generalService->getService('EmailService');
$client = $this->configuration->getClient();
$user = $enrollment->getUser();
if(!$emailService->checkUserToSend($user)){
return;
}
$emailService->setToEmail($user->getEmail());
$emailService->setToName($user->getName());
$subText1 = $this->configuration->getLanguage('enrollment.subject1', 'email');
$subText2 = $this->configuration->getLanguage('enrollment.subject2', 'email');
$subject = $subText1 . $enrollment->getCourse()->getTitle() . $subText2;
$emailService->setSubject($subject);
$domain = $client->getDomainPrimary();
$emailService->setData([
"userName" => $user->getName(),
"courseTitle" => $enrollment->getCourse()->getTitle(),
"btnLink" => "https://{$domain}/enrollment/{$enrollment->getId()}",
]);
$emailService->setTemplateBody("enrollment");
$emailService->send();
//notify user
$notificationService = $this->generalService->getService('NotificationService');
$notificationService->create(
$enrollment->getCourse()->getUser(),
$user,
NotificationEnum::ORIGIN_ENROLLMENT_NEW,
$enrollment->getId()
);
}
public function generateCertificate(
Enrollment $enrollment,
bool $download = false
)
{
$pdfService = $this->generalService->getService('PdfService');
$user = $enrollment->getUser();
$course = $enrollment->getCourse();
$examUserRepository = $this->em->getRepository(ExamUser::class);
$userExams = $examUserRepository->getStudentReportCard($user->getId(), $course->getId());
$finalAvarage = $examUserRepository->getFinalAvarege($user->getId(), $course->getId());
$history = $this->getHistoryByEnrollment($enrollment);
$historyMetrics = $this->getHistoryMetricsByEnrollment($enrollment->getId());
$data = [
"enrollmentUserPhoto" => $user->getPhoto(),
"enrollmentUserName" => mb_strtoupper($user->getName()),
"enrollmentCourseTitle" => $course->getTitle(),
"enrollmentDateStart" => $enrollment->getDateStart(),
"enrollmentLastAccess" => $enrollment->getDateLastAccess(),
"courseProgress" => $historyMetrics->progress,
"userExams" => $userExams,
"finalAvarage" => $finalAvarage,
"dataAccessLesson" => $historyMetrics->lessonCompleted,
"dataAccessLessonTotal" => $historyMetrics->lessonTotal,
"dataAccessPreview" => $historyMetrics->numberAccess,
"dataAccessSopportRequests" => $historyMetrics->numberSupport,
"dataAccessTimeCourse" => $historyMetrics->timeWatch,
"history" => $history
];
$pdfService->setFileName("historico_do_aluno");
$pdfService->setTemplateBody("enrollment_history");
$pdfService->setData($data);
return $pdfService->generate(false, $download);
}
public function export(
$courseId = null,
$userId = null,
$groupId = null,
$teacherId = null,
$status = null,
$dateStart = null,
$dateEnd = null
)
{
$query = $this->createQueryBuilder('e');
$query->select("
e.id,
e.status,
e.lessonNumberComplete,
DATE_FORMAT(e.dateRegister, '%Y-%m-%d %H:%i:%s') AS dateRegister,
DATE_FORMAT(e.dateConclusion, '%Y-%m-%d %H:%i:%s') AS dateConclusion,
DATE_FORMAT(e.dateStart, '%Y-%m-%d %H:%i:%s') AS dateStart,
DATE_FORMAT(e.dateSupport, '%Y-%m-%d %H:%i:%s') AS dateSupport,
DATE_FORMAT(e.datePeriod, '%Y-%m-%d %H:%i:%s') AS datePeriod,
DATE_FORMAT(e.dateLastAccess, '%Y-%m-%d %H:%i:%s') AS dateLastAccess,
e.lessonNumberViews AS lessonNumberViews,
e.supportNumberRequest AS supportNumberRequest,
e.couponKey AS couponKey,
e.certificate AS certificate,
e.origin,
e.finalAverage,
u.id AS userId,
u.status AS userStatus,
u.name AS userName,
u.email AS userEmail,
u.document AS userDocument,
DATE_FORMAT(u.birthDate, '%Y-%m-%d') AS userBirthDate,
u.phone AS userPhone,
u.address AS userAddress,
u.addressNumber AS userAddressNumber,
u.addressComplement AS userAddressComplement,
u.addressNeighborhood AS userAddressNeighborhood,
u.zipCode AS userZipCode,
u.occupation AS userOccupation,
u.notes AS userNotes,
u.custom AS userCustom,
DATE_FORMAT(u.dateRegister, '%Y-%m-%d %H:%i:%s') AS userDateRegister,
u.acceptTerms AS userAcceptTerms,
u.customField AS userCustomField,
ct.name AS cityName,
st.name AS stateName,
cty.name AS countryName,
c.title,
c.numberLesson,
c.certificateAverage,
ca.category,
g.name AS groupName
");
$query->innerJoin('EADPlataforma:Course', 'c', 'WITH', 'c.id = e.course');
$query->innerJoin('EADPlataforma:Category', 'ca', 'WITH', 'ca.id = c.category');
$query->innerJoin('EADPlataforma:User', 'u', 'WITH', 'u.id = e.user');
$query->leftJoin('EADPlataforma:City', 'ct', 'WITH', 'ct.id = u.city');
$query->leftJoin('EADPlataforma:State', 'st', 'WITH', 'st.id = u.state');
$query->leftJoin('EADPlataforma:Country', 'cty', 'WITH', 'cty.id = u.country');
$query->andWhere('e.deleted = :deleted');
$query->andWhere('u.deleted = :deleted');
$query->andWhere('c.deleted = :deleted');
$query->andWhere('u.id > 1');
$query->andWhere('u.status != :userStatus');
$query->setParameter('userStatus', UserEnum::INACTIVE);
$query->setParameter('deleted', UserEnum::ITEM_NO_DELETED);
if(!is_null($dateStart) && !is_null($dateEnd)){
$query->andWhere('DATE(e.dateRegister) BETWEEN :dateStart AND :dateEnd');
$query->setParameter('dateStart', $dateStart);
$query->setParameter('dateEnd', $dateEnd);
}
if(!empty($courseId)){
$query->andWhere('e.course = :course')->setParameter('course', $courseId);
}
if(!empty($groupId)){
$query->innerJoin(
'EADPlataforma:Group', 'g', 'WITH',
'e.course MEMBER OF g.course AND e.user MEMBER OF g.user'
);
$query->andWhere('g.id = :groupId');
$query->setParameter('groupId', $groupId);
}else{
$query->leftJoin(
'EADPlataforma:Group', 'g', 'WITH',
'e.course MEMBER OF g.course AND e.user MEMBER OF g.user'
);
}
if(!empty($userId)){
$query->andWhere('e.user = :user')->setParameter('user', $userId);
}
if(!empty($teacherId)){
$subQuery = $this->createQueryBuilder('course_team');
$subQuery->select('IDENTITY(cteam.course)');
$subQuery->from('EADPlataforma:CourseTeam', 'cteam');
$subQuery->andWhere('cteam.user = :teacherId');
$subQuery = $subQuery->getDQL();
$query->andWhere($query->expr()->in('e.course', $subQuery));
$query->setParameter('teacherId', $teacherId);
}
if($status == EnrollmentEnum::STATUS_EXPIRED){
$query->andWhere('e.datePeriod < :now');
$query->setParameter('now', date('Y-m-d H:i:s'));
$query->andWhere('e.status = :status');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
}else if($status == EnrollmentEnum::STATUS_ACTIVE){
$query->andWhere('e.datePeriod >= :now');
$query->setParameter('now', date('Y-m-d H:i:s'));
$query->andWhere('e.status = :status');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
}else if(!empty($status)){
$query->andWhere('e.status = :status');
$query->setParameter('status', $status);
}
$data = $query->getQuery()->execute();
return $data;
}
public function getEnrollmentBeforeExpireByCourse(Course $course, string $dateExpire)
{
$query = $this->createQueryBuilder('e');
$query->andWhere('e.deleted = 0');
$query->andWhere('e.course = :course');
$query->andWhere('DATE(e.datePeriod) = :datePeriod');
$query->setParameter('course', $course->getId());
$query->setParameter('datePeriod', $dateExpire);
return $query->getQuery()->execute();
}
public function updateDataAccessLog(Enrollment $enrollment, ?bool $updateDate = true){
$course = $enrollment->getCourse();
$courseId = $enrollment->getCourse()->getId();
$userId = $enrollment->getUser()->getId();
$courseRepository = $this->em->getRepository(Course::class);
$lessonSupportRepository = $this->em->getRepository(LessonSupport::class);
$lessonLogRepository = $this->emEadmin->getRepository(LessonLog::class);
$lessonLogOriginRepository = $this->em->getRepository(LessonLogOrigin::class);
$isStudent = $courseRepository->isStudent($course);
$lessonsNumberComplete = $lessonLogRepository->countLessonLogCompleteByUser(
$course,
$enrollment->getUser()
);
$lessonsDateLastAccess = $lessonLogRepository->getLessonDateLastAccess(
$courseId,
$userId
);
$lessonsNumberViews = $lessonLogRepository->getLessonNumberViews(
$courseId,
$userId
);
$lessonTimeWatch = $lessonLogRepository->userLessonTimeWatch(
$course,
$enrollment->getUser()
);
$supportNumberRequest = $lessonSupportRepository->getSupportNumberRequestByEnrollment(
$enrollment
);
$enrollment->setLessonTimeWatch(
!empty($lessonTimeWatch) ? $lessonTimeWatch : null
);
if($this->getUser()){
if($this->getUser()->getId() == $userId && $updateDate){
if(empty($lessonsDateLastAccess)){
$lessonsDateLastAccess = date('Y-m-d H:i:s');
}
$enrollment->setDateLastAccess(
!empty($lessonsDateLastAccess) ? $lessonsDateLastAccess : null
);
if(empty($enrollment->getDateStart()) && !empty($lessonsDateLastAccess)){
if($isStudent){
//send mkt start course
$marketingService = $this->generalService->getService(
'Marketing\\MarketingService'
);
$marketingService->setTag(TagsMarketingEnum::TAG_BEGIN_COURSE);
$marketingService->setTextComplement($course->getTitle());
$marketingService->setUser($this->getUser());
$marketingService->send();
}
$enrollment->setDateStart(date('Y-m-d H:i:s'));
}
}
}
$enrollment->setLessonNumberComplete((int)$lessonsNumberComplete);
$enrollment->setLessonNumberViews((int)$lessonsNumberViews);
$enrollment->setSupportNumberRequest((int)$supportNumberRequest);
$this->em->flush();
return $enrollment;
}
public function getEnrollmentForPresence(
Course $course,
?bool $active = true,
?int $user = null,
?int $groupId = null,
?string $dateStart = null,
?string $dateEnd = null
)
{
$query = $this->createQueryBuilder('e');
$query->innerJoin('EADPlataforma:User', 'u', 'WITH', 'u.id = e.user');
if($active){
$query->andWhere('e.datePeriod >= :now');
$query->setParameter('now', date('Y-m-d H:i:s'));
$query->andWhere('e.status = :status');
$query->setParameter('status', EnrollmentEnum::STATUS_ACTIVE);
}
if(!empty($user)){
$query->andWhere('e.user = :user');
$query->setParameter('user', $user);
}
if(!empty($groupId)){
$query->innerJoin(
'EADPlataforma:Group', 'g', 'WITH',
'e.course MEMBER OF g.course AND e.user MEMBER OF g.user'
);
$query->andWhere('g.id = :groupId');
$query->setParameter('groupId', $groupId);
}
if(!is_null($dateStart) && !is_null($dateEnd)){
$query->andWhere('DATE(e.dateLastAccess) BETWEEN :dateStart AND :dateEnd');
$query->setParameter('dateStart', $dateStart);
$query->setParameter('dateEnd', $dateEnd);
}
$query->andWhere('u.status != :userStatus');
$query->setParameter('userStatus', UserEnum::INACTIVE);
$query->andWhere('e.deleted = 0');
$query->andWhere('u.deleted = 0');
$query->andWhere('u.id > 1');
$query->andWhere('e.course = :course');
$query->setParameter('course', $course->getId());
return $query->getQuery()->execute();
}
public function restore(Enrollment $enrollment, $typeItem)
{
$itemId = $enrollment->getId();
$dateNow = date('Y-m-d H:i:s');
$enrollment->setUserDelete($this->getUser());
$enrollment->setDateDelete(date('Y-m-d H:i:s'));
$enrollment->restore();
$this->em->getRepository(Trash::class)->deleteTrash($itemId, $typeItem);
$examUserRepository = $this->em->getRepository(ExamUser::class);
$examUsers = $examUserRepository->findBy([
"course" => $enrollment->getCourse()->getId(),
"user" => $enrollment->getUser()->getId(),
"deleted" => ExamUserEnum::ITEM_ON_TRASH
]);
foreach ($examUsers as $examUser) {
$this->em->getRepository(ExamUser::class)->restoreByExamUser(
$examUser->getId(),
EnrollmentEnum::ITEM_NO_DELETED,
EnrollmentEnum::CASCADE,
$this->getUser() ?? null,
$dateNow
);
}
}
public function delete(Enrollment $enrollment, $typeItem, $permission, $isTrash)
{
$userPermissionUtil = $this->generalService->getUtil('UserPermissionUtil');
if($isTrash == 1){
$permission = $userPermissionUtil->getPermission("trash", "delete");
}
$isInTeam = false;
$course = $enrollment->getCourse();
$dateNow = date('Y-m-d H:i:s');
if($this->getUser()){
$isInTeam = $this->em->getRepository(CourseTeam::class)->userExistInCourseTeam(
$course,
$this->getUser()
);
}
if($isInTeam || $userPermissionUtil->isHigh($permission)){
$enrollment->setUserDelete($this->getUser());
$enrollment->setDateDelete(date('Y-m-d H:i:s'));
$enrollment->individual();
if($enrollment->isOnTrash() || $enrollment->isDeleted()){
$enrollment->delete();
$itemId = $enrollment->getId();
$this->em->getRepository(Trash::class)->deleteTrash($itemId, $typeItem);
}
if(!$enrollment->isOnTrash() && !$enrollment->isDeleted()){
$enrollment->trash();
$this->em->getRepository(Trash::class)->insertTrash(
$enrollment,
$typeItem,
"Aluno: {$enrollment->getUser()->getName()} | Curso: {$enrollment->getCourse()->getTitle()}"
);
}
$examUserRepository = $this->em->getRepository(ExamUser::class);
$examUsers = $examUserRepository->findBy([
"course" => $enrollment->getCourse()->getId(),
"user" => $enrollment->getUser()->getId(),
"deleted" => ExamUserEnum::ITEM_NO_DELETED
]);
foreach ($examUsers as $examUser) {
$this->em->getRepository(ExamUser::class)->deleteByExamUser(
$examUser->getId(),
EnrollmentEnum::ITEM_ON_TRASH,
EnrollmentEnum::CASCADE,
($this->getUser() ? $this->getUser()->getId() : null),
$dateNow
);
}
}
$this->em->flush();
}
public function restoreByUser($userId, $deleted, $typeDelete, $userDelete, $dateNow){
$sql = "UPDATE EADPlataforma:Enrollment AS e
SET e.deleted = :deleted, e.userDelete = :userDelete,
e.dateDelete = :dateNow
WHERE e.deleted = (1 - :deleted)
AND e.typeDelete = :typeDelete
AND e.user = :userId";
$query = $this->em->createQuery($sql);
$query->setParameter('userId', $userId);
$query->setParameter('deleted', $deleted);
$query->setParameter('typeDelete', $typeDelete);
$query->setParameter('userDelete', $userDelete);
$query->setParameter('dateNow', $dateNow);
$query->execute();
return true;
}
public function deleteByUser($userId, $deleted, $typeDelete, $userDelete, $dateNow){
$sql = "UPDATE EADPlataforma:Enrollment AS e
SET e.deleted = :deleted, e.typeDelete = :typeDelete,
e.userDelete = :userDelete, e.dateDelete = :dateNow
WHERE e.deleted = (:deleted - 1)
AND e.user = :userId";
$query = $this->em->createQuery($sql);
$query->setParameter('userId', $userId);
$query->setParameter('deleted', $deleted);
$query->setParameter('typeDelete', $typeDelete);
$query->setParameter('userDelete', $userDelete);
$query->setParameter('dateNow', $dateNow);
$query->execute();
return true;
}
public function restoreByCourse($courseId, $deleted, $typeDelete, $userDelete, $dateNow){
$sql = "UPDATE EADPlataforma:Enrollment AS e
SET e.deleted = :deleted, e.userDelete = :userDelete,
e.dateDelete = :dateNow
WHERE e.deleted = (1 - :deleted)
AND e.typeDelete = :typeDelete
AND e.course = :courseId";
$query = $this->em->createQuery($sql);
$query->setParameter('courseId', $courseId);
$query->setParameter('deleted', $deleted);
$query->setParameter('typeDelete', $typeDelete);
$query->setParameter('userDelete', $userDelete);
$query->setParameter('dateNow', $dateNow);
$query->execute();
return true;
}
public function deleteByCourse($courseId, $deleted, $typeDelete, $userDelete, $dateNow){
$sql = "UPDATE EADPlataforma:Enrollment AS e
SET e.deleted = :deleted, e.typeDelete = :typeDelete,
e.userDelete = :userDelete, e.dateDelete = :dateNow
WHERE e.deleted = (:deleted - 1)
AND e.course = :courseId";
$query = $this->em->createQuery($sql);
$query->setParameter('courseId', $courseId);
$query->setParameter('deleted', $deleted);
$query->setParameter('typeDelete', $typeDelete);
$query->setParameter('userDelete', $userDelete);
$query->setParameter('dateNow', $dateNow);
$query->execute();
return true;
}
public function deleteTrashCron()
{
$sql = "UPDATE EADPlataforma:Enrollment AS e SET e.deleted = 2
WHERE e.dateDelete <= :date AND e.deleted = 1 ";
$query = $this->em->createQuery($sql);
$query->setParameter('date', date('Y-m-d H:i:s', strtotime('-90 days')));
$query->execute();
}
public function bulkUpdateStatus(array $enrollments, int $status): array
{
foreach ($enrollments as $enrollment) {
$enrollment->setStatus($status);
}
$this->em->flush();
return $enrollments;
}
public function updateEnrollmentsWithGroup(array $enrollments, array $data)
{
$dates = $this->verifyDate($data);
foreach ($enrollments as $enrollment) {
$enrollment->setDatePeriod($dates['dateAccessConclusion']);
$enrollment->setDateSupport($dates['dateSupportConclusion']);
}
$this->em->flush();
return $enrollments;
}
public function verifyDate($data)
{
$dates = [];
if($data["typeDateAccess"] == GroupEnum::TYPE_DATE_FIXED){
$dateAccessConclusion = $data["dateAccessConclusion"];
}
if($data["typeDateSupport"] == GroupEnum::TYPE_DATE_FIXED){
$dateSupportConclusion = $data["dateSupportConclusion"];
}
if($data["typeDateAccess"] == GroupEnum::TYPE_DATE_PERIOD){
$period = $data["dateAccessDays"];
$dateNow = date('Y-m-d H:i:s');
$dateSupportConclusion = date('Y-m-d H:i:s', strtotime("{$dateNow} + {$period} days"));
}
if($data["typeDateSupport"] == GroupEnum::TYPE_DATE_PERIOD){
$period = $data["dateSupportDays"];
$dateNow = date('Y-m-d H:i:s');
$dateSupportConclusion = date('Y-m-d H:i:s', strtotime("{$dateNow} + {$period} days"));
}
$dates = [
"dateAccessConclusion" => $dateAccessConclusion,
"dateSupportConclusion" => $dateSupportConclusion,
];
return $dates;
}
public function getSituation(int $progress, ?float $certificateAverage, ?float $finalAverage)
{
$situation = EnrollmentEnum::SITUATION_NOT_STARTED;
if($progress >= 100){
$situation = EnrollmentEnum::SITUATION_COMPLETED;
}else if($progress > 0){
$situation = EnrollmentEnum::SITUATION_STARTED;
}
if(!empty($finalAverage) && $situation == EnrollmentEnum::SITUATION_COMPLETED){
if($finalAverage >= $certificateAverage){
return $this->configuration->getLanguage('approved', 'enrollments');
}else{
return $this->configuration->getLanguage('disapproved', 'enrollments');
}
}
$situationLabels = [
EnrollmentEnum::SITUATION_NOT_STARTED => "not_started",
EnrollmentEnum::SITUATION_STARTED => "in_progress",
EnrollmentEnum::SITUATION_COMPLETED => "completed",
];
$index = $situationLabels[$situation];
return $this->configuration->getLanguage($index, 'enrollments');
}
}