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

offering_subjects.rs317 lines, 13.9 KiBHistoryRawDownload
1//! Syllabus topic selection on the course-template system: the topics an
2//! offering ([`crate::domain::course_offering::CourseOffering`]) selects for
3//! its grade, and the per-section override
4//! ([`crate::domain::class_course::ClassCourse`]). The override rule is
5//! override-or-inherit, never merge, and it is **flag-driven**:
6//! `subjects_inherited` `TRUE` follows the offering's set, `FALSE` makes the
7//! section's own table authoritative *including when it is empty* — the
8//! section-level deletes and the reset door flip it in the same statement as
9//! the row change ([`crate::db::offering_subject`]).
10//!
11//! This module exports two routers: [`offering_routes`] (mounted under
12//! `/offerings` by the offerings router) and [`instance_routes`] (mounted
13//! inside `/instances` like the exam/session/homework children). Reads are
14//! open to any signed-in session; offering writes are the office's
15//! (`manager`+); instance writes pay the D10 gate every other
16//! instance-scoped write pays (`service::class_course::ensure_instance_teacher`)
17//! and refuse on an archived year.
18//!
19//! Selection always names a subject of the offering's own course — a foreign
20//! topic is the same 400 the question/homework tag check answers.
21
22use axum::Json;
23use axum::extract::Path;
24use axum::http::StatusCode;
25use serde::{Deserialize, Serialize};
26use utoipa::ToSchema;
27use utoipa_axum::router::OpenApiRouter;
28use utoipa_axum::routes;
29
30use crate::database::Database;
31use crate::domain::class_course::{ClassCourse, ClassCourseId};
32use crate::domain::course_offering::{CourseOffering, CourseOfferingId};
33use crate::domain::user::User;
34use crate::error::{AppError, ErrorResponse};
35use crate::service;
36use crate::state::AppState;
37use crate::web::dto::SubjectResponse;
38use crate::web::tenant_state::State;
39
40use super::{CurrentUser, RequireManager, RequireTeacher};
41
42/// The offering-side half: mounted under `/offerings`.
43pub fn offering_routes() -> OpenApiRouter<AppState> {
44 OpenApiRouter::new()
45 .routes(routes!(list_offering_subjects, add_offering_subject))
46 .routes(routes!(remove_offering_subject))
47}
48
49/// The instance-side half: mounted inside `/instances`, next to the exam,
50/// session and homework children. The two `DELETE`s stay in separate
51/// `routes!` calls — one call may register each HTTP method only once.
52pub fn instance_routes() -> OpenApiRouter<AppState> {
53 OpenApiRouter::new()
54 .routes(routes!(list_instance_subjects, add_instance_subject))
55 .routes(routes!(remove_instance_subject))
56 .routes(routes!(reset_instance_subjects))
57}
58
59#[derive(Deserialize, ToSchema)]
60struct AddSubject {
61 /// The subject id to select (`GET /courses/{id}/subjects`). Must belong
62 /// to the offering's own course — a foreign topic is a 400.
63 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
64 subject: String,
65}
66
67/// The topics one section teaches, resolved override-or-inherit — plus the
68/// switch, so a client can tell "the template's set" from "its own (possibly
69/// empty) set".
70#[derive(Serialize, ToSchema)]
71struct ResolvedSubjects {
72 /// The resolved set, by subject name then id.
73 subjects: Vec<SubjectResponse>,
74 /// `true` = the section follows its offering's set; `false` = its own
75 /// selection is authoritative, even when the list above is empty.
76 subjects_inherited: bool,
77}
78
79async fn offering_or_404(key: &str, db: &Database) -> Result<CourseOffering, AppError> {
80 service::course_offering::read(db, &CourseOfferingId::from_key(key))
81 .await?
82 .ok_or(AppError::NotFound)
83}
84
85async fn instance_or_404(key: &str, db: &Database) -> Result<ClassCourse, AppError> {
86 service::class_course::read(db, &ClassCourseId::from_key(key))
87 .await?
88 .ok_or(AppError::NotFound)
89}
90
91/// The instance-side write gate: D10 (manager+, this instance's teachers, its
92/// şube's homeroom teacher) over a live year — the same pair every other
93/// instance-scoped write pays.
94async fn gated_instance(key: &str, user: &User, db: &Database) -> Result<ClassCourse, AppError> {
95 let instance = instance_or_404(key, db).await?;
96 service::class_course::ensure_instance_teacher(db, user, instance.get_id()).await?;
97 service::class_course::require_open(db, instance.get_id()).await?;
98 Ok(instance)
99}
100
101/// The offering's selected topics — the set every inheriting section at that
102/// grade teaches — by subject name then id. Any signed-in session.
103#[utoipa::path(
104 get,
105 path = "/{id}/subjects",
106 tag = "offerings",
107 security(("session_cookie" = [])),
108 params(("id" = String, Path, description = "Offering id")),
109 responses(
110 (status = 200, description = "The offering's selected subjects", body = [SubjectResponse]),
111 (status = 401, description = "Not authenticated", body = ErrorResponse),
112 (status = 404, description = "Offering not found", body = ErrorResponse),
113 ),
114)]
115async fn list_offering_subjects(
116 State(st): State<AppState>,
117 CurrentUser(_user): CurrentUser,
118 Path(id): Path<String>,
119) -> Result<Json<Vec<SubjectResponse>>, AppError> {
120 let offering = offering_or_404(&id, &st.db).await?;
121 let subjects = service::offering_subject::resolved_for_offering(&st.db, offering.get_id())
122 .await?;
123 Ok(Json(subjects.iter().map(SubjectResponse::new).collect()))
124}
125
126/// Select a topic for the offering. Manager+. Re-selecting an already
127/// selected topic is a no-op success (`200`, not a second row).
128#[utoipa::path(
129 post,
130 path = "/{id}/subjects",
131 tag = "offerings",
132 security(("session_cookie" = [])),
133 params(("id" = String, Path, description = "Offering id")),
134 request_body = AddSubject,
135 responses(
136 (status = 201, description = "Subject selected", body = SubjectResponse),
137 (status = 200, description = "Already selected — no-op success", body = SubjectResponse),
138 (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse),
139 (status = 401, description = "Not authenticated", body = ErrorResponse),
140 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
141 (status = 404, description = "Offering not found", body = ErrorResponse),
142 (status = 422, description = "The body does not fit this request: `subject` is missing or malformed"),
143 ),
144)]
145async fn add_offering_subject(
146 State(st): State<AppState>,
147 RequireManager(_user): RequireManager,
148 Path(id): Path<String>,
149 Json(req): Json<AddSubject>,
150) -> Result<(StatusCode, Json<SubjectResponse>), AppError> {
151 let offering = offering_or_404(&id, &st.db).await?;
152 let (subject, added) =
153 service::offering_subject::add_to_offering(&st.db, offering.get_id(), &req.subject)
154 .await?;
155 let code = if added {
156 StatusCode::CREATED
157 } else {
158 StatusCode::OK
159 };
160 Ok((code, Json(SubjectResponse::new(&subject))))
161}
162
163/// Drop a topic from the offering's selection. Manager+. Dropping a topic the
164/// offering never selected is a 404.
165#[utoipa::path(
166 delete,
167 path = "/{id}/subjects/{subject}",
168 tag = "offerings",
169 security(("session_cookie" = [])),
170 params(
171 ("id" = String, Path, description = "Offering id"),
172 ("subject" = String, Path, description = "Subject id"),
173 ),
174 responses(
175 (status = 204, description = "Dropped"),
176 (status = 401, description = "Not authenticated", body = ErrorResponse),
177 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
178 (status = 404, description = "Offering not found, or subject not selected", body = ErrorResponse),
179 ),
180)]
181async fn remove_offering_subject(
182 State(st): State<AppState>,
183 RequireManager(_user): RequireManager,
184 Path((id, subject)): Path<(String, String)>,
185) -> Result<StatusCode, AppError> {
186 let offering = offering_or_404(&id, &st.db).await?;
187 service::offering_subject::remove_from_offering(&st.db, offering.get_id(), &subject).await?;
188 Ok(StatusCode::NO_CONTENT)
189}
190
191/// The topics this section teaches, resolved override-or-inherit, with the
192/// switch: `subjects_inherited: false` means the listed set (even when
193/// empty) is the section's own and the offering's is ignored. Any signed-in
194/// session.
195#[utoipa::path(
196 get,
197 path = "/{id}/subjects",
198 tag = "instances",
199 security(("session_cookie" = [])),
200 params(("id" = String, Path, description = "Instance (class×course) id")),
201 responses(
202 (status = 200, description = "The resolved subject set and whether it is inherited", body = ResolvedSubjects),
203 (status = 401, description = "Not authenticated", body = ErrorResponse),
204 (status = 404, description = "Instance not found", body = ErrorResponse),
205 ),
206)]
207async fn list_instance_subjects(
208 State(st): State<AppState>,
209 CurrentUser(_user): CurrentUser,
210 Path(id): Path<String>,
211) -> Result<Json<ResolvedSubjects>, AppError> {
212 let instance = instance_or_404(&id, &st.db).await?;
213 let subjects = service::offering_subject::resolved_for_instance(&st.db, &instance).await?;
214 Ok(Json(ResolvedSubjects {
215 subjects: subjects.iter().map(SubjectResponse::new).collect(),
216 subjects_inherited: instance.subjects_inherited(),
217 }))
218}
219
220/// Select a topic for this section's own set — the override. The switch
221/// flips to "own" in the same write, so the section's table (not the
222/// offering's set) becomes authoritative from this call on. Re-selecting an
223/// already selected topic is a no-op success. D10 gate; refuses on an
224/// archived year.
225#[utoipa::path(
226 post,
227 path = "/{id}/subjects",
228 tag = "instances",
229 security(("session_cookie" = [])),
230 params(("id" = String, Path, description = "Instance (class×course) id")),
231 request_body = AddSubject,
232 responses(
233 (status = 201, description = "Subject selected — the section now owns its set", body = SubjectResponse),
234 (status = 200, description = "Already selected — no-op success", body = SubjectResponse),
235 (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse),
236 (status = 401, description = "Not authenticated", body = ErrorResponse),
237 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
238 (status = 404, description = "Instance not found", body = ErrorResponse),
239 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
240 (status = 422, description = "The body does not fit this request: `subject` is missing or malformed"),
241 ),
242)]
243async fn add_instance_subject(
244 State(st): State<AppState>,
245 RequireTeacher(user): RequireTeacher,
246 Path(id): Path<String>,
247 Json(req): Json<AddSubject>,
248) -> Result<(StatusCode, Json<SubjectResponse>), AppError> {
249 let instance = gated_instance(&id, &user, &st.db).await?;
250 let (subject, added) =
251 service::offering_subject::add_to_instance(&st.db, &instance, &req.subject).await?;
252 let code = if added {
253 StatusCode::CREATED
254 } else {
255 StatusCode::OK
256 };
257 Ok((code, Json(SubjectResponse::new(&subject))))
258}
259
260/// Drop one topic from this section's own set (keeping the set its own —
261/// clearing the syllabus needs the reset below, or deleting the last rows
262/// one by one). Dropping a topic the section never selected is a 404 and
263/// flips nothing. D10 gate; refuses on an archived year.
264#[utoipa::path(
265 delete,
266 path = "/{id}/subjects/{subject}",
267 tag = "instances",
268 security(("session_cookie" = [])),
269 params(
270 ("id" = String, Path, description = "Instance (class×course) id"),
271 ("subject" = String, Path, description = "Subject id"),
272 ),
273 responses(
274 (status = 204, description = "Dropped — the section keeps its own set"),
275 (status = 401, description = "Not authenticated", body = ErrorResponse),
276 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
277 (status = 404, description = "Instance not found, or subject not in the section's own set", body = ErrorResponse),
278 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
279 ),
280)]
281async fn remove_instance_subject(
282 State(st): State<AppState>,
283 RequireTeacher(user): RequireTeacher,
284 Path((id, subject)): Path<(String, String)>,
285) -> Result<StatusCode, AppError> {
286 let instance = gated_instance(&id, &user, &st.db).await?;
287 service::offering_subject::remove_from_instance(&st.db, &instance, &subject).await?;
288 Ok(StatusCode::NO_CONTENT)
289}
290
291/// Restore inheritance: sweep the section's own rows and flip
292/// `subjects_inherited` back to TRUE in the same statement — the offering's
293/// set applies again. A section whose own set was already empty resets
294/// cleanly. D10 gate; refuses on an archived year.
295#[utoipa::path(
296 delete,
297 path = "/{id}/subjects",
298 tag = "instances",
299 security(("session_cookie" = [])),
300 params(("id" = String, Path, description = "Instance (class×course) id")),
301 responses(
302 (status = 204, description = "Own set swept — the offering's set applies again"),
303 (status = 401, description = "Not authenticated", body = ErrorResponse),
304 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
305 (status = 404, description = "Instance not found", body = ErrorResponse),
306 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
307 ),
308)]
309async fn reset_instance_subjects(
310 State(st): State<AppState>,
311 RequireTeacher(user): RequireTeacher,
312 Path(id): Path<String>,
313) -> Result<StatusCode, AppError> {
314 let instance = gated_instance(&id, &user, &st.db).await?;
315 service::offering_subject::reset_instance(&st.db, &instance).await?;
316 Ok(StatusCode::NO_CONTENT)
317}