forge
Explore
Log in

Don't you dare go Hollow

Domain, tables, constants

Browse files at this commit

7425b19c815bf8d0d9ba7a3eab9d10ba34770941Ahmet Kaan GümüşParent: 0c59412
  • feat
    • domain, tables, constants
Show full message
✨ feat(homework): domain, tables, constants
src/constant.rsmodified+20 -0
@@ -85,6 +85,19 @@ pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000;
85 pub const MAX_SUBJECT_NAME_LEN: usize = 200;85 pub const MAX_SUBJECT_NAME_LEN: usize = 200;
86 pub const MAX_SUBJECT_DESCRIPTION_LEN: usize = 2_000;86 pub const MAX_SUBJECT_DESCRIPTION_LEN: usize = 2_000;
87 87
88+pub const MAX_HOMEWORK_TITLE_LEN: usize = 200;
89+pub const MAX_HOMEWORK_DESCRIPTION_LEN: usize = 2_000;
90+
91+/// A homework submission's optional free-text note, sent alongside its files.
92+pub const MAX_HOMEWORK_TEXT_LEN: usize = 5_000;
93+
94+/// How many files one homework submission may carry.
95+pub const MAX_HOMEWORK_FILES_PER_SUBMISSION: usize = 10;
96+
97+/// How many students a homework may be narrowed to. The whole-course default
98+/// carries no assigned list at all, so this caps only an explicit subset.
99+pub const MAX_HOMEWORK_ASSIGNED: usize = 200;
100+
88 /// The default attendance states, and also the mandatory core: a school may101 /// The default attendance states, and also the mandatory core: a school may
89 /// add its own statuses via `PATCH /settings`, but these four can never be102 /// add its own statuses via `PATCH /settings`, but these four can never be
90 /// removed — the attendance rate's semantics are defined over them.103 /// removed — the attendance rate's semantics are defined over them.
@@ -133,6 +146,13 @@ pub const COURSE_KINDS: [&str; 3] = ["course", "study", "club"];
133 /// exam with no mode at all is an offline-graded draft and cannot be sat.146 /// exam with no mode at all is an offline-graded draft and cannot be sat.
134 pub const EXAM_MODES: [&str; 3] = ["sync", "async", "open"];147 pub const EXAM_MODES: [&str; 3] = ["sync", "async", "open"];
135 148
149+/// The only accepted homework grades. `done`: submitted and complete;
150+/// `incomplete`: submitted but lacking; `missing`: not done. A teacher-set
151+/// `missing` is a deliberate verdict, distinct from the roster's *computed*
152+/// missing (unsubmitted past due). The `HomeworkStatus` newtype enforces the
153+/// set; the DDL carries no ASSERT (repo convention), exactly like `EXAM_MODES`.
154+pub const HOMEWORK_STATUSES: [&str; 3] = ["done", "incomplete", "missing"];
155+
136 /// Inclusive bounds for an exam's per-attempt duration, milliseconds156 /// Inclusive bounds for an exam's per-attempt duration, milliseconds
137 /// (1 minute to 24 hours). Required for `async`, optional for `open`.157 /// (1 minute to 24 hours). Required for `async`, optional for `open`.
138 pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000;158 pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000;
src/database.rsmodified+48 -0
@@ -50,6 +50,10 @@ pub const TERM_TABLE: &str = "term";
50 pub const SUBJECT_TABLE: &str = "subject";50 pub const SUBJECT_TABLE: &str = "subject";
51 pub const POOL_QUESTION_TABLE: &str = "pool_question";51 pub const POOL_QUESTION_TABLE: &str = "pool_question";
52 pub const SOLUTION_TABLE: &str = "solution";52 pub const SOLUTION_TABLE: &str = "solution";
53+pub const HOMEWORK_TABLE: &str = "homework";
54+pub const HOMEWORK_SUBMISSION_TABLE: &str = "homework_submission";
55+pub const HOMEWORK_FILE_TABLE: &str = "homework_file";
56+pub const HOMEWORK_RESULT_TABLE: &str = "homework_result";
53 57
54 /// SCHEMAFULL schema: every column is typed, references use `record<..>`.58 /// SCHEMAFULL schema: every column is typed, references use `record<..>`.
55 /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the59 /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the
@@ -307,6 +311,50 @@ const MIGRATION: &str = "
307 DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int;311 DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int;
308 DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string;312 DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string;
309 DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option<int>;313 DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option<int>;
314+
315+ -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students
316+ -- submit files + optional text, a teacher grades a status + optional mark.
317+ -- `course`/`created_by`/`created_at` are READONLY (a homework never moves
318+ -- course, and stamps never rewrite); `subject` is NOT — it is re-taggable
319+ -- via PATCH. `assigned` NONE/empty means the whole course. No BACKFILL: the
320+ -- tables are new, so the whole migration stays additive and idempotent.
321+ DEFINE TABLE IF NOT EXISTS homework SCHEMAFULL;
322+ DEFINE FIELD IF NOT EXISTS course ON homework TYPE record<course> READONLY;
323+ DEFINE FIELD IF NOT EXISTS subject ON homework TYPE record<subject>;
324+ DEFINE FIELD IF NOT EXISTS title ON homework TYPE string;
325+ DEFINE FIELD IF NOT EXISTS description ON homework TYPE option<string>;
326+ DEFINE FIELD IF NOT EXISTS due_at ON homework TYPE int;
327+ DEFINE FIELD IF NOT EXISTS assigned ON homework TYPE option<array<record<user>>>;
328+ DEFINE FIELD IF NOT EXISTS assigned[*] ON homework TYPE record<user>;
329+ DEFINE FIELD IF NOT EXISTS created_by ON homework TYPE record<user> READONLY;
330+ DEFINE FIELD IF NOT EXISTS created_at ON homework TYPE int READONLY;
331+ DEFINE INDEX IF NOT EXISTS homework_course ON homework FIELDS course;
332+
333+ DEFINE TABLE IF NOT EXISTS homework_submission SCHEMAFULL;
334+ DEFINE FIELD IF NOT EXISTS homework ON homework_submission TYPE record<homework> READONLY;
335+ DEFINE FIELD IF NOT EXISTS user ON homework_submission TYPE record<user> READONLY;
336+ DEFINE FIELD IF NOT EXISTS text ON homework_submission TYPE option<string>;
337+ DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY;
338+ DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int;
339+ DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework;
340+
341+ DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL;
342+ DEFINE FIELD IF NOT EXISTS submission ON homework_file TYPE record<homework_submission> READONLY;
343+ DEFINE FIELD IF NOT EXISTS name ON homework_file TYPE string;
344+ DEFINE FIELD IF NOT EXISTS content_type ON homework_file TYPE string;
345+ DEFINE FIELD IF NOT EXISTS size ON homework_file TYPE int;
346+ DEFINE FIELD IF NOT EXISTS file ON homework_file TYPE string READONLY;
347+ DEFINE FIELD IF NOT EXISTS created_at ON homework_file TYPE int READONLY;
348+ DEFINE INDEX IF NOT EXISTS homework_file_submission ON homework_file FIELDS submission;
349+
350+ DEFINE TABLE IF NOT EXISTS homework_result SCHEMAFULL;
351+ DEFINE FIELD IF NOT EXISTS homework ON homework_result TYPE record<homework> READONLY;
352+ DEFINE FIELD IF NOT EXISTS user ON homework_result TYPE record<user> READONLY;
353+ DEFINE FIELD IF NOT EXISTS status ON homework_result TYPE string;
354+ DEFINE FIELD IF NOT EXISTS mark ON homework_result TYPE option<int>;
355+ DEFINE FIELD IF NOT EXISTS graded_by ON homework_result TYPE record<user>;
356+ DEFINE FIELD IF NOT EXISTS created_at ON homework_result TYPE int;
357+ DEFINE INDEX IF NOT EXISTS homework_result_homework ON homework_result FIELDS homework;
310 ";358 ";
311 359
312 /// Data backfills for rows written by older binaries. Runs *after* (and apart360 /// Data backfills for rows written by older binaries. Runs *after* (and apart
src/domain/homework.rsadded+303 -0
@@ -0,0 +1,303 @@
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. Students submit against it
4+//! ([`crate::domain::homework_submission`]) and a teacher grades a status plus
5+//! an optional mark ([`crate::domain::homework_result`]).
6+//!
7+//! `course`, `created_by`, and `created_at` are fixed at creation (the schema
8+//! marks them `READONLY`): moving a homework between courses would strand the
9+//! submissions and grades of students not in the target course. `subject` is
10+//! deliberately *not* readonly — it is re-taggable through PATCH, validated
11+//! same-course by the web layer, exactly like an exam question's subject.
12+
13+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
14+use ulid::Ulid;
15+
16+use crate::constant::{MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN};
17+use crate::database::{Database, HOMEWORK_TABLE};
18+use crate::domain::course::CourseId;
19+use crate::domain::subject::SubjectId;
20+use crate::domain::timestamp::Timestamp;
21+use crate::domain::user::UserId;
22+use crate::error::{AppError, ValidationError};
23+use crate::validate::{validate_optional, validate_required};
24+
25+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
26+pub struct HomeworkId(RecordId);
27+
28+impl HomeworkId {
29+ pub fn generate() -> Self {
30+ Self(RecordId::new(HOMEWORK_TABLE, Ulid::new().to_string()))
31+ }
32+
33+ pub fn from_key(key: &str) -> Self {
34+ Self(RecordId::new(HOMEWORK_TABLE, key))
35+ }
36+
37+ pub fn record(&self) -> RecordId {
38+ self.0.clone()
39+ }
40+
41+ pub fn key(&self) -> &str {
42+ match &self.0.key {
43+ RecordIdKey::String(key) => key,
44+ _ => "",
45+ }
46+ }
47+}
48+
49+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
50+pub struct HomeworkTitle(String);
51+
52+impl HomeworkTitle {
53+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
54+ validate_required("title", value, MAX_HOMEWORK_TITLE_LEN)?;
55+ Ok(Self(value.to_string()))
56+ }
57+
58+ pub fn as_str(&self) -> &str {
59+ &self.0
60+ }
61+}
62+
63+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
64+pub struct HomeworkDescription(String);
65+
66+impl HomeworkDescription {
67+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
68+ validate_optional("description", value, MAX_HOMEWORK_DESCRIPTION_LEN)?;
69+ Ok(Self(value.to_string()))
70+ }
71+
72+ pub fn as_str(&self) -> &str {
73+ &self.0
74+ }
75+}
76+
77+/// A homework assignment. `assigned` is the optional student subset: `None`
78+/// (the column absent) and an empty list both mean "the whole course" — see
79+/// [`Homework::student_sees`]. Because whole-course homework carries no roster,
80+/// a student who enrolls later is covered automatically; a subset is a fixed
81+/// snapshot of the students named at assign (or last PATCH) time.
82+#[derive(Debug, Clone, SurrealValue)]
83+pub struct Homework {
84+ id: HomeworkId,
85+ course: CourseId,
86+ subject: SubjectId,
87+ title: HomeworkTitle,
88+ description: Option<HomeworkDescription>,
89+ due_at: Timestamp,
90+ assigned: Option<Vec<UserId>>,
91+ created_by: UserId,
92+ created_at: Timestamp,
93+}
94+
95+impl Homework {
96+ pub fn get_id(&self) -> &HomeworkId {
97+ &self.id
98+ }
99+
100+ pub fn get_course(&self) -> &CourseId {
101+ &self.course
102+ }
103+
104+ pub fn get_subject(&self) -> &SubjectId {
105+ &self.subject
106+ }
107+
108+ pub fn get_title(&self) -> &HomeworkTitle {
109+ &self.title
110+ }
111+
112+ pub fn get_description(&self) -> Option<&HomeworkDescription> {
113+ self.description.as_ref()
114+ }
115+
116+ pub fn get_due_at(&self) -> Timestamp {
117+ self.due_at
118+ }
119+
120+ /// The assigned student subset, or `None` for a whole-course homework.
121+ pub fn get_assigned(&self) -> Option<&[UserId]> {
122+ self.assigned.as_deref()
123+ }
124+
125+ pub fn get_created_by(&self) -> &UserId {
126+ &self.created_by
127+ }
128+
129+ pub fn get_created_at(&self) -> Timestamp {
130+ self.created_at
131+ }
132+
133+ /// Whether `user` is in this homework's audience. A whole-course homework
134+ /// (`assigned` absent or empty) is visible to every enrolled student; a
135+ /// subset homework only to the students it names. Callers pair this with an
136+ /// enrollment check — being named is visibility, not enrollment.
137+ pub fn student_sees(&self, user: &UserId) -> bool {
138+ match &self.assigned {
139+ None => true,
140+ Some(assigned) => assigned.is_empty() || assigned.contains(user),
141+ }
142+ }
143+
144+ #[expect(
145+ clippy::too_many_arguments,
146+ reason = "mirrors the sibling entities' create(field, field, ..) shape"
147+ )]
148+ pub async fn create(
149+ course: &CourseId,
150+ subject: &SubjectId,
151+ title: HomeworkTitle,
152+ description: Option<HomeworkDescription>,
153+ due_at: Timestamp,
154+ assigned: Option<Vec<UserId>>,
155+ created_by: &UserId,
156+ db: &Database,
157+ ) -> Result<Homework, AppError> {
158+ let homework = Homework {
159+ id: HomeworkId::generate(),
160+ course: course.clone(),
161+ subject: subject.clone(),
162+ title,
163+ description,
164+ due_at,
165+ assigned,
166+ created_by: created_by.clone(),
167+ created_at: Timestamp::now(),
168+ };
169+ let created: Option<Homework> = db.create(homework.id.record()).content(homework).await?;
170+ created.ok_or_else(|| AppError::Internal("failed to create homework".into()))
171+ }
172+
173+ pub async fn read(id: &HomeworkId, db: &Database) -> Result<Option<Homework>, AppError> {
174+ Ok(db.select(id.record()).await?)
175+ }
176+
177+ /// The course's homework, newest first (ULID ids sort by creation). The web
178+ /// layer retains only the rows a given student `student_sees`.
179+ pub async fn list_for_course(
180+ course: &CourseId,
181+ db: &Database,
182+ ) -> Result<Vec<Homework>, AppError> {
183+ let mut result = db
184+ .query("SELECT * FROM homework WHERE course = $course ORDER BY id DESC")
185+ .bind(("course", course.record()))
186+ .await?
187+ .check()?;
188+ Ok(result.take::<Vec<Homework>>(0)?)
189+ }
190+
191+ /// The homework of `course` that `user` is meant to see — whole-course ones
192+ /// plus any subset that names them — newest first. Backs a student's (or an
193+ /// observer's) per-course homework report; mirrors [`Homework::student_sees`]
194+ /// in SurQL so the filter runs in the database.
195+ pub async fn list_for_user_in_course(
196+ course: &CourseId,
197+ user: &UserId,
198+ db: &Database,
199+ ) -> Result<Vec<Homework>, AppError> {
200+ let mut result = db
201+ .query(
202+ "SELECT * FROM homework
203+ WHERE course = $course
204+ AND (assigned = NONE OR assigned = [] OR $usr IN assigned)
205+ ORDER BY id DESC",
206+ )
207+ .bind(("course", course.record()))
208+ .bind(("usr", user.record()))
209+ .await?
210+ .check()?;
211+ Ok(result.take::<Vec<Homework>>(0)?)
212+ }
213+
214+ /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework.
215+ /// `course`, `created_by`, and `created_at` are untouched — the write
216+ /// re-sends them unchanged, which the `READONLY` schema permits (only a
217+ /// *changed* readonly value is refused). The web layer has already
218+ /// re-checked the new `due_at` against now and the new `subject` against
219+ /// the course, and refused a narrowing that would orphan a submission.
220+ pub async fn update(
221+ mut self,
222+ subject: &SubjectId,
223+ title: HomeworkTitle,
224+ description: Option<HomeworkDescription>,
225+ due_at: Timestamp,
226+ assigned: Option<Vec<UserId>>,
227+ db: &Database,
228+ ) -> Result<Homework, AppError> {
229+ self.subject = subject.clone();
230+ self.title = title;
231+ self.description = description;
232+ self.due_at = due_at;
233+ self.assigned = assigned;
234+ let updated: Option<Homework> = db.update(self.id.record()).content(self).await?;
235+ updated.ok_or(AppError::NotFound)
236+ }
237+
238+ /// Delete the homework and cascade its submissions, their files, and its
239+ /// results — one transaction, so a crash can't orphan a submission under a
240+ /// vanished homework. The submission file *blobs* are the web layer's to
241+ /// unlink: it collects their names via
242+ /// [`crate::domain::homework_file::HomeworkFile::file_keys_for_homework`]
243+ /// before calling this, and removes them after the rows are gone.
244+ pub async fn delete(self, db: &Database) -> Result<Homework, AppError> {
245+ let mut result = db
246+ .query(
247+ "BEGIN TRANSACTION;
248+ DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw);
249+ DELETE homework_submission WHERE homework = $hw;
250+ DELETE homework_result WHERE homework = $hw;
251+ DELETE $hw RETURN BEFORE;
252+ COMMIT TRANSACTION;",
253+ )
254+ .bind(("hw", self.id.record()))
255+ .await?
256+ .check()?;
257+ // BEGIN is slot 0; the homework's own DELETE is slot 4.
258+ let deleted: Option<Homework> = result.take::<Vec<Homework>>(4)?.into_iter().next();
259+ deleted.ok_or(AppError::NotFound)
260+ }
261+}
262+
263+#[cfg(test)]
264+mod tests {
265+ use super::*;
266+
267+ #[tokio::test]
268+ async fn title_is_required() {
269+ assert!(HomeworkTitle::try_new("Read chapter 3").is_ok());
270+ assert!(HomeworkTitle::try_new("").is_err());
271+ assert!(HomeworkTitle::try_new(" ").is_err());
272+ assert!(HomeworkTitle::try_new(&"x".repeat(201)).is_err());
273+ }
274+
275+ #[tokio::test]
276+ async fn description_is_optional_but_bounded() {
277+ assert!(HomeworkDescription::try_new("").is_ok());
278+ assert!(HomeworkDescription::try_new(&"x".repeat(2_001)).is_err());
279+ }
280+
281+ #[tokio::test]
282+ async fn student_sees_covers_whole_course_and_named_subsets() {
283+ let a = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
284+ let b = UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB");
285+ let with = |assigned| Homework {
286+ id: HomeworkId::generate(),
287+ course: CourseId::from_key("01TESTCOURSEAAAAAAAAAAAAAA"),
288+ subject: SubjectId::from_key("01TESTSUBJECTAAAAAAAAAAAAA"),
289+ title: HomeworkTitle::try_new("hw").unwrap(),
290+ description: None,
291+ due_at: Timestamp::from_millis(1),
292+ assigned,
293+ created_by: a.clone(),
294+ created_at: Timestamp::from_millis(1),
295+ };
296+ // Whole course: absent or empty list means everyone sees it.
297+ assert!(with(None).student_sees(&a));
298+ assert!(with(Some(vec![])).student_sees(&b));
299+ // Subset: only the named students.
300+ assert!(with(Some(vec![a.clone()])).student_sees(&a));
301+ assert!(!with(Some(vec![a.clone()])).student_sees(&b));
302+ }
303+}
src/domain/homework_file.rsadded+281 -0
@@ -0,0 +1,281 @@
1+//! A file attached to a homework submission. Like a note file, the row carries
2+//! metadata only (original filename, MIME type, byte size) and the bytes live
3+//! on disk under [`crate::config::Config::files_path`] — but named by this
4+//! row's own `file` field (a fresh server-generated ULID per upload, like a
5+//! question image), never by user input, so nothing a client sends shapes a
6+//! disk path. Files are immutable: created and deleted, never updated, so the
7+//! `READONLY` `submission`/`file`/`created_at` columns are only ever set once.
8+//! The web layer owns the blob I/O and its ordering (blob before row on
9+//! upload, row before blob on delete); this module owns the rows.
10+
11+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
12+use tokio::sync::Mutex;
13+use ulid::Ulid;
14+
15+use crate::constant::MAX_HOMEWORK_FILES_PER_SUBMISSION;
16+use crate::database::{Database, HOMEWORK_FILE_TABLE};
17+use crate::domain::course::CourseId;
18+use crate::domain::homework::HomeworkId;
19+use crate::domain::homework_submission::HomeworkSubmissionId;
20+use crate::domain::note_file::{FileContentType, FileName};
21+use crate::domain::timestamp::Timestamp;
22+use crate::error::AppError;
23+
24+/// Serializes the files-per-submission cap check against the insert (see
25+/// [`HomeworkFile::insert`]). Its own lock, not note files' `FILE_CAP_LOCK`:
26+/// the two caps are independent counts and must not needlessly contend on one
27+/// mutex. This backend is the database's only writer, so one process-wide lock
28+/// suffices.
29+// ponytail: global lock, per-submission locks if uploads ever see real contention.
30+static SUBMISSION_FILE_LOCK: Mutex<()> = Mutex::const_new(());
31+
32+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
33+pub struct HomeworkFileId(RecordId);
34+
35+impl HomeworkFileId {
36+ pub fn generate() -> Self {
37+ Self(RecordId::new(HOMEWORK_FILE_TABLE, Ulid::new().to_string()))
38+ }
39+
40+ pub fn from_key(key: &str) -> Self {
41+ Self(RecordId::new(HOMEWORK_FILE_TABLE, key))
42+ }
43+
44+ pub fn record(&self) -> RecordId {
45+ self.0.clone()
46+ }
47+
48+ pub fn key(&self) -> &str {
49+ match &self.0.key {
50+ RecordIdKey::String(key) => key,
51+ _ => "",
52+ }
53+ }
54+}
55+
56+/// An attachment row. `file` is the blob's on-disk name (a fresh ULID per
57+/// upload), independent of the row id and reused as the GC key on cascade.
58+#[derive(Debug, Clone, SurrealValue)]
59+pub struct HomeworkFile {
60+ id: HomeworkFileId,
61+ submission: HomeworkSubmissionId,
62+ name: FileName,
63+ content_type: FileContentType,
64+ size: i64,
65+ file: String,
66+ created_at: Timestamp,
67+}
68+
69+impl HomeworkFile {
70+ /// Assemble a row (fresh blob name generated here) without persisting it.
71+ /// The caller writes the blob under [`Self::get_file`] first, then calls
72+ /// [`Self::insert`] — so a stored row always points at a real blob.
73+ pub fn new(
74+ submission: &HomeworkSubmissionId,
75+ name: FileName,
76+ content_type: FileContentType,
77+ size: i64,
78+ ) -> Self {
79+ Self {
80+ id: HomeworkFileId::generate(),
81+ submission: submission.clone(),
82+ name,
83+ content_type,
84+ size,
85+ file: Ulid::new().to_string(),
86+ created_at: Timestamp::now(),
87+ }
88+ }
89+
90+ pub fn get_id(&self) -> &HomeworkFileId {
91+ &self.id
92+ }
93+
94+ pub fn get_submission(&self) -> &HomeworkSubmissionId {
95+ &self.submission
96+ }
97+
98+ pub fn get_name(&self) -> &FileName {
99+ &self.name
100+ }
101+
102+ pub fn get_content_type(&self) -> &FileContentType {
103+ &self.content_type
104+ }
105+
106+ pub fn get_size(&self) -> i64 {
107+ self.size
108+ }
109+
110+ /// The blob's on-disk name — a fresh ULID, so no user input shapes a path.
111+ pub fn get_file(&self) -> &str {
112+ &self.file
113+ }
114+
115+ pub fn get_created_at(&self) -> Timestamp {
116+ self.created_at
117+ }
118+
119+ /// Persist the row assembled by [`Self::new`], refusing once its submission
120+ /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`]. The
121+ /// count-then-create runs under [`SUBMISSION_FILE_LOCK`]: a `BEGIN…COMMIT`
122+ /// can't enforce the cap because SurrealDB doesn't conflict-check a
123+ /// cross-record count against a concurrent insert (write-skew), the same
124+ /// story as `NoteFile::insert`.
125+ pub async fn insert(self, db: &Database) -> Result<HomeworkFile, AppError> {
126+ let _guard = SUBMISSION_FILE_LOCK.lock().await;
127+ if Self::count_for_submission(&self.submission, db).await?
128+ >= MAX_HOMEWORK_FILES_PER_SUBMISSION
129+ {
130+ return Err(AppError::Conflict(
131+ "the submission already holds the maximum of 10 files — delete one first",
132+ ));
133+ }
134+ let created: Option<HomeworkFile> = db.create(self.id.record()).content(self).await?;
135+ created.ok_or_else(|| AppError::Internal("failed to create homework file".into()))
136+ }
137+
138+ /// Read a file's row only if it belongs to `submission` — callers have
139+ /// already checked the submission belongs to the requesting user.
140+ pub async fn read_for(
141+ id: &HomeworkFileId,
142+ submission: &HomeworkSubmissionId,
143+ db: &Database,
144+ ) -> Result<Option<HomeworkFile>, AppError> {
145+ let file: Option<HomeworkFile> = db.select(id.record()).await?;
146+ Ok(file.filter(|file| &file.submission == submission))
147+ }
148+
149+ /// All of `submission`'s files, newest first.
150+ pub async fn list_for_submission(
151+ submission: &HomeworkSubmissionId,
152+ db: &Database,
153+ ) -> Result<Vec<HomeworkFile>, AppError> {
154+ let mut result = db
155+ .query("SELECT * FROM homework_file WHERE submission = $sub ORDER BY id DESC")
156+ .bind(("sub", submission.record()))
157+ .await?
158+ .check()?;
159+ Ok(result.take::<Vec<HomeworkFile>>(0)?)
160+ }
161+
162+ /// How many files `submission` holds — the cap check reads this under the
163+ /// lock. Counting via the rows (not a `count()` query) keeps it identical
164+ /// to `NoteFile`'s proven cap check; at a ceiling of 10 the cost is nil.
165+ pub async fn count_for_submission(
166+ submission: &HomeworkSubmissionId,
167+ db: &Database,
168+ ) -> Result<usize, AppError> {
169+ Ok(Self::list_for_submission(submission, db).await?.len())
170+ }
171+
172+ /// The blob names behind every file of every submission to `homework` —
173+ /// collected *before* the homework-delete cascade wipes the rows, so the
174+ /// web layer can unlink them once the rows are gone.
175+ pub async fn file_keys_for_homework(
176+ homework: &HomeworkId,
177+ db: &Database,
178+ ) -> Result<Vec<String>, AppError> {
179+ let mut result = db
180+ .query(
181+ "SELECT VALUE file FROM homework_file \
182+ WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw)",
183+ )
184+ .bind(("hw", homework.record()))
185+ .await?
186+ .check()?;
187+ Ok(result.take::<Vec<String>>(0)?)
188+ }
189+
190+ /// The blob names behind every homework file of `course` — collected
191+ /// *before* the course-delete cascade wipes the rows.
192+ pub async fn file_keys_for_course(
193+ course: &CourseId,
194+ db: &Database,
195+ ) -> Result<Vec<String>, AppError> {
196+ let mut result = db
197+ .query(
198+ "SELECT VALUE file FROM homework_file WHERE submission IN ( \
199+ SELECT VALUE id FROM homework_submission \
200+ WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course) \
201+ )",
202+ )
203+ .bind(("course", course.record()))
204+ .await?
205+ .check()?;
206+ Ok(result.take::<Vec<String>>(0)?)
207+ }
208+
209+ pub async fn delete(self, db: &Database) -> Result<HomeworkFile, AppError> {
210+ let deleted: Option<HomeworkFile> = db.delete(self.id.record()).await?;
211+ deleted.ok_or(AppError::NotFound)
212+ }
213+}
214+
215+#[cfg(test)]
216+mod tests {
217+ use super::*;
218+ use crate::domain::homework_submission::HomeworkSubmission;
219+ use crate::domain::user::UserId;
220+
221+ fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile {
222+ HomeworkFile::new(
223+ submission,
224+ FileName::try_new("answer.pdf").unwrap(),
225+ FileContentType::try_new("application/pdf").unwrap(),
226+ 3,
227+ )
228+ }
229+
230+ #[tokio::test]
231+ async fn rows_scope_to_their_submission_gc_and_cap() {
232+ let db = crate::database::init_mem().await.unwrap();
233+ let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA");
234+ let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
235+ // A real submission row, so the GC join through it resolves.
236+ let submission = HomeworkSubmission::upsert(&homework, &user, None, &db)
237+ .await
238+ .unwrap();
239+ let sub_a = submission.get_id().clone();
240+ let sub_b = HomeworkSubmissionId::composite(
241+ &homework,
242+ &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"),
243+ );
244+
245+ let stored = a_file(&sub_a).insert(&db).await.unwrap();
246+ // Readable under its own submission, invisible under another.
247+ assert!(
248+ HomeworkFile::read_for(stored.get_id(), &sub_a, &db)
249+ .await
250+ .unwrap()
251+ .is_some()
252+ );
253+ assert!(
254+ HomeworkFile::read_for(stored.get_id(), &sub_b, &db)
255+ .await
256+ .unwrap()
257+ .is_none()
258+ );
259+ assert_eq!(
260+ HomeworkFile::count_for_submission(&sub_a, &db)
261+ .await
262+ .unwrap(),
263+ 1
264+ );
265+
266+ // The blob name is collectable for GC before a cascade wipes the rows.
267+ let keys = HomeworkFile::file_keys_for_homework(&homework, &db)
268+ .await
269+ .unwrap();
270+ assert_eq!(keys, vec![stored.get_file().to_string()]);
271+
272+ // Fill to the cap, then the 11th is refused.
273+ for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION {
274+ a_file(&sub_a).insert(&db).await.unwrap();
275+ }
276+ assert!(matches!(
277+ a_file(&sub_a).insert(&db).await,
278+ Err(AppError::Conflict(_))
279+ ));
280+ }
281+}
src/domain/homework_result.rsadded+282 -0
@@ -0,0 +1,282 @@
1+//! A teacher's grade on one student's homework: a status
2+//! (`done`/`incomplete`/`missing`) plus an optional numeric [`Mark`] (0..=100,
3+//! reused from exam results). Like an exam result, the row id is the
4+//! deterministic `{homework}_{user}` composite, so grading is one atomic UPSERT
5+//! and there is exactly one grade per (homework, user) by construction.
6+//!
7+//! A stored result is what *freezes* a submission: while a grade exists the
8+//! student's submission and files are locked (the web layer answers 409), until
9+//! the teacher removes the grade to reopen them. The teacher-set `missing`
10+//! status is a deliberate verdict, distinct from the roster's *computed*
11+//! "missing" (unsubmitted past due) — the latter is derived in the web layer,
12+//! never stored.
13+
14+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
15+
16+use crate::database::{Database, HOMEWORK_RESULT_TABLE};
17+use crate::domain::course::CourseId;
18+use crate::domain::exam_result::Mark;
19+use crate::domain::homework::HomeworkId;
20+use crate::domain::timestamp::Timestamp;
21+use crate::domain::user::UserId;
22+use crate::error::{AppError, ValidationError};
23+use crate::validate::validate_homework_status;
24+
25+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
26+pub struct HomeworkResultId(RecordId);
27+
28+impl HomeworkResultId {
29+ /// The one id a (homework, user) pair can have — a deterministic composite,
30+ /// so grading is a single atomic UPSERT with no find-then-insert race and
31+ /// one grade per pair by construction. ULID keys are alphanumeric, so `_`
32+ /// is an unambiguous joiner.
33+ pub fn composite(homework: &HomeworkId, user: &UserId) -> Self {
34+ Self(RecordId::new(
35+ HOMEWORK_RESULT_TABLE,
36+ format!("{}_{}", homework.key(), user.key()),
37+ ))
38+ }
39+
40+ pub fn record(&self) -> RecordId {
41+ self.0.clone()
42+ }
43+
44+ pub fn key(&self) -> &str {
45+ match &self.0.key {
46+ RecordIdKey::String(key) => key,
47+ _ => "",
48+ }
49+ }
50+}
51+
52+/// A validated homework grade: `done` (submitted and complete), `incomplete`
53+/// (submitted but lacking), or `missing` (not done). Held to the
54+/// [`crate::constant::HOMEWORK_STATUSES`] set by [`HomeworkStatus::try_new`] —
55+/// the same validated-string-against-a-const shape as
56+/// [`crate::domain::exam::ExamMode`], which is why the `status` column needs no
57+/// DDL `ASSERT` (repo convention: enums live in Rust newtypes, not the schema).
58+/// It stores as the bare string. A stored `missing` is a teacher's deliberate
59+/// verdict, distinct from the roster's *computed* missing (unsubmitted past due,
60+/// derived in the web layer, never stored).
61+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
62+pub struct HomeworkStatus(String);
63+
64+impl HomeworkStatus {
65+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
66+ validate_homework_status(value)?;
67+ Ok(Self(value.to_string()))
68+ }
69+
70+ pub fn as_str(&self) -> &str {
71+ &self.0
72+ }
73+}
74+
75+#[derive(Debug, Clone, SurrealValue)]
76+pub struct HomeworkResult {
77+ id: HomeworkResultId,
78+ homework: HomeworkId,
79+ user: UserId,
80+ status: HomeworkStatus,
81+ mark: Option<Mark>,
82+ graded_by: UserId,
83+ created_at: Timestamp,
84+}
85+
86+impl HomeworkResult {
87+ pub fn get_id(&self) -> &HomeworkResultId {
88+ &self.id
89+ }
90+
91+ pub fn get_homework(&self) -> &HomeworkId {
92+ &self.homework
93+ }
94+
95+ pub fn get_user(&self) -> &UserId {
96+ &self.user
97+ }
98+
99+ pub fn get_status(&self) -> &HomeworkStatus {
100+ &self.status
101+ }
102+
103+ /// The optional numeric mark; `None` when the teacher graded status only.
104+ pub fn get_mark(&self) -> Option<Mark> {
105+ self.mark
106+ }
107+
108+ pub fn get_graded_by(&self) -> &UserId {
109+ &self.graded_by
110+ }
111+
112+ pub fn get_created_at(&self) -> Timestamp {
113+ self.created_at
114+ }
115+
116+ /// Record (or overwrite) the grade for (homework, user). One row per pair,
117+ /// keyed by the deterministic composite id, so this is a single atomic
118+ /// UPSERT — concurrent grades for the same pair converge on one row instead
119+ /// of racing a unique index into a 500. Grading before the due date, or
120+ /// before any submission exists, is allowed (the caller's policy call).
121+ pub async fn grade(
122+ homework: &HomeworkId,
123+ user: &UserId,
124+ status: HomeworkStatus,
125+ mark: Option<Mark>,
126+ graded_by: &UserId,
127+ db: &Database,
128+ ) -> Result<HomeworkResult, AppError> {
129+ let result = HomeworkResult {
130+ id: HomeworkResultId::composite(homework, user),
131+ homework: homework.clone(),
132+ user: user.clone(),
133+ status,
134+ mark,
135+ graded_by: graded_by.clone(),
136+ created_at: Timestamp::now(),
137+ };
138+ let saved: Option<HomeworkResult> = db.upsert(result.id.record()).content(result).await?;
139+ saved.ok_or_else(|| AppError::Internal("failed to record homework result".into()))
140+ }
141+
142+ /// `user`'s grade for `homework`, if graded.
143+ pub async fn read_for(
144+ homework: &HomeworkId,
145+ user: &UserId,
146+ db: &Database,
147+ ) -> Result<Option<HomeworkResult>, AppError> {
148+ Ok(db
149+ .select(HomeworkResultId::composite(homework, user).record())
150+ .await?)
151+ }
152+
153+ /// Every grade for `homework` — the roster joins these onto the submissions.
154+ pub async fn list_for_homework(
155+ homework: &HomeworkId,
156+ db: &Database,
157+ ) -> Result<Vec<HomeworkResult>, AppError> {
158+ let mut result = db
159+ .query("SELECT * FROM homework_result WHERE homework = $hw ORDER BY id DESC")
160+ .bind(("hw", homework.record()))
161+ .await?
162+ .check()?;
163+ Ok(result.take::<Vec<HomeworkResult>>(0)?)
164+ }
165+
166+ /// `user`'s homework grades across one course — the raw rows behind the
167+ /// per-course block of a homework report. Mirrors
168+ /// `ExamResult::list_for_user_in_course`.
169+ pub async fn list_for_user_in_course(
170+ course: &CourseId,
171+ user: &UserId,
172+ db: &Database,
173+ ) -> Result<Vec<HomeworkResult>, AppError> {
174+ let mut result = db
175+ .query(
176+ "SELECT * FROM homework_result WHERE user = $usr
177+ AND homework IN (SELECT VALUE id FROM homework WHERE course = $course)
178+ ORDER BY id DESC",
179+ )
180+ .bind(("usr", user.record()))
181+ .bind(("course", course.record()))
182+ .await?
183+ .check()?;
184+ Ok(result.take::<Vec<HomeworkResult>>(0)?)
185+ }
186+
187+ /// Un-grade (homework, user), returning the removed row (`None` if there
188+ /// was none). Removing the grade unfreezes the student's submission.
189+ pub async fn remove(
190+ homework: &HomeworkId,
191+ user: &UserId,
192+ db: &Database,
193+ ) -> Result<Option<HomeworkResult>, AppError> {
194+ let mut result = db
195+ .query("DELETE homework_result WHERE homework = $hw AND user = $usr RETURN BEFORE")
196+ .bind(("hw", homework.record()))
197+ .bind(("usr", user.record()))
198+ .await?
199+ .check()?;
200+ Ok(result.take::<Vec<HomeworkResult>>(0)?.into_iter().next())
201+ }
202+}
203+
204+#[cfg(test)]
205+mod tests {
206+ use super::*;
207+ use crate::constant::HOMEWORK_STATUSES;
208+ use surrealdb::types::Value;
209+
210+ #[tokio::test]
211+ async fn status_is_held_to_the_const_and_stores_as_a_bare_string() {
212+ // Enforcement lives in the newtype against HOMEWORK_STATUSES (the DDL
213+ // carries no ASSERT), and the stored value is the bare validated string
214+ // the `status` column's `TYPE string` accepts. Guard both never drift.
215+ for status in HOMEWORK_STATUSES {
216+ let parsed = HomeworkStatus::try_new(status).unwrap();
217+ assert_eq!(parsed.as_str(), status);
218+ assert_eq!(parsed.into_value(), Value::String(status.to_string()));
219+ }
220+ assert!(HomeworkStatus::try_new("late").is_err());
221+ assert!(HomeworkStatus::try_new("").is_err());
222+ }
223+
224+ #[tokio::test]
225+ async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() {
226+ let db = crate::database::init_mem().await.unwrap();
227+ let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA");
228+ let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
229+ let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
230+
231+ let first = HomeworkResult::grade(
232+ &homework,
233+ &user,
234+ HomeworkStatus::try_new("incomplete").unwrap(),
235+ None,
236+ &teacher,
237+ &db,
238+ )
239+ .await
240+ .unwrap();
241+ // A regrade lands on the same row (composite id), overwriting the grade.
242+ let second = HomeworkResult::grade(
243+ &homework,
244+ &user,
245+ HomeworkStatus::try_new("done").unwrap(),
246+ Some(Mark::try_new(80).unwrap()),
247+ &teacher,
248+ &db,
249+ )
250+ .await
251+ .unwrap();
252+ assert_eq!(first.get_id(), second.get_id());
253+ assert_eq!(second.get_status().as_str(), "done");
254+ assert_eq!(second.get_mark().unwrap().as_i64(), 80);
255+ assert_eq!(
256+ HomeworkResult::list_for_homework(&homework, &db)
257+ .await
258+ .unwrap()
259+ .len(),
260+ 1
261+ );
262+
263+ assert!(
264+ HomeworkResult::read_for(&homework, &user, &db)
265+ .await
266+ .unwrap()
267+ .is_some()
268+ );
269+ assert!(
270+ HomeworkResult::remove(&homework, &user, &db)
271+ .await
272+ .unwrap()
273+ .is_some()
274+ );
275+ assert!(
276+ HomeworkResult::read_for(&homework, &user, &db)
277+ .await
278+ .unwrap()
279+ .is_none()
280+ );
281+ }
282+}
src/domain/homework_submission.rsadded+233 -0
@@ -0,0 +1,233 @@
1+//! One student's submission to a homework: an optional free-text note plus any
2+//! number of files ([`crate::domain::homework_file`]). The row id is the
3+//! deterministic `{homework}_{user}` composite, so a student has exactly one
4+//! submission per homework by construction and a re-submit is a single atomic
5+//! UPSERT.
6+//!
7+//! `submitted_at` — the first-submit stamp — is `READONLY` and survives every
8+//! re-submit; [`HomeworkSubmission::upsert`] preserves it inside one statement
9+//! rather than through `.content()`, see there. `updated_at` moves to now on
10+//! every (re-)submit (and, later, on a file add/delete) and drives the computed
11+//! "late" flag (`updated_at > homework.due_at`, judged in the web layer, never
12+//! stored): `submitted_at` answers "was the first hand-in on time", `updated_at`
13+//! "was it touched after the deadline".
14+
15+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
16+
17+use crate::constant::MAX_HOMEWORK_TEXT_LEN;
18+use crate::database::{Database, HOMEWORK_SUBMISSION_TABLE};
19+use crate::domain::homework::HomeworkId;
20+use crate::domain::timestamp::Timestamp;
21+use crate::domain::user::UserId;
22+use crate::error::{AppError, ValidationError};
23+use crate::validate::validate_optional;
24+
25+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
26+pub struct HomeworkSubmissionId(RecordId);
27+
28+impl HomeworkSubmissionId {
29+ /// The one id a (homework, user) pair can have. A deterministic composite
30+ /// means one submission per pair with no unique index and no
31+ /// find-then-insert race — a re-submit UPSERTs the same row. ULID keys are
32+ /// alphanumeric, so `_` is an unambiguous joiner.
33+ pub fn composite(homework: &HomeworkId, user: &UserId) -> Self {
34+ Self(RecordId::new(
35+ HOMEWORK_SUBMISSION_TABLE,
36+ format!("{}_{}", homework.key(), user.key()),
37+ ))
38+ }
39+
40+ pub fn record(&self) -> RecordId {
41+ self.0.clone()
42+ }
43+
44+ pub fn key(&self) -> &str {
45+ match &self.0.key {
46+ RecordIdKey::String(key) => key,
47+ _ => "",
48+ }
49+ }
50+}
51+
52+/// A submission's optional free-text note: may be empty, at most
53+/// `MAX_HOMEWORK_TEXT_LEN` characters. Files ride separately.
54+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
55+pub struct SubmissionText(String);
56+
57+impl SubmissionText {
58+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
59+ validate_optional("text", value, MAX_HOMEWORK_TEXT_LEN)?;
60+ Ok(Self(value.to_string()))
61+ }
62+
63+ pub fn as_str(&self) -> &str {
64+ &self.0
65+ }
66+}
67+
68+#[derive(Debug, Clone, SurrealValue)]
69+pub struct HomeworkSubmission {
70+ id: HomeworkSubmissionId,
71+ homework: HomeworkId,
72+ user: UserId,
73+ text: Option<SubmissionText>,
74+ submitted_at: Timestamp,
75+ updated_at: Timestamp,
76+}
77+
78+impl HomeworkSubmission {
79+ pub fn get_id(&self) -> &HomeworkSubmissionId {
80+ &self.id
81+ }
82+
83+ pub fn get_homework(&self) -> &HomeworkId {
84+ &self.homework
85+ }
86+
87+ pub fn get_user(&self) -> &UserId {
88+ &self.user
89+ }
90+
91+ pub fn get_text(&self) -> Option<&SubmissionText> {
92+ self.text.as_ref()
93+ }
94+
95+ pub fn get_submitted_at(&self) -> Timestamp {
96+ self.submitted_at
97+ }
98+
99+ pub fn get_updated_at(&self) -> Timestamp {
100+ self.updated_at
101+ }
102+
103+ /// Create or re-stamp `user`'s submission to `homework`. `updated_at` moves
104+ /// to now every time; `submitted_at` (readonly, the first-submit stamp) is
105+ /// kept on an existing row and set only on a fresh one.
106+ ///
107+ /// Hand-written rather than `.content()` on purpose: `.content()` re-sends
108+ /// the whole row, so it would carry a `submitted_at`, and any value differing
109+ /// from the stored one trips the readonly guard. The
110+ /// `submitted_at = submitted_at ?? $now` expression preserves it inside the
111+ /// one UPSERT statement — race-free without a lock, where a read-then-content
112+ /// could let two concurrent first-submits pick different stamps and 500.
113+ pub async fn upsert(
114+ homework: &HomeworkId,
115+ user: &UserId,
116+ text: Option<SubmissionText>,
117+ db: &Database,
118+ ) -> Result<HomeworkSubmission, AppError> {
119+ let id = HomeworkSubmissionId::composite(homework, user);
120+ let now = Timestamp::now();
121+ let text = text.map(|text| text.as_str().to_string());
122+ let mut saved = db
123+ .query(
124+ "UPSERT $id SET homework = $hw, user = $usr, text = $text, \
125+ updated_at = $now, submitted_at = submitted_at ?? $now RETURN AFTER",
126+ )
127+ .bind(("id", id.record()))
128+ .bind(("hw", homework.record()))
129+ .bind(("usr", user.record()))
130+ .bind(("text", text))
131+ .bind(("now", now))
132+ .await?
133+ .check()?;
134+ saved
135+ .take::<Vec<HomeworkSubmission>>(0)?
136+ .into_iter()
137+ .next()
138+ .ok_or_else(|| AppError::Internal("failed to save homework submission".into()))
139+ }
140+
141+ /// `user`'s submission to `homework`, if they have one.
142+ pub async fn read_for(
143+ homework: &HomeworkId,
144+ user: &UserId,
145+ db: &Database,
146+ ) -> Result<Option<HomeworkSubmission>, AppError> {
147+ Ok(db
148+ .select(HomeworkSubmissionId::composite(homework, user).record())
149+ .await?)
150+ }
151+
152+ /// Every submission to `homework`, in student (composite-id) order — the
153+ /// roster's raw rows.
154+ pub async fn list_for_homework(
155+ homework: &HomeworkId,
156+ db: &Database,
157+ ) -> Result<Vec<HomeworkSubmission>, AppError> {
158+ let mut result = db
159+ .query("SELECT * FROM homework_submission WHERE homework = $hw ORDER BY id ASC")
160+ .bind(("hw", homework.record()))
161+ .await?
162+ .check()?;
163+ Ok(result.take::<Vec<HomeworkSubmission>>(0)?)
164+ }
165+
166+ /// Delete this submission and its files in one transaction — so a crash
167+ /// can't leave a file pointing at a vanished submission. The file *blobs*
168+ /// are the web layer's to unlink: it lists them
169+ /// ([`crate::domain::homework_file::HomeworkFile::list_for_submission`])
170+ /// before calling this. The caller has already refused the delete if the
171+ /// submission is graded (a result exists).
172+ pub async fn delete(self, db: &Database) -> Result<HomeworkSubmission, AppError> {
173+ let mut result = db
174+ .query(
175+ "BEGIN TRANSACTION;
176+ DELETE homework_file WHERE submission = $sub;
177+ DELETE $sub RETURN BEFORE;
178+ COMMIT TRANSACTION;",
179+ )
180+ .bind(("sub", self.id.record()))
181+ .await?
182+ .check()?;
183+ // BEGIN is slot 0, the file wipe slot 1; the submission's DELETE is slot 2.
184+ let deleted: Option<HomeworkSubmission> =
185+ result.take::<Vec<HomeworkSubmission>>(2)?.into_iter().next();
186+ deleted.ok_or(AppError::NotFound)
187+ }
188+}
189+
190+#[cfg(test)]
191+mod tests {
192+ use super::*;
193+
194+ #[tokio::test]
195+ async fn text_is_optional_but_bounded() {
196+ assert!(SubmissionText::try_new("").is_ok());
197+ assert!(SubmissionText::try_new(&"x".repeat(5_000)).is_ok());
198+ assert!(SubmissionText::try_new(&"x".repeat(5_001)).is_err());
199+ }
200+
201+ #[tokio::test]
202+ async fn resubmit_keeps_submitted_at_and_restamps_updated_at() {
203+ let db = crate::database::init_mem().await.unwrap();
204+ let homework = HomeworkId::generate();
205+ let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
206+
207+ let first = HomeworkSubmission::upsert(
208+ &homework,
209+ &user,
210+ Some(SubmissionText::try_new("draft").unwrap()),
211+ &db,
212+ )
213+ .await
214+ .unwrap();
215+ // A re-submit lands on the same row: submitted_at (the first hand-in)
216+ // pinned, updated_at moves forward, and the text can be cleared.
217+ let second = HomeworkSubmission::upsert(&homework, &user, None, &db)
218+ .await
219+ .unwrap();
220+ assert_eq!(first.get_id(), second.get_id());
221+ assert_eq!(first.get_submitted_at(), second.get_submitted_at());
222+ assert!(second.get_updated_at() >= first.get_updated_at());
223+ assert!(second.get_text().is_none());
224+ // One row per (homework, user), whatever the re-submit count.
225+ assert_eq!(
226+ HomeworkSubmission::list_for_homework(&homework, &db)
227+ .await
228+ .unwrap()
229+ .len(),
230+ 1
231+ );
232+ }
233+}
src/domain/mod.rsmodified+4 -0
@@ -13,6 +13,10 @@ pub mod exam_answer;
13 pub mod exam_attempt;13 pub mod exam_attempt;
14 pub mod exam_question;14 pub mod exam_question;
15 pub mod exam_result;15 pub mod exam_result;
16+pub mod homework;
17+pub mod homework_file;
18+pub mod homework_result;
19+pub mod homework_submission;
16 pub mod message;20 pub mod message;
17 pub mod note;21 pub mod note;
18 pub mod note_file;22 pub mod note_file;
src/validate.rsmodified+16 -4
@@ -2,10 +2,11 @@
2 //! the value, so an existing newtype is always valid (parse, don't validate).2 //! the value, so an existing newtype is always valid (parse, don't validate).
3 3
4 use crate::constant::{4 use crate::constant::{
5- COURSE_KINDS, EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, MAX_EXAM_DURATION_MS, MAX_MARK,5+ COURSE_KINDS, EXAM_MODES, HOMEWORK_STATUSES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS,
6- MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN,6+ MAX_EXAM_DURATION_MS, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS,
7- MIN_EXAM_DURATION_MS, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS,7+ MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS,
8- MIN_USERNAME_LEN, QUESTION_KINDS, UNLIMITED_EXAM_ATTEMPTS, USERNAME_SEPARATORS,8+ MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, UNLIMITED_EXAM_ATTEMPTS,
9+ USERNAME_SEPARATORS,
9 };10 };
10 use crate::error::ValidationError;11 use crate::error::ValidationError;
11 12
@@ -219,6 +220,17 @@ pub fn validate_exam_mode(value: &str) -> Result<(), ValidationError> {
219 }220 }
220 }221 }
221 222
223+pub fn validate_homework_status(value: &str) -> Result<(), ValidationError> {
224+ if HOMEWORK_STATUSES.contains(&value) {
225+ Ok(())
226+ } else {
227+ Err(ValidationError::Invalid {
228+ field: "status",
229+ reason: "must be one of: done, incomplete, missing",
230+ })
231+ }
232+}
233+
222 pub fn validate_attempt_limit(value: i64) -> Result<(), ValidationError> {234 pub fn validate_attempt_limit(value: i64) -> Result<(), ValidationError> {
223 if value == UNLIMITED_EXAM_ATTEMPTS || (1..=MAX_EXAM_ATTEMPTS).contains(&value) {235 if value == UNLIMITED_EXAM_ATTEMPTS || (1..=MAX_EXAM_ATTEMPTS).contains(&value) {
224 Ok(())236 Ok(())