| 1 | use crate::web::tenant_state::State; |
| 2 | use axum::Json; |
| 3 | use axum::extract::{Path, Query}; |
| 4 | use axum::http::StatusCode; |
| 5 | use serde::{Deserialize, Serialize}; |
| 6 | use utoipa::ToSchema; |
| 7 | use utoipa_axum::router::OpenApiRouter; |
| 8 | use utoipa_axum::routes; |
| 9 | |
| 10 | use crate::domain::term::{Term, TermId, TermName}; |
| 11 | use crate::domain::timestamp::Timestamp; |
| 12 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 13 | use crate::service; |
| 14 | use crate::state::AppState; |
| 15 | |
| 16 | use super::{CurrentUser, Page, PageParams, RequireManager, check_time_range}; |
| 17 | |
| 18 | pub 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)] |
| 27 | struct CreateTerm { |
| 28 | #[schema(example = "1. Dönem", max_length = 100)] |
| 29 | name: String, |
| 30 | |
| 31 | |
| 32 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 33 | year: String, |
| 34 | |
| 35 | |
| 36 | #[schema(example = 1_780_000_000_000_i64)] |
| 37 | starts_at: i64, |
| 38 | |
| 39 | #[schema(example = 1_790_000_000_000_i64)] |
| 40 | ends_at: i64, |
| 41 | } |
| 42 | |
| 43 | #[derive(Deserialize, ToSchema)] |
| 44 | struct 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)] |
| 52 | struct TermResponse { |
| 53 | id: String, |
| 54 | #[schema(example = "1. Dönem")] |
| 55 | name: String, |
| 56 | |
| 57 | year: String, |
| 58 | |
| 59 | starts_at: i64, |
| 60 | |
| 61 | ends_at: i64, |
| 62 | |
| 63 | archived_at: Option<i64>, |
| 64 | } |
| 65 | |
| 66 | impl 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 | |
| 80 | |
| 81 | |
| 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 | )] |
| 97 | async 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 | |
| 104 | |
| 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 | |
| 119 | |
| 120 | |
| 121 | |
| 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 | )] |
| 134 | async 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 | |
| 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 | )] |
| 158 | async 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 | |
| 170 | |
| 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 | )] |
| 188 | async 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 | |
| 203 | |
| 204 | |
| 205 | service::academic_year::require_open(&st.db, term.get_year()).await?; |
| 206 | |
| 207 | |
| 208 | |
| 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 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 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 | )] |
| 237 | async 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 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 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 | )] |
| 272 | async 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 | |
| 285 | |
| 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 | )] |
| 299 | async 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 | } |