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

terms.rs309 lines, 12.6 KiBHistoryRawDownload
1use crate::web::tenant_state::State;
2use axum::Json;
3use axum::extract::{Path, Query};
4use axum::http::StatusCode;
5use serde::{Deserialize, Serialize};
6use utoipa::ToSchema;
7use utoipa_axum::router::OpenApiRouter;
8use utoipa_axum::routes;
9
10use crate::domain::term::{Term, TermId, TermName};
11use crate::domain::timestamp::Timestamp;
12use crate::error::{AppError, ErrorResponse, ValidationError};
13use crate::service;
14use crate::state::AppState;
15
16use super::{CurrentUser, Page, PageParams, RequireManager, check_time_range};
17
18pub fn routes() -> OpenApiRouter<AppState> {
19 OpenApiRouter::new()
20 .routes(routes!(create_term, list_terms))
21 .routes(routes!(get_term, update_term, delete_term))
22 .routes(routes!(archive_term))
23 .routes(routes!(unarchive_term))
24}
25
26#[derive(Deserialize, ToSchema)]
27struct CreateTerm {
28 #[schema(example = "1. Dönem", max_length = 100)]
29 name: String,
30 /// The academic year this term is a slice of (`GET /academic-years`).
31 /// Required — a term outside a year has no report card to be counted into.
32 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
33 year: String,
34 /// Term start, UTC unix-milliseconds. May lie in the past — a school
35 /// adopting the app mid-year backfills its calendar legitimately.
36 #[schema(example = 1_780_000_000_000_i64)]
37 starts_at: i64,
38 /// Term end, UTC unix-milliseconds; must not precede `starts_at`.
39 #[schema(example = 1_790_000_000_000_i64)]
40 ends_at: i64,
41}
42
43#[derive(Deserialize, ToSchema)]
44struct UpdateTerm {
45 #[schema(max_length = 100)]
46 name: Option<String>,
47 starts_at: Option<i64>,
48 ends_at: Option<i64>,
49}
50
51#[derive(Serialize, ToSchema)]
52struct TermResponse {
53 id: String,
54 #[schema(example = "1. Dönem")]
55 name: String,
56 /// The academic year this term belongs to (`GET /academic-years/{id}`).
57 year: String,
58 /// Term start, UTC unix-milliseconds.
59 starts_at: i64,
60 /// Term end, UTC unix-milliseconds.
61 ends_at: i64,
62 /// Archived at, UTC unix-millis; null while the term is open.
63 archived_at: Option<i64>,
64}
65
66impl TermResponse {
67 fn new(term: &Term) -> Self {
68 Self {
69 id: term.get_id().key().to_string(),
70 name: term.get_name().as_str().to_string(),
71 year: term.get_year().key().to_string(),
72 starts_at: term.get_starts_at().as_millis(),
73 ends_at: term.get_ends_at().as_millis(),
74 archived_at: term.get_archived_at().map(|at| at.as_millis()),
75 }
76 }
77}
78
79/// Create a term inside an academic year. Requires manager+. Past dates are
80/// allowed — terms are calendar structure, not schedules; an *archived* year
81/// refuses the new term (`409`), because past years take no new structure.
82#[utoipa::path(
83 post,
84 path = "/",
85 tag = "terms",
86 security(("session_cookie" = [])),
87 request_body = CreateTerm,
88 responses(
89 (status = 201, description = "Term created", body = TermResponse),
90 (status = 400, description = "Invalid name or range, or an unknown year", body = ErrorResponse),
91 (status = 401, description = "Not authenticated", body = ErrorResponse),
92 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
93 (status = 409, description = "The named academic year is archived — past years are read-only", body = ErrorResponse),
94 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
95 ),
96)]
97async fn create_term(
98 State(st): State<AppState>,
99 RequireManager(_user): RequireManager,
100 Json(req): Json<CreateTerm>,
101) -> Result<(StatusCode, Json<TermResponse>), AppError> {
102 let name = TermName::try_new(&req.name)?;
103 // The single spot a request-supplied year passes through: an unknown id is
104 // a 400 naming the field, an archived one the year's own 409.
105 let Some(year) = service::academic_year::resolve(&st.db, Some(&req.year)).await? else {
106 return Err(AppError::Validation(ValidationError::Invalid {
107 field: "year",
108 reason: "academic year is required",
109 }));
110 };
111 let starts_at = Timestamp::from_millis(req.starts_at);
112 let ends_at = Timestamp::from_millis(req.ends_at);
113 check_time_range(Some(starts_at), Some(ends_at))?;
114 let term = service::term::create(&st.db, name, year, starts_at, ends_at).await?;
115 Ok((StatusCode::CREATED, Json(TermResponse::new(&term))))
116}
117
118/// List every term, newest first. Any authenticated user — students need the
119/// calendar to make sense of their courses. Paged via `?limit=&offset=` (omit
120/// `limit` for the full list); returns a `{items, total, limit, offset}`
121/// envelope.
122#[utoipa::path(
123 get,
124 path = "/",
125 tag = "terms",
126 security(("session_cookie" = [])),
127 params(PageParams),
128 responses(
129 (status = 200, description = "A page of terms (the full list when unpaged)", body = Page<TermResponse>),
130 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
131 (status = 401, description = "Not authenticated", body = ErrorResponse),
132 ),
133)]
134async fn list_terms(
135 State(st): State<AppState>,
136 CurrentUser(_user): CurrentUser,
137 Query(page): Query<PageParams>,
138) -> Result<Json<Page<TermResponse>>, AppError> {
139 let (limit, offset) = page.resolve()?;
140 let (terms, total) = service::term::list_all(&st.db, limit, offset).await?;
141 let items = terms.iter().map(TermResponse::new).collect();
142 Ok(Json(Page::new(items, total, limit, offset)))
143}
144
145/// Fetch a single term by id.
146#[utoipa::path(
147 get,
148 path = "/{id}",
149 tag = "terms",
150 security(("session_cookie" = [])),
151 params(("id" = String, Path, description = "Term id")),
152 responses(
153 (status = 200, description = "The term", body = TermResponse),
154 (status = 401, description = "Not authenticated", body = ErrorResponse),
155 (status = 404, description = "Not found", body = ErrorResponse),
156 ),
157)]
158async fn get_term(
159 State(st): State<AppState>,
160 CurrentUser(_user): CurrentUser,
161 Path(id): Path<String>,
162) -> Result<Json<TermResponse>, AppError> {
163 let term = service::term::read(&st.db, &TermId::from_key(&id))
164 .await?
165 .ok_or(AppError::NotFound)?;
166 Ok(Json(TermResponse::new(&term)))
167}
168
169/// Update a term. Requires manager+. Omitted fields keep their value; the
170/// merged range must stay ordered.
171#[utoipa::path(
172 patch,
173 path = "/{id}",
174 tag = "terms",
175 security(("session_cookie" = [])),
176 params(("id" = String, Path, description = "Term id")),
177 request_body = UpdateTerm,
178 responses(
179 (status = 200, description = "Updated term", body = TermResponse),
180 (status = 400, description = "Invalid name or range", body = ErrorResponse),
181 (status = 401, description = "Not authenticated", body = ErrorResponse),
182 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
183 (status = 404, description = "Not found", body = ErrorResponse),
184 (status = 409, description = "The term is archived, or its academic year is archived — past years are read-only", body = ErrorResponse),
185 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
186 ),
187)]
188async fn update_term(
189 State(st): State<AppState>,
190 RequireManager(_user): RequireManager,
191 Path(id): Path<String>,
192 Json(req): Json<UpdateTerm>,
193) -> Result<Json<TermResponse>, AppError> {
194 let name = req.name.as_deref().map(TermName::try_new).transpose()?;
195 let starts_at = req.starts_at.map(Timestamp::from_millis);
196 let ends_at = req.ends_at.map(Timestamp::from_millis);
197
198 let term = service::term::read(&st.db, &TermId::from_key(&id))
199 .await?
200 .ok_or(AppError::NotFound)?;
201 service::term::require_writable(&term)?;
202 // The year above the term is the other half of the read-only rule, and
203 // the half a closed term no longer covers: a term still open inside an
204 // archived year takes no edit either.
205 service::academic_year::require_open(&st.db, term.get_year()).await?;
206 // Pre-flight only: the range check is re-made inside the UPDATE's own
207 // `WHERE` (the term update in the db layer), so a concurrent move of the
208 // end this PATCH omits cannot slip an inverted range past this snapshot.
209 check_time_range(
210 Some(starts_at.unwrap_or_else(|| term.get_starts_at())),
211 Some(ends_at.unwrap_or_else(|| term.get_ends_at())),
212 )?;
213
214 let updated = service::term::update(&st.db, term, name, starts_at, ends_at).await?;
215 Ok(Json(TermResponse::new(&updated)))
216}
217
218/// Delete a term. Requires manager+. Refused with a 409 while anything still
219/// hangs off it — an exam filed in it, or a report card frozen for it — so a
220/// term is never dropped out from under marks that name it; move or delete
221/// those first. The term's own academic year is untouched (that is `DELETE
222/// /academic-years/{id}`, which refuses while a term still links it).
223#[utoipa::path(
224 delete,
225 path = "/{id}",
226 tag = "terms",
227 security(("session_cookie" = [])),
228 params(("id" = String, Path, description = "Term id")),
229 responses(
230 (status = 204, description = "Deleted"),
231 (status = 401, description = "Not authenticated", body = ErrorResponse),
232 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
233 (status = 404, description = "Not found", body = ErrorResponse),
234 (status = 409, description = "Exams or frozen karnes still belong to this term, the term is archived, or its academic year is archived — past years are read-only", body = ErrorResponse),
235 ),
236)]
237async fn delete_term(
238 State(st): State<AppState>,
239 RequireManager(_user): RequireManager,
240 Path(id): Path<String>,
241) -> Result<StatusCode, AppError> {
242 let term = service::term::read(&st.db, &TermId::from_key(&id))
243 .await?
244 .ok_or(AppError::NotFound)?;
245 service::term::require_writable(&term)?;
246 service::academic_year::require_open(&st.db, term.get_year()).await?;
247 service::term::delete(&st.db, term).await?;
248 Ok(StatusCode::NO_CONTENT)
249}
250
251/// Archive a term. Requires manager+. Archiving **freezes the report cards**:
252/// every student with a roster row under the term's year gets a snapshot of
253/// their report, and from then on `GET /marks/karne` serves that record instead
254/// of recomputing — a mark corrected after the fact no longer rewrites what a
255/// family holds. An archived term takes no edits and no delete; exams may
256/// still be created in it while its *year* is open (the archive is a record,
257/// not a wall). Idempotent — archiving an already-archived term answers `200`
258/// with the stamp it already had and never re-freezes.
259#[utoipa::path(
260 post,
261 path = "/{id}/archive",
262 tag = "terms",
263 security(("session_cookie" = [])),
264 params(("id" = String, Path, description = "Term id")),
265 responses(
266 (status = 200, description = "The archived term", body = TermResponse),
267 (status = 401, description = "Not authenticated", body = ErrorResponse),
268 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
269 (status = 404, description = "Not found", body = ErrorResponse),
270 ),
271)]
272async fn archive_term(
273 State(st): State<AppState>,
274 RequireManager(_user): RequireManager,
275 Path(id): Path<String>,
276) -> Result<Json<TermResponse>, AppError> {
277 let term = service::term::read(&st.db, &TermId::from_key(&id))
278 .await?
279 .ok_or(AppError::NotFound)?;
280 let archived = service::term::archive(&st.db, term).await?;
281 Ok(Json(TermResponse::new(&archived)))
282}
283
284/// Re-open an archived term. Requires manager+. Idempotent the same way as
285/// archiving: an already-open term answers `200`.
286#[utoipa::path(
287 post,
288 path = "/{id}/unarchive",
289 tag = "terms",
290 security(("session_cookie" = [])),
291 params(("id" = String, Path, description = "Term id")),
292 responses(
293 (status = 200, description = "The re-opened term", body = TermResponse),
294 (status = 401, description = "Not authenticated", body = ErrorResponse),
295 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
296 (status = 404, description = "Not found", body = ErrorResponse),
297 ),
298)]
299async fn unarchive_term(
300 State(st): State<AppState>,
301 RequireManager(_user): RequireManager,
302 Path(id): Path<String>,
303) -> Result<Json<TermResponse>, AppError> {
304 let term = service::term::read(&st.db, &TermId::from_key(&id))
305 .await?
306 .ok_or(AppError::NotFound)?;
307 let reopened = service::term::unarchive(&st.db, term).await?;
308 Ok(Json(TermResponse::new(&reopened)))
309}