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

holidays.rs296 lines, 11.3 KiBHistoryRawDownload
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
13use crate::web::tenant_state::State;
14use axum::Json;
15use axum::extract::{Path, Query};
16use axum::http::StatusCode;
17use serde::{Deserialize, Serialize};
18use utoipa::{IntoParams, ToSchema};
19use utoipa_axum::router::OpenApiRouter;
20use utoipa_axum::routes;
21
22use crate::db::holiday::HolidayPatch;
23use crate::domain::holiday::{Holiday, HolidayId, HolidayKind, HolidayName};
24use crate::domain::timestamp::Timestamp;
25use crate::error::{AppError, ErrorResponse};
26use crate::service;
27use crate::state::AppState;
28
29use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, check_time_range, person_map};
30
31pub 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)]
38struct 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)]
56struct UpdateHoliday {
57 /// New name, held to the same published bound as `POST` — and still
58 /// re-checked by the `HolidayName` newtype at runtime.
59 #[schema(max_length = 100)]
60 name: Option<String>,
61 #[schema(example = 1_793_318_400_000_i64)]
62 starts_at: Option<i64>,
63 #[schema(example = 1_793_404_800_000_i64)]
64 ends_at: Option<i64>,
65 #[schema(example = "idari")]
66 kind: Option<String>,
67}
68
69#[derive(Serialize, ToSchema)]
70struct HolidayResponse {
71 id: String,
72 #[schema(example = "29 Ekim Cumhuriyet Bayramı")]
73 name: String,
74 /// First blocked instant, UTC unix-milliseconds.
75 starts_at: i64,
76 /// Last blocked instant, UTC unix-milliseconds.
77 ends_at: i64,
78 #[schema(example = "resmi")]
79 kind: String,
80 /// The manager who declared the holiday (`GET /users/{id}`).
81 creator: PersonRef,
82 /// Declared at, UTC unix-milliseconds.
83 created_at: i64,
84}
85
86impl HolidayResponse {
87 fn new(holiday: &Holiday, people: &std::collections::HashMap<String, PersonRef>) -> Self {
88 Self {
89 id: holiday.get_id().key().to_string(),
90 name: holiday.get_name().as_str().to_string(),
91 starts_at: holiday.get_starts_at().as_millis(),
92 ends_at: holiday.get_ends_at().as_millis(),
93 kind: holiday.get_kind().as_str().to_string(),
94 creator: PersonRef::resolve(people, holiday.get_creator()),
95 created_at: holiday.get_created_at().as_millis(),
96 }
97 }
98}
99
100/// Inclusive instant bounds on `GET /holidays`. Either may be omitted; a
101/// holiday is listed when it *reaches into* the window, not only when it lies
102/// entirely inside it.
103#[derive(Debug, Deserialize, IntoParams)]
104struct HolidayRange {
105 /// Keep holidays reaching at or after this instant, unix-milliseconds.
106 #[param(example = 1_793_318_400_000_i64)]
107 from: Option<i64>,
108 /// Keep holidays reaching at or before this instant, unix-milliseconds.
109 #[param(example = 1_793_404_800_000_i64)]
110 to: Option<i64>,
111}
112
113/// Every holiday the request named — the join half of the responses below.
114async fn people_of(
115 holidays: &[Holiday],
116 db: &crate::database::Database,
117) -> Result<std::collections::HashMap<String, PersonRef>, AppError> {
118 person_map(holidays.iter().map(|holiday| *holiday.get_creator()), db).await
119}
120
121/// Declare a school-wide holiday. Requires manager+. Past dates are allowed —
122/// the calendar is a record, and a school adopting the app mid-year backfills
123/// it legitimately.
124#[utoipa::path(
125 post,
126 path = "/",
127 tag = "holidays",
128 security(("session_cookie" = [])),
129 request_body = CreateHoliday,
130 responses(
131 (status = 201, description = "Holiday declared", body = HolidayResponse),
132 (status = 400, description = "Invalid name, kind, or range", body = ErrorResponse),
133 (status = 401, description = "Not authenticated", body = ErrorResponse),
134 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
135 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
136 ),
137)]
138async fn create_holiday(
139 State(st): State<AppState>,
140 RequireManager(user): RequireManager,
141 Json(req): Json<CreateHoliday>,
142) -> Result<(StatusCode, Json<HolidayResponse>), AppError> {
143 let name = HolidayName::try_new(&req.name)?;
144 let kind = HolidayKind::try_new(&req.kind)?;
145 let starts_at = Timestamp::from_millis(req.starts_at);
146 let ends_at = Timestamp::from_millis(req.ends_at);
147 check_time_range(Some(starts_at), Some(ends_at))?;
148 let holiday = service::holiday::create(
149 &st.db,
150 &name,
151 starts_at,
152 ends_at,
153 &kind,
154 user.get_id(),
155 )
156 .await?;
157 // The creator is the caller — already loaded, no extra lookup.
158 let people = PersonRef::map_of(&[&user]);
159 Ok((
160 StatusCode::CREATED,
161 Json(HolidayResponse::new(&holiday, &people)),
162 ))
163}
164
165/// List the calendar, newest start first. Any authenticated user — students
166/// need the calendar to make sense of their courses. Paged via
167/// `?limit=&offset=` (omit `limit` for the full list), optionally windowed by
168/// `?from=&to=`; returns a `{items, total, limit, offset}` envelope.
169#[utoipa::path(
170 get,
171 path = "/",
172 tag = "holidays",
173 security(("session_cookie" = [])),
174 params(HolidayRange, PageParams),
175 responses(
176 (status = 200, description = "A page of holidays (the full list when unpaged)", body = Page<HolidayResponse>),
177 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
178 (status = 401, description = "Not authenticated", body = ErrorResponse),
179 ),
180)]
181async fn list_holidays(
182 State(st): State<AppState>,
183 CurrentUser(_user): CurrentUser,
184 Query(range): Query<HolidayRange>,
185 Query(page): Query<PageParams>,
186) -> Result<Json<Page<HolidayResponse>>, AppError> {
187 let (limit, offset) = page.resolve()?;
188 let (holidays, total) = service::holiday::list(
189 &st.db,
190 range.from.map(Timestamp::from_millis),
191 range.to.map(Timestamp::from_millis),
192 limit,
193 offset,
194 )
195 .await?;
196 let people = people_of(&holidays, &st.db).await?;
197 let items = holidays
198 .iter()
199 .map(|holiday| HolidayResponse::new(holiday, &people))
200 .collect();
201 Ok(Json(Page::new(items, total, limit, offset)))
202}
203
204/// Fetch a single holiday by id.
205#[utoipa::path(
206 get,
207 path = "/{id}",
208 tag = "holidays",
209 security(("session_cookie" = [])),
210 params(("id" = String, Path, description = "Holiday id")),
211 responses(
212 (status = 200, description = "The holiday", body = HolidayResponse),
213 (status = 401, description = "Not authenticated", body = ErrorResponse),
214 (status = 404, description = "Not found", body = ErrorResponse),
215 ),
216)]
217async fn get_holiday(
218 State(st): State<AppState>,
219 CurrentUser(_user): CurrentUser,
220 Path(id): Path<String>,
221) -> Result<Json<HolidayResponse>, AppError> {
222 let holiday = service::holiday::read(&st.db, &HolidayId::from_key(&id)).await?;
223 let people = people_of(std::slice::from_ref(&holiday), &st.db).await?;
224 Ok(Json(HolidayResponse::new(&holiday, &people)))
225}
226
227/// Update a holiday. Requires manager+. Omitted fields keep their value; the
228/// merged range must stay ordered. A holiday is a *record* of the calendar,
229/// so a past range is editable like a future one.
230#[utoipa::path(
231 patch,
232 path = "/{id}",
233 tag = "holidays",
234 security(("session_cookie" = [])),
235 params(("id" = String, Path, description = "Holiday id")),
236 request_body = UpdateHoliday,
237 responses(
238 (status = 200, description = "Updated holiday", body = HolidayResponse),
239 (status = 400, description = "Invalid name, kind, or range", body = ErrorResponse),
240 (status = 401, description = "Not authenticated", body = ErrorResponse),
241 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
242 (status = 404, description = "Not found", body = ErrorResponse),
243 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
244 ),
245)]
246async fn update_holiday(
247 State(st): State<AppState>,
248 RequireManager(_user): RequireManager,
249 Path(id): Path<String>,
250 Json(req): Json<UpdateHoliday>,
251) -> Result<Json<HolidayResponse>, AppError> {
252 let name = req.name.as_deref().map(HolidayName::try_new).transpose()?;
253 let kind = req.kind.as_deref().map(HolidayKind::try_new).transpose()?;
254 let starts_at = req.starts_at.map(Timestamp::from_millis);
255 let ends_at = req.ends_at.map(Timestamp::from_millis);
256 // Pre-flight only: the merged range is re-checked inside the UPDATE's own
257 // `WHERE` (the holiday update in the db layer), so a concurrent move of
258 // the end this PATCH omits cannot slip an inverted range past this
259 // snapshot.
260 check_time_range(starts_at, ends_at)?;
261
262 let patch = HolidayPatch {
263 name,
264 starts_at,
265 ends_at,
266 kind,
267 };
268 let holiday = service::holiday::update(&st.db, &HolidayId::from_key(&id), patch).await?;
269 let people = people_of(std::slice::from_ref(&holiday), &st.db).await?;
270 Ok(Json(HolidayResponse::new(&holiday, &people)))
271}
272
273/// Delete a holiday. Requires manager+. Nothing references a holiday — the
274/// materializer only *reads* the calendar — so the delete is unconditional and
275/// the lessons already generated on those days stay where they are.
276#[utoipa::path(
277 delete,
278 path = "/{id}",
279 tag = "holidays",
280 security(("session_cookie" = [])),
281 params(("id" = String, Path, description = "Holiday id")),
282 responses(
283 (status = 204, description = "Deleted"),
284 (status = 401, description = "Not authenticated", body = ErrorResponse),
285 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
286 (status = 404, description = "Not found", body = ErrorResponse),
287 ),
288)]
289async fn delete_holiday(
290 State(st): State<AppState>,
291 RequireManager(_user): RequireManager,
292 Path(id): Path<String>,
293) -> Result<StatusCode, AppError> {
294 service::holiday::delete(&st.db, &HolidayId::from_key(&id)).await?;
295 Ok(StatusCode::NO_CONTENT)
296}