forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

terms.rs280 lines, 10.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};
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 = "2026 Fall", max_length = 100)]
29 name: String,
30 /// Term start, UTC unix-milliseconds. May lie in the past — a school
31 /// adopting the app mid-year backfills its calendar legitimately.
32 #[schema(example = 1_780_000_000_000_i64)]
33 starts_at: i64,
34 /// Term end, UTC unix-milliseconds; must not precede `starts_at`.
35 #[schema(example = 1_790_000_000_000_i64)]
36 ends_at: i64,
37}
38
39#[derive(Deserialize, ToSchema)]
40struct UpdateTerm {
41 #[schema(max_length = 100)]
42 name: Option<String>,
43 starts_at: Option<i64>,
44 ends_at: Option<i64>,
45}
46
47#[derive(Serialize, ToSchema)]
48struct TermResponse {
49 id: String,
50 #[schema(example = "2026 Fall")]
51 name: String,
52 /// Term start, UTC unix-milliseconds.
53 starts_at: i64,
54 /// Term end, UTC unix-milliseconds.
55 ends_at: i64,
56 /// Archived at, UTC unix-millis; null while the term is open.
57 archived_at: Option<i64>,
58}
59
60impl TermResponse {
61 fn new(term: &Term) -> Self {
62 Self {
63 id: term.get_id().key().to_string(),
64 name: term.get_name().as_str().to_string(),
65 starts_at: term.get_starts_at().as_millis(),
66 ends_at: term.get_ends_at().as_millis(),
67 archived_at: term.get_archived_at().map(|at| at.as_millis()),
68 }
69 }
70}
71
72/// Create an academic term. Requires manager+. Past dates are allowed —
73/// terms are calendar structure, not schedules.
74#[utoipa::path(
75 post,
76 path = "/",
77 tag = "terms",
78 security(("session_cookie" = [])),
79 request_body = CreateTerm,
80 responses(
81 (status = 201, description = "Term created", body = TermResponse),
82 (status = 400, description = "Invalid name or range", body = ErrorResponse),
83 (status = 401, description = "Not authenticated", body = ErrorResponse),
84 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
85 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
86 ),
87)]
88async fn create_term(
89 State(st): State<AppState>,
90 RequireManager(_user): RequireManager,
91 Json(req): Json<CreateTerm>,
92) -> Result<(StatusCode, Json<TermResponse>), AppError> {
93 let name = TermName::try_new(&req.name)?;
94 let starts_at = Timestamp::from_millis(req.starts_at);
95 let ends_at = Timestamp::from_millis(req.ends_at);
96 check_time_range(Some(starts_at), Some(ends_at))?;
97 let term = service::term::create(&st.db, name, starts_at, ends_at).await?;
98 Ok((StatusCode::CREATED, Json(TermResponse::new(&term))))
99}
100
101/// List every term, newest first. Any authenticated user — students need the
102/// calendar to make sense of their courses. Paged via `?limit=&offset=` (omit
103/// `limit` for the full list); returns a `{items, total, limit, offset}`
104/// envelope.
105#[utoipa::path(
106 get,
107 path = "/",
108 tag = "terms",
109 security(("session_cookie" = [])),
110 params(PageParams),
111 responses(
112 (status = 200, description = "A page of terms (the full list when unpaged)", body = Page<TermResponse>),
113 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
114 (status = 401, description = "Not authenticated", body = ErrorResponse),
115 ),
116)]
117async fn list_terms(
118 State(st): State<AppState>,
119 CurrentUser(_user): CurrentUser,
120 Query(page): Query<PageParams>,
121) -> Result<Json<Page<TermResponse>>, AppError> {
122 let (limit, offset) = page.resolve()?;
123 let (terms, total) = service::term::list_all(&st.db, limit, offset).await?;
124 let items = terms.iter().map(TermResponse::new).collect();
125 Ok(Json(Page::new(items, total, limit, offset)))
126}
127
128/// Fetch a single term by id.
129#[utoipa::path(
130 get,
131 path = "/{id}",
132 tag = "terms",
133 security(("session_cookie" = [])),
134 params(("id" = String, Path, description = "Term id")),
135 responses(
136 (status = 200, description = "The term", body = TermResponse),
137 (status = 401, description = "Not authenticated", body = ErrorResponse),
138 (status = 404, description = "Not found", body = ErrorResponse),
139 ),
140)]
141async fn get_term(
142 State(st): State<AppState>,
143 CurrentUser(_user): CurrentUser,
144 Path(id): Path<String>,
145) -> Result<Json<TermResponse>, AppError> {
146 let term = service::term::read(&st.db, &TermId::from_key(&id))
147 .await?
148 .ok_or(AppError::NotFound)?;
149 Ok(Json(TermResponse::new(&term)))
150}
151
152/// Update a term. Requires manager+. Omitted fields keep their value; the
153/// merged range must stay ordered.
154#[utoipa::path(
155 patch,
156 path = "/{id}",
157 tag = "terms",
158 security(("session_cookie" = [])),
159 params(("id" = String, Path, description = "Term id")),
160 request_body = UpdateTerm,
161 responses(
162 (status = 200, description = "Updated term", body = TermResponse),
163 (status = 400, description = "Invalid name or range", body = ErrorResponse),
164 (status = 401, description = "Not authenticated", body = ErrorResponse),
165 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
166 (status = 404, description = "Not found", body = ErrorResponse),
167 (status = 409, description = "The term is archived — past years are read-only", body = ErrorResponse),
168 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
169 ),
170)]
171async fn update_term(
172 State(st): State<AppState>,
173 RequireManager(_user): RequireManager,
174 Path(id): Path<String>,
175 Json(req): Json<UpdateTerm>,
176) -> Result<Json<TermResponse>, AppError> {
177 let name = req.name.as_deref().map(TermName::try_new).transpose()?;
178 let starts_at = req.starts_at.map(Timestamp::from_millis);
179 let ends_at = req.ends_at.map(Timestamp::from_millis);
180
181 let term = service::term::read(&st.db, &TermId::from_key(&id))
182 .await?
183 .ok_or(AppError::NotFound)?;
184 // Pre-flight only: the range check is re-made inside the UPDATE's own
185 // `WHERE` (the term update in the db layer), so a concurrent move of the
186 // end this PATCH omits cannot slip an inverted range past this snapshot.
187 check_time_range(
188 Some(starts_at.unwrap_or_else(|| term.get_starts_at())),
189 Some(ends_at.unwrap_or_else(|| term.get_ends_at())),
190 )?;
191
192 let updated = service::term::update(&st.db, term, name, starts_at, ends_at).await?;
193 Ok(Json(TermResponse::new(&updated)))
194}
195
196/// Delete a term. Requires manager+. Refused with a 409 while any course still
197/// links to it — unlink those courses (`PATCH /courses/{id}` with
198/// `"term_id": null`) or delete them first, so a term is never dropped out from
199/// under the calendar its courses hang on.
200#[utoipa::path(
201 delete,
202 path = "/{id}",
203 tag = "terms",
204 security(("session_cookie" = [])),
205 params(("id" = String, Path, description = "Term id")),
206 responses(
207 (status = 204, description = "Deleted"),
208 (status = 401, description = "Not authenticated", body = ErrorResponse),
209 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
210 (status = 404, description = "Not found", body = ErrorResponse),
211 (status = 409, description = "Courses are still linked to this term, or the term is archived — past years are read-only", body = ErrorResponse),
212 ),
213)]
214async fn delete_term(
215 State(st): State<AppState>,
216 RequireManager(_user): RequireManager,
217 Path(id): Path<String>,
218) -> Result<StatusCode, AppError> {
219 let term = service::term::read(&st.db, &TermId::from_key(&id))
220 .await?
221 .ok_or(AppError::NotFound)?;
222 service::term::require_writable(&term)?;
223 service::term::delete(&st.db, term).await?;
224 Ok(StatusCode::NO_CONTENT)
225}
226
227/// Archive a term. Requires manager+. An archived term is frozen: it takes no
228/// edits, no delete, and no new course or class link. Idempotent — archiving an
229/// already-archived term answers `200` with the stamp it already had.
230#[utoipa::path(
231 post,
232 path = "/{id}/archive",
233 tag = "terms",
234 security(("session_cookie" = [])),
235 params(("id" = String, Path, description = "Term id")),
236 responses(
237 (status = 200, description = "The archived term", body = TermResponse),
238 (status = 401, description = "Not authenticated", body = ErrorResponse),
239 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
240 (status = 404, description = "Not found", body = ErrorResponse),
241 ),
242)]
243async fn archive_term(
244 State(st): State<AppState>,
245 RequireManager(_user): RequireManager,
246 Path(id): Path<String>,
247) -> Result<Json<TermResponse>, AppError> {
248 let term = service::term::read(&st.db, &TermId::from_key(&id))
249 .await?
250 .ok_or(AppError::NotFound)?;
251 let archived = service::term::archive(&st.db, term).await?;
252 Ok(Json(TermResponse::new(&archived)))
253}
254
255/// Re-open an archived term. Requires manager+. Idempotent the same way as
256/// archiving: an already-open term answers `200`.
257#[utoipa::path(
258 post,
259 path = "/{id}/unarchive",
260 tag = "terms",
261 security(("session_cookie" = [])),
262 params(("id" = String, Path, description = "Term id")),
263 responses(
264 (status = 200, description = "The re-opened term", body = TermResponse),
265 (status = 401, description = "Not authenticated", body = ErrorResponse),
266 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
267 (status = 404, description = "Not found", body = ErrorResponse),
268 ),
269)]
270async fn unarchive_term(
271 State(st): State<AppState>,
272 RequireManager(_user): RequireManager,
273 Path(id): Path<String>,
274) -> Result<Json<TermResponse>, AppError> {
275 let term = service::term::read(&st.db, &TermId::from_key(&id))
276 .await?
277 .ok_or(AppError::NotFound)?;
278 let reopened = service::term::unarchive(&st.db, term).await?;
279 Ok(Json(TermResponse::new(&reopened)))
280}