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

exam.rs1006 lines, 41.7 KiBHistoryRawDownload
1//! Exam workflows: the create that resolves the exam's instance and term,
2//! the PATCH re-derive — the merge (set / clear / keep per field) re-judged
3//! against a fresh read every retry round, and the mode-freeze, re-draft, and
4//! kind gates that guard it — and the delete that collects the image blob keys
5//! inside the cascade's own transaction. The queries live in
6//! [`crate::db::exam`]; the sitting workflows next door in
7//! [`crate::service::exam_attempt`].
8
9use crate::constant::CAS_UPDATE_RETRIES;
10use crate::database::Database;
11use crate::db::exam;
12use crate::db::exam_attempt::any_for_exam;
13use crate::db::exam_audience;
14use crate::db::exam_result;
15use crate::domain::class_course::ClassCourseId;
16use crate::domain::course::CourseId;
17use crate::domain::exam::{
18 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
19 ExamSchedule, ExamTitle, redraft_error,
20};
21use crate::domain::term::TermId;
22use crate::domain::timestamp::Timestamp;
23use crate::domain::user::{User, UserId};
24use crate::error::{AppError, ValidationError};
25use crate::service::exam_attempt::require_open;
26
27pub use crate::db::exam::WindowedListParams;
28
29/// Publish (or draft) an exam on one class×course instance, inside one term.
30///
31/// Two refusals stand in front of the write. The instance's catalog course
32/// must be class-delivered (`kind = course`): a club or supervised study has
33/// no exams — D9 keeps the two membership tiers apart, and an exam on a club
34/// would be a roster nothing enrolls into. And the instance's *year* must
35/// still be open (D8: the term is a grading slice inside the year, so the year
36/// is what the exam's structure belongs to; a term archived inside an open
37/// year does not close exam creation — the archive is a record, not a wall).
38///
39/// The `term` is the term the exam is sat in, and it is required; the store's
40/// create claims it in the same transaction as the row. It must be one of the
41/// *instance's own year's* terms: a term is a grading slice inside a year, so
42/// a term from another year is refused here with a `400` on the field rather
43/// than filed — the write would succeed in the store and misfile the exam in
44/// the report card of a year it is not taught in.
45#[expect(
46 clippy::too_many_arguments,
47 reason = "mirrors the sibling entities' create(field, field, ..) shape"
48)]
49pub async fn create(
50 db: &Database,
51 creator: &UserId,
52 class_course: &ClassCourseId,
53 term: &TermId,
54 title: ExamTitle,
55 description: ExamDescription,
56 kind: ExamKind,
57 schedule: ExamSchedule,
58 max_attempts: ExamAttemptLimit,
59 allow_rejoin: bool,
60 allow_review: bool,
61 draft: bool,
62) -> Result<Exam, AppError> {
63 let Some(instance) = crate::db::class_course::read(db, class_course).await? else {
64 return Err(AppError::NotFound);
65 };
66 let Some(course) = crate::db::course::read(db, instance.get_course()).await? else {
67 return Err(AppError::Internal(
68 "the instance references a missing course".into(),
69 ));
70 };
71 if !course.get_kind().is_class_delivered() {
72 return Err(AppError::Validation(ValidationError::Invalid {
73 field: "course",
74 reason: "only a ders can carry exams — a club or etüt is joined, not sat",
75 }));
76 }
77 // The term must be one of the instance's own year's: the year is the
78 // scope a report card is computed over (and a term is a grading slice
79 // *inside* it), so an exam filed under another year's term would be
80 // counted into a report whose terms it does not belong to — invisible to
81 // the year it is actually taught in and foreign to the one it names. The
82 // instance's year is its section's, read through the one seam that
83 // resolves it.
84 let Some(term_row) = crate::db::term::read(db, term).await? else {
85 return Err(crate::domain::term::gone_error());
86 };
87 let instance_year = crate::service::class_course::year_of(db, class_course).await?;
88 if instance_year != Some(*term_row.get_year()) {
89 return Err(AppError::Validation(ValidationError::Invalid {
90 field: "term",
91 reason: "the term belongs to another academic year than this class",
92 }));
93 }
94 crate::service::class_course::require_open(db, class_course).await?;
95 exam::create(
96 db,
97 creator,
98 class_course,
99 term,
100 title,
101 description,
102 kind,
103 schedule,
104 max_attempts,
105 allow_rejoin,
106 allow_review,
107 draft,
108 )
109 .await
110}
111
112/// The exam row, for callers that only inspect it — the web layer's gates
113/// read through here.
114pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError> {
115 exam::read(db, id).await
116}
117
118/// The `GET /exams` list. `visible`/`managed` are the non-manager read (the
119/// exams of the caller's visible instances, a draft only where they manage
120/// the owner instance); both `None` is the manager+ whole-table read. The
121/// schedule window, the visibility, the draft rule, the page, and the count
122/// share one SQL `WHERE` — see [`exam::list_windowed`].
123pub async fn list_windowed(
124 db: &Database,
125 visible: Option<&[ClassCourseId]>,
126 managed: Option<&[ClassCourseId]>,
127 params: WindowedListParams,
128) -> Result<(Vec<Exam>, i64), AppError> {
129 exam::list_windowed(db, visible, managed, params).await
130}
131
132/// One instance's exams, newest first — the read behind
133/// `GET /instances/{id}/exams`.
134pub async fn list_for_class_course(
135 db: &Database,
136 class_course: &ClassCourseId,
137) -> Result<Vec<Exam>, AppError> {
138 exam::list_for_class_course(db, class_course).await
139}
140
141/// Every exam of every catalog course in `courses` (one query) — the catalog
142/// as one user sees it, across the instances those courses are taught in.
143pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec<Exam>, AppError> {
144 exam::list_for_courses(db, courses).await
145}
146
147// ---- audience: the shared exam (D2) ---------------------------------------
148
149/// The exam, or the `404` a gone id deserves — and the caller's right to act
150/// on the exam's **owner** instance, or the `403` D10 answers
151/// ([`crate::service::class_course::ensure_instance_teacher`]: manager+, an
152/// assigned teacher, or the section's homeroom teacher).
153///
154/// The audience routes never move the exam, they announce it, so the gate is
155/// the owner's and not the target's: the section that runs the exam decides
156/// who else it is addressed to, and a teacher of the receiving section has no
157/// say in the announcement.
158async fn managed_exam(db: &Database, user: &User, id: &ExamId) -> Result<Exam, AppError> {
159 let exam = exam::read(db, id).await?.ok_or(AppError::NotFound)?;
160 crate::service::class_course::ensure_instance_teacher(db, user, exam.get_class_course())
161 .await?;
162 Ok(exam)
163}
164
165/// Announce `exam` to another instance — the shared-exam write (D2).
166///
167/// The exam stays owned by the instance it was created on; an audience row is
168/// what makes a second (third, …) class section sit the same sitting and carry the
169/// mark in its own marks and report card ([`crate::db::exam_result`] reads
170/// through `exam_audience`). Three rules keep the announcement from filing
171/// academic work where it cannot be graded:
172///
173/// - the target must teach the **same catalog course** — a mark on an algebra
174/// exam standing in a geometry instance's report is a subject that report
175/// never taught;
176/// - both instances must sit under the **same academic year** — a report card
177/// is computed over one year, so an announcement across years would file the
178/// mark into a year the exam is not taught in (the rule [`create`] already
179/// applies to the term);
180/// - the target may not be the owner itself: the owner's audience row always
181/// exists, and the owner cannot be withdrawn (see [`remove_audience`]) —
182/// deleting the exam is what ends it.
183///
184/// The target's year must still be open ([`crate::service::class_course::require_open`]):
185/// announcing into an archived year is a write into a read-only year like
186/// every other one. A repeat announcement is success, not a conflict — the
187/// store treats the existing row as a no-op — and the answer is the audience
188/// the exam holds after the call.
189///
190/// Every refusal is coded: `404` for a gone exam or target instance, `403`
191/// for a caller with no right over the owner, `400` for the three shape
192/// rules, and the archived year's `409`.
193pub async fn add_audience(
194 db: &Database,
195 user: &User,
196 id: &ExamId,
197 target: &ClassCourseId,
198) -> Result<Vec<exam_audience::Audience>, AppError> {
199 let exam = managed_exam(db, user, id).await?;
200 let owner = crate::db::class_course::read(db, exam.get_class_course())
201 .await?
202 // A foreign key names the owner, so only a concurrent detach — which
203 // sweeps the exam in the same transaction — could have taken it;
204 // either way the exam is gone, and 404 is that answer.
205 .ok_or(AppError::NotFound)?;
206 let target_row = crate::db::class_course::read(db, target)
207 .await?
208 .ok_or(AppError::NotFound)?;
209 if target_row.get_id() == owner.get_id() {
210 return Err(AppError::Validation(ValidationError::Invalid {
211 field: "instance",
212 reason: "this instance owns the exam — an audience is another instance, and \
213 deleting the exam is what ends the owner's",
214 }));
215 }
216 if target_row.get_course() != owner.get_course() {
217 return Err(AppError::Validation(ValidationError::Invalid {
218 field: "instance",
219 reason: "the instance teaches another course than the exam's",
220 }));
221 }
222 let owner_year = crate::service::class_course::year_of(db, owner.get_id()).await?;
223 if owner_year != crate::service::class_course::year_of(db, target).await? {
224 return Err(AppError::Validation(ValidationError::Invalid {
225 field: "instance",
226 reason: "the instance belongs to another academic year than the exam's",
227 }));
228 }
229 crate::service::class_course::require_open(db, target).await?;
230 exam_audience::add(db, id, target).await?;
231 list_audience(db, id).await
232}
233
234/// Withdraw `exam` from one instance's audience. The same **gate** as
235/// [`add_audience`] (management rights over the exam's owner instance), and
236/// none of its shape rules re-run: the row was validated when it was
237/// announced, and taking it back is cleanup — a stale announcement (an
238/// instance whose section moved years, say) can always be withdrawn.
239///
240/// One pair is the exception, and it is the route's whole safety property:
241/// the **owner's** row is not withdrawable. Removing it would leave an exam
242/// belonging to no instance — every audience read is the `exam_audience`
243/// join, so the exam, its marks and its attempts would vanish from every
244/// report while their rows stood — which is why the owner pair is a `400`
245/// here and not a delete.
246///
247/// A pair that holds no audience row is the `404`
248/// [`crate::db::exam_audience::remove`]'s boolean carries — never a silent
249/// success. The exam's own year must still be open, like every other write
250/// against the exam's structure ([`update`] and [`delete`]): withdrawing from
251/// an archived year's shared exam is a `409`, not a silent edit of a past
252/// year's record. The answer is the audience the exam holds after the call.
253pub async fn remove_audience(
254 db: &Database,
255 user: &User,
256 id: &ExamId,
257 target: &ClassCourseId,
258) -> Result<Vec<exam_audience::Audience>, AppError> {
259 let exam = managed_exam(db, user, id).await?;
260 if exam.get_class_course() == target {
261 return Err(AppError::Validation(ValidationError::Invalid {
262 field: "instance",
263 reason: "the owner instance is not an audience — an exam cannot lose the \
264 instance it belongs to; delete the exam instead",
265 }));
266 }
267 require_open(db, &exam).await?;
268 if !exam_audience::remove(db, id, target).await? {
269 return Err(AppError::NotFound);
270 }
271 list_audience(db, id).await
272}
273
274/// The audience of one exam: the instances it is announced to, its owner
275/// included — the read behind `GET /exams/{id}/audience`. Read-only, so the
276/// web layer gates it with the exam's own view rule.
277pub async fn list_audience(
278 db: &Database,
279 id: &ExamId,
280) -> Result<Vec<exam_audience::Audience>, AppError> {
281 exam_audience::list_for_exam(db, id).await
282}
283
284/// Whether `user` is enrolled in any instance `exam` is addressed to — its
285/// owner or an announced sibling (D2).
286///
287/// This is the enrollment predicate every *student* door at an exam asks
288/// (sitting, answering, grading), and announcing an exam is what moves it:
289/// the addressed sections' students sit and are graded at their own instance.
290/// An exam nobody was announced to answers exactly what the owner-only check
291/// these doors used to run answered.
292pub async fn enrolled_anywhere(
293 db: &Database,
294 exam: &Exam,
295 user: &UserId,
296) -> Result<bool, AppError> {
297 exam_audience::enrolled(db, exam.get_id(), user).await
298}
299
300/// A `403` unless [`enrolled_anywhere`] — the refusal the sit paths answer,
301/// kept byte-for-byte from the owner-only check it replaces.
302pub async fn ensure_enrolled_anywhere(
303 db: &Database,
304 exam: &Exam,
305 user: &UserId,
306) -> Result<(), AppError> {
307 if enrolled_anywhere(db, exam, user).await? {
308 return Ok(());
309 }
310 Err(AppError::Forbidden(
311 "you are not enrolled in this exam's course",
312 ))
313}
314
315/// A `PATCH /exams/{id}` request after field validation: every value the
316/// request *set* is already validated (title, description, mode, duration,
317/// and attempt limit by their newtypes; the kind against the school's
318/// current list; newly set window ends by the web layer's no-past grace).
319/// What is *kept* — and whether the merged whole is a legal schedule — are
320/// the update's own decisions, re-derived against a fresh read every retry
321/// round, so they live here and not in the web layer. A `None` field keeps
322/// the stored value; the `Option<Option<..>>` schedule fields carry the
323/// web DTO's set-or-clear spelling (`Some(None)` = explicit `null`).
324pub struct ExamPatch {
325 pub title: Option<ExamTitle>,
326 pub description: Option<ExamDescription>,
327 pub kind: Option<ExamKind>,
328 pub mode: Option<Option<ExamMode>>,
329 pub starts_at: Option<Option<Timestamp>>,
330 pub ends_at: Option<Option<Timestamp>>,
331 pub duration_ms: Option<Option<ExamDuration>>,
332 pub max_attempts: Option<ExamAttemptLimit>,
333 pub allow_rejoin: Option<bool>,
334 pub allow_review: Option<bool>,
335 pub draft: Option<bool>,
336}
337
338/// Re-derive and save the exam: merge the patch over a fresh read, re-validate
339/// the schedule as a unit, judge every business gate against that same row,
340/// and land the whole merge with the compare-and-set — retried while the row
341/// keeps moving under the snapshot.
342///
343/// The mode gate below reads `exam_attempt`, and the sitting create's
344/// transaction re-judges the sittable gates on the locked exam row
345/// ([`crate::db::exam_attempt::guard_start`]), so a first sitting still
346/// cannot land on an exam whose mode this PATCH is flipping — the store
347/// decides, not a process lock.
348///
349/// It buys nothing against grading, which is a reader too: the re-draft gate
350/// is therefore enforced inside the update's own transaction
351/// ([`exam::update_if_unchanged`]), where the store decides it. The gate
352/// below stays as the pre-flight — same error, one round trip earlier.
353/// Concurrent PATCHes of this exam no longer queue behind each other either:
354/// the lost update they used to cause is refused by the compare-and-set.
355pub async fn update(db: &Database, id: &ExamId, patch: &ExamPatch) -> Result<Exam, AppError> {
356 let mut left = CAS_UPDATE_RETRIES;
357 loop {
358 let current = exam::read(db, id).await?.ok_or(AppError::NotFound)?;
359 require_open(db, &current).await?;
360
361 let title = patch
362 .title
363 .clone()
364 .unwrap_or_else(|| current.get_title().clone());
365 let description = patch
366 .description
367 .clone()
368 .unwrap_or_else(|| current.get_description().clone());
369 let kind = patch
370 .kind
371 .clone()
372 .unwrap_or_else(|| current.get_kind().clone());
373
374 // Merge the schedule (set / clear / keep per field), then re-validate it
375 // as a unit — a PATCH can't leave a half-schedule behind. Only values this
376 // request sets are held to the no-past rule: kept ones may legitimately be
377 // past (a running exam's `starts_at`), and rechecking them would block
378 // unrelated edits.
379 let mode = match &patch.mode {
380 Some(update) => update.clone(),
381 None => current.get_mode().cloned(),
382 };
383 let starts_at = match patch.starts_at {
384 Some(update) => update,
385 None => current.get_starts_at(),
386 };
387 let ends_at = match patch.ends_at {
388 Some(update) => update,
389 None => current.get_ends_at(),
390 };
391 let duration_ms = match patch.duration_ms {
392 Some(update) => update,
393 None => current.get_duration_ms(),
394 };
395 let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?;
396 let max_attempts = patch
397 .max_attempts
398 .unwrap_or_else(|| current.get_max_attempts());
399 let allow_rejoin = patch
400 .allow_rejoin
401 .unwrap_or_else(|| current.get_allow_rejoin());
402 let allow_review = patch
403 .allow_review
404 .unwrap_or_else(|| current.get_allow_review());
405 let draft = patch.draft.unwrap_or(current.is_draft());
406
407 // Switching sync <-> async <-> open (or back to unscheduled) would
408 // silently rewrite the deadline rules under students who already sat
409 // down; extending times, the attempt limit, and the rejoin door are the
410 // supported live adjustments instead. The sitting create's own
411 // transaction re-judges the mode gate on the locked row, so a first
412 // attempt can't land in the gap and leave a sat exam's mode flipped
413 // under it.
414 let mode_changed =
415 schedule.get_mode().map(ExamMode::as_str) != current.get_mode().map(ExamMode::as_str);
416 if mode_changed && any_for_exam(db, current.get_id()).await? {
417 return Err(AppError::Conflict(
418 "cannot change the exam mode after attempts have started",
419 ));
420 }
421 // Re-drafting hides the exam — never out from under a student who
422 // already sat it or holds a mark on it. Pre-flight only: the write's own
423 // transaction re-makes this check and answers with the same error, so a
424 // grade landing after this read still cannot leave a mark on a draft.
425 if draft && !current.is_draft() {
426 let sat = any_for_exam(db, current.get_id()).await?;
427 let graded = !exam_result::list_for_exam(db, current.get_id())
428 .await?
429 .is_empty();
430 if sat || graded {
431 return Err(redraft_error());
432 }
433 }
434
435 // A graded exam keeps its kind. Moving it re-weights every mark it
436 // already carries — the same silent re-weighting the settings' removal
437 // guard refuses — and it would strand those marks' references on the
438 // kind they were counted under, freeing the kind the exam now claims to
439 // be. Marks are counted on the exam row, and the save below pins
440 // that counter — reading it inside its own transaction — so a grade
441 // landing between this read and the write refuses the save (the
442 // loop then re-reads and answers the 409 below).
443 if kind.as_str() != current.get_kind().as_str()
444 && exam::result_count(db, current.get_id()).await? > 0
445 {
446 return Err(AppError::Conflict(
447 "cannot change the kind of an exam that already has marks",
448 ));
449 }
450
451 if let Some(updated) = exam::update_if_unchanged(
452 db,
453 current,
454 title,
455 description,
456 kind,
457 schedule,
458 max_attempts,
459 allow_rejoin,
460 allow_review,
461 draft,
462 )
463 .await?
464 {
465 return Ok(updated);
466 }
467 // The row moved under the snapshot every gate above judged: re-read and
468 // re-merge, so both edits land instead of the later reverting the earlier.
469 left -= 1;
470 if left == 0 {
471 return Err(AppError::Conflict(
472 "the exam kept changing underneath this update — try again",
473 ));
474 }
475 }
476}
477
478/// What [`delete`] did: the blob keys of the image rows the cascade removed —
479/// exactly whose files the web layer may unlink.
480#[derive(Debug)]
481pub struct DeleteOutcome {
482 pub image_files: Vec<String>,
483 pub answer_image_files: Vec<String>,
484}
485
486/// Delete the exam: collect the question/answer image blob keys, then run the
487/// cascading delete.
488///
489/// The store replaced the writer lease this delete used to hold across the
490/// whole cascade, blob names included: the delete's transaction takes the
491/// exam row `FOR UPDATE` first, and every child writer that matters locks
492/// the same row first (a sitting create's guard, the freeze gate, an answer
493/// save ahead of its upsert). So a start or a save either finishes before
494/// the sweep — which then takes its row too — or finds no exam and is a
495/// `404`. Left orphaned, an attempt kept a sitting on the student's
496/// lifetime counter and could mint a badge — awards are add-only and never
497/// revoked — for an exam that never existed.
498///
499/// It spans the blob names too: they are collected *inside* the deleting
500/// transaction, under the lock, so an image row written after an
501/// out-of-transaction snapshot cannot strand its bytes on disk even though
502/// the row itself is now refused.
503pub async fn delete(db: &Database, target: &Exam) -> Result<DeleteOutcome, AppError> {
504 require_open(db, target).await?;
505 // Rows go first (the delete cascades them), blobs after — a crash in
506 // between strands at worst an unreachable blob.
507 let deleted = exam::delete(db, target.clone()).await?;
508 Ok(DeleteOutcome {
509 image_files: deleted.question_image_files,
510 answer_image_files: deleted.answer_image_files,
511 })
512}
513
514#[cfg(test)]
515mod tests {
516 use super::*;
517 use crate::domain::academic_year::AcademicYearId;
518 use crate::domain::class_course::ClassCourse;
519 use crate::domain::class_group::ClassName;
520 use crate::domain::role::Role;
521 use crate::domain::settings::Settings;
522 use crate::domain::user::Username;
523
524 /// A real account at a role — the announcement gate judges the live row,
525 /// so a raw fixture id would not do.
526 async fn staff(db: &Database, username: &str, role: Role) -> User {
527 let account = crate::db::user::create(db, Username::try_new(username).unwrap(), None)
528 .await
529 .unwrap();
530 crate::service::user::set_role(db, account.get_id(), role)
531 .await
532 .unwrap();
533 crate::db::user::read(db, account.get_id())
534 .await
535 .unwrap()
536 .unwrap()
537 }
538
539 /// An instance of `course` inside a fresh class section of `year` — one
540 /// side of an announcement.
541 async fn instance_in(
542 db: &Database,
543 manager: &UserId,
544 name: &str,
545 course: &CourseId,
546 year: Option<&AcademicYearId>,
547 ) -> ClassCourse {
548 let class = crate::db::class_group::create(
549 db,
550 manager,
551 ClassName::try_new(name).unwrap(),
552 crate::domain::grade::GradeLevel::new(9).unwrap(),
553 year.cloned(),
554 None,
555 )
556 .await
557 .unwrap();
558 crate::service::class_course::attach(db, class.get_id(), course, manager)
559 .await
560 .unwrap()
561 }
562
563 /// A published, unscheduled exam on `instance` — the parent an audience
564 /// row hangs off.
565 async fn exam_on(db: &Database, instance: &ClassCourse) -> Exam {
566 let creator = crate::db::class_member::tests::fixture_user(db, "audience-author").await;
567 let term = crate::db::term::a_test_term(db).await;
568 let allowed = Settings::defaults().get_exam_kinds().to_vec();
569 crate::db::exam::create(
570 db,
571 &creator,
572 instance.get_id(),
573 &term,
574 ExamTitle::try_new("1. Yazılı").unwrap(),
575 ExamDescription::try_new("").unwrap(),
576 ExamKind::try_new("yazili", &allowed).unwrap(),
577 ExamSchedule::try_new(None, None, None, None).unwrap(),
578 ExamAttemptLimit::try_new(1).unwrap(),
579 true,
580 false,
581 false,
582 )
583 .await
584 .unwrap()
585 }
586
587 /// The announcement's shape rules: same catalog course, same academic
588 /// year, another instance — each violation a coded `400`, the pair that
589 /// satisfies all three a row the audience read (and so the marks reports)
590 /// sees, and a repeat a no-op rather than a conflict.
591 #[tokio::test]
592 async fn an_announcement_needs_the_same_course_and_year() {
593 let (db, _leases) = crate::database::init_test_db().await;
594 let manager = staff(&db, "audience-mudur", Role::Manager).await;
595 let algebra = crate::db::class_member::tests::a_course("algebra", &db).await;
596 let geometry = crate::db::class_member::tests::a_course("geometry", &db).await;
597 let year = crate::db::academic_year::a_test_year(&db).await;
598 let other_year = crate::db::academic_year::a_test_year(&db).await;
599
600 let owner = instance_in(&db, manager.get_id(), "5-A", &algebra, Some(&year)).await;
601 let sibling = instance_in(&db, manager.get_id(), "5-B", &algebra, Some(&year)).await;
602 let wrong_course = instance_in(&db, manager.get_id(), "5-C", &geometry, Some(&year)).await;
603 let wrong_year =
604 instance_in(&db, manager.get_id(), "6-A", &algebra, Some(&other_year)).await;
605 let exam = exam_on(&db, &owner).await;
606
607 let audience = add_audience(&db, &manager, exam.get_id(), sibling.get_id())
608 .await
609 .unwrap();
610 assert_eq!(audience.len(), 2, "owner + announcement");
611 assert_eq!(
612 audience[0].get_instance(),
613 owner.get_id(),
614 "the owner stands first — announcement order is creation order"
615 );
616 assert_eq!(audience[1].get_instance(), sibling.get_id());
617 assert_eq!(audience[1].get_class(), sibling.get_class());
618 assert_eq!(audience[1].get_course(), &algebra);
619 // The sibling's own exam list carries it — the join the marks reports
620 // and the instance page read.
621 assert_eq!(
622 list_for_class_course(&db, sibling.get_id())
623 .await
624 .unwrap()
625 .len(),
626 1,
627 "the announcement is one exam, addressed here"
628 );
629
630 for (bad, why) in [
631 (&wrong_course, "another course"),
632 (&wrong_year, "another year"),
633 ] {
634 let refused = add_audience(&db, &manager, exam.get_id(), bad.get_id()).await;
635 assert!(
636 matches!(refused, Err(AppError::Validation(_))),
637 "{why} must be a coded 400: {refused:?}"
638 );
639 }
640 let owned = add_audience(&db, &manager, exam.get_id(), owner.get_id()).await;
641 assert!(
642 matches!(owned, Err(AppError::Validation(_))),
643 "the owner is not an audience: {owned:?}"
644 );
645 let ghost = ClassCourseId::generate();
646 assert!(
647 matches!(
648 add_audience(&db, &manager, exam.get_id(), &ghost).await,
649 Err(AppError::NotFound)
650 ),
651 "a minted instance id names nothing"
652 );
653 assert!(matches!(
654 add_audience(&db, &manager, &ExamId::generate(), sibling.get_id()).await,
655 Err(AppError::NotFound)
656 ));
657
658 add_audience(&db, &manager, exam.get_id(), sibling.get_id())
659 .await
660 .unwrap();
661 assert_eq!(
662 exam_audience::list_for_exam(&db, exam.get_id())
663 .await
664 .unwrap()
665 .len(),
666 2,
667 "a repeat announcement is a no-op, not a second row"
668 );
669 }
670
671 /// The gate is the **owner** instance's: its assigned teacher and a
672 /// manager+ may announce and withdraw; the target instance's own teacher
673 /// may not — running the receiving section is not running the exam — and
674 /// a student may not either.
675 #[tokio::test]
676 async fn an_announcement_is_gated_on_the_owner_instance() {
677 let (db, _leases) = crate::database::init_test_db().await;
678 let manager = staff(&db, "audience-mudur-2", Role::Manager).await;
679 let owner_teacher = staff(&db, "audience-ogretmen-a", Role::Teacher).await;
680 let target_teacher = staff(&db, "audience-ogretmen-b", Role::Teacher).await;
681 let student = staff(&db, "audience-ogrenci", Role::Student).await;
682 let algebra = crate::db::class_member::tests::a_course("algebra", &db).await;
683 let owner = instance_in(&db, manager.get_id(), "7-A", &algebra, None).await;
684 let target = instance_in(&db, manager.get_id(), "7-B", &algebra, None).await;
685 crate::service::class_course::assign_teacher(
686 &db,
687 owner.get_id(),
688 owner_teacher.get_id(),
689 manager.get_id(),
690 )
691 .await
692 .unwrap();
693 crate::service::class_course::assign_teacher(
694 &db,
695 target.get_id(),
696 target_teacher.get_id(),
697 manager.get_id(),
698 )
699 .await
700 .unwrap();
701 let exam = exam_on(&db, &owner).await;
702
703 assert!(
704 add_audience(&db, &owner_teacher, exam.get_id(), target.get_id())
705 .await
706 .is_ok(),
707 "an assigned teacher of the owner instance announces"
708 );
709 assert!(
710 remove_audience(&db, &owner_teacher, exam.get_id(), target.get_id())
711 .await
712 .is_ok(),
713 "…and withdraws"
714 );
715 for (user, who) in [
716 (&target_teacher, "the target's teacher"),
717 (&student, "a student"),
718 ] {
719 let refused = add_audience(&db, user, exam.get_id(), target.get_id()).await;
720 assert!(
721 matches!(refused, Err(AppError::Forbidden(_))),
722 "{who} must be a 403: {refused:?}"
723 );
724 }
725 }
726
727 /// Withdrawal: the owner's own pair is a coded `400` (an exam cannot lose
728 /// the instance it belongs to), a pair holding no row is a `404`, and the
729 /// row the instance's read joins on is gone afterwards.
730 #[tokio::test]
731 async fn withdrawing_an_audience_leaves_the_owner_alone() {
732 let (db, _leases) = crate::database::init_test_db().await;
733 let manager = staff(&db, "audience-mudur-3", Role::Manager).await;
734 let algebra = crate::db::class_member::tests::a_course("algebra", &db).await;
735 let owner = instance_in(&db, manager.get_id(), "8-A", &algebra, None).await;
736 let target = instance_in(&db, manager.get_id(), "8-B", &algebra, None).await;
737 let exam = exam_on(&db, &owner).await;
738 add_audience(&db, &manager, exam.get_id(), target.get_id())
739 .await
740 .unwrap();
741
742 let audience = remove_audience(&db, &manager, exam.get_id(), target.get_id())
743 .await
744 .unwrap();
745 assert_eq!(audience.len(), 1);
746 assert_eq!(audience[0].get_instance(), owner.get_id());
747 assert!(
748 list_for_class_course(&db, target.get_id())
749 .await
750 .unwrap()
751 .is_empty(),
752 "the withdrawn instance no longer carries the exam"
753 );
754
755 assert!(
756 matches!(
757 remove_audience(&db, &manager, exam.get_id(), target.get_id()).await,
758 Err(AppError::NotFound)
759 ),
760 "a pair holding no row is a 404, never a silent success"
761 );
762 let owner_pair = remove_audience(&db, &manager, exam.get_id(), owner.get_id()).await;
763 assert!(
764 matches!(owner_pair, Err(AppError::Validation(_))),
765 "the owner pair is refused: {owner_pair:?}"
766 );
767 assert_eq!(
768 exam_audience::list_for_exam(&db, exam.get_id())
769 .await
770 .unwrap()
771 .len(),
772 1,
773 "the owner's row stands"
774 );
775 }
776
777 /// The archived-year posture of both routes: announcing into an archived
778 /// year and withdrawing from one are the coded `409` every other write
779 /// against the year answers, and neither writes — an announcement row
780 /// predating the archive is no loophole for more of them.
781 #[tokio::test]
782 async fn an_archived_year_refuses_the_announcement_and_the_withdrawal() {
783 let (db, _leases) = crate::database::init_test_db().await;
784 let manager = staff(&db, "audience-mudur-4", Role::Manager).await;
785 let algebra = crate::db::class_member::tests::a_course("algebra", &db).await;
786 let year = crate::db::academic_year::a_test_year(&db).await;
787 let owner = instance_in(&db, manager.get_id(), "9-A", &algebra, Some(&year)).await;
788 let announced = instance_in(&db, manager.get_id(), "9-B", &algebra, Some(&year)).await;
789 let later = instance_in(&db, manager.get_id(), "9-C", &algebra, Some(&year)).await;
790 let exam = exam_on(&db, &owner).await;
791 add_audience(&db, &manager, exam.get_id(), announced.get_id())
792 .await
793 .unwrap();
794
795 crate::service::academic_year::archive(&db, &year)
796 .await
797 .unwrap();
798
799 for (result, route) in [
800 (
801 add_audience(&db, &manager, exam.get_id(), later.get_id()).await,
802 "the announcement",
803 ),
804 (
805 remove_audience(&db, &manager, exam.get_id(), announced.get_id()).await,
806 "the withdrawal",
807 ),
808 ] {
809 assert!(
810 matches!(
811 result,
812 Err(AppError::ConflictCoded { code, .. }) if code == "academic_year_archived"
813 ),
814 "{route} into an archived year must be the coded 409: {result:?}"
815 );
816 }
817 assert_eq!(
818 exam_audience::list_for_exam(&db, exam.get_id())
819 .await
820 .unwrap()
821 .len(),
822 2,
823 "neither refusal wrote"
824 );
825 }
826
827 /// An exam with full control over the schedule and the draft flag — the
828 /// window and draft-rule tests need shapes [`exam_on`] does not make.
829 async fn exam_shaped(
830 db: &Database,
831 instance: &ClassCourse,
832 schedule: ExamSchedule,
833 draft: bool,
834 title: &str,
835 ) -> Exam {
836 let creator = crate::db::class_member::tests::fixture_user(db, "window-author").await;
837 let term = crate::db::term::a_test_term(db).await;
838 let allowed = Settings::defaults().get_exam_kinds().to_vec();
839 crate::db::exam::create(
840 db,
841 &creator,
842 instance.get_id(),
843 &term,
844 ExamTitle::try_new(title).unwrap(),
845 ExamDescription::try_new("").unwrap(),
846 ExamKind::try_new("yazili", &allowed).unwrap(),
847 schedule,
848 ExamAttemptLimit::try_new(1).unwrap(),
849 true,
850 false,
851 draft,
852 )
853 .await
854 .unwrap()
855 }
856
857 /// `list_windowed` in SQL must answer exactly what the old
858 /// list-and-retain read answered: visibility (any addressed instance),
859 /// the draft rule (only where the caller manages the owner instance),
860 /// the schedule window (schedule-less rows out, ascending order), and a
861 /// `total` that is the filtered count even when the page is short.
862 #[tokio::test]
863 async fn the_exam_list_window_keeps_visibility_and_draft_rules() {
864 let (db, _leases) = crate::database::init_test_db().await;
865 let manager = staff(&db, "window-mudur", Role::Manager).await;
866 let algebra = crate::db::class_member::tests::a_course("algebra", &db).await;
867 let geometry = crate::db::class_member::tests::a_course("geometry", &db).await;
868 let a = instance_in(&db, manager.get_id(), "8-A", &algebra, None).await;
869 let b = instance_in(&db, manager.get_id(), "8-B", &geometry, None).await;
870
871 let now = Timestamp::now().as_millis();
872 let sync =
873 |starts_at: i64| -> ExamSchedule {
874 ExamSchedule::try_new(
875 Some(ExamMode::try_new("sync").unwrap()),
876 Some(Timestamp::from_millis(starts_at)),
877 Some(Timestamp::from_millis(starts_at + 3_600_000)),
878 None,
879 )
880 .unwrap()
881 };
882 // On A: a scheduled exam ahead, a scheduled draft ahead, a
883 // window-less (`sync`-less, so no-mode) published exam, and one that
884 // already ran. On B: a draft of *another* instance.
885 let ahead = exam_shaped(&db, &a, sync(now + 3_600_000), false, "ahead").await;
886 let ahead_draft = exam_shaped(&db, &a, sync(now + 3_600_000), true, "ahead-draft").await;
887 let open = exam_shaped(&db, &a, ExamSchedule::default(), false, "open").await;
888 let ran = exam_shaped(&db, &a, sync(now - 3_600_000), false, "ran").await;
889 let other_draft = exam_shaped(&db, &b, sync(now + 3_600_000), true, "other-draft").await;
890
891 // Manager+: the whole table, newest first.
892 let (rows, total) = list_windowed(&db, None, None, WindowedListParams::default())
893 .await
894 .unwrap();
895 assert_eq!(total, 5);
896 let listed: Vec<_> = rows.iter().map(|exam| exam.get_id()).cloned().collect();
897 assert_eq!(
898 listed,
899 [&other_draft, &ran, &open, &ahead_draft, &ahead]
900 .into_iter()
901 .map(|exam| exam.get_id().clone())
902 .collect::<Vec<_>>()
903 );
904
905 // Manager+ WITH a window: the window predicates must name the
906 // unaliased `exam` (the audience join only exists on the other
907 // branch). This exact call 500'd with "missing FROM-clause entry for
908 // table e" while the predicates were `e.`-qualified.
909 let (rows, total) = list_windowed(
910 &db,
911 None,
912 None,
913 WindowedListParams {
914 ends_after: Some(now),
915 ..Default::default()
916 },
917 )
918 .await
919 .unwrap();
920 assert_eq!(total, 3);
921 let listed: Vec<_> = rows.iter().map(|exam| exam.get_id()).cloned().collect();
922 assert_eq!(
923 listed,
924 [&ahead, &ahead_draft, &other_draft]
925 .into_iter()
926 .map(|exam| exam.get_id().clone())
927 .collect::<Vec<_>>()
928 );
929 let (_, total) = list_windowed(
930 &db,
931 None,
932 None,
933 WindowedListParams {
934 starts_before: Some(now + 45 * 60_000),
935 ..Default::default()
936 },
937 )
938 .await
939 .unwrap();
940 assert_eq!(total, 1, "starts_before keeps only the already-run exam");
941
942 // A viewer of A who manages nothing: A's published exams only — both
943 // drafts (A's own and the other instance's) stay hidden.
944 let visible = vec![a.get_id().clone()];
945 let nothing: Vec<ClassCourseId> = Vec::new();
946 let (rows, total) =
947 list_windowed(&db, Some(&visible), Some(&nothing), WindowedListParams::default())
948 .await
949 .unwrap();
950 assert_eq!(total, 3);
951 assert!(rows.iter().all(|exam| !exam.is_draft()));
952
953 // A's teacher manages A: sees A's draft — and still not B's.
954 let manages_a = vec![a.get_id().clone()];
955 let (rows, total) =
956 list_windowed(&db, Some(&visible), Some(&manages_a), WindowedListParams::default())
957 .await
958 .unwrap();
959 assert_eq!(total, 4);
960 assert!(rows.iter().any(|exam| exam.get_id() == ahead_draft.get_id()));
961 assert!(!rows.iter().any(|exam| exam.get_id() == other_draft.get_id()));
962
963 // The window rides the same WHERE: `ends_after=now` keeps the
964 // scheduled ahead pair (the draft included — a draft is visible where
965 // it is visible), drops the open exam (no schedule) and the one that
966 // ran, and flips the order to schedule ascending, id tie-break.
967 let (rows, total) = list_windowed(
968 &db,
969 Some(&visible),
970 Some(&manages_a),
971 WindowedListParams {
972 ends_after: Some(now),
973 ..Default::default()
974 },
975 )
976 .await
977 .unwrap();
978 assert_eq!(total, 2);
979 let listed: Vec<_> = rows.iter().map(|exam| exam.get_id()).cloned().collect();
980 assert_eq!(listed, vec![ahead.get_id().clone(), ahead_draft.get_id().clone()]);
981
982 // A short page of the filtered set still reports the filtered total.
983 let (rows, total) = list_windowed(
984 &db,
985 Some(&visible),
986 Some(&manages_a),
987 WindowedListParams {
988 ends_after: Some(now),
989 limit: Some(1),
990 ..Default::default()
991 },
992 )
993 .await
994 .unwrap();
995 assert_eq!((rows.len(), total), (1, 2));
996
997 // A viewer of B manages nothing, and B's only exam is a draft: the
998 // draft wall leaves them an empty page, not an error.
999 let sees_b = vec![b.get_id().clone()];
1000 let (rows, total) =
1001 list_windowed(&db, Some(&sees_b), Some(&nothing), WindowedListParams::default())
1002 .await
1003 .unwrap();
1004 assert!(rows.is_empty() && total == 0);
1005 }
1006}