-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodels.py
More file actions
1257 lines (1087 loc) · 45.7 KB
/
models.py
File metadata and controls
1257 lines (1087 loc) · 45.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import ipaddress
import re
import random
import uuid
import logging
from enum import StrEnum
from typing import Any
from django.conf import settings
from django.conf.global_settings import LANGUAGES
from django.core.files.storage import default_storage
from django.urls import reverse
from django.db import models, transaction, IntegrityError
from django.core.validators import (
MaxValueValidator,
MinValueValidator,
MinLengthValidator,
)
from django_email_learning.services.email_sender_service import EmailSenderService
from django_email_learning.services.metrics_service import MetricsService
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.core.exceptions import ImproperlyConfigured
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
from django.forms import ValidationError
from django.contrib.auth.models import User
from django.utils import timezone
from django.utils.translation import gettext as _
from django.utils.translation import ngettext
from datetime import timedelta
from django_email_learning.services import jwt_service
from django_email_learning.services.utils import mask_email
from PIL import Image
from typing import Optional
from datetime import datetime
logger = logging.getLogger(__name__)
class EnrollmentStatus(StrEnum):
UNVERIFIED = "unverified"
ACTIVE = "active"
COMPLETED = "completed"
DEACTIVATED = "deactivated"
class DeactivationReason(StrEnum):
CANCELED = "canceled"
BLOCKED = "blocked"
FAILED = "failed"
INACTIVE = "inactive"
class DeliveryStatus(StrEnum):
SCHEDULED = "scheduled"
PROCESSING = "processing"
DELIVERED = "delivered"
CANCELED = "canceled"
BLOCKED = "blocked"
METRIC_SERVICE = MetricsService()
def is_domain_or_ip(value: str) -> None:
"""
Validate if the given value is a valid domain name or IP address.
Raises:
ValueError: If the value is not a valid domain or IP address.
"""
try:
ipaddress.ip_address(value)
except ValueError:
DOMAIN_REGEX = re.compile(r"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$")
if not bool(DOMAIN_REGEX.match(value.lower())):
raise ValueError(f"{value} is not a valid domain or IP address")
class Organization(models.Model):
name = models.CharField(max_length=200, unique=True)
logo = models.ImageField(upload_to="organization_logos/", null=True, blank=True)
description = models.TextField(null=True, blank=True)
website = models.URLField(max_length=500, null=True, blank=True)
youtube_channel = models.URLField(max_length=500, null=True, blank=True)
linkedin_page = models.URLField(max_length=500, null=True, blank=True)
is_public = models.BooleanField(default=True)
def __str__(self) -> str:
return self.name
@property
def public_url(self) -> str:
if not self.is_public:
raise ValueError("Organization is not public, no public URL available.")
path = reverse(
"django_email_learning:public:organization_view",
kwargs={"organization_id": self.id},
)
return f"{settings.DJANGO_EMAIL_LEARNING['SITE_BASE_URL']}{path}"
def replace_logo(self, file_path: str) -> str:
if default_storage.exists(file_path):
allowed_extensions = [".jpg", ".jpeg", ".png", ".svg"]
if not any(file_path.lower().endswith(ext) for ext in allowed_extensions):
raise ValueError("Logo must be an image file with a valid extension.")
final_path = f"organization_logos/{self.id}/{file_path.split('/')[-1]}"
default_storage.save(final_path, default_storage.open(file_path))
self.logo = final_path
self.save()
return final_path
else:
raise ValueError("Logo file does not exist.")
class OrganizationUser(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="memberships")
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
role = models.CharField(
max_length=50,
choices=[
("admin", "Admin"),
("editor", "Editor"),
("instructor", "Instructor"),
("viewer", "Viewer"),
],
db_index=True,
)
display_name = models.CharField(max_length=200, null=True, blank=True)
photo = models.ImageField(upload_to="org_user_photos/", null=True, blank=True)
def __str__(self) -> str:
return f"{self.user.username} - {self.organization.name}"
def can_act_as_instructor(self) -> bool:
if self.role == "instructor":
return True
if self.role == "admin" and self.display_name:
return True
return False
def save(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
if self.role == "instructor" and not self.display_name:
raise ValidationError("Instructor role requires a display name.")
super().save(*args, **kwargs)
class Meta:
unique_together = [["user", "organization"]]
class EncryptionMixin(models.Model):
salt = models.CharField(max_length=32, editable=False)
@classmethod
def _fernet(cls, salt: str) -> Fernet:
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt.encode(),
iterations=100000,
)
DJANGO_EMAIL_LEARNING_SETTINGS: dict = getattr(
settings, "DJANGO_EMAIL_LEARNING", {}
)
try:
secret = DJANGO_EMAIL_LEARNING_SETTINGS["ENCRYPTION_SECRET_KEY"]
except KeyError:
raise ImproperlyConfigured(
"DJANGO_EMAIL_LEARNING['ENCRYPTION_SECRET_KEY'] must be set in settings.py"
)
key = base64.urlsafe_b64encode(kdf.derive(secret.encode()))
return Fernet(key)
@classmethod
def encrypted_value(cls, value: str, salt: str) -> str:
f = cls._fernet(salt)
return f.encrypt(value.encode()).decode()
def _encrypt_password(self, password: str) -> str:
if not self.salt:
self.salt = (
base64.urlsafe_b64encode(uuid.uuid4().bytes).decode().rstrip("=")
)
f = self._fernet(self.salt)
return f.encrypt(password.encode()).decode()
def decrypt_password(self, encrypted_password: str) -> str:
f = self._fernet(self.salt)
return f.decrypt(encrypted_password.encode()).decode()
class Meta:
abstract = True
class ImapConnection(EncryptionMixin):
server = models.CharField(max_length=200, validators=[is_domain_or_ip])
port = models.IntegerField(db_default=993)
email = models.EmailField(max_length=200, unique=True)
password = models.CharField(max_length=200)
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
def __str__(self) -> str:
return f"{self.email}|{self.server}:{self.port}"
def save(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
if self.password:
try:
self.decrypt_password(self.password)
# Password is already encrypted
except InvalidToken:
self.password = self._encrypt_password(self.password)
if self.server:
self.server = self.server.lower()
self.full_clean()
super().save(*args, **kwargs)
class InboxFolder(models.Model):
imap_connection = models.ForeignKey(
ImapConnection, on_delete=models.CASCADE, related_name="folders"
)
folder_name = models.CharField(max_length=200)
def __str__(self) -> str:
return f"{self.imap_connection.email} - {self.folder_name}"
class Course(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(
max_length=50,
help_text="A short label for the course, used in URLs or email interactive actions. You can not edit it later.",
)
description = models.TextField(null=True, blank=True)
enabled = models.BooleanField(default=False)
imap_connection = models.ForeignKey(
ImapConnection, on_delete=models.SET_NULL, null=True, blank=True
)
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
image = models.ImageField(upload_to="course_images/", null=True, blank=True)
language = models.CharField(
max_length=10,
choices=LANGUAGES,
default="en",
)
target_audience = models.TextField(null=True, blank=True)
is_public = models.BooleanField(default=True)
def __str__(self) -> str:
return self.title
class Meta:
unique_together = [["slug", "organization"], ["title", "organization"]]
def delete(
self, using: Any | None = None, keep_parents: bool = False
) -> tuple[int, dict[str, int]]:
if self.enabled:
raise ValueError(
"Course can not be deleted when enabled, please disable the course first!"
)
return super().delete(using, keep_parents)
@property
def enrollments_count(self) -> dict[str, int]:
unverified_count = self.enrollment_set.filter(
status=EnrollmentStatus.UNVERIFIED
).count()
active_count = self.enrollment_set.filter(
status=EnrollmentStatus.ACTIVE
).count()
completed_count = self.enrollment_set.filter(
status=EnrollmentStatus.COMPLETED
).count()
deactivated_count = self.enrollment_set.filter(
status=EnrollmentStatus.DEACTIVATED
).count()
total_count = self.enrollment_set.count()
return {
EnrollmentStatus.UNVERIFIED: unverified_count,
EnrollmentStatus.ACTIVE: active_count,
EnrollmentStatus.COMPLETED: completed_count,
EnrollmentStatus.DEACTIVATED: deactivated_count,
"total": total_count,
}
def generate_unsubscribe_link(self, email: str) -> str:
payload = {
"email": email,
"course_slug": self.slug,
"organization_id": self.organization.id,
}
token = jwt_service.generate_jwt(payload=payload)
unsubscribe_path = reverse("django_email_learning:personalised:unsubscribe")
link = f"{settings.DJANGO_EMAIL_LEARNING['SITE_BASE_URL']}{unsubscribe_path}?token={token}"
return link
def replace_image(self, file_path: str) -> str:
if default_storage.exists(file_path):
with default_storage.open(file_path) as f:
img = Image.open(f)
width, height = img.size
if width < 580 or height < 360:
raise ValueError(
"Image dimensions must be at least 580x360 pixels."
)
allowed_extensions = [".jpg", ".jpeg", ".png", ".svg"]
if not any(file_path.lower().endswith(ext) for ext in allowed_extensions):
raise ValueError("Image must be an image file with a valid extension.")
final_path = f"organization/{self.organization.id}/course_images/{self.id}_{file_path.split('/')[-1]}"
default_storage.save(final_path, default_storage.open(file_path))
self.image = final_path
self.save()
return final_path
else:
raise ValueError("Image file does not exist.")
class CourseInstructor(models.Model):
course = models.ForeignKey(
Course, on_delete=models.CASCADE, related_name="instructors"
)
org_user = models.ForeignKey(OrganizationUser, on_delete=models.CASCADE)
def __str__(self) -> str:
return f"{self.course.title} - {self.org_user.user.email}"
def save(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
if self.org_user.organization != self.course.organization:
raise ValidationError(
"Instructor must belong to the same organization as the course."
)
if not self.org_user.can_act_as_instructor():
raise ValidationError("Organization user doesn't have instructor role.")
super().save(*args, **kwargs)
class Meta:
unique_together = [["course", "org_user"]]
class ExternalReference(models.Model):
course = models.ForeignKey(
Course, on_delete=models.CASCADE, related_name="external_references"
)
name = models.CharField(max_length=200)
url = models.URLField(max_length=500)
def __str__(self) -> str:
return f"{self.course.title} - {self.name}"
class Lesson(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
def __str__(self) -> str:
return self.title
class QuizSelectionStrategy(StrEnum):
ALL_QUESTIONS = "all"
RANDOM_QUESTIONS = "random"
class Quiz(models.Model):
title = models.CharField(max_length=500)
required_score = models.IntegerField(validators=[MaxValueValidator(100)])
selection_strategy = models.CharField(
max_length=50,
choices=[
(QuizSelectionStrategy.ALL_QUESTIONS.value, "All Questions"),
(QuizSelectionStrategy.RANDOM_QUESTIONS.value, "Random Questions"),
],
)
deadline_days = models.IntegerField(
help_text="Time limit to complete the quiz in days. 0 indicates no deadline.",
validators=[MinValueValidator(0)],
)
limited_attempts = models.BooleanField(default=True)
is_blocking = models.BooleanField(default=True)
reminder_interval_days = models.IntegerField(
help_text="For quizzes without a deadline (deadline_days = 0), send reminder emails every N days.",
validators=[MinValueValidator(0)],
blank=True,
null=True,
)
class Meta:
verbose_name_plural = "Quizzes"
def __str__(self) -> str:
return self.title
def validate_questions(self) -> None:
if not self.questions.exists():
raise ValidationError("At least one question is required.")
for question in self.questions.all():
try:
question.validate_answers()
except ValidationError as e:
raise ValidationError(f"For question '{question.text}', {e.message}")
def random_question_ids(self) -> list[int]:
question_ids = list(self.questions.values_list("id", flat=True))
if self.selection_strategy == QuizSelectionStrategy.ALL_QUESTIONS.value:
return question_ids
if len(question_ids) <= 5:
return question_ids
number_of_questions = int(max(5, len(question_ids) // 1.5))
selected_ids = random.sample(question_ids, k=number_of_questions)
return selected_ids
class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name="questions")
text = models.CharField(max_length=500)
priority = models.IntegerField()
def __str__(self) -> str:
return self.text
def validate_answers(self) -> None:
if not self.answers.filter(is_correct=True).exists():
raise ValueError("At least one correct answer is required.")
if self.answers.count() < 2:
raise ValueError("At least two answers are required.")
def is_multiple_choice(self) -> bool:
return self.answers.filter(is_correct=True).count() > 1
class Answer(models.Model):
question = models.ForeignKey(
Question, on_delete=models.CASCADE, related_name="answers"
)
text = models.CharField(max_length=500)
is_correct = models.BooleanField(default=False)
def __str__(self) -> str:
return self.text
def delete(self, *args, **kwargs) -> tuple[int, dict[str, int]]: # type: ignore[no-untyped-def]
if self.question.quiz.coursecontent_set.filter(is_published=True).exists():
raise ValidationError("Cannot delete answers from a published quiz.")
return super().delete(*args, **kwargs)
class Assignment(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
is_blocking = models.BooleanField(
default=True,
help_text="Whether the learner is required to submit the assignment to proceed to the next content.",
)
deadline_days = models.IntegerField(
help_text="Time limit to complete the assignment in days. 0 indicates no deadline.",
validators=[MinValueValidator(0)],
)
requires_text_submission = models.BooleanField(
help_text="Whether the assignment requires text submission."
)
requires_file_submission = models.BooleanField(
help_text="Whether the assignment requires file submission."
)
reminder_interval_days = models.IntegerField(
help_text="For assignments without a deadline (deadline_days = 0), send reminder emails every N days.",
validators=[MinValueValidator(0)],
null=True,
blank=True,
)
def __str__(self) -> str:
return self.title
class CourseContent(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
priority = models.IntegerField()
type = models.CharField(
max_length=50,
choices=[
("lesson", "Lesson"),
("quiz", "Quiz"),
("assignment", "Assignment"),
],
)
lesson = models.ForeignKey(Lesson, null=True, blank=True, on_delete=models.CASCADE)
quiz = models.ForeignKey(Quiz, null=True, blank=True, on_delete=models.CASCADE)
assignment = models.ForeignKey(
Assignment, null=True, blank=True, on_delete=models.CASCADE
)
waiting_period = models.IntegerField(
help_text="Waiting period in seconds after previous content is sent or submited."
)
is_published = models.BooleanField(default=False)
def __str__(self) -> str:
if self.type == "lesson" and self.lesson:
return f"{self.priority} - Lesson: {self.lesson.title}"
elif self.type == "quiz" and self.quiz:
return f"{self.priority} - Quiz: {self.quiz.title}"
elif self.type == "assignment" and self.assignment:
return f"{self.priority} - Assignment: {self.assignment.title}"
return f"{self.course.title} content #{self.priority}"
@property
def deadline_days(self) -> Optional[int]:
if self.type == "quiz" and self.quiz:
return self.quiz.deadline_days
elif self.type == "assignment" and self.assignment:
return self.assignment.deadline_days
return None
@property
def reminder_interval_days(self) -> Optional[int]:
if self.type == "quiz" and self.quiz:
return self.quiz.reminder_interval_days
elif self.type == "assignment" and self.assignment:
return self.assignment.reminder_interval_days
return None
@property
def title(self) -> str:
if self.type == "lesson" and self.lesson:
return self.lesson.title
elif self.type == "quiz" and self.quiz:
return self.quiz.title
elif self.type == "assignment" and self.assignment:
return self.assignment.title
return "Untitled Content"
@property
def limited_attempts(self) -> Optional[bool]:
if self.type == "quiz" and self.quiz:
return self.quiz.limited_attempts
return None
@property
def is_blocking(self) -> Optional[bool]:
if self.type == "quiz" and self.quiz:
return self.quiz.is_blocking
elif self.type == "assignment" and self.assignment:
return self.assignment.is_blocking
return None
def human_readable_waiting_period(self) -> str:
if self.waiting_period < 60:
return ngettext(
"%(count)d second", "%(count)d seconds", self.waiting_period
) % {"count": self.waiting_period}
elif self.waiting_period < 3600:
minutes = self.waiting_period // 60
return ngettext("%(count)d minute", "%(count)d minutes", minutes) % {
"count": minutes
}
elif self.waiting_period < 86400:
hours = self.waiting_period // 3600
return ngettext("%(count)d hour", "%(count)d hours", hours) % {
"count": hours
}
else:
days = self.waiting_period // 86400
return ngettext("%(count)d day", "%(count)d days", days) % {"count": days}
def _validate_content(self) -> None:
if self.type == "lesson" and not self.lesson:
raise ValidationError("Lesson must be provided for lesson content.")
if self.type == "quiz" and not self.quiz:
raise ValidationError("Quiz must be provided for quiz content.")
if self.type == "assignment" and not self.assignment:
raise ValidationError("Assignment must be provided for assignment content.")
if self.type == "lesson" and self.lesson:
self.lesson.full_clean()
elif self.type == "quiz" and self.quiz:
self.quiz.full_clean()
elif self.type == "assignment" and self.assignment:
self.assignment.full_clean()
def full_clean(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
self._validate_content()
return super().full_clean(*args, **kwargs)
def save(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
self.full_clean()
super().save(*args, **kwargs)
def get_next(self) -> Optional["CourseContent"]:
next_content = (
CourseContent.objects.filter(
course=self.course, is_published=True, priority__gt=self.priority
)
.order_by("priority")
.first()
)
return next_content
class Meta:
constraints = [
models.UniqueConstraint(
fields=["course", "quiz"],
condition=models.Q(quiz__isnull=False),
name="unique_quiz_per_course",
),
models.UniqueConstraint(
fields=["course", "lesson"],
condition=models.Q(lesson__isnull=False),
name="unique_lesson_per_course",
),
models.UniqueConstraint(
fields=["course", "assignment"],
condition=models.Q(assignment__isnull=False),
name="unique_assignment_per_course",
),
models.UniqueConstraint(
fields=["course", "priority"],
name="unique_priority_per_course",
),
]
class BlockedEmail(models.Model):
email = models.EmailField(unique=True)
def __str__(self) -> str:
return self.email
def save(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
self.email = self.email.lower()
self.full_clean()
super().save(*args, **kwargs)
class Learner(models.Model):
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
email = models.EmailField()
created_at = models.DateTimeField(auto_now_add=True)
photo = models.ImageField(upload_to="learner_photos/", null=True, blank=True)
def save(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
self.email = self.email.lower()
self.full_clean()
super().save(*args, **kwargs)
@property
def enrollments_count(self) -> dict[str, int]:
return {
"total": self.enrollment_set.count(),
"completed": self.enrollment_set.filter(
status=EnrollmentStatus.COMPLETED
).count(),
}
class Meta:
unique_together = [["organization", "email"]]
def __str__(self) -> str:
return self.email
class Enrollment(models.Model):
state_transitions = {
EnrollmentStatus.UNVERIFIED: [
EnrollmentStatus.ACTIVE,
EnrollmentStatus.DEACTIVATED,
],
EnrollmentStatus.ACTIVE: [
EnrollmentStatus.COMPLETED,
EnrollmentStatus.DEACTIVATED,
],
EnrollmentStatus.COMPLETED: [],
EnrollmentStatus.DEACTIVATED: [],
}
learner = models.ForeignKey(Learner, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
enrolled_at = models.DateTimeField(auto_now_add=True)
activated_at = models.DateTimeField(null=True, blank=True)
final_state_at = models.DateTimeField(null=True, blank=True)
status = models.CharField(
max_length=50,
choices=[
(EnrollmentStatus.UNVERIFIED, "Unverified"),
(EnrollmentStatus.ACTIVE, "Active"),
(EnrollmentStatus.COMPLETED, "Completed"),
(EnrollmentStatus.DEACTIVATED, "Deactivated"),
],
default=EnrollmentStatus.UNVERIFIED,
)
deactivation_reason = models.CharField(
null=True,
blank=True,
choices=[
(DeactivationReason.CANCELED, "Canceled"),
(DeactivationReason.BLOCKED, "Blocked"),
(DeactivationReason.FAILED, "Failed"),
(DeactivationReason.INACTIVE, "Inactive"),
],
max_length=50,
)
activation_code = models.CharField(max_length=6, null=True, blank=True)
def save(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
if self.pk:
old_status = Enrollment.objects.get(pk=self.pk).status
old_status = EnrollmentStatus(old_status)
if old_status != self.status:
allowed_transitions = self.state_transitions.get(old_status, [])
if self.status not in allowed_transitions:
raise ValidationError(
f"Invalid status transition from {old_status} to {self.status}."
)
else:
self.activation_code = "".join(random.choices("0123456789", k=6))
if self.status != "deactivated" and self.deactivation_reason is not None:
raise ValidationError(
"Deactivation reason must be null unless status is 'deactivated'."
)
if self.status == "deactivated" and not self.deactivation_reason:
raise ValidationError(
"Deactivation reason must be provided when status is 'deactivated'."
)
self.full_clean()
if self.status == EnrollmentStatus.ACTIVE and self.activated_at is None:
self.activated_at = timezone.now()
if self.status in [EnrollmentStatus.COMPLETED, EnrollmentStatus.DEACTIVATED]:
if self.final_state_at is None:
self.final_state_at = timezone.now()
super().save(*args, **kwargs)
def __str__(self) -> str:
return f"{self.learner.email} - {self.course.title} ({self.status})"
class Meta:
constraints = [
models.UniqueConstraint(
fields=["learner", "course"],
condition=models.Q(status__in=["unverified", "active", "completed"]),
name="unique_active_enrollment",
)
]
def graduate(self) -> None:
with transaction.atomic():
if self.status != EnrollmentStatus.ACTIVE:
raise ValidationError(
"Only active enrollments can be marked as completed."
)
self.status = EnrollmentStatus.COMPLETED
self.final_state_at = timezone.now()
METRIC_SERVICE.user_completed_course(
course_slug=self.course.slug,
organization_id=self.course.organization.id,
)
logger.info(
f"Learner ID {self.learner.id} has completed the course {self.course.title}."
)
self.save()
self.send_certificate_form()
def send_certificate_form(self) -> None:
if self.status != EnrollmentStatus.COMPLETED:
raise ValidationError(
"Certificate form can only be sent for completed enrollments."
)
token_payload = {
"enrollment_id": self.id,
}
logging.info(
f"Executing SendCertificateFormCommand for enrollment ID {self.id}"
)
token = jwt_service.generate_jwt(token_payload, exp=datetime.max)
certificate_path = reverse(
"django_email_learning:personalised:certificate_form"
)
link = f"{settings.DJANGO_EMAIL_LEARNING['SITE_BASE_URL']}{certificate_path}?token={token}"
subject = _("Finalize your Certificate")
context = {
"course_title": self.course.title,
"organization_name": self.course.organization.name,
"link": link,
}
payload = render_to_string("emails/certificate_form.txt", context)
email_service = EmailSenderService()
email_message = EmailMultiAlternatives(
subject=subject,
body=payload,
from_email=email_service.from_email,
to=[self.learner.email],
)
email_message.attach_alternative(
render_to_string("emails/certificate_form.html", context), "text/html"
)
email_service.send(email_message)
logging.info(f"Certificate form email sent for enrollment ID {self.id}")
def fail(self) -> None:
if self.status != EnrollmentStatus.ACTIVE:
raise ValidationError("Only active enrollments can be marked as failed.")
self.status = EnrollmentStatus.DEACTIVATED
self.deactivation_reason = DeactivationReason.FAILED
self.final_state_at = timezone.now()
METRIC_SERVICE.user_enrollment_deactivated(
course_slug=self.course.slug,
organization_id=self.course.organization.id,
reason=DeactivationReason.FAILED,
)
logger.info(
f"Learner ID {self.learner.id} has failed the course {self.course.title}."
)
self.save()
@transaction.atomic()
def schedule_first_content_delivery(self) -> None:
first_content = (
CourseContent.objects.filter(course=self.course, is_published=True)
.order_by("priority")
.first()
)
if first_content:
delivery = ContentDelivery.objects.create(
enrollment=self,
course_content=first_content,
)
scheduled = DeliverySchedule.objects.create(
time=timezone.now() + timedelta(seconds=first_content.waiting_period),
delivery=delivery,
)
scheduled.generate_link()
else:
raise ValidationError("No published content available to schedule.")
@property
def progress_percentage(self) -> int:
total_content = self.course.coursecontent_set.filter(is_published=True).count()
if total_content == 0:
return 0
delivered_content = (
ContentDelivery.objects.filter(
enrollment=self,
delivery_schedules__status=DeliveryStatus.DELIVERED,
course_content__is_published=True,
)
.distinct()
.count()
)
progress = int((delivered_content / total_content) * 100)
return progress
class Certificate(models.Model):
enrollment = models.OneToOneField(
Enrollment, on_delete=models.CASCADE, related_name="certificate"
)
issued_at = models.DateTimeField(auto_now_add=True)
name_on_certificate = models.CharField(max_length=200)
random_suffix = models.IntegerField()
@property
def certificate_number(self) -> str:
return f"{self.enrollment.course.id}-{self.enrollment.id}-{self.id}-{self.random_suffix}"
def save( # type: ignore[no-untyped-def]
self, *, force_insert=False, force_update=False, using=None, update_fields=None
):
if not self.random_suffix:
self.random_suffix = random.randint(100000, 999999)
return super().save(
force_insert=force_insert,
force_update=force_update,
using=using,
update_fields=update_fields,
)
class ContentDelivery(models.Model):
class ReminderStatus(models.TextChoices):
NOT_APPLICABLE = "not_applicable", "Not Applicable"
PENDING = "pending", "Pending"
PROCESSING = "processing", "Processing"
SENT = "sent", "Sent"
BLOCKED = "blocked", "Blocked"
enrollment = models.ForeignKey(
Enrollment, on_delete=models.CASCADE, related_name="content_deliveries"
)
course_content = models.ForeignKey(CourseContent, on_delete=models.CASCADE)
hash_value = models.CharField(max_length=64, null=True, blank=True)
remind_at = models.DateTimeField(null=True, blank=True)
valid_until = models.DateTimeField(null=True, blank=True)
reminder_state = models.CharField(
max_length=50,
choices=ReminderStatus.choices,
default=ReminderStatus.NOT_APPLICABLE,
db_index=True,
)
class Meta:
unique_together = [["enrollment", "course_content"]]
@property
def times_delivered(self) -> int:
return self.delivery_schedules.filter(status=DeliveryStatus.DELIVERED).count() # type: ignore[misc]
def update_hash(self) -> None:
self.hash_value = (
base64.urlsafe_b64encode(uuid.uuid4().bytes).decode().rstrip("=")
)
self.save()
def schedule_next_delivery(self) -> Optional["ContentDelivery"]:
"""
Schedules the next content delivery based on the current content's priority.
Returns the ID of the newly created ContentDelivery if successful, otherwise None.
"""
next_content = (
CourseContent.objects.filter(
course=self.course_content.course,
is_published=True,
priority__gt=self.course_content.priority,
)
.order_by("priority")
.first()
)
if next_content:
delivery, created = ContentDelivery.objects.get_or_create(
enrollment=self.enrollment,
course_content=next_content,
)
schedule = DeliverySchedule.objects.create(
time=timezone.now() + timedelta(seconds=next_content.waiting_period),
delivery=delivery,
)
schedule.generate_link()
return delivery
return None
def repeat_delivery_in_days(self, days: int) -> bool:
"""
Schedules a repeat delivery of the current content after a specified number of days.
Returns True if the repeat delivery was scheduled, otherwise False.
"""
schedule = DeliverySchedule.objects.create(
time=timezone.now() + timedelta(days=days),
delivery=self,
)
schedule.generate_link()
logger.info(
f"Repeat delivery scheduled for ContentDelivery ID {self.id} in {days} days."
)
return True
def calculate_remind_at(self) -> Optional[datetime]:
if self.course_content.quiz or self.course_content.assignment:
if (
self.course_content.deadline_days
and self.course_content.deadline_days > 0
):
if self.course_content.deadline_days > 1:
return timezone.now() + timedelta(
days=self.course_content.deadline_days - 1
)
else:
return timezone.now() + timedelta(
hours=(self.course_content.deadline_days * 24) - 10
)
else:
if self.course_content.reminder_interval_days:
return timezone.now() + timedelta(
days=self.course_content.reminder_interval_days
)
return None
def calculate_valid_until(self) -> Optional[datetime]:
if self.course_content.deadline_days and self.course_content.deadline_days > 0:
return timezone.now() + timedelta(days=self.course_content.deadline_days)
return None
def save(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
self.full_clean()
if not self.hash_value:
self.hash_value = (
base64.urlsafe_b64encode(uuid.uuid4().bytes).decode().rstrip("=")
)
if not self.pk: # Only auto populate remind_at and valid_untill when the delivery is first created
self.remind_at = self.calculate_remind_at()
self.valid_until = self.calculate_valid_until()
if self.remind_at:
self.reminder_state = self.ReminderStatus.PENDING