-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserializers.py
More file actions
1197 lines (1026 loc) · 42 KB
/
serializers.py
File metadata and controls
1197 lines (1026 loc) · 42 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 re
from pydantic import (
BaseModel,
ConfigDict,
Field,
field_serializer,
field_validator,
model_validator,
)
from datetime import datetime
from typing import Optional, Literal, Any, Callable
from django.urls import reverse
from django_email_learning.models import (
ApiKey,
AssignmentSubmission,
ContentDelivery,
CourseInstructor,
DeliveryStatus,
Organization,
ImapConnection,
InboxFolder,
Assignment,
Lesson,
Quiz,
Question,
Answer,
CourseContent,
Course,
QuizSelectionStrategy,
Enrollment,
EnrollmentStatus,
OrganizationUser,
)
from django_email_learning.services.jwt_service import generate_jwt
from django.utils.translation import get_language_info
import enum
class ApiKeyResponse(BaseModel):
id: int
key: str
created_at: datetime
created_by: Optional[str] = None
@staticmethod
def from_django_model(api_key: ApiKey) -> "ApiKeyResponse":
decrypted_key = api_key.decrypt_password(api_key.key)
salt = api_key.salt
jwt_key = generate_jwt({"key": decrypted_key, "salt": salt}, exp=datetime.max)
return ApiKeyResponse.model_validate(
{
"id": api_key.id, # type: ignore[attr-defined]
"key": jwt_key,
"created_at": api_key.created_at,
"created_by": api_key.created_by.username
if api_key.created_by
else None,
}
)
class GetOrCreateUserRequest(BaseModel):
email: str = Field(min_length=1, examples=["user@example.com"])
organization_id: int = Field(gt=0, examples=[1])
@field_validator("email")
def validate_email(cls, email: str) -> str:
email_regex = r"^[\w\.-]+@[\w\.-]+\.\w+$"
if not re.match(email_regex, email):
raise ValueError("Invalid email format")
return email
class CreateEnrollmentRequest(BaseModel):
learner_email: str = Field(min_length=1, examples=["user@example.com"])
class UserResponse(BaseModel):
id: int
email: str
model_config = ConfigDict(from_attributes=True)
class Identifier(BaseModel):
id: int
class CreateCourseRequest(BaseModel):
title: str = Field(min_length=1, examples=["Introduction to Python"])
slug: str = Field(
min_length=1,
examples=["intro-to-python"],
description="A short label for the course, used in URLs or email interactive actions. "
"You can not edit it later.",
)
description: Optional[str] = Field(
None, examples=["A beginner's course on Python programming."]
)
imap_connection_id: Optional[int] = Field(None, examples=[1])
image: Optional[str] = Field(None, examples=["/path/to/course_image.png"])
language: str = Field(min_length=2, max_length=10, examples=["en"])
target_audience: Optional[str] = Field(
None, examples=["Beginners with no prior programming experience."]
)
external_references: Optional[list[dict[str, str]]] = Field(
None,
examples=[
[
{
"name": "GitHub Repository",
"url": "https://github.com/AvaCodeSolutions/django-email-learning",
},
{
"name": "Documentation",
"url": "https://django-email-learning.readthedocs.io/",
},
]
],
)
is_public: bool = Field(default=True, examples=[True])
instructors: Optional[list[int]] = Field(
None,
examples=[[1, 2, 3]],
description="List of organization user IDs to be assigned as instructors for this course.",
)
def to_django_model(self, organization_id: int) -> Course:
organization = Organization.objects.get(id=organization_id)
if not organization:
raise ValueError(f"Organization with id {organization_id} does not exist.")
imap_connection = None
if self.imap_connection_id:
try:
imap_connection = ImapConnection.objects.get(
id=self.imap_connection_id, organization=organization
)
except ImapConnection.DoesNotExist:
raise ValueError(
f"ImapConnection with id {self.imap_connection_id} does not exist."
)
imap_connection = ImapConnection.objects.get(
id=self.imap_connection_id, organization=organization
)
course = Course(
title=self.title,
slug=self.slug,
description=self.description,
organization=organization,
language=self.language,
is_public=self.is_public,
)
if imap_connection:
course.imap_connection = imap_connection
if self.instructors:
course.save() # Save course before adding instructors
for instructor_id in self.instructors:
try:
org_user = OrganizationUser.objects.get(
id=instructor_id, organization=organization
)
except OrganizationUser.DoesNotExist:
raise ValueError(
f"OrganizationUser with id {instructor_id} does not exist in organization {organization.name}."
)
if not org_user.can_act_as_instructor():
raise ValueError(
f"OrganizationUser with id {instructor_id} does not have instructor role."
)
CourseInstructor.objects.create(course=course, org_user=org_user)
if self.image:
course.replace_image(self.image)
if self.target_audience:
course.target_audience = self.target_audience
if self.external_references:
course.save() # Save course before adding external references
for ref in self.external_references:
course.external_references.create(name=ref["name"], url=ref["url"])
return course
class UpdateCourseRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
title: Optional[str] = Field(
None, min_length=1, examples=["Introduction to Python"]
)
description: Optional[str] = Field(
None, examples=["A beginner's course on Python programming."]
)
imap_connection_id: Optional[int] = Field(None, examples=[1])
enabled: Optional[bool] = Field(None, examples=[True])
reset_imap_connection: Optional[bool] = Field(None, examples=[False])
image: Optional[str] = Field(None, examples=["/path/to/course_image.png"])
language: Optional[str] = Field(None, min_length=2, max_length=10, examples=["en"])
target_audience: Optional[str] = Field(
None, examples=["Beginners with no prior programming experience."]
)
external_references: Optional[list[dict[str, str]]] = Field(
None,
examples=[
[
{
"name": "GitHub Repository",
"url": "https://github.com/AvaCodeSolutions/django-email-learning",
},
{
"name": "Documentation",
"url": "https://django-email-learning.readthedocs.io/",
},
]
],
)
is_public: Optional[bool] = Field(None, examples=[True])
instructors: Optional[list[int]] = Field(None, examples=[1, 2, 3])
def to_django_model(self, course_id: int) -> Course:
try:
course = Course.objects.get(id=course_id)
except Course.DoesNotExist:
raise ValueError(f"Course with id {course_id} does not exist.")
if self.reset_imap_connection and self.imap_connection_id is not None:
raise ValueError(
"Cannot set imap_connection_id when reset_imap_connection is True."
)
if self.title is not None:
course.title = self.title
if self.description is not None:
course.description = self.description
if self.imap_connection_id is not None:
imap_connection = ImapConnection.objects.get(id=self.imap_connection_id)
course.imap_connection = imap_connection
if self.enabled is not None:
course.enabled = self.enabled
if self.reset_imap_connection:
course.imap_connection = None
if self.image is not None:
if self.image != "SKIP":
course.replace_image(self.image)
if not self.image:
course.image = None
if self.language is not None:
course.language = self.language
if self.target_audience is not None:
course.target_audience = self.target_audience
if self.external_references is not None:
course.save() # Save course before adding external references
course.external_references.all().delete()
for ref in self.external_references:
course.external_references.create(name=ref["name"], url=ref["url"])
if self.is_public is not None:
course.is_public = self.is_public
if self.instructors is not None:
instructors_to_remove = course.instructors.exclude(
org_user_id__in=self.instructors
)
for instructor in instructors_to_remove:
instructor.delete()
instructors_to_add = set(self.instructors) - set(
course.instructors.values_list("org_user_id", flat=True)
)
for instructor_id in instructors_to_add:
try:
org_user = OrganizationUser.objects.get(
id=instructor_id, organization=course.organization
)
except OrganizationUser.DoesNotExist:
raise ValueError(
f"OrganizationUser with id {instructor_id} does not exist in organization {course.organization.name}."
)
if not org_user.can_act_as_instructor():
raise ValueError(
f"OrganizationUser with id {instructor_id} does not have instructor role."
)
CourseInstructor.objects.create(course=course, org_user=org_user)
return course
class InstructorResponse(BaseModel):
id: int
email: str
model_config = ConfigDict(from_attributes=True)
class CourseResponse(BaseModel):
id: int
title: str
slug: str
description: Optional[str]
organization_id: int
imap_connection_id: Optional[int]
enabled: bool
enrollments_count: dict[str, int]
image: Optional[str] = None
image_path: Optional[str] = None
language: str
is_rtl: bool = False
target_audience: Optional[str] = None
external_references: Optional[list[dict[str, str]]] = None
is_public: bool
instructors: Optional[list[InstructorResponse]] = None
model_config = ConfigDict(from_attributes=True)
@staticmethod
def from_django_model(
course: Course, abs_url_builder: Callable
) -> "CourseResponse":
language_info = get_language_info(course.language)
return CourseResponse.model_validate(
{
"id": course.id,
"title": course.title,
"slug": course.slug,
"description": course.description,
"organization_id": course.organization.id,
"imap_connection_id": course.imap_connection.id
if course.imap_connection
else None,
"enabled": course.enabled,
"enrollments_count": course.enrollments_count,
"image": abs_url_builder(course.image.url) if course.image else None,
"image_path": course.image.name if course.image else None,
"language": course.language,
"is_rtl": language_info["bidi"],
"target_audience": course.target_audience,
"external_references": [
{"name": ref.name, "url": ref.url}
for ref in course.external_references.all()
]
if course.external_references.exists()
else None,
"is_public": course.is_public,
"instructors": [
InstructorResponse(
id=instructor.org_user.id, email=instructor.org_user.user.email
)
for instructor in course.instructors.all()
],
}
)
class CourseSummaryResponse(BaseModel):
id: int
title: str
slug: str
is_public: bool
model_config = ConfigDict(from_attributes=True)
class CreateImapConnectionRequest(BaseModel):
email: str = Field(min_length=1, examples=["user@example.com"])
password: str = Field(min_length=1, examples=["aSafePassword123!"])
server: str = Field(min_length=1, examples=["imap.example.com"])
port: int = Field(gt=0, examples=[993])
folders: list[str] = Field(min_length=1, examples=[["inbox"]])
@field_validator("folders", mode="after")
def validate_folders(cls, v: list[str]) -> list[str]:
if "inbox" not in v:
raise ValueError("Folders list must contain 'inbox'.")
return v
def to_django_model(self, organization_id: int) -> ImapConnection:
organization = Organization.objects.get(id=organization_id)
if not organization:
raise ValueError(f"Organization with id {organization_id} does not exist.")
imap_connection = ImapConnection(
email=self.email,
password=self.password,
server=self.server,
port=self.port,
organization=organization,
)
imap_connection.save()
for folder in self.folders:
InboxFolder.objects.create(
imap_connection=imap_connection, folder_name=folder
)
return imap_connection
class ImapConnectionResponse(BaseModel):
id: int
email: str
server: str
port: int
organization_id: int
folders: Any
@field_serializer("folders")
def serialize_folders(self, folders: Any) -> list[str]:
return [folder.folder_name for folder in folders.all()] # type: ignore[attr-defined]
model_config = ConfigDict(from_attributes=True)
class OrganizationResponse(BaseModel):
id: int
name: str
logo: Optional[str] = None
logo_path: Optional[str] = None
description: Optional[str] = None
public_url: str
website: Optional[str] = None
youtube_channel: Optional[str] = None
linkedin_page: Optional[str] = None
is_public: bool
model_config = ConfigDict(from_attributes=True)
@staticmethod
def from_django_model(
organization: Organization, abs_url_builder: Callable
) -> "OrganizationResponse":
url = reverse(
"django_email_learning:public:organization_view",
kwargs={"organization_id": organization.id},
)
return OrganizationResponse.model_validate(
{
"id": organization.id,
"name": organization.name,
"logo": abs_url_builder(organization.logo.url)
if organization.logo
else None,
"logo_path": organization.logo.name if organization.logo else None,
"description": organization.description,
"public_url": abs_url_builder(url),
"website": organization.website,
"youtube_channel": organization.youtube_channel,
"linkedin_page": organization.linkedin_page,
"is_public": organization.is_public,
}
)
class CreateOrganizationRequest(BaseModel):
name: str = Field(min_length=1, examples=["AvaCode"])
description: Optional[str] = Field(
None, examples=["A description of the organization."]
)
logo: Optional[str] = Field(None, examples=["/path/to/logo.png"])
website: Optional[str] = Field(None, examples=["https://example.com"])
youtube_channel: Optional[str] = Field(
None, examples=["https://youtube.com/channel/xyz"]
)
linkedin_page: Optional[str] = Field(
None, examples=["https://linkedin.com/company/xyz"]
)
is_public: bool = Field(default=True, examples=[True])
def to_django_model(self) -> Organization:
organization = Organization(
name=self.name,
description=self.description,
website=self.website,
youtube_channel=self.youtube_channel,
linkedin_page=self.linkedin_page,
is_public=self.is_public,
)
organization.save()
organization.refresh_from_db()
if self.logo:
organization.replace_logo(self.logo)
return organization
class UpdateOrganizationRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
name: Optional[str] = Field(None, min_length=1, examples=["AvaCode"])
description: Optional[str] = Field(
None, examples=["A description of the organization."]
)
website: Optional[str] = Field(None, examples=["https://example.com"])
youtube_channel: Optional[str] = Field(
None, examples=["https://youtube.com/channel/xyz"]
)
linkedin_page: Optional[str] = Field(
None, examples=["https://linkedin.com/company/xyz"]
)
logo: Optional[str] = Field(None, examples=["/path/to/logo.png"])
remove_logo: Optional[bool] = Field(None, examples=[True])
is_public: Optional[bool] = Field(None, examples=[True])
class UserRole(enum.StrEnum):
ADMIN = "admin"
EDITOR = "editor"
INSTRUCTOR = "instructor"
VIEWER = "viewer"
class AddOrganizationUserRequest(BaseModel):
user_id: int = Field(gt=0, examples=[1])
role: UserRole = Field(min_length=1, examples=[UserRole.ADMIN])
display_name: Optional[str] = Field(None, examples=["John Doe"])
photo: Optional[str] = Field(None, examples=["/path/to/photo.png"])
@model_validator(mode="before")
def validate_instructor_display_name(cls, values: dict) -> dict:
role = values.get("role")
display_name = values.get("display_name")
if role == UserRole.INSTRUCTOR and not display_name:
raise ValueError("Instructor role requires a display name.")
return values
class UpdateOrganizationUserRequest(BaseModel):
role: UserRole = Field(min_length=1, examples=[UserRole.ADMIN])
display_name: Optional[str] = Field(None, examples=["John Doe"])
photo: Optional[str] = Field(None, examples=["/path/to/photo.png"])
@model_validator(mode="before")
def validate_instructor_display_name(cls, values: dict) -> dict:
role = values.get("role")
display_name = values.get("display_name")
if role == UserRole.INSTRUCTOR and not display_name:
raise ValueError("Instructor role requires a display name.")
return values
class OrganizationUserResponse(BaseModel):
id: int
user_id: int
organization_id: int
email: str
role: UserRole
can_act_as_instructor: bool
display_name: Optional[str] = None
photo: Optional[str] = None
photo_url: Optional[str] = None
@staticmethod
def from_django_model(
org_user: OrganizationUser, request: Any
) -> "OrganizationUserResponse":
return OrganizationUserResponse(
id=org_user.id,
user_id=org_user.user.id,
organization_id=org_user.organization.id,
email=org_user.user.email,
role=UserRole(org_user.role),
can_act_as_instructor=org_user.can_act_as_instructor(),
display_name=org_user.display_name,
photo=org_user.photo.name if org_user.photo else None,
photo_url=request.build_absolute_uri(org_user.photo.url)
if org_user.photo
else None,
)
class UpdateSessionRequest(BaseModel):
active_organization_id: int = Field(examples=[1])
model_config = ConfigDict(extra="forbid")
class SessionInfo(BaseModel):
active_organization_id: int
@classmethod
def populate_from_session(cls, session): # type: ignore[no-untyped-def]
return super().model_validate(
{"active_organization_id": session.get("active_organization_id")}
)
class AssignmentCreate(BaseModel):
title: str
description: str
is_blocking: bool
deadline_days: int = Field(ge=0, examples=[14])
requires_text_submission: bool
requires_file_submission: bool
type: Literal["assignment"] = "assignment"
reminder_interval_days: Optional[int] = Field(default=None, examples=[3])
class AssignmentUpdate(BaseModel):
title: Optional[str] = None
description: Optional[str] = None
is_blocking: Optional[bool] = None
deadline_days: Optional[int] = Field(ge=0, examples=[14], default=None)
requires_text_submission: Optional[bool] = None
requires_file_submission: Optional[bool] = None
reminder_interval_days: Optional[int] = Field(default=None, examples=[3])
model_config = ConfigDict(extra="forbid")
class AssignmentResponse(BaseModel):
id: int
title: str
description: str
is_blocking: bool
deadline_days: int
requires_text_submission: bool
requires_file_submission: bool
reminder_interval_days: Optional[int] = None
model_config = ConfigDict(from_attributes=True)
class LessonCreate(BaseModel):
title: str
content: str
type: Literal["lesson"] = "lesson"
class LessonUpdate(BaseModel):
title: Optional[str] = None
content: Optional[str] = None
model_config = ConfigDict(extra="forbid")
class LessonResponse(BaseModel):
id: int
title: str
content: str
model_config = ConfigDict(from_attributes=True)
class AnswerCreate(BaseModel):
text: str
is_correct: bool = Field(examples=[True])
class AnswerUpdate(AnswerCreate):
id: Optional[int] = None
class AnswerObject(BaseModel):
id: int
text: str
is_correct: bool
model_config = ConfigDict(from_attributes=True)
class QuestionCreate(BaseModel):
text: str
priority: int = Field(gt=0, examples=[1])
answers: list[AnswerCreate] = Field(min_length=2)
@field_validator("answers")
@classmethod
def at_least_one_correct_answer(
cls, answers: list[AnswerCreate]
) -> list[AnswerCreate]:
correct_answers = [answer for answer in answers if answer.is_correct]
if not correct_answers:
raise ValueError("At least one answer must be marked as correct.")
return answers
class QuestionUpdate(QuestionCreate):
id: Optional[int] = None
answers: list[AnswerUpdate] = Field(min_length=2) # type: ignore[assignment]
class QuestionObject(BaseModel):
id: int
text: str
priority: int
answers: Any # Will be converted to list in field_serializer
@field_serializer("answers")
def serialize_answers(self, answers: Any) -> list[dict]:
return [
AnswerObject.model_validate(answer).model_dump() for answer in answers.all()
]
model_config = ConfigDict(from_attributes=True)
MIN_QUIZ_DEADLINE = 0 # Allow 0 to indicate no deadline
class UpdateQuiz(BaseModel):
questions: Optional[list[QuestionUpdate]] = Field(min_length=1, default=None)
title: Optional[str] = None
required_score: Optional[int] = Field(ge=0, examples=[80], default=None)
selection_strategy: Optional[QuizSelectionStrategy] = None
limited_attempts: Optional[bool] = None
deadline_days: Optional[int] = Field(
ge=MIN_QUIZ_DEADLINE, examples=[14], default=None
)
is_blocking: Optional[bool] = None
reminder_interval_days: Optional[int] = Field(default=None, examples=[3])
model_config = ConfigDict(extra="forbid")
class QuizCreate(BaseModel):
title: str
required_score: int = Field(ge=0, examples=[80])
selection_strategy: QuizSelectionStrategy
deadline_days: int = Field(ge=MIN_QUIZ_DEADLINE, examples=[14])
questions: list[QuestionCreate] = Field(min_length=1)
type: Literal["quiz"] = "quiz"
limited_attempts: bool = Field(default=True, examples=[True])
is_blocking: bool = Field(default=True, examples=[True])
reminder_interval_days: Optional[int] = Field(default=None, examples=[3])
class QuizResponse(BaseModel):
id: int
title: str
required_score: int
selection_strategy: str
deadline_days: int = Field(ge=MIN_QUIZ_DEADLINE)
questions: Any # Will be converted to list in field_serializer
limited_attempts: bool
is_blocking: bool
reminder_interval_days: Optional[int] = None
@field_serializer("questions")
def serialize_questions(self, questions: Any) -> list[dict]:
return [
QuestionObject.model_validate(question).model_dump()
for question in questions.all()
]
model_config = ConfigDict(from_attributes=True)
class PeriodType(enum.StrEnum):
HOURS = "hours"
DAYS = "days"
class WaitingPeriod(BaseModel):
period: int = Field(gt=0, examples=[7])
type: PeriodType
def to_seconds(self) -> int:
if self.type == PeriodType.HOURS:
return self.period * 3600
elif self.type == PeriodType.DAYS:
return self.period * 86400
else:
raise ValueError(f"Unsupported period type: {self.type}")
@classmethod
def from_seconds(cls, seconds: int) -> "WaitingPeriod":
if seconds % 86400 == 0:
return cls(period=seconds // 86400, type=PeriodType.DAYS)
elif seconds % 3600 == 0:
return cls(period=seconds // 3600, type=PeriodType.HOURS)
else:
raise ValueError(
f"Cannot convert {seconds} seconds to a valid WaitingPeriod."
)
class EnrollmentSummaryResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
course_title: str
status: EnrollmentStatus
progress: int
certificate_url: str | None = None
class EnrollmentsCount(BaseModel):
total: int
completed: int
class LearnerResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
email: str
photo: Optional[Any] = None
enrollments_count: EnrollmentsCount
@field_serializer("photo")
def serialize_photo(self, photo: Optional[Any]) -> Optional[str]:
if photo:
return photo.url # type: ignore[attr-defined]
return None
class EventType(enum.StrEnum):
REGISTERED = "registered"
VERIFIED = "verified"
DEACTIVATED = "deactivated"
QUIZ_SUBMITED = "quiz_submitted"
ASSIGNMENT_SUBMITTED = "assignment_submitted"
ASSIGNMENT_REVIEWED = "assignment_reviewed"
CONTENT_SENT = "content_sent"
REMINDER_SENT = "reminder_sent"
COURSE_COMPLETED = "course_completed"
class ReviewResult(enum.StrEnum):
APPROVED = "approved"
REJECTED = "rejected"
REQUESTING_CHANGES = "requesting_changes"
class DeactivatedEvent(BaseModel):
type: Literal[EventType.DEACTIVATED] = Field(
default=EventType.DEACTIVATED, exclude=True
)
reason: str
class QuizSubmitedEvent(BaseModel):
type: Literal[EventType.QUIZ_SUBMITED] = Field(
default=EventType.QUIZ_SUBMITED, exclude=True
)
quiz_id: int
quiz_title: str
score: int
is_passed: bool
attempt_number: int
is_practice: bool
class AssignmentSubmitedEvent(BaseModel):
type: Literal[EventType.ASSIGNMENT_SUBMITTED] = Field(
default=EventType.ASSIGNMENT_SUBMITTED, exclude=True
)
assignment_id: int
assignment_title: str
class AssignmentReviewdEvent(BaseModel):
type: Literal[EventType.ASSIGNMENT_REVIEWED] = Field(
default=EventType.ASSIGNMENT_REVIEWED, exclude=True
)
assignment_id: int
assignment_title: str
review_result: ReviewResult
reviewed_by: str
class ReminderSentEvent(BaseModel):
type: Literal[EventType.REMINDER_SENT] = Field(
default=EventType.REMINDER_SENT, exclude=True
)
content_id: int
content_title: str
class ContentSentEvent(BaseModel):
type: Literal[EventType.CONTENT_SENT] = Field(
default=EventType.CONTENT_SENT, exclude=True
)
course_content_id: int
course_content_title: str
course_content_type: str
class Event(BaseModel):
type: EventType
timestamp: datetime
event_data: DeactivatedEvent | QuizSubmitedEvent | ContentSentEvent | AssignmentSubmitedEvent | AssignmentReviewdEvent | ReminderSentEvent | None = Field(
discriminator="type"
) # REGISTERED, VERIFIED, COURSE_COMPLETED have no additional data
class EnrollmentResponse(BaseModel):
id: int
learner: LearnerResponse
course: CourseSummaryResponse
status: EnrollmentStatus
events: list[Event]
@staticmethod
def from_django_model(enrollment: Enrollment) -> "EnrollmentResponse":
events = [
Event(
type=EventType.REGISTERED,
timestamp=enrollment.enrolled_at,
event_data=None,
)
]
if enrollment.activated_at:
events.append(
Event(
type=EventType.VERIFIED,
timestamp=enrollment.activated_at,
event_data=None,
)
)
for delivery in enrollment.content_deliveries.all().order_by("id"): # type: ignore[attr-defined]
schedule_no = 0
for schedule in delivery.delivery_schedules.filter(
status=DeliveryStatus.DELIVERED
):
schedule_no += 1
events.append(
Event(
type=EventType.CONTENT_SENT,
timestamp=schedule.delivered_at, # type: ignore[arg-type]
event_data=ContentSentEvent(
course_content_id=delivery.course_content.id,
course_content_title=delivery.course_content.title, # type: ignore[union-attr]
course_content_type=delivery.course_content.type,
),
)
)
if delivery.course_content.type == "assignment":
if (
delivery.reminder_state == ContentDelivery.ReminderStatus.SENT
and delivery.remind_at
):
events.append(
Event(
type=EventType.REMINDER_SENT,
timestamp=delivery.remind_at, # type: ignore[arg-type]
event_data=ReminderSentEvent(
content_id=delivery.course_content.id, # type: ignore[union-attr]
content_title=delivery.course_content.title, # type: ignore[union-attr]
),
)
)
submission = delivery.assignment_submission # type: ignore[attr-defined]
if submission:
events.append(
Event(
type=EventType.ASSIGNMENT_SUBMITTED,
timestamp=submission.submitted_at, # type: ignore[arg-type]
event_data=AssignmentSubmitedEvent(
assignment_id=delivery.course_content.assignment.id, # type: ignore[union-attr]
assignment_title=delivery.course_content.assignment.title, # type: ignore[union-attr]
),
)
)
if (
submission.reviewed_at
and submission.status
!= AssignmentSubmission.SubmissionStatus.PENDING_REVIEW
):
events.append(
Event(
type=EventType.ASSIGNMENT_REVIEWED,
timestamp=submission.reviewed_at, # type: ignore[arg-type]
event_data=AssignmentReviewdEvent(
assignment_id=delivery.course_content.assignment.id, # type: ignore[union-attr]
assignment_title=delivery.course_content.assignment.title, # type: ignore[union-attr]
review_result=ReviewResult(submission.status), # type: ignore[union-attr]
reviewed_by=submission.reviewer.display_name, # type: ignore[union-attr, arg-type]
),
)
)
# TODO:events for reminders and submissions for assignments
if delivery.course_content.type == "quiz":
if (
delivery.reminder_state == ContentDelivery.ReminderStatus.SENT
and delivery.remind_at
):
events.append(
Event(
type=EventType.REMINDER_SENT,
timestamp=delivery.remind_at, # type: ignore[arg-type]
event_data=ReminderSentEvent(
content_id=delivery.course_content.id, # type: ignore[union-attr]
content_title=delivery.course_content.title, # type: ignore[union-attr]
),
)
)
attempt_number = 0
quiz_attempts = delivery.quiz_submissions.all().order_by(
"submitted_at"
)
attempt = None
if (
delivery.course_content.quiz.is_blocking # type: ignore[union-attr]
and delivery.course_content.limited_attempts
):
if schedule_no == 1:
attempts = [quiz_attempts.first()]
attempt_number = 1
elif schedule_no > 1:
attempt_number = schedule_no
attempts = list(quiz_attempts[1:])
else:
attempt_number = 1
attempts = list(quiz_attempts)
if attempts:
for attempt in [i for i in attempts if i is not None]: # type: ignore[union-attr]
events.append(
Event(
type=EventType.QUIZ_SUBMITED,
timestamp=attempt.submitted_at,
event_data=QuizSubmitedEvent(
quiz_id=delivery.course_content.quiz.id, # type: ignore[union-attr]
quiz_title=delivery.course_content.quiz.title, # type: ignore[union-attr]
score=attempt.score,