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

offerings.rs376 lines, 15.6 KiBHistoryRawDownload
1//! The course **offerings**: the grade-level templates (`course_offering`)
2//! every class×course instance inherits from — one row per
3//! (course × grade_level) carrying the title, description and the
4//! weekly-hours / report-card defaults for that grade, with the per-class
5//! overrides living on the instances themselves
6//! ([`crate::web::instances`]).
7//!
8//! Reads are open to any signed-in session; writes are the office's
9//! (`manager`+), the same bar as the catalog itself. Every write door keeps
10//! the override-or-inherit rule visible: a `PATCH` field sent as `null`
11//! clears back to inherit, and the delete refuses with `offering_in_use`
12//! while any instance still teaches from the template.
13
14use std::collections::HashMap;
15
16use axum::Json;
17use axum::extract::{Path, Query};
18use axum::http::StatusCode;
19use serde::{Deserialize, Serialize};
20use utoipa::{IntoParams, ToSchema};
21use utoipa_axum::router::OpenApiRouter;
22use utoipa_axum::routes;
23
24use crate::database::Database;
25use crate::domain::class_course::DersSaati;
26use crate::domain::course::{CourseDescription, CourseId, CourseTitle};
27use crate::domain::course_offering::{CourseOffering, CourseOfferingId};
28use crate::domain::grade::GradeLevel;
29use crate::error::{AppError, ErrorResponse, ValidationError};
30use crate::service;
31use crate::state::AppState;
32use crate::web::tenant_state::State;
33
34use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, person_map, set_or_clear};
35
36pub fn routes() -> OpenApiRouter<AppState> {
37 OpenApiRouter::new()
38 .routes(routes!(create_offering, list_offerings))
39 .routes(routes!(get_offering, update_offering, delete_offering))
40}
41
42#[derive(Deserialize, ToSchema)]
43struct CreateOffering {
44 /// The catalog course this template teaches from (`POST /courses`).
45 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
46 course: String,
47 /// The ladder rung: `0` is anaokulu, `1..=12` the school years.
48 #[schema(minimum = 0, maximum = 12, example = 9)]
49 grade_level: i16,
50 /// The grade's own title; omit to inherit the catalog course's.
51 #[schema(max_length = 200)]
52 title: Option<String>,
53 /// The grade's own description; omit to inherit the catalog's.
54 #[schema(max_length = 2_000)]
55 description: Option<String>,
56 /// The grade's default weekly hours; omit for the constant 1.
57 #[schema(minimum = 1, maximum = 40, example = 5)]
58 default_ders_saati: Option<i64>,
59 /// The grade's default report-card policy; omit for counted (`true`).
60 default_counts_toward_karne: Option<bool>,
61}
62
63#[derive(Deserialize, ToSchema)]
64struct UpdateOffering {
65 /// Omit to keep; send `null` to clear (inherit the catalog course's
66 /// title); send a value to set the grade's own.
67 #[serde(default, deserialize_with = "set_or_clear")]
68 #[schema(value_type = Option<String>, max_length = 200)]
69 title: Option<Option<String>>,
70 /// Omit to keep; `null` to clear (inherit the catalog's); a value to set.
71 #[serde(default, deserialize_with = "set_or_clear")]
72 #[schema(value_type = Option<String>, max_length = 2_000)]
73 description: Option<Option<String>>,
74 /// Omit to keep; `null` to clear (inherit the constant 1); 1..=40 to set.
75 #[serde(default, deserialize_with = "set_or_clear")]
76 #[schema(value_type = Option<i64>, minimum = 1, maximum = 40)]
77 default_ders_saati: Option<Option<i64>>,
78 /// Omit to keep; `null` to clear (inherit counted); a value to set.
79 #[serde(default, deserialize_with = "set_or_clear")]
80 #[schema(value_type = Option<bool>)]
81 default_counts_toward_karne: Option<Option<bool>>,
82}
83
84/// The list filters, both optional and combinable.
85#[derive(Deserialize, IntoParams)]
86struct OfferingFilter {
87 /// Only this course's offerings.
88 #[param(example = "019732e3-7b00-7000-8000-00000000dead")]
89 course: Option<String>,
90 /// Only this ladder rung (`0` = anaokulu).
91 #[param(minimum = 0, maximum = 12)]
92 grade_level: Option<i16>,
93}
94
95impl OfferingFilter {
96 /// Validate + canonicalize: a malformed course key is a 400, not an empty
97 /// page — the caller asked for something, the key just does not name it.
98 fn resolve(&self) -> Result<(Option<CourseId>, Option<GradeLevel>), AppError> {
99 let course = match &self.course {
100 Some(key) => {
101 let id = CourseId::from_key(key);
102 if id.uuid().is_nil() {
103 return Err(ValidationError::Invalid {
104 field: "course",
105 reason: "must be a hyphenated uuid",
106 }
107 .into());
108 }
109 Some(id)
110 }
111 None => None,
112 };
113 let grade = self.grade_level.map(GradeLevel::new).transpose()?;
114 Ok((course, grade))
115 }
116}
117
118/// Public shape of one offering: the grade-level template, with `null`
119/// meaning *inherit* on every content field. These are the **raw template
120/// values** — this row IS the grade's template, so a manager reads and edits
121/// exactly what is stored here. The per-instance **resolved** view (override
122/// → offering → catalog/constant, no nulls, with the source flags) is what
123/// `GET /instances/{id}` serves.
124#[derive(Serialize, ToSchema)]
125pub struct OfferingResponse {
126 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
127 pub id: String,
128 /// The catalog course taught from this template (`GET /courses/{id}`).
129 pub course: String,
130 /// The ladder rung: `0` = anaokulu, `1..=12` the school years.
131 pub grade_level: i16,
132 /// The grade's own title; `null` = the catalog course's title.
133 pub title: Option<String>,
134 /// The grade's own description; `null` = the catalog course's.
135 pub description: Option<String>,
136 /// The grade's default weekly hours; `null` = the constant 1.
137 pub default_ders_saati: Option<i64>,
138 /// The grade's default report-card policy; `null` = counted (`true`).
139 pub default_counts_toward_karne: Option<bool>,
140 /// Who minted the template (deliberately, or by first attaching the
141 /// course to a class at this grade).
142 pub created_by: PersonRef,
143 /// Mint instant, UTC unix-milliseconds.
144 pub created_at: i64,
145 /// Last content edit, UTC unix-milliseconds.
146 pub updated_at: i64,
147}
148
149impl OfferingResponse {
150 fn new(offering: &CourseOffering, people: &HashMap<String, PersonRef>) -> Self {
151 Self {
152 id: offering.get_id().key(),
153 course: offering.get_course().key(),
154 grade_level: offering.get_grade_level().get(),
155 title: offering.get_title().map(|t| t.as_str().to_string()),
156 description: offering.get_description().map(|d| d.as_str().to_string()),
157 default_ders_saati: offering.get_default_ders_saati().map(DersSaati::as_i64),
158 default_counts_toward_karne: offering.get_default_counts_toward_karne(),
159 created_by: PersonRef::resolve(people, offering.get_created_by()),
160 created_at: offering.get_created_at().as_millis(),
161 updated_at: offering.get_updated_at().as_millis(),
162 }
163 }
164}
165
166async fn offering_or_404(key: &str, db: &Database) -> Result<CourseOffering, AppError> {
167 service::course_offering::read(db, &CourseOfferingId::from_key(key))
168 .await?
169 .ok_or(AppError::NotFound)
170}
171
172/// Create the grade-level template for a course. Manager+. A course that is
173/// not a class-delivered ders has no grade axis and is refused (a club or
174/// etüt is joined individually, never attached); a template that already
175/// exists for the (course, grade) pair is a 409 `offering_exists`.
176#[utoipa::path(
177 post,
178 path = "/",
179 tag = "offerings",
180 security(("session_cookie" = [])),
181 request_body = CreateOffering,
182 responses(
183 (status = 201, description = "Offering created", body = OfferingResponse),
184 (status = 400, description = "Invalid fields, or the course is not a class-delivered ders (kind `course`)", body = ErrorResponse),
185 (status = 401, description = "Not authenticated", body = ErrorResponse),
186 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
187 (status = 404, description = "Course not found", body = ErrorResponse),
188 (status = 409, description = "The course already has an offering for this grade — the body carries the machine code `offering_exists`", body = ErrorResponse),
189 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
190 ),
191)]
192async fn create_offering(
193 State(st): State<AppState>,
194 RequireManager(user): RequireManager,
195 Json(req): Json<CreateOffering>,
196) -> Result<(StatusCode, Json<OfferingResponse>), AppError> {
197 let course = CourseId::from_key(&req.course);
198 if course.uuid().is_nil() {
199 return Err(ValidationError::Invalid {
200 field: "course",
201 reason: "must be a hyphenated uuid",
202 }
203 .into());
204 }
205 let grade = GradeLevel::new(req.grade_level)?;
206 let title = match &req.title {
207 Some(title) => Some(CourseTitle::try_new(title)?),
208 None => None,
209 };
210 let description = match &req.description {
211 Some(description) => Some(CourseDescription::try_new(description)?),
212 None => None,
213 };
214 let staff = req.default_ders_saati.map(DersSaati::try_new).transpose()?;
215 let offering = service::course_offering::create(
216 &st.db,
217 user.get_id(),
218 &course,
219 grade,
220 title,
221 description,
222 staff,
223 req.default_counts_toward_karne,
224 )
225 .await?;
226 let people = PersonRef::map_of(&[&user]);
227 Ok((StatusCode::CREATED, Json(OfferingResponse::new(&offering, &people))))
228}
229
230/// List the offerings, paged via `?limit=&offset=` (omit `limit` for all of
231/// them); optionally narrowed by `?course=` and/or `?grade_level=`. Returns a
232/// `{items, total, limit, offset}` envelope.
233#[utoipa::path(
234 get,
235 path = "/",
236 tag = "offerings",
237 security(("session_cookie" = [])),
238 params(PageParams, OfferingFilter),
239 responses(
240 (status = 200, description = "A page of offerings (all of them when unpaged)", body = Page<OfferingResponse>),
241 (status = 400, description = "Invalid limit, offset, course key, or grade_level", body = ErrorResponse),
242 (status = 401, description = "Not authenticated", body = ErrorResponse),
243 ),
244)]
245async fn list_offerings(
246 State(st): State<AppState>,
247 CurrentUser(_user): CurrentUser,
248 Query(page): Query<PageParams>,
249 Query(filter): Query<OfferingFilter>,
250) -> Result<Json<Page<OfferingResponse>>, AppError> {
251 let (limit, offset) = page.resolve()?;
252 let (course, grade) = filter.resolve()?;
253 let (rows, total) =
254 service::course_offering::list(&st.db, course.as_ref(), grade, limit, offset).await?;
255 let people = person_map(rows.iter().map(|o| *o.get_created_by()), &st.db).await?;
256 let items = rows
257 .iter()
258 .map(|offering| OfferingResponse::new(offering, &people))
259 .collect();
260 Ok(Json(Page::new(items, total, limit, offset)))
261}
262
263/// Fetch one offering by id. Any signed-in session. The body is the raw
264/// template row (nullable = inherit) — not the per-instance resolved view
265/// `GET /instances/{id}` serves.
266#[utoipa::path(
267 get,
268 path = "/{id}",
269 tag = "offerings",
270 security(("session_cookie" = [])),
271 params(("id" = String, Path, description = "Offering id")),
272 responses(
273 (status = 200, description = "The offering's raw template values (null = inherit); the per-class resolved view lives on GET /instances/{id}", body = OfferingResponse),
274 (status = 401, description = "Not authenticated", body = ErrorResponse),
275 (status = 404, description = "Not found", body = ErrorResponse),
276 ),
277)]
278async fn get_offering(
279 State(st): State<AppState>,
280 CurrentUser(_user): CurrentUser,
281 Path(id): Path<String>,
282) -> Result<Json<OfferingResponse>, AppError> {
283 let offering = offering_or_404(&id, &st.db).await?;
284 let people = person_map(std::iter::once(*offering.get_created_by()), &st.db).await?;
285 Ok(Json(OfferingResponse::new(&offering, &people)))
286}
287
288/// Field-scoped edit. Manager+. Omitted fields keep their value; an explicit
289/// `null` clears the override back to inherit (the catalog course's title or
290/// description, the constant 1 weekly hour, counted toward the karne); a
291/// value sets the grade's own. Instances that carry no override of their own
292/// follow the change immediately — that is what inherit means.
293#[utoipa::path(
294 patch,
295 path = "/{id}",
296 tag = "offerings",
297 security(("session_cookie" = [])),
298 params(("id" = String, Path, description = "Offering id")),
299 request_body = UpdateOffering,
300 responses(
301 (status = 200, description = "Updated offering", body = OfferingResponse),
302 (status = 400, description = "Invalid field values", body = ErrorResponse),
303 (status = 401, description = "Not authenticated", body = ErrorResponse),
304 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
305 (status = 404, description = "Not found", body = ErrorResponse),
306 (status = 422, description = "The body does not fit this request: a field has the wrong type"),
307 ),
308)]
309async fn update_offering(
310 State(st): State<AppState>,
311 RequireManager(_user): RequireManager,
312 Path(id): Path<String>,
313 Json(req): Json<UpdateOffering>,
314) -> Result<Json<OfferingResponse>, AppError> {
315 // Tri-state per field: absent = keep, null = clear to inherit, value = set.
316 let title = match req.title {
317 None => None,
318 Some(inner) => Some(match inner {
319 None => None,
320 Some(text) => Some(CourseTitle::try_new(&text)?),
321 }),
322 };
323 let description = match req.description {
324 None => None,
325 Some(inner) => Some(match inner {
326 None => None,
327 Some(text) => Some(CourseDescription::try_new(&text)?),
328 }),
329 };
330 let staff = match req.default_ders_saati {
331 None => None,
332 Some(inner) => Some(match inner {
333 None => None,
334 Some(hours) => Some(DersSaati::try_new(hours)?),
335 }),
336 };
337 let offering = service::course_offering::update(
338 &st.db,
339 &CourseOfferingId::from_key(&id),
340 title,
341 description,
342 staff,
343 req.default_counts_toward_karne,
344 )
345 .await?;
346 let people = person_map(std::iter::once(*offering.get_created_by()), &st.db).await?;
347 Ok(Json(OfferingResponse::new(&offering, &people)))
348}
349
350/// Delete the template. Manager+. Refused with 409 `offering_in_use` while
351/// any class×course instance still teaches from it — detach the course from
352/// those classes first. Deleting a template no section uses erases only the
353/// grade's overrides; the instances keep existing (their next attach
354/// re-mints an empty template).
355#[utoipa::path(
356 delete,
357 path = "/{id}",
358 tag = "offerings",
359 security(("session_cookie" = [])),
360 params(("id" = String, Path, description = "Offering id")),
361 responses(
362 (status = 204, description = "Deleted"),
363 (status = 401, description = "Not authenticated", body = ErrorResponse),
364 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
365 (status = 404, description = "Not found", body = ErrorResponse),
366 (status = 409, description = "An instance still teaches from this offering — the body carries the machine code `offering_in_use`", body = ErrorResponse),
367 ),
368)]
369async fn delete_offering(
370 State(st): State<AppState>,
371 RequireManager(_user): RequireManager,
372 Path(id): Path<String>,
373) -> Result<StatusCode, AppError> {
374 service::course_offering::delete(&st.db, &CourseOfferingId::from_key(&id)).await?;
375 Ok(StatusCode::NO_CONTENT)
376}