| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::collections::HashMap; |
| 15 | |
| 16 | use axum::Json; |
| 17 | use axum::extract::{Path, Query}; |
| 18 | use axum::http::StatusCode; |
| 19 | use serde::{Deserialize, Serialize}; |
| 20 | use utoipa::{IntoParams, ToSchema}; |
| 21 | use utoipa_axum::router::OpenApiRouter; |
| 22 | use utoipa_axum::routes; |
| 23 | |
| 24 | use crate::database::Database; |
| 25 | use crate::domain::class_course::DersSaati; |
| 26 | use crate::domain::course::{CourseDescription, CourseId, CourseTitle}; |
| 27 | use crate::domain::course_offering::{CourseOffering, CourseOfferingId}; |
| 28 | use crate::domain::grade::GradeLevel; |
| 29 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 30 | use crate::service; |
| 31 | use crate::state::AppState; |
| 32 | use crate::web::tenant_state::State; |
| 33 | |
| 34 | use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, person_map, set_or_clear}; |
| 35 | |
| 36 | pub fn routes() -> OpenApiRouter<AppState> { |
| 37 | OpenApiRouter::new() |
| 38 | .routes(routes!(create_offering, list_offerings)) |
| 39 | .routes(routes!(get_offering, update_offering, delete_offering)) |
| 40 | } |
| 41 | |
| 42 | #[derive(Deserialize, ToSchema)] |
| 43 | struct CreateOffering { |
| 44 | |
| 45 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 46 | course: String, |
| 47 | |
| 48 | #[schema(minimum = 0, maximum = 12, example = 9)] |
| 49 | grade_level: i16, |
| 50 | |
| 51 | #[schema(max_length = 200)] |
| 52 | title: Option<String>, |
| 53 | |
| 54 | #[schema(max_length = 2_000)] |
| 55 | description: Option<String>, |
| 56 | |
| 57 | #[schema(minimum = 1, maximum = 40, example = 5)] |
| 58 | default_ders_saati: Option<i64>, |
| 59 | |
| 60 | default_counts_toward_karne: Option<bool>, |
| 61 | } |
| 62 | |
| 63 | #[derive(Deserialize, ToSchema)] |
| 64 | struct UpdateOffering { |
| 65 | |
| 66 | |
| 67 | #[serde(default, deserialize_with = "set_or_clear")] |
| 68 | #[schema(value_type = Option<String>, max_length = 200)] |
| 69 | title: Option<Option<String>>, |
| 70 | |
| 71 | #[serde(default, deserialize_with = "set_or_clear")] |
| 72 | #[schema(value_type = Option<String>, max_length = 2_000)] |
| 73 | description: Option<Option<String>>, |
| 74 | |
| 75 | #[serde(default, deserialize_with = "set_or_clear")] |
| 76 | #[schema(value_type = Option<i64>, minimum = 1, maximum = 40)] |
| 77 | default_ders_saati: Option<Option<i64>>, |
| 78 | |
| 79 | #[serde(default, deserialize_with = "set_or_clear")] |
| 80 | #[schema(value_type = Option<bool>)] |
| 81 | default_counts_toward_karne: Option<Option<bool>>, |
| 82 | } |
| 83 | |
| 84 | |
| 85 | #[derive(Deserialize, IntoParams)] |
| 86 | struct OfferingFilter { |
| 87 | |
| 88 | #[param(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 89 | course: Option<String>, |
| 90 | |
| 91 | #[param(minimum = 0, maximum = 12)] |
| 92 | grade_level: Option<i16>, |
| 93 | } |
| 94 | |
| 95 | impl OfferingFilter { |
| 96 | |
| 97 | |
| 98 | fn resolve(&self) -> Result<(Option<CourseId>, Option<GradeLevel>), AppError> { |
| 99 | let course = match &self.course { |
| 100 | Some(key) => { |
| 101 | let id = CourseId::from_key(key); |
| 102 | if id.uuid().is_nil() { |
| 103 | return Err(ValidationError::Invalid { |
| 104 | field: "course", |
| 105 | reason: "must be a hyphenated uuid", |
| 106 | } |
| 107 | .into()); |
| 108 | } |
| 109 | Some(id) |
| 110 | } |
| 111 | None => None, |
| 112 | }; |
| 113 | let grade = self.grade_level.map(GradeLevel::new).transpose()?; |
| 114 | Ok((course, grade)) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | #[derive(Serialize, ToSchema)] |
| 125 | pub struct OfferingResponse { |
| 126 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 127 | pub id: String, |
| 128 | |
| 129 | pub course: String, |
| 130 | |
| 131 | pub grade_level: i16, |
| 132 | |
| 133 | pub title: Option<String>, |
| 134 | |
| 135 | pub description: Option<String>, |
| 136 | |
| 137 | pub default_ders_saati: Option<i64>, |
| 138 | |
| 139 | pub default_counts_toward_karne: Option<bool>, |
| 140 | |
| 141 | |
| 142 | pub created_by: PersonRef, |
| 143 | |
| 144 | pub created_at: i64, |
| 145 | |
| 146 | pub updated_at: i64, |
| 147 | } |
| 148 | |
| 149 | impl OfferingResponse { |
| 150 | fn new(offering: &CourseOffering, people: &HashMap<String, PersonRef>) -> Self { |
| 151 | Self { |
| 152 | id: offering.get_id().key(), |
| 153 | course: offering.get_course().key(), |
| 154 | grade_level: offering.get_grade_level().get(), |
| 155 | title: offering.get_title().map(|t| t.as_str().to_string()), |
| 156 | description: offering.get_description().map(|d| d.as_str().to_string()), |
| 157 | default_ders_saati: offering.get_default_ders_saati().map(DersSaati::as_i64), |
| 158 | default_counts_toward_karne: offering.get_default_counts_toward_karne(), |
| 159 | created_by: PersonRef::resolve(people, offering.get_created_by()), |
| 160 | created_at: offering.get_created_at().as_millis(), |
| 161 | updated_at: offering.get_updated_at().as_millis(), |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | async fn offering_or_404(key: &str, db: &Database) -> Result<CourseOffering, AppError> { |
| 167 | service::course_offering::read(db, &CourseOfferingId::from_key(key)) |
| 168 | .await? |
| 169 | .ok_or(AppError::NotFound) |
| 170 | } |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | #[utoipa::path( |
| 177 | post, |
| 178 | path = "/", |
| 179 | tag = "offerings", |
| 180 | security(("session_cookie" = [])), |
| 181 | request_body = CreateOffering, |
| 182 | responses( |
| 183 | (status = 201, description = "Offering created", body = OfferingResponse), |
| 184 | (status = 400, description = "Invalid fields, or the course is not a class-delivered ders (kind `course`)", body = ErrorResponse), |
| 185 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 186 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 187 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 188 | (status = 409, description = "The course already has an offering for this grade — the body carries the machine code `offering_exists`", body = ErrorResponse), |
| 189 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 190 | ), |
| 191 | )] |
| 192 | async fn create_offering( |
| 193 | State(st): State<AppState>, |
| 194 | RequireManager(user): RequireManager, |
| 195 | Json(req): Json<CreateOffering>, |
| 196 | ) -> Result<(StatusCode, Json<OfferingResponse>), AppError> { |
| 197 | let course = CourseId::from_key(&req.course); |
| 198 | if course.uuid().is_nil() { |
| 199 | return Err(ValidationError::Invalid { |
| 200 | field: "course", |
| 201 | reason: "must be a hyphenated uuid", |
| 202 | } |
| 203 | .into()); |
| 204 | } |
| 205 | let grade = GradeLevel::new(req.grade_level)?; |
| 206 | let title = match &req.title { |
| 207 | Some(title) => Some(CourseTitle::try_new(title)?), |
| 208 | None => None, |
| 209 | }; |
| 210 | let description = match &req.description { |
| 211 | Some(description) => Some(CourseDescription::try_new(description)?), |
| 212 | None => None, |
| 213 | }; |
| 214 | let staff = req.default_ders_saati.map(DersSaati::try_new).transpose()?; |
| 215 | let offering = service::course_offering::create( |
| 216 | &st.db, |
| 217 | user.get_id(), |
| 218 | &course, |
| 219 | grade, |
| 220 | title, |
| 221 | description, |
| 222 | staff, |
| 223 | req.default_counts_toward_karne, |
| 224 | ) |
| 225 | .await?; |
| 226 | let people = PersonRef::map_of(&[&user]); |
| 227 | Ok((StatusCode::CREATED, Json(OfferingResponse::new(&offering, &people)))) |
| 228 | } |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | #[utoipa::path( |
| 234 | get, |
| 235 | path = "/", |
| 236 | tag = "offerings", |
| 237 | security(("session_cookie" = [])), |
| 238 | params(PageParams, OfferingFilter), |
| 239 | responses( |
| 240 | (status = 200, description = "A page of offerings (all of them when unpaged)", body = Page<OfferingResponse>), |
| 241 | (status = 400, description = "Invalid limit, offset, course key, or grade_level", body = ErrorResponse), |
| 242 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 243 | ), |
| 244 | )] |
| 245 | async fn list_offerings( |
| 246 | State(st): State<AppState>, |
| 247 | CurrentUser(_user): CurrentUser, |
| 248 | Query(page): Query<PageParams>, |
| 249 | Query(filter): Query<OfferingFilter>, |
| 250 | ) -> Result<Json<Page<OfferingResponse>>, AppError> { |
| 251 | let (limit, offset) = page.resolve()?; |
| 252 | let (course, grade) = filter.resolve()?; |
| 253 | let (rows, total) = |
| 254 | service::course_offering::list(&st.db, course.as_ref(), grade, limit, offset).await?; |
| 255 | let people = person_map(rows.iter().map(|o| *o.get_created_by()), &st.db).await?; |
| 256 | let items = rows |
| 257 | .iter() |
| 258 | .map(|offering| OfferingResponse::new(offering, &people)) |
| 259 | .collect(); |
| 260 | Ok(Json(Page::new(items, total, limit, offset))) |
| 261 | } |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 266 | #[utoipa::path( |
| 267 | get, |
| 268 | path = "/{id}", |
| 269 | tag = "offerings", |
| 270 | security(("session_cookie" = [])), |
| 271 | params(("id" = String, Path, description = "Offering id")), |
| 272 | responses( |
| 273 | (status = 200, description = "The offering's raw template values (null = inherit); the per-class resolved view lives on GET /instances/{id}", body = OfferingResponse), |
| 274 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 275 | (status = 404, description = "Not found", body = ErrorResponse), |
| 276 | ), |
| 277 | )] |
| 278 | async fn get_offering( |
| 279 | State(st): State<AppState>, |
| 280 | CurrentUser(_user): CurrentUser, |
| 281 | Path(id): Path<String>, |
| 282 | ) -> Result<Json<OfferingResponse>, AppError> { |
| 283 | let offering = offering_or_404(&id, &st.db).await?; |
| 284 | let people = person_map(std::iter::once(*offering.get_created_by()), &st.db).await?; |
| 285 | Ok(Json(OfferingResponse::new(&offering, &people))) |
| 286 | } |
| 287 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | |
| 293 | #[utoipa::path( |
| 294 | patch, |
| 295 | path = "/{id}", |
| 296 | tag = "offerings", |
| 297 | security(("session_cookie" = [])), |
| 298 | params(("id" = String, Path, description = "Offering id")), |
| 299 | request_body = UpdateOffering, |
| 300 | responses( |
| 301 | (status = 200, description = "Updated offering", body = OfferingResponse), |
| 302 | (status = 400, description = "Invalid field values", body = ErrorResponse), |
| 303 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 304 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 305 | (status = 404, description = "Not found", body = ErrorResponse), |
| 306 | (status = 422, description = "The body does not fit this request: a field has the wrong type"), |
| 307 | ), |
| 308 | )] |
| 309 | async fn update_offering( |
| 310 | State(st): State<AppState>, |
| 311 | RequireManager(_user): RequireManager, |
| 312 | Path(id): Path<String>, |
| 313 | Json(req): Json<UpdateOffering>, |
| 314 | ) -> Result<Json<OfferingResponse>, AppError> { |
| 315 | |
| 316 | let title = match req.title { |
| 317 | None => None, |
| 318 | Some(inner) => Some(match inner { |
| 319 | None => None, |
| 320 | Some(text) => Some(CourseTitle::try_new(&text)?), |
| 321 | }), |
| 322 | }; |
| 323 | let description = match req.description { |
| 324 | None => None, |
| 325 | Some(inner) => Some(match inner { |
| 326 | None => None, |
| 327 | Some(text) => Some(CourseDescription::try_new(&text)?), |
| 328 | }), |
| 329 | }; |
| 330 | let staff = match req.default_ders_saati { |
| 331 | None => None, |
| 332 | Some(inner) => Some(match inner { |
| 333 | None => None, |
| 334 | Some(hours) => Some(DersSaati::try_new(hours)?), |
| 335 | }), |
| 336 | }; |
| 337 | let offering = service::course_offering::update( |
| 338 | &st.db, |
| 339 | &CourseOfferingId::from_key(&id), |
| 340 | title, |
| 341 | description, |
| 342 | staff, |
| 343 | req.default_counts_toward_karne, |
| 344 | ) |
| 345 | .await?; |
| 346 | let people = person_map(std::iter::once(*offering.get_created_by()), &st.db).await?; |
| 347 | Ok(Json(OfferingResponse::new(&offering, &people))) |
| 348 | } |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | |
| 355 | #[utoipa::path( |
| 356 | delete, |
| 357 | path = "/{id}", |
| 358 | tag = "offerings", |
| 359 | security(("session_cookie" = [])), |
| 360 | params(("id" = String, Path, description = "Offering id")), |
| 361 | responses( |
| 362 | (status = 204, description = "Deleted"), |
| 363 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 364 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 365 | (status = 404, description = "Not found", body = ErrorResponse), |
| 366 | (status = 409, description = "An instance still teaches from this offering — the body carries the machine code `offering_in_use`", body = ErrorResponse), |
| 367 | ), |
| 368 | )] |
| 369 | async fn delete_offering( |
| 370 | State(st): State<AppState>, |
| 371 | RequireManager(_user): RequireManager, |
| 372 | Path(id): Path<String>, |
| 373 | ) -> Result<StatusCode, AppError> { |
| 374 | service::course_offering::delete(&st.db, &CourseOfferingId::from_key(&id)).await?; |
| 375 | Ok(StatusCode::NO_CONTENT) |
| 376 | } |