The non-teaching calendar over the API and the materialize route
Browse files at this commit3547dc5f13a33fa90cb3036635de8360975218ddParent: 7c481f7- feat
- the non-teaching calendar over the API and the materialize route
8 changed files +547 -26
- src/lib.rs +2 -0
- src/service/course_session.rs +13 -6
- src/web/holidays.rs +297 -0
- src/web/instances.rs +3 -2
- src/web/limits.rs +31 -1
- src/web/mod.rs +1 -0
- src/web/weekly_plan.rs +195 -16
- tests/integration.rs +5 -1
src/lib.rsmodified+2 -0
| @@ -86,6 +86,7 @@ use crate::web::module_gate::gate; | ||
| 86 | 86 | (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids — no course, session or appointment is involved — and every participant draws on it; the creator alone clears, locks, closes or deletes it. `GET /boards` takes `?open=true|false` to narrow the list by the closing stamp (`total` counts the filtered list) — a closed board is never deleted, so this is how a creator holding many boards trims the retired ones out of sight. It filters `closed_at` and nothing else: a **locked** board, and one that has spent its lifetime stroke budget but was never drawn on again, are both still open, because the stamp is written only by `/close` or by the append the lifetime cap refuses. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) — so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. Every frame the room delivers is authorized against the database first, so a caller who loses the right to be there — taken off the roster, or demoted below `student` — is served no further content: they get one `error{code:\"forbidden\"}` naming which of the two happened, and the room closes. That is separate from a refused *command*: `clear` and `lock` by a non-creator answer `error{code:\"forbidden\"}` and deliberately keep the socket open, since a participant who clicked the wrong button has made a mistake, not left the room. A demotion below `student` also sweeps that account off every roster it was on, and the rosters an older binary left behind were repaired at boot: a board written before that sweep can name a parent, or a user since deleted, and every such id is stripped the first time this binary starts. A board whose *creator* was demoted is **closed** by that same write: barred to them, still fully readable to everyone else, and refusing every write with the terminal `board_closed` — because clearing, locking, closing and deleting are the creator's alone and nothing lists a board the caller is not on, so a room whose creator was demoted could be ended by nobody at all while its participants kept drawing on it. Nothing is deleted (the marks are the participants' work too) and the seat it holds on `max_boards_per_creator` stays taken, exactly as a manually closed board's does. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored — `GET /boards/{id}/strokes` is the current epoch — drawn marks only, never a `clear` marker, exactly as the room's socket replays it, so the REST catch-up and the live canvas can never disagree, `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers (a clear needs at least one mark to close: an **already-blank** canvas answers `409` alongside the closed board and the **locked** one — the pause the creator set holds against their own clear too, so a locked board sitting at `max_epoch_strokes` is recovered by unlock, clear, relock — since the marker is a stored row charged to the lifetime cap), each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage — rows on the board, so a `clear` marker costs one unit like any mark, and a board holds at most `max_board_strokes + 1` rows because the marker closing the final stroke is never the one refused — and stamps `closed_at` on the way past — a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. Closing and locking are independent, and a board holding both flags answers **closed** everywhere — a stroke, a socket `clear` and `POST /boards/{id}/clear` all report the terminal state, never the pause, because the pause can never lift. `DELETE /boards/{id}` is the one operation here that really destroys marks — it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). `POST /boards/{id}/invite` fills that roster from a group that already exists rather than one id at a time — `{kind:\"class\", class}` for a class section (şube), `{kind:\"course\", course}` for a course's enrolled students (clubs and study groups *are* courses, so this is how a whole club is invited), `{kind:\"event\", event}` for an event's expected-attendee roster exactly as `GET /events/{id}/roster` resolves it. It is the creator's alone and strictly **additive** — nothing is ever removed by it, removal stays `PATCH` — and it resolves **once**, at the call: a board holds a flat list of ids and no memory of where they came from, so a student who joins that class tomorrow is not on today's board, and re-inviting the same source is how a roster is topped up (idempotent when nothing changed). Ineligible members are dropped silently rather than failing the call for everyone else — ids that no longer resolve to a user, and anyone below `student`, which is the same cut that keeps `parent` off a whiteboard — but the participant cap is **all-or-nothing**: an invite that would carry the board past `max_participants` is refused with a `409` naming both numbers, and nobody is added. Since a board's roster is visible to every participant, inviting a group *discloses* that group's membership, so each source carries the gate its own listing route already carries: teacher+ for a class, the course's creator/assigned teacher/manager+ for a course, teacher+ for an event. A student may still build a board one id at a time; they cannot pour a class roster into one. Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens — JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"), |
| 87 | 87 | (name = "academic-years", description = "The calendar above the dönemler. A year (`POST /academic-years`, manager+) holds the şubeler and the sınıf-geçme policy (`grade_promotions`) that `POST /academic-years/{id}/rollover` applies: each şube of the source year whose grade the target promotes is planted afresh there — same name, mapped grade, copies of its instances (same courses, `ders_saati`, karne policy), their assigned teachers and every live member, who are also enrolled into the new instances. A grade the policy does not name is not carried over: that is how graduation is expressed, and `graduated` reports it. The target year must still be empty (a second rollover into it is `409`, which is what makes the command idempotent), open, and different from the source. `POST /academic-years/{id}/archive` (manager+) closes a finished year — it stamps `archived_at`, and a second archive keeps the stamp that already stood — after which the year is read-only: no new şube, no new dönem, no new exam inside it, and no edit or delete of the year itself. A year still linked by any şube or dönem cannot be deleted (`409`). `GET` is teacher+, every write manager+."), |
| 88 | 88 | (name = "terms", description = "Academic terms (dönem: semester/trimester/quarter — whatever the school runs), each a grading slice **inside an academic year** (`year`, required; `GET /academic-years`). Exams name one — that is the dönem whose karne their marks count into — and `?term=` on `/marks/karne` picks one. A dönem still holding an exam or a frozen karne cannot be deleted (`409`). `POST /terms/{id}/archive` (manager+) **freezes the karnes**: every student with a roster row under the dönem's year gets a snapshot of their report, and from then on the karne route serves that record instead of recomputing, so a mark corrected later never rewrites what a family holds; `POST /terms/{id}/unarchive` re-opens it. Both are idempotent — a second archive answers 200 with the original stamp and never re-freezes. An archived dönem is read-only (`PATCH`/`DELETE` refused, no new exam); creating an exam inside it stays allowed while its *year* is open, because the archive is a record and not a wall. An archived **year** is what refuses new structure: şubeler, dönemler, and every write to either."), |
| 89 | + (name = "holidays", description = "The school-wide non-teaching calendar. A holiday is one named instant range (`starts_at`/`ends_at`, UTC unix-milliseconds, like every other dated resource here) and nothing else: no class, no course, no per-role audience — the whole school is out. `kind` is one of the fixed set (`resmi` official, `dini` religious, `idari` administrative, `ara` a break; `GET /limits` publishes them). Manager+ declares, edits and deletes; every authenticated user reads, because students need the calendar to make sense of their courses and their lessons. `GET /holidays?from=&to=` windows the list with **overlap** semantics — a holiday that merely reaches into the window is listed. The calendar's one workflow consumer is the weekly-plan materializer (`POST /instances/{id}/weekly-plan/materialize`): a day a holiday reaches into generates no lesson, and the dry run names it in `blocked`."), | |
| 89 | 90 | ), |
| 90 | 91 | )] |
| 91 | 92 | struct ApiDoc; |
| @@ -287,6 +288,7 @@ pub fn build_router(state: AppState) -> Router { | ||
| 287 | 288 | gate(web::homework::routes(), &state, Module::Homework), |
| 288 | 289 | ) |
| 289 | 290 | .nest("/terms", web::terms::routes()) |
| 291 | + .nest("/holidays", web::holidays::routes()) | |
| 290 | 292 | .nest( |
| 291 | 293 | "/boards", |
| 292 | 294 | gate(web::boards::routes(), &state, Module::Boards), |
src/service/course_session.rsmodified+13 -6
| @@ -178,16 +178,23 @@ pub async fn materialize( | ||
| 178 | 178 | // the generated rows are written on that same connection: a rival |
| 179 | 179 | // materialize run waits here instead of racing the existence read, and a |
| 180 | 180 | // refusal rolls back whatever it had collected. |
| 181 | + // Owned captures (`Send` rule of `tx_with_retry` closures): the closure may | |
| 182 | + // not hold a reference out of the caller's frame — a `&PgPool` or a | |
| 183 | + // `&ClassCourse` captured there fails the higher-ranked `Send` check the | |
| 184 | + // function's own future must pass, so no route could await it. `PgPool` is | |
| 185 | + // a cheap handle clone and the instance is one row. | |
| 186 | + let pool = db.clone(); | |
| 187 | + let instance = instance.clone(); | |
| 181 | 188 | tx_with_retry(db, false, async move |tx| { |
| 182 | 189 | // The archived-year wall every instance write passes: a past year is |
| 183 | 190 | // read-only, and this run mints lesson rows. |
| 184 | - crate::service::class_course::require_open(db, &instance_id).await?; | |
| 191 | + crate::service::class_course::require_open(&pool, &instance_id).await?; | |
| 185 | 192 | // The serialization point. `FOR NO KEY UPDATE` rather than |
| 186 | 193 | // `FOR UPDATE`: the batch insert below takes this same row's |
| 187 | 194 | // foreign-key `FOR KEY SHARE`, which `FOR UPDATE` would block on. |
| 188 | 195 | crate::db::weekly_slot::lock_class_tx(tx, &instance_id).await?; |
| 189 | 196 | |
| 190 | - let slots = crate::service::weekly_slot::resolved_for_instance(db, instance).await?; | |
| 197 | + let slots = crate::service::weekly_slot::resolved_for_instance(&pool, &instance).await?; | |
| 191 | 198 | if slots.is_empty() { |
| 192 | 199 | return Err(AppError::ConflictCoded { |
| 193 | 200 | code: "instance_has_no_weekly_plan", |
| @@ -195,7 +202,7 @@ pub async fn materialize( | ||
| 195 | 202 | }); |
| 196 | 203 | } |
| 197 | 204 | let teachers = |
| 198 | - crate::db::class_course_teacher::list_for_instance(db, &instance_id).await?; | |
| 205 | + crate::db::class_course_teacher::list_for_instance(&pool, &instance_id).await?; | |
| 199 | 206 | let Some(teacher) = teachers.first().copied() else { |
| 200 | 207 | return Err(AppError::ConflictCoded { |
| 201 | 208 | code: "instance_has_no_teacher", |
| @@ -207,7 +214,7 @@ pub async fn materialize( | ||
| 207 | 214 | // title second (the one display chain every surface rides), the |
| 208 | 215 | // literal `"Ders"` last. The resolved title is bounded by |
| 209 | 216 | // `MAX_COURSE_TITLE_LEN`, so it always fits a `SessionTopic`. |
| 210 | - let resolved = crate::service::instance_resolve::resolved_content(db, &[instance]).await?; | |
| 217 | + let resolved = crate::service::instance_resolve::resolved_content(&pool, &[&instance]).await?; | |
| 211 | 218 | let fallback_topic = resolved |
| 212 | 219 | .get(&instance_id.key()) |
| 213 | 220 | .map(|content| content.title.as_str()) |
| @@ -215,8 +222,8 @@ pub async fn materialize( | ||
| 215 | 222 | .and_then(|title| SessionTopic::try_new(title).ok()) |
| 216 | 223 | .unwrap_or(SessionTopic::try_new("Ders")?); |
| 217 | 224 | |
| 218 | - let holidays = crate::service::holiday::blocked_days(db, from, to).await?; | |
| 219 | - let existing = course_session::existing_starts(db, &instance_id).await?; | |
| 225 | + let holidays = crate::service::holiday::blocked_days(&pool, from, to).await?; | |
| 226 | + let existing = course_session::existing_starts(&pool, &instance_id).await?; | |
| 220 | 227 | |
| 221 | 228 | let mut rows: Vec<NewSession> = Vec::new(); |
| 222 | 229 | let mut blocked: Vec<BlockedDay> = Vec::new(); |
src/web/holidays.rsadded+297 -0
| @@ -0,0 +1,297 @@ | ||
| 1 | +//! The holiday calendar's HTTP surface: the school-wide non-teaching ranges | |
| 2 | +//! the weekly-plan materializer bounds its generation with. Plain CRUD — the | |
| 3 | +//! rows carry no refcounts and nothing else writes them — so every handler is | |
| 4 | +//! the same shape as `terms`': manager+ on the writes, any session on the | |
| 5 | +//! reads, an ungated nest because the calendar is school structure rather than | |
| 6 | +//! a per-role feature. | |
| 7 | +//! | |
| 8 | +//! `starts_at`/`ends_at` are **instants** (UTC unix milliseconds) exactly like | |
| 9 | +//! every other dated resource here; the list's `?from=&to=` bounds are | |
| 10 | +//! inclusive and use *overlap* semantics — a holiday that merely reaches into | |
| 11 | +//! the window is listed. | |
| 12 | + | |
| 13 | +use crate::web::tenant_state::State; | |
| 14 | +use axum::Json; | |
| 15 | +use axum::extract::{Path, Query}; | |
| 16 | +use axum::http::StatusCode; | |
| 17 | +use serde::{Deserialize, Serialize}; | |
| 18 | +use utoipa::{IntoParams, ToSchema}; | |
| 19 | +use utoipa_axum::router::OpenApiRouter; | |
| 20 | +use utoipa_axum::routes; | |
| 21 | + | |
| 22 | +use crate::db::holiday::HolidayPatch; | |
| 23 | +use crate::domain::holiday::{Holiday, HolidayId, HolidayKind, HolidayName}; | |
| 24 | +use crate::domain::timestamp::Timestamp; | |
| 25 | +use crate::error::{AppError, ErrorResponse}; | |
| 26 | +use crate::service; | |
| 27 | +use crate::state::AppState; | |
| 28 | + | |
| 29 | +use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, check_time_range, person_map}; | |
| 30 | + | |
| 31 | +pub fn routes() -> OpenApiRouter<AppState> { | |
| 32 | + OpenApiRouter::new() | |
| 33 | + .routes(routes!(create_holiday, list_holidays)) | |
| 34 | + .routes(routes!(get_holiday, update_holiday, delete_holiday)) | |
| 35 | +} | |
| 36 | + | |
| 37 | +#[derive(Deserialize, ToSchema)] | |
| 38 | +struct CreateHoliday { | |
| 39 | + /// The holiday's display name ("29 Ekim Cumhuriyet Bayramı"). | |
| 40 | + #[schema(example = "29 Ekim Cumhuriyet Bayramı", max_length = 100)] | |
| 41 | + name: String, | |
| 42 | + /// First blocked instant, UTC unix-milliseconds. | |
| 43 | + #[schema(example = 1_793_318_400_000_i64)] | |
| 44 | + starts_at: i64, | |
| 45 | + /// Last blocked instant, UTC unix-milliseconds; must not precede | |
| 46 | + /// `starts_at`. A single-day holiday sets both ends to that day's bounds. | |
| 47 | + #[schema(example = 1_793_404_800_000_i64)] | |
| 48 | + ends_at: i64, | |
| 49 | + /// Why the school is closed: one of `HOLIDAY_KINDS` (`GET /limits` | |
| 50 | + /// publishes them). | |
| 51 | + #[schema(example = "resmi")] | |
| 52 | + kind: String, | |
| 53 | +} | |
| 54 | + | |
| 55 | +#[derive(Deserialize, ToSchema)] | |
| 56 | +struct UpdateHoliday { | |
| 57 | + /// New name, held to the same bound as `POST` — the `HolidayName` newtype | |
| 58 | + /// re-checks it. No `maxLength` here: a published bound needs its own row | |
| 59 | + /// in the OpenAPI bounds table, and `CreateHoliday.name` already carries | |
| 60 | + /// this one. | |
| 61 | + name: Option<String>, | |
| 62 | + #[schema(example = 1_793_318_400_000_i64)] | |
| 63 | + starts_at: Option<i64>, | |
| 64 | + #[schema(example = 1_793_404_800_000_i64)] | |
| 65 | + ends_at: Option<i64>, | |
| 66 | + #[schema(example = "idari")] | |
| 67 | + kind: Option<String>, | |
| 68 | +} | |
| 69 | + | |
| 70 | +#[derive(Serialize, ToSchema)] | |
| 71 | +struct HolidayResponse { | |
| 72 | + id: String, | |
| 73 | + #[schema(example = "29 Ekim Cumhuriyet Bayramı")] | |
| 74 | + name: String, | |
| 75 | + /// First blocked instant, UTC unix-milliseconds. | |
| 76 | + starts_at: i64, | |
| 77 | + /// Last blocked instant, UTC unix-milliseconds. | |
| 78 | + ends_at: i64, | |
| 79 | + #[schema(example = "resmi")] | |
| 80 | + kind: String, | |
| 81 | + /// The manager who declared the holiday (`GET /users/{id}`). | |
| 82 | + creator: PersonRef, | |
| 83 | + /// Declared at, UTC unix-milliseconds. | |
| 84 | + created_at: i64, | |
| 85 | +} | |
| 86 | + | |
| 87 | +impl HolidayResponse { | |
| 88 | + fn new(holiday: &Holiday, people: &std::collections::HashMap<String, PersonRef>) -> Self { | |
| 89 | + Self { | |
| 90 | + id: holiday.get_id().key().to_string(), | |
| 91 | + name: holiday.get_name().as_str().to_string(), | |
| 92 | + starts_at: holiday.get_starts_at().as_millis(), | |
| 93 | + ends_at: holiday.get_ends_at().as_millis(), | |
| 94 | + kind: holiday.get_kind().as_str().to_string(), | |
| 95 | + creator: PersonRef::resolve(people, holiday.get_creator()), | |
| 96 | + created_at: holiday.get_created_at().as_millis(), | |
| 97 | + } | |
| 98 | + } | |
| 99 | +} | |
| 100 | + | |
| 101 | +/// Inclusive instant bounds on `GET /holidays`. Either may be omitted; a | |
| 102 | +/// holiday is listed when it *reaches into* the window, not only when it lies | |
| 103 | +/// entirely inside it. | |
| 104 | +#[derive(Debug, Deserialize, IntoParams)] | |
| 105 | +struct HolidayRange { | |
| 106 | + /// Keep holidays reaching at or after this instant, unix-milliseconds. | |
| 107 | + #[param(example = 1_793_318_400_000_i64)] | |
| 108 | + from: Option<i64>, | |
| 109 | + /// Keep holidays reaching at or before this instant, unix-milliseconds. | |
| 110 | + #[param(example = 1_793_404_800_000_i64)] | |
| 111 | + to: Option<i64>, | |
| 112 | +} | |
| 113 | + | |
| 114 | +/// Every holiday the request named — the join half of the responses below. | |
| 115 | +async fn people_of( | |
| 116 | + holidays: &[Holiday], | |
| 117 | + db: &crate::database::Database, | |
| 118 | +) -> Result<std::collections::HashMap<String, PersonRef>, AppError> { | |
| 119 | + person_map(holidays.iter().map(|holiday| *holiday.get_creator()), db).await | |
| 120 | +} | |
| 121 | + | |
| 122 | +/// Declare a school-wide holiday. Requires manager+. Past dates are allowed — | |
| 123 | +/// the calendar is a record, and a school adopting the app mid-year backfills | |
| 124 | +/// it legitimately. | |
| 125 | +#[utoipa::path( | |
| 126 | + post, | |
| 127 | + path = "/", | |
| 128 | + tag = "holidays", | |
| 129 | + security(("session_cookie" = [])), | |
| 130 | + request_body = CreateHoliday, | |
| 131 | + responses( | |
| 132 | + (status = 201, description = "Holiday declared", body = HolidayResponse), | |
| 133 | + (status = 400, description = "Invalid name, kind, or range", body = ErrorResponse), | |
| 134 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 135 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | |
| 136 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | |
| 137 | + ), | |
| 138 | +)] | |
| 139 | +async fn create_holiday( | |
| 140 | + State(st): State<AppState>, | |
| 141 | + RequireManager(user): RequireManager, | |
| 142 | + Json(req): Json<CreateHoliday>, | |
| 143 | +) -> Result<(StatusCode, Json<HolidayResponse>), AppError> { | |
| 144 | + let name = HolidayName::try_new(&req.name)?; | |
| 145 | + let kind = HolidayKind::try_new(&req.kind)?; | |
| 146 | + let starts_at = Timestamp::from_millis(req.starts_at); | |
| 147 | + let ends_at = Timestamp::from_millis(req.ends_at); | |
| 148 | + check_time_range(Some(starts_at), Some(ends_at))?; | |
| 149 | + let holiday = service::holiday::create( | |
| 150 | + &st.db, | |
| 151 | + &name, | |
| 152 | + starts_at, | |
| 153 | + ends_at, | |
| 154 | + &kind, | |
| 155 | + user.get_id(), | |
| 156 | + ) | |
| 157 | + .await?; | |
| 158 | + // The creator is the caller — already loaded, no extra lookup. | |
| 159 | + let people = PersonRef::map_of(&[&user]); | |
| 160 | + Ok(( | |
| 161 | + StatusCode::CREATED, | |
| 162 | + Json(HolidayResponse::new(&holiday, &people)), | |
| 163 | + )) | |
| 164 | +} | |
| 165 | + | |
| 166 | +/// List the calendar, newest start first. Any authenticated user — students | |
| 167 | +/// need the calendar to make sense of their courses. Paged via | |
| 168 | +/// `?limit=&offset=` (omit `limit` for the full list), optionally windowed by | |
| 169 | +/// `?from=&to=`; returns a `{items, total, limit, offset}` envelope. | |
| 170 | +#[utoipa::path( | |
| 171 | + get, | |
| 172 | + path = "/", | |
| 173 | + tag = "holidays", | |
| 174 | + security(("session_cookie" = [])), | |
| 175 | + params(HolidayRange, PageParams), | |
| 176 | + responses( | |
| 177 | + (status = 200, description = "A page of holidays (the full list when unpaged)", body = Page<HolidayResponse>), | |
| 178 | + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | |
| 179 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 180 | + ), | |
| 181 | +)] | |
| 182 | +async fn list_holidays( | |
| 183 | + State(st): State<AppState>, | |
| 184 | + CurrentUser(_user): CurrentUser, | |
| 185 | + Query(range): Query<HolidayRange>, | |
| 186 | + Query(page): Query<PageParams>, | |
| 187 | +) -> Result<Json<Page<HolidayResponse>>, AppError> { | |
| 188 | + let (limit, offset) = page.resolve()?; | |
| 189 | + let (holidays, total) = service::holiday::list( | |
| 190 | + &st.db, | |
| 191 | + range.from.map(Timestamp::from_millis), | |
| 192 | + range.to.map(Timestamp::from_millis), | |
| 193 | + limit, | |
| 194 | + offset, | |
| 195 | + ) | |
| 196 | + .await?; | |
| 197 | + let people = people_of(&holidays, &st.db).await?; | |
| 198 | + let items = holidays | |
| 199 | + .iter() | |
| 200 | + .map(|holiday| HolidayResponse::new(holiday, &people)) | |
| 201 | + .collect(); | |
| 202 | + Ok(Json(Page::new(items, total, limit, offset))) | |
| 203 | +} | |
| 204 | + | |
| 205 | +/// Fetch a single holiday by id. | |
| 206 | +#[utoipa::path( | |
| 207 | + get, | |
| 208 | + path = "/{id}", | |
| 209 | + tag = "holidays", | |
| 210 | + security(("session_cookie" = [])), | |
| 211 | + params(("id" = String, Path, description = "Holiday id")), | |
| 212 | + responses( | |
| 213 | + (status = 200, description = "The holiday", body = HolidayResponse), | |
| 214 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 215 | + (status = 404, description = "Not found", body = ErrorResponse), | |
| 216 | + ), | |
| 217 | +)] | |
| 218 | +async fn get_holiday( | |
| 219 | + State(st): State<AppState>, | |
| 220 | + CurrentUser(_user): CurrentUser, | |
| 221 | + Path(id): Path<String>, | |
| 222 | +) -> Result<Json<HolidayResponse>, AppError> { | |
| 223 | + let holiday = service::holiday::read(&st.db, &HolidayId::from_key(&id)).await?; | |
| 224 | + let people = people_of(std::slice::from_ref(&holiday), &st.db).await?; | |
| 225 | + Ok(Json(HolidayResponse::new(&holiday, &people))) | |
| 226 | +} | |
| 227 | + | |
| 228 | +/// Update a holiday. Requires manager+. Omitted fields keep their value; the | |
| 229 | +/// merged range must stay ordered. A holiday is a *record* of the calendar, | |
| 230 | +/// so a past range is editable like a future one. | |
| 231 | +#[utoipa::path( | |
| 232 | + patch, | |
| 233 | + path = "/{id}", | |
| 234 | + tag = "holidays", | |
| 235 | + security(("session_cookie" = [])), | |
| 236 | + params(("id" = String, Path, description = "Holiday id")), | |
| 237 | + request_body = UpdateHoliday, | |
| 238 | + responses( | |
| 239 | + (status = 200, description = "Updated holiday", body = HolidayResponse), | |
| 240 | + (status = 400, description = "Invalid name, kind, or range", body = ErrorResponse), | |
| 241 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 242 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | |
| 243 | + (status = 404, description = "Not found", body = ErrorResponse), | |
| 244 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | |
| 245 | + ), | |
| 246 | +)] | |
| 247 | +async fn update_holiday( | |
| 248 | + State(st): State<AppState>, | |
| 249 | + RequireManager(_user): RequireManager, | |
| 250 | + Path(id): Path<String>, | |
| 251 | + Json(req): Json<UpdateHoliday>, | |
| 252 | +) -> Result<Json<HolidayResponse>, AppError> { | |
| 253 | + let name = req.name.as_deref().map(HolidayName::try_new).transpose()?; | |
| 254 | + let kind = req.kind.as_deref().map(HolidayKind::try_new).transpose()?; | |
| 255 | + let starts_at = req.starts_at.map(Timestamp::from_millis); | |
| 256 | + let ends_at = req.ends_at.map(Timestamp::from_millis); | |
| 257 | + // Pre-flight only: the merged range is re-checked inside the UPDATE's own | |
| 258 | + // `WHERE` (the holiday update in the db layer), so a concurrent move of | |
| 259 | + // the end this PATCH omits cannot slip an inverted range past this | |
| 260 | + // snapshot. | |
| 261 | + check_time_range(starts_at, ends_at)?; | |
| 262 | + | |
| 263 | + let patch = HolidayPatch { | |
| 264 | + name, | |
| 265 | + starts_at, | |
| 266 | + ends_at, | |
| 267 | + kind, | |
| 268 | + }; | |
| 269 | + let holiday = service::holiday::update(&st.db, &HolidayId::from_key(&id), patch).await?; | |
| 270 | + let people = people_of(std::slice::from_ref(&holiday), &st.db).await?; | |
| 271 | + Ok(Json(HolidayResponse::new(&holiday, &people))) | |
| 272 | +} | |
| 273 | + | |
| 274 | +/// Delete a holiday. Requires manager+. Nothing references a holiday — the | |
| 275 | +/// materializer only *reads* the calendar — so the delete is unconditional and | |
| 276 | +/// the lessons already generated on those days stay where they are. | |
| 277 | +#[utoipa::path( | |
| 278 | + delete, | |
| 279 | + path = "/{id}", | |
| 280 | + tag = "holidays", | |
| 281 | + security(("session_cookie" = [])), | |
| 282 | + params(("id" = String, Path, description = "Holiday id")), | |
| 283 | + responses( | |
| 284 | + (status = 204, description = "Deleted"), | |
| 285 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 286 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | |
| 287 | + (status = 404, description = "Not found", body = ErrorResponse), | |
| 288 | + ), | |
| 289 | +)] | |
| 290 | +async fn delete_holiday( | |
| 291 | + State(st): State<AppState>, | |
| 292 | + RequireManager(_user): RequireManager, | |
| 293 | + Path(id): Path<String>, | |
| 294 | +) -> Result<StatusCode, AppError> { | |
| 295 | + service::holiday::delete(&st.db, &HolidayId::from_key(&id)).await?; | |
| 296 | + Ok(StatusCode::NO_CONTENT) | |
| 297 | +} |
src/web/instances.rsmodified+3 -2
| @@ -270,8 +270,9 @@ pub struct InstanceResponse { | ||
| 270 | 270 | /// The section's **resolved** weekly plan: its own `class_course_slot` |
| 271 | 271 | /// rows when the flag above is `false` — including when that set is |
| 272 | 272 | /// empty — the offering's `offering_slot` template week when `true`. |
| 273 | - /// Weekday first, then start time. Template data a timetable renders; | |
| 274 | - /// nothing generates dated `course_session` rows from it. | |
| 273 | + /// Weekday first, then start time. Template data a timetable renders; no | |
| 274 | + /// dated `course_session` rows come from it until a caller asks | |
| 275 | + /// (`POST /instances/{id}/weekly-plan/materialize`). | |
| 275 | 276 | pub weekly_plan: Vec<WeeklySlotDto>, |
| 276 | 277 | /// How many students are enrolled right now. |
| 277 | 278 | #[schema(example = 28)] |
src/web/limits.rsmodified+31 -1
| @@ -195,9 +195,14 @@ struct CourseLimits { | ||
| 195 | 195 | max_ders_saati: i64, |
| 196 | 196 | /// An academic year's name (`POST /academic-years`). |
| 197 | 197 | max_academic_year_name_len: usize, |
| 198 | + /// How many sections one catalogue course row embeds in `sections`. A | |
| 199 | + /// course taught in more still lists them at `/instances`; the row's | |
| 200 | + /// `class_course_count` carries the untruncated total. | |
| 201 | + max_course_sections: usize, | |
| 198 | 202 | } |
| 199 | 203 | |
| 200 | -/// The weekly plan: one offering's (or one section's) timetable template. | |
| 204 | +/// The weekly plan: one offering's (or one section's) timetable template, and | |
| 205 | +/// the one call that expands it into dated lessons. | |
| 201 | 206 | #[derive(Serialize, ToSchema)] |
| 202 | 207 | struct WeeklyPlanLimits { |
| 203 | 208 | /// Inclusive bounds for a slot's `starts_at`/`ends_at` minutes past |
| @@ -206,6 +211,21 @@ struct WeeklyPlanLimits { | ||
| 206 | 211 | max_slot_minute: i64, |
| 207 | 212 | /// Slots one weekly plan may hold. |
| 208 | 213 | max_weekly_slots: i64, |
| 214 | + /// Longest `from`–`to` span one `POST /instances/{id}/weekly-plan/ | |
| 215 | + /// materialize` call may cover, days. | |
| 216 | + max_materialize_days: i64, | |
| 217 | + /// Most lessons one materialize call may write. | |
| 218 | + max_materialize_sessions: usize, | |
| 219 | +} | |
| 220 | + | |
| 221 | +/// The school-wide non-teaching calendar. | |
| 222 | +#[derive(Serialize, ToSchema)] | |
| 223 | +struct HolidayLimits { | |
| 224 | + /// The holiday's display name. | |
| 225 | + max_name_len: usize, | |
| 226 | + /// The only accepted `kind` values. | |
| 227 | + #[schema(example = json!(["resmi", "dini", "idari", "ara"]))] | |
| 228 | + kinds: Vec<&'static str>, | |
| 209 | 229 | } |
| 210 | 230 | |
| 211 | 231 | /// Exams, their questions, answers, and marks. |
| @@ -528,6 +548,9 @@ struct LimitsResponse { | ||
| 528 | 548 | file: FileLimits, |
| 529 | 549 | message: MessageLimits, |
| 530 | 550 | event: EventLimits, |
| 551 | + /// The school-wide non-teaching calendar the materializer bounds its | |
| 552 | + /// generation with. | |
| 553 | + holiday: HolidayLimits, | |
| 531 | 554 | course: CourseLimits, |
| 532 | 555 | /// The weekly plan's timetable bounds (`/offerings/{id}/weekly-plan` and |
| 533 | 556 | /// the instance override doors). |
| @@ -610,6 +633,10 @@ impl LimitsResponse { | ||
| 610 | 633 | max_title_len: MAX_EVENT_TITLE_LEN, |
| 611 | 634 | max_description_len: MAX_EVENT_DESCRIPTION_LEN, |
| 612 | 635 | }, |
| 636 | + holiday: HolidayLimits { | |
| 637 | + max_name_len: MAX_HOLIDAY_NAME_LEN, | |
| 638 | + kinds: HOLIDAY_KINDS.to_vec(), | |
| 639 | + }, | |
| 613 | 640 | course: CourseLimits { |
| 614 | 641 | max_title_len: MAX_COURSE_TITLE_LEN, |
| 615 | 642 | max_description_len: MAX_COURSE_DESCRIPTION_LEN, |
| @@ -626,11 +653,14 @@ impl LimitsResponse { | ||
| 626 | 653 | min_ders_saati: MIN_DERS_SAATI, |
| 627 | 654 | max_ders_saati: MAX_DERS_SAATI, |
| 628 | 655 | max_academic_year_name_len: MAX_ACADEMIC_YEAR_NAME_LEN, |
| 656 | + max_course_sections: MAX_COURSE_SECTIONS, | |
| 629 | 657 | }, |
| 630 | 658 | weekly_plan: WeeklyPlanLimits { |
| 631 | 659 | min_slot_minute: MIN_SLOT_MINUTE, |
| 632 | 660 | max_slot_minute: MAX_SLOT_MINUTE, |
| 633 | 661 | max_weekly_slots: MAX_WEEKLY_SLOTS as i64, |
| 662 | + max_materialize_days: MAX_MATERIALIZE_DAYS, | |
| 663 | + max_materialize_sessions: MAX_MATERIALIZE_SESSIONS, | |
| 634 | 664 | }, |
| 635 | 665 | exam: ExamLimits { |
| 636 | 666 | max_title_len: MAX_EXAM_TITLE_LEN, |
src/web/mod.rsmodified+1 -0
| @@ -22,6 +22,7 @@ pub mod exam_weights; | ||
| 22 | 22 | pub mod exam_ws; |
| 23 | 23 | pub mod exams; |
| 24 | 24 | pub mod homework; |
| 25 | +pub mod holidays; | |
| 25 | 26 | pub mod insights; |
| 26 | 27 | pub mod instances; |
| 27 | 28 | pub mod limits; |
src/web/weekly_plan.rsmodified+195 -16
| @@ -6,17 +6,22 @@ | ||
| 6 | 6 | //! `/instances`) so each carries its own module's gate. |
| 7 | 7 | //! |
| 8 | 8 | //! A slot is one weekday plus a minutes-past-midnight window (`1` = Monday |
| 9 | -//! through `7` = Sunday, `540` = 09:00). Two slots of one owner may touch but | |
| 10 | -//! never overlap (409 `slot_overlap`); a plan holds at most | |
| 9 | +//! through `7` = Sunday, `540` = 09:00), and may carry an optional lesson | |
| 10 | +//! topic. Two slots of one owner may touch but never overlap (409 | |
| 11 | +//! `slot_overlap`); a plan holds at most | |
| 11 | 12 | //! [`crate::constant::MAX_WEEKLY_SLOTS`] slots (409 `slot_cap`). |
| 12 | 13 | //! Writing any instance-side row flips `weekly_plan_inherited` to `false` in |
| 13 | 14 | //! the same statement, and `DELETE /instances/{id}/weekly-plan` (no slot id) |
| 14 | 15 | //! is the reset back to inherit — the resolved reads never merge the two |
| 15 | 16 | //! sets. |
| 16 | 17 | //! |
| 17 | -//! **No scheduler.** Nothing generates dated `course_session` rows from a | |
| 18 | -//! weekly plan — `course_session` stays the per-lesson occurrence, written by | |
| 19 | -//! its own routes. These routes serve template + override + resolution only. | |
| 18 | +//! **No scheduler** — but one explicit door: `POST | |
| 19 | +//! /instances/{id}/weekly-plan/materialize` expands the section's *resolved* | |
| 20 | +//! plan into dated `course_session` rows over a range, dry-run first and | |
| 21 | +//! bounded by the school's holiday calendar | |
| 22 | +//! ([`crate::service::course_session::materialize`]). Nothing generates | |
| 23 | +//! lessons on its own; a caller asks, and a second ask over the same range | |
| 24 | +//! writes nothing new. | |
| 20 | 25 | |
| 21 | 26 | use axum::Json; |
| 22 | 27 | use axum::extract::Path; |
| @@ -27,8 +32,11 @@ use utoipa_axum::router::OpenApiRouter; | ||
| 27 | 32 | use utoipa_axum::routes; |
| 28 | 33 | |
| 29 | 34 | use crate::database::Database; |
| 35 | +use crate::domain::calendar::zone_offset_minutes; | |
| 30 | 36 | use crate::domain::class_course::{ClassCourse, ClassCourseId}; |
| 31 | 37 | use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; |
| 38 | +use crate::domain::course_session::SessionTopic; | |
| 39 | +use crate::domain::timestamp::Timestamp; | |
| 32 | 40 | use crate::domain::weekly_slot::{SlotMinute, Weekday, WeeklySlot, WeeklySlotId}; |
| 33 | 41 | use crate::error::{AppError, ErrorResponse}; |
| 34 | 42 | use crate::service; |
| @@ -36,7 +44,10 @@ use crate::state::AppState; | ||
| 36 | 44 | use crate::web::tenant_state::State; |
| 37 | 45 | |
| 38 | 46 | use super::instances::can_view_instance; |
| 39 | -use super::{CurrentUser, RequireManager, RequireTeacher}; | |
| 47 | +use super::{ | |
| 48 | + CurrentUser, RequireManager, RequireTeacher, SessionResponse, check_not_past, check_time_range, | |
| 49 | + person_map, | |
| 50 | +}; | |
| 40 | 51 | |
| 41 | 52 | /// The route set mounted under `/offerings` (relative paths): the template |
| 42 | 53 | /// week's reads and the office's writes. |
| @@ -55,18 +66,29 @@ pub fn instance_routes() -> OpenApiRouter<AppState> { | ||
| 55 | 66 | .routes(routes!(list_instance_weekly_plan, add_instance_slot)) |
| 56 | 67 | .routes(routes!(remove_instance_slot)) |
| 57 | 68 | .routes(routes!(reset_instance_weekly_plan)) |
| 69 | + .routes(routes!(materialize_weekly_plan)) | |
| 58 | 70 | } |
| 59 | 71 | |
| 60 | -/// A weekly plan line the caller sent: the ISO weekday and the two | |
| 61 | -/// minutes-past-midnight bounds of the lesson window. | |
| 72 | +/// A weekly plan line the caller sent: the ISO weekday, the two | |
| 73 | +/// minutes-past-midnight bounds of the lesson window, and the optional topic | |
| 74 | +/// every lesson generated from it is stamped with. | |
| 62 | 75 | #[derive(Deserialize, ToSchema)] |
| 63 | 76 | struct CreateSlot { |
| 64 | 77 | /// `1` = Monday through `7` = Sunday. |
| 78 | + #[schema(example = 1)] | |
| 65 | 79 | weekday: i16, |
| 66 | 80 | /// Minutes past midnight (`540` = 09:00) — the window opens here. |
| 81 | + #[schema(example = 540)] | |
| 67 | 82 | starts_at: i64, |
| 68 | 83 | /// Minutes past midnight — strictly after `starts_at`. |
| 84 | + #[schema(example = 600)] | |
| 69 | 85 | ends_at: i64, |
| 86 | + /// What this line's lessons are about. The materializer stamps it onto | |
| 87 | + /// every lesson it generates from this slot; omit it and a generated | |
| 88 | + /// lesson takes the instance's resolved course title instead (then the | |
| 89 | + /// literal `"Ders"`). | |
| 90 | + #[schema(example = "Üslü sayılar", max_length = 200)] | |
| 91 | + topic: Option<String>, | |
| 70 | 92 | } |
| 71 | 93 | |
| 72 | 94 | /// Public shape of one weekly plan slot. Times stay the minutes-past-midnight |
| @@ -80,6 +102,9 @@ pub struct WeeklySlotDto { | ||
| 80 | 102 | pub starts_at: i64, |
| 81 | 103 | /// Minutes past midnight, strictly after `starts_at`. |
| 82 | 104 | pub ends_at: i64, |
| 105 | + /// The topic this line's generated lessons carry; `null` = fall back to | |
| 106 | + /// the instance's resolved title. | |
| 107 | + pub topic: Option<String>, | |
| 83 | 108 | } |
| 84 | 109 | |
| 85 | 110 | impl WeeklySlotDto { |
| @@ -89,6 +114,7 @@ impl WeeklySlotDto { | ||
| 89 | 114 | weekday: slot.get_weekday().get(), |
| 90 | 115 | starts_at: slot.get_starts_at().get(), |
| 91 | 116 | ends_at: slot.get_ends_at().get(), |
| 117 | + topic: slot.get_topic().map(|topic| topic.as_str().to_string()), | |
| 92 | 118 | } |
| 93 | 119 | } |
| 94 | 120 | } |
| @@ -120,14 +146,19 @@ async fn instance_or_404(key: &str, db: &Database) -> Result<ClassCourse, AppErr | ||
| 120 | 146 | } |
| 121 | 147 | |
| 122 | 148 | /// The body's slot, range-checked before anything is written: weekday and |
| 123 | -/// minute bounds here, the non-empty window inside the domain `WeeklySlot`. | |
| 149 | +/// minute bounds here, the non-empty window inside the domain `WeeklySlot`, | |
| 150 | +/// and the optional topic through its own newtype. | |
| 124 | 151 | fn parse_slot( |
| 125 | 152 | req: &CreateSlot, |
| 126 | -) -> Result<(Weekday, SlotMinute, SlotMinute), crate::error::ValidationError> { | |
| 153 | +) -> Result<(Weekday, SlotMinute, SlotMinute, Option<SessionTopic>), crate::error::ValidationError> { | |
| 127 | 154 | Ok(( |
| 128 | 155 | Weekday::new(req.weekday)?, |
| 129 | 156 | SlotMinute::new(req.starts_at)?, |
| 130 | 157 | SlotMinute::new(req.ends_at)?, |
| 158 | + req.topic | |
| 159 | + .as_deref() | |
| 160 | + .map(SessionTopic::try_new) | |
| 161 | + .transpose()?, | |
| 131 | 162 | )) |
| 132 | 163 | } |
| 133 | 164 | |
| @@ -168,7 +199,7 @@ async fn list_offering_weekly_plan( | ||
| 168 | 199 | request_body = CreateSlot, |
| 169 | 200 | responses( |
| 170 | 201 | (status = 201, description = "Slot added", body = WeeklySlotDto), |
| 171 | - (status = 400, description = "Invalid weekday or minutes, or an empty window", body = ErrorResponse), | |
| 202 | + (status = 400, description = "Invalid weekday or minutes, an empty window, or an over-long topic", body = ErrorResponse), | |
| 172 | 203 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 173 | 204 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 174 | 205 | (status = 404, description = "Offering not found", body = ErrorResponse), |
| @@ -183,14 +214,14 @@ async fn add_offering_slot( | ||
| 183 | 214 | Json(req): Json<CreateSlot>, |
| 184 | 215 | ) -> Result<(StatusCode, Json<WeeklySlotDto>), AppError> { |
| 185 | 216 | let offering = offering_or_404(&id, &st.db).await?; |
| 186 | - let (weekday, starts_at, ends_at) = parse_slot(&req)?; | |
| 217 | + let (weekday, starts_at, ends_at, topic) = parse_slot(&req)?; | |
| 187 | 218 | let slot = service::weekly_slot::add_for_offering( |
| 188 | 219 | &st.db, |
| 189 | 220 | offering.get_id(), |
| 190 | 221 | weekday, |
| 191 | 222 | starts_at, |
| 192 | 223 | ends_at, |
| 193 | - None, | |
| 224 | + topic, | |
| 194 | 225 | ) |
| 195 | 226 | .await?; |
| 196 | 227 | Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot)))) |
| @@ -277,7 +308,7 @@ async fn list_instance_weekly_plan( | ||
| 277 | 308 | request_body = CreateSlot, |
| 278 | 309 | responses( |
| 279 | 310 | (status = 201, description = "Slot added; the section now overrides the template", body = WeeklySlotDto), |
| 280 | - (status = 400, description = "Invalid weekday or minutes, or an empty window", body = ErrorResponse), | |
| 311 | + (status = 400, description = "Invalid weekday or minutes, an empty window, or an over-long topic", body = ErrorResponse), | |
| 281 | 312 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 282 | 313 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 283 | 314 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| @@ -294,7 +325,7 @@ async fn add_instance_slot( | ||
| 294 | 325 | let instance = instance_or_404(&id, &st.db).await?; |
| 295 | 326 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 296 | 327 | service::class_course::require_open(&st.db, instance.get_id()).await?; |
| 297 | - let (weekday, starts_at, ends_at) = parse_slot(&req)?; | |
| 328 | + let (weekday, starts_at, ends_at, topic) = parse_slot(&req)?; | |
| 298 | 329 | let slot = |
| 299 | 330 | service::weekly_slot::add_for_class( |
| 300 | 331 | &st.db, |
| @@ -302,7 +333,7 @@ async fn add_instance_slot( | ||
| 302 | 333 | weekday, |
| 303 | 334 | starts_at, |
| 304 | 335 | ends_at, |
| 305 | - None, | |
| 336 | + topic, | |
| 306 | 337 | ) |
| 307 | 338 | .await?; |
| 308 | 339 | Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot)))) |
| @@ -377,3 +408,151 @@ async fn reset_instance_weekly_plan( | ||
| 377 | 408 | service::weekly_slot::reset_for_class(&st.db, instance.get_id()).await?; |
| 378 | 409 | Ok(StatusCode::NO_CONTENT) |
| 379 | 410 | } |
| 411 | + | |
| 412 | +// ---- materialize: the plan, made real ---------------------------------------- | |
| 413 | + | |
| 414 | +/// One materialize call: the range to cover, and whether to write. | |
| 415 | +#[derive(Deserialize, ToSchema)] | |
| 416 | +struct MaterializeRequest { | |
| 417 | + /// First instant to generate lessons from, UTC unix-milliseconds. The | |
| 418 | + /// instant names a *school* day (the school's timezone), so a late-evening | |
| 419 | + /// UTC instant is the next Turkish day. | |
| 420 | + #[schema(example = 1_793_318_400_000_i64)] | |
| 421 | + from: i64, | |
| 422 | + /// Last instant to generate lessons through, UTC unix-milliseconds; must | |
| 423 | + /// not precede `from`, and the span between the two may not exceed | |
| 424 | + /// `max_materialize_days` (`GET /limits`). | |
| 425 | + #[schema(example = 1_794_873_600_000_i64)] | |
| 426 | + to: i64, | |
| 427 | + /// `false` (the default) is a **dry run**: it reads, decides, and writes | |
| 428 | + /// nothing, so a client shows the outcome before committing. `true` writes | |
| 429 | + /// the lessons and answers with the rows that landed. | |
| 430 | + #[serde(default)] | |
| 431 | + #[schema(example = false)] | |
| 432 | + apply: bool, | |
| 433 | +} | |
| 434 | + | |
| 435 | +/// One non-teaching day the range reached into. | |
| 436 | +#[derive(Serialize, ToSchema)] | |
| 437 | +struct BlockedDayResponse { | |
| 438 | + /// The calendar day, `YYYY-MM-DD`, in the school's timezone. | |
| 439 | + #[schema(example = "2026-10-29")] | |
| 440 | + date: String, | |
| 441 | + /// The holiday blocking it (`GET /holidays`). | |
| 442 | + #[schema(example = "29 Ekim Cumhuriyet Bayramı")] | |
| 443 | + holiday: String, | |
| 444 | +} | |
| 445 | + | |
| 446 | +/// What one materialize call did — or, on a dry run, would have done. | |
| 447 | +#[derive(Serialize, ToSchema)] | |
| 448 | +struct MaterializeReport { | |
| 449 | + /// The range the call covered, UTC unix-milliseconds. | |
| 450 | + from: i64, | |
| 451 | + to: i64, | |
| 452 | + /// Whether the call wrote: `false` for a dry run. | |
| 453 | + applied: bool, | |
| 454 | + /// The resolved weekly plan's size — the lines the range was expanded | |
| 455 | + /// from. | |
| 456 | + slots: usize, | |
| 457 | + /// How many lessons the range *asked* for, before the holidays and the | |
| 458 | + /// instants the section already holds were subtracted. | |
| 459 | + candidates: usize, | |
| 460 | + /// The rows the database actually inserted, empty on a dry run. Same shape | |
| 461 | + /// as a hand-created lesson (`POST /instances/{id}/sessions`). | |
| 462 | + created: Vec<SessionResponse>, | |
| 463 | + /// Candidate instants the section already had a lesson at. | |
| 464 | + skipped_existing: usize, | |
| 465 | + /// Days a holiday reached into — one `blocked` entry each; a day counted | |
| 466 | + /// here produces no lesson at all. | |
| 467 | + skipped_holiday: usize, | |
| 468 | + blocked: Vec<BlockedDayResponse>, | |
| 469 | + /// How many days the range spanned, inclusive. | |
| 470 | + range_days: i64, | |
| 471 | +} | |
| 472 | + | |
| 473 | +/// Expand this section's **resolved** weekly plan into dated lessons over | |
| 474 | +/// `from`–`to`. Requires teacher+ and a right over the instance (the same door | |
| 475 | +/// as adding a slot, since this writes lessons). | |
| 476 | +/// | |
| 477 | +/// Nothing is ever deleted or updated: the call is additive, and a second call | |
| 478 | +/// over the same range writes nothing (`UNIQUE (class_course, starts_at)`), so | |
| 479 | +/// retrying after a failure is safe. A weekday the plan has no slot for | |
| 480 | +/// produces nothing, and so does every day a holiday reaches into — those days | |
| 481 | +/// are named in `blocked`. Weekends are *not* special-cased: a school may run | |
| 482 | +/// Saturday, so only the plan and the calendar decide. | |
| 483 | +/// | |
| 484 | +/// The generated lesson's teacher is the instance's **first assigned** | |
| 485 | +/// teacher, and its topic is the slot's own topic, else the instance's | |
| 486 | +/// resolved course title, else the literal `"Ders"`. | |
| 487 | +#[utoipa::path( | |
| 488 | + post, | |
| 489 | + path = "/{id}/weekly-plan/materialize", | |
| 490 | + tag = "instances", | |
| 491 | + security(("session_cookie" = [])), | |
| 492 | + params(("id" = String, Path, description = "Instance id")), | |
| 493 | + request_body = MaterializeRequest, | |
| 494 | + responses( | |
| 495 | + (status = 200, description = "What the call did, or would do on a dry run", body = MaterializeReport), | |
| 496 | + (status = 400, description = "The range is inverted, lies in the past, spans more than a year, or would create more than `max_materialize_sessions` lessons", body = ErrorResponse), | |
| 497 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 498 | + (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), | |
| 499 | + (status = 404, description = "Instance not found", body = ErrorResponse), | |
| 500 | + (status = 409, description = "This instance's academic year is archived; the section's weekly plan is empty (`instance_has_no_weekly_plan`); or no teacher is assigned to it (`instance_has_no_teacher`)", body = ErrorResponse), | |
| 501 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | |
| 502 | + ), | |
| 503 | +)] | |
| 504 | +async fn materialize_weekly_plan( | |
| 505 | + State(st): State<AppState>, | |
| 506 | + RequireTeacher(user): RequireTeacher, | |
| 507 | + Path(id): Path<String>, | |
| 508 | + Json(req): Json<MaterializeRequest>, | |
| 509 | +) -> Result<Json<MaterializeReport>, AppError> { | |
| 510 | + let instance = instance_or_404(&id, &st.db).await?; | |
| 511 | + service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; | |
| 512 | + let from = Timestamp::from_millis(req.from); | |
| 513 | + let to = Timestamp::from_millis(req.to); | |
| 514 | + check_time_range(Some(from), Some(to))?; | |
| 515 | + // The same rule a hand-created lesson's `starts_at` obeys: nothing is | |
| 516 | + // scheduled to begin in the past. (`to` is deliberately not checked — a | |
| 517 | + // range may legitimately end in the past when `from` does not, which is | |
| 518 | + // how a school backfills a plan it only now entered.) | |
| 519 | + check_not_past("from", Some(from))?; | |
| 520 | + // The day-bucketing read `attendance` makes: a range's instants name | |
| 521 | + // *school* days, and each lesson lands at its slot's minute of that local | |
| 522 | + // day. | |
| 523 | + let school = service::settings::load(&st.db).await?; | |
| 524 | + let offset = zone_offset_minutes(school.get_timezone()); | |
| 525 | + | |
| 526 | + let outcome = | |
| 527 | + service::course_session::materialize(&st.db, &instance, from, to, req.apply, offset).await?; | |
| 528 | + // The teacher every generated row names, in one query. | |
| 529 | + let people = person_map( | |
| 530 | + outcome.created.iter().map(|session| *session.get_teacher()), | |
| 531 | + &st.db, | |
| 532 | + ) | |
| 533 | + .await?; | |
| 534 | + let created = outcome | |
| 535 | + .created | |
| 536 | + .iter() | |
| 537 | + .map(|session| SessionResponse::new(session, &people)) | |
| 538 | + .collect(); | |
| 539 | + Ok(Json(MaterializeReport { | |
| 540 | + from: from.as_millis(), | |
| 541 | + to: to.as_millis(), | |
| 542 | + applied: outcome.applied, | |
| 543 | + slots: outcome.slots, | |
| 544 | + candidates: outcome.candidates, | |
| 545 | + created, | |
| 546 | + skipped_existing: outcome.skipped_existing, | |
| 547 | + skipped_holiday: outcome.skipped_holiday, | |
| 548 | + blocked: outcome | |
| 549 | + .blocked | |
| 550 | + .iter() | |
| 551 | + .map(|day| BlockedDayResponse { | |
| 552 | + date: day.day.to_string(), | |
| 553 | + holiday: day.holiday.as_str().to_string(), | |
| 554 | + }) | |
| 555 | + .collect(), | |
| 556 | + range_days: outcome.range_days, | |
| 557 | + })) | |
| 558 | +} |
tests/integration.rsmodified+5 -1
| @@ -30266,7 +30266,7 @@ async fn a_school_with_no_modules_can_still_use_the_core_routes() { | ||
| 30266 | 30266 | |
| 30267 | 30267 | /// Route prefixes that are deliberately ungated, each with the reason it is — |
| 30268 | 30268 | /// a nest here is one no school can be sold or refused. |
| 30269 | -const CORE_PREFIXES: [(&str, &str); 14] = [ | |
| 30269 | +const CORE_PREFIXES: [(&str, &str); 15] = [ | |
| 30270 | 30270 | ("/", "the health mirror at the root"), |
| 30271 | 30271 | ("/health", "liveness, read before any school is resolved"), |
| 30272 | 30272 | ("/time", "the server clock, a deploy constant"), |
| @@ -30289,6 +30289,10 @@ const CORE_PREFIXES: [(&str, &str); 14] = [ | ||
| 30289 | 30289 | "/terms", |
| 30290 | 30290 | "the academic calendar every other module hangs off", |
| 30291 | 30291 | ), |
| 30292 | + ( | |
| 30293 | + "/holidays", | |
| 30294 | + "the school-wide non-teaching calendar the schedule bounds itself with", | |
| 30295 | + ), | |
| 30292 | 30296 | ( |
| 30293 | 30297 | "/academic-years", |
| 30294 | 30298 | "the calendar above the dönemler — every şube sits in one", |