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

homework.rs204 lines, 7.1 KiBHistoryRawDownload
1//! A homework assignment: a teacher hands it out per course, optionally
2//! narrowed to a subset of the enrolled students, and every homework is tagged
3//! with one of its course's subjects.
4//! Students submit against it ([`crate::domain::homework_submission`]) and a
5//! teacher grades a status plus an optional mark
6//! ([`crate::domain::homework_result`]). Persistence lives in
7//! [`crate::db::homework`], workflows in [`crate::service::homework`].
8//!
9//! `course`, `created_by`, and `created_at` are fixed at creation (READONLY
10//! app discipline): moving a homework between courses would strand the
11//! submissions and grades of students not in the target course. `subject` is
12//! deliberately *not* fixed — it is re-taggable through PATCH, validated
13//! same-course by the web layer, exactly like an exam question's subject.
14
15use crate::constant::{MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN};
16use crate::domain::class_course::ClassCourseId;
17use crate::domain::monotonic_id::next_uuid;
18use crate::domain::subject::SubjectId;
19use crate::domain::timestamp::Timestamp;
20use crate::domain::user::UserId;
21use crate::error::ValidationError;
22use crate::validate::{validate_optional, validate_required};
23
24#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
25#[sqlx(transparent)]
26pub struct HomeworkId(uuid::Uuid);
27
28impl HomeworkId {
29 /// Minted from the process-wide monotonic generator, not a plain random
30 /// UUID: homework lists `id DESC` (newest first, [`HomeworkId`]-ordered
31 /// listings), and a random low half scrambles rows minted in the same
32 /// millisecond.
33 pub fn generate() -> Self {
34 Self(next_uuid())
35 }
36
37 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
38 /// cannot take the newtype. Static `query!` binds take `self` directly.
39 pub fn uuid(&self) -> uuid::Uuid {
40 self.0
41 }
42
43 /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
44 /// which matches no row.
45 pub fn from_key(key: &str) -> Self {
46 Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
47 }
48
49 pub fn key(&self) -> String {
50 self.0.to_string()
51 }
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
55#[sqlx(transparent)]
56pub struct HomeworkTitle(String);
57
58impl HomeworkTitle {
59 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
60 validate_required("title", value, MAX_HOMEWORK_TITLE_LEN)?;
61 Ok(Self(value.to_string()))
62 }
63
64 pub fn as_str(&self) -> &str {
65 &self.0
66 }
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
70#[sqlx(transparent)]
71pub struct HomeworkDescription(String);
72
73impl HomeworkDescription {
74 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
75 validate_optional("description", value, MAX_HOMEWORK_DESCRIPTION_LEN)?;
76 Ok(Self(value.to_string()))
77 }
78
79 pub fn as_str(&self) -> &str {
80 &self.0
81 }
82}
83
84/// A homework assignment. `assigned` is the optional student subset,
85/// assembled from the `homework_assignment` child rows (`None` = no rows =
86/// the whole course — see [`Homework::student_sees`]). Because whole-course
87/// homework carries no roster, a student who enrolls later is covered
88/// automatically; a subset is a fixed snapshot of the students named at
89/// assign (or last PATCH) time.
90///
91/// The `subject` tag names a topic of the homework's course — and, since the
92/// course-template system, one the instance actually *teaches*: its resolved
93/// subject set (override-or-inherit), validated service-side
94/// ([`crate::service::subject::in_instance`] at tag time,
95/// [`crate::service::offering_subject::ensure_resolved_member`] on create),
96/// because the check needs the instance's override state and so cannot live
97/// as a pure rule on this row.
98#[derive(Debug, Clone, sqlx::FromRow)]
99pub struct Homework {
100 pub(crate) id: HomeworkId,
101 pub(crate) class_course: ClassCourseId,
102 pub(crate) subject: SubjectId,
103 pub(crate) title: HomeworkTitle,
104 pub(crate) description: Option<HomeworkDescription>,
105 pub(crate) due_at: Timestamp,
106 pub(crate) assigned: Option<Vec<UserId>>,
107 pub(crate) created_by: UserId,
108 pub(crate) created_at: Timestamp,
109}
110
111impl Homework {
112 pub fn get_id(&self) -> &HomeworkId {
113 &self.id
114 }
115
116 pub fn get_class_course(&self) -> &ClassCourseId {
117 &self.class_course
118 }
119
120 pub fn get_subject(&self) -> &SubjectId {
121 &self.subject
122 }
123
124 pub fn get_title(&self) -> &HomeworkTitle {
125 &self.title
126 }
127
128 pub fn get_description(&self) -> Option<&HomeworkDescription> {
129 self.description.as_ref()
130 }
131
132 pub fn get_due_at(&self) -> Timestamp {
133 self.due_at
134 }
135
136 /// The assigned student subset, or `None` for a whole-course homework.
137 pub fn get_assigned(&self) -> Option<&[UserId]> {
138 self.assigned.as_deref()
139 }
140
141 pub fn get_created_by(&self) -> &UserId {
142 &self.created_by
143 }
144
145 pub fn get_created_at(&self) -> Timestamp {
146 self.created_at
147 }
148
149 /// Whether `user` is in this homework's audience. A whole-course homework
150 /// (`assigned` NULL or empty) is visible to every enrolled student; a
151 /// subset homework only to the students it names. Callers pair this with an
152 /// enrollment check — being named is visibility, not enrollment.
153 pub fn student_sees(&self, user: &UserId) -> bool {
154 match &self.assigned {
155 None => true,
156 Some(assigned) => assigned.is_empty() || assigned.contains(user),
157 }
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use super::*;
164
165 const A: &str = "0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e";
166 const B: &str = "0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f";
167
168 #[tokio::test]
169 async fn title_is_required() {
170 assert!(HomeworkTitle::try_new("Read chapter 3").is_ok());
171 assert!(HomeworkTitle::try_new("").is_err());
172 assert!(HomeworkTitle::try_new(" ").is_err());
173 assert!(HomeworkTitle::try_new(&"x".repeat(201)).is_err());
174 }
175
176 #[tokio::test]
177 async fn description_is_optional_but_bounded() {
178 assert!(HomeworkDescription::try_new("").is_ok());
179 assert!(HomeworkDescription::try_new(&"x".repeat(2_001)).is_err());
180 }
181
182 #[tokio::test]
183 async fn student_sees_covers_whole_course_and_named_subsets() {
184 let a = UserId::from_key(A);
185 let b = UserId::from_key(B);
186 let with = |assigned| Homework {
187 id: HomeworkId::generate(),
188 class_course: ClassCourseId::from_key("0198f1a2-3b4c-7d5e-8f90-cccc3c4d5e6f"),
189 subject: SubjectId::from_key("0198f1a2-3b4c-7d5e-8f90-dddd4c4d5e6f"),
190 title: HomeworkTitle::try_new("hw").unwrap(),
191 description: None,
192 due_at: Timestamp::from_millis(1),
193 assigned,
194 created_by: a,
195 created_at: Timestamp::from_millis(1),
196 };
197 // Whole course: NULL or empty list means everyone sees it.
198 assert!(with(None).student_sees(&a));
199 assert!(with(Some(vec![])).student_sees(&b));
200 // Subset: only the named students.
201 assert!(with(Some(vec![a])).student_sees(&a));
202 assert!(!with(Some(vec![a])).student_sees(&b));
203 }
204}