forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

dto.rs544 lines, 22.9 KiBHistoryRawDownload
1//! Response DTOs shared across more than one handler module.
2
3use std::collections::{HashMap, HashSet};
4
5use serde::Serialize;
6use utoipa::ToSchema;
7
8use crate::database::Database;
9use crate::domain::course::Course;
10use crate::domain::course_session::CourseSession;
11use crate::domain::exam::Exam;
12use crate::domain::homework::Homework;
13use crate::domain::role::Role as DomainRole;
14use crate::domain::subject::Subject;
15use crate::domain::user::{User, UserId};
16use crate::error::AppError;
17
18/// The access roles a response can carry, lowest to highest privilege (`parent`
19/// is a read-only observer of its linked students). `ai` is an internal service
20/// principal — the identity an out-of-process AI service carries over the QUIC
21/// bridge. It is never assignable and never stored on a user row, so it only
22/// ever appears in a response; requests take the five human roles
23/// (`AssignableRole`), which is also what `GET /limits` lists.
24///
25/// The web-facing mirror of [`crate::domain::role::Role`] — it carries the
26/// serde + OpenAPI derives (which the domain type deliberately omits), so it
27/// renders as a proper `enum` in the docs. Serializes to the same lowercase
28/// strings the domain stores.
29#[derive(Serialize, Clone, Copy, ToSchema)]
30#[serde(rename_all = "lowercase")]
31pub enum Role {
32 Ai,
33 Parent,
34 Student,
35 Teacher,
36 Manager,
37 Admin,
38}
39
40/// The roles a request may ask for: the five human ones, exactly
41/// [`crate::domain::role::ROLES`]. Documentation only — the handlers still take the
42/// role as a string and funnel it through
43/// [`crate::domain::role::Role::try_from_str`], so an unknown value is a uniform
44/// `400` rather than a deserialization error. It exists because [`Role`] (the
45/// response schema) also names `ai`, and a request schema pointed at it offered
46/// callers a value the server has always refused.
47#[derive(ToSchema)]
48#[schema(rename_all = "lowercase")]
49#[allow(dead_code)] // Nothing constructs it: the variants exist to be emitted.
50pub enum AssignableRole {
51 Parent,
52 Student,
53 Teacher,
54 Manager,
55 Admin,
56}
57
58impl From<DomainRole> for Role {
59 fn from(role: DomainRole) -> Self {
60 match role {
61 DomainRole::Ai => Role::Ai,
62 DomainRole::Parent => Role::Parent,
63 DomainRole::Student => Role::Student,
64 DomainRole::Teacher => Role::Teacher,
65 DomainRole::Manager => Role::Manager,
66 DomainRole::Admin => Role::Admin,
67 }
68 }
69}
70
71/// How another person appears inside a response: enough to say *who* without
72/// leaking contact details. Rows that reference users (enrollments, attendance,
73/// exam results) embed this instead of a bare id, so no client ever has to
74/// show a raw ULID to a human.
75#[derive(Serialize, Clone, ToSchema)]
76pub struct PersonRef {
77 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
78 pub id: String,
79 #[schema(example = "ada")]
80 pub username: String,
81 /// The name to show this person under, resolved in the same three steps
82 /// `GET /users/{id}/profile` uses: the stored `display_name`, else the
83 /// `"Name Surname"` join, else `null`.
84 #[schema(example = "Ada Lovelace")]
85 pub display_name: Option<String>,
86 /// The school-issued student number, `null` for every account that holds
87 /// none (every staff account included). Part of "who this is" the way a
88 /// username is, which is why it rides this ref rather than a route of its
89 /// own — a roster that names a student can name their number.
90 #[schema(example = "1234")]
91 pub student_number: Option<String>,
92}
93
94impl PersonRef {
95 /// The one spelling of the display-name resolve — `ProfileResponse` calls
96 /// this too. It was two hand-kept copies once, and the copy here forgot the
97 /// stored name, so a person who chose one was still shown their legal name
98 /// by every list that embeds a person.
99 pub fn new(user: &User) -> Self {
100 let full: Vec<&str> = [user.get_name(), user.get_surname()]
101 .into_iter()
102 .flatten()
103 .map(|part| part.as_str())
104 .collect();
105 Self {
106 id: user.get_id().key().to_string(),
107 username: user.get_username().as_str().to_string(),
108 display_name: user
109 .get_display_name()
110 .map(|chosen| chosen.as_str().to_string())
111 .or_else(|| (!full.is_empty()).then(|| full.join(" "))),
112 student_number: user
113 .get_student_number()
114 .map(|number| number.as_str().to_string()),
115 }
116 }
117
118 /// Key already-loaded users by id — for handlers that hold the rows anyway.
119 pub fn map_of(users: &[&User]) -> HashMap<String, PersonRef> {
120 users
121 .iter()
122 .map(|user| (user.get_id().key().to_string(), PersonRef::new(user)))
123 .collect()
124 }
125
126 /// Look `id` up in `people`, degrading to the bare id when the row is gone
127 /// — a stale reference renders oddly instead of failing the request.
128 pub fn resolve(people: &HashMap<String, PersonRef>, id: &UserId) -> Self {
129 people
130 .get(id.key().as_str())
131 .cloned()
132 .unwrap_or_else(|| Self {
133 id: id.key().to_string(),
134 username: id.key().to_string(),
135 display_name: None,
136 student_number: None,
137 })
138 }
139}
140
141/// Load every user behind `ids` (duplicates collapsed, one query) and key
142/// their `PersonRef`s by id — the join half of list endpoints that embed people.
143pub async fn person_map(
144 ids: impl IntoIterator<Item = UserId>,
145 db: &Database,
146) -> Result<HashMap<String, PersonRef>, AppError> {
147 let mut seen = HashSet::new();
148 let unique: Vec<UserId> = ids
149 .into_iter()
150 .filter(|id| seen.insert(id.key().to_string()))
151 .collect();
152 let users = crate::service::user::list_by_ids(db, &unique).await?;
153 Ok(users
154 .iter()
155 .map(|user| (user.get_id().key().to_string(), PersonRef::new(user)))
156 .collect())
157}
158
159/// Public shape of a user: id, username, role, and the optional personal info
160/// (`null` until filled in). Never carries the password hash. Shared by `auth`
161/// (register/login/me) and `users` (listing, role and profile changes).
162#[derive(Serialize, ToSchema)]
163pub struct UserResponse {
164 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
165 pub id: String,
166 #[schema(example = "ada")]
167 pub username: String,
168 pub role: Role,
169 /// The school-issued student number, unique inside the school. `null`
170 /// when the account holds none — every staff account, and any student the
171 /// office has not numbered yet. Only ever a value on a `student` row: a
172 /// role change away from `student` clears it.
173 #[schema(example = "1234")]
174 pub student_number: Option<String>,
175 #[schema(example = "Ada")]
176 pub name: Option<String>,
177 #[schema(example = "Lovelace")]
178 pub surname: Option<String>,
179 #[schema(example = "ada@example.com")]
180 pub email: Option<String>,
181 #[schema(example = "+90 555 123 45 67")]
182 pub phone: Option<String>,
183 #[schema(example = "1990-01-02")]
184 pub birth_date: Option<String>,
185 /// Self-declared gender: `female`, `male`, `other`, or `undisclosed`;
186 /// `null` = never chosen.
187 #[schema(example = "female")]
188 pub gender: Option<String>,
189 /// Postal address; `null` when unset, at most `max_address_len` characters.
190 #[schema(example = "Çamlık Mah. 2. Sk. No: 7, Bornova / İzmir")]
191 pub address: Option<String>,
192 /// Who to call when this person is unreachable; `null` when unset. Same
193 /// gate as the other contact fields — never on the public profile.
194 #[schema(example = "Mehmet Yılmaz")]
195 pub emergency_contact_name: Option<String>,
196 /// The emergency contact's phone, same shape as `phone`; `null` when unset.
197 #[schema(example = "+90 555 987 65 43")]
198 pub emergency_contact_phone: Option<String>,
199 /// UI color scheme: `light` or `dark`. `null` = never chosen — the client
200 /// should fall back to the device preference.
201 #[schema(example = "dark")]
202 pub theme: Option<String>,
203 /// UI language (ISO 639-1): `tr` or `en`. `null` = never chosen — the
204 /// client should fall back to the device language.
205 #[schema(example = "tr")]
206 pub language: Option<String>,
207 /// UI accent color as a 6-digit hex with a leading `#`, lowercase. `null` =
208 /// never chosen — the client should fall back to its default accent.
209 #[schema(example = "#fefae0")]
210 pub palette_color: Option<String>,
211 /// The name the public profile is shown under, instead of the legal one.
212 /// `null` = never chosen; unlike [`PersonRef::display_name`] this is the
213 /// stored column, never a fallback to `"Name Surname"`.
214 #[schema(example = "Ada")]
215 pub display_name: Option<String>,
216 /// Free text under the profile's name; `null` when unset.
217 #[schema(example = "Sınıfın en hızlı pomodorocusu.")]
218 pub bio: Option<String>,
219}
220
221impl UserResponse {
222 pub fn new(user: &User) -> Self {
223 Self {
224 id: user.get_id().key().to_string(),
225 username: user.get_username().as_str().to_string(),
226 role: user.get_role().into(),
227 student_number: user
228 .get_student_number()
229 .map(|number| number.as_str().to_string()),
230 name: user.get_name().map(|v| v.as_str().to_string()),
231 surname: user.get_surname().map(|v| v.as_str().to_string()),
232 email: user.get_email().map(|v| v.as_str().to_string()),
233 phone: user.get_phone().map(|v| v.as_str().to_string()),
234 birth_date: user.get_birth_date().map(|v| v.as_str().to_string()),
235 gender: user.get_gender().map(|v| v.as_str().to_string()),
236 address: user.get_address().map(|v| v.as_str().to_string()),
237 emergency_contact_name: user
238 .get_emergency_contact_name()
239 .map(|v| v.as_str().to_string()),
240 emergency_contact_phone: user
241 .get_emergency_contact_phone()
242 .map(|v| v.as_str().to_string()),
243 theme: user.get_theme().map(|v| v.as_str().to_string()),
244 language: user.get_language().map(|v| v.as_str().to_string()),
245 palette_color: user.get_palette_color().map(|v| v.as_str().to_string()),
246 display_name: user.get_display_name().map(|v| v.as_str().to_string()),
247 bio: user.get_bio().map(|v| v.as_str().to_string()),
248 }
249 }
250}
251
252/// Public shape of a course — the **catalog** row, the school's template for a
253/// taught course. Shared by `courses` (CRUD) and the reports that embed the
254/// course an instance teaches. The taught thing is the *instance*
255/// ([`super::instances::InstanceResponse`]): teachers, weekly hours and the
256/// report-card weight live there, per class section.
257#[derive(Serialize, ToSchema)]
258pub struct CourseResponse {
259 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
260 pub id: String,
261 /// Who created (and owns) the catalog row. Only they and managers/admins
262 /// may edit or delete it.
263 pub creator: PersonRef,
264 #[schema(example = "Algebra")]
265 pub title: String,
266 pub description: String,
267 /// `course` (a regular class), `study` (a supervised study session), or
268 /// `club` (a student club). Only a `course` is taught through class-section
269 /// instances and carries exams; a `study`/`club` is joined school-wide.
270 #[schema(example = "course")]
271 pub kind: String,
272 /// How many class×course instances teach this course right now — the count
273 /// the delete refusal watches (`0` is what lets the row go).
274 #[schema(example = 3)]
275 pub class_course_count: i64,
276 /// How many individual club/study memberships the course carries.
277 #[schema(example = 12)]
278 pub course_membership_count: i64,
279 /// The class sections teaching this course right now — one entry per
280 /// instance, each with its own resolved title and hours. Populated by the
281 /// catalogue reads (`GET /courses`, `GET /courses/{id}`); `[]` everywhere
282 /// else, including the CRUD responses and every report that embeds a
283 /// course row. Truncated to `MAX_COURSE_SECTIONS`; `class_course_count` is
284 /// the untruncated total.
285 pub sections: Vec<CourseSectionRef>,
286}
287
288/// One class section teaching a catalog course. Shared by the catalogue rows
289/// and the profile course block; `id` is the **instance** id
290/// (`GET /instances/{id}`), never the catalog row's — the 9-A and 12-A
291/// sections of one ders are two entries here, with their own resolved titles
292/// and weekly hours.
293#[derive(Serialize, Clone, ToSchema)]
294pub struct CourseSectionRef {
295 /// The instance id (`GET /instances/{id}`).
296 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
297 pub id: String,
298 /// The catalog course this section teaches (`GET /courses/{id}`).
299 #[schema(example = "019732e3-7b00-7000-8000-00000000beef")]
300 pub course: String,
301 /// The class this section belongs to (`GET /classes/{id}`).
302 #[schema(example = "019732e3-7b00-7000-8000-00000000cafe")]
303 pub class: String,
304 /// The class's own name, e.g. `9-A`.
305 #[schema(example = "9-A")]
306 pub class_name: String,
307 /// The **resolved** display title of this section: its own override, else
308 /// its offering's, else the catalog course's — the same chain every
309 /// instance-scoped surface shows.
310 #[schema(example = "Matematik")]
311 pub title: String,
312 /// The class's rung on the grade ladder (`0` = anaokulu).
313 #[schema(example = 9)]
314 pub grade_level: i16,
315 /// The **resolved** weekly lesson hours of this section: its own override,
316 /// else its offering's default, else the floor.
317 #[schema(example = 5)]
318 pub ders_saati: i64,
319 /// The staff assigned to run this section.
320 pub teachers: Vec<PersonRef>,
321 /// How many students are enrolled in this section right now.
322 #[schema(example = 28)]
323 pub enrollment_count: i64,
324}
325
326/// Every person a [`CourseResponse`] names: its creator. Feed this into
327/// `person_map` so the response can resolve them — a name the map is missing
328/// renders as an unknown person.
329pub fn course_people(course: &Course) -> impl Iterator<Item = UserId> + '_ {
330 std::iter::once(*course.get_creator())
331}
332
333impl CourseResponse {
334 pub fn new(course: &Course, people: &HashMap<String, PersonRef>) -> Self {
335 Self {
336 id: course.get_id().key().to_string(),
337 creator: PersonRef::resolve(people, course.get_creator()),
338 title: course.get_title().as_str().to_string(),
339 description: course.get_description().as_str().to_string(),
340 kind: course.get_kind().as_str().to_string(),
341 class_course_count: course.get_class_course_count(),
342 course_membership_count: course.get_course_membership_count(),
343 sections: Vec::new(),
344 }
345 }
346
347 /// The same row plus its sections — the catalogue reads' constructor
348 /// (`GET /courses`, `GET /courses/{id}`), where every row carries the
349 /// class sections teaching it.
350 pub fn with_sections(
351 course: &Course,
352 people: &HashMap<String, PersonRef>,
353 sections: Vec<CourseSectionRef>,
354 ) -> Self {
355 Self {
356 sections,
357 ..Self::new(course, people)
358 }
359 }
360}
361
362/// Public shape of a subject (one topic of a course's curriculum). Shared by
363/// `courses` (in-course creation and listing) and `subjects` (lookup, edit,
364/// delete).
365#[derive(Serialize, ToSchema)]
366pub struct SubjectResponse {
367 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
368 pub id: String,
369 /// The course whose curriculum this subject belongs to.
370 pub course: String,
371 #[schema(example = "Limits and continuity")]
372 pub name: String,
373 pub description: String,
374}
375
376impl SubjectResponse {
377 pub fn new(subject: &Subject) -> Self {
378 Self {
379 id: subject.get_id().key().to_string(),
380 course: subject.get_course().key().to_string(),
381 name: subject.get_name().as_str().to_string(),
382 description: subject.get_description().as_str().to_string(),
383 }
384 }
385}
386
387/// Public shape of a homework assignment. Shared by the instance routes
388/// (creation and listing) and `homework` (cross-instance list, lookup, edit).
389/// `assigned` is the student subset — `null` means the whole enrolled roster
390/// (whoever is enrolled at submit time); a subset lists the named students' ids.
391/// `due_at`/`created_at` are UTC unix-milliseconds; lateness is judged per
392/// submission (against `due_at`), never stored on the homework itself.
393#[derive(Serialize, ToSchema)]
394pub struct HomeworkResponse {
395 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
396 pub id: String,
397 /// The class×course instance this homework belongs to
398 /// (`GET /instances/{id}`) — the class section's own assignment, not a
399 /// school-wide course's.
400 pub class_course: String,
401 /// The course subject this homework is tagged with.
402 pub subject: String,
403 #[schema(example = "Read chapter 3")]
404 pub title: String,
405 pub description: Option<String>,
406 /// When the homework is due, UTC unix-milliseconds.
407 #[schema(example = 1_900_000_000_000_i64)]
408 pub due_at: i64,
409 /// The assigned student ids, or `null` for the whole enrolled course. Only
410 /// a viewer who manages the course sees the whole subset; to anyone else it
411 /// is narrowed to their own id (the course roster is teacher+-only, so a
412 /// subset assignment must not hand out the names it lists).
413 pub assigned: Option<Vec<String>>,
414 /// Who assigned the homework.
415 pub created_by: String,
416 /// When it was assigned, UTC unix-milliseconds.
417 pub created_at: i64,
418}
419
420impl HomeworkResponse {
421 pub fn new(homework: &Homework) -> Self {
422 Self {
423 id: homework.get_id().key().to_string(),
424 class_course: homework.get_class_course().key().to_string(),
425 subject: homework.get_subject().key().to_string(),
426 title: homework.get_title().as_str().to_string(),
427 description: homework.get_description().map(|d| d.as_str().to_string()),
428 due_at: homework.get_due_at().as_millis(),
429 assigned: homework
430 .get_assigned()
431 .map(|users| users.iter().map(|user| user.key().to_string()).collect()),
432 created_by: homework.get_created_by().key().to_string(),
433 created_at: homework.get_created_at().as_millis(),
434 }
435 }
436
437 /// The same homework as seen by a viewer who does *not* manage its course.
438 /// A subset roster is narrowed to `viewer` alone: they learn that they are
439 /// named — which is why the homework reached them at all — and nothing
440 /// about who else is. Whole-course (`null`) stays `null`; every read path
441 /// that uses this has already refused a viewer the subset does not name
442 /// (404), so a one-element list is never a lie.
443 pub fn for_viewer(homework: &Homework, viewer: &UserId) -> Self {
444 let mut response = Self::new(homework);
445 response.assigned = response.assigned.map(|_| vec![viewer.key().to_string()]);
446 response
447 }
448}
449
450/// Public shape of a course session (one lesson). Shared by the instance
451/// routes (creation and listing) and `sessions` (CRUD + roll call).
452#[derive(Serialize, ToSchema)]
453pub struct SessionResponse {
454 pub id: String,
455 /// The class×course instance this lesson belongs to
456 /// (`GET /instances/{id}`).
457 pub class_course: String,
458 /// Who teaches this session.
459 pub teacher: PersonRef,
460 pub topic: String,
461 /// Lesson start, UTC unix-milliseconds.
462 pub starts_at: i64,
463 /// Lesson end, UTC unix-milliseconds; `null` when open-ended.
464 pub ends_at: Option<i64>,
465}
466
467impl SessionResponse {
468 pub fn new(session: &CourseSession, people: &HashMap<String, PersonRef>) -> Self {
469 Self {
470 id: session.get_id().key().to_string(),
471 class_course: session.get_class_course().key().to_string(),
472 teacher: PersonRef::resolve(people, session.get_teacher()),
473 topic: session.get_topic().as_str().to_string(),
474 starts_at: session.get_starts_at().as_millis(),
475 ends_at: session.get_ends_at().map(|t| t.as_millis()),
476 }
477 }
478}
479
480/// Public shape of an exam. Shared by `exams` (CRUD/results) and the instance
481/// routes (creation and listing). The schedule fields are all `null` for an
482/// offline-graded exam (no mode); see the create/update endpoints for the
483/// rules tying them together.
484#[derive(Serialize, ToSchema)]
485pub struct ExamResponse {
486 pub id: String,
487 pub creator: String,
488 /// The class×course instance the exam belongs to (`GET /instances/{id}`) —
489 /// two class sections teaching the same course sit their own exams.
490 pub class_course: String,
491 /// The term the exam is sat in (`GET /terms`); its marks count into that
492 /// term's report card.
493 pub term: String,
494 pub title: String,
495 pub description: String,
496 /// The assessment form. Its weight in the course average is school policy:
497 /// `GET /settings` maps each kind to a weight.
498 pub kind: String,
499 /// `sync`, `async`, or `open`; `null` for an offline-graded exam
500 /// (not sittable).
501 #[schema(example = "sync")]
502 pub mode: Option<String>,
503 /// Window open, UTC unix-milliseconds (`sync`/`async`).
504 pub starts_at: Option<i64>,
505 /// Window close, UTC unix-milliseconds (`sync`/`async`).
506 pub ends_at: Option<i64>,
507 /// Per-attempt time budget in milliseconds — required for `async`,
508 /// optional for `open` (`null` = unlimited time).
509 pub duration_ms: Option<i64>,
510 /// How many attempts each student gets; `0` means unlimited.
511 #[schema(example = 1)]
512 pub max_attempts: i64,
513 /// Whether a student who left the exam room may come back in and keep
514 /// answering. Teachers can flip this live.
515 pub allow_rejoin: bool,
516 /// Whether students may review their graded attempt once results are out.
517 /// Teachers can flip this live.
518 pub allow_review: bool,
519 /// Still being prepared: visible only to the course's managers, not
520 /// sittable, not gradable. Publish by `PATCH`ing `draft: false`.
521 pub draft: bool,
522}
523
524impl ExamResponse {
525 pub fn new(exam: &Exam) -> Self {
526 Self {
527 id: exam.get_id().key().to_string(),
528 creator: exam.get_creator().key().to_string(),
529 class_course: exam.get_class_course().key().to_string(),
530 term: exam.get_term().key().to_string(),
531 title: exam.get_title().as_str().to_string(),
532 description: exam.get_description().as_str().to_string(),
533 kind: exam.get_kind().as_str().to_string(),
534 mode: exam.get_mode().map(|m| m.as_str().to_string()),
535 starts_at: exam.get_starts_at().map(|t| t.as_millis()),
536 ends_at: exam.get_ends_at().map(|t| t.as_millis()),
537 duration_ms: exam.get_duration_ms().map(|d| d.as_millis()),
538 max_attempts: exam.get_max_attempts().as_i64(),
539 allow_rejoin: exam.get_allow_rejoin(),
540 allow_review: exam.get_allow_review(),
541 draft: exam.is_draft(),
542 }
543 }
544}