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

course.rs174 lines, 7.3 KiBHistoryRawDownload
1//! Course workflows: the catalog's CRUD — the template a class section
2//! attaches, with no term, capacity or teacher list of its own any more
3//! (D1/D5/D6: staffing and roster live on the instances,
4//! [`crate::service::class_course`]) — the two gates over a catalog row every
5//! caller of those routes shares ([`can_manage_course`], [`can_view_course`]),
6//! and the delete that collects the image/homework/note-file blob keys before
7//! the guarded cascade sweeps those rows. The queries live in
8//! [`crate::db::course`].
9
10use crate::database::Database;
11use crate::db::course;
12use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
13use crate::domain::role::Role;
14use crate::domain::user::{User, UserId};
15use crate::error::AppError;
16
17/// Mint a catalog course. The catalog is not bound to a term (D1): exams are,
18/// through their instance, and no capacity is stored — the roster counter
19/// lives on the instance and gates nothing.
20pub async fn create(
21 db: &Database,
22 creator: &UserId,
23 title: CourseTitle,
24 description: CourseDescription,
25 kind: CourseKind,
26) -> Result<Course, AppError> {
27 course::create(db, creator, title, description, kind).await
28}
29
30pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> {
31 course::read(db, id).await
32}
33
34/// The catalog the visible list's manager arm serves, optionally narrowed by
35/// the `GET /courses` filters (`kind`, folded `q`) — pushed into the SQL so
36/// listing one kind is not a full-catalog pull.
37pub async fn list_filtered(
38 db: &Database,
39 kind: Option<CourseKind>,
40 q: Option<&str>,
41 taught: Option<bool>,
42) -> Result<Vec<Course>, AppError> {
43 course::list_filtered(db, kind, q, taught).await
44}
45
46pub async fn list_enrolled(
47 db: &Database,
48 user: &UserId,
49 limit: Option<i64>,
50 offset: i64,
51) -> Result<(Vec<Course>, i64), AppError> {
52 course::list_enrolled(db, user, limit, offset).await
53}
54
55pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> {
56 course::list_for_teacher(db, user).await
57}
58
59pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result<Vec<Course>, AppError> {
60 course::list_by_ids(db, ids).await
61}
62
63/// Who may write the **catalog** row (edit it, delete it, write its
64/// subjects): its creator, or anyone `manager` and above — and in every case
65/// only while the caller is *still* `teacher` or above.
66///
67/// The `teacher` floor is enforced here rather than left to the callers: half
68/// of them extract `CurrentUser`, not `RequireTeacher`, so a creator demoted
69/// to `student` or `parent` would otherwise keep catalog rights forever (the
70/// `creator` column is a historical fact and is never swept).
71///
72/// The teacher *assignment* list is gone from this row (D6): who teaches is
73/// per instance now, and being assigned to one grants rights inside it — via
74/// [`super::instance::can_manage_instance`] — never over the catalog.
75///
76/// It lives here, not in the web layer, because the gates over a catalog row
77/// are a service rule the RAG surfaces read too ([`super::rag_scope`] scopes
78/// what a course note's own reader may ask about).
79pub fn can_manage_course(course: &Course, user: &User) -> bool {
80 user.get_role().at_least(Role::Teacher)
81 && (course.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager))
82}
83
84/// Who may read a catalog course (its details, its curriculum subjects):
85/// anyone who can manage it, a teacher assigned to one of its **instances**,
86/// and anyone the course reaches — a student enrolled in any of its instances,
87/// or a member of the course itself. Other teachers and unenrolled students see
88/// nothing.
89///
90/// The assigned-teacher arm is what keeps the catalog honest about the
91/// instance layer: those teachers author homework and exam questions *inside*
92/// the instance (D10 lets them), and every one of those routes needs a
93/// `subject_id` belonging to this very course — so a `403` here would hand them
94/// a picker they cannot fill. At HEAD the assignment list lived on the catalog
95/// row and the arm came for free; after D6 it is read through the instances
96/// they teach ([`list_for_teacher`]).
97pub async fn can_view_course(
98 course: &Course,
99 user: &User,
100 db: &Database,
101) -> Result<bool, AppError> {
102 if can_manage_course(course, user) {
103 return Ok(true);
104 }
105 if user.get_role().at_least(Role::Teacher)
106 && list_for_teacher(db, user.get_id())
107 .await?
108 .iter()
109 .any(|taught| taught.get_id() == course.get_id())
110 {
111 return Ok(true);
112 }
113 crate::db::enrollment::user_is_in_course(db, course.get_id(), user.get_id()).await
114}
115
116/// Only what the request carried is written: an omitted field (`None`) is
117/// not stored at all, so a concurrent PATCH of that field survives.
118pub async fn update(
119 db: &Database,
120 course: Course,
121 title: Option<CourseTitle>,
122 description: Option<CourseDescription>,
123 kind: Option<CourseKind>,
124) -> Result<Course, AppError> {
125 course::update(db, course, title, description, kind).await
126}
127
128/// What [`delete`] did: whether the course went, and the blob keys of the
129/// rows its cascade removed — exactly whose files the web layer may unlink.
130#[derive(Debug)]
131pub struct DeleteOutcome {
132 /// `false` = refused, nothing was written: a class section still teaches
133 /// this course, or a student still holds an individual membership in it.
134 pub deleted: bool,
135 pub image_files: Vec<String>,
136 pub answer_image_files: Vec<String>,
137 pub homework_files: Vec<String>,
138 pub course_note_files: Vec<String>,
139}
140
141/// Delete the course: collect the image/homework/note-file blob keys, then
142/// run the cascading delete — which takes every instance the catalog is taught
143/// in (with everything under them), every individual membership and every
144/// teacher link, all in one guarded transaction.
145///
146/// The old writer leases on the exam-attempt and homework state are gone
147/// with the store that needed them: this cascade is one guarded
148/// transaction whose retry answers a child write that raced it mid-sweep
149/// (`is_retryable_cascade` — a foreign key naming a row the racing write
150/// just landed), so an attempt started or a grade written beside the sweep
151/// is either swept by the re-sent cascade or refused by the very foreign
152/// key it would have orphaned. No lock can out-guard that.
153///
154/// The keys are read before the delete because it takes their rows with it;
155/// a refused delete just drops them unused. Unlinking the blobs stays the
156/// web layer's job — a crash in between strands at worst an unreachable
157/// blob.
158pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, AppError> {
159 let image_files = crate::db::question_image::file_keys_for_course(db, course.get_id()).await?;
160 let answer_image_files =
161 crate::db::answer_image::file_keys_for_course(db, course.get_id()).await?;
162 let homework_files =
163 crate::db::homework_file::file_keys_for_course(db, course.get_id()).await?;
164 let course_note_files =
165 crate::db::course_note_file::file_keys_for_course(db, course.get_id()).await?;
166 let deleted = course::delete(db, course.clone()).await?;
167 Ok(DeleteOutcome {
168 deleted,
169 image_files,
170 answer_image_files,
171 homework_files,
172 course_note_files,
173 })
174}