-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserializers.py
More file actions
415 lines (332 loc) · 12.3 KB
/
serializers.py
File metadata and controls
415 lines (332 loc) · 12.3 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
from pydantic import (
BaseModel,
ConfigDict,
Field,
field_serializer,
field_validator,
model_validator,
)
from typing import Optional, Literal, Any
from django_email_learning.models import (
Organization,
ImapConnection,
Lesson,
Quiz,
Question,
Answer,
CourseContent,
Course,
)
import enum
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])
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,
)
if imap_connection:
course.imap_connection = imap_connection
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])
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
return course
class CourseResponse(BaseModel):
id: int
title: str
slug: str
description: Optional[str]
organization_id: int
imap_connection_id: Optional[int]
enabled: 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])
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,
)
return imap_connection
class ImapConnectionResponse(BaseModel):
id: int
email: str
server: str
port: int
organization_id: int
model_config = ConfigDict(from_attributes=True)
class OrganizationResponse(BaseModel):
id: int
name: str
model_config = ConfigDict(from_attributes=True)
class CreateOrganizationRequest(BaseModel):
name: str = Field(min_length=1, examples=["AvaCode"])
description: Optional[str] = Field(
None, examples=["A description of the organization."]
)
def to_django_model(self) -> Organization:
organization = Organization(name=self.name, description=self.description)
return organization
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 LessonCreate(BaseModel):
title: str
content: str
type: Literal["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 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 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)
class UpdateQuiz(BaseModel):
questions: Optional[list[QuestionCreate]] = Field(min_length=1)
title: Optional[str] = None
required_score: Optional[int] = Field(ge=0, examples=[80], default=None)
model_config = ConfigDict(extra="forbid")
class QuizCreate(BaseModel):
title: str
required_score: int = Field(ge=0, examples=[80])
questions: list[QuestionCreate] = Field(min_length=1)
type: Literal["quiz"]
class QuizResponse(BaseModel):
id: int
title: str
required_score: int
questions: Any # Will be converted to list in field_serializer
@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 CreateCourseContentRequest(BaseModel):
priority: int | None = Field(gt=0, examples=[1], default=None)
waiting_period: WaitingPeriod
content: LessonCreate | QuizCreate = Field(discriminator="type")
@property
def required_priority(self) -> int:
if self.priority is not None:
return self.priority
else:
raise ValueError("Priority must be set before converting to Django model.")
def to_django_model(self, course: Course) -> CourseContent:
lesson = None
quiz = None
if isinstance(self.content, LessonCreate):
lesson = Lesson(
title=self.content.title,
content=self.content.content,
)
lesson.save()
content_type = "lesson"
elif isinstance(self.content, QuizCreate):
quiz = Quiz(
title=self.content.title,
required_score=self.content.required_score,
)
quiz.save()
for question_data in self.content.questions:
question = Question(
text=question_data.text,
priority=question_data.priority,
quiz=quiz,
)
question.save()
for answer_data in question_data.answers:
answer = Answer(
text=answer_data.text,
is_correct=answer_data.is_correct,
question=question,
)
answer.save()
content_type = "quiz"
course_content = CourseContent.objects.create(
course=course,
priority=self.required_priority,
waiting_period=self.waiting_period.to_seconds(),
lesson=lesson,
quiz=quiz,
type=content_type,
)
return course_content
class UpdateCourseContentRequest(BaseModel):
priority: Optional[int] = Field(gt=0, examples=[1], default=None)
waiting_period: Optional[WaitingPeriod] = None
lesson: Optional[LessonUpdate] = None
quiz: Optional[UpdateQuiz] = None
is_published: Optional[bool] = None
model_config = ConfigDict(extra="forbid")
@model_validator(mode="after")
def check_at_least_one(self) -> "UpdateCourseContentRequest":
# Check if all fields are None
fields = [
self.priority,
self.waiting_period,
self.lesson,
self.quiz,
self.is_published,
]
if not any(f is not None for f in fields):
raise ValueError(
"At least one of 'priority', 'waiting_period', 'lesson', 'quiz', or 'is_published' must be provided."
)
return self
class CourseContentResponse(BaseModel):
id: int
priority: int
waiting_period: int
type: str
lesson: Optional[LessonResponse] = None
quiz: Optional[QuizResponse] = None
is_published: bool
@field_serializer("waiting_period")
def serialize_waiting_period(self, waiting_period: int) -> dict:
return WaitingPeriod.from_seconds(waiting_period).model_dump()
model_config = ConfigDict(from_attributes=True)
class CourseContentSummaryResponse(BaseModel):
id: int
title: str
priority: int
waiting_period: int
is_published: bool
type: str
@field_serializer("waiting_period")
def serialize_waiting_period(self, waiting_period: int) -> dict:
return WaitingPeriod.from_seconds(waiting_period).model_dump()
model_config = ConfigDict(from_attributes=True)
class ReorderCourseContentsRequest(BaseModel):
ordered_content_ids: list[int] = Field(min_length=2, examples=[[3, 1, 2]])