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_weights.rs368 lines, 15.6 KiBHistoryRawDownload
1//! The exam-weight override routes: per-kind weights on the grade-level
2//! template (`/offerings/{id}/exam-weights`, manager+) and on the class
3//! section (`/instances/{id}/exam-weights`, the D10 instance gate), plus the
4//! section's reset.
5//!
6//! Every `GET` returns the **resolved** map — the effective weight of every
7//! kind under that level, computed here — so a client renders it verbatim and
8//! never re-implements the class → offering → settings → 1 chain. The
9//! instance map carries the `inherited` flag: while it is `true` the map is
10//! the offering's resolved set; while `false` it is exactly the section's own
11//! rows, empty included (an own set in force is authoritative even when
12//! empty).
13//!
14//! A write naming a kind the school does not run is the one refusal here with
15//! a machine code — 400 `unknown_exam_kind` — because a client can branch on
16//! "fix the kind" vs "fix the weight"; it is rendered by this module (the
17//! service's `ValidationError::Invalid { field: "kind" }` re-wrapped), since
18//! the coded-body vocabulary lives with the route that publishes it.
19
20use axum::Json;
21use axum::extract::Path;
22use axum::http::StatusCode;
23use axum::response::{IntoResponse, Response};
24use serde::{Deserialize, Serialize};
25use utoipa::ToSchema;
26use utoipa_axum::router::OpenApiRouter;
27use utoipa_axum::routes;
28
29use crate::database::Database;
30use crate::domain::class_course::{ClassCourse, ClassCourseId};
31use crate::domain::course_offering::CourseOfferingId;
32use crate::domain::exam_weight::ExamWeight;
33use crate::error::{AppError, ErrorResponse, ValidationError};
34use crate::service;
35use crate::state::AppState;
36use crate::web::instances::can_view_instance;
37use crate::web::tenant_state::State;
38
39use super::{CurrentUser, RequireManager, RequireTeacher};
40
41/// Mounted under `/offerings` — the template's weight routes.
42pub fn offering_routes() -> OpenApiRouter<AppState> {
43 OpenApiRouter::new()
44 .routes(routes!(get_offering_weights, patch_offering_weight))
45 .routes(routes!(delete_offering_weight))
46}
47
48/// Mounted inside `/instances` — the section's weight routes and reset.
49pub fn instance_routes() -> OpenApiRouter<AppState> {
50 OpenApiRouter::new()
51 .routes(routes!(get_instance_weights, patch_instance_weight))
52 .routes(routes!(delete_instance_weight))
53 .routes(routes!(reset_instance_weights))
54}
55
56#[derive(Deserialize, ToSchema)]
57struct PatchExamWeight {
58 /// The exam kind exactly as the school spells it in `GET /settings`
59 /// (`settings.exam_kinds`). Anything else is a 400 `unknown_exam_kind`.
60 #[schema(example = "midterm")]
61 kind: String,
62 /// The weight this kind carries under the level being edited: 1..=100.
63 #[schema(minimum = 1, maximum = 100, example = 3)]
64 weight: i64,
65}
66
67/// One resolved entry: the kind and the weight an exam of it carries *here*
68/// after the whole fallback chain.
69#[derive(Serialize, ToSchema)]
70pub struct ExamWeightEntry {
71 #[schema(example = "midterm")]
72 pub kind: String,
73 pub weight: i64,
74}
75
76impl ExamWeightEntry {
77 pub(crate) fn of(row: &ExamWeight) -> Self {
78 Self {
79 kind: row.get_kind().to_string(),
80 weight: row.get_weight(),
81 }
82 }
83}
84
85/// The template's resolved weight map.
86#[derive(Serialize, ToSchema)]
87pub struct OfferingExamWeightsResponse {
88 /// Every kind the school runs (plus any kind a stored row adds), each at
89 /// its effective weight: the offering's own row, else the settings
90 /// weight, else 1.
91 pub weights: Vec<ExamWeightEntry>,
92}
93
94/// The section's resolved weight map, with the override switch.
95#[derive(Serialize, ToSchema)]
96pub struct InstanceExamWeightsResponse {
97 /// `true` = the section follows its offering's set (the map below is the
98 /// offering's, resolved); `false` = the section's own table is
99 /// authoritative and the map is exactly its rows — including when that is
100 /// none, which is how a section zeroes the template's weights.
101 pub inherited: bool,
102 pub weights: Vec<ExamWeightEntry>,
103}
104
105async fn offering_or_404(key: &str, db: &Database) -> Result<CourseOfferingId, AppError> {
106 let id = CourseOfferingId::from_key(key);
107 if service::course_offering::read(db, &id).await?.is_none() {
108 return Err(AppError::NotFound);
109 }
110 Ok(id)
111}
112
113/// The instance row the write gates judge — a missing id is a 404 before any
114/// body is read.
115async fn instance_or_404(key: &str, db: &Database) -> Result<ClassCourse, AppError> {
116 service::class_course::read(db, &ClassCourseId::from_key(key))
117 .await?
118 .ok_or(AppError::NotFound)
119}
120
121/// Re-renders the service's kind refusal as the coded 400 this route
122/// documents; every other error keeps its own wire shape.
123fn kind_refusal(err: AppError, kind: &str) -> Response {
124 if let AppError::Validation(ValidationError::Invalid { field: "kind", .. }) = &err {
125 return (
126 StatusCode::BAD_REQUEST,
127 Json(serde_json::json!({
128 "error": format!("kind: `{kind}` is not a known exam kind"),
129 "code": "unknown_exam_kind",
130 })),
131 )
132 .into_response();
133 }
134 err.into_response()
135}
136
137// ---- the template's weights --------------------------------------------------
138
139/// The grade-level template's resolved exam-kind weights. Any signed-in
140/// session.
141#[utoipa::path(
142 get,
143 path = "/{id}/exam-weights",
144 tag = "offerings",
145 security(("session_cookie" = [])),
146 params(("id" = String, Path, description = "Offering id")),
147 responses(
148 (status = 200, description = "The offering's resolved weights", body = OfferingExamWeightsResponse),
149 (status = 401, description = "Not authenticated", body = ErrorResponse),
150 (status = 404, description = "Offering not found", body = ErrorResponse),
151 ),
152)]
153async fn get_offering_weights(
154 State(st): State<AppState>,
155 CurrentUser(_user): CurrentUser,
156 Path(id): Path<String>,
157) -> Result<Json<OfferingExamWeightsResponse>, AppError> {
158 let offering = offering_or_404(&id, &st.db).await?;
159 let weights = service::exam_weight::resolved_for_offering(&st.db, &offering).await?;
160 Ok(Json(OfferingExamWeightsResponse {
161 weights: weights.iter().map(ExamWeightEntry::of).collect(),
162 }))
163}
164
165/// Set (or rewrite) one kind's weight on the template. Manager+. The kind must
166/// be one the school runs — a 400 carrying the machine code
167/// `unknown_exam_kind` otherwise; the weight must sit in 1..=100. Sections
168/// that still inherit the template pick the change up immediately.
169#[utoipa::path(
170 patch,
171 path = "/{id}/exam-weights",
172 tag = "offerings",
173 security(("session_cookie" = [])),
174 params(("id" = String, Path, description = "Offering id")),
175 request_body = PatchExamWeight,
176 responses(
177 (status = 200, description = "The offering's resolved weights after the write", body = OfferingExamWeightsResponse),
178 (status = 400, description = "A weight outside 1..=100, or a kind the school does not run (body carries the machine code `unknown_exam_kind`)", body = ErrorResponse),
179 (status = 401, description = "Not authenticated", body = ErrorResponse),
180 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
181 (status = 404, description = "Offering not found", body = ErrorResponse),
182 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
183 ),
184)]
185async fn patch_offering_weight(
186 State(st): State<AppState>,
187 RequireManager(_user): RequireManager,
188 Path(id): Path<String>,
189 Json(req): Json<PatchExamWeight>,
190) -> Result<Response, AppError> {
191 let offering = offering_or_404(&id, &st.db).await?;
192 if let Err(err) =
193 service::exam_weight::set_for_offering(&st.db, &offering, &req.kind, req.weight).await
194 {
195 return Ok(kind_refusal(err, &req.kind));
196 }
197 let weights = service::exam_weight::resolved_for_offering(&st.db, &offering).await?;
198 Ok(Json(OfferingExamWeightsResponse {
199 weights: weights.iter().map(ExamWeightEntry::of).collect(),
200 })
201 .into_response())
202}
203
204/// Drop one kind's weight row from the template; the settings weight applies
205/// again. A kind with no row is a 404.
206#[utoipa::path(
207 delete,
208 path = "/{id}/exam-weights/{kind}",
209 tag = "offerings",
210 security(("session_cookie" = [])),
211 params(
212 ("id" = String, Path, description = "Offering id"),
213 ("kind" = String, Path, description = "Exam kind"),
214 ),
215 responses(
216 (status = 204, description = "Row deleted — the settings weight applies again"),
217 (status = 401, description = "Not authenticated", body = ErrorResponse),
218 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
219 (status = 404, description = "Offering not found, or it carries no weight row for this kind", body = ErrorResponse),
220 ),
221)]
222async fn delete_offering_weight(
223 State(st): State<AppState>,
224 RequireManager(_user): RequireManager,
225 Path((id, kind)): Path<(String, String)>,
226) -> Result<StatusCode, AppError> {
227 let offering = offering_or_404(&id, &st.db).await?;
228 service::exam_weight::remove_from_offering(&st.db, &offering, &kind).await?;
229 Ok(StatusCode::NO_CONTENT)
230}
231
232// ---- the section's weights ---------------------------------------------------
233
234/// The section's resolved exam-kind weights and its override switch. Visible
235/// to the same eyes as the rest of the instance's reads.
236#[utoipa::path(
237 get,
238 path = "/{id}/exam-weights",
239 tag = "instances",
240 security(("session_cookie" = [])),
241 params(("id" = String, Path, description = "Instance id")),
242 responses(
243 (status = 200, description = "The section's resolved weights, with the inherited flag", body = InstanceExamWeightsResponse),
244 (status = 401, description = "Not authenticated", body = ErrorResponse),
245 (status = 403, description = "Not enrolled, not this instance's teacher, and not a manager/admin", body = ErrorResponse),
246 (status = 404, description = "Instance not found", body = ErrorResponse),
247 ),
248)]
249async fn get_instance_weights(
250 State(st): State<AppState>,
251 CurrentUser(user): CurrentUser,
252 Path(id): Path<String>,
253) -> Result<Json<InstanceExamWeightsResponse>, AppError> {
254 let instance = instance_or_404(&id, &st.db).await?;
255 if !can_view_instance(&st.db, instance.get_id(), &user).await? {
256 return Err(AppError::Forbidden(
257 "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view its weights",
258 ));
259 }
260 let (inherited, weights) = service::exam_weight::resolved_for_class(&st.db, &instance).await?;
261 Ok(Json(InstanceExamWeightsResponse {
262 inherited,
263 weights: weights.iter().map(ExamWeightEntry::of).collect(),
264 }))
265}
266
267/// Set (or rewrite) one kind's weight on the section — and take its weight set
268/// own: the flag flips in the same statement, so from here on the section's
269/// own rows (these included) are the whole map, even where they are absent.
270/// Requires teacher+ and a right over the instance (D10).
271#[utoipa::path(
272 patch,
273 path = "/{id}/exam-weights",
274 tag = "instances",
275 security(("session_cookie" = [])),
276 params(("id" = String, Path, description = "Instance id")),
277 request_body = PatchExamWeight,
278 responses(
279 (status = 200, description = "The section's resolved weights after the write (`inherited` now `false`)", body = InstanceExamWeightsResponse),
280 (status = 400, description = "A weight outside 1..=100, or a kind the school does not run (body carries the machine code `unknown_exam_kind`)", body = ErrorResponse),
281 (status = 401, description = "Not authenticated", body = ErrorResponse),
282 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
283 (status = 404, description = "Instance not found", body = ErrorResponse),
284 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
285 ),
286)]
287async fn patch_instance_weight(
288 State(st): State<AppState>,
289 RequireTeacher(user): RequireTeacher,
290 Path(id): Path<String>,
291 Json(req): Json<PatchExamWeight>,
292) -> Result<Response, AppError> {
293 let instance = instance_or_404(&id, &st.db).await?;
294 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
295 if let Err(err) =
296 service::exam_weight::set_for_class(&st.db, instance.get_id(), &req.kind, req.weight).await
297 {
298 return Ok(kind_refusal(err, &req.kind));
299 }
300 // The write flipped the flag, so the map is computed off the fresh row,
301 // never the one the gate read.
302 let fresh = service::class_course::read(&st.db, instance.get_id())
303 .await?
304 .ok_or(AppError::NotFound)?;
305 let (inherited, weights) = service::exam_weight::resolved_for_class(&st.db, &fresh).await?;
306 Ok(Json(InstanceExamWeightsResponse {
307 inherited,
308 weights: weights.iter().map(ExamWeightEntry::of).collect(),
309 })
310 .into_response())
311}
312
313/// Drop one kind's weight row from the section. Deleting still takes the set
314/// own — removing the last row *decides* on an empty set (every kind then
315/// weighs 1 here) rather than falling back. A kind with no row is a 404 that
316/// changes nothing.
317#[utoipa::path(
318 delete,
319 path = "/{id}/exam-weights/{kind}",
320 tag = "instances",
321 security(("session_cookie" = [])),
322 params(
323 ("id" = String, Path, description = "Instance id"),
324 ("kind" = String, Path, description = "Exam kind"),
325 ),
326 responses(
327 (status = 204, description = "Row deleted — the section's own set stays authoritative without it"),
328 (status = 401, description = "Not authenticated", body = ErrorResponse),
329 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
330 (status = 404, description = "Instance not found, or it carries no weight row for this kind", body = ErrorResponse),
331 ),
332)]
333async fn delete_instance_weight(
334 State(st): State<AppState>,
335 RequireTeacher(user): RequireTeacher,
336 Path((id, kind)): Path<(String, String)>,
337) -> Result<StatusCode, AppError> {
338 let instance = instance_or_404(&id, &st.db).await?;
339 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
340 service::exam_weight::remove_from_class(&st.db, instance.get_id(), &kind).await?;
341 Ok(StatusCode::NO_CONTENT)
342}
343
344/// The reset: drop every section weight row and follow the offering's set
345/// (then the settings, then 1) again. Idempotent.
346#[utoipa::path(
347 delete,
348 path = "/{id}/exam-weights",
349 tag = "instances",
350 security(("session_cookie" = [])),
351 params(("id" = String, Path, description = "Instance id")),
352 responses(
353 (status = 204, description = "Rows deleted — inheritance restored"),
354 (status = 401, description = "Not authenticated", body = ErrorResponse),
355 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
356 (status = 404, description = "Instance not found", body = ErrorResponse),
357 ),
358)]
359async fn reset_instance_weights(
360 State(st): State<AppState>,
361 RequireTeacher(user): RequireTeacher,
362 Path(id): Path<String>,
363) -> Result<StatusCode, AppError> {
364 let instance = instance_or_404(&id, &st.db).await?;
365 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
366 service::exam_weight::reset_class(&st.db, instance.get_id()).await?;
367 Ok(StatusCode::NO_CONTENT)
368}