| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | use axum::Json; |
| 21 | use axum::extract::Path; |
| 22 | use axum::http::StatusCode; |
| 23 | use axum::response::{IntoResponse, Response}; |
| 24 | use serde::{Deserialize, Serialize}; |
| 25 | use utoipa::ToSchema; |
| 26 | use utoipa_axum::router::OpenApiRouter; |
| 27 | use utoipa_axum::routes; |
| 28 | |
| 29 | use crate::database::Database; |
| 30 | use crate::domain::class_course::{ClassCourse, ClassCourseId}; |
| 31 | use crate::domain::course_offering::CourseOfferingId; |
| 32 | use crate::domain::exam_weight::ExamWeight; |
| 33 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 34 | use crate::service; |
| 35 | use crate::state::AppState; |
| 36 | use crate::web::instances::can_view_instance; |
| 37 | use crate::web::tenant_state::State; |
| 38 | |
| 39 | use super::{CurrentUser, RequireManager, RequireTeacher}; |
| 40 | |
| 41 | |
| 42 | pub fn offering_routes() -> OpenApiRouter<AppState> { |
| 43 | OpenApiRouter::new() |
| 44 | .routes(routes!(get_offering_weights, patch_offering_weight)) |
| 45 | .routes(routes!(delete_offering_weight)) |
| 46 | } |
| 47 | |
| 48 | |
| 49 | pub fn instance_routes() -> OpenApiRouter<AppState> { |
| 50 | OpenApiRouter::new() |
| 51 | .routes(routes!(get_instance_weights, patch_instance_weight)) |
| 52 | .routes(routes!(delete_instance_weight)) |
| 53 | .routes(routes!(reset_instance_weights)) |
| 54 | } |
| 55 | |
| 56 | #[derive(Deserialize, ToSchema)] |
| 57 | struct PatchExamWeight { |
| 58 | |
| 59 | |
| 60 | #[schema(example = "midterm")] |
| 61 | kind: String, |
| 62 | |
| 63 | #[schema(minimum = 1, maximum = 100, example = 3)] |
| 64 | weight: i64, |
| 65 | } |
| 66 | |
| 67 | |
| 68 | |
| 69 | #[derive(Serialize, ToSchema)] |
| 70 | pub struct ExamWeightEntry { |
| 71 | #[schema(example = "midterm")] |
| 72 | pub kind: String, |
| 73 | pub weight: i64, |
| 74 | } |
| 75 | |
| 76 | impl ExamWeightEntry { |
| 77 | pub(crate) fn of(row: &ExamWeight) -> Self { |
| 78 | Self { |
| 79 | kind: row.get_kind().to_string(), |
| 80 | weight: row.get_weight(), |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | |
| 86 | #[derive(Serialize, ToSchema)] |
| 87 | pub struct OfferingExamWeightsResponse { |
| 88 | |
| 89 | |
| 90 | |
| 91 | pub weights: Vec<ExamWeightEntry>, |
| 92 | } |
| 93 | |
| 94 | |
| 95 | #[derive(Serialize, ToSchema)] |
| 96 | pub struct InstanceExamWeightsResponse { |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | pub inherited: bool, |
| 102 | pub weights: Vec<ExamWeightEntry>, |
| 103 | } |
| 104 | |
| 105 | async fn offering_or_404(key: &str, db: &Database) -> Result<CourseOfferingId, AppError> { |
| 106 | let id = CourseOfferingId::from_key(key); |
| 107 | if service::course_offering::read(db, &id).await?.is_none() { |
| 108 | return Err(AppError::NotFound); |
| 109 | } |
| 110 | Ok(id) |
| 111 | } |
| 112 | |
| 113 | |
| 114 | |
| 115 | async fn instance_or_404(key: &str, db: &Database) -> Result<ClassCourse, AppError> { |
| 116 | service::class_course::read(db, &ClassCourseId::from_key(key)) |
| 117 | .await? |
| 118 | .ok_or(AppError::NotFound) |
| 119 | } |
| 120 | |
| 121 | |
| 122 | |
| 123 | fn kind_refusal(err: AppError, kind: &str) -> Response { |
| 124 | if let AppError::Validation(ValidationError::Invalid { field: "kind", .. }) = &err { |
| 125 | return ( |
| 126 | StatusCode::BAD_REQUEST, |
| 127 | Json(serde_json::json!({ |
| 128 | "error": format!("kind: `{kind}` is not a known exam kind"), |
| 129 | "code": "unknown_exam_kind", |
| 130 | })), |
| 131 | ) |
| 132 | .into_response(); |
| 133 | } |
| 134 | err.into_response() |
| 135 | } |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | #[utoipa::path( |
| 142 | get, |
| 143 | path = "/{id}/exam-weights", |
| 144 | tag = "offerings", |
| 145 | security(("session_cookie" = [])), |
| 146 | params(("id" = String, Path, description = "Offering id")), |
| 147 | responses( |
| 148 | (status = 200, description = "The offering's resolved weights", body = OfferingExamWeightsResponse), |
| 149 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 150 | (status = 404, description = "Offering not found", body = ErrorResponse), |
| 151 | ), |
| 152 | )] |
| 153 | async fn get_offering_weights( |
| 154 | State(st): State<AppState>, |
| 155 | CurrentUser(_user): CurrentUser, |
| 156 | Path(id): Path<String>, |
| 157 | ) -> Result<Json<OfferingExamWeightsResponse>, AppError> { |
| 158 | let offering = offering_or_404(&id, &st.db).await?; |
| 159 | let weights = service::exam_weight::resolved_for_offering(&st.db, &offering).await?; |
| 160 | Ok(Json(OfferingExamWeightsResponse { |
| 161 | weights: weights.iter().map(ExamWeightEntry::of).collect(), |
| 162 | })) |
| 163 | } |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | #[utoipa::path( |
| 170 | patch, |
| 171 | path = "/{id}/exam-weights", |
| 172 | tag = "offerings", |
| 173 | security(("session_cookie" = [])), |
| 174 | params(("id" = String, Path, description = "Offering id")), |
| 175 | request_body = PatchExamWeight, |
| 176 | responses( |
| 177 | (status = 200, description = "The offering's resolved weights after the write", body = OfferingExamWeightsResponse), |
| 178 | (status = 400, description = "A weight outside 1..=100, or a kind the school does not run (body carries the machine code `unknown_exam_kind`)", body = ErrorResponse), |
| 179 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 180 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 181 | (status = 404, description = "Offering not found", body = ErrorResponse), |
| 182 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 183 | ), |
| 184 | )] |
| 185 | async fn patch_offering_weight( |
| 186 | State(st): State<AppState>, |
| 187 | RequireManager(_user): RequireManager, |
| 188 | Path(id): Path<String>, |
| 189 | Json(req): Json<PatchExamWeight>, |
| 190 | ) -> Result<Response, AppError> { |
| 191 | let offering = offering_or_404(&id, &st.db).await?; |
| 192 | if let Err(err) = |
| 193 | service::exam_weight::set_for_offering(&st.db, &offering, &req.kind, req.weight).await |
| 194 | { |
| 195 | return Ok(kind_refusal(err, &req.kind)); |
| 196 | } |
| 197 | let weights = service::exam_weight::resolved_for_offering(&st.db, &offering).await?; |
| 198 | Ok(Json(OfferingExamWeightsResponse { |
| 199 | weights: weights.iter().map(ExamWeightEntry::of).collect(), |
| 200 | }) |
| 201 | .into_response()) |
| 202 | } |
| 203 | |
| 204 | |
| 205 | |
| 206 | #[utoipa::path( |
| 207 | delete, |
| 208 | path = "/{id}/exam-weights/{kind}", |
| 209 | tag = "offerings", |
| 210 | security(("session_cookie" = [])), |
| 211 | params( |
| 212 | ("id" = String, Path, description = "Offering id"), |
| 213 | ("kind" = String, Path, description = "Exam kind"), |
| 214 | ), |
| 215 | responses( |
| 216 | (status = 204, description = "Row deleted — the settings weight applies again"), |
| 217 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 218 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 219 | (status = 404, description = "Offering not found, or it carries no weight row for this kind", body = ErrorResponse), |
| 220 | ), |
| 221 | )] |
| 222 | async fn delete_offering_weight( |
| 223 | State(st): State<AppState>, |
| 224 | RequireManager(_user): RequireManager, |
| 225 | Path((id, kind)): Path<(String, String)>, |
| 226 | ) -> Result<StatusCode, AppError> { |
| 227 | let offering = offering_or_404(&id, &st.db).await?; |
| 228 | service::exam_weight::remove_from_offering(&st.db, &offering, &kind).await?; |
| 229 | Ok(StatusCode::NO_CONTENT) |
| 230 | } |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | #[utoipa::path( |
| 237 | get, |
| 238 | path = "/{id}/exam-weights", |
| 239 | tag = "instances", |
| 240 | security(("session_cookie" = [])), |
| 241 | params(("id" = String, Path, description = "Instance id")), |
| 242 | responses( |
| 243 | (status = 200, description = "The section's resolved weights, with the inherited flag", body = InstanceExamWeightsResponse), |
| 244 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 245 | (status = 403, description = "Not enrolled, not this instance's teacher, and not a manager/admin", body = ErrorResponse), |
| 246 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| 247 | ), |
| 248 | )] |
| 249 | async fn get_instance_weights( |
| 250 | State(st): State<AppState>, |
| 251 | CurrentUser(user): CurrentUser, |
| 252 | Path(id): Path<String>, |
| 253 | ) -> Result<Json<InstanceExamWeightsResponse>, AppError> { |
| 254 | let instance = instance_or_404(&id, &st.db).await?; |
| 255 | if !can_view_instance(&st.db, instance.get_id(), &user).await? { |
| 256 | return Err(AppError::Forbidden( |
| 257 | "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view its weights", |
| 258 | )); |
| 259 | } |
| 260 | let (inherited, weights) = service::exam_weight::resolved_for_class(&st.db, &instance).await?; |
| 261 | Ok(Json(InstanceExamWeightsResponse { |
| 262 | inherited, |
| 263 | weights: weights.iter().map(ExamWeightEntry::of).collect(), |
| 264 | })) |
| 265 | } |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | #[utoipa::path( |
| 272 | patch, |
| 273 | path = "/{id}/exam-weights", |
| 274 | tag = "instances", |
| 275 | security(("session_cookie" = [])), |
| 276 | params(("id" = String, Path, description = "Instance id")), |
| 277 | request_body = PatchExamWeight, |
| 278 | responses( |
| 279 | (status = 200, description = "The section's resolved weights after the write (`inherited` now `false`)", body = InstanceExamWeightsResponse), |
| 280 | (status = 400, description = "A weight outside 1..=100, or a kind the school does not run (body carries the machine code `unknown_exam_kind`)", body = ErrorResponse), |
| 281 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 282 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 283 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| 284 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 285 | ), |
| 286 | )] |
| 287 | async fn patch_instance_weight( |
| 288 | State(st): State<AppState>, |
| 289 | RequireTeacher(user): RequireTeacher, |
| 290 | Path(id): Path<String>, |
| 291 | Json(req): Json<PatchExamWeight>, |
| 292 | ) -> Result<Response, AppError> { |
| 293 | let instance = instance_or_404(&id, &st.db).await?; |
| 294 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 295 | if let Err(err) = |
| 296 | service::exam_weight::set_for_class(&st.db, instance.get_id(), &req.kind, req.weight).await |
| 297 | { |
| 298 | return Ok(kind_refusal(err, &req.kind)); |
| 299 | } |
| 300 | |
| 301 | |
| 302 | let fresh = service::class_course::read(&st.db, instance.get_id()) |
| 303 | .await? |
| 304 | .ok_or(AppError::NotFound)?; |
| 305 | let (inherited, weights) = service::exam_weight::resolved_for_class(&st.db, &fresh).await?; |
| 306 | Ok(Json(InstanceExamWeightsResponse { |
| 307 | inherited, |
| 308 | weights: weights.iter().map(ExamWeightEntry::of).collect(), |
| 309 | }) |
| 310 | .into_response()) |
| 311 | } |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | #[utoipa::path( |
| 318 | delete, |
| 319 | path = "/{id}/exam-weights/{kind}", |
| 320 | tag = "instances", |
| 321 | security(("session_cookie" = [])), |
| 322 | params( |
| 323 | ("id" = String, Path, description = "Instance id"), |
| 324 | ("kind" = String, Path, description = "Exam kind"), |
| 325 | ), |
| 326 | responses( |
| 327 | (status = 204, description = "Row deleted — the section's own set stays authoritative without it"), |
| 328 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 329 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 330 | (status = 404, description = "Instance not found, or it carries no weight row for this kind", body = ErrorResponse), |
| 331 | ), |
| 332 | )] |
| 333 | async fn delete_instance_weight( |
| 334 | State(st): State<AppState>, |
| 335 | RequireTeacher(user): RequireTeacher, |
| 336 | Path((id, kind)): Path<(String, String)>, |
| 337 | ) -> Result<StatusCode, AppError> { |
| 338 | let instance = instance_or_404(&id, &st.db).await?; |
| 339 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 340 | service::exam_weight::remove_from_class(&st.db, instance.get_id(), &kind).await?; |
| 341 | Ok(StatusCode::NO_CONTENT) |
| 342 | } |
| 343 | |
| 344 | |
| 345 | |
| 346 | #[utoipa::path( |
| 347 | delete, |
| 348 | path = "/{id}/exam-weights", |
| 349 | tag = "instances", |
| 350 | security(("session_cookie" = [])), |
| 351 | params(("id" = String, Path, description = "Instance id")), |
| 352 | responses( |
| 353 | (status = 204, description = "Rows deleted — inheritance restored"), |
| 354 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 355 | (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse), |
| 356 | (status = 404, description = "Instance not found", body = ErrorResponse), |
| 357 | ), |
| 358 | )] |
| 359 | async fn reset_instance_weights( |
| 360 | State(st): State<AppState>, |
| 361 | RequireTeacher(user): RequireTeacher, |
| 362 | Path(id): Path<String>, |
| 363 | ) -> Result<StatusCode, AppError> { |
| 364 | let instance = instance_or_404(&id, &st.db).await?; |
| 365 | service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?; |
| 366 | service::exam_weight::reset_class(&st.db, instance.get_id()).await?; |
| 367 | Ok(StatusCode::NO_CONTENT) |
| 368 | } |