forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

terms.rs281 lines, 10.7 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 service::term::require_writable(&term)?;
185 // Pre-flight only: the range check is re-made inside the UPDATE's own
186 // `WHERE` (the term update in the db layer), so a concurrent move of the
187 // end this PATCH omits cannot slip an inverted range past this snapshot.
188 check_time_range(
189 Some(starts_at.unwrap_or_else(|| term.get_starts_at())),
190 Some(ends_at.unwrap_or_else(|| term.get_ends_at())),
191 )?;
192
193 let updated = service::term::update(&st.db, term, name, starts_at, ends_at).await?;
194 Ok(Json(TermResponse::new(&updated)))
195}
196
197/// Delete a term. Requires manager+. Refused with a 409 while any course still
198/// links to it — unlink those courses (`PATCH /courses/{id}` with
199/// `"term_id": null`) or delete them first, so a term is never dropped out from
200/// under the calendar its courses hang on.
201#[utoipa::path(
202 delete,
203 path = "/{id}",
204 tag = "terms",
205 security(("session_cookie" = [])),
206 params(("id" = String, Path, description = "Term id")),
207 responses(
208 (status = 204, description = "Deleted"),
209 (status = 401, description = "Not authenticated", body = ErrorResponse),
210 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
211 (status = 404, description = "Not found", body = ErrorResponse),
212 (status = 409, description = "Courses are still linked to this term, or the term is archived — past years are read-only", body = ErrorResponse),
213 ),
214)]
215async fn delete_term(
216 State(st): State<AppState>,
217 RequireManager(_user): RequireManager,
218 Path(id): Path<String>,
219) -> Result<StatusCode, AppError> {
220 let term = service::term::read(&st.db, &TermId::from_key(&id))
221 .await?
222 .ok_or(AppError::NotFound)?;
223 service::term::require_writable(&term)?;
224 service::term::delete(&st.db, term).await?;
225 Ok(StatusCode::NO_CONTENT)
226}
227
228/// Archive a term. Requires manager+. An archived term is frozen: it takes no
229/// edits, no delete, and no new course or class link. Idempotent — archiving an
230/// already-archived term answers `200` with the stamp it already had.
231#[utoipa::path(
232 post,
233 path = "/{id}/archive",
234 tag = "terms",
235 security(("session_cookie" = [])),
236 params(("id" = String, Path, description = "Term id")),
237 responses(
238 (status = 200, description = "The archived term", body = TermResponse),
239 (status = 401, description = "Not authenticated", body = ErrorResponse),
240 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
241 (status = 404, description = "Not found", body = ErrorResponse),
242 ),
243)]
244async fn archive_term(
245 State(st): State<AppState>,
246 RequireManager(_user): RequireManager,
247 Path(id): Path<String>,
248) -> Result<Json<TermResponse>, AppError> {
249 let term = service::term::read(&st.db, &TermId::from_key(&id))
250 .await?
251 .ok_or(AppError::NotFound)?;
252 let archived = service::term::archive(&st.db, term).await?;
253 Ok(Json(TermResponse::new(&archived)))
254}
255
256/// Re-open an archived term. Requires manager+. Idempotent the same way as
257/// archiving: an already-open term answers `200`.
258#[utoipa::path(
259 post,
260 path = "/{id}/unarchive",
261 tag = "terms",
262 security(("session_cookie" = [])),
263 params(("id" = String, Path, description = "Term id")),
264 responses(
265 (status = 200, description = "The re-opened term", body = TermResponse),
266 (status = 401, description = "Not authenticated", body = ErrorResponse),
267 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
268 (status = 404, description = "Not found", body = ErrorResponse),
269 ),
270)]
271async fn unarchive_term(
272 State(st): State<AppState>,
273 RequireManager(_user): RequireManager,
274 Path(id): Path<String>,
275) -> Result<Json<TermResponse>, AppError> {
276 let term = service::term::read(&st.db, &TermId::from_key(&id))
277 .await?
278 .ok_or(AppError::NotFound)?;
279 let reopened = service::term::unarchive(&st.db, term).await?;
280 Ok(Json(TermResponse::new(&reopened)))
281}