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

audience.rs207 lines, 9.5 KiBHistoryRawDownload
1use super::*;
2
3use crate::domain::class_course::ClassCourseId;
4
5// ---- audience: the shared exam ----------------------------------------------
6// An exam is owned by the instance it was created on, but it can be announced
7// to other instances of the same course in the same academic year: one
8// sitting, one mark, standing in every addressed instance's marks and report card.
9// The gate is the owner instance's (a manager+, its assigned teachers, its
10// class section's homeroom teacher) — the instance that runs the exam decides
11// who else sits it.
12
13/// One instance an exam is announced to.
14#[derive(Serialize, ToSchema)]
15pub(crate) struct ExamAudienceResponse {
16 /// The class×course instance the exam is announced to.
17 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
18 instance: String,
19 /// The class section that instance belongs to.
20 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
21 class: String,
22 /// The catalog course that instance teaches — the exam's own course, by
23 /// the announcement's rule.
24 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
25 course: String,
26}
27
28impl ExamAudienceResponse {
29 fn new(audience: &crate::db::exam_audience::Audience) -> Self {
30 Self {
31 instance: audience.get_instance().key().to_string(),
32 class: audience.get_class().key().to_string(),
33 course: audience.get_course().key().to_string(),
34 }
35 }
36
37 fn list(audience: &[crate::db::exam_audience::Audience]) -> Vec<Self> {
38 audience.iter().map(Self::new).collect()
39 }
40}
41
42/// `(may_view, may_manage)` over the instances an exam is addressed to — the
43/// pair of questions every exam-level gate asks (D2).
44///
45/// A caller *sees* the exam when any addressed instance admits them as a
46/// viewer (its enrolled students, its teachers, its class section's homeroom
47/// teacher, manager+), and *acts* on it — grading, the results readers, the live
48/// monitor — when they manage one of them. Both are exactly the predicates
49/// that instance's own routes apply
50/// ([`super::instances::list_instance_exams`], `POST /instances/{id}/exams`),
51/// so an announced-to section's teacher runs the exam there like the owner's.
52/// One walk: an audience is one or two rows.
53pub(crate) async fn audience_rights(
54 db: &Database,
55 exam: &Exam,
56 user: &User,
57) -> Result<(bool, bool), AppError> {
58 let mut may_view = false;
59 let mut may_manage = false;
60 for row in crate::service::exam::list_audience(db, exam.get_id()).await? {
61 if !may_view && can_view_instance(db, row.get_instance(), user).await? {
62 may_view = true;
63 }
64 if !may_manage && can_manage_instance(db, row.get_instance(), user).await? {
65 may_manage = true;
66 }
67 if may_view && may_manage {
68 break;
69 }
70 }
71 Ok((may_view, may_manage))
72}
73
74#[derive(Deserialize, ToSchema)]
75pub(crate) struct AddAudience {
76 /// The class×course instance to announce the exam to (`GET /instances/me`,
77 /// `GET /classes/{id}/instances`). It must teach the exam's own catalog
78 /// course, sit under the same academic year, and be a *different*
79 /// instance — the owner is refused with a `400`.
80 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
81 instance: String,
82}
83
84/// Announce an exam to another instance — the **shared exam** write: one exam
85/// addressed to a sibling class section, so it and its marks stand in that
86/// section's exam list, marks report and report card. Requires teacher+ and
87/// management rights over the exam's **owner** instance (an assigned teacher,
88/// its class section's homeroom teacher, or a manager/admin) — the target
89/// instance's teachers have no say.
90/// The target must teach the exam's own catalog course and sit under the same
91/// academic year (`400` otherwise), the owner itself is refused (`400`), and
92/// an archived target year is a `409`. Announcing a pair that already stands
93/// is a no-op answering `200` with the audience unchanged.
94#[utoipa::path(
95 post,
96 path = "/{id}/audience",
97 tag = "exams",
98 security(("session_cookie" = [])),
99 params(("id" = String, Path, description = "Exam id")),
100 request_body = AddAudience,
101 responses(
102 (status = 200, description = "The exam's audience after the announcement", body = [ExamAudienceResponse]),
103 (status = 400, description = "The instance is the exam's own, teaches another course, or belongs to another academic year", body = ErrorResponse),
104 (status = 401, description = "Not authenticated", body = ErrorResponse),
105 (status = 403, description = "Not this exam's owner instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
106 (status = 404, description = "The exam or the instance does not exist", body = ErrorResponse),
107 (status = 409, description = "The instance's academic year is archived (read-only)", body = ErrorResponse),
108 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
109 ),
110)]
111pub(crate) async fn add_audience(
112 State(st): State<AppState>,
113 RequireTeacher(user): RequireTeacher,
114 Path(id): Path<String>,
115 Json(req): Json<AddAudience>,
116) -> Result<Json<Vec<ExamAudienceResponse>>, AppError> {
117 let audience = service::exam::add_audience(
118 &st.db,
119 &user,
120 &ExamId::from_key(&id),
121 &ClassCourseId::from_key(&req.instance),
122 )
123 .await?;
124 Ok(Json(ExamAudienceResponse::list(&audience)))
125}
126
127/// List the instances an exam is announced to, its owner included — the read
128/// behind the announce routes' answer, useful on its own to a client that
129/// wants to show where else an exam is sat. Visible to the exam's own
130/// audience: an addressed instance's enrolled students, its teachers (or its
131/// class section's homeroom teacher), and managers/admins — except drafts,
132/// which stay a `404` to everyone but an addressed instance's managers.
133#[utoipa::path(
134 get,
135 path = "/{id}/audience",
136 tag = "exams",
137 security(("session_cookie" = [])),
138 params(("id" = String, Path, description = "Exam id")),
139 responses(
140 (status = 200, description = "The instances the exam is announced to (the owner first, then in announcement order)", body = [ExamAudienceResponse]),
141 (status = 401, description = "Not authenticated", body = ErrorResponse),
142 (status = 403, description = "Not enrolled and not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin", body = ErrorResponse),
143 (status = 404, description = "Not found (or a draft the caller may not see)", body = ErrorResponse),
144 ),
145)]
146pub(crate) async fn list_audience(
147 State(st): State<AppState>,
148 CurrentUser(user): CurrentUser,
149 Path(id): Path<String>,
150) -> Result<Json<Vec<ExamAudienceResponse>>, AppError> {
151 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
152 .await?
153 .ok_or(AppError::NotFound)?;
154 let (may_view, may_manage) = audience_rights(&st.db, &exam, &user).await?;
155 if !may_view {
156 return Err(AppError::Forbidden(
157 "only an addressed instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view this exam",
158 ));
159 }
160 // A draft doesn't exist for anyone but an addressed instance's managers —
161 // 404, not 403, so its existence never leaks to the students it's hidden
162 // from.
163 if exam.is_draft() && !may_manage {
164 return Err(AppError::NotFound);
165 }
166 let audience = service::exam::list_audience(&st.db, exam.get_id()).await?;
167 Ok(Json(ExamAudienceResponse::list(&audience)))
168}
169
170/// Withdraw an exam from one instance's audience. Requires teacher+ and
171/// management rights over the exam's **owner** instance, like the announce
172/// itself. The owner's own pair is not withdrawable (`400`) — that is the
173/// instance the exam belongs to, and deleting the exam is what ends it; an
174/// archived year refuses the withdrawal with the same `409` its other writes
175/// answer. A pair that holds no audience row is a `404`.
176#[utoipa::path(
177 delete,
178 path = "/{id}/audience/{instance}",
179 tag = "exams",
180 security(("session_cookie" = [])),
181 params(
182 ("id" = String, Path, description = "Exam id"),
183 ("instance" = String, Path, description = "Instance id"),
184 ),
185 responses(
186 (status = 200, description = "The exam's audience after the withdrawal", body = [ExamAudienceResponse]),
187 (status = 400, description = "The pair names the exam's owner instance", body = ErrorResponse),
188 (status = 401, description = "Not authenticated", body = ErrorResponse),
189 (status = 403, description = "Not this exam's owner instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
190 (status = 404, description = "The exam does not exist, or the pair holds no audience row", body = ErrorResponse),
191 (status = 409, description = "The exam's academic year is archived (read-only)", body = ErrorResponse),
192 ),
193)]
194pub(crate) async fn remove_audience(
195 State(st): State<AppState>,
196 RequireTeacher(user): RequireTeacher,
197 Path((id, instance)): Path<(String, String)>,
198) -> Result<Json<Vec<ExamAudienceResponse>>, AppError> {
199 let audience = service::exam::remove_audience(
200 &st.db,
201 &user,
202 &ExamId::from_key(&id),
203 &ClassCourseId::from_key(&instance),
204 )
205 .await?;
206 Ok(Json(ExamAudienceResponse::list(&audience)))
207}