hezarfen_backend
Clone
https://git.tahinli.com/archive/hezarfen_backend.git
0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits
| 1 | //! Integration tests: drive the assembled axum router directly (no network) |
| 2 | //! against a fresh per-test Postgres deployment, via `tower::ServiceExt::oneshot`. |
| 3 | |
| 4 | mod common; |
| 5 | |
| 6 | use axum::body::Body; |
| 7 | use axum::http::{Request, StatusCode}; |
| 8 | use common::{ |
| 9 | add_member, app_and_db, app_and_tenants, attach_instance, create_class, create_course, |
| 10 | create_exam, create_exam_with, create_homework, create_session, create_subject, create_term, |
| 11 | create_year, enroll, ensure_year, id_of, login, login_as, me_id, mem_app, select_instance_subject, |
| 12 | send, set_role, taught, taught_under, unenroll, upload_course_note_file, |
| 13 | }; |
| 14 | use hezarfen_backend::build_router; |
| 15 | use hezarfen_backend::constant::{ |
| 16 | BANK_VISIBILITY_SCHOOL, MAX_BOARD_STROKES, MAX_BOARDS_PER_CREATOR, MAX_CLASS_MEMBERS, |
| 17 | MAX_COURSE_NOTE_FILES, MAX_EPOCH_STROKES, MAX_FEE_PLAN_ASSIGN_STUDENTS, |
| 18 | }; |
| 19 | use hezarfen_backend::db::exam_attempt::any_for_exam; |
| 20 | use hezarfen_backend::db::session; |
| 21 | use hezarfen_backend::domain::board::{Board, BoardId}; |
| 22 | use hezarfen_backend::domain::board_stroke::{BoardStroke, BoardStrokeId}; |
| 23 | use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId; |
| 24 | use hezarfen_backend::domain::course::CourseId; |
| 25 | use hezarfen_backend::domain::course_note::CourseNoteId; |
| 26 | use hezarfen_backend::domain::course_note_file::CourseNoteFileId; |
| 27 | use hezarfen_backend::domain::exam::ExamId; |
| 28 | use hezarfen_backend::domain::timestamp::Timestamp; |
| 29 | use hezarfen_backend::domain::user::{Password, UserId, Username}; |
| 30 | use hezarfen_backend::module::ModuleSet; |
| 31 | use hezarfen_backend::state::AppState; |
| 32 | use serde_json::json; |
| 33 | use tower::ServiceExt; |
| 34 | use uuid::Uuid; |
| 35 | |
| 36 | // --- health + auth ------------------------------------------------------- |
| 37 | |
| 38 | #[tokio::test] |
| 39 | async fn health_reports_ok() { |
| 40 | let app = mem_app().await; |
| 41 | let res = send(&app, "GET", "/health", None, None).await; |
| 42 | assert_eq!(res.status, StatusCode::OK); |
| 43 | assert_eq!(res.body["status"], "ok"); |
| 44 | assert_eq!(res.body["db"], "up"); |
| 45 | // No `AI_QUIC_ADDR` in the suites, so the bridge is off — which is a |
| 46 | // configuration, not a fault: the status stays `ok`. |
| 47 | assert_eq!(res.body["ai"]["enabled"], false); |
| 48 | assert_eq!(res.body["ai"]["workers"], 0); |
| 49 | } |
| 50 | |
| 51 | /// The probe must survive the outage it reports. A wedged database refuses |
| 52 | /// everything else with a generic timeout while `/health` (and `/`) answer |
| 53 | /// their own 503 that names the database, or the probe is useless exactly when |
| 54 | /// it is needed. The control pool is closed to play the outage: the probe then |
| 55 | /// cannot reach its database, which is what a dead server looks like from a |
| 56 | /// pool handle. |
| 57 | #[tokio::test] |
| 58 | async fn health_reports_the_database_down_instead_of_being_refused() { |
| 59 | let (app, _db, tenants) = app_and_tenants().await; |
| 60 | let res = send(&app, "GET", "/health", None, None).await; |
| 61 | assert_eq!(res.status, StatusCode::OK); |
| 62 | assert_eq!(res.body["db"], "up"); |
| 63 | |
| 64 | tenants.control().close().await; |
| 65 | for path in ["/health", "/"] { |
| 66 | let res = send(&app, "GET", path, None, None).await; |
| 67 | assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{path}"); |
| 68 | assert_eq!(res.body["status"], "degraded", "{path}"); |
| 69 | assert_eq!(res.body["db"], "down", "{path}"); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | #[tokio::test] |
| 74 | async fn time_serves_server_clock_without_auth() { |
| 75 | let app = mem_app().await; |
| 76 | |
| 77 | let before = Timestamp::now().as_millis(); |
| 78 | let res = send(&app, "GET", "/time", None, None).await; |
| 79 | let after = Timestamp::now().as_millis(); |
| 80 | |
| 81 | assert_eq!(res.status, StatusCode::OK); |
| 82 | // Bracketed by two local reads: proves it is the same clock in millis, |
| 83 | // not seconds/nanos or some other epoch. |
| 84 | let now = res.body["now"].as_i64().expect("now is an integer"); |
| 85 | assert!(before <= now && now <= after); |
| 86 | } |
| 87 | |
| 88 | /// `GET /school` is the school the session cookie is already bound to. |
| 89 | /// Every authenticated role may read it; a missing cookie and a builder |
| 90 | /// cookie are both `401`, the same as every other school surface. The body |
| 91 | /// is the registry uuid and the display name — never the slug. |
| 92 | #[tokio::test] |
| 93 | async fn get_school_returns_uuid_and_name_without_slug() { |
| 94 | let (app, db, tenants) = app_and_tenants().await; |
| 95 | let (id, name): (Uuid, String) = |
| 96 | sqlx::query_as("SELECT id, name FROM school WHERE id = '019732e3-7b00-7000-8000-00000000dead'") |
| 97 | .fetch_one(tenants.control()) |
| 98 | .await |
| 99 | .expect("demo school"); |
| 100 | |
| 101 | let anon = send(&app, "GET", "/school", None, None).await; |
| 102 | assert_eq!(anon.status, StatusCode::UNAUTHORIZED); |
| 103 | |
| 104 | hezarfen_backend::service::builder::ensure( |
| 105 | tenants.control(), |
| 106 | Username::try_new("operator").unwrap(), |
| 107 | Password::try_new("secret1").unwrap(), |
| 108 | ) |
| 109 | .await |
| 110 | .expect("seed the builder"); |
| 111 | let builder_login = send( |
| 112 | &app, |
| 113 | "POST", |
| 114 | "/builder/login", |
| 115 | None, |
| 116 | Some(json!({ "username": "operator", "password": "secret1" })), |
| 117 | ) |
| 118 | .await; |
| 119 | assert_eq!(builder_login.status, StatusCode::OK, "{}", builder_login.body); |
| 120 | let builder_cookie = builder_login.cookie.expect("builder cookie"); |
| 121 | let builder = send(&app, "GET", "/school", Some(&builder_cookie), None).await; |
| 122 | assert_eq!(builder.status, StatusCode::UNAUTHORIZED, "{}", builder.body); |
| 123 | |
| 124 | let expected = json!({ "id": id.to_string(), "name": name }); |
| 125 | for (username, role) in [("school_student", "student"), ("school_parent", "parent")] { |
| 126 | let cookie = login_as(&app, &db, username, role).await; |
| 127 | let res = send(&app, "GET", "/school", Some(&cookie), None).await; |
| 128 | assert_eq!(res.status, StatusCode::OK, "{role}: {}", res.body); |
| 129 | assert_eq!(res.body, expected, "{role}"); |
| 130 | assert!( |
| 131 | res.body.get("slug").is_none(), |
| 132 | "{role} response must not carry a slug: {}", |
| 133 | res.body |
| 134 | ); |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | #[tokio::test] |
| 139 | async fn limits_publishes_the_bounds_the_api_actually_enforces() { |
| 140 | let app = mem_app().await; |
| 141 | |
| 142 | let res = send(&app, "GET", "/limits", None, None).await; |
| 143 | assert_eq!(res.status, StatusCode::OK); |
| 144 | |
| 145 | // Every group is present — a frontend reads one document, not thirteen. |
| 146 | for group in [ |
| 147 | "user", |
| 148 | "note", |
| 149 | "file", |
| 150 | "message", |
| 151 | "event", |
| 152 | "course", |
| 153 | "exam", |
| 154 | "homework", |
| 155 | "question_pool", |
| 156 | "appointment", |
| 157 | "chatbot", |
| 158 | "settings", |
| 159 | "request", |
| 160 | ] { |
| 161 | assert!(res.body[group].is_object(), "missing group: {group}"); |
| 162 | } |
| 163 | |
| 164 | // The published value must equal the one the constants carry — the whole |
| 165 | // point is that the frontend stops keeping its own copy. |
| 166 | assert_eq!( |
| 167 | res.body["user"]["max_username_len"], |
| 168 | json!(hezarfen_backend::constant::MAX_USERNAME_LEN) |
| 169 | ); |
| 170 | assert_eq!(res.body["exam"]["modes"], json!(["sync", "async", "open"])); |
| 171 | // The accent color is published as a pattern, not a value list — it is an |
| 172 | // open set, so a client validates the shape instead of a fixed palette. |
| 173 | assert_eq!( |
| 174 | res.body["user"]["palette_color_pattern"], |
| 175 | json!(hezarfen_backend::constant::PALETTE_COLOR_PATTERN) |
| 176 | ); |
| 177 | assert_eq!( |
| 178 | res.body["user"]["palette_color_len"], |
| 179 | json!(hezarfen_backend::constant::PALETTE_COLOR_LEN) |
| 180 | ); |
| 181 | assert_eq!( |
| 182 | res.body["user"]["roles"], |
| 183 | json!(["parent", "student", "teacher", "manager", "admin"]) |
| 184 | ); |
| 185 | |
| 186 | // The request budgets a caller is actually held to, read live off this |
| 187 | // server rather than from a constant — a client should learn its budget |
| 188 | // here, not by collecting a 429. |
| 189 | assert!(res.body["rate"]["auth_per_minute"].is_number()); |
| 190 | assert!(res.body["rate"]["api_per_minute"].is_number()); |
| 191 | assert!(res.body["rate"]["chatbot_per_minute"].is_number()); |
| 192 | assert_eq!(res.body["rate"]["window_secs"], json!(60)); |
| 193 | |
| 194 | // Structural sanity over EVERY published pair, which is what a spot-check |
| 195 | // of a few named fields cannot give: any `min_x` must not exceed its |
| 196 | // `max_x`. This is what catches a mapping that wired a floor to a ceiling |
| 197 | // — the one mistake a "does the constant appear?" check cannot see. |
| 198 | let groups = res.body.as_object().expect("limits is an object"); |
| 199 | let mut checked = 0; |
| 200 | for (group, fields) in groups { |
| 201 | let fields = fields.as_object().expect("each group is an object"); |
| 202 | for (key, value) in fields { |
| 203 | let Some(bare) = key.strip_prefix("min_") else { |
| 204 | continue; |
| 205 | }; |
| 206 | let Some(max) = fields.get(&format!("max_{bare}")) else { |
| 207 | continue; |
| 208 | }; |
| 209 | let (min, max) = ( |
| 210 | value.as_i64().expect("min is an integer"), |
| 211 | max.as_i64().expect("max is an integer"), |
| 212 | ); |
| 213 | assert!( |
| 214 | min <= max, |
| 215 | "{group}.{key} ({min}) exceeds its maximum ({max}) — the pair is inverted" |
| 216 | ); |
| 217 | checked += 1; |
| 218 | } |
| 219 | } |
| 220 | assert!( |
| 221 | checked >= 10, |
| 222 | "only {checked} min/max pairs were checked — the pairing broke, not the values" |
| 223 | ); |
| 224 | |
| 225 | // …and the endpoint that enforces it must agree: one over the published |
| 226 | // maximum is refused. This is what catches a constant moving without the |
| 227 | // limits response, or the reverse. |
| 228 | let max = res.body["user"]["max_username_len"] |
| 229 | .as_u64() |
| 230 | .expect("max_username_len is an integer") as usize; |
| 231 | let too_long = |
| 232 | json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "a".repeat(max + 1), "password": "secret1" }); |
| 233 | let res = send(&app, "POST", "/auth/register", None, Some(too_long)).await; |
| 234 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 235 | } |
| 236 | |
| 237 | #[tokio::test] |
| 238 | async fn limits_still_answers_while_the_database_is_down() { |
| 239 | // A frontend booting against a backend whose database is reconnecting is |
| 240 | // precisely when it needs the validation contract. `/limits` touches no |
| 241 | // row, so the outage must not take it down with the database — otherwise |
| 242 | // the client falls back to the hard-coded copy this endpoint exists to |
| 243 | // remove. The school pool is closed to play the outage. |
| 244 | let (tenants, db) = common::mem_deployment().await; |
| 245 | let app = build_router(AppState { |
| 246 | db: tenants.control().clone(), |
| 247 | tenants, |
| 248 | files_path: tempfile::tempdir().expect("files dir").keep(), |
| 249 | cookie_secure: false, |
| 250 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| 251 | chatbot_limit: Default::default(), |
| 252 | rag_limit: Default::default(), |
| 253 | exam_presence: Default::default(), |
| 254 | board_hub: Default::default(), |
| 255 | ai: None, |
| 256 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 257 | }); |
| 258 | let ali = login(&app, "ali").await; |
| 259 | db.close().await; |
| 260 | |
| 261 | let res = send(&app, "GET", "/limits", None, None).await; |
| 262 | assert_eq!(res.status, StatusCode::OK); |
| 263 | assert!(res.body["user"]["max_username_len"].is_number()); |
| 264 | |
| 265 | // Everything that does touch the database still refuses, so the static |
| 266 | // route staying up is not the database silently passing for healthy. |
| 267 | let res = send(&app, "GET", "/settings", Some(&ali), None).await; |
| 268 | assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE); |
| 269 | } |
| 270 | |
| 271 | #[tokio::test] |
| 272 | async fn register_validates_input() { |
| 273 | let app = mem_app().await; |
| 274 | |
| 275 | // Password too short -> 400. |
| 276 | let short = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "bob", "password": "123" }); |
| 277 | let res = send(&app, "POST", "/auth/register", None, Some(short)).await; |
| 278 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 279 | |
| 280 | // Blank username -> 400. |
| 281 | let blank = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": " ", "password": "secret1" }); |
| 282 | let res = send(&app, "POST", "/auth/register", None, Some(blank)).await; |
| 283 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 284 | |
| 285 | // Uppercase anywhere in the username -> 400. |
| 286 | for bad in ["Bob", "bOb", "BOB"] { |
| 287 | let upper = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": bad, "password": "secret1" }); |
| 288 | let res = send(&app, "POST", "/auth/register", None, Some(upper)).await; |
| 289 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted"); |
| 290 | } |
| 291 | |
| 292 | // Username must start and end with a letter or digit -> 400. |
| 293 | for bad in ["-bob", "bob-", "_bob", "bob_", ".bob"] { |
| 294 | let edge = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": bad, "password": "secret1" }); |
| 295 | let res = send(&app, "POST", "/auth/register", None, Some(edge)).await; |
| 296 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted"); |
| 297 | } |
| 298 | |
| 299 | // Interior characters are an allowlist: lowercase, digits, . _ - only. |
| 300 | for bad in [ |
| 301 | "a b", |
| 302 | "a\nb", |
| 303 | "a\u{1b}[31mb", |
| 304 | "a<b>c", |
| 305 | "a@b.c", |
| 306 | "a/b", |
| 307 | "a\"b", |
| 308 | ] { |
| 309 | let ugly = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": bad, "password": "secret1" }); |
| 310 | let res = send(&app, "POST", "/auth/register", None, Some(ugly)).await; |
| 311 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad:?} accepted"); |
| 312 | } |
| 313 | |
| 314 | // Consecutive separators -> 400. |
| 315 | for bad in ["a--b", "a..b", "a__b", "a.-b"] { |
| 316 | let doubled = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": bad, "password": "secret1" }); |
| 317 | let res = send(&app, "POST", "/auth/register", None, Some(doubled)).await; |
| 318 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted"); |
| 319 | } |
| 320 | |
| 321 | // Single separators between alphanumerics are fine -> 201. |
| 322 | let dotted = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ali.k_1-b", "password": "secret1" }); |
| 323 | let res = send(&app, "POST", "/auth/register", None, Some(dotted)).await; |
| 324 | assert_eq!(res.status, StatusCode::CREATED); |
| 325 | assert_eq!(res.body["username"], "ali.k_1-b"); |
| 326 | |
| 327 | // Valid -> 201, no password echoed back, defaults to the student role. |
| 328 | let ok = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "bob", "password": "secret1" }); |
| 329 | let res = send(&app, "POST", "/auth/register", None, Some(ok)).await; |
| 330 | assert_eq!(res.status, StatusCode::CREATED); |
| 331 | assert_eq!(res.body["username"], "bob"); |
| 332 | assert_eq!(res.body["role"], "student"); |
| 333 | assert!(res.body.get("password_hash").is_none()); |
| 334 | |
| 335 | // A duplicate answers 201 like any other register (the "taken" reply is |
| 336 | // deliberately indistinguishable — see tests/auth_enumeration.rs), but the |
| 337 | // write is still rejected: the original password keeps working and the |
| 338 | // second one never becomes valid. |
| 339 | let dup = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "bob", "password": "hijack1" }); |
| 340 | let res = send(&app, "POST", "/auth/register", None, Some(dup)).await; |
| 341 | assert_eq!(res.status, StatusCode::CREATED); |
| 342 | let res = send( |
| 343 | &app, |
| 344 | "POST", |
| 345 | "/auth/login", |
| 346 | None, |
| 347 | Some(json!({ "username": "bob", "password": "secret1" })), |
| 348 | ) |
| 349 | .await; |
| 350 | assert_eq!( |
| 351 | res.status, |
| 352 | StatusCode::OK, |
| 353 | "original password stopped working" |
| 354 | ); |
| 355 | let res = send( |
| 356 | &app, |
| 357 | "POST", |
| 358 | "/auth/login", |
| 359 | None, |
| 360 | Some(json!({ "username": "bob", "password": "hijack1" })), |
| 361 | ) |
| 362 | .await; |
| 363 | assert_eq!( |
| 364 | res.status, |
| 365 | StatusCode::UNAUTHORIZED, |
| 366 | "the duplicate register overwrote the account" |
| 367 | ); |
| 368 | } |
| 369 | |
| 370 | #[tokio::test] |
| 371 | async fn register_rejects_reserved_usernames() { |
| 372 | let app = mem_app().await; |
| 373 | |
| 374 | // Staff-looking names can't be claimed through public registration. |
| 375 | for name in [ |
| 376 | "admin", |
| 377 | "administrator", |
| 378 | "root", |
| 379 | "support", |
| 380 | "system", |
| 381 | "moderator", |
| 382 | "staff", |
| 383 | ] { |
| 384 | let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": name, "password": "secret1" }); |
| 385 | let res = send(&app, "POST", "/auth/register", None, Some(creds)).await; |
| 386 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{name} accepted"); |
| 387 | let msg = res.body["error"].as_str().unwrap_or_default(); |
| 388 | assert!( |
| 389 | msg.contains("reserved"), |
| 390 | "unexpected error for {name}: {msg}" |
| 391 | ); |
| 392 | } |
| 393 | |
| 394 | // The reservation is registration-only policy: the seeded bootstrap admin |
| 395 | // (created through `ensure_admin`, not `/auth/register`) still logs in. |
| 396 | // Covered by the admin bootstrap tests; here just prove a reserved name |
| 397 | // is not permanently poisoned for login by the register-level check. |
| 398 | let creds = json!({ "username": "admin", "password": "wrong" }); |
| 399 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 400 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); // bad credentials, not "reserved" |
| 401 | } |
| 402 | |
| 403 | #[tokio::test] |
| 404 | async fn login_rejects_bad_credentials() { |
| 405 | let app = mem_app().await; |
| 406 | send( |
| 407 | &app, |
| 408 | "POST", |
| 409 | "/auth/register", |
| 410 | None, |
| 411 | Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "kate", "password": "secret1" })), |
| 412 | ) |
| 413 | .await; |
| 414 | |
| 415 | // Wrong password. |
| 416 | let res = send( |
| 417 | &app, |
| 418 | "POST", |
| 419 | "/auth/login", |
| 420 | None, |
| 421 | Some(json!({ "username": "kate", "password": "wrong" })), |
| 422 | ) |
| 423 | .await; |
| 424 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); |
| 425 | |
| 426 | // Unknown user. |
| 427 | let res = send( |
| 428 | &app, |
| 429 | "POST", |
| 430 | "/auth/login", |
| 431 | None, |
| 432 | Some(json!({ "username": "ghost", "password": "secret1" })), |
| 433 | ) |
| 434 | .await; |
| 435 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); |
| 436 | } |
| 437 | |
| 438 | /// Routes that answer without a session, on purpose. Adding a route here is a |
| 439 | /// deliberate, reviewable decision to leave a door open — everything else in |
| 440 | /// the spec is asserted to reject an anonymous caller with a 401. |
| 441 | const PUBLIC: &[(&str, &str)] = &[ |
| 442 | ("GET", "/health"), |
| 443 | ("GET", "/time"), |
| 444 | ("GET", "/limits"), |
| 445 | // The deployment's product catalog: which modules exist, what each needs, |
| 446 | // how they are packaged. Deploy-constant and identical for every school — |
| 447 | // public for the same reason `/limits` is. What one school *bought* is |
| 448 | // `GET /modules`, which is behind a session. |
| 449 | ("GET", "/modules/catalog"), |
| 450 | ("POST", "/auth/register"), |
| 451 | ("POST", "/auth/login"), |
| 452 | // Person-cookie gated, not a school session: OpenAPI declares no |
| 453 | // session_cookie security, so the public-route audit lists it here. |
| 454 | ("POST", "/auth/school"), |
| 455 | // Register's school picker: active `{id, name}` rows, no session. |
| 456 | ("GET", "/auth/schools"), |
| 457 | // Idempotent: revokes the session if there is one, `204` either way. |
| 458 | ("POST", "/auth/logout"), |
| 459 | // A server certificate is handed to every peer in the TLS handshake, so |
| 460 | // publishing it discloses nothing (see the module doc in `web/ai.rs`). |
| 461 | ("GET", "/ai/certificate"), |
| 462 | // The vendor's own credential endpoint: the door a builder session comes |
| 463 | // out of, behind the same strict per-IP tier `/auth/login` sits behind. |
| 464 | ("POST", "/builder/login"), |
| 465 | // Idempotent, like `/auth/logout`: revokes the builder session if there is |
| 466 | // one, `204` either way. |
| 467 | ("POST", "/builder/logout"), |
| 468 | ]; |
| 469 | |
| 470 | /// Router paths that carry no OpenAPI operation, so the derived sweep below |
| 471 | /// cannot see them: `OpenApiRouter` has no way to describe a WebSocket |
| 472 | /// upgrade, so both rooms are plain `.route()`s. They authenticate before they |
| 473 | /// upgrade, so a rejection is an ordinary HTTP status here. |
| 474 | const UNDOCUMENTED_WS: &[(&str, &str)] = &[("GET", "/exams/x/attempt/ws"), ("GET", "/boards/x/ws")]; |
| 475 | |
| 476 | /// Every protected operation the server publishes must reject a caller with no |
| 477 | /// cookie — derived from the emitted OpenAPI document, never from a list |
| 478 | /// somebody keeps by hand. A hand-kept list drifts silently, and the drift is |
| 479 | /// auth coverage: ~10 route families were missing from the one this replaced. |
| 480 | /// |
| 481 | /// Route and spec entry come from the same `routes!()` macro, so a family that |
| 482 | /// leaves the router leaves the document too; `MIN_PROTECTED` is what makes |
| 483 | /// that visible instead of a quietly shorter sweep. |
| 484 | #[tokio::test] |
| 485 | async fn protected_routes_require_session() { |
| 486 | /// Floor on the number of protected operations swept. It only ever goes |
| 487 | /// up: raise it when routes are added. Without it, deleting a route family |
| 488 | /// would delete its own coverage and still pass. |
| 489 | const MIN_PROTECTED: usize = 343; |
| 490 | |
| 491 | let app = mem_app().await; |
| 492 | let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) |
| 493 | .await |
| 494 | .body; |
| 495 | let paths = spec["paths"].as_object().expect("spec has paths"); |
| 496 | |
| 497 | let mut checked = 0; |
| 498 | for (path, item) in paths { |
| 499 | let item = item.as_object().expect("path item is an object"); |
| 500 | for (method, operation) in item { |
| 501 | let secured = operation["security"] |
| 502 | .as_array() |
| 503 | .is_some_and(|requirements| { |
| 504 | requirements |
| 505 | .iter() |
| 506 | .any(|requirement| requirement.get("session_cookie").is_some()) |
| 507 | }); |
| 508 | let method = method.to_uppercase(); |
| 509 | if !secured { |
| 510 | assert!( |
| 511 | PUBLIC.contains(&(method.as_str(), path.as_str())), |
| 512 | "{method} {path} declares no session requirement and is not \ |
| 513 | in the deliberate PUBLIC list" |
| 514 | ); |
| 515 | continue; |
| 516 | } |
| 517 | |
| 518 | // `{id}` → `x`, but an integer-typed parameter (a choice index) |
| 519 | // has to stay parseable or axum answers 400 before the extractor |
| 520 | // that would have answered 401. |
| 521 | let mut uri = path.clone(); |
| 522 | for parameter in operation["parameters"].as_array().unwrap_or(&vec![]) { |
| 523 | let name = parameter["name"].as_str().expect("parameter name"); |
| 524 | let placeholder = if parameter["schema"]["type"] == "integer" { |
| 525 | "0" |
| 526 | } else { |
| 527 | "x" |
| 528 | }; |
| 529 | uri = uri.replace(&format!("{{{name}}}"), placeholder); |
| 530 | } |
| 531 | assert!(!uri.contains('{'), "unsubstituted path parameter: {uri}"); |
| 532 | |
| 533 | let res = send(&app, &method, &uri, None, None).await; |
| 534 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}"); |
| 535 | checked += 1; |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | for (method, uri) in UNDOCUMENTED_WS { |
| 540 | let res = send(&app, method, uri, None, None).await; |
| 541 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}"); |
| 542 | } |
| 543 | |
| 544 | assert!( |
| 545 | checked >= MIN_PROTECTED, |
| 546 | "swept only {checked} protected operations, expected at least \ |
| 547 | {MIN_PROTECTED} — did a route family leave the router?" |
| 548 | ); |
| 549 | } |
| 550 | |
| 551 | /// The AI allowlist is a hand-kept list of router paths, so it can only drift |
| 552 | /// one way: a route is renamed and every entry naming it silently stops |
| 553 | /// matching, leaving the AI services with a scope that quietly shrank. Pinning |
| 554 | /// each entry to a `GET` in the emitted document makes the rename break here |
| 555 | /// instead of out there. |
| 556 | #[tokio::test] |
| 557 | async fn ai_allowlist_entries_are_real_get_routes() { |
| 558 | let app = mem_app().await; |
| 559 | let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) |
| 560 | .await |
| 561 | .body; |
| 562 | let paths = spec["paths"].as_object().expect("spec has paths"); |
| 563 | |
| 564 | for entry in hezarfen_backend::constant::AI_API_ALLOWLIST { |
| 565 | let item = paths |
| 566 | .get(*entry) |
| 567 | .unwrap_or_else(|| panic!("allowlisted {entry} is not a path in the OpenAPI document")); |
| 568 | assert!( |
| 569 | item.get("get").is_some(), |
| 570 | "allowlisted {entry} exists but serves no GET" |
| 571 | ); |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | #[tokio::test] |
| 576 | async fn garbage_cookie_is_unauthorized() { |
| 577 | let app = mem_app().await; |
| 578 | let res = send(&app, "GET", "/auth/me", Some("session=deadbeef"), None).await; |
| 579 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); |
| 580 | } |
| 581 | |
| 582 | #[tokio::test] |
| 583 | async fn me_returns_current_user_without_secrets() { |
| 584 | let app = mem_app().await; |
| 585 | let ali = login(&app, "ali").await; |
| 586 | let res = send(&app, "GET", "/auth/me", Some(&ali), None).await; |
| 587 | assert_eq!(res.status, StatusCode::OK); |
| 588 | assert_eq!(res.body["username"], "ali"); |
| 589 | assert_eq!(res.body["role"], "student"); |
| 590 | assert!(res.body.get("password_hash").is_none()); |
| 591 | } |
| 592 | |
| 593 | #[tokio::test] |
| 594 | async fn logout_invalidates_the_session_server_side() { |
| 595 | let app = mem_app().await; |
| 596 | let ali = login(&app, "ali").await; |
| 597 | |
| 598 | assert_eq!( |
| 599 | send(&app, "GET", "/auth/me", Some(&ali), None).await.status, |
| 600 | StatusCode::OK |
| 601 | ); |
| 602 | |
| 603 | let res = send(&app, "POST", "/auth/logout", Some(&ali), None).await; |
| 604 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 605 | assert_eq!( |
| 606 | res.cookie.as_deref(), |
| 607 | Some("session="), |
| 608 | "logout must send a clearing Set-Cookie, got {:?}", |
| 609 | res.cookie |
| 610 | ); |
| 611 | |
| 612 | // Re-using the same token now fails: the session row is gone. |
| 613 | let res = send(&app, "GET", "/auth/me", Some(&ali), None).await; |
| 614 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); |
| 615 | } |
| 616 | |
| 617 | // --- notes --------------------------------------------------------------- |
| 618 | |
| 619 | #[tokio::test] |
| 620 | async fn notes_crud_is_scoped_to_owner() { |
| 621 | let app = mem_app().await; |
| 622 | let ali = login(&app, "ali").await; |
| 623 | let veli = login(&app, "veli").await; |
| 624 | |
| 625 | let res = send( |
| 626 | &app, |
| 627 | "POST", |
| 628 | "/notes", |
| 629 | Some(&ali), |
| 630 | Some(json!({ "title": "first", "content": "hello" })), |
| 631 | ) |
| 632 | .await; |
| 633 | assert_eq!(res.status, StatusCode::CREATED); |
| 634 | let note_id = id_of(&res.body); |
| 635 | |
| 636 | // Partial update keeps the untouched field. |
| 637 | let res = send( |
| 638 | &app, |
| 639 | "PATCH", |
| 640 | &format!("/notes/{note_id}"), |
| 641 | Some(&ali), |
| 642 | Some(json!({ "content": "edited" })), |
| 643 | ) |
| 644 | .await; |
| 645 | assert_eq!(res.status, StatusCode::OK); |
| 646 | assert_eq!(res.body["content"], "edited"); |
| 647 | assert_eq!(res.body["title"], "first"); |
| 648 | |
| 649 | // Owner sees exactly one; other user sees none and gets 404 on direct access. |
| 650 | assert_eq!( |
| 651 | common::items(&send(&app, "GET", "/notes", Some(&ali), None).await.body).len(), |
| 652 | 1 |
| 653 | ); |
| 654 | assert_eq!( |
| 655 | send(&app, "GET", &format!("/notes/{note_id}"), Some(&veli), None) |
| 656 | .await |
| 657 | .status, |
| 658 | StatusCode::NOT_FOUND |
| 659 | ); |
| 660 | assert_eq!( |
| 661 | common::items(&send(&app, "GET", "/notes", Some(&veli), None).await.body).len(), |
| 662 | 0 |
| 663 | ); |
| 664 | |
| 665 | // Other user cannot update or delete it either. |
| 666 | assert_eq!( |
| 667 | send( |
| 668 | &app, |
| 669 | "PATCH", |
| 670 | &format!("/notes/{note_id}"), |
| 671 | Some(&veli), |
| 672 | Some(json!({"title":"x"})) |
| 673 | ) |
| 674 | .await |
| 675 | .status, |
| 676 | StatusCode::NOT_FOUND |
| 677 | ); |
| 678 | assert_eq!( |
| 679 | send( |
| 680 | &app, |
| 681 | "DELETE", |
| 682 | &format!("/notes/{note_id}"), |
| 683 | Some(&veli), |
| 684 | None |
| 685 | ) |
| 686 | .await |
| 687 | .status, |
| 688 | StatusCode::NOT_FOUND |
| 689 | ); |
| 690 | |
| 691 | // Delete, then it's gone. |
| 692 | assert_eq!( |
| 693 | send( |
| 694 | &app, |
| 695 | "DELETE", |
| 696 | &format!("/notes/{note_id}"), |
| 697 | Some(&ali), |
| 698 | None |
| 699 | ) |
| 700 | .await |
| 701 | .status, |
| 702 | StatusCode::NO_CONTENT |
| 703 | ); |
| 704 | assert_eq!( |
| 705 | send(&app, "GET", &format!("/notes/{note_id}"), Some(&ali), None) |
| 706 | .await |
| 707 | .status, |
| 708 | StatusCode::NOT_FOUND |
| 709 | ); |
| 710 | } |
| 711 | |
| 712 | /// A demotion to `parent` must not confiscate the account's own notes. It used |
| 713 | /// to: every note route required `student`, so after the demotion the owner |
| 714 | /// could no longer list, read or **delete** their notes — and since nothing |
| 715 | /// else in the crate reads a note and no route cascades one, the rows and their |
| 716 | /// on-disk blobs were unreachable and undeletable by everybody, forever. The |
| 717 | /// role bar is gone; the owner scoping that was always underneath it is now the |
| 718 | /// whole authorization, so a `parent` reaches their own notes and nobody |
| 719 | /// else's. |
| 720 | #[tokio::test] |
| 721 | async fn a_demotion_to_parent_strands_no_note_and_no_blob() { |
| 722 | let (app, db) = app_and_db().await; |
| 723 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 724 | let ali = login(&app, "ali").await; |
| 725 | let ali_id = me_id(&app, &ali).await; |
| 726 | |
| 727 | // A student's note with a file on it. |
| 728 | let res = send( |
| 729 | &app, |
| 730 | "POST", |
| 731 | "/notes", |
| 732 | Some(&ali), |
| 733 | Some(json!({ "title": "kept", "content": "mine" })), |
| 734 | ) |
| 735 | .await; |
| 736 | assert_eq!(res.status, StatusCode::CREATED); |
| 737 | let note_id = id_of(&res.body); |
| 738 | let up = common::upload_file( |
| 739 | &app, |
| 740 | &ali, |
| 741 | ¬e_id, |
| 742 | "plan.pdf", |
| 743 | "application/pdf", |
| 744 | b"bytes", |
| 745 | ) |
| 746 | .await; |
| 747 | assert_eq!(up.status, StatusCode::CREATED); |
| 748 | let file_id = id_of(&up.body); |
| 749 | let blob = common::blob_dir().join(&file_id); |
| 750 | assert!(blob.exists(), "the upload must have written a blob"); |
| 751 | |
| 752 | // Demote through the real route, not a seeded role. |
| 753 | let res = send( |
| 754 | &app, |
| 755 | "PATCH", |
| 756 | &format!("/users/{ali_id}/role"), |
| 757 | Some(&admin), |
| 758 | Some(json!({ "role": "parent" })), |
| 759 | ) |
| 760 | .await; |
| 761 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 762 | assert_eq!(res.body["role"], "parent"); |
| 763 | |
| 764 | // Every own-scoped read still answers the owner. |
| 765 | let res = send(&app, "GET", "/notes", Some(&ali), None).await; |
| 766 | assert_eq!(res.status, StatusCode::OK); |
| 767 | assert_eq!(common::items(&res.body).len(), 1); |
| 768 | assert_eq!( |
| 769 | send(&app, "GET", &format!("/notes/{note_id}"), Some(&ali), None) |
| 770 | .await |
| 771 | .body["title"], |
| 772 | "kept" |
| 773 | ); |
| 774 | let res = send( |
| 775 | &app, |
| 776 | "PATCH", |
| 777 | &format!("/notes/{note_id}"), |
| 778 | Some(&ali), |
| 779 | Some(json!({ "content": "still mine" })), |
| 780 | ) |
| 781 | .await; |
| 782 | assert_eq!(res.status, StatusCode::OK); |
| 783 | assert_eq!(res.body["content"], "still mine"); |
| 784 | |
| 785 | // Files too: list, download the bytes, and attach another one. |
| 786 | let res = send( |
| 787 | &app, |
| 788 | "GET", |
| 789 | &format!("/notes/{note_id}/files"), |
| 790 | Some(&ali), |
| 791 | None, |
| 792 | ) |
| 793 | .await; |
| 794 | assert_eq!(common::items(&res.body).len(), 1); |
| 795 | let (status, _, bytes) = common::send_raw( |
| 796 | &app, |
| 797 | "GET", |
| 798 | &format!("/notes/{note_id}/files/{file_id}"), |
| 799 | Some(&ali), |
| 800 | None, |
| 801 | Vec::new(), |
| 802 | ) |
| 803 | .await; |
| 804 | assert_eq!(status, StatusCode::OK); |
| 805 | assert_eq!(bytes, b"bytes"); |
| 806 | let extra = |
| 807 | common::upload_file(&app, &ali, ¬e_id, "more.pdf", "application/pdf", b"x").await; |
| 808 | assert_eq!(extra.status, StatusCode::CREATED); |
| 809 | |
| 810 | // A different parent reaches none of it — the owner check is all that |
| 811 | // stands there now, so prove every route holds. `404`, the crate's answer |
| 812 | // for someone else's row, never `403`. |
| 813 | let veli = login_as(&app, &db, "veli", "parent").await; |
| 814 | for (method, uri) in [ |
| 815 | ("GET", format!("/notes/{note_id}")), |
| 816 | ("PATCH", format!("/notes/{note_id}")), |
| 817 | ("GET", format!("/notes/{note_id}/files")), |
| 818 | ("GET", format!("/notes/{note_id}/files/{file_id}")), |
| 819 | ("DELETE", format!("/notes/{note_id}/files/{file_id}")), |
| 820 | ("DELETE", format!("/notes/{note_id}")), |
| 821 | ] { |
| 822 | let body = (method == "PATCH").then(|| json!({ "title": "stolen" })); |
| 823 | assert_eq!( |
| 824 | send(&app, method, &uri, Some(&veli), body).await.status, |
| 825 | StatusCode::NOT_FOUND, |
| 826 | "{method} {uri} must not reach another user's note" |
| 827 | ); |
| 828 | } |
| 829 | assert_eq!( |
| 830 | common::upload_file(&app, &veli, ¬e_id, "x.pdf", "application/pdf", b"x") |
| 831 | .await |
| 832 | .status, |
| 833 | StatusCode::NOT_FOUND, |
| 834 | "a stranger must not attach a file to someone else's note" |
| 835 | ); |
| 836 | assert!(common::items(&send(&app, "GET", "/notes", Some(&veli), None).await.body).is_empty()); |
| 837 | // A parent's own notes work end to end, which is what makes the demoted |
| 838 | // owner's access ownership and not leftover privilege. |
| 839 | assert_eq!( |
| 840 | send( |
| 841 | &app, |
| 842 | "POST", |
| 843 | "/notes", |
| 844 | Some(&veli), |
| 845 | Some(json!({ "title": "veli's" })) |
| 846 | ) |
| 847 | .await |
| 848 | .status, |
| 849 | StatusCode::CREATED |
| 850 | ); |
| 851 | |
| 852 | // And the demoted owner can still clear the whole thing out: one file by |
| 853 | // hand, the rest through the note's cascade — blobs included. |
| 854 | assert_eq!( |
| 855 | send( |
| 856 | &app, |
| 857 | "DELETE", |
| 858 | &format!("/notes/{note_id}/files/{file_id}"), |
| 859 | Some(&ali), |
| 860 | None |
| 861 | ) |
| 862 | .await |
| 863 | .status, |
| 864 | StatusCode::NO_CONTENT |
| 865 | ); |
| 866 | assert!(!blob.exists(), "deleting a file must unlink its blob"); |
| 867 | let extra_blob = common::blob_dir().join(id_of(&extra.body)); |
| 868 | assert_eq!( |
| 869 | send( |
| 870 | &app, |
| 871 | "DELETE", |
| 872 | &format!("/notes/{note_id}"), |
| 873 | Some(&ali), |
| 874 | None |
| 875 | ) |
| 876 | .await |
| 877 | .status, |
| 878 | StatusCode::NO_CONTENT |
| 879 | ); |
| 880 | assert!( |
| 881 | !extra_blob.exists(), |
| 882 | "the note delete must take its remaining blobs with it" |
| 883 | ); |
| 884 | assert!(common::items(&send(&app, "GET", "/notes", Some(&ali), None).await.body).is_empty()); |
| 885 | } |
| 886 | |
| 887 | #[tokio::test] |
| 888 | async fn note_content_defaults_to_empty() { |
| 889 | let app = mem_app().await; |
| 890 | let ali = login(&app, "ali").await; |
| 891 | let res = send( |
| 892 | &app, |
| 893 | "POST", |
| 894 | "/notes", |
| 895 | Some(&ali), |
| 896 | Some(json!({ "title": "solo" })), |
| 897 | ) |
| 898 | .await; |
| 899 | assert_eq!(res.status, StatusCode::CREATED); |
| 900 | assert_eq!(res.body["content"], ""); |
| 901 | } |
| 902 | |
| 903 | /// Regression: two partial PATCHes touching *different* fields must both |
| 904 | /// survive. The handler used to fill the field a request omitted from the |
| 905 | /// snapshot it had read, so the writer that landed second reverted the other |
| 906 | /// one's field — a field-scoped `SET` does not help while the value bound to |
| 907 | /// it comes from a stale read. Raced repeatedly: a single round only loses the |
| 908 | /// update on the interleaving where both handlers read before either writes. |
| 909 | #[tokio::test] |
| 910 | async fn concurrent_partial_note_patches_keep_both_fields() { |
| 911 | let app = mem_app().await; |
| 912 | let ali = login(&app, "ali").await; |
| 913 | |
| 914 | for round in 0..20 { |
| 915 | let note = create_note(&app, &ali, "old title").await; |
| 916 | let uri = format!("/notes/{note}"); |
| 917 | let title_patch = json!({ "title": "new title" }); |
| 918 | let content_patch = json!({ "content": "new body" }); |
| 919 | let (a, b) = tokio::join!( |
| 920 | send(&app, "PATCH", &uri, Some(&ali), Some(title_patch)), |
| 921 | send(&app, "PATCH", &uri, Some(&ali), Some(content_patch)), |
| 922 | ); |
| 923 | assert_eq!(a.status, StatusCode::OK, "round {round} title patch"); |
| 924 | assert_eq!(b.status, StatusCode::OK, "round {round} content patch"); |
| 925 | |
| 926 | let after = send(&app, "GET", &uri, Some(&ali), None).await.body; |
| 927 | assert_eq!(after["title"], "new title", "round {round}: title reverted"); |
| 928 | assert_eq!( |
| 929 | after["content"], "new body", |
| 930 | "round {round}: content reverted" |
| 931 | ); |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | #[tokio::test] |
| 936 | async fn note_validation_and_missing_ids() { |
| 937 | let app = mem_app().await; |
| 938 | let ali = login(&app, "ali").await; |
| 939 | |
| 940 | // Blank title on create -> 400. |
| 941 | assert_eq!( |
| 942 | send( |
| 943 | &app, |
| 944 | "POST", |
| 945 | "/notes", |
| 946 | Some(&ali), |
| 947 | Some(json!({ "title": " " })) |
| 948 | ) |
| 949 | .await |
| 950 | .status, |
| 951 | StatusCode::BAD_REQUEST |
| 952 | ); |
| 953 | |
| 954 | // Operations on a non-existent id -> 404. |
| 955 | for method in ["GET", "PATCH", "DELETE"] { |
| 956 | let body = (method == "PATCH").then(|| json!({ "title": "x" })); |
| 957 | let res = send(&app, method, "/notes/does-not-exist", Some(&ali), body).await; |
| 958 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{method}"); |
| 959 | } |
| 960 | |
| 961 | // Blank title on update -> 400. |
| 962 | let created = send( |
| 963 | &app, |
| 964 | "POST", |
| 965 | "/notes", |
| 966 | Some(&ali), |
| 967 | Some(json!({ "title": "keep" })), |
| 968 | ) |
| 969 | .await; |
| 970 | let id = id_of(&created.body); |
| 971 | assert_eq!( |
| 972 | send( |
| 973 | &app, |
| 974 | "PATCH", |
| 975 | &format!("/notes/{id}"), |
| 976 | Some(&ali), |
| 977 | Some(json!({ "title": "" })) |
| 978 | ) |
| 979 | .await |
| 980 | .status, |
| 981 | StatusCode::BAD_REQUEST |
| 982 | ); |
| 983 | } |
| 984 | |
| 985 | // --- note files ------------------------------------------------------------ |
| 986 | |
| 987 | /// Create a note as `cookie`; returns its id. |
| 988 | async fn create_note(app: &axum::Router, cookie: &str, title: &str) -> String { |
| 989 | let res = send( |
| 990 | app, |
| 991 | "POST", |
| 992 | "/notes", |
| 993 | Some(cookie), |
| 994 | Some(json!({ "title": title })), |
| 995 | ) |
| 996 | .await; |
| 997 | assert_eq!(res.status, StatusCode::CREATED, "create note {title}"); |
| 998 | id_of(&res.body) |
| 999 | } |
| 1000 | |
| 1001 | #[tokio::test] |
| 1002 | async fn note_files_upload_download_delete_roundtrip() { |
| 1003 | let app = mem_app().await; |
| 1004 | let ali = login(&app, "ali").await; |
| 1005 | let note = create_note(&app, &ali, "with file").await; |
| 1006 | |
| 1007 | let bytes = b"%PDF-1.4 fake but binary \x00\x01\x02".to_vec(); |
| 1008 | let up = common::upload_file(&app, &ali, ¬e, "plan.pdf", "application/pdf", &bytes).await; |
| 1009 | assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); |
| 1010 | assert_eq!(up.body["name"], "plan.pdf"); |
| 1011 | assert_eq!(up.body["content_type"], "application/pdf"); |
| 1012 | assert_eq!(up.body["size"], bytes.len() as i64); |
| 1013 | let file_id = id_of(&up.body); |
| 1014 | |
| 1015 | // Listed under the note (paged envelope). |
| 1016 | let list = send( |
| 1017 | &app, |
| 1018 | "GET", |
| 1019 | &format!("/notes/{note}/files"), |
| 1020 | Some(&ali), |
| 1021 | None, |
| 1022 | ) |
| 1023 | .await; |
| 1024 | assert_eq!(list.status, StatusCode::OK); |
| 1025 | assert_eq!(common::total(&list.body), 1); |
| 1026 | assert_eq!(common::items(&list.body)[0]["name"], "plan.pdf"); |
| 1027 | |
| 1028 | // Download returns the exact bytes with the declared type and filename. |
| 1029 | let (status, headers, body) = common::send_raw( |
| 1030 | &app, |
| 1031 | "GET", |
| 1032 | &format!("/notes/{note}/files/{file_id}"), |
| 1033 | Some(&ali), |
| 1034 | None, |
| 1035 | Vec::new(), |
| 1036 | ) |
| 1037 | .await; |
| 1038 | assert_eq!(status, StatusCode::OK); |
| 1039 | assert_eq!(body, bytes); |
| 1040 | assert_eq!(headers["content-type"], "application/pdf"); |
| 1041 | assert_eq!( |
| 1042 | headers["content-disposition"], |
| 1043 | "attachment; filename=\"plan.pdf\"; filename*=UTF-8''plan.pdf" |
| 1044 | ); |
| 1045 | |
| 1046 | // Delete; the file is gone from the list, download 404s, blob removed. |
| 1047 | assert_eq!( |
| 1048 | send( |
| 1049 | &app, |
| 1050 | "DELETE", |
| 1051 | &format!("/notes/{note}/files/{file_id}"), |
| 1052 | Some(&ali), |
| 1053 | None |
| 1054 | ) |
| 1055 | .await |
| 1056 | .status, |
| 1057 | StatusCode::NO_CONTENT |
| 1058 | ); |
| 1059 | let list = send( |
| 1060 | &app, |
| 1061 | "GET", |
| 1062 | &format!("/notes/{note}/files"), |
| 1063 | Some(&ali), |
| 1064 | None, |
| 1065 | ) |
| 1066 | .await; |
| 1067 | assert_eq!(common::total(&list.body), 0); |
| 1068 | assert_eq!( |
| 1069 | send( |
| 1070 | &app, |
| 1071 | "GET", |
| 1072 | &format!("/notes/{note}/files/{file_id}"), |
| 1073 | Some(&ali), |
| 1074 | None |
| 1075 | ) |
| 1076 | .await |
| 1077 | .status, |
| 1078 | StatusCode::NOT_FOUND |
| 1079 | ); |
| 1080 | assert!( |
| 1081 | !common::blob_dir().join(&file_id).exists(), |
| 1082 | "blob must be unlinked with its row" |
| 1083 | ); |
| 1084 | } |
| 1085 | |
| 1086 | #[tokio::test] |
| 1087 | async fn note_files_are_scoped_to_the_notes_owner() { |
| 1088 | let app = mem_app().await; |
| 1089 | let ali = login(&app, "ali").await; |
| 1090 | let veli = login(&app, "veli").await; |
| 1091 | let note = create_note(&app, &ali, "mine").await; |
| 1092 | let up = common::upload_file(&app, &ali, ¬e, "a.txt", "text/plain", b"hi").await; |
| 1093 | assert_eq!(up.status, StatusCode::CREATED); |
| 1094 | let file_id = id_of(&up.body); |
| 1095 | |
| 1096 | // Another user can't upload to, list, download from, or delete on the note. |
| 1097 | let foreign = common::upload_file(&app, &veli, ¬e, "b.txt", "text/plain", b"x").await; |
| 1098 | assert_eq!(foreign.status, StatusCode::NOT_FOUND); |
| 1099 | assert_eq!( |
| 1100 | send( |
| 1101 | &app, |
| 1102 | "GET", |
| 1103 | &format!("/notes/{note}/files"), |
| 1104 | Some(&veli), |
| 1105 | None |
| 1106 | ) |
| 1107 | .await |
| 1108 | .status, |
| 1109 | StatusCode::NOT_FOUND |
| 1110 | ); |
| 1111 | for method in ["GET", "DELETE"] { |
| 1112 | assert_eq!( |
| 1113 | send( |
| 1114 | &app, |
| 1115 | method, |
| 1116 | &format!("/notes/{note}/files/{file_id}"), |
| 1117 | Some(&veli), |
| 1118 | None |
| 1119 | ) |
| 1120 | .await |
| 1121 | .status, |
| 1122 | StatusCode::NOT_FOUND, |
| 1123 | "{method}" |
| 1124 | ); |
| 1125 | } |
| 1126 | |
| 1127 | // A file id under someone else's note id doesn't resolve either. |
| 1128 | let veli_note = create_note(&app, &veli, "veli's").await; |
| 1129 | assert_eq!( |
| 1130 | send( |
| 1131 | &app, |
| 1132 | "GET", |
| 1133 | &format!("/notes/{veli_note}/files/{file_id}"), |
| 1134 | Some(&veli), |
| 1135 | None |
| 1136 | ) |
| 1137 | .await |
| 1138 | .status, |
| 1139 | StatusCode::NOT_FOUND |
| 1140 | ); |
| 1141 | } |
| 1142 | |
| 1143 | #[tokio::test] |
| 1144 | async fn note_file_size_follows_the_school_limit() { |
| 1145 | let (app, db) = app_and_db().await; |
| 1146 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 1147 | let ali = login(&app, "ali").await; |
| 1148 | let note = create_note(&app, &ali, "sized").await; |
| 1149 | |
| 1150 | // Lower the school cap to 1 KiB. |
| 1151 | let res = send( |
| 1152 | &app, |
| 1153 | "PATCH", |
| 1154 | "/settings", |
| 1155 | Some(&boss), |
| 1156 | Some(json!({ "max_file_bytes": 1024 })), |
| 1157 | ) |
| 1158 | .await; |
| 1159 | assert_eq!(res.status, StatusCode::OK); |
| 1160 | assert_eq!(res.body["max_file_bytes"], 1024); |
| 1161 | |
| 1162 | // Over the cap dies with 413; at the cap passes. |
| 1163 | let big = common::upload_file(&app, &ali, ¬e, "big.bin", "", &vec![7u8; 1025]).await; |
| 1164 | assert_eq!(big.status, StatusCode::PAYLOAD_TOO_LARGE, "{}", big.body); |
| 1165 | let fits = common::upload_file(&app, &ali, ¬e, "fits.bin", "", &vec![7u8; 1024]).await; |
| 1166 | assert_eq!(fits.status, StatusCode::CREATED, "{}", fits.body); |
| 1167 | // A blank part content type falls back to octet-stream. |
| 1168 | assert_eq!(fits.body["content_type"], "application/octet-stream"); |
| 1169 | |
| 1170 | // Raising the cap unlocks bigger files at once. |
| 1171 | assert_eq!( |
| 1172 | send( |
| 1173 | &app, |
| 1174 | "PATCH", |
| 1175 | "/settings", |
| 1176 | Some(&boss), |
| 1177 | Some(json!({ "max_file_bytes": 10_000 })), |
| 1178 | ) |
| 1179 | .await |
| 1180 | .status, |
| 1181 | StatusCode::OK |
| 1182 | ); |
| 1183 | let now_fits = common::upload_file(&app, &ali, ¬e, "big.bin", "", &vec![7u8; 1025]).await; |
| 1184 | assert_eq!(now_fits.status, StatusCode::CREATED); |
| 1185 | } |
| 1186 | |
| 1187 | #[tokio::test] |
| 1188 | async fn settings_bound_the_file_limit() { |
| 1189 | let (app, db) = app_and_db().await; |
| 1190 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 1191 | |
| 1192 | // The default is visible to any authenticated user. |
| 1193 | let res = send(&app, "GET", "/settings", Some(&boss), None).await; |
| 1194 | assert_eq!(res.body["max_file_bytes"], 5 * 1024 * 1024); |
| 1195 | |
| 1196 | // Outside the hard bounds -> 400 (and the stored value is untouched). |
| 1197 | for bad in [0, 1023, 25 * 1024 * 1024 + 1] { |
| 1198 | let res = send( |
| 1199 | &app, |
| 1200 | "PATCH", |
| 1201 | "/settings", |
| 1202 | Some(&boss), |
| 1203 | Some(json!({ "max_file_bytes": bad })), |
| 1204 | ) |
| 1205 | .await; |
| 1206 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "cap {bad}"); |
| 1207 | } |
| 1208 | let res = send(&app, "GET", "/settings", Some(&boss), None).await; |
| 1209 | assert_eq!(res.body["max_file_bytes"], 5 * 1024 * 1024); |
| 1210 | |
| 1211 | // Editing another field leaves the cap alone. |
| 1212 | let res = send( |
| 1213 | &app, |
| 1214 | "PATCH", |
| 1215 | "/settings", |
| 1216 | Some(&boss), |
| 1217 | Some(json!({ "max_file_bytes": 2048 })), |
| 1218 | ) |
| 1219 | .await; |
| 1220 | assert_eq!(res.status, StatusCode::OK); |
| 1221 | let res = send( |
| 1222 | &app, |
| 1223 | "PATCH", |
| 1224 | "/settings", |
| 1225 | Some(&boss), |
| 1226 | Some(json!({ "grade_bands": [{ "min": 0, "label": "F" }] })), |
| 1227 | ) |
| 1228 | .await; |
| 1229 | assert_eq!(res.status, StatusCode::OK); |
| 1230 | assert_eq!(res.body["max_file_bytes"], 2048); |
| 1231 | } |
| 1232 | |
| 1233 | #[tokio::test] |
| 1234 | async fn note_file_count_is_capped() { |
| 1235 | let app = mem_app().await; |
| 1236 | let ali = login(&app, "ali").await; |
| 1237 | let note = create_note(&app, &ali, "full").await; |
| 1238 | |
| 1239 | for i in 0..10 { |
| 1240 | let up = common::upload_file(&app, &ali, ¬e, &format!("f{i}.txt"), "", b"x").await; |
| 1241 | assert_eq!(up.status, StatusCode::CREATED, "file {i}"); |
| 1242 | } |
| 1243 | let over = common::upload_file(&app, &ali, ¬e, "f10.txt", "", b"x").await; |
| 1244 | assert_eq!(over.status, StatusCode::CONFLICT); |
| 1245 | |
| 1246 | // Deleting one frees a slot. |
| 1247 | let list = send( |
| 1248 | &app, |
| 1249 | "GET", |
| 1250 | &format!("/notes/{note}/files"), |
| 1251 | Some(&ali), |
| 1252 | None, |
| 1253 | ) |
| 1254 | .await; |
| 1255 | let victim = id_of(&common::items(&list.body)[0]); |
| 1256 | assert_eq!( |
| 1257 | send( |
| 1258 | &app, |
| 1259 | "DELETE", |
| 1260 | &format!("/notes/{note}/files/{victim}"), |
| 1261 | Some(&ali), |
| 1262 | None |
| 1263 | ) |
| 1264 | .await |
| 1265 | .status, |
| 1266 | StatusCode::NO_CONTENT |
| 1267 | ); |
| 1268 | let retry = common::upload_file(&app, &ali, ¬e, "f10.txt", "", b"x").await; |
| 1269 | assert_eq!(retry.status, StatusCode::CREATED); |
| 1270 | } |
| 1271 | |
| 1272 | /// Regression: the 10-file cap was a bare count-then-write — concurrent |
| 1273 | /// uploads all read the same pre-count and pushed a note past the cap (the |
| 1274 | /// same write-skew as the event-capacity over-admit; the old engine's |
| 1275 | /// transactions did not conflict-check a cross-record count against an |
| 1276 | /// insert). The insert now recounts under a lock, so the outcome is |
| 1277 | /// race-order independent: exactly enough uploads win to land on the cap, |
| 1278 | /// the rest get the same 409 as a sequential over-fill. |
| 1279 | #[tokio::test] |
| 1280 | async fn concurrent_uploads_never_exceed_the_file_cap() { |
| 1281 | let app = mem_app().await; |
| 1282 | let ali = login(&app, "ali").await; |
| 1283 | let note = create_note(&app, &ali, "contested").await; |
| 1284 | |
| 1285 | for i in 0..8 { |
| 1286 | let up = common::upload_file(&app, &ali, ¬e, &format!("f{i}.txt"), "", b"x").await; |
| 1287 | assert_eq!(up.status, StatusCode::CREATED, "seed file {i}"); |
| 1288 | } |
| 1289 | |
| 1290 | // Four racers for the two remaining slots. |
| 1291 | let results = tokio::join!( |
| 1292 | common::upload_file(&app, &ali, ¬e, "r0.txt", "", b"x"), |
| 1293 | common::upload_file(&app, &ali, ¬e, "r1.txt", "", b"x"), |
| 1294 | common::upload_file(&app, &ali, ¬e, "r2.txt", "", b"x"), |
| 1295 | common::upload_file(&app, &ali, ¬e, "r3.txt", "", b"x"), |
| 1296 | ); |
| 1297 | let statuses = [ |
| 1298 | results.0.status, |
| 1299 | results.1.status, |
| 1300 | results.2.status, |
| 1301 | results.3.status, |
| 1302 | ]; |
| 1303 | for status in statuses { |
| 1304 | assert!( |
| 1305 | status == StatusCode::CREATED || status == StatusCode::CONFLICT, |
| 1306 | "a lost cap race must be a 409, got {status}" |
| 1307 | ); |
| 1308 | } |
| 1309 | |
| 1310 | let list = send( |
| 1311 | &app, |
| 1312 | "GET", |
| 1313 | &format!("/notes/{note}/files"), |
| 1314 | Some(&ali), |
| 1315 | None, |
| 1316 | ) |
| 1317 | .await; |
| 1318 | assert_eq!( |
| 1319 | common::total(&list.body), |
| 1320 | 10, |
| 1321 | "the cap must hold exactly under concurrency, statuses={statuses:?}" |
| 1322 | ); |
| 1323 | } |
| 1324 | |
| 1325 | /// The crate-wide `422` is a *behaviour*, not just 74 utoipa annotations. |
| 1326 | /// |
| 1327 | /// Every JSON-bodied operation declares `422` with no `ErrorResponse`, and the |
| 1328 | /// only thing making that true is axum's default [`JsonRejection`]: a custom |
| 1329 | /// mapping added anywhere (an `AppError` `From`, a `WithRejection` wrapper, a |
| 1330 | /// hand-rolled `Json`) would silently turn the whole surface into `400`, or into |
| 1331 | /// a `422` carrying an `ErrorResponse` the annotations say it does not, and the |
| 1332 | /// spec-drift test in `spec_bounds.rs` — which only reads the document — would |
| 1333 | /// still pass. |
| 1334 | /// |
| 1335 | /// Four extractor shapes stand in for all 74 sites, because the rejection is a |
| 1336 | /// property of the *extractor*, never of the route: |
| 1337 | /// 1. plain `Json<T>`, unauthenticated — the bare shape most sites are; |
| 1338 | /// 2. `Json<T>` behind a role gate (`RequireTeacher`), where the gate runs |
| 1339 | /// first: proves the gate passing still leaves the body rejection in |
| 1340 | /// charge (a `403`/`400` here would mean the order had changed); |
| 1341 | /// 3. `deny_unknown_fields` — the only DTO flavour that can reject a body |
| 1342 | /// that is otherwise perfectly typed; |
| 1343 | /// 4. `Multipart`, which has a different rejection entirely and must answer |
| 1344 | /// `400`, never `422` — that is why those routes declare no `422`. |
| 1345 | /// Both `422` triggers are covered (a type-mismatched field and a missing |
| 1346 | /// required one), as is the `400` line either side of them: unparseable JSON |
| 1347 | /// and a well-typed value that a domain rule refuses. |
| 1348 | #[tokio::test] |
| 1349 | async fn malformed_json_bodies_answer_422_across_every_extractor_shape() { |
| 1350 | let (app, db) = app_and_db().await; |
| 1351 | let ali = login(&app, "ali").await; |
| 1352 | let ogretmen = login_as(&app, &db, "ogretmen", "teacher").await; |
| 1353 | let json = Some("application/json"); |
| 1354 | |
| 1355 | // 422: the body reached serde and did not fit the target type. |
| 1356 | for (uri, cookie, body, shape) in [ |
| 1357 | ( |
| 1358 | "/auth/register", |
| 1359 | None, |
| 1360 | r#"{"school": "019732e3-7b00-7000-8000-00000000dead", "username": 5, "password": "secret1"}"#, |
| 1361 | "plain Json, type mismatch", |
| 1362 | ), |
| 1363 | ( |
| 1364 | "/auth/register", |
| 1365 | None, |
| 1366 | r#"{"school": "019732e3-7b00-7000-8000-00000000dead", "username": "veli"}"#, |
| 1367 | "plain Json, missing required field", |
| 1368 | ), |
| 1369 | ( |
| 1370 | "/courses", |
| 1371 | Some(ogretmen.as_str()), |
| 1372 | r#"{"title": 42}"#, |
| 1373 | "role-gated Json, type mismatch", |
| 1374 | ), |
| 1375 | ( |
| 1376 | "/boards", |
| 1377 | Some(ali.as_str()), |
| 1378 | r#"{"title": "Geometri", "participant_ids": []}"#, |
| 1379 | "deny_unknown_fields, unknown key", |
| 1380 | ), |
| 1381 | ] { |
| 1382 | let (status, headers, bytes) = |
| 1383 | common::send_raw(&app, "POST", uri, cookie, json, body.as_bytes().to_vec()).await; |
| 1384 | assert_eq!( |
| 1385 | status, |
| 1386 | StatusCode::UNPROCESSABLE_ENTITY, |
| 1387 | "{shape} ({uri}) must be 422" |
| 1388 | ); |
| 1389 | // The declared shape is "422, no `ErrorResponse`": axum answers a |
| 1390 | // plain-text explanation, *not* the `{"error": ...}` body every other |
| 1391 | // failure carries. A custom mapping that started emitting one would |
| 1392 | // make the annotations lie, so pin the negative rather than the text. |
| 1393 | assert_eq!( |
| 1394 | headers.get("content-type").and_then(|v| v.to_str().ok()), |
| 1395 | Some("text/plain; charset=utf-8"), |
| 1396 | "{shape} ({uri}) must not answer an ErrorResponse body" |
| 1397 | ); |
| 1398 | assert!( |
| 1399 | serde_json::from_slice::<serde_json::Value>(&bytes).is_err(), |
| 1400 | "{shape} ({uri}) body must not be JSON, got {}", |
| 1401 | String::from_utf8_lossy(&bytes) |
| 1402 | ); |
| 1403 | } |
| 1404 | |
| 1405 | // 400, both flavours: never a 422. Syntax that serde cannot even parse, and |
| 1406 | // a value that parsed fine but a domain rule refuses. |
| 1407 | for (body, why) in [ |
| 1408 | ("not json at all", "unparseable JSON"), |
| 1409 | ( |
| 1410 | r#"{"school": "019732e3-7b00-7000-8000-00000000dead", "username": "a", "password": "secret1"}"#, |
| 1411 | "well-typed value refused by a domain rule", |
| 1412 | ), |
| 1413 | ] { |
| 1414 | let (status, _, _) = common::send_raw( |
| 1415 | &app, |
| 1416 | "POST", |
| 1417 | "/auth/register", |
| 1418 | None, |
| 1419 | json, |
| 1420 | body.as_bytes().to_vec(), |
| 1421 | ) |
| 1422 | .await; |
| 1423 | assert_eq!(status, StatusCode::BAD_REQUEST, "{why} must be 400"); |
| 1424 | } |
| 1425 | |
| 1426 | // The multipart shape: a different rejection, and it must stay 400 — those |
| 1427 | // routes deliberately declare no 422 at all. |
| 1428 | let note = create_note(&app, &ali, "attachments").await; |
| 1429 | let (status, _, _) = common::send_raw( |
| 1430 | &app, |
| 1431 | "POST", |
| 1432 | &format!("/notes/{note}/files"), |
| 1433 | Some(&ali), |
| 1434 | Some("multipart/form-data; boundary=hezarfen-test-boundary"), |
| 1435 | b"not a multipart body".to_vec(), |
| 1436 | ) |
| 1437 | .await; |
| 1438 | assert_eq!( |
| 1439 | status, |
| 1440 | StatusCode::BAD_REQUEST, |
| 1441 | "a multipart route must answer 400, never 422" |
| 1442 | ); |
| 1443 | } |
| 1444 | |
| 1445 | #[tokio::test] |
| 1446 | async fn note_file_upload_validation() { |
| 1447 | let app = mem_app().await; |
| 1448 | let ali = login(&app, "ali").await; |
| 1449 | let note = create_note(&app, &ali, "strict").await; |
| 1450 | |
| 1451 | // Empty file, filename with a path separator, no file field at all: 400. |
| 1452 | let empty = common::upload_file(&app, &ali, ¬e, "e.txt", "", b"").await; |
| 1453 | assert_eq!(empty.status, StatusCode::BAD_REQUEST, "{}", empty.body); |
| 1454 | let traversal = common::upload_file(&app, &ali, ¬e, "../../etc/passwd", "", b"data").await; |
| 1455 | assert_eq!(traversal.status, StatusCode::BAD_REQUEST); |
| 1456 | |
| 1457 | // A body whose only part isn't named "file" has no upload in it. |
| 1458 | let stray = common::multipart_file("y.txt", "", b"data"); |
| 1459 | let stray = String::from_utf8(stray) |
| 1460 | .unwrap() |
| 1461 | .replace("name=\"file\"", "name=\"attachment\""); |
| 1462 | let (status, _, _) = common::send_raw( |
| 1463 | &app, |
| 1464 | "POST", |
| 1465 | &format!("/notes/{note}/files"), |
| 1466 | Some(&ali), |
| 1467 | Some("multipart/form-data; boundary=hezarfen-test-boundary"), |
| 1468 | stray.into_bytes(), |
| 1469 | ) |
| 1470 | .await; |
| 1471 | assert_eq!(status, StatusCode::BAD_REQUEST); |
| 1472 | |
| 1473 | // Non-ASCII filenames are fine — stored and encoded on download. |
| 1474 | let turkish = |
| 1475 | common::upload_file(&app, &ali, ¬e, "ödev 1.pdf", "application/pdf", b"pdf").await; |
| 1476 | assert_eq!(turkish.status, StatusCode::CREATED); |
| 1477 | let (status, headers, _) = common::send_raw( |
| 1478 | &app, |
| 1479 | "GET", |
| 1480 | &format!("/notes/{note}/files/{}", id_of(&turkish.body)), |
| 1481 | Some(&ali), |
| 1482 | None, |
| 1483 | Vec::new(), |
| 1484 | ) |
| 1485 | .await; |
| 1486 | assert_eq!(status, StatusCode::OK); |
| 1487 | assert_eq!( |
| 1488 | headers["content-disposition"], |
| 1489 | "attachment; filename=\"_dev 1.pdf\"; filename*=UTF-8''%C3%B6dev%201.pdf" |
| 1490 | ); |
| 1491 | } |
| 1492 | |
| 1493 | #[tokio::test] |
| 1494 | async fn deleting_a_note_removes_its_files() { |
| 1495 | let (app, db) = app_and_db().await; |
| 1496 | let ali = login(&app, "ali").await; |
| 1497 | let note = create_note(&app, &ali, "doomed").await; |
| 1498 | let up = common::upload_file(&app, &ali, ¬e, "gone.txt", "", b"bye").await; |
| 1499 | assert_eq!(up.status, StatusCode::CREATED); |
| 1500 | let file_id = id_of(&up.body); |
| 1501 | |
| 1502 | assert_eq!( |
| 1503 | send(&app, "DELETE", &format!("/notes/{note}"), Some(&ali), None) |
| 1504 | .await |
| 1505 | .status, |
| 1506 | StatusCode::NO_CONTENT |
| 1507 | ); |
| 1508 | |
| 1509 | // Row and blob are both gone. |
| 1510 | let left: i64 = sqlx::query_scalar("SELECT count(*) FROM note_file") |
| 1511 | .fetch_one(&db) |
| 1512 | .await |
| 1513 | .expect("note_file count"); |
| 1514 | assert_eq!(left, 0, "note_file rows must cascade"); |
| 1515 | assert!( |
| 1516 | !common::blob_dir().join(&file_id).exists(), |
| 1517 | "blob must be unlinked when its note dies" |
| 1518 | ); |
| 1519 | } |
| 1520 | |
| 1521 | // --- events + attendance ------------------------------------------------- |
| 1522 | |
| 1523 | #[tokio::test] |
| 1524 | async fn events_are_shared_but_creator_guarded() { |
| 1525 | let (app, db) = app_and_db().await; |
| 1526 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 1527 | let veli = login_as(&app, &db, "veli", "teacher").await; |
| 1528 | |
| 1529 | let ev = send( |
| 1530 | &app, |
| 1531 | "POST", |
| 1532 | "/events", |
| 1533 | Some(&ali), |
| 1534 | Some(json!({ "title": "standup", "description": "daily" })), |
| 1535 | ) |
| 1536 | .await; |
| 1537 | assert_eq!(ev.status, StatusCode::CREATED); |
| 1538 | let event_id = id_of(&ev.body); |
| 1539 | |
| 1540 | // Any authenticated user can read the event and its roster. |
| 1541 | assert_eq!( |
| 1542 | send( |
| 1543 | &app, |
| 1544 | "GET", |
| 1545 | &format!("/events/{event_id}"), |
| 1546 | Some(&veli), |
| 1547 | None |
| 1548 | ) |
| 1549 | .await |
| 1550 | .status, |
| 1551 | StatusCode::OK |
| 1552 | ); |
| 1553 | assert_eq!( |
| 1554 | common::items(&send(&app, "GET", "/events", Some(&veli), None).await.body).len(), |
| 1555 | 1 |
| 1556 | ); |
| 1557 | |
| 1558 | // Non-creator cannot edit or delete. |
| 1559 | assert_eq!( |
| 1560 | send( |
| 1561 | &app, |
| 1562 | "PATCH", |
| 1563 | &format!("/events/{event_id}"), |
| 1564 | Some(&veli), |
| 1565 | Some(json!({"title":"hijack"})) |
| 1566 | ) |
| 1567 | .await |
| 1568 | .status, |
| 1569 | StatusCode::FORBIDDEN |
| 1570 | ); |
| 1571 | assert_eq!( |
| 1572 | send( |
| 1573 | &app, |
| 1574 | "DELETE", |
| 1575 | &format!("/events/{event_id}"), |
| 1576 | Some(&veli), |
| 1577 | None |
| 1578 | ) |
| 1579 | .await |
| 1580 | .status, |
| 1581 | StatusCode::FORBIDDEN |
| 1582 | ); |
| 1583 | |
| 1584 | // Creator can edit (partial). |
| 1585 | let res = send( |
| 1586 | &app, |
| 1587 | "PATCH", |
| 1588 | &format!("/events/{event_id}"), |
| 1589 | Some(&ali), |
| 1590 | Some(json!({ "description": "moved" })), |
| 1591 | ) |
| 1592 | .await; |
| 1593 | assert_eq!(res.status, StatusCode::OK); |
| 1594 | assert_eq!(res.body["description"], "moved"); |
| 1595 | assert_eq!(res.body["title"], "standup"); |
| 1596 | |
| 1597 | // Blank title on update -> 400. Missing event -> 404. |
| 1598 | assert_eq!( |
| 1599 | send( |
| 1600 | &app, |
| 1601 | "PATCH", |
| 1602 | &format!("/events/{event_id}"), |
| 1603 | Some(&ali), |
| 1604 | Some(json!({"title":" "})) |
| 1605 | ) |
| 1606 | .await |
| 1607 | .status, |
| 1608 | StatusCode::BAD_REQUEST |
| 1609 | ); |
| 1610 | assert_eq!( |
| 1611 | send(&app, "GET", "/events/nope", Some(&ali), None) |
| 1612 | .await |
| 1613 | .status, |
| 1614 | StatusCode::NOT_FOUND |
| 1615 | ); |
| 1616 | } |
| 1617 | |
| 1618 | #[tokio::test] |
| 1619 | async fn attendance_marking_and_upsert() { |
| 1620 | let (app, db) = app_and_db().await; |
| 1621 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 1622 | let veli = login(&app, "veli").await; |
| 1623 | let veli_id = id_of(&send(&app, "GET", "/auth/me", Some(&veli), None).await.body); |
| 1624 | |
| 1625 | let event_id = id_of( |
| 1626 | &send( |
| 1627 | &app, |
| 1628 | "POST", |
| 1629 | "/events", |
| 1630 | Some(&ali), |
| 1631 | Some(json!({ "title": "standup" })), |
| 1632 | ) |
| 1633 | .await |
| 1634 | .body, |
| 1635 | ); |
| 1636 | |
| 1637 | // Default target is the caller. |
| 1638 | let res = send( |
| 1639 | &app, |
| 1640 | "POST", |
| 1641 | &format!("/events/{event_id}/attendance"), |
| 1642 | Some(&ali), |
| 1643 | Some(json!({ "status": "present" })), |
| 1644 | ) |
| 1645 | .await; |
| 1646 | assert_eq!(res.status, StatusCode::OK); |
| 1647 | assert_eq!(res.body["status"], "present"); |
| 1648 | |
| 1649 | // Mark veli, then re-mark: upsert keeps a single row (same id). |
| 1650 | let first = send( |
| 1651 | &app, |
| 1652 | "POST", |
| 1653 | &format!("/events/{event_id}/attendance"), |
| 1654 | Some(&ali), |
| 1655 | Some(json!({ "status": "late", "user_id": veli_id })), |
| 1656 | ) |
| 1657 | .await; |
| 1658 | let second = send( |
| 1659 | &app, |
| 1660 | "POST", |
| 1661 | &format!("/events/{event_id}/attendance"), |
| 1662 | Some(&ali), |
| 1663 | Some(json!({ "status": "absent", "user_id": veli_id })), |
| 1664 | ) |
| 1665 | .await; |
| 1666 | assert_eq!( |
| 1667 | id_of(&first.body), |
| 1668 | id_of(&second.body), |
| 1669 | "upsert same record" |
| 1670 | ); |
| 1671 | assert_eq!(second.body["status"], "absent"); |
| 1672 | |
| 1673 | // Two rows total. |
| 1674 | assert_eq!( |
| 1675 | common::items( |
| 1676 | &send( |
| 1677 | &app, |
| 1678 | "GET", |
| 1679 | &format!("/events/{event_id}/attendance"), |
| 1680 | Some(&ali), |
| 1681 | None |
| 1682 | ) |
| 1683 | .await |
| 1684 | .body |
| 1685 | ) |
| 1686 | .len(), |
| 1687 | 2 |
| 1688 | ); |
| 1689 | |
| 1690 | // Remove veli -> one row; removing again -> 404. |
| 1691 | assert_eq!( |
| 1692 | send( |
| 1693 | &app, |
| 1694 | "DELETE", |
| 1695 | &format!("/events/{event_id}/attendance/{veli_id}"), |
| 1696 | Some(&ali), |
| 1697 | None |
| 1698 | ) |
| 1699 | .await |
| 1700 | .status, |
| 1701 | StatusCode::NO_CONTENT |
| 1702 | ); |
| 1703 | assert_eq!( |
| 1704 | common::items( |
| 1705 | &send( |
| 1706 | &app, |
| 1707 | "GET", |
| 1708 | &format!("/events/{event_id}/attendance"), |
| 1709 | Some(&ali), |
| 1710 | None |
| 1711 | ) |
| 1712 | .await |
| 1713 | .body |
| 1714 | ) |
| 1715 | .len(), |
| 1716 | 1 |
| 1717 | ); |
| 1718 | assert_eq!( |
| 1719 | send( |
| 1720 | &app, |
| 1721 | "DELETE", |
| 1722 | &format!("/events/{event_id}/attendance/{veli_id}"), |
| 1723 | Some(&ali), |
| 1724 | None |
| 1725 | ) |
| 1726 | .await |
| 1727 | .status, |
| 1728 | StatusCode::NOT_FOUND |
| 1729 | ); |
| 1730 | } |
| 1731 | |
| 1732 | #[tokio::test] |
| 1733 | async fn attendance_input_validation() { |
| 1734 | let (app, db) = app_and_db().await; |
| 1735 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 1736 | let event_id = id_of( |
| 1737 | &send( |
| 1738 | &app, |
| 1739 | "POST", |
| 1740 | "/events", |
| 1741 | Some(&ali), |
| 1742 | Some(json!({ "title": "e" })), |
| 1743 | ) |
| 1744 | .await |
| 1745 | .body, |
| 1746 | ); |
| 1747 | |
| 1748 | // Invalid status -> 400. |
| 1749 | assert_eq!( |
| 1750 | send( |
| 1751 | &app, |
| 1752 | "POST", |
| 1753 | &format!("/events/{event_id}/attendance"), |
| 1754 | Some(&ali), |
| 1755 | Some(json!({"status":"maybe"})) |
| 1756 | ) |
| 1757 | .await |
| 1758 | .status, |
| 1759 | StatusCode::BAD_REQUEST |
| 1760 | ); |
| 1761 | |
| 1762 | // Unknown target user -> 400. |
| 1763 | assert_eq!( |
| 1764 | send( |
| 1765 | &app, |
| 1766 | "POST", |
| 1767 | &format!("/events/{event_id}/attendance"), |
| 1768 | Some(&ali), |
| 1769 | Some(json!({"status":"present","user_id":"ghost"})) |
| 1770 | ) |
| 1771 | .await |
| 1772 | .status, |
| 1773 | StatusCode::BAD_REQUEST |
| 1774 | ); |
| 1775 | |
| 1776 | // Attendance on a missing event -> 404. |
| 1777 | assert_eq!( |
| 1778 | send( |
| 1779 | &app, |
| 1780 | "POST", |
| 1781 | "/events/nope/attendance", |
| 1782 | Some(&ali), |
| 1783 | Some(json!({"status":"present"})) |
| 1784 | ) |
| 1785 | .await |
| 1786 | .status, |
| 1787 | StatusCode::NOT_FOUND |
| 1788 | ); |
| 1789 | } |
| 1790 | |
| 1791 | #[tokio::test] |
| 1792 | async fn deleting_event_cascades_attendance() { |
| 1793 | let (app, db) = app_and_db().await; |
| 1794 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 1795 | let event_id = id_of( |
| 1796 | &send( |
| 1797 | &app, |
| 1798 | "POST", |
| 1799 | "/events", |
| 1800 | Some(&ali), |
| 1801 | Some(json!({ "title": "e" })), |
| 1802 | ) |
| 1803 | .await |
| 1804 | .body, |
| 1805 | ); |
| 1806 | send( |
| 1807 | &app, |
| 1808 | "POST", |
| 1809 | &format!("/events/{event_id}/attendance"), |
| 1810 | Some(&ali), |
| 1811 | Some(json!({"status":"present"})), |
| 1812 | ) |
| 1813 | .await; |
| 1814 | |
| 1815 | assert_eq!( |
| 1816 | send( |
| 1817 | &app, |
| 1818 | "DELETE", |
| 1819 | &format!("/events/{event_id}"), |
| 1820 | Some(&ali), |
| 1821 | None |
| 1822 | ) |
| 1823 | .await |
| 1824 | .status, |
| 1825 | StatusCode::NO_CONTENT |
| 1826 | ); |
| 1827 | // Event gone — and its roster endpoint with it (404, not an empty list). |
| 1828 | assert_eq!( |
| 1829 | send( |
| 1830 | &app, |
| 1831 | "GET", |
| 1832 | &format!("/events/{event_id}"), |
| 1833 | Some(&ali), |
| 1834 | None |
| 1835 | ) |
| 1836 | .await |
| 1837 | .status, |
| 1838 | StatusCode::NOT_FOUND |
| 1839 | ); |
| 1840 | assert_eq!( |
| 1841 | send( |
| 1842 | &app, |
| 1843 | "GET", |
| 1844 | &format!("/events/{event_id}/attendance"), |
| 1845 | Some(&ali), |
| 1846 | None |
| 1847 | ) |
| 1848 | .await |
| 1849 | .status, |
| 1850 | StatusCode::NOT_FOUND |
| 1851 | ); |
| 1852 | } |
| 1853 | |
| 1854 | #[tokio::test] |
| 1855 | async fn event_timestamps_echo_and_validate() { |
| 1856 | let (app, db) = app_and_db().await; |
| 1857 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 1858 | let now = Timestamp::now().as_millis(); |
| 1859 | let starts = now + 3_600_000; |
| 1860 | let ends = now + 7_200_000; |
| 1861 | |
| 1862 | // Create with unix-millis times. |
| 1863 | let res = send( |
| 1864 | &app, |
| 1865 | "POST", |
| 1866 | "/events", |
| 1867 | Some(&ali), |
| 1868 | Some(json!({ "title": "mtg", "starts_at": starts, "ends_at": ends })), |
| 1869 | ) |
| 1870 | .await; |
| 1871 | assert_eq!(res.status, StatusCode::CREATED); |
| 1872 | assert_eq!(res.body["starts_at"], starts); |
| 1873 | assert_eq!(res.body["ends_at"], ends); |
| 1874 | let event_id = id_of(&res.body); |
| 1875 | |
| 1876 | // Omitted times serialize as null. |
| 1877 | let untimed = send( |
| 1878 | &app, |
| 1879 | "POST", |
| 1880 | "/events", |
| 1881 | Some(&ali), |
| 1882 | Some(json!({ "title": "notime" })), |
| 1883 | ) |
| 1884 | .await; |
| 1885 | assert!(untimed.body["starts_at"].is_null()); |
| 1886 | assert!(untimed.body["ends_at"].is_null()); |
| 1887 | |
| 1888 | // ends_at before starts_at -> 400. |
| 1889 | let bad = send( |
| 1890 | &app, |
| 1891 | "POST", |
| 1892 | "/events", |
| 1893 | Some(&ali), |
| 1894 | Some(json!({ "title": "bad", "starts_at": now + 5_000_000, "ends_at": now + 1_000_000 })), |
| 1895 | ) |
| 1896 | .await; |
| 1897 | assert_eq!(bad.status, StatusCode::BAD_REQUEST); |
| 1898 | |
| 1899 | // Past times -> 400, whichever end carries them. |
| 1900 | for body in [ |
| 1901 | json!({ "title": "old", "starts_at": now - 3_600_000 }), |
| 1902 | json!({ "title": "old", "ends_at": now - 3_600_000 }), |
| 1903 | ] { |
| 1904 | let res = send(&app, "POST", "/events", Some(&ali), Some(body)).await; |
| 1905 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 1906 | } |
| 1907 | |
| 1908 | // Updating only ends_at keeps starts_at. |
| 1909 | let updated = send( |
| 1910 | &app, |
| 1911 | "PATCH", |
| 1912 | &format!("/events/{event_id}"), |
| 1913 | Some(&ali), |
| 1914 | Some(json!({ "ends_at": now + 10_800_000 })), |
| 1915 | ) |
| 1916 | .await; |
| 1917 | assert_eq!(updated.status, StatusCode::OK); |
| 1918 | assert_eq!(updated.body["starts_at"], starts); |
| 1919 | assert_eq!(updated.body["ends_at"], now + 10_800_000); |
| 1920 | |
| 1921 | // A PATCH may not move a time into the past either — whichever end. |
| 1922 | for body in [ |
| 1923 | json!({ "starts_at": now - 3_600_000 }), |
| 1924 | json!({ "ends_at": now - 3_600_000 }), |
| 1925 | ] { |
| 1926 | let res = send( |
| 1927 | &app, |
| 1928 | "PATCH", |
| 1929 | &format!("/events/{event_id}"), |
| 1930 | Some(&ali), |
| 1931 | Some(body), |
| 1932 | ) |
| 1933 | .await; |
| 1934 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 1935 | } |
| 1936 | } |
| 1937 | |
| 1938 | #[tokio::test] |
| 1939 | async fn event_audience_defaults_validates_and_echoes() { |
| 1940 | let (app, db) = app_and_db().await; |
| 1941 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 1942 | |
| 1943 | // Omitted audience = school-wide, and it echoes on every read. |
| 1944 | let ev = send( |
| 1945 | &app, |
| 1946 | "POST", |
| 1947 | "/events", |
| 1948 | Some(&ali), |
| 1949 | Some(json!({ "title": "assembly" })), |
| 1950 | ) |
| 1951 | .await; |
| 1952 | assert_eq!(ev.status, StatusCode::CREATED); |
| 1953 | assert_eq!(ev.body["audience"]["kind"], "school"); |
| 1954 | |
| 1955 | // A role audience round-trips… |
| 1956 | let ev = send( |
| 1957 | &app, |
| 1958 | "POST", |
| 1959 | "/events", |
| 1960 | Some(&ali), |
| 1961 | Some(json!({ "title": "orientation", "audience": { "kind": "role", "role": "student" } })), |
| 1962 | ) |
| 1963 | .await; |
| 1964 | assert_eq!(ev.status, StatusCode::CREATED); |
| 1965 | assert_eq!(ev.body["audience"]["role"], "student"); |
| 1966 | let event_id = id_of(&ev.body); |
| 1967 | |
| 1968 | // …a PATCH without `audience` keeps it, and a sent one replaces it. |
| 1969 | let res = send( |
| 1970 | &app, |
| 1971 | "PATCH", |
| 1972 | &format!("/events/{event_id}"), |
| 1973 | Some(&ali), |
| 1974 | Some(json!({ "title": "orientation day" })), |
| 1975 | ) |
| 1976 | .await; |
| 1977 | assert_eq!(res.body["audience"]["role"], "student"); |
| 1978 | let res = send( |
| 1979 | &app, |
| 1980 | "PATCH", |
| 1981 | &format!("/events/{event_id}"), |
| 1982 | Some(&ali), |
| 1983 | Some(json!({ "audience": { "kind": "registration", "capacity": 5 } })), |
| 1984 | ) |
| 1985 | .await; |
| 1986 | assert_eq!(res.status, StatusCode::OK); |
| 1987 | assert_eq!(res.body["audience"]["capacity"], 5); |
| 1988 | |
| 1989 | // An omitted capacity echoes as null: an uncapped signup list. |
| 1990 | let res = send( |
| 1991 | &app, |
| 1992 | "POST", |
| 1993 | "/events", |
| 1994 | Some(&ali), |
| 1995 | Some(json!({ "title": "trip", "audience": { "kind": "registration" } })), |
| 1996 | ) |
| 1997 | .await; |
| 1998 | assert_eq!(res.status, StatusCode::CREATED); |
| 1999 | assert_eq!(res.body["audience"]["kind"], "registration"); |
| 2000 | assert!(res.body["audience"]["capacity"].is_null()); |
| 2001 | |
| 2002 | // Invalid audiences are rejected: unknown role, ghost course, and |
| 2003 | // non-positive capacities. |
| 2004 | for audience in [ |
| 2005 | json!({ "kind": "role", "role": "wizard" }), |
| 2006 | json!({ "kind": "course", "course": "nope" }), |
| 2007 | json!({ "kind": "registration", "capacity": 0 }), |
| 2008 | json!({ "kind": "registration", "capacity": -3 }), |
| 2009 | ] { |
| 2010 | let res = send( |
| 2011 | &app, |
| 2012 | "POST", |
| 2013 | "/events", |
| 2014 | Some(&ali), |
| 2015 | Some(json!({ "title": "bad", "audience": audience })), |
| 2016 | ) |
| 2017 | .await; |
| 2018 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{audience}"); |
| 2019 | } |
| 2020 | // An unknown kind never deserializes — including the retired hand-picked |
| 2021 | // `users` kind, gone in the registration clean break. |
| 2022 | for audience in [ |
| 2023 | json!({ "kind": "galaxy" }), |
| 2024 | json!({ "kind": "users", "users": ["ghost"] }), |
| 2025 | ] { |
| 2026 | let res = send( |
| 2027 | &app, |
| 2028 | "POST", |
| 2029 | "/events", |
| 2030 | Some(&ali), |
| 2031 | Some(json!({ "title": "bad", "audience": audience })), |
| 2032 | ) |
| 2033 | .await; |
| 2034 | assert!(res.status.is_client_error(), "{audience}: {}", res.status); |
| 2035 | } |
| 2036 | } |
| 2037 | |
| 2038 | #[tokio::test] |
| 2039 | async fn event_audience_gates_marking() { |
| 2040 | let (app, db) = app_and_db().await; |
| 2041 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 2042 | let veli = login(&app, "veli").await; // student |
| 2043 | let mina = login(&app, "mina").await; // student |
| 2044 | let veli_id = me_id(&app, &veli).await; |
| 2045 | let mina_id = me_id(&app, &mina).await; |
| 2046 | let ali_id = me_id(&app, &ali).await; |
| 2047 | |
| 2048 | let create = |audience: serde_json::Value| { |
| 2049 | let app = &app; |
| 2050 | let ali = &ali; |
| 2051 | async move { |
| 2052 | let res = send( |
| 2053 | app, |
| 2054 | "POST", |
| 2055 | "/events", |
| 2056 | Some(ali), |
| 2057 | Some(json!({ "title": "ev", "audience": audience })), |
| 2058 | ) |
| 2059 | .await; |
| 2060 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 2061 | id_of(&res.body) |
| 2062 | } |
| 2063 | }; |
| 2064 | let mark = |event: String, user: String| { |
| 2065 | let app = &app; |
| 2066 | let ali = &ali; |
| 2067 | async move { |
| 2068 | send( |
| 2069 | app, |
| 2070 | "POST", |
| 2071 | &format!("/events/{event}/attendance"), |
| 2072 | Some(ali), |
| 2073 | Some(json!({ "status": "present", "user_id": user })), |
| 2074 | ) |
| 2075 | .await |
| 2076 | .status |
| 2077 | } |
| 2078 | }; |
| 2079 | |
| 2080 | // Role audience: students are markable, the (teacher) marker is not — |
| 2081 | // including implicitly, via the marker-defaults-to-caller path. |
| 2082 | let ev = create(json!({ "kind": "role", "role": "student" })).await; |
| 2083 | assert_eq!(mark(ev.clone(), veli_id.clone()).await, StatusCode::OK); |
| 2084 | assert_eq!( |
| 2085 | mark(ev.clone(), ali_id.clone()).await, |
| 2086 | StatusCode::BAD_REQUEST |
| 2087 | ); |
| 2088 | assert_eq!( |
| 2089 | send( |
| 2090 | &app, |
| 2091 | "POST", |
| 2092 | &format!("/events/{ev}/attendance"), |
| 2093 | Some(&ali), |
| 2094 | Some(json!({ "status": "present" })), |
| 2095 | ) |
| 2096 | .await |
| 2097 | .status, |
| 2098 | StatusCode::BAD_REQUEST, |
| 2099 | "caller-defaulted target must still clear the audience gate" |
| 2100 | ); |
| 2101 | |
| 2102 | // Course audience: enrollment decides, live. The enrollment that decides is |
| 2103 | // the one on a şube's instance — a catalog row teaches nobody by itself. |
| 2104 | let mudur = login_as(&app, &db, "ev_mgr", "manager").await; |
| 2105 | let t = taught_under(&app, &mudur, &ali, "algebra").await; |
| 2106 | enroll(&app, &ali, &t.instance, &veli_id).await; |
| 2107 | let ev = create(json!({ "kind": "course", "course": t.course })).await; |
| 2108 | assert_eq!(mark(ev.clone(), veli_id.clone()).await, StatusCode::OK); |
| 2109 | assert_eq!( |
| 2110 | mark(ev.clone(), mina_id.clone()).await, |
| 2111 | StatusCode::BAD_REQUEST |
| 2112 | ); |
| 2113 | |
| 2114 | // Registration audience: the signup list is the roster. |
| 2115 | let ev = create(json!({ "kind": "registration" })).await; |
| 2116 | let res = send( |
| 2117 | &app, |
| 2118 | "POST", |
| 2119 | &format!("/events/{ev}/register"), |
| 2120 | Some(&ali), |
| 2121 | Some(json!({ "user_id": mina_id })), |
| 2122 | ) |
| 2123 | .await; |
| 2124 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 2125 | assert_eq!(mark(ev.clone(), mina_id.clone()).await, StatusCode::OK); |
| 2126 | assert_eq!( |
| 2127 | mark(ev.clone(), veli_id.clone()).await, |
| 2128 | StatusCode::BAD_REQUEST |
| 2129 | ); |
| 2130 | |
| 2131 | // School audience: everyone is expected — the teacher may mark themselves. |
| 2132 | let ev = create(json!({ "kind": "school" })).await; |
| 2133 | assert_eq!(mark(ev.clone(), ali_id.clone()).await, StatusCode::OK); |
| 2134 | assert_eq!(mark(ev, veli_id.clone()).await, StatusCode::OK); |
| 2135 | } |
| 2136 | |
| 2137 | #[tokio::test] |
| 2138 | async fn event_roster_joins_expected_with_marks() { |
| 2139 | let (app, db) = app_and_db().await; |
| 2140 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 2141 | let s1 = login(&app, "selin").await; |
| 2142 | let s2 = login(&app, "zeynep").await; |
| 2143 | let s1_id = me_id(&app, &s1).await; |
| 2144 | // The audience names the catalog course; the roster it resolves is the |
| 2145 | // instance's, so the şube the teacher runs is what seats them. |
| 2146 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 2147 | let t = taught_under(&app, &mudur, &ali, "algebra").await; |
| 2148 | let course = t.course.clone(); |
| 2149 | enroll(&app, &ali, &t.instance, &s1_id).await; |
| 2150 | enroll(&app, &ali, &t.instance, &me_id(&app, &s2).await).await; |
| 2151 | |
| 2152 | let ev = send( |
| 2153 | &app, |
| 2154 | "POST", |
| 2155 | "/events", |
| 2156 | Some(&ali), |
| 2157 | Some(json!({ "title": "field trip", |
| 2158 | "audience": { "kind": "course", "course": course } })), |
| 2159 | ) |
| 2160 | .await; |
| 2161 | let event_id = id_of(&ev.body); |
| 2162 | let roster_uri = format!("/events/{event_id}/roster"); |
| 2163 | |
| 2164 | // Before any marks: every expected attendee, all unmarked. |
| 2165 | let res = send(&app, "GET", &roster_uri, Some(&ali), None).await; |
| 2166 | assert_eq!(res.status, StatusCode::OK); |
| 2167 | assert_eq!(common::total(&res.body), 2); |
| 2168 | assert!( |
| 2169 | common::items(&res.body) |
| 2170 | .iter() |
| 2171 | .all(|entry| entry["status"].is_null() && entry["marked_by"].is_null()) |
| 2172 | ); |
| 2173 | |
| 2174 | // Mark one: the roster shows who came and who's still missing. |
| 2175 | send( |
| 2176 | &app, |
| 2177 | "POST", |
| 2178 | &format!("/events/{event_id}/attendance"), |
| 2179 | Some(&ali), |
| 2180 | Some(json!({ "status": "present", "user_id": s1_id })), |
| 2181 | ) |
| 2182 | .await; |
| 2183 | let res = send(&app, "GET", &roster_uri, Some(&ali), None).await; |
| 2184 | let items = common::items(&res.body); |
| 2185 | assert_eq!(items.len(), 2); |
| 2186 | let marked: Vec<_> = items |
| 2187 | .iter() |
| 2188 | .filter(|entry| entry["status"] == "present") |
| 2189 | .collect(); |
| 2190 | assert_eq!(marked.len(), 1); |
| 2191 | assert_eq!(marked[0]["user"]["id"], s1_id); |
| 2192 | assert_eq!(marked[0]["marked_by"]["username"], "ali"); |
| 2193 | assert_eq!( |
| 2194 | items |
| 2195 | .iter() |
| 2196 | .filter(|entry| entry["status"].is_null()) |
| 2197 | .count(), |
| 2198 | 1 |
| 2199 | ); |
| 2200 | |
| 2201 | // The roster pages like any list. |
| 2202 | let res = send( |
| 2203 | &app, |
| 2204 | "GET", |
| 2205 | &format!("{roster_uri}?limit=1&offset=1"), |
| 2206 | Some(&ali), |
| 2207 | None, |
| 2208 | ) |
| 2209 | .await; |
| 2210 | assert_eq!(common::items(&res.body).len(), 1); |
| 2211 | assert_eq!(common::total(&res.body), 2); |
| 2212 | |
| 2213 | // Dropping someone from the audience (unenroll) drops them from the |
| 2214 | // roster report — their recorded mark stays in the attendance listing. |
| 2215 | let res = send( |
| 2216 | &app, |
| 2217 | "DELETE", |
| 2218 | &format!("/instances/{}/enrollments/{s1_id}", t.instance), |
| 2219 | Some(&ali), |
| 2220 | None, |
| 2221 | ) |
| 2222 | .await; |
| 2223 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 2224 | let res = send(&app, "GET", &roster_uri, Some(&ali), None).await; |
| 2225 | assert_eq!(common::total(&res.body), 1); |
| 2226 | assert!(common::items(&res.body)[0]["status"].is_null()); |
| 2227 | let res = send( |
| 2228 | &app, |
| 2229 | "GET", |
| 2230 | &format!("/events/{event_id}/attendance"), |
| 2231 | Some(&ali), |
| 2232 | None, |
| 2233 | ) |
| 2234 | .await; |
| 2235 | assert_eq!(common::total(&res.body), 1, "stale mark stays recorded"); |
| 2236 | |
| 2237 | // A missing event has no roster — 404, not an empty page. |
| 2238 | assert_eq!( |
| 2239 | send(&app, "GET", "/events/nope/roster", Some(&ali), None) |
| 2240 | .await |
| 2241 | .status, |
| 2242 | StatusCode::NOT_FOUND |
| 2243 | ); |
| 2244 | } |
| 2245 | |
| 2246 | // --- exams + results ----------------------------------------------------- |
| 2247 | |
| 2248 | #[tokio::test] |
| 2249 | async fn exams_are_instance_scoped_and_instance_guarded() { |
| 2250 | let (app, db) = app_and_db().await; |
| 2251 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 2252 | let veli = login_as(&app, &db, "veli", "teacher").await; |
| 2253 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 2254 | |
| 2255 | // The exam keys on the instance — one şube teaching the catalog course — |
| 2256 | // and ali is that şube's homeroom teacher, which is what carries the right. |
| 2257 | let t = taught_under(&app, &mudur, &ali, "algebra").await; |
| 2258 | let ex = send( |
| 2259 | &app, |
| 2260 | "POST", |
| 2261 | &format!("/instances/{}/exams", t.instance), |
| 2262 | Some(&ali), |
| 2263 | Some(json!({ |
| 2264 | "title": "ch3", |
| 2265 | "description": "algebra", |
| 2266 | "kind": "yazili", |
| 2267 | "term": &t.term, |
| 2268 | })), |
| 2269 | ) |
| 2270 | .await; |
| 2271 | assert_eq!(ex.status, StatusCode::CREATED); |
| 2272 | assert_eq!(ex.body["kind"], "yazili"); |
| 2273 | assert_eq!(ex.body["class_course"], t.instance); |
| 2274 | // Weight lives on the kind (settings), not the exam. |
| 2275 | assert_eq!(ex.body.get("weight"), None); |
| 2276 | let exam_id = id_of(&ex.body); |
| 2277 | |
| 2278 | // A teacher outside the instance sees none of it: not the exam, not the |
| 2279 | // instance's exam list, and an empty catalog. |
| 2280 | assert_eq!( |
| 2281 | send(&app, "GET", &format!("/exams/{exam_id}"), Some(&veli), None) |
| 2282 | .await |
| 2283 | .status, |
| 2284 | StatusCode::FORBIDDEN |
| 2285 | ); |
| 2286 | assert_eq!( |
| 2287 | common::items(&send(&app, "GET", "/exams", Some(&veli), None).await.body).len(), |
| 2288 | 0 |
| 2289 | ); |
| 2290 | assert_eq!( |
| 2291 | send( |
| 2292 | &app, |
| 2293 | "GET", |
| 2294 | &format!("/instances/{}/exams", t.instance), |
| 2295 | Some(&veli), |
| 2296 | None |
| 2297 | ) |
| 2298 | .await |
| 2299 | .status, |
| 2300 | StatusCode::FORBIDDEN |
| 2301 | ); |
| 2302 | |
| 2303 | // Assign ali to the instance itself: the flat exam catalog lists the |
| 2304 | // instances a teacher is *assigned* to (the şube's homeroom teacher reads |
| 2305 | // it through the instance routes, not through this catalog). |
| 2306 | let ali_id = me_id(&app, &ali).await; |
| 2307 | assert_eq!( |
| 2308 | send( |
| 2309 | &app, |
| 2310 | "POST", |
| 2311 | &format!("/instances/{}/teachers", t.instance), |
| 2312 | Some(&mudur), |
| 2313 | Some(json!({ "user_id": ali_id })) |
| 2314 | ) |
| 2315 | .await |
| 2316 | .status, |
| 2317 | StatusCode::OK |
| 2318 | ); |
| 2319 | |
| 2320 | // The instance's own teacher reads all three views. |
| 2321 | assert_eq!( |
| 2322 | send(&app, "GET", &format!("/exams/{exam_id}"), Some(&ali), None) |
| 2323 | .await |
| 2324 | .status, |
| 2325 | StatusCode::OK |
| 2326 | ); |
| 2327 | assert_eq!( |
| 2328 | common::items(&send(&app, "GET", "/exams", Some(&ali), None).await.body).len(), |
| 2329 | 1 |
| 2330 | ); |
| 2331 | assert_eq!( |
| 2332 | common::items( |
| 2333 | &send( |
| 2334 | &app, |
| 2335 | "GET", |
| 2336 | &format!("/instances/{}/exams", t.instance), |
| 2337 | Some(&ali), |
| 2338 | None |
| 2339 | ) |
| 2340 | .await |
| 2341 | .body |
| 2342 | ) |
| 2343 | .len(), |
| 2344 | 1 |
| 2345 | ); |
| 2346 | |
| 2347 | // A teacher who doesn't teach the instance cannot edit or delete its exams. |
| 2348 | assert_eq!( |
| 2349 | send( |
| 2350 | &app, |
| 2351 | "PATCH", |
| 2352 | &format!("/exams/{exam_id}"), |
| 2353 | Some(&veli), |
| 2354 | Some(json!({"title":"hijack"})) |
| 2355 | ) |
| 2356 | .await |
| 2357 | .status, |
| 2358 | StatusCode::FORBIDDEN |
| 2359 | ); |
| 2360 | assert_eq!( |
| 2361 | send( |
| 2362 | &app, |
| 2363 | "DELETE", |
| 2364 | &format!("/exams/{exam_id}"), |
| 2365 | Some(&veli), |
| 2366 | None |
| 2367 | ) |
| 2368 | .await |
| 2369 | .status, |
| 2370 | StatusCode::FORBIDDEN |
| 2371 | ); |
| 2372 | |
| 2373 | // The instance's teacher edits (partial) — kind flips sozlu, title kept. |
| 2374 | let res = send( |
| 2375 | &app, |
| 2376 | "PATCH", |
| 2377 | &format!("/exams/{exam_id}"), |
| 2378 | Some(&ali), |
| 2379 | Some(json!({ "kind": "sozlu" })), |
| 2380 | ) |
| 2381 | .await; |
| 2382 | assert_eq!(res.status, StatusCode::OK); |
| 2383 | assert_eq!(res.body["kind"], "sozlu"); |
| 2384 | assert_eq!(res.body["title"], "ch3"); |
| 2385 | } |
| 2386 | |
| 2387 | #[tokio::test] |
| 2388 | async fn exam_input_validation() { |
| 2389 | let (app, db) = app_and_db().await; |
| 2390 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 2391 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 2392 | let t = taught_under(&app, &mudur, &ali, "algebra").await; |
| 2393 | let exams_uri = format!("/instances/{}/exams", t.instance); |
| 2394 | |
| 2395 | // Missing/blank title -> 400. |
| 2396 | assert_eq!( |
| 2397 | send( |
| 2398 | &app, |
| 2399 | "POST", |
| 2400 | &exams_uri, |
| 2401 | Some(&ali), |
| 2402 | Some(json!({"title":" ","kind":"yazili","term": &t.term})) |
| 2403 | ) |
| 2404 | .await |
| 2405 | .status, |
| 2406 | StatusCode::BAD_REQUEST |
| 2407 | ); |
| 2408 | // Unknown kind -> 400 ("yazili" is a default kind; "essay" is not). |
| 2409 | assert_eq!( |
| 2410 | send( |
| 2411 | &app, |
| 2412 | "POST", |
| 2413 | &exams_uri, |
| 2414 | Some(&ali), |
| 2415 | Some(json!({"title":"t","kind":"essay","term": &t.term})) |
| 2416 | ) |
| 2417 | .await |
| 2418 | .status, |
| 2419 | StatusCode::BAD_REQUEST |
| 2420 | ); |
| 2421 | assert_eq!( |
| 2422 | send( |
| 2423 | &app, |
| 2424 | "POST", |
| 2425 | &exams_uri, |
| 2426 | Some(&ali), |
| 2427 | Some(json!({"title":"t","kind":"yazili","term": &t.term})) |
| 2428 | ) |
| 2429 | .await |
| 2430 | .status, |
| 2431 | StatusCode::CREATED |
| 2432 | ); |
| 2433 | // Missing exam -> 404. |
| 2434 | assert_eq!( |
| 2435 | send(&app, "GET", "/exams/nope", Some(&ali), None) |
| 2436 | .await |
| 2437 | .status, |
| 2438 | StatusCode::NOT_FOUND |
| 2439 | ); |
| 2440 | } |
| 2441 | |
| 2442 | #[tokio::test] |
| 2443 | async fn grading_upsert_and_own_result() { |
| 2444 | let (app, db) = app_and_db().await; |
| 2445 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 2446 | let alice = login(&app, "alice").await; // student |
| 2447 | let bob = login(&app, "bob").await; // student |
| 2448 | let alice_id = me_id(&app, &alice).await; |
| 2449 | |
| 2450 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 2451 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 2452 | enroll(&app, &teacher, &t.instance, &alice_id).await; |
| 2453 | let exam_id = create_exam(&app, &teacher, &t.instance, &t.term, "mt", "yazili").await; |
| 2454 | |
| 2455 | // Before grading, the student's own result is 404. |
| 2456 | assert_eq!( |
| 2457 | send( |
| 2458 | &app, |
| 2459 | "GET", |
| 2460 | &format!("/exams/{exam_id}/result"), |
| 2461 | Some(&alice), |
| 2462 | None |
| 2463 | ) |
| 2464 | .await |
| 2465 | .status, |
| 2466 | StatusCode::NOT_FOUND |
| 2467 | ); |
| 2468 | |
| 2469 | // Teacher grades alice, then re-grades: upsert keeps one row (same id). |
| 2470 | let first = send( |
| 2471 | &app, |
| 2472 | "POST", |
| 2473 | &format!("/exams/{exam_id}/results"), |
| 2474 | Some(&teacher), |
| 2475 | Some(json!({ "mark": 70, "user_id": alice_id })), |
| 2476 | ) |
| 2477 | .await; |
| 2478 | assert_eq!(first.status, StatusCode::OK); |
| 2479 | let second = send( |
| 2480 | &app, |
| 2481 | "POST", |
| 2482 | &format!("/exams/{exam_id}/results"), |
| 2483 | Some(&teacher), |
| 2484 | Some(json!({ "mark": 88, "user_id": alice_id })), |
| 2485 | ) |
| 2486 | .await; |
| 2487 | assert_eq!( |
| 2488 | id_of(&first.body), |
| 2489 | id_of(&second.body), |
| 2490 | "upsert same record" |
| 2491 | ); |
| 2492 | assert_eq!(second.body["mark"], 88); |
| 2493 | |
| 2494 | // Alice reads her own result; bob (ungraded) still 404s and can't see alice's. |
| 2495 | let mine = send( |
| 2496 | &app, |
| 2497 | "GET", |
| 2498 | &format!("/exams/{exam_id}/result"), |
| 2499 | Some(&alice), |
| 2500 | None, |
| 2501 | ) |
| 2502 | .await; |
| 2503 | assert_eq!(mine.status, StatusCode::OK); |
| 2504 | assert_eq!(mine.body["mark"], 88); |
| 2505 | assert_eq!( |
| 2506 | send( |
| 2507 | &app, |
| 2508 | "GET", |
| 2509 | &format!("/exams/{exam_id}/result"), |
| 2510 | Some(&bob), |
| 2511 | None |
| 2512 | ) |
| 2513 | .await |
| 2514 | .status, |
| 2515 | StatusCode::NOT_FOUND |
| 2516 | ); |
| 2517 | |
| 2518 | // Teacher sees the full list (one row). |
| 2519 | assert_eq!( |
| 2520 | common::items( |
| 2521 | &send( |
| 2522 | &app, |
| 2523 | "GET", |
| 2524 | &format!("/exams/{exam_id}/results"), |
| 2525 | Some(&teacher), |
| 2526 | None |
| 2527 | ) |
| 2528 | .await |
| 2529 | .body |
| 2530 | ) |
| 2531 | .len(), |
| 2532 | 1 |
| 2533 | ); |
| 2534 | |
| 2535 | // Remove alice's result -> her own read 404s again; removing again -> 404. |
| 2536 | assert_eq!( |
| 2537 | send( |
| 2538 | &app, |
| 2539 | "DELETE", |
| 2540 | &format!("/exams/{exam_id}/results/{alice_id}"), |
| 2541 | Some(&teacher), |
| 2542 | None |
| 2543 | ) |
| 2544 | .await |
| 2545 | .status, |
| 2546 | StatusCode::NO_CONTENT |
| 2547 | ); |
| 2548 | assert_eq!( |
| 2549 | send( |
| 2550 | &app, |
| 2551 | "GET", |
| 2552 | &format!("/exams/{exam_id}/result"), |
| 2553 | Some(&alice), |
| 2554 | None |
| 2555 | ) |
| 2556 | .await |
| 2557 | .status, |
| 2558 | StatusCode::NOT_FOUND |
| 2559 | ); |
| 2560 | assert_eq!( |
| 2561 | send( |
| 2562 | &app, |
| 2563 | "DELETE", |
| 2564 | &format!("/exams/{exam_id}/results/{alice_id}"), |
| 2565 | Some(&teacher), |
| 2566 | None |
| 2567 | ) |
| 2568 | .await |
| 2569 | .status, |
| 2570 | StatusCode::NOT_FOUND |
| 2571 | ); |
| 2572 | } |
| 2573 | |
| 2574 | #[tokio::test] |
| 2575 | async fn grading_rbac_and_validation() { |
| 2576 | let (app, db) = app_and_db().await; |
| 2577 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 2578 | let alice = login(&app, "alice").await; // student |
| 2579 | let bob = login(&app, "bob").await; // student |
| 2580 | let alice_id = me_id(&app, &alice).await; |
| 2581 | let bob_id = me_id(&app, &bob).await; |
| 2582 | |
| 2583 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 2584 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 2585 | enroll(&app, &teacher, &t.instance, &alice_id).await; |
| 2586 | let exam_id = create_exam(&app, &teacher, &t.instance, &t.term, "e", "yazili").await; |
| 2587 | |
| 2588 | // Students cannot create exams, grade anyone, list all results, or delete a result. |
| 2589 | assert_eq!( |
| 2590 | send( |
| 2591 | &app, |
| 2592 | "POST", |
| 2593 | &format!("/instances/{}/exams", t.instance), |
| 2594 | Some(&alice), |
| 2595 | Some(json!({"title":"x","kind":"yazili","term": &t.term})) |
| 2596 | ) |
| 2597 | .await |
| 2598 | .status, |
| 2599 | StatusCode::FORBIDDEN |
| 2600 | ); |
| 2601 | assert_eq!( |
| 2602 | send( |
| 2603 | &app, |
| 2604 | "POST", |
| 2605 | &format!("/exams/{exam_id}/results"), |
| 2606 | Some(&alice), |
| 2607 | Some(json!({"mark":100,"user_id":alice_id})) |
| 2608 | ) |
| 2609 | .await |
| 2610 | .status, |
| 2611 | StatusCode::FORBIDDEN |
| 2612 | ); |
| 2613 | assert_eq!( |
| 2614 | send( |
| 2615 | &app, |
| 2616 | "GET", |
| 2617 | &format!("/exams/{exam_id}/results"), |
| 2618 | Some(&alice), |
| 2619 | None |
| 2620 | ) |
| 2621 | .await |
| 2622 | .status, |
| 2623 | StatusCode::FORBIDDEN |
| 2624 | ); |
| 2625 | assert_eq!( |
| 2626 | send( |
| 2627 | &app, |
| 2628 | "DELETE", |
| 2629 | &format!("/exams/{exam_id}/results/{alice_id}"), |
| 2630 | Some(&bob), |
| 2631 | None |
| 2632 | ) |
| 2633 | .await |
| 2634 | .status, |
| 2635 | StatusCode::FORBIDDEN |
| 2636 | ); |
| 2637 | |
| 2638 | // Mark out of range -> 400. |
| 2639 | assert_eq!( |
| 2640 | send( |
| 2641 | &app, |
| 2642 | "POST", |
| 2643 | &format!("/exams/{exam_id}/results"), |
| 2644 | Some(&teacher), |
| 2645 | Some(json!({"mark":101,"user_id":alice_id})) |
| 2646 | ) |
| 2647 | .await |
| 2648 | .status, |
| 2649 | StatusCode::BAD_REQUEST |
| 2650 | ); |
| 2651 | // Unknown target user -> 400. |
| 2652 | assert_eq!( |
| 2653 | send( |
| 2654 | &app, |
| 2655 | "POST", |
| 2656 | &format!("/exams/{exam_id}/results"), |
| 2657 | Some(&teacher), |
| 2658 | Some(json!({"mark":50,"user_id":"ghost"})) |
| 2659 | ) |
| 2660 | .await |
| 2661 | .status, |
| 2662 | StatusCode::BAD_REQUEST |
| 2663 | ); |
| 2664 | // Target exists but is not enrolled in the instance -> 400. |
| 2665 | assert_eq!( |
| 2666 | send( |
| 2667 | &app, |
| 2668 | "POST", |
| 2669 | &format!("/exams/{exam_id}/results"), |
| 2670 | Some(&teacher), |
| 2671 | Some(json!({"mark":50,"user_id":bob_id})) |
| 2672 | ) |
| 2673 | .await |
| 2674 | .status, |
| 2675 | StatusCode::BAD_REQUEST |
| 2676 | ); |
| 2677 | // Grading on a missing exam -> 404. |
| 2678 | assert_eq!( |
| 2679 | send( |
| 2680 | &app, |
| 2681 | "POST", |
| 2682 | "/exams/nope/results", |
| 2683 | Some(&teacher), |
| 2684 | Some(json!({"mark":50,"user_id":alice_id})) |
| 2685 | ) |
| 2686 | .await |
| 2687 | .status, |
| 2688 | StatusCode::NOT_FOUND |
| 2689 | ); |
| 2690 | } |
| 2691 | |
| 2692 | #[tokio::test] |
| 2693 | async fn deleting_exam_cascades_results() { |
| 2694 | let (app, db) = app_and_db().await; |
| 2695 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 2696 | let alice = login(&app, "alice").await; |
| 2697 | let alice_id = me_id(&app, &alice).await; |
| 2698 | |
| 2699 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 2700 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 2701 | enroll(&app, &teacher, &t.instance, &alice_id).await; |
| 2702 | let exam_id = create_exam(&app, &teacher, &t.instance, &t.term, "e", "yazili").await; |
| 2703 | send( |
| 2704 | &app, |
| 2705 | "POST", |
| 2706 | &format!("/exams/{exam_id}/results"), |
| 2707 | Some(&teacher), |
| 2708 | Some(json!({"mark":60,"user_id":alice_id})), |
| 2709 | ) |
| 2710 | .await; |
| 2711 | |
| 2712 | assert_eq!( |
| 2713 | send( |
| 2714 | &app, |
| 2715 | "DELETE", |
| 2716 | &format!("/exams/{exam_id}"), |
| 2717 | Some(&teacher), |
| 2718 | None |
| 2719 | ) |
| 2720 | .await |
| 2721 | .status, |
| 2722 | StatusCode::NO_CONTENT |
| 2723 | ); |
| 2724 | // Exam gone; the student's result is gone with it. |
| 2725 | assert_eq!( |
| 2726 | send( |
| 2727 | &app, |
| 2728 | "GET", |
| 2729 | &format!("/exams/{exam_id}"), |
| 2730 | Some(&teacher), |
| 2731 | None |
| 2732 | ) |
| 2733 | .await |
| 2734 | .status, |
| 2735 | StatusCode::NOT_FOUND |
| 2736 | ); |
| 2737 | assert_eq!( |
| 2738 | send( |
| 2739 | &app, |
| 2740 | "GET", |
| 2741 | &format!("/exams/{exam_id}/result"), |
| 2742 | Some(&alice), |
| 2743 | None |
| 2744 | ) |
| 2745 | .await |
| 2746 | .status, |
| 2747 | StatusCode::NOT_FOUND |
| 2748 | ); |
| 2749 | } |
| 2750 | |
| 2751 | // --- courses + enrollments + marks ---------------------------------------- |
| 2752 | |
| 2753 | #[tokio::test] |
| 2754 | async fn courses_are_owner_scoped_and_creator_guarded() { |
| 2755 | let (app, db) = app_and_db().await; |
| 2756 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 2757 | let veli = login_as(&app, &db, "veli", "teacher").await; |
| 2758 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 2759 | |
| 2760 | let res = send( |
| 2761 | &app, |
| 2762 | "POST", |
| 2763 | "/courses", |
| 2764 | Some(&ali), |
| 2765 | Some(json!({ "title": "algebra", "description": "numbers" })), |
| 2766 | ) |
| 2767 | .await; |
| 2768 | assert_eq!(res.status, StatusCode::CREATED); |
| 2769 | assert_eq!(res.body["title"], "algebra"); |
| 2770 | // The creator comes back as an embedded person ref, not a bare id — the |
| 2771 | // catalog renders names without a second users request. |
| 2772 | assert_eq!(res.body["creator"]["username"], "ali"); |
| 2773 | let course_id = id_of(&res.body); |
| 2774 | |
| 2775 | // Another teacher is not enrolled and doesn't manage it: no read, and the |
| 2776 | // catalog shows them nothing. |
| 2777 | assert_eq!( |
| 2778 | send( |
| 2779 | &app, |
| 2780 | "GET", |
| 2781 | &format!("/courses/{course_id}"), |
| 2782 | Some(&veli), |
| 2783 | None |
| 2784 | ) |
| 2785 | .await |
| 2786 | .status, |
| 2787 | StatusCode::FORBIDDEN |
| 2788 | ); |
| 2789 | assert_eq!( |
| 2790 | common::items(&send(&app, "GET", "/courses", Some(&veli), None).await.body).len(), |
| 2791 | 0 |
| 2792 | ); |
| 2793 | |
| 2794 | // The creator and a manager read the row itself. |
| 2795 | for caller in [&ali, &boss] { |
| 2796 | assert_eq!( |
| 2797 | send( |
| 2798 | &app, |
| 2799 | "GET", |
| 2800 | &format!("/courses/{course_id}"), |
| 2801 | Some(caller), |
| 2802 | None |
| 2803 | ) |
| 2804 | .await |
| 2805 | .status, |
| 2806 | StatusCode::OK |
| 2807 | ); |
| 2808 | } |
| 2809 | // The catalog list is a "courses this caller is reached by" list now: |
| 2810 | // teaching an instance of it, or being enrolled. ali only created the row |
| 2811 | // and teaches no şube, so it is absent from their catalog; the manager |
| 2812 | // sees every course. |
| 2813 | assert!( |
| 2814 | common::items(&send(&app, "GET", "/courses", Some(&ali), None).await.body).is_empty(), |
| 2815 | "a course nobody teaches and nobody is enrolled in is not in the catalog" |
| 2816 | ); |
| 2817 | let catalog = send(&app, "GET", "/courses", Some(&boss), None).await.body; |
| 2818 | let rows = common::items(&catalog); |
| 2819 | assert_eq!(rows.len(), 1); |
| 2820 | assert_eq!( |
| 2821 | rows[0]["creator"]["username"], "ali", |
| 2822 | "the catalog embeds the creator ref on every row" |
| 2823 | ); |
| 2824 | |
| 2825 | // Non-creator teacher cannot edit or delete. |
| 2826 | assert_eq!( |
| 2827 | send( |
| 2828 | &app, |
| 2829 | "PATCH", |
| 2830 | &format!("/courses/{course_id}"), |
| 2831 | Some(&veli), |
| 2832 | Some(json!({"title":"hijack"})) |
| 2833 | ) |
| 2834 | .await |
| 2835 | .status, |
| 2836 | StatusCode::FORBIDDEN |
| 2837 | ); |
| 2838 | assert_eq!( |
| 2839 | send( |
| 2840 | &app, |
| 2841 | "DELETE", |
| 2842 | &format!("/courses/{course_id}"), |
| 2843 | Some(&veli), |
| 2844 | None |
| 2845 | ) |
| 2846 | .await |
| 2847 | .status, |
| 2848 | StatusCode::FORBIDDEN |
| 2849 | ); |
| 2850 | |
| 2851 | // Creator edits (partial) — description flips, title kept. |
| 2852 | let res = send( |
| 2853 | &app, |
| 2854 | "PATCH", |
| 2855 | &format!("/courses/{course_id}"), |
| 2856 | Some(&ali), |
| 2857 | Some(json!({ "description": "letters" })), |
| 2858 | ) |
| 2859 | .await; |
| 2860 | assert_eq!(res.status, StatusCode::OK); |
| 2861 | assert_eq!(res.body["title"], "algebra"); |
| 2862 | assert_eq!(res.body["description"], "letters"); |
| 2863 | |
| 2864 | // A manager can edit anyone's course. |
| 2865 | assert_eq!( |
| 2866 | send( |
| 2867 | &app, |
| 2868 | "PATCH", |
| 2869 | &format!("/courses/{course_id}"), |
| 2870 | Some(&boss), |
| 2871 | Some(json!({"title":"algebra II"})) |
| 2872 | ) |
| 2873 | .await |
| 2874 | .status, |
| 2875 | StatusCode::OK |
| 2876 | ); |
| 2877 | } |
| 2878 | |
| 2879 | /// A manager can put a second teacher in charge of an instance. The assignee |
| 2880 | /// then runs everything inside it — its roster, its exams — but the catalog |
| 2881 | /// course stays its creator's to write, and a demotion takes the assignment |
| 2882 | /// away. |
| 2883 | #[tokio::test] |
| 2884 | async fn assigned_teacher_manages_instance_without_owning_the_course() { |
| 2885 | let (app, db) = app_and_db().await; |
| 2886 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 2887 | let veli = login_as(&app, &db, "veli", "teacher").await; |
| 2888 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 2889 | let rektor = login_as(&app, &db, "rektor", "admin").await; |
| 2890 | let veli_id = id_of(&send(&app, "GET", "/auth/me", Some(&veli), None).await.body); |
| 2891 | |
| 2892 | let t = taught_under(&app, &boss, &ali, "algebra").await; |
| 2893 | let staff = format!("/instances/{}/teachers", t.instance); |
| 2894 | |
| 2895 | // Before assignment veli is just another teacher: no read of the instance. |
| 2896 | assert_eq!( |
| 2897 | send( |
| 2898 | &app, |
| 2899 | "GET", |
| 2900 | &format!("/instances/{}/enrollments", t.instance), |
| 2901 | Some(&veli), |
| 2902 | None |
| 2903 | ) |
| 2904 | .await |
| 2905 | .status, |
| 2906 | StatusCode::FORBIDDEN |
| 2907 | ); |
| 2908 | |
| 2909 | // Staffing is the office's call — the instance's own teacher cannot do it. |
| 2910 | assert_eq!( |
| 2911 | send( |
| 2912 | &app, |
| 2913 | "POST", |
| 2914 | &staff, |
| 2915 | Some(&ali), |
| 2916 | Some(json!({ "user_id": veli_id })) |
| 2917 | ) |
| 2918 | .await |
| 2919 | .status, |
| 2920 | StatusCode::FORBIDDEN |
| 2921 | ); |
| 2922 | |
| 2923 | // Only teacher+ can be assigned. |
| 2924 | let student = login_as(&app, &db, "zeynep", "student").await; |
| 2925 | let student_id = id_of( |
| 2926 | &send(&app, "GET", "/auth/me", Some(&student), None) |
| 2927 | .await |
| 2928 | .body, |
| 2929 | ); |
| 2930 | assert_eq!( |
| 2931 | send( |
| 2932 | &app, |
| 2933 | "POST", |
| 2934 | &staff, |
| 2935 | Some(&boss), |
| 2936 | Some(json!({ "user_id": student_id })) |
| 2937 | ) |
| 2938 | .await |
| 2939 | .status, |
| 2940 | StatusCode::BAD_REQUEST |
| 2941 | ); |
| 2942 | |
| 2943 | // The manager assigns veli; the instance echoes its staff back. |
| 2944 | let res = send( |
| 2945 | &app, |
| 2946 | "POST", |
| 2947 | &staff, |
| 2948 | Some(&boss), |
| 2949 | Some(json!({ "user_id": veli_id })), |
| 2950 | ) |
| 2951 | .await; |
| 2952 | assert_eq!(res.status, StatusCode::OK); |
| 2953 | assert_eq!(res.body["teachers"][0]["username"], "veli"); |
| 2954 | |
| 2955 | // Assigning twice is idempotent — no duplicate row in the list. |
| 2956 | let again = send( |
| 2957 | &app, |
| 2958 | "POST", |
| 2959 | &staff, |
| 2960 | Some(&boss), |
| 2961 | Some(json!({ "user_id": veli_id })), |
| 2962 | ) |
| 2963 | .await; |
| 2964 | assert_eq!(again.status, StatusCode::OK); |
| 2965 | assert_eq!(again.body["teachers"].as_array().unwrap().len(), 1); |
| 2966 | |
| 2967 | // Veli now runs the instance: its roster answers and they can enroll |
| 2968 | // students into it — but the catalog row is not theirs to write. |
| 2969 | assert_eq!( |
| 2970 | send( |
| 2971 | &app, |
| 2972 | "GET", |
| 2973 | &format!("/instances/{}/enrollments", t.instance), |
| 2974 | Some(&veli), |
| 2975 | None |
| 2976 | ) |
| 2977 | .await |
| 2978 | .status, |
| 2979 | StatusCode::OK |
| 2980 | ); |
| 2981 | assert_eq!( |
| 2982 | send( |
| 2983 | &app, |
| 2984 | "PATCH", |
| 2985 | &format!("/courses/{}", t.course), |
| 2986 | Some(&veli), |
| 2987 | Some(json!({"description":"letters"})) |
| 2988 | ) |
| 2989 | .await |
| 2990 | .status, |
| 2991 | StatusCode::FORBIDDEN |
| 2992 | ); |
| 2993 | assert_eq!( |
| 2994 | send( |
| 2995 | &app, |
| 2996 | "POST", |
| 2997 | &format!("/instances/{}/enrollments", t.instance), |
| 2998 | Some(&veli), |
| 2999 | Some(json!({ "user_id": student_id })) |
| 3000 | ) |
| 3001 | .await |
| 3002 | .status, |
| 3003 | StatusCode::OK |
| 3004 | ); |
| 3005 | |
| 3006 | // But the catalog row is not theirs to delete, nor the instance theirs to |
| 3007 | // hand on. |
| 3008 | assert_eq!( |
| 3009 | send( |
| 3010 | &app, |
| 3011 | "DELETE", |
| 3012 | &format!("/courses/{}", t.course), |
| 3013 | Some(&veli), |
| 3014 | None |
| 3015 | ) |
| 3016 | .await |
| 3017 | .status, |
| 3018 | StatusCode::FORBIDDEN |
| 3019 | ); |
| 3020 | assert_eq!( |
| 3021 | send( |
| 3022 | &app, |
| 3023 | "DELETE", |
| 3024 | &format!("{staff}/{veli_id}"), |
| 3025 | Some(&veli), |
| 3026 | None |
| 3027 | ) |
| 3028 | .await |
| 3029 | .status, |
| 3030 | StatusCode::FORBIDDEN |
| 3031 | ); |
| 3032 | |
| 3033 | // Demoting veli below teacher sweeps the assignment: the instance's staff |
| 3034 | // list drops them and the rights go with it. |
| 3035 | assert_eq!( |
| 3036 | send( |
| 3037 | &app, |
| 3038 | "PATCH", |
| 3039 | &format!("/users/{veli_id}/role"), |
| 3040 | Some(&rektor), |
| 3041 | Some(json!({"role":"student"})) |
| 3042 | ) |
| 3043 | .await |
| 3044 | .status, |
| 3045 | StatusCode::OK |
| 3046 | ); |
| 3047 | let after = send( |
| 3048 | &app, |
| 3049 | "GET", |
| 3050 | &format!("/instances/{}", t.instance), |
| 3051 | Some(&ali), |
| 3052 | None, |
| 3053 | ) |
| 3054 | .await; |
| 3055 | assert_eq!( |
| 3056 | after.body["teachers"].as_array().unwrap().len(), |
| 3057 | 0, |
| 3058 | "a demoted teacher is swept off the instances they were assigned to" |
| 3059 | ); |
| 3060 | |
| 3061 | // Re-assign, then unassign by hand: the second removal is a 404. |
| 3062 | send( |
| 3063 | &app, |
| 3064 | "PATCH", |
| 3065 | &format!("/users/{veli_id}/role"), |
| 3066 | Some(&rektor), |
| 3067 | Some(json!({"role":"teacher"})), |
| 3068 | ) |
| 3069 | .await; |
| 3070 | assert_eq!( |
| 3071 | send( |
| 3072 | &app, |
| 3073 | "POST", |
| 3074 | &staff, |
| 3075 | Some(&boss), |
| 3076 | Some(json!({ "user_id": veli_id })) |
| 3077 | ) |
| 3078 | .await |
| 3079 | .status, |
| 3080 | StatusCode::OK |
| 3081 | ); |
| 3082 | assert_eq!( |
| 3083 | send( |
| 3084 | &app, |
| 3085 | "DELETE", |
| 3086 | &format!("{staff}/{veli_id}"), |
| 3087 | Some(&boss), |
| 3088 | None |
| 3089 | ) |
| 3090 | .await |
| 3091 | .status, |
| 3092 | StatusCode::NO_CONTENT |
| 3093 | ); |
| 3094 | assert_eq!( |
| 3095 | send( |
| 3096 | &app, |
| 3097 | "DELETE", |
| 3098 | &format!("{staff}/{veli_id}"), |
| 3099 | Some(&boss), |
| 3100 | None |
| 3101 | ) |
| 3102 | .await |
| 3103 | .status, |
| 3104 | StatusCode::NOT_FOUND |
| 3105 | ); |
| 3106 | assert_eq!( |
| 3107 | send( |
| 3108 | &app, |
| 3109 | "GET", |
| 3110 | &format!("/instances/{}/enrollments", t.instance), |
| 3111 | Some(&veli), |
| 3112 | None |
| 3113 | ) |
| 3114 | .await |
| 3115 | .status, |
| 3116 | StatusCode::FORBIDDEN, |
| 3117 | "unassigning takes the instance back out of their reach" |
| 3118 | ); |
| 3119 | } |
| 3120 | |
| 3121 | #[tokio::test] |
| 3122 | async fn course_input_validation() { |
| 3123 | let (app, db) = app_and_db().await; |
| 3124 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 3125 | |
| 3126 | // Missing/blank title -> 400. |
| 3127 | assert_eq!( |
| 3128 | send( |
| 3129 | &app, |
| 3130 | "POST", |
| 3131 | "/courses", |
| 3132 | Some(&ali), |
| 3133 | Some(json!({"title":" "})) |
| 3134 | ) |
| 3135 | .await |
| 3136 | .status, |
| 3137 | StatusCode::BAD_REQUEST |
| 3138 | ); |
| 3139 | // Missing course -> 404. |
| 3140 | assert_eq!( |
| 3141 | send(&app, "GET", "/courses/nope", Some(&ali), None) |
| 3142 | .await |
| 3143 | .status, |
| 3144 | StatusCode::NOT_FOUND |
| 3145 | ); |
| 3146 | } |
| 3147 | |
| 3148 | /// A course is `course` by default, may be born a `study` (etüt), the kind is |
| 3149 | /// PATCH-editable, and anything else is a 400. |
| 3150 | #[tokio::test] |
| 3151 | async fn course_kind_defaults_validates_and_edits() { |
| 3152 | let (app, db) = app_and_db().await; |
| 3153 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 3154 | |
| 3155 | let plain = send( |
| 3156 | &app, |
| 3157 | "POST", |
| 3158 | "/courses", |
| 3159 | Some(&ali), |
| 3160 | Some(json!({"title":"algebra"})), |
| 3161 | ) |
| 3162 | .await; |
| 3163 | assert_eq!(plain.status, StatusCode::CREATED); |
| 3164 | assert_eq!(plain.body["kind"], "course"); |
| 3165 | |
| 3166 | let etut = send( |
| 3167 | &app, |
| 3168 | "POST", |
| 3169 | "/courses", |
| 3170 | Some(&ali), |
| 3171 | Some(json!({"title":"evening etut", "kind":"study"})), |
| 3172 | ) |
| 3173 | .await; |
| 3174 | assert_eq!(etut.status, StatusCode::CREATED); |
| 3175 | assert_eq!(etut.body["kind"], "study"); |
| 3176 | |
| 3177 | assert_eq!( |
| 3178 | send( |
| 3179 | &app, |
| 3180 | "POST", |
| 3181 | "/courses", |
| 3182 | Some(&ali), |
| 3183 | Some(json!({"title":"nope", "kind":"etut"})) |
| 3184 | ) |
| 3185 | .await |
| 3186 | .status, |
| 3187 | StatusCode::BAD_REQUEST |
| 3188 | ); |
| 3189 | |
| 3190 | // PATCH flips the kind; omitting it keeps the current one. |
| 3191 | let id = id_of(&plain.body); |
| 3192 | let flipped = send( |
| 3193 | &app, |
| 3194 | "PATCH", |
| 3195 | &format!("/courses/{id}"), |
| 3196 | Some(&ali), |
| 3197 | Some(json!({"kind":"study"})), |
| 3198 | ) |
| 3199 | .await; |
| 3200 | assert_eq!(flipped.status, StatusCode::OK); |
| 3201 | assert_eq!(flipped.body["kind"], "study"); |
| 3202 | let renamed = send( |
| 3203 | &app, |
| 3204 | "PATCH", |
| 3205 | &format!("/courses/{id}"), |
| 3206 | Some(&ali), |
| 3207 | Some(json!({"title":"geometry"})), |
| 3208 | ) |
| 3209 | .await; |
| 3210 | assert_eq!(renamed.body["kind"], "study", "omitted kind is kept"); |
| 3211 | } |
| 3212 | |
| 3213 | #[tokio::test] |
| 3214 | async fn enrollment_upsert_roster_and_my_courses() { |
| 3215 | let (app, db) = app_and_db().await; |
| 3216 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 3217 | let alice = login(&app, "alice").await; // student |
| 3218 | let bob = login(&app, "bob").await; // student |
| 3219 | let alice_id = me_id(&app, &alice).await; |
| 3220 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 3221 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 3222 | let roster_uri = format!("/instances/{}/enrollments", t.instance); |
| 3223 | |
| 3224 | // Enrolling twice is an upsert: same row id both times. |
| 3225 | let first = send( |
| 3226 | &app, |
| 3227 | "POST", |
| 3228 | &roster_uri, |
| 3229 | Some(&teacher), |
| 3230 | Some(json!({ "user_id": alice_id })), |
| 3231 | ) |
| 3232 | .await; |
| 3233 | assert_eq!(first.status, StatusCode::OK); |
| 3234 | let second = send( |
| 3235 | &app, |
| 3236 | "POST", |
| 3237 | &roster_uri, |
| 3238 | Some(&teacher), |
| 3239 | Some(json!({ "user_id": alice_id })), |
| 3240 | ) |
| 3241 | .await; |
| 3242 | assert_eq!(id_of(&first.body), id_of(&second.body), "upsert same row"); |
| 3243 | |
| 3244 | // Roster lists alice once; students can't read the roster. |
| 3245 | let roster = send(&app, "GET", &roster_uri, Some(&teacher), None).await; |
| 3246 | assert_eq!(common::items(&roster.body).len(), 1); |
| 3247 | assert_eq!( |
| 3248 | send(&app, "GET", &roster_uri, Some(&alice), None) |
| 3249 | .await |
| 3250 | .status, |
| 3251 | StatusCode::FORBIDDEN |
| 3252 | ); |
| 3253 | |
| 3254 | // /courses/me shows the catalog course alice's instance teaches; it stays |
| 3255 | // empty for bob. |
| 3256 | assert_eq!( |
| 3257 | common::items( |
| 3258 | &send(&app, "GET", "/courses/me", Some(&alice), None) |
| 3259 | .await |
| 3260 | .body, |
| 3261 | ) |
| 3262 | .len(), |
| 3263 | 1 |
| 3264 | ); |
| 3265 | assert_eq!( |
| 3266 | common::items( |
| 3267 | &send(&app, "GET", "/courses/me", Some(&bob), None) |
| 3268 | .await |
| 3269 | .body, |
| 3270 | ) |
| 3271 | .len(), |
| 3272 | 0 |
| 3273 | ); |
| 3274 | |
| 3275 | // Unenroll -> 204; repeating -> 404. |
| 3276 | assert_eq!( |
| 3277 | send( |
| 3278 | &app, |
| 3279 | "DELETE", |
| 3280 | &format!("{roster_uri}/{alice_id}"), |
| 3281 | Some(&teacher), |
| 3282 | None |
| 3283 | ) |
| 3284 | .await |
| 3285 | .status, |
| 3286 | StatusCode::NO_CONTENT |
| 3287 | ); |
| 3288 | assert_eq!( |
| 3289 | send( |
| 3290 | &app, |
| 3291 | "DELETE", |
| 3292 | &format!("{roster_uri}/{alice_id}"), |
| 3293 | Some(&teacher), |
| 3294 | None |
| 3295 | ) |
| 3296 | .await |
| 3297 | .status, |
| 3298 | StatusCode::NOT_FOUND |
| 3299 | ); |
| 3300 | } |
| 3301 | |
| 3302 | #[tokio::test] |
| 3303 | async fn enrollment_requires_instance_management() { |
| 3304 | let (app, db) = app_and_db().await; |
| 3305 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 3306 | let veli = login_as(&app, &db, "veli", "teacher").await; |
| 3307 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 3308 | let alice = login(&app, "alice").await; // student |
| 3309 | let alice_id = me_id(&app, &alice).await; |
| 3310 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 3311 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 3312 | let roster_uri = format!("/instances/{}/enrollments", t.instance); |
| 3313 | |
| 3314 | // A teacher who doesn't run the instance cannot enroll anyone into it. |
| 3315 | assert_eq!( |
| 3316 | send( |
| 3317 | &app, |
| 3318 | "POST", |
| 3319 | &roster_uri, |
| 3320 | Some(&veli), |
| 3321 | Some(json!({ "user_id": alice_id })) |
| 3322 | ) |
| 3323 | .await |
| 3324 | .status, |
| 3325 | StatusCode::FORBIDDEN |
| 3326 | ); |
| 3327 | // A manager can. |
| 3328 | assert_eq!( |
| 3329 | send( |
| 3330 | &app, |
| 3331 | "POST", |
| 3332 | &roster_uri, |
| 3333 | Some(&boss), |
| 3334 | Some(json!({ "user_id": alice_id })) |
| 3335 | ) |
| 3336 | .await |
| 3337 | .status, |
| 3338 | StatusCode::OK |
| 3339 | ); |
| 3340 | // Unknown target -> 400; missing instance -> 404. |
| 3341 | assert_eq!( |
| 3342 | send( |
| 3343 | &app, |
| 3344 | "POST", |
| 3345 | &roster_uri, |
| 3346 | Some(&teacher), |
| 3347 | Some(json!({ "user_id": "ghost" })) |
| 3348 | ) |
| 3349 | .await |
| 3350 | .status, |
| 3351 | StatusCode::BAD_REQUEST |
| 3352 | ); |
| 3353 | assert_eq!( |
| 3354 | send( |
| 3355 | &app, |
| 3356 | "POST", |
| 3357 | "/instances/nope/enrollments", |
| 3358 | Some(&teacher), |
| 3359 | Some(json!({ "user_id": alice_id })) |
| 3360 | ) |
| 3361 | .await |
| 3362 | .status, |
| 3363 | StatusCode::NOT_FOUND |
| 3364 | ); |
| 3365 | } |
| 3366 | |
| 3367 | #[tokio::test] |
| 3368 | async fn exam_creation_lives_under_instances() { |
| 3369 | let (app, db) = app_and_db().await; |
| 3370 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 3371 | let veli = login_as(&app, &db, "veli", "teacher").await; |
| 3372 | let alice = login(&app, "alice").await; // student |
| 3373 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 3374 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 3375 | let exams_uri = format!("/instances/{}/exams", t.instance); |
| 3376 | |
| 3377 | // The old flat creation route is gone: /exams only serves GET now. |
| 3378 | assert_eq!( |
| 3379 | send( |
| 3380 | &app, |
| 3381 | "POST", |
| 3382 | "/exams", |
| 3383 | Some(&teacher), |
| 3384 | Some(json!({"title":"t","kind":"yazili","term": &t.term})) |
| 3385 | ) |
| 3386 | .await |
| 3387 | .status, |
| 3388 | StatusCode::METHOD_NOT_ALLOWED |
| 3389 | ); |
| 3390 | |
| 3391 | // Creation inside the instance echoes the instance it belongs to. |
| 3392 | let res = send( |
| 3393 | &app, |
| 3394 | "POST", |
| 3395 | &exams_uri, |
| 3396 | Some(&teacher), |
| 3397 | Some(json!({"title":"mt","kind":"yazili","term": &t.term})), |
| 3398 | ) |
| 3399 | .await; |
| 3400 | assert_eq!(res.status, StatusCode::CREATED); |
| 3401 | assert_eq!(res.body["class_course"], t.instance); |
| 3402 | |
| 3403 | // A teacher who doesn't run the instance cannot add exams to it. |
| 3404 | assert_eq!( |
| 3405 | send( |
| 3406 | &app, |
| 3407 | "POST", |
| 3408 | &exams_uri, |
| 3409 | Some(&veli), |
| 3410 | Some(json!({"title":"x","kind":"yazili","term": &t.term})) |
| 3411 | ) |
| 3412 | .await |
| 3413 | .status, |
| 3414 | StatusCode::FORBIDDEN |
| 3415 | ); |
| 3416 | |
| 3417 | // An unenrolled student cannot list the instance's exams … |
| 3418 | assert_eq!( |
| 3419 | send(&app, "GET", &exams_uri, Some(&alice), None) |
| 3420 | .await |
| 3421 | .status, |
| 3422 | StatusCode::FORBIDDEN |
| 3423 | ); |
| 3424 | |
| 3425 | // … but an enrolled one can. |
| 3426 | let alice_id = me_id(&app, &alice).await; |
| 3427 | enroll(&app, &teacher, &t.instance, &alice_id).await; |
| 3428 | assert_eq!( |
| 3429 | common::items(&send(&app, "GET", &exams_uri, Some(&alice), None).await.body).len(), |
| 3430 | 1 |
| 3431 | ); |
| 3432 | } |
| 3433 | |
| 3434 | #[tokio::test] |
| 3435 | async fn grading_requires_enrollment() { |
| 3436 | let (app, db) = app_and_db().await; |
| 3437 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 3438 | let alice = login(&app, "alice").await; // student |
| 3439 | let alice_id = me_id(&app, &alice).await; |
| 3440 | |
| 3441 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 3442 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 3443 | let exam_id = create_exam(&app, &teacher, &t.instance, &t.term, "mt", "yazili").await; |
| 3444 | let grade_uri = format!("/exams/{exam_id}/results"); |
| 3445 | let grade_body = json!({ "mark": 70, "user_id": alice_id }); |
| 3446 | |
| 3447 | // Not enrolled -> 400. |
| 3448 | assert_eq!( |
| 3449 | send( |
| 3450 | &app, |
| 3451 | "POST", |
| 3452 | &grade_uri, |
| 3453 | Some(&teacher), |
| 3454 | Some(grade_body.clone()) |
| 3455 | ) |
| 3456 | .await |
| 3457 | .status, |
| 3458 | StatusCode::BAD_REQUEST |
| 3459 | ); |
| 3460 | |
| 3461 | // In the şube: the pump enrolls her into the instance it carries -> 200. |
| 3462 | add_member(&app, &mudur, &t.class, &alice_id).await; |
| 3463 | assert_eq!( |
| 3464 | send( |
| 3465 | &app, |
| 3466 | "POST", |
| 3467 | &grade_uri, |
| 3468 | Some(&teacher), |
| 3469 | Some(grade_body.clone()) |
| 3470 | ) |
| 3471 | .await |
| 3472 | .status, |
| 3473 | StatusCode::OK |
| 3474 | ); |
| 3475 | |
| 3476 | // Dropping the roster row blocks further grading but keeps the recorded |
| 3477 | // result: the row still lists for the teacher and the student still reads |
| 3478 | // it. |
| 3479 | unenroll(&app, &teacher, &t.instance, &alice_id).await; |
| 3480 | assert_eq!( |
| 3481 | send(&app, "POST", &grade_uri, Some(&teacher), Some(grade_body)) |
| 3482 | .await |
| 3483 | .status, |
| 3484 | StatusCode::BAD_REQUEST |
| 3485 | ); |
| 3486 | assert_eq!( |
| 3487 | common::items( |
| 3488 | &send(&app, "GET", &grade_uri, Some(&teacher), None) |
| 3489 | .await |
| 3490 | .body |
| 3491 | ) |
| 3492 | .len(), |
| 3493 | 1 |
| 3494 | ); |
| 3495 | assert_eq!( |
| 3496 | send( |
| 3497 | &app, |
| 3498 | "GET", |
| 3499 | &format!("/exams/{exam_id}/result"), |
| 3500 | Some(&alice), |
| 3501 | None |
| 3502 | ) |
| 3503 | .await |
| 3504 | .body["mark"], |
| 3505 | 70 |
| 3506 | ); |
| 3507 | |
| 3508 | // The report follows the student's section, not the roster row, so the |
| 3509 | // mark stays on it while she is off the roster. |
| 3510 | let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; |
| 3511 | assert_eq!(report.body["courses"].as_array().unwrap().len(), 1); |
| 3512 | assert_eq!(report.body["courses"][0]["average"], 70.0); |
| 3513 | |
| 3514 | // Re-enrolling reopens grading, and the new mark lands in the report. |
| 3515 | enroll(&app, &teacher, &t.instance, &alice_id).await; |
| 3516 | assert_eq!( |
| 3517 | send( |
| 3518 | &app, |
| 3519 | "POST", |
| 3520 | &grade_uri, |
| 3521 | Some(&teacher), |
| 3522 | Some(json!({ "mark": 80, "user_id": alice_id })) |
| 3523 | ) |
| 3524 | .await |
| 3525 | .status, |
| 3526 | StatusCode::OK |
| 3527 | ); |
| 3528 | let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; |
| 3529 | assert_eq!(report.body["courses"][0]["average"], 80.0); |
| 3530 | } |
| 3531 | |
| 3532 | #[tokio::test] |
| 3533 | async fn exam_writes_follow_instance_management() { |
| 3534 | let (app, db) = app_and_db().await; |
| 3535 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 3536 | let veli = login_as(&app, &db, "veli", "teacher").await; |
| 3537 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 3538 | let t = taught_under(&app, &boss, &teacher, "algebra").await; |
| 3539 | |
| 3540 | // A manager creates an exam in the teacher's instance... |
| 3541 | let exam_id = create_exam(&app, &boss, &t.instance, &t.term, "mt", "yazili").await; |
| 3542 | |
| 3543 | // ...and the instance's own teacher (not the exam's creator) can edit and |
| 3544 | // delete it. |
| 3545 | assert_eq!( |
| 3546 | send( |
| 3547 | &app, |
| 3548 | "PATCH", |
| 3549 | &format!("/exams/{exam_id}"), |
| 3550 | Some(&teacher), |
| 3551 | Some(json!({"title":"renamed"})) |
| 3552 | ) |
| 3553 | .await |
| 3554 | .body["title"], |
| 3555 | "renamed" |
| 3556 | ); |
| 3557 | // An unrelated teacher still cannot. |
| 3558 | assert_eq!( |
| 3559 | send( |
| 3560 | &app, |
| 3561 | "PATCH", |
| 3562 | &format!("/exams/{exam_id}"), |
| 3563 | Some(&veli), |
| 3564 | Some(json!({"title":"hijack"})) |
| 3565 | ) |
| 3566 | .await |
| 3567 | .status, |
| 3568 | StatusCode::FORBIDDEN |
| 3569 | ); |
| 3570 | assert_eq!( |
| 3571 | send( |
| 3572 | &app, |
| 3573 | "DELETE", |
| 3574 | &format!("/exams/{exam_id}"), |
| 3575 | Some(&teacher), |
| 3576 | None |
| 3577 | ) |
| 3578 | .await |
| 3579 | .status, |
| 3580 | StatusCode::NO_CONTENT |
| 3581 | ); |
| 3582 | } |
| 3583 | |
| 3584 | #[tokio::test] |
| 3585 | async fn exam_statistics_summarize_results() { |
| 3586 | let (app, db) = app_and_db().await; |
| 3587 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 3588 | let alice = login(&app, "alice").await; |
| 3589 | let bob = login(&app, "bob").await; |
| 3590 | let alice_id = me_id(&app, &alice).await; |
| 3591 | let bob_id = me_id(&app, &bob).await; |
| 3592 | |
| 3593 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 3594 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 3595 | enroll(&app, &teacher, &t.instance, &alice_id).await; |
| 3596 | enroll(&app, &teacher, &t.instance, &bob_id).await; |
| 3597 | let exam_id = create_exam(&app, &teacher, &t.instance, &t.term, "mt", "yazili").await; |
| 3598 | let stats_uri = format!("/exams/{exam_id}/statistics"); |
| 3599 | |
| 3600 | // Nothing graded yet: zero count, null aggregates. |
| 3601 | let res = send(&app, "GET", &stats_uri, Some(&teacher), None).await; |
| 3602 | assert_eq!(res.status, StatusCode::OK); |
| 3603 | assert_eq!(res.body["graded"], 0); |
| 3604 | assert_eq!(res.body["average"], serde_json::Value::Null); |
| 3605 | assert_eq!(res.body["min"], serde_json::Value::Null); |
| 3606 | assert_eq!(res.body["max"], serde_json::Value::Null); |
| 3607 | |
| 3608 | for (id, mark) in [(&alice_id, 60), (&bob_id, 80)] { |
| 3609 | send( |
| 3610 | &app, |
| 3611 | "POST", |
| 3612 | &format!("/exams/{exam_id}/results"), |
| 3613 | Some(&teacher), |
| 3614 | Some(json!({ "mark": mark, "user_id": id })), |
| 3615 | ) |
| 3616 | .await; |
| 3617 | } |
| 3618 | |
| 3619 | let res = send(&app, "GET", &stats_uri, Some(&teacher), None).await; |
| 3620 | assert_eq!(res.body["graded"], 2); |
| 3621 | assert_eq!(res.body["average"], 70.0); |
| 3622 | assert_eq!(res.body["min"], 60); |
| 3623 | assert_eq!(res.body["max"], 80); |
| 3624 | |
| 3625 | // Students don't see statistics; missing exam is a 404. |
| 3626 | assert_eq!( |
| 3627 | send(&app, "GET", &stats_uri, Some(&alice), None) |
| 3628 | .await |
| 3629 | .status, |
| 3630 | StatusCode::FORBIDDEN |
| 3631 | ); |
| 3632 | } |
| 3633 | |
| 3634 | #[tokio::test] |
| 3635 | async fn weighted_averages_follow_kind_weights() { |
| 3636 | let (app, db) = app_and_db().await; |
| 3637 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 3638 | let manager = login_as(&app, &db, "boss", "manager").await; |
| 3639 | let alice = login(&app, "alice").await; |
| 3640 | let alice_id = me_id(&app, &alice).await; |
| 3641 | |
| 3642 | // Weights are school policy, per kind: quizzes count once, midterms three |
| 3643 | // times (the defaults are all 1). |
| 3644 | let res = send( |
| 3645 | &app, |
| 3646 | "PATCH", |
| 3647 | "/settings", |
| 3648 | Some(&manager), |
| 3649 | Some(json!({ "exam_kinds": [ |
| 3650 | {"name": "quiz", "weight": 1}, |
| 3651 | {"name": "midterm", "weight": 3}, |
| 3652 | {"name": "final", "weight": 4}, |
| 3653 | {"name": "homework", "weight": 1}, |
| 3654 | ]})), |
| 3655 | ) |
| 3656 | .await; |
| 3657 | assert_eq!(res.status, StatusCode::OK); |
| 3658 | |
| 3659 | // Course A: quiz (w1, mark 50) + midterm (w3, mark 90) -> (50 + 270) / 4 = 80. |
| 3660 | let algebra = taught_under(&app, &manager, &teacher, "algebra").await; |
| 3661 | // The report follows the student's section, so she is a member of the şube |
| 3662 | // each instance hangs off (the pump enrolls her there). |
| 3663 | add_member(&app, &manager, &algebra.class, &alice_id).await; |
| 3664 | let quiz = create_exam( |
| 3665 | &app, |
| 3666 | &teacher, |
| 3667 | &algebra.instance, |
| 3668 | &algebra.term, |
| 3669 | "quiz", |
| 3670 | "quiz", |
| 3671 | ) |
| 3672 | .await; |
| 3673 | let midterm = create_exam( |
| 3674 | &app, |
| 3675 | &teacher, |
| 3676 | &algebra.instance, |
| 3677 | &algebra.term, |
| 3678 | "midterm", |
| 3679 | "midterm", |
| 3680 | ) |
| 3681 | .await; |
| 3682 | // A third exam stays ungraded and must not drag the average. |
| 3683 | create_exam( |
| 3684 | &app, |
| 3685 | &teacher, |
| 3686 | &algebra.instance, |
| 3687 | &algebra.term, |
| 3688 | "final", |
| 3689 | "final", |
| 3690 | ) |
| 3691 | .await; |
| 3692 | for (exam, mark) in [(&quiz, 50), (&midterm, 90)] { |
| 3693 | let res = send( |
| 3694 | &app, |
| 3695 | "POST", |
| 3696 | &format!("/exams/{exam}/results"), |
| 3697 | Some(&teacher), |
| 3698 | Some(json!({ "mark": mark, "user_id": alice_id })), |
| 3699 | ) |
| 3700 | .await; |
| 3701 | assert_eq!(res.status, StatusCode::OK); |
| 3702 | } |
| 3703 | |
| 3704 | // Course B: enrolled, nothing graded -> null average. |
| 3705 | let physics = taught_under(&app, &manager, &teacher, "physics").await; |
| 3706 | add_member(&app, &manager, &physics.class, &alice_id).await; |
| 3707 | create_exam( |
| 3708 | &app, |
| 3709 | &teacher, |
| 3710 | &physics.instance, |
| 3711 | &physics.term, |
| 3712 | "hw", |
| 3713 | "homework", |
| 3714 | ) |
| 3715 | .await; |
| 3716 | |
| 3717 | let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; |
| 3718 | assert_eq!(report.status, StatusCode::OK); |
| 3719 | let courses = report.body["courses"].as_array().unwrap(); |
| 3720 | assert_eq!(courses.len(), 2); |
| 3721 | let algebra_block = courses |
| 3722 | .iter() |
| 3723 | .find(|c| c["course"]["title"] == "algebra") |
| 3724 | .unwrap(); |
| 3725 | let physics_block = courses |
| 3726 | .iter() |
| 3727 | .find(|c| c["course"]["title"] == "physics") |
| 3728 | .unwrap(); |
| 3729 | |
| 3730 | assert_eq!(algebra_block["average"], 80.0); |
| 3731 | assert_eq!(algebra_block["results"].as_array().unwrap().len(), 2); |
| 3732 | // Each entry carries its kind's resolved weight. |
| 3733 | let midterm_entry = algebra_block["results"] |
| 3734 | .as_array() |
| 3735 | .unwrap() |
| 3736 | .iter() |
| 3737 | .find(|entry| entry["kind"] == "midterm") |
| 3738 | .unwrap(); |
| 3739 | assert_eq!(midterm_entry["weight"], 3); |
| 3740 | assert_eq!(physics_block["average"], serde_json::Value::Null); |
| 3741 | assert_eq!(physics_block["results"].as_array().unwrap().len(), 0); |
| 3742 | // Overall skips the null course instead of zeroing it. |
| 3743 | assert_eq!(report.body["overall_average"], 80.0); |
| 3744 | assert_eq!(report.body["user"], alice_id); |
| 3745 | } |
| 3746 | |
| 3747 | /// Kind weights resolve at report time: editing a kind's weight re-weights |
| 3748 | /// already-graded exams, and a kind removed from settings counts once. |
| 3749 | #[tokio::test] |
| 3750 | async fn kind_weight_edits_reweight_reports_live() { |
| 3751 | let (app, db) = app_and_db().await; |
| 3752 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 3753 | let manager = login_as(&app, &db, "boss", "manager").await; |
| 3754 | let alice = login(&app, "alice").await; |
| 3755 | let alice_id = me_id(&app, &alice).await; |
| 3756 | |
| 3757 | // The kinds this test re-weights are the school's own: it lists them |
| 3758 | // first, since the shipped defaults are yazili/sozlu/uygulama. |
| 3759 | let res = send( |
| 3760 | &app, |
| 3761 | "PATCH", |
| 3762 | "/settings", |
| 3763 | Some(&manager), |
| 3764 | Some(json!({ "exam_kinds": [ |
| 3765 | {"name": "quiz", "weight": 1}, |
| 3766 | {"name": "oral", "weight": 1}, |
| 3767 | {"name": "project", "weight": 1}, |
| 3768 | ]})), |
| 3769 | ) |
| 3770 | .await; |
| 3771 | assert_eq!(res.status, StatusCode::OK); |
| 3772 | |
| 3773 | let course = taught_under(&app, &manager, &teacher, "algebra").await; |
| 3774 | add_member(&app, &manager, &course.class, &alice_id).await; |
| 3775 | let quiz = create_exam(&app, &teacher, &course.instance, &course.term, "q", "quiz").await; |
| 3776 | let oral = create_exam(&app, &teacher, &course.instance, &course.term, "o", "oral").await; |
| 3777 | // Ungraded for now — its kind gets retired below, out from under it. |
| 3778 | let project = create_exam( |
| 3779 | &app, |
| 3780 | &teacher, |
| 3781 | &course.instance, |
| 3782 | &course.term, |
| 3783 | "p", |
| 3784 | "project", |
| 3785 | ) |
| 3786 | .await; |
| 3787 | for (exam, mark) in [(&quiz, 40), (&oral, 80)] { |
| 3788 | let res = send( |
| 3789 | &app, |
| 3790 | "POST", |
| 3791 | &format!("/exams/{exam}/results"), |
| 3792 | Some(&teacher), |
| 3793 | Some(json!({ "mark": mark, "user_id": alice_id })), |
| 3794 | ) |
| 3795 | .await; |
| 3796 | assert_eq!(res.status, StatusCode::OK); |
| 3797 | } |
| 3798 | |
| 3799 | // The school's weights, all 1: plain mean of 40 and 80. |
| 3800 | let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; |
| 3801 | assert_eq!(report.body["courses"][0]["average"], 60.0); |
| 3802 | |
| 3803 | // Triple the oral weight — the already-graded exam follows immediately: |
| 3804 | // (40 + 240) / 4 = 70. |
| 3805 | let res = send( |
| 3806 | &app, |
| 3807 | "PATCH", |
| 3808 | "/settings", |
| 3809 | Some(&manager), |
| 3810 | Some(json!({ "exam_kinds": [ |
| 3811 | {"name": "quiz", "weight": 1}, |
| 3812 | {"name": "oral", "weight": 3}, |
| 3813 | ]})), |
| 3814 | ) |
| 3815 | .await; |
| 3816 | assert_eq!(res.status, StatusCode::OK); |
| 3817 | let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; |
| 3818 | assert_eq!(report.body["courses"][0]["average"], 70.0); |
| 3819 | |
| 3820 | // The PATCH above also retired `project` (allowed — no marks of that kind |
| 3821 | // existed yet; a graded kind can't leave at all, see |
| 3822 | // `exam_kind_removal_blocks_while_marks_exist`). Its exam lives on, but a |
| 3823 | // retired kind takes no new marks: that is the other end of the same rule, |
| 3824 | // and it is what keeps "a kind with marks cannot be removed" true however |
| 3825 | // the two writes interleave. |
| 3826 | let grade_project = async || { |
| 3827 | send( |
| 3828 | &app, |
| 3829 | "POST", |
| 3830 | &format!("/exams/{project}/results"), |
| 3831 | Some(&teacher), |
| 3832 | Some(json!({ "mark": 60, "user_id": alice_id })), |
| 3833 | ) |
| 3834 | .await |
| 3835 | }; |
| 3836 | assert_eq!(grade_project().await.status, StatusCode::CONFLICT); |
| 3837 | // Offered again — at weight 1, so the exam counts exactly as an exam of a |
| 3838 | // since-removed kind would have. |
| 3839 | let res = send( |
| 3840 | &app, |
| 3841 | "PATCH", |
| 3842 | "/settings", |
| 3843 | Some(&manager), |
| 3844 | Some(json!({ "exam_kinds": [ |
| 3845 | {"name": "quiz", "weight": 1}, |
| 3846 | {"name": "oral", "weight": 3}, |
| 3847 | {"name": "project", "weight": 1}, |
| 3848 | ]})), |
| 3849 | ) |
| 3850 | .await; |
| 3851 | assert_eq!(res.status, StatusCode::OK); |
| 3852 | assert_eq!(grade_project().await.status, StatusCode::OK); |
| 3853 | // (40 + 240 + 60) / 5 = 68. |
| 3854 | let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; |
| 3855 | assert_eq!(report.body["courses"][0]["average"], 68.0); |
| 3856 | let project_entry = report.body["courses"][0]["results"] |
| 3857 | .as_array() |
| 3858 | .unwrap() |
| 3859 | .iter() |
| 3860 | .find(|entry| entry["kind"] == "project") |
| 3861 | .unwrap() |
| 3862 | .clone(); |
| 3863 | assert_eq!(project_entry["weight"], 1); |
| 3864 | } |
| 3865 | |
| 3866 | #[tokio::test] |
| 3867 | async fn marks_reports_are_self_or_teacher_scoped() { |
| 3868 | let (app, db) = app_and_db().await; |
| 3869 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 3870 | let alice = login(&app, "alice").await; |
| 3871 | let bob = login(&app, "bob").await; |
| 3872 | let alice_id = me_id(&app, &alice).await; |
| 3873 | |
| 3874 | // Own report works for a student. |
| 3875 | assert_eq!( |
| 3876 | send(&app, "GET", "/marks/me", Some(&alice), None) |
| 3877 | .await |
| 3878 | .status, |
| 3879 | StatusCode::OK |
| 3880 | ); |
| 3881 | // Another user's report needs teacher+. |
| 3882 | assert_eq!( |
| 3883 | send(&app, "GET", &format!("/marks/{alice_id}"), Some(&bob), None) |
| 3884 | .await |
| 3885 | .status, |
| 3886 | StatusCode::FORBIDDEN |
| 3887 | ); |
| 3888 | assert_eq!( |
| 3889 | send( |
| 3890 | &app, |
| 3891 | "GET", |
| 3892 | &format!("/marks/{alice_id}"), |
| 3893 | Some(&teacher), |
| 3894 | None |
| 3895 | ) |
| 3896 | .await |
| 3897 | .status, |
| 3898 | StatusCode::OK |
| 3899 | ); |
| 3900 | } |
| 3901 | |
| 3902 | /// One teacher's course is a wall: another teacher can't read its roster, |
| 3903 | /// results, statistics, live monitor, answer key, or answer sheets, and the |
| 3904 | /// per-user reports narrow to the courses the caller manages. Managers see |
| 3905 | /// through the wall; an enrolled student sees the course itself. |
| 3906 | #[tokio::test] |
| 3907 | async fn course_data_is_walled_off_from_other_teachers() { |
| 3908 | let (app, db) = app_and_db().await; |
| 3909 | let owner = login_as(&app, &db, "owner", "teacher").await; |
| 3910 | let rival = login_as(&app, &db, "rival", "teacher").await; |
| 3911 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 3912 | let alice = login(&app, "alice").await; |
| 3913 | let alice_id = me_id(&app, &alice).await; |
| 3914 | |
| 3915 | let t = taught_under(&app, &boss, &owner, "algebra").await; |
| 3916 | // Alice sits in the şube: the pump enrolls her into the instance it carries |
| 3917 | // and puts the instance in her catalog and report. |
| 3918 | add_member(&app, &boss, &t.class, &alice_id).await; |
| 3919 | let exam_id = create_exam(&app, &owner, &t.instance, &t.term, "mt", "yazili").await; |
| 3920 | let res = send( |
| 3921 | &app, |
| 3922 | "POST", |
| 3923 | &format!("/exams/{exam_id}/results"), |
| 3924 | Some(&owner), |
| 3925 | Some(json!({ "mark": 70, "user_id": alice_id })), |
| 3926 | ) |
| 3927 | .await; |
| 3928 | assert_eq!(res.status, StatusCode::OK); |
| 3929 | |
| 3930 | // Every instance-scoped teacher read is refused for the rival … |
| 3931 | for uri in [ |
| 3932 | format!("/instances/{}/enrollments", t.instance), |
| 3933 | format!("/exams/{exam_id}/results"), |
| 3934 | format!("/exams/{exam_id}/statistics"), |
| 3935 | format!("/exams/{exam_id}/live"), |
| 3936 | format!("/exams/{exam_id}/questions"), |
| 3937 | format!("/exams/{exam_id}/attempts/{alice_id}/answers"), |
| 3938 | ] { |
| 3939 | let res = send(&app, "GET", &uri, Some(&rival), None).await; |
| 3940 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri}"); |
| 3941 | } |
| 3942 | |
| 3943 | // … and open to the owner and a manager. (The answer sheet turns into a |
| 3944 | // 404 once authorization clears: alice never sat the exam.) |
| 3945 | for caller in [&owner, &boss] { |
| 3946 | for uri in [ |
| 3947 | format!("/instances/{}/enrollments", t.instance), |
| 3948 | format!("/exams/{exam_id}/results"), |
| 3949 | format!("/exams/{exam_id}/statistics"), |
| 3950 | format!("/exams/{exam_id}/live"), |
| 3951 | format!("/exams/{exam_id}/questions"), |
| 3952 | ] { |
| 3953 | let res = send(&app, "GET", &uri, Some(caller), None).await; |
| 3954 | assert_eq!(res.status, StatusCode::OK, "{uri}"); |
| 3955 | } |
| 3956 | let res = send( |
| 3957 | &app, |
| 3958 | "GET", |
| 3959 | &format!("/exams/{exam_id}/attempts/{alice_id}/answers"), |
| 3960 | Some(caller), |
| 3961 | None, |
| 3962 | ) |
| 3963 | .await; |
| 3964 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 3965 | } |
| 3966 | |
| 3967 | // The marks report narrows to the caller's instances: the rival gets an |
| 3968 | // empty shell, the owner and the manager get the graded course. |
| 3969 | let res = send( |
| 3970 | &app, |
| 3971 | "GET", |
| 3972 | &format!("/marks/{alice_id}"), |
| 3973 | Some(&rival), |
| 3974 | None, |
| 3975 | ) |
| 3976 | .await; |
| 3977 | assert_eq!(res.status, StatusCode::OK); |
| 3978 | assert!(res.body["courses"].as_array().unwrap().is_empty()); |
| 3979 | assert!(res.body["overall_average"].is_null()); |
| 3980 | for caller in [&owner, &boss] { |
| 3981 | let res = send( |
| 3982 | &app, |
| 3983 | "GET", |
| 3984 | &format!("/marks/{alice_id}"), |
| 3985 | Some(caller), |
| 3986 | None, |
| 3987 | ) |
| 3988 | .await; |
| 3989 | assert_eq!(res.body["courses"].as_array().unwrap().len(), 1); |
| 3990 | assert_eq!(res.body["overall_average"], 70.0); |
| 3991 | } |
| 3992 | |
| 3993 | // The enrolled student reads the course and its exam, and both catalogs |
| 3994 | // include them; the rival's catalogs stay empty; a manager sees all. |
| 3995 | for uri in [ |
| 3996 | format!("/courses/{}", t.course), |
| 3997 | format!("/exams/{exam_id}"), |
| 3998 | ] { |
| 3999 | let res = send(&app, "GET", &uri, Some(&alice), None).await; |
| 4000 | assert_eq!(res.status, StatusCode::OK, "{uri}"); |
| 4001 | } |
| 4002 | for (caller, visible) in [(&alice, 1), (&rival, 0), (&boss, 1)] { |
| 4003 | for uri in ["/courses", "/exams"] { |
| 4004 | let res = send(&app, "GET", uri, Some(caller), None).await; |
| 4005 | assert_eq!( |
| 4006 | common::items(&res.body).len(), |
| 4007 | visible, |
| 4008 | "{uri} as seen by caller" |
| 4009 | ); |
| 4010 | } |
| 4011 | } |
| 4012 | } |
| 4013 | |
| 4014 | #[tokio::test] |
| 4015 | async fn deleting_course_cascades_enrollments_exams_and_results() { |
| 4016 | let (app, db) = app_and_db().await; |
| 4017 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 4018 | let alice = login(&app, "alice").await; |
| 4019 | let alice_id = me_id(&app, &alice).await; |
| 4020 | |
| 4021 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 4022 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 4023 | |
| 4024 | add_member(&app, &mudur, &t.class, &alice_id).await; |
| 4025 | let exam_id = create_exam(&app, &teacher, &t.instance, &t.term, "mt", "yazili").await; |
| 4026 | send( |
| 4027 | &app, |
| 4028 | "POST", |
| 4029 | &format!("/exams/{exam_id}/results"), |
| 4030 | Some(&teacher), |
| 4031 | Some(json!({ "mark": 70, "user_id": alice_id })), |
| 4032 | ) |
| 4033 | .await; |
| 4034 | |
| 4035 | // A course a şube still teaches is not deletable: the guard that keeps a |
| 4036 | // taught catalog row from being dropped by accident. |
| 4037 | assert_eq!( |
| 4038 | send( |
| 4039 | &app, |
| 4040 | "DELETE", |
| 4041 | &format!("/courses/{}", t.course), |
| 4042 | Some(&teacher), |
| 4043 | None |
| 4044 | ) |
| 4045 | .await |
| 4046 | .status, |
| 4047 | StatusCode::CONFLICT |
| 4048 | ); |
| 4049 | |
| 4050 | // Detaching the instance is what takes its exams, results and roster. |
| 4051 | assert_eq!( |
| 4052 | send( |
| 4053 | &app, |
| 4054 | "DELETE", |
| 4055 | &format!("/classes/{}/instances/{}", t.class, t.instance), |
| 4056 | Some(&teacher), |
| 4057 | None |
| 4058 | ) |
| 4059 | .await |
| 4060 | .status, |
| 4061 | StatusCode::NO_CONTENT |
| 4062 | ); |
| 4063 | |
| 4064 | // Now free, the catalog row goes. |
| 4065 | assert_eq!( |
| 4066 | send( |
| 4067 | &app, |
| 4068 | "DELETE", |
| 4069 | &format!("/courses/{}", t.course), |
| 4070 | Some(&teacher), |
| 4071 | None |
| 4072 | ) |
| 4073 | .await |
| 4074 | .status, |
| 4075 | StatusCode::NO_CONTENT |
| 4076 | ); |
| 4077 | |
| 4078 | // Course, exam, result, and enrollment are all gone. |
| 4079 | assert_eq!( |
| 4080 | send( |
| 4081 | &app, |
| 4082 | "GET", |
| 4083 | &format!("/courses/{}", t.course), |
| 4084 | Some(&teacher), |
| 4085 | None |
| 4086 | ) |
| 4087 | .await |
| 4088 | .status, |
| 4089 | StatusCode::NOT_FOUND |
| 4090 | ); |
| 4091 | assert_eq!( |
| 4092 | send( |
| 4093 | &app, |
| 4094 | "GET", |
| 4095 | &format!("/exams/{exam_id}"), |
| 4096 | Some(&teacher), |
| 4097 | None |
| 4098 | ) |
| 4099 | .await |
| 4100 | .status, |
| 4101 | StatusCode::NOT_FOUND |
| 4102 | ); |
| 4103 | assert_eq!( |
| 4104 | send( |
| 4105 | &app, |
| 4106 | "GET", |
| 4107 | &format!("/exams/{exam_id}/result"), |
| 4108 | Some(&alice), |
| 4109 | None |
| 4110 | ) |
| 4111 | .await |
| 4112 | .status, |
| 4113 | StatusCode::NOT_FOUND |
| 4114 | ); |
| 4115 | assert_eq!( |
| 4116 | common::items( |
| 4117 | &send(&app, "GET", "/courses/me", Some(&alice), None) |
| 4118 | .await |
| 4119 | .body, |
| 4120 | ) |
| 4121 | .len(), |
| 4122 | 0 |
| 4123 | ); |
| 4124 | assert_eq!( |
| 4125 | send(&app, "GET", "/marks/me", Some(&alice), None) |
| 4126 | .await |
| 4127 | .body["courses"] |
| 4128 | .as_array() |
| 4129 | .unwrap() |
| 4130 | .len(), |
| 4131 | 0 |
| 4132 | ); |
| 4133 | } |
| 4134 | |
| 4135 | /// Same guarantee as attendance/grading: concurrent enrolls of the same pair |
| 4136 | /// converge on one row instead of racing the unique index into a 500. |
| 4137 | #[tokio::test] |
| 4138 | async fn concurrent_enrollments_never_collide() { |
| 4139 | let (app, db) = app_and_db().await; |
| 4140 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 4141 | let alice = login(&app, "alice").await; |
| 4142 | let alice_id = me_id(&app, &alice).await; |
| 4143 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 4144 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 4145 | |
| 4146 | let mut handles = Vec::new(); |
| 4147 | for _ in 0..24 { |
| 4148 | let app = app.clone(); |
| 4149 | let teacher = teacher.clone(); |
| 4150 | let uri = format!("/instances/{}/enrollments", t.instance); |
| 4151 | let body = json!({ "user_id": alice_id }); |
| 4152 | handles.push(tokio::spawn(async move { |
| 4153 | send(&app, "POST", &uri, Some(&teacher), Some(body)) |
| 4154 | .await |
| 4155 | .status |
| 4156 | })); |
| 4157 | } |
| 4158 | for h in handles { |
| 4159 | assert_eq!( |
| 4160 | h.await.unwrap(), |
| 4161 | StatusCode::OK, |
| 4162 | "concurrent enroll must not fail" |
| 4163 | ); |
| 4164 | } |
| 4165 | |
| 4166 | let roster = send( |
| 4167 | &app, |
| 4168 | "GET", |
| 4169 | &format!("/instances/{}/enrollments", t.instance), |
| 4170 | Some(&teacher), |
| 4171 | None, |
| 4172 | ) |
| 4173 | .await; |
| 4174 | assert_eq!( |
| 4175 | common::items(&roster.body).len(), |
| 4176 | 1, |
| 4177 | "upsert keeps a single row" |
| 4178 | ); |
| 4179 | } |
| 4180 | |
| 4181 | // --- roles / RBAC -------------------------------------------------------- |
| 4182 | |
| 4183 | #[tokio::test] |
| 4184 | async fn students_cannot_create_events() { |
| 4185 | let app = mem_app().await; |
| 4186 | let ali = login(&app, "ali").await; // default role: student |
| 4187 | let res = send( |
| 4188 | &app, |
| 4189 | "POST", |
| 4190 | "/events", |
| 4191 | Some(&ali), |
| 4192 | Some(json!({ "title": "class" })), |
| 4193 | ) |
| 4194 | .await; |
| 4195 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 4196 | } |
| 4197 | |
| 4198 | #[tokio::test] |
| 4199 | async fn students_never_mark_attendance() { |
| 4200 | let (app, db) = app_and_db().await; |
| 4201 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 4202 | let alice = login(&app, "alice").await; // student |
| 4203 | let bob = login(&app, "bob").await; // student |
| 4204 | let bob_id = id_of(&send(&app, "GET", "/auth/me", Some(&bob), None).await.body); |
| 4205 | |
| 4206 | let ev = id_of( |
| 4207 | &send( |
| 4208 | &app, |
| 4209 | "POST", |
| 4210 | "/events", |
| 4211 | Some(&teacher), |
| 4212 | Some(json!({ "title": "class" })), |
| 4213 | ) |
| 4214 | .await |
| 4215 | .body, |
| 4216 | ); |
| 4217 | |
| 4218 | // Taking attendance is teacher+: a student cannot mark even themselves… |
| 4219 | assert_eq!( |
| 4220 | send( |
| 4221 | &app, |
| 4222 | "POST", |
| 4223 | &format!("/events/{ev}/attendance"), |
| 4224 | Some(&alice), |
| 4225 | Some(json!({"status":"present"})) |
| 4226 | ) |
| 4227 | .await |
| 4228 | .status, |
| 4229 | StatusCode::FORBIDDEN |
| 4230 | ); |
| 4231 | // …let alone someone else. |
| 4232 | assert_eq!( |
| 4233 | send( |
| 4234 | &app, |
| 4235 | "POST", |
| 4236 | &format!("/events/{ev}/attendance"), |
| 4237 | Some(&alice), |
| 4238 | Some(json!({"status":"present","user_id":bob_id})) |
| 4239 | ) |
| 4240 | .await |
| 4241 | .status, |
| 4242 | StatusCode::FORBIDDEN |
| 4243 | ); |
| 4244 | // And cannot remove attendance rows or read the roster report. |
| 4245 | assert_eq!( |
| 4246 | send( |
| 4247 | &app, |
| 4248 | "DELETE", |
| 4249 | &format!("/events/{ev}/attendance/{bob_id}"), |
| 4250 | Some(&alice), |
| 4251 | None |
| 4252 | ) |
| 4253 | .await |
| 4254 | .status, |
| 4255 | StatusCode::FORBIDDEN |
| 4256 | ); |
| 4257 | assert_eq!( |
| 4258 | send( |
| 4259 | &app, |
| 4260 | "GET", |
| 4261 | &format!("/events/{ev}/roster"), |
| 4262 | Some(&alice), |
| 4263 | None |
| 4264 | ) |
| 4265 | .await |
| 4266 | .status, |
| 4267 | StatusCode::FORBIDDEN |
| 4268 | ); |
| 4269 | } |
| 4270 | |
| 4271 | /// Registration seats follow the placement rule — teachers seat students and |
| 4272 | /// themselves, never other staff; students never touch the endpoints — and a |
| 4273 | /// repeat register is a no-op on the same single row. Deleting the event |
| 4274 | /// removes its signup rows with it. |
| 4275 | #[tokio::test] |
| 4276 | async fn event_registration_follows_placement_rules() { |
| 4277 | let (app, db) = app_and_db().await; |
| 4278 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 4279 | let deniz = login_as(&app, &db, "deniz", "teacher").await; |
| 4280 | let veli = login(&app, "veli").await; // student |
| 4281 | let veli_id = me_id(&app, &veli).await; |
| 4282 | let ali_id = me_id(&app, &ali).await; |
| 4283 | let deniz_id = me_id(&app, &deniz).await; |
| 4284 | |
| 4285 | let res = send( |
| 4286 | &app, |
| 4287 | "POST", |
| 4288 | "/events", |
| 4289 | Some(&ali), |
| 4290 | Some(json!({ "title": "seminar", "audience": { "kind": "registration" } })), |
| 4291 | ) |
| 4292 | .await; |
| 4293 | assert_eq!(res.status, StatusCode::CREATED); |
| 4294 | let ev = id_of(&res.body); |
| 4295 | let register_uri = format!("/events/{ev}/register"); |
| 4296 | |
| 4297 | // Students can't register — not even themselves. |
| 4298 | let res = send(&app, "POST", ®ister_uri, Some(&veli), Some(json!({}))).await; |
| 4299 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 4300 | |
| 4301 | // A teacher seats a student; the row names who placed whom. |
| 4302 | let res = send( |
| 4303 | &app, |
| 4304 | "POST", |
| 4305 | ®ister_uri, |
| 4306 | Some(&ali), |
| 4307 | Some(json!({ "user_id": veli_id })), |
| 4308 | ) |
| 4309 | .await; |
| 4310 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 4311 | assert_eq!(res.body["user"]["id"], veli_id); |
| 4312 | assert_eq!(res.body["registered_by"]["id"], ali_id); |
| 4313 | |
| 4314 | // Registering the same student again is a no-op on the same seat. |
| 4315 | let res = send( |
| 4316 | &app, |
| 4317 | "POST", |
| 4318 | ®ister_uri, |
| 4319 | Some(&deniz), |
| 4320 | Some(json!({ "user_id": veli_id })), |
| 4321 | ) |
| 4322 | .await; |
| 4323 | assert_eq!(res.status, StatusCode::OK); |
| 4324 | let roster = send( |
| 4325 | &app, |
| 4326 | "GET", |
| 4327 | &format!("/events/{ev}/roster"), |
| 4328 | Some(&ali), |
| 4329 | None, |
| 4330 | ) |
| 4331 | .await; |
| 4332 | assert_eq!(common::total(&roster.body), 1, "upsert keeps a single seat"); |
| 4333 | |
| 4334 | // A teacher takes their own seat by omitting the target… |
| 4335 | let res = send(&app, "POST", ®ister_uri, Some(&ali), Some(json!({}))).await; |
| 4336 | assert_eq!(res.status, StatusCode::OK); |
| 4337 | // …but never seats another staff member, and ghosts don't register. |
| 4338 | let res = send( |
| 4339 | &app, |
| 4340 | "POST", |
| 4341 | ®ister_uri, |
| 4342 | Some(&ali), |
| 4343 | Some(json!({ "user_id": deniz_id })), |
| 4344 | ) |
| 4345 | .await; |
| 4346 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 4347 | let res = send( |
| 4348 | &app, |
| 4349 | "POST", |
| 4350 | ®ister_uri, |
| 4351 | Some(&ali), |
| 4352 | Some(json!({ "user_id": "ghost" })), |
| 4353 | ) |
| 4354 | .await; |
| 4355 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 4356 | |
| 4357 | // Non-registration events refuse the endpoint outright. |
| 4358 | let school = send( |
| 4359 | &app, |
| 4360 | "POST", |
| 4361 | "/events", |
| 4362 | Some(&ali), |
| 4363 | Some(json!({ "title": "assembly" })), |
| 4364 | ) |
| 4365 | .await; |
| 4366 | let res = send( |
| 4367 | &app, |
| 4368 | "POST", |
| 4369 | &format!("/events/{}/register", id_of(&school.body)), |
| 4370 | Some(&ali), |
| 4371 | Some(json!({})), |
| 4372 | ) |
| 4373 | .await; |
| 4374 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 4375 | |
| 4376 | // Unregistering mirrors the rule: students never, staff seats are their |
| 4377 | // own, students' seats are anyone's (teacher+) to free. |
| 4378 | let res = send( |
| 4379 | &app, |
| 4380 | "DELETE", |
| 4381 | &format!("{register_uri}/{ali_id}"), |
| 4382 | Some(&veli), |
| 4383 | None, |
| 4384 | ) |
| 4385 | .await; |
| 4386 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 4387 | let res = send( |
| 4388 | &app, |
| 4389 | "DELETE", |
| 4390 | &format!("{register_uri}/{ali_id}"), |
| 4391 | Some(&deniz), |
| 4392 | None, |
| 4393 | ) |
| 4394 | .await; |
| 4395 | assert_eq!( |
| 4396 | res.status, |
| 4397 | StatusCode::FORBIDDEN, |
| 4398 | "staff seat is not deniz's" |
| 4399 | ); |
| 4400 | let res = send( |
| 4401 | &app, |
| 4402 | "DELETE", |
| 4403 | &format!("{register_uri}/{veli_id}"), |
| 4404 | Some(&deniz), |
| 4405 | None, |
| 4406 | ) |
| 4407 | .await; |
| 4408 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 4409 | let res = send( |
| 4410 | &app, |
| 4411 | "DELETE", |
| 4412 | &format!("{register_uri}/{veli_id}"), |
| 4413 | Some(&deniz), |
| 4414 | None, |
| 4415 | ) |
| 4416 | .await; |
| 4417 | assert_eq!(res.status, StatusCode::NOT_FOUND, "seat already freed"); |
| 4418 | |
| 4419 | // Deleting the event cascades its signup rows away. |
| 4420 | let res = send(&app, "DELETE", &format!("/events/{ev}"), Some(&ali), None).await; |
| 4421 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 4422 | let left: i64 = sqlx::query_scalar("SELECT count(*) FROM registration") |
| 4423 | .fetch_one(&db) |
| 4424 | .await |
| 4425 | .expect("registration count"); |
| 4426 | assert_eq!(left, 0, "event delete leaves no seats behind"); |
| 4427 | } |
| 4428 | |
| 4429 | /// A capacity caps live seats, not history: re-registering never double-counts, |
| 4430 | /// freeing a seat reopens it, and shrinking the cap below the current count |
| 4431 | /// only blocks new seats. |
| 4432 | #[tokio::test] |
| 4433 | async fn event_registration_capacity_caps_seats() { |
| 4434 | let (app, db) = app_and_db().await; |
| 4435 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 4436 | let veli = login(&app, "veli").await; |
| 4437 | let mina = login(&app, "mina").await; |
| 4438 | let veli_id = me_id(&app, &veli).await; |
| 4439 | let mina_id = me_id(&app, &mina).await; |
| 4440 | |
| 4441 | let res = send( |
| 4442 | &app, |
| 4443 | "POST", |
| 4444 | "/events", |
| 4445 | Some(&ali), |
| 4446 | Some(json!({ "title": "workshop", |
| 4447 | "audience": { "kind": "registration", "capacity": 1 } })), |
| 4448 | ) |
| 4449 | .await; |
| 4450 | let ev = id_of(&res.body); |
| 4451 | let register_uri = format!("/events/{ev}/register"); |
| 4452 | let register = |user: String| { |
| 4453 | let app = &app; |
| 4454 | let ali = &ali; |
| 4455 | let uri = ®ister_uri; |
| 4456 | async move { |
| 4457 | send( |
| 4458 | app, |
| 4459 | "POST", |
| 4460 | uri, |
| 4461 | Some(ali), |
| 4462 | Some(json!({ "user_id": user })), |
| 4463 | ) |
| 4464 | .await |
| 4465 | .status |
| 4466 | } |
| 4467 | }; |
| 4468 | |
| 4469 | assert_eq!(register(veli_id.clone()).await, StatusCode::OK); |
| 4470 | assert_eq!( |
| 4471 | register(mina_id.clone()).await, |
| 4472 | StatusCode::CONFLICT, |
| 4473 | "full" |
| 4474 | ); |
| 4475 | assert_eq!( |
| 4476 | register(veli_id.clone()).await, |
| 4477 | StatusCode::OK, |
| 4478 | "re-register of a seated user never counts against the cap" |
| 4479 | ); |
| 4480 | |
| 4481 | // Freeing the seat reopens the list. |
| 4482 | let res = send( |
| 4483 | &app, |
| 4484 | "DELETE", |
| 4485 | &format!("{register_uri}/{veli_id}"), |
| 4486 | Some(&ali), |
| 4487 | None, |
| 4488 | ) |
| 4489 | .await; |
| 4490 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 4491 | assert_eq!(register(mina_id.clone()).await, StatusCode::OK); |
| 4492 | |
| 4493 | // Shrinking the cap under the current count keeps the seats and only |
| 4494 | // refuses growth. |
| 4495 | assert_eq!( |
| 4496 | send( |
| 4497 | &app, |
| 4498 | "PATCH", |
| 4499 | &format!("/events/{ev}"), |
| 4500 | Some(&ali), |
| 4501 | Some(json!({ "audience": { "kind": "registration", "capacity": 2 } })), |
| 4502 | ) |
| 4503 | .await |
| 4504 | .status, |
| 4505 | StatusCode::OK |
| 4506 | ); |
| 4507 | assert_eq!(register(veli_id.clone()).await, StatusCode::OK); |
| 4508 | assert_eq!( |
| 4509 | send( |
| 4510 | &app, |
| 4511 | "PATCH", |
| 4512 | &format!("/events/{ev}"), |
| 4513 | Some(&ali), |
| 4514 | Some(json!({ "audience": { "kind": "registration", "capacity": 1 } })), |
| 4515 | ) |
| 4516 | .await |
| 4517 | .status, |
| 4518 | StatusCode::OK |
| 4519 | ); |
| 4520 | let roster = send( |
| 4521 | &app, |
| 4522 | "GET", |
| 4523 | &format!("/events/{ev}/roster"), |
| 4524 | Some(&ali), |
| 4525 | None, |
| 4526 | ) |
| 4527 | .await; |
| 4528 | assert_eq!( |
| 4529 | common::total(&roster.body), |
| 4530 | 2, |
| 4531 | "shrink keeps existing seats" |
| 4532 | ); |
| 4533 | } |
| 4534 | |
| 4535 | /// Regression: re-registering an already-seated student used to be an UPSERT |
| 4536 | /// that silently rewrote `registered_by` to the second caller. The documented |
| 4537 | /// contract is a no-op — the seat and its audit trail come back unchanged. |
| 4538 | #[tokio::test] |
| 4539 | async fn re_registering_returns_the_seat_untouched() { |
| 4540 | let (app, db) = app_and_db().await; |
| 4541 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 4542 | let deniz = login_as(&app, &db, "deniz", "teacher").await; |
| 4543 | let veli = login(&app, "veli").await; |
| 4544 | let veli_id = me_id(&app, &veli).await; |
| 4545 | let ali_id = me_id(&app, &ali).await; |
| 4546 | |
| 4547 | let res = send( |
| 4548 | &app, |
| 4549 | "POST", |
| 4550 | "/events", |
| 4551 | Some(&ali), |
| 4552 | Some(json!({ "title": "seminar", "audience": { "kind": "registration" } })), |
| 4553 | ) |
| 4554 | .await; |
| 4555 | let uri = format!("/events/{}/register", id_of(&res.body)); |
| 4556 | |
| 4557 | let first = send( |
| 4558 | &app, |
| 4559 | "POST", |
| 4560 | &uri, |
| 4561 | Some(&ali), |
| 4562 | Some(json!({ "user_id": veli_id })), |
| 4563 | ) |
| 4564 | .await; |
| 4565 | assert_eq!(first.status, StatusCode::OK); |
| 4566 | assert_eq!(first.body["registered_by"]["id"], ali_id); |
| 4567 | |
| 4568 | let second = send( |
| 4569 | &app, |
| 4570 | "POST", |
| 4571 | &uri, |
| 4572 | Some(&deniz), |
| 4573 | Some(json!({ "user_id": veli_id })), |
| 4574 | ) |
| 4575 | .await; |
| 4576 | assert_eq!(second.status, StatusCode::OK); |
| 4577 | assert_eq!( |
| 4578 | second.body["registered_by"]["id"], ali_id, |
| 4579 | "re-registering must not rewrite who placed the student" |
| 4580 | ); |
| 4581 | // Regression: the response used to resolve people only from {target, |
| 4582 | // caller}, so the original registrar degraded to a bare id username. |
| 4583 | assert_eq!( |
| 4584 | second.body["registered_by"]["username"], "ali", |
| 4585 | "the original registrar must resolve to a person, not a bare id" |
| 4586 | ); |
| 4587 | assert_eq!(second.body["user"]["username"], "veli"); |
| 4588 | } |
| 4589 | |
| 4590 | /// Regression: the capacity check used to run inside a `BEGIN…COMMIT` whose |
| 4591 | /// cross-record `count()` the old engine did not conflict-check against a |
| 4592 | /// concurrent insert (write-skew) — two racing placements both saw the last |
| 4593 | /// seat free and a capacity-1 event admitted 2. The register path now |
| 4594 | /// serializes the check-then-write, so exactly one wins and the loser gets |
| 4595 | /// the same 409 as a sequential over-fill. |
| 4596 | #[tokio::test] |
| 4597 | async fn concurrent_placements_never_exceed_capacity() { |
| 4598 | let (app, db) = app_and_db().await; |
| 4599 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 4600 | let veli = login(&app, "veli").await; |
| 4601 | let ayse = login(&app, "ayse").await; |
| 4602 | let veli_id = me_id(&app, &veli).await; |
| 4603 | let ayse_id = me_id(&app, &ayse).await; |
| 4604 | |
| 4605 | let res = send( |
| 4606 | &app, |
| 4607 | "POST", |
| 4608 | "/events", |
| 4609 | Some(&ali), |
| 4610 | Some(json!({ "title": "trip", "audience": { "kind": "registration", "capacity": 1 } })), |
| 4611 | ) |
| 4612 | .await; |
| 4613 | let ev = id_of(&res.body); |
| 4614 | let uri = format!("/events/{ev}/register"); |
| 4615 | |
| 4616 | for _round in 0..10 { |
| 4617 | for uid in [&veli_id, &ayse_id] { |
| 4618 | let _ = send(&app, "DELETE", &format!("{uri}/{uid}"), Some(&ali), None).await; |
| 4619 | } |
| 4620 | let (a, b) = tokio::join!( |
| 4621 | send( |
| 4622 | &app, |
| 4623 | "POST", |
| 4624 | &uri, |
| 4625 | Some(&ali), |
| 4626 | Some(json!({ "user_id": veli_id })), |
| 4627 | ), |
| 4628 | send( |
| 4629 | &app, |
| 4630 | "POST", |
| 4631 | &uri, |
| 4632 | Some(&ali), |
| 4633 | Some(json!({ "user_id": ayse_id })), |
| 4634 | ), |
| 4635 | ); |
| 4636 | for status in [a.status, b.status] { |
| 4637 | assert!( |
| 4638 | status == StatusCode::OK || status == StatusCode::CONFLICT, |
| 4639 | "a lost capacity race must be a 409, got {status}" |
| 4640 | ); |
| 4641 | } |
| 4642 | let roster = send( |
| 4643 | &app, |
| 4644 | "GET", |
| 4645 | &format!("/events/{ev}/roster"), |
| 4646 | Some(&ali), |
| 4647 | None, |
| 4648 | ) |
| 4649 | .await; |
| 4650 | assert!( |
| 4651 | common::total(&roster.body) <= 1, |
| 4652 | "capacity 1 must never over-admit, roster={}", |
| 4653 | roster.body |
| 4654 | ); |
| 4655 | } |
| 4656 | } |
| 4657 | |
| 4658 | /// The two reference counters a subject carries — the whole basis of its |
| 4659 | /// delete guard — must equal the rows that actually point at it, through every |
| 4660 | /// writer: create, re-tag, delete, and the exam cascade. Nothing recomputes |
| 4661 | /// them, so a single missed decrement makes a subject undeletable forever. |
| 4662 | /// |
| 4663 | /// This bites on the halves the HTTP status alone cannot see. Drop the |
| 4664 | /// release of the *old* subject from either re-tag and the counter drifts up: |
| 4665 | /// the last delete below comes back 409 instead of 204. |
| 4666 | #[tokio::test] |
| 4667 | async fn subject_reference_counts_track_every_writer() { |
| 4668 | let (app, db) = app_and_db().await; |
| 4669 | let teacher = login_as(&app, &db, "refc_t", "teacher").await; |
| 4670 | let mudur = login_as(&app, &db, "refc_m", "manager").await; |
| 4671 | let t = taught_under(&app, &mudur, &teacher, "physics").await; |
| 4672 | let from = create_subject(&app, &teacher, &t.course, "optics").await; |
| 4673 | let to = create_subject(&app, &teacher, &t.course, "waves").await; |
| 4674 | select_instance_subject(&app, &teacher, &t.instance, &from).await; |
| 4675 | select_instance_subject(&app, &teacher, &t.instance, &to).await; |
| 4676 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "yazili").await; |
| 4677 | let due = Timestamp::now().as_millis() + 86_400_000; |
| 4678 | |
| 4679 | let counts = async |subject: &str| -> (i64, i64) { |
| 4680 | let pair: (i64, i64) = |
| 4681 | sqlx::query_as("SELECT exam_question_count, homework_count FROM subject WHERE id = $1") |
| 4682 | .bind(Uuid::parse_str(subject).expect("subject id")) |
| 4683 | .fetch_one(&db) |
| 4684 | .await |
| 4685 | .expect("counter read"); |
| 4686 | pair |
| 4687 | }; |
| 4688 | |
| 4689 | let question = create_question( |
| 4690 | &app, |
| 4691 | &teacher, |
| 4692 | &exam, |
| 4693 | &from, |
| 4694 | json!({ "text": "How fast?", "kind": "text", "points": 10 }), |
| 4695 | ) |
| 4696 | .await; |
| 4697 | let cascaded = create_question( |
| 4698 | &app, |
| 4699 | &teacher, |
| 4700 | &exam, |
| 4701 | &from, |
| 4702 | json!({ "text": "How bright?", "kind": "text", "points": 10 }), |
| 4703 | ) |
| 4704 | .await; |
| 4705 | let homework = create_homework(&app, &teacher, &t.instance, &from, "lenses", due).await; |
| 4706 | assert_eq!(counts(&from).await, (2, 1), "two questions and a homework"); |
| 4707 | assert_eq!(counts(&to).await, (0, 0), "the spare subject holds nothing"); |
| 4708 | |
| 4709 | // A re-tag moves a reference: both ends must move, not just the new one. |
| 4710 | let res = send( |
| 4711 | &app, |
| 4712 | "PATCH", |
| 4713 | &format!("/exams/{exam}/questions/{question}"), |
| 4714 | Some(&teacher), |
| 4715 | Some(json!({ "subject_id": to })), |
| 4716 | ) |
| 4717 | .await; |
| 4718 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 4719 | let res = send( |
| 4720 | &app, |
| 4721 | "PATCH", |
| 4722 | &format!("/homework/{homework}"), |
| 4723 | Some(&teacher), |
| 4724 | Some(json!({ "subject_id": to })), |
| 4725 | ) |
| 4726 | .await; |
| 4727 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 4728 | assert_eq!(counts(&from).await, (1, 0), "both re-tags must have left"); |
| 4729 | assert_eq!(counts(&to).await, (1, 1), "and both must have arrived"); |
| 4730 | |
| 4731 | // A re-tag back to where it already is moves nothing. |
| 4732 | let res = send( |
| 4733 | &app, |
| 4734 | "PATCH", |
| 4735 | &format!("/homework/{homework}"), |
| 4736 | Some(&teacher), |
| 4737 | Some(json!({ "subject_id": to })), |
| 4738 | ) |
| 4739 | .await; |
| 4740 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 4741 | assert_eq!(counts(&to).await, (1, 1), "a no-op re-tag is a no-op"); |
| 4742 | |
| 4743 | // Deleting the referencing rows gives every reference back — including the |
| 4744 | // question the *exam* cascade takes with it, which the row delete never |
| 4745 | // sees. |
| 4746 | let res = send( |
| 4747 | &app, |
| 4748 | "DELETE", |
| 4749 | &format!("/homework/{homework}"), |
| 4750 | Some(&teacher), |
| 4751 | None, |
| 4752 | ) |
| 4753 | .await; |
| 4754 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 4755 | let res = send( |
| 4756 | &app, |
| 4757 | "DELETE", |
| 4758 | &format!("/exams/{exam}/questions/{question}"), |
| 4759 | Some(&teacher), |
| 4760 | None, |
| 4761 | ) |
| 4762 | .await; |
| 4763 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 4764 | assert_eq!(counts(&to).await, (0, 0), "the new subject is free again"); |
| 4765 | assert_eq!( |
| 4766 | counts(&from).await, |
| 4767 | (1, 0), |
| 4768 | "the cascaded question still holds" |
| 4769 | ); |
| 4770 | assert!(!cascaded.is_empty()); |
| 4771 | |
| 4772 | let res = send( |
| 4773 | &app, |
| 4774 | "DELETE", |
| 4775 | &format!("/exams/{exam}"), |
| 4776 | Some(&teacher), |
| 4777 | None, |
| 4778 | ) |
| 4779 | .await; |
| 4780 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 4781 | assert_eq!(counts(&from).await, (0, 0), "the exam cascade gave it back"); |
| 4782 | |
| 4783 | for subject in [&from, &to] { |
| 4784 | let res = send( |
| 4785 | &app, |
| 4786 | "DELETE", |
| 4787 | &format!("/subjects/{subject}"), |
| 4788 | Some(&teacher), |
| 4789 | None, |
| 4790 | ) |
| 4791 | .await; |
| 4792 | assert_eq!( |
| 4793 | res.status, |
| 4794 | StatusCode::NO_CONTENT, |
| 4795 | "an unreferenced subject must delete: {}", |
| 4796 | res.body |
| 4797 | ); |
| 4798 | } |
| 4799 | } |
| 4800 | |
| 4801 | /// A subject delete racing question creates on the same subject. Exactly one |
| 4802 | /// outcome is legal, and it is decided by the delete's own `WHERE`: either the |
| 4803 | /// subject is gone and *no* question points at it, or it survived and its |
| 4804 | /// counter equals the questions that landed. Stored state is the only witness — |
| 4805 | /// the embedded engine can tell two racers they both won, so the statuses prove |
| 4806 | /// nothing. |
| 4807 | /// |
| 4808 | /// The count-then-delete this replaced fails here: it reads "no questions", |
| 4809 | /// then deletes while a create that already passed its own subject check lands |
| 4810 | /// its row on the corpse. |
| 4811 | #[tokio::test] |
| 4812 | async fn a_subject_delete_racing_question_creates_leaves_no_orphan() { |
| 4813 | let (app, db) = app_and_db().await; |
| 4814 | let teacher = login_as(&app, &db, "race_t", "teacher").await; |
| 4815 | let mudur = login_as(&app, &db, "race_m", "manager").await; |
| 4816 | let t = taught_under(&app, &mudur, &teacher, "chemistry").await; |
| 4817 | let subject = create_subject(&app, &teacher, &t.course, "bonds").await; |
| 4818 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "quiz", "yazili").await; |
| 4819 | // One question already tagged before the race starts, so the delete is |
| 4820 | // never legal: whichever way the interleaving falls, it must be refused. |
| 4821 | create_question( |
| 4822 | &app, |
| 4823 | &teacher, |
| 4824 | &exam, |
| 4825 | &subject, |
| 4826 | json!({ "text": "first", "kind": "text", "points": 1 }), |
| 4827 | ) |
| 4828 | .await; |
| 4829 | |
| 4830 | let mut handles = Vec::new(); |
| 4831 | for i in 0..8 { |
| 4832 | let (app, teacher, exam, subject) = |
| 4833 | (app.clone(), teacher.clone(), exam.clone(), subject.clone()); |
| 4834 | handles.push(tokio::spawn(async move { |
| 4835 | let body = json!({ |
| 4836 | "text": format!("q{i}"), |
| 4837 | "kind": "text", |
| 4838 | "points": 1, |
| 4839 | "subject_id": subject, |
| 4840 | }); |
| 4841 | send( |
| 4842 | &app, |
| 4843 | "POST", |
| 4844 | &format!("/exams/{exam}/questions"), |
| 4845 | Some(&teacher), |
| 4846 | Some(body), |
| 4847 | ) |
| 4848 | .await |
| 4849 | .status |
| 4850 | })); |
| 4851 | } |
| 4852 | let killer = { |
| 4853 | let (app, teacher, subject) = (app.clone(), teacher.clone(), subject.clone()); |
| 4854 | tokio::spawn(async move { |
| 4855 | send( |
| 4856 | &app, |
| 4857 | "DELETE", |
| 4858 | &format!("/subjects/{subject}"), |
| 4859 | Some(&teacher), |
| 4860 | None, |
| 4861 | ) |
| 4862 | .await |
| 4863 | .status |
| 4864 | }) |
| 4865 | }; |
| 4866 | for handle in handles { |
| 4867 | let status = handle.await.unwrap(); |
| 4868 | assert!( |
| 4869 | status == StatusCode::CREATED || status == StatusCode::BAD_REQUEST, |
| 4870 | "a create either lands or is told the subject is gone, got {status}" |
| 4871 | ); |
| 4872 | } |
| 4873 | let killed = killer.await.unwrap(); |
| 4874 | |
| 4875 | let counter: i64 = sqlx::query_scalar("SELECT exam_question_count FROM subject WHERE id = $1") |
| 4876 | .bind(Uuid::parse_str(&subject).expect("subject id")) |
| 4877 | .fetch_one(&db) |
| 4878 | .await |
| 4879 | .expect("counter read"); |
| 4880 | let landed: i64 = sqlx::query_scalar("SELECT count(*) FROM exam_question WHERE subject = $1") |
| 4881 | .bind(Uuid::parse_str(&subject).expect("subject id")) |
| 4882 | .fetch_one(&db) |
| 4883 | .await |
| 4884 | .expect("row read"); |
| 4885 | assert_eq!( |
| 4886 | killed, |
| 4887 | StatusCode::CONFLICT, |
| 4888 | "a subject a question already points at may never be deleted" |
| 4889 | ); |
| 4890 | assert_eq!( |
| 4891 | counter, landed, |
| 4892 | "the subject must survive with its counter equal to the rows it guards" |
| 4893 | ); |
| 4894 | } |
| 4895 | |
| 4896 | /// The signup list freezes the moment the event starts — both directions. |
| 4897 | /// (The create-time no-past grace lets a just-started event exist, which is |
| 4898 | /// exactly a closed list.) |
| 4899 | #[tokio::test] |
| 4900 | async fn event_registration_closes_at_start() { |
| 4901 | let (app, db) = app_and_db().await; |
| 4902 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 4903 | let veli = login(&app, "veli").await; |
| 4904 | let veli_id = me_id(&app, &veli).await; |
| 4905 | let now = Timestamp::now().as_millis(); |
| 4906 | |
| 4907 | // Started 30s ago: inside the scheduling grace, so creation passes — but |
| 4908 | // the list is already closed. |
| 4909 | let res = send( |
| 4910 | &app, |
| 4911 | "POST", |
| 4912 | "/events", |
| 4913 | Some(&ali), |
| 4914 | Some(json!({ "title": "underway", "starts_at": now - 30_000, |
| 4915 | "audience": { "kind": "registration" } })), |
| 4916 | ) |
| 4917 | .await; |
| 4918 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 4919 | let ev = id_of(&res.body); |
| 4920 | let res = send( |
| 4921 | &app, |
| 4922 | "POST", |
| 4923 | &format!("/events/{ev}/register"), |
| 4924 | Some(&ali), |
| 4925 | Some(json!({ "user_id": veli_id })), |
| 4926 | ) |
| 4927 | .await; |
| 4928 | assert_eq!(res.status, StatusCode::CONFLICT); |
| 4929 | let res = send( |
| 4930 | &app, |
| 4931 | "DELETE", |
| 4932 | &format!("/events/{ev}/register/{veli_id}"), |
| 4933 | Some(&ali), |
| 4934 | None, |
| 4935 | ) |
| 4936 | .await; |
| 4937 | assert_eq!(res.status, StatusCode::CONFLICT, "unregister freezes too"); |
| 4938 | |
| 4939 | // Regression: an ends_at-only event (a pure signup deadline) used to stay |
| 4940 | // open forever — the gate read starts_at alone. Ended 30s ago: inside the |
| 4941 | // creation grace, but the list is closed. |
| 4942 | let res = send( |
| 4943 | &app, |
| 4944 | "POST", |
| 4945 | "/events", |
| 4946 | Some(&ali), |
| 4947 | Some(json!({ "title": "deadline passed", "ends_at": now - 30_000, |
| 4948 | "audience": { "kind": "registration" } })), |
| 4949 | ) |
| 4950 | .await; |
| 4951 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 4952 | let ev = id_of(&res.body); |
| 4953 | let res = send( |
| 4954 | &app, |
| 4955 | "POST", |
| 4956 | &format!("/events/{ev}/register"), |
| 4957 | Some(&ali), |
| 4958 | Some(json!({ "user_id": veli_id })), |
| 4959 | ) |
| 4960 | .await; |
| 4961 | assert_eq!( |
| 4962 | res.status, |
| 4963 | StatusCode::CONFLICT, |
| 4964 | "an event whose end has passed takes no signups" |
| 4965 | ); |
| 4966 | |
| 4967 | // A future or timeless event keeps its list open — a future signup |
| 4968 | // deadline (ends_at only) included. |
| 4969 | for body in [ |
| 4970 | json!({ "title": "later", "starts_at": now + 3_600_000, |
| 4971 | "audience": { "kind": "registration" } }), |
| 4972 | json!({ "title": "deadline ahead", "ends_at": now + 3_600_000, |
| 4973 | "audience": { "kind": "registration" } }), |
| 4974 | json!({ "title": "whenever", "audience": { "kind": "registration" } }), |
| 4975 | ] { |
| 4976 | let res = send(&app, "POST", "/events", Some(&ali), Some(body)).await; |
| 4977 | let ev = id_of(&res.body); |
| 4978 | let res = send( |
| 4979 | &app, |
| 4980 | "POST", |
| 4981 | &format!("/events/{ev}/register"), |
| 4982 | Some(&ali), |
| 4983 | Some(json!({ "user_id": veli_id })), |
| 4984 | ) |
| 4985 | .await; |
| 4986 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 4987 | } |
| 4988 | } |
| 4989 | |
| 4990 | #[tokio::test] |
| 4991 | async fn event_management_follows_hierarchy() { |
| 4992 | let (app, db) = app_and_db().await; |
| 4993 | let owner = login_as(&app, &db, "owner", "teacher").await; |
| 4994 | let other = login_as(&app, &db, "other", "teacher").await; |
| 4995 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 4996 | |
| 4997 | let ev = id_of( |
| 4998 | &send( |
| 4999 | &app, |
| 5000 | "POST", |
| 5001 | "/events", |
| 5002 | Some(&owner), |
| 5003 | Some(json!({ "title": "orig" })), |
| 5004 | ) |
| 5005 | .await |
| 5006 | .body, |
| 5007 | ); |
| 5008 | |
| 5009 | // A different teacher (not the creator) cannot edit it. |
| 5010 | assert_eq!( |
| 5011 | send( |
| 5012 | &app, |
| 5013 | "PATCH", |
| 5014 | &format!("/events/{ev}"), |
| 5015 | Some(&other), |
| 5016 | Some(json!({"title":"hijack"})) |
| 5017 | ) |
| 5018 | .await |
| 5019 | .status, |
| 5020 | StatusCode::FORBIDDEN |
| 5021 | ); |
| 5022 | // A manager can edit anyone's event. |
| 5023 | let res = send( |
| 5024 | &app, |
| 5025 | "PATCH", |
| 5026 | &format!("/events/{ev}"), |
| 5027 | Some(&boss), |
| 5028 | Some(json!({"title":"by mgr"})), |
| 5029 | ) |
| 5030 | .await; |
| 5031 | assert_eq!(res.status, StatusCode::OK); |
| 5032 | assert_eq!(res.body["title"], "by mgr"); |
| 5033 | // The creator can still delete their own. |
| 5034 | assert_eq!( |
| 5035 | send(&app, "DELETE", &format!("/events/{ev}"), Some(&owner), None) |
| 5036 | .await |
| 5037 | .status, |
| 5038 | StatusCode::NO_CONTENT |
| 5039 | ); |
| 5040 | } |
| 5041 | |
| 5042 | #[tokio::test] |
| 5043 | async fn admin_manages_roles_with_guards() { |
| 5044 | let (app, db) = app_and_db().await; |
| 5045 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 5046 | let alice = login(&app, "alice").await; // student |
| 5047 | let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body); |
| 5048 | |
| 5049 | // Non-admins cannot reach the role endpoints. |
| 5050 | assert_eq!( |
| 5051 | send(&app, "GET", "/users", Some(&alice), None).await.status, |
| 5052 | StatusCode::FORBIDDEN |
| 5053 | ); |
| 5054 | assert_eq!( |
| 5055 | send( |
| 5056 | &app, |
| 5057 | "PATCH", |
| 5058 | &format!("/users/{alice_id}/role"), |
| 5059 | Some(&alice), |
| 5060 | Some(json!({"role":"teacher"})) |
| 5061 | ) |
| 5062 | .await |
| 5063 | .status, |
| 5064 | StatusCode::FORBIDDEN |
| 5065 | ); |
| 5066 | |
| 5067 | // Admin lists users (at least admin + alice). |
| 5068 | let list = send(&app, "GET", "/users", Some(&admin), None).await; |
| 5069 | assert_eq!(list.status, StatusCode::OK); |
| 5070 | assert!(common::items(&list.body).len() >= 2); |
| 5071 | |
| 5072 | // Admin promotes alice to teacher; the change is reflected in the response... |
| 5073 | let promoted = send( |
| 5074 | &app, |
| 5075 | "PATCH", |
| 5076 | &format!("/users/{alice_id}/role"), |
| 5077 | Some(&admin), |
| 5078 | Some(json!({"role":"teacher"})), |
| 5079 | ) |
| 5080 | .await; |
| 5081 | assert_eq!(promoted.status, StatusCode::OK); |
| 5082 | assert_eq!(promoted.body["role"], "teacher"); |
| 5083 | // ...and takes effect immediately: alice can now create events. |
| 5084 | assert_eq!( |
| 5085 | send( |
| 5086 | &app, |
| 5087 | "POST", |
| 5088 | "/events", |
| 5089 | Some(&alice), |
| 5090 | Some(json!({ "title": "now allowed" })) |
| 5091 | ) |
| 5092 | .await |
| 5093 | .status, |
| 5094 | StatusCode::CREATED |
| 5095 | ); |
| 5096 | |
| 5097 | // Unknown role value -> 400. |
| 5098 | assert_eq!( |
| 5099 | send( |
| 5100 | &app, |
| 5101 | "PATCH", |
| 5102 | &format!("/users/{alice_id}/role"), |
| 5103 | Some(&admin), |
| 5104 | Some(json!({"role":"wizard"})) |
| 5105 | ) |
| 5106 | .await |
| 5107 | .status, |
| 5108 | StatusCode::BAD_REQUEST |
| 5109 | ); |
| 5110 | // Missing user -> 404. |
| 5111 | assert_eq!( |
| 5112 | send( |
| 5113 | &app, |
| 5114 | "PATCH", |
| 5115 | "/users/does-not-exist/role", |
| 5116 | Some(&admin), |
| 5117 | Some(json!({"role":"teacher"})) |
| 5118 | ) |
| 5119 | .await |
| 5120 | .status, |
| 5121 | StatusCode::NOT_FOUND |
| 5122 | ); |
| 5123 | // An admin cannot change their own role (anti-lockout guard). |
| 5124 | let admin_id = id_of(&send(&app, "GET", "/auth/me", Some(&admin), None).await.body); |
| 5125 | assert_eq!( |
| 5126 | send( |
| 5127 | &app, |
| 5128 | "PATCH", |
| 5129 | &format!("/users/{admin_id}/role"), |
| 5130 | Some(&admin), |
| 5131 | Some(json!({"role":"student"})) |
| 5132 | ) |
| 5133 | .await |
| 5134 | .status, |
| 5135 | StatusCode::FORBIDDEN |
| 5136 | ); |
| 5137 | } |
| 5138 | |
| 5139 | /// `POST /users` is the school-office path: an admin mints a school account |
| 5140 | /// outright, born with the role named (default `student`), with the username |
| 5141 | /// a global person credential exactly as at `POST /auth/register`. A username |
| 5142 | /// taken in this school, or an existing person under a different password, is |
| 5143 | /// a `409`; the reserved staff-reading names are a `400`. |
| 5144 | #[tokio::test] |
| 5145 | async fn admin_creates_a_user() { |
| 5146 | let (app, db) = app_and_db().await; |
| 5147 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 5148 | |
| 5149 | // A student may not mint accounts. |
| 5150 | let student = login(&app, "kid").await; |
| 5151 | assert_eq!( |
| 5152 | send( |
| 5153 | &app, |
| 5154 | "POST", |
| 5155 | "/users", |
| 5156 | Some(&student), |
| 5157 | Some(json!({"username": "nope", "password": "secret1"})) |
| 5158 | ) |
| 5159 | .await |
| 5160 | .status, |
| 5161 | StatusCode::FORBIDDEN |
| 5162 | ); |
| 5163 | |
| 5164 | // The admin mints a teacher directly — the row is born with the role. |
| 5165 | let res = send( |
| 5166 | &app, |
| 5167 | "POST", |
| 5168 | "/users", |
| 5169 | Some(&admin), |
| 5170 | Some(json!({"username": "ayse", "password": "secret1", "role": "teacher"})), |
| 5171 | ) |
| 5172 | .await; |
| 5173 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 5174 | assert_eq!(res.body["username"], "ayse"); |
| 5175 | assert_eq!(res.body["role"], "teacher"); |
| 5176 | assert!( |
| 5177 | res.body["name"].is_null(), |
| 5178 | "a fresh account holds no profile" |
| 5179 | ); |
| 5180 | let ayse_id = id_of(&res.body); |
| 5181 | |
| 5182 | // The account is real: it logs in with the password the admin chose, and |
| 5183 | // that session carries the role. |
| 5184 | let login = send( |
| 5185 | &app, |
| 5186 | "POST", |
| 5187 | "/auth/login", |
| 5188 | None, |
| 5189 | Some(json!({"username": "ayse", "password": "secret1"})), |
| 5190 | ) |
| 5191 | .await; |
| 5192 | assert_eq!(login.status, StatusCode::OK, "{}", login.body); |
| 5193 | assert_eq!(login.body["role"], "teacher"); |
| 5194 | assert_eq!(login.body["id"], ayse_id); |
| 5195 | let ayse = login.cookie.expect("session cookie set on login"); |
| 5196 | let me = send(&app, "GET", "/auth/me", Some(&ayse), None).await; |
| 5197 | assert_eq!(me.status, StatusCode::OK, "{}", me.body); |
| 5198 | assert_eq!(me.body["role"], "teacher"); |
| 5199 | |
| 5200 | // Omitted role -> student. |
| 5201 | let res = send( |
| 5202 | &app, |
| 5203 | "POST", |
| 5204 | "/users", |
| 5205 | Some(&admin), |
| 5206 | Some(json!({"username": "veli", "password": "secret1"})), |
| 5207 | ) |
| 5208 | .await; |
| 5209 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 5210 | assert_eq!(res.body["role"], "student"); |
| 5211 | |
| 5212 | // A username already taken in this school is a 409. |
| 5213 | assert_eq!( |
| 5214 | send( |
| 5215 | &app, |
| 5216 | "POST", |
| 5217 | "/users", |
| 5218 | Some(&admin), |
| 5219 | Some(json!({"username": "ayse", "password": "secret1"})) |
| 5220 | ) |
| 5221 | .await |
| 5222 | .status, |
| 5223 | StatusCode::CONFLICT |
| 5224 | ); |
| 5225 | // The same name under a different password is a 409 too — the person |
| 5226 | // already stands under a credential this caller has not proven. |
| 5227 | assert_eq!( |
| 5228 | send( |
| 5229 | &app, |
| 5230 | "POST", |
| 5231 | "/users", |
| 5232 | Some(&admin), |
| 5233 | Some(json!({"username": "ayse", "password": "different1"})) |
| 5234 | ) |
| 5235 | .await |
| 5236 | .status, |
| 5237 | StatusCode::CONFLICT |
| 5238 | ); |
| 5239 | |
| 5240 | // Refused before anything is written: a reserved name, an unknown role, |
| 5241 | // and a password under the floor. |
| 5242 | for body in [ |
| 5243 | json!({"username": "root", "password": "secret1"}), |
| 5244 | json!({"username": "zey", "password": "secret1", "role": "wizard"}), |
| 5245 | json!({"username": "zey", "password": "x"}), |
| 5246 | ] { |
| 5247 | let res = send(&app, "POST", "/users", Some(&admin), Some(body.clone())).await; |
| 5248 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{body}: {}", res.body); |
| 5249 | } |
| 5250 | |
| 5251 | // The created student is really in the roster: the new teacher finds them. |
| 5252 | let found = send( |
| 5253 | &app, |
| 5254 | "GET", |
| 5255 | "/users/search?q=veli&role=student", |
| 5256 | Some(&ayse), |
| 5257 | None, |
| 5258 | ) |
| 5259 | .await; |
| 5260 | assert_eq!(found.status, StatusCode::OK, "{}", found.body); |
| 5261 | assert!( |
| 5262 | common::items(&found.body) |
| 5263 | .iter() |
| 5264 | .any(|item| item["username"] == "veli"), |
| 5265 | "the minted student is searchable: {}", |
| 5266 | found.body |
| 5267 | ); |
| 5268 | } |
| 5269 | |
| 5270 | /// `student_number` on the mint: a student may be born with one (stored |
| 5271 | /// trimmed), a duplicate in the same school is the partial unique index's |
| 5272 | /// refusal — a 409 carrying the `student_number_taken` code — and any |
| 5273 | /// non-student role refuses the field outright. |
| 5274 | #[tokio::test] |
| 5275 | async fn student_numbers_are_minted_uniquely_and_only_for_students() { |
| 5276 | let (app, db) = app_and_db().await; |
| 5277 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 5278 | |
| 5279 | // The number is stored trimmed, exactly like a username: the unique index |
| 5280 | // keys on the stored string, so padding must not mint a second number. |
| 5281 | let created = send( |
| 5282 | &app, |
| 5283 | "POST", |
| 5284 | "/users", |
| 5285 | Some(&admin), |
| 5286 | Some(json!({ |
| 5287 | "username": "numarali", |
| 5288 | "password": "secret1", |
| 5289 | "student_number": " 1234 ", |
| 5290 | })), |
| 5291 | ) |
| 5292 | .await; |
| 5293 | assert_eq!(created.status, StatusCode::CREATED, "{}", created.body); |
| 5294 | assert_eq!(created.body["student_number"], "1234", "{}", created.body); |
| 5295 | let numbered_id = id_of(&created.body); |
| 5296 | |
| 5297 | // Read back off the row, not off the create echo. |
| 5298 | let one = send( |
| 5299 | &app, |
| 5300 | "GET", |
| 5301 | &format!("/users/{numbered_id}"), |
| 5302 | Some(&admin), |
| 5303 | None, |
| 5304 | ) |
| 5305 | .await; |
| 5306 | assert_eq!(one.body["student_number"], "1234"); |
| 5307 | |
| 5308 | // A second student claiming the same number — padded or not — is the |
| 5309 | // index's refusal, and the body names the cause for a client that |
| 5310 | // branches on it. |
| 5311 | for duplicate in ["1234", "1234 "] { |
| 5312 | let res = send( |
| 5313 | &app, |
| 5314 | "POST", |
| 5315 | "/users", |
| 5316 | Some(&admin), |
| 5317 | Some(json!({ |
| 5318 | "username": "kopyaci", |
| 5319 | "password": "secret1", |
| 5320 | "student_number": duplicate, |
| 5321 | })), |
| 5322 | ) |
| 5323 | .await; |
| 5324 | assert_eq!( |
| 5325 | res.status, |
| 5326 | StatusCode::CONFLICT, |
| 5327 | "{duplicate}: {}", |
| 5328 | res.body |
| 5329 | ); |
| 5330 | assert_eq!(res.body["error"], "student number already taken"); |
| 5331 | assert_eq!(res.body["code"], "student_number_taken"); |
| 5332 | } |
| 5333 | // The refused mint wrote nothing: the username is still free. |
| 5334 | let retry = send( |
| 5335 | &app, |
| 5336 | "POST", |
| 5337 | "/users", |
| 5338 | Some(&admin), |
| 5339 | Some(json!({ "username": "kopyaci", "password": "secret1" })), |
| 5340 | ) |
| 5341 | .await; |
| 5342 | assert_eq!(retry.status, StatusCode::CREATED, "{}", retry.body); |
| 5343 | assert!( |
| 5344 | retry.body["student_number"].is_null(), |
| 5345 | "an omitted number is null: {}", |
| 5346 | retry.body |
| 5347 | ); |
| 5348 | |
| 5349 | // A non-student role may not be born with a number — refused before |
| 5350 | // anything is written, so the username stays free too. |
| 5351 | assert_eq!( |
| 5352 | send( |
| 5353 | &app, |
| 5354 | "POST", |
| 5355 | "/users", |
| 5356 | Some(&admin), |
| 5357 | Some(json!({ |
| 5358 | "username": "hoca", |
| 5359 | "password": "secret1", |
| 5360 | "role": "teacher", |
| 5361 | "student_number": "5678", |
| 5362 | })), |
| 5363 | ) |
| 5364 | .await |
| 5365 | .status, |
| 5366 | StatusCode::BAD_REQUEST |
| 5367 | ); |
| 5368 | assert_eq!( |
| 5369 | send( |
| 5370 | &app, |
| 5371 | "POST", |
| 5372 | "/users", |
| 5373 | Some(&admin), |
| 5374 | Some(json!({ "username": "hoca", "password": "secret1", "role": "teacher" })), |
| 5375 | ) |
| 5376 | .await |
| 5377 | .status, |
| 5378 | StatusCode::CREATED |
| 5379 | ); |
| 5380 | |
| 5381 | // Bound: 32 characters fit, 33 do not. |
| 5382 | assert_eq!( |
| 5383 | send( |
| 5384 | &app, |
| 5385 | "POST", |
| 5386 | "/users", |
| 5387 | Some(&admin), |
| 5388 | Some(json!({ |
| 5389 | "username": "uzun", |
| 5390 | "password": "secret1", |
| 5391 | "student_number": "9".repeat(33), |
| 5392 | })), |
| 5393 | ) |
| 5394 | .await |
| 5395 | .status, |
| 5396 | StatusCode::BAD_REQUEST |
| 5397 | ); |
| 5398 | |
| 5399 | // Blank is the same as omitted, never a stored empty string. |
| 5400 | let blank = send( |
| 5401 | &app, |
| 5402 | "POST", |
| 5403 | "/users", |
| 5404 | Some(&admin), |
| 5405 | Some(json!({ |
| 5406 | "username": "bosluk", |
| 5407 | "password": "secret1", |
| 5408 | "student_number": " ", |
| 5409 | })), |
| 5410 | ) |
| 5411 | .await; |
| 5412 | assert_eq!(blank.status, StatusCode::CREATED, "{}", blank.body); |
| 5413 | assert!( |
| 5414 | blank.body["student_number"].is_null(), |
| 5415 | "whitespace is absent, not a number: {}", |
| 5416 | blank.body |
| 5417 | ); |
| 5418 | } |
| 5419 | |
| 5420 | /// The AI service principal must never be mintable, storable, or filterable |
| 5421 | /// over HTTP: it is the QUIC bridge's own identity, not an account anybody can |
| 5422 | /// hold. `Role` carries no `serde` derive (`src/domain/role.rs:21`), so no |
| 5423 | /// handler can bind a role straight out of a body — every request-supplied role |
| 5424 | /// passes `Role::try_from_str`, which answers only with a member of |
| 5425 | /// `domain::role::ROLES` (`src/domain/role.rs`, the five human roles). |
| 5426 | /// |
| 5427 | /// Grep-verified 2026-08-12, the complete set of role paths a request can reach: |
| 5428 | /// * `src/web/users.rs:453` — `PATCH /users/{id}/role`, the *only* path that |
| 5429 | /// writes `user.role` from a caller's string (`Role::try_from_str`). |
| 5430 | /// * `src/web/auth.rs:114` — `POST /auth/register`, hardcoded `Role::Student` |
| 5431 | /// (`service::user::create` → `create_with_role`, `src/db/user.rs`). |
| 5432 | /// * `src/web/users.rs:231` — the user-search `?role=` filter (a read). |
| 5433 | /// * `src/web/events.rs:89` — a role-audience event stores a role string of |
| 5434 | /// its own on the event row. |
| 5435 | /// The only other `create_with_role` caller is the out-of-band admin bootstrap |
| 5436 | /// (`src/domain/user.rs:426`, hardcoded `Role::Admin`, behind no route). |
| 5437 | /// |
| 5438 | /// corner-cut: that funnel list is grep-verified, not machine-enforced — a *new* |
| 5439 | /// route writing an arbitrary role string would slip past this test. Upgrade |
| 5440 | /// path: derive the surface list from the emitted OpenAPI, the way the auth-gate |
| 5441 | /// test derives its protected-path set. |
| 5442 | #[tokio::test] |
| 5443 | async fn role_ai_is_unreachable_over_http() { |
| 5444 | let (app, db) = app_and_db().await; |
| 5445 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 5446 | let alice = login(&app, "alice").await; |
| 5447 | let alice_id = me_id(&app, &alice).await; |
| 5448 | |
| 5449 | // 1. Registration mints a student and nothing else — read back off the row, |
| 5450 | // not off the register echo. |
| 5451 | let me = send(&app, "GET", "/auth/me", Some(&alice), None).await; |
| 5452 | assert_eq!(me.body["role"], "student"); |
| 5453 | |
| 5454 | // 2. The one role-write funnel refuses it, and the stored role stands. |
| 5455 | assert_eq!( |
| 5456 | send( |
| 5457 | &app, |
| 5458 | "PATCH", |
| 5459 | &format!("/users/{alice_id}/role"), |
| 5460 | Some(&admin), |
| 5461 | Some(json!({"role":"ai"})) |
| 5462 | ) |
| 5463 | .await |
| 5464 | .status, |
| 5465 | StatusCode::BAD_REQUEST |
| 5466 | ); |
| 5467 | assert_eq!( |
| 5468 | send( |
| 5469 | &app, |
| 5470 | "GET", |
| 5471 | &format!("/users/{alice_id}"), |
| 5472 | Some(&admin), |
| 5473 | None |
| 5474 | ) |
| 5475 | .await |
| 5476 | .body["role"], |
| 5477 | "student" |
| 5478 | ); |
| 5479 | |
| 5480 | // 3. The search filter refuses it too — an unknown role is a 400, never an |
| 5481 | // empty page, so a caller can't probe for service accounts. |
| 5482 | assert_eq!( |
| 5483 | send(&app, "GET", "/users/search?q=&role=ai", Some(&admin), None) |
| 5484 | .await |
| 5485 | .status, |
| 5486 | StatusCode::BAD_REQUEST |
| 5487 | ); |
| 5488 | |
| 5489 | // 4. And an event audience, the other surface that stores a role string. |
| 5490 | assert_eq!( |
| 5491 | send( |
| 5492 | &app, |
| 5493 | "POST", |
| 5494 | "/events", |
| 5495 | Some(&admin), |
| 5496 | Some(json!({ "title": "ai only", "audience": { "kind": "role", "role": "ai" } })) |
| 5497 | ) |
| 5498 | .await |
| 5499 | .status, |
| 5500 | StatusCode::BAD_REQUEST |
| 5501 | ); |
| 5502 | |
| 5503 | // 5. The published contract never names it. The exact five-role equality is |
| 5504 | // pinned in `limits_publishes_the_bounds_the_api_actually_enforces`; this |
| 5505 | // is the `ai`-specific |
| 5506 | // angle on the same array, so growing `ROLES` fails here as well. |
| 5507 | let roles = send(&app, "GET", "/limits", None, None).await.body["user"]["roles"].clone(); |
| 5508 | let roles = roles.as_array().expect("limits user.roles array"); |
| 5509 | assert_eq!(roles.len(), 5, "{roles:?}"); |
| 5510 | assert!(!roles.iter().any(|r| r == "ai"), "{roles:?}"); |
| 5511 | |
| 5512 | // 6. Neither does the OpenAPI document Swagger UI renders its forms from. |
| 5513 | // The request schema once `$ref`ed the response-side `Role`, which does |
| 5514 | // name `ai` — so the try-it-out form offered a value the funnel above has |
| 5515 | // always refused with a 400. Request schemas carry the five; the response |
| 5516 | // schema keeps `ai` (a service principal really does read back as one) |
| 5517 | // and must say what it is, since utoipa emits only the *type*-level doc |
| 5518 | // comment, never a variant's. |
| 5519 | let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) |
| 5520 | .await |
| 5521 | .body; |
| 5522 | let schemas = &spec["components"]["schemas"]; |
| 5523 | let human = json!(["parent", "student", "teacher", "manager", "admin"]); |
| 5524 | assert_eq!(schemas["AssignableRole"]["enum"], human, "{schemas:?}"); |
| 5525 | assert_eq!( |
| 5526 | spec["paths"]["/users/{id}/role"]["patch"]["requestBody"]["content"]["application/json"]["schema"] |
| 5527 | ["$ref"], |
| 5528 | "#/components/schemas/SetRole" |
| 5529 | ); |
| 5530 | assert_eq!( |
| 5531 | schemas["SetRole"]["properties"]["role"]["$ref"], |
| 5532 | "#/components/schemas/AssignableRole" |
| 5533 | ); |
| 5534 | let response_role = &schemas["Role"]; |
| 5535 | assert_eq!( |
| 5536 | response_role["enum"], |
| 5537 | json!(["ai", "parent", "student", "teacher", "manager", "admin"]), |
| 5538 | "{response_role:?}" |
| 5539 | ); |
| 5540 | let described = response_role["description"] |
| 5541 | .as_str() |
| 5542 | .expect("Role schema carries its type-level doc comment"); |
| 5543 | assert!(described.contains("never assignable"), "{described:?}"); |
| 5544 | } |
| 5545 | |
| 5546 | // --- users: personal info (profile) --------------------------------------- |
| 5547 | |
| 5548 | #[tokio::test] |
| 5549 | async fn profile_starts_empty_and_updates_via_users_me() { |
| 5550 | let app = mem_app().await; |
| 5551 | let bob = login(&app, "bob").await; |
| 5552 | |
| 5553 | // A fresh account carries no personal info. |
| 5554 | let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; |
| 5555 | assert_eq!(me.status, StatusCode::OK); |
| 5556 | for field in ["name", "surname", "email", "phone", "birth_date"] { |
| 5557 | assert!(me.body[field].is_null(), "{field} should start null"); |
| 5558 | } |
| 5559 | |
| 5560 | // Fill everything in via the self-service endpoint. |
| 5561 | let res = send( |
| 5562 | &app, |
| 5563 | "PATCH", |
| 5564 | "/users/me", |
| 5565 | Some(&bob), |
| 5566 | Some(json!({ |
| 5567 | "name": "Bob", |
| 5568 | "surname": "Gümüş", |
| 5569 | "email": "bob@example.com", |
| 5570 | "phone": "+90 555 123 45 67", |
| 5571 | "birth_date": "1990-1-2", |
| 5572 | })), |
| 5573 | ) |
| 5574 | .await; |
| 5575 | assert_eq!(res.status, StatusCode::OK); |
| 5576 | assert_eq!(res.body["name"], "Bob"); |
| 5577 | assert_eq!(res.body["surname"], "Gümüş"); // unicode names allowed |
| 5578 | assert_eq!(res.body["email"], "bob@example.com"); |
| 5579 | assert_eq!(res.body["phone"], "+90 555 123 45 67"); |
| 5580 | assert_eq!(res.body["birth_date"], "1990-01-02"); // canonicalized |
| 5581 | assert!(res.body.get("password_hash").is_none()); |
| 5582 | |
| 5583 | // Partial patch: only phone changes, everything else survives. |
| 5584 | let res = send( |
| 5585 | &app, |
| 5586 | "PATCH", |
| 5587 | "/users/me", |
| 5588 | Some(&bob), |
| 5589 | Some(json!({ "phone": "05551112233" })), |
| 5590 | ) |
| 5591 | .await; |
| 5592 | assert_eq!(res.status, StatusCode::OK); |
| 5593 | assert_eq!(res.body["phone"], "05551112233"); |
| 5594 | assert_eq!(res.body["name"], "Bob"); |
| 5595 | assert_eq!(res.body["email"], "bob@example.com"); |
| 5596 | |
| 5597 | // Empty string clears a field; the others stay. |
| 5598 | let res = send( |
| 5599 | &app, |
| 5600 | "PATCH", |
| 5601 | "/users/me", |
| 5602 | Some(&bob), |
| 5603 | Some(json!({ "phone": "" })), |
| 5604 | ) |
| 5605 | .await; |
| 5606 | assert_eq!(res.status, StatusCode::OK); |
| 5607 | assert!(res.body["phone"].is_null()); |
| 5608 | assert_eq!(res.body["name"], "Bob"); |
| 5609 | |
| 5610 | // The merged state is what /auth/me reports afterwards. |
| 5611 | let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; |
| 5612 | assert_eq!(me.body["name"], "Bob"); |
| 5613 | assert_eq!(me.body["surname"], "Gümüş"); |
| 5614 | assert_eq!(me.body["birth_date"], "1990-01-02"); |
| 5615 | assert!(me.body["phone"].is_null()); |
| 5616 | |
| 5617 | // No session -> 401. |
| 5618 | assert_eq!( |
| 5619 | send(&app, "PATCH", "/users/me", None, Some(json!({"name":"x"}))) |
| 5620 | .await |
| 5621 | .status, |
| 5622 | StatusCode::UNAUTHORIZED |
| 5623 | ); |
| 5624 | } |
| 5625 | |
| 5626 | #[tokio::test] |
| 5627 | async fn profile_rejects_invalid_fields() { |
| 5628 | let app = mem_app().await; |
| 5629 | let bob = login(&app, "bob").await; |
| 5630 | |
| 5631 | let bad = [ |
| 5632 | json!({ "email": "not-an-email" }), |
| 5633 | json!({ "email": "bob@nodot" }), |
| 5634 | json!({ "phone": "123" }), |
| 5635 | json!({ "phone": "letters" }), |
| 5636 | json!({ "birth_date": "02/01/1990" }), |
| 5637 | json!({ "birth_date": "1990-02-30" }), |
| 5638 | json!({ "birth_date": "9999-01-01" }), |
| 5639 | json!({ "name": " " }), |
| 5640 | json!({ "name": "x".repeat(101) }), |
| 5641 | ]; |
| 5642 | for body in bad { |
| 5643 | let res = send(&app, "PATCH", "/users/me", Some(&bob), Some(body.clone())).await; |
| 5644 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "should reject {body}"); |
| 5645 | } |
| 5646 | |
| 5647 | // A rejected patch must not have half-applied: profile is still empty. |
| 5648 | let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; |
| 5649 | for field in ["name", "surname", "email", "phone", "birth_date"] { |
| 5650 | assert!(me.body[field].is_null(), "{field} should still be null"); |
| 5651 | } |
| 5652 | } |
| 5653 | |
| 5654 | // --- users: gender, address, emergency contact ------------------------------ |
| 5655 | |
| 5656 | #[tokio::test] |
| 5657 | async fn profile_extra_fields_round_trip_via_users_me() { |
| 5658 | let app = mem_app().await; |
| 5659 | let bob = login(&app, "bob").await; |
| 5660 | |
| 5661 | // A fresh account carries none of the extras. |
| 5662 | let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; |
| 5663 | assert_eq!(me.status, StatusCode::OK); |
| 5664 | for field in [ |
| 5665 | "gender", |
| 5666 | "address", |
| 5667 | "emergency_contact_name", |
| 5668 | "emergency_contact_phone", |
| 5669 | ] { |
| 5670 | assert!(me.body[field].is_null(), "{field} should start null"); |
| 5671 | } |
| 5672 | |
| 5673 | // Set all four in one patch. |
| 5674 | let res = send( |
| 5675 | &app, |
| 5676 | "PATCH", |
| 5677 | "/users/me", |
| 5678 | Some(&bob), |
| 5679 | Some(json!({ |
| 5680 | "gender": "female", |
| 5681 | "address": " Çamlık Mah. 2. Sk. No: 7 ", |
| 5682 | "emergency_contact_name": "Mehmet Yılmaz", |
| 5683 | "emergency_contact_phone": "+90 555 987 65 43", |
| 5684 | })), |
| 5685 | ) |
| 5686 | .await; |
| 5687 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 5688 | assert_eq!(res.body["gender"], "female"); |
| 5689 | assert_eq!(res.body["address"], "Çamlık Mah. 2. Sk. No: 7"); // trimmed |
| 5690 | assert_eq!(res.body["emergency_contact_name"], "Mehmet Yılmaz"); |
| 5691 | assert_eq!(res.body["emergency_contact_phone"], "+90 555 987 65 43"); |
| 5692 | |
| 5693 | // Partial patch: only the address changes, everything else survives. |
| 5694 | let res = send( |
| 5695 | &app, |
| 5696 | "PATCH", |
| 5697 | "/users/me", |
| 5698 | Some(&bob), |
| 5699 | Some(json!({ "address": "Yeni Mah." })), |
| 5700 | ) |
| 5701 | .await; |
| 5702 | assert_eq!(res.status, StatusCode::OK); |
| 5703 | assert_eq!(res.body["address"], "Yeni Mah."); |
| 5704 | assert_eq!(res.body["gender"], "female"); |
| 5705 | assert_eq!(res.body["emergency_contact_name"], "Mehmet Yılmaz"); |
| 5706 | assert_eq!(res.body["emergency_contact_phone"], "+90 555 987 65 43"); |
| 5707 | |
| 5708 | // Empty string clears exactly the field it was sent for. |
| 5709 | let res = send( |
| 5710 | &app, |
| 5711 | "PATCH", |
| 5712 | "/users/me", |
| 5713 | Some(&bob), |
| 5714 | Some(json!({ "gender": "" })), |
| 5715 | ) |
| 5716 | .await; |
| 5717 | assert_eq!(res.status, StatusCode::OK); |
| 5718 | assert!(res.body["gender"].is_null()); |
| 5719 | assert_eq!(res.body["address"], "Yeni Mah."); |
| 5720 | |
| 5721 | // The merged state is what /auth/me reports afterwards. |
| 5722 | let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; |
| 5723 | assert!(me.body["gender"].is_null()); |
| 5724 | assert_eq!(me.body["address"], "Yeni Mah."); |
| 5725 | assert_eq!(me.body["emergency_contact_phone"], "+90 555 987 65 43"); |
| 5726 | } |
| 5727 | |
| 5728 | #[tokio::test] |
| 5729 | async fn profile_rejects_invalid_extra_fields() { |
| 5730 | let app = mem_app().await; |
| 5731 | let bob = login(&app, "bob").await; |
| 5732 | |
| 5733 | let bad = [ |
| 5734 | json!({ "gender": "woman" }), // not in the vocabulary |
| 5735 | json!({ "gender": "FEMALE" }), // the vocabulary is lowercase |
| 5736 | json!({ "address": "x".repeat(501) }), // one over the bound |
| 5737 | json!({ "address": " " }), // whitespace-only is not a value |
| 5738 | json!({ "emergency_contact_phone": "123" }), |
| 5739 | json!({ "emergency_contact_phone": "letters" }), |
| 5740 | json!({ "emergency_contact_name": " " }), |
| 5741 | ]; |
| 5742 | for body in bad { |
| 5743 | let res = send(&app, "PATCH", "/users/me", Some(&bob), Some(body.clone())).await; |
| 5744 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "should reject {body}"); |
| 5745 | } |
| 5746 | |
| 5747 | // A rejected patch must not have half-applied. |
| 5748 | let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; |
| 5749 | for field in [ |
| 5750 | "gender", |
| 5751 | "address", |
| 5752 | "emergency_contact_name", |
| 5753 | "emergency_contact_phone", |
| 5754 | ] { |
| 5755 | assert!(me.body[field].is_null(), "{field} should still be null"); |
| 5756 | } |
| 5757 | } |
| 5758 | |
| 5759 | #[tokio::test] |
| 5760 | async fn admin_reads_and_edits_any_profile_with_guards() { |
| 5761 | let (app, db) = app_and_db().await; |
| 5762 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 5763 | let alice = login(&app, "alice").await; |
| 5764 | let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body); |
| 5765 | let admin_id = id_of(&send(&app, "GET", "/auth/me", Some(&admin), None).await.body); |
| 5766 | |
| 5767 | // Students can neither look up nor edit someone else's record. |
| 5768 | assert_eq!( |
| 5769 | send( |
| 5770 | &app, |
| 5771 | "GET", |
| 5772 | &format!("/users/{admin_id}"), |
| 5773 | Some(&alice), |
| 5774 | None |
| 5775 | ) |
| 5776 | .await |
| 5777 | .status, |
| 5778 | StatusCode::FORBIDDEN |
| 5779 | ); |
| 5780 | assert_eq!( |
| 5781 | send( |
| 5782 | &app, |
| 5783 | "PATCH", |
| 5784 | &format!("/users/{admin_id}/profile"), |
| 5785 | Some(&alice), |
| 5786 | Some(json!({"name":"Mallory"})) |
| 5787 | ) |
| 5788 | .await |
| 5789 | .status, |
| 5790 | StatusCode::FORBIDDEN |
| 5791 | ); |
| 5792 | |
| 5793 | // Admin maintains alice's record on her behalf. |
| 5794 | let res = send( |
| 5795 | &app, |
| 5796 | "PATCH", |
| 5797 | &format!("/users/{alice_id}/profile"), |
| 5798 | Some(&admin), |
| 5799 | Some(json!({ "name": "Alice", "email": "alice@school.edu" })), |
| 5800 | ) |
| 5801 | .await; |
| 5802 | assert_eq!(res.status, StatusCode::OK); |
| 5803 | assert_eq!(res.body["name"], "Alice"); |
| 5804 | |
| 5805 | // Admin reads a single user; alice sees the change on /auth/me. |
| 5806 | let one = send( |
| 5807 | &app, |
| 5808 | "GET", |
| 5809 | &format!("/users/{alice_id}"), |
| 5810 | Some(&admin), |
| 5811 | None, |
| 5812 | ) |
| 5813 | .await; |
| 5814 | assert_eq!(one.status, StatusCode::OK); |
| 5815 | assert_eq!(one.body["username"], "alice"); |
| 5816 | assert_eq!(one.body["email"], "alice@school.edu"); |
| 5817 | let me = send(&app, "GET", "/auth/me", Some(&alice), None).await; |
| 5818 | assert_eq!(me.body["name"], "Alice"); |
| 5819 | |
| 5820 | // The admin listing now carries the info columns too. |
| 5821 | let list = send(&app, "GET", "/users", Some(&admin), None).await; |
| 5822 | let listed = common::items(&list.body) |
| 5823 | .iter() |
| 5824 | .find(|u| u["username"] == "alice") |
| 5825 | .expect("alice listed") |
| 5826 | .clone(); |
| 5827 | assert_eq!(listed["email"], "alice@school.edu"); |
| 5828 | |
| 5829 | // Unknown ids -> 404 on both admin endpoints. |
| 5830 | assert_eq!( |
| 5831 | send(&app, "GET", "/users/does-not-exist", Some(&admin), None) |
| 5832 | .await |
| 5833 | .status, |
| 5834 | StatusCode::NOT_FOUND |
| 5835 | ); |
| 5836 | assert_eq!( |
| 5837 | send( |
| 5838 | &app, |
| 5839 | "PATCH", |
| 5840 | "/users/does-not-exist/profile", |
| 5841 | Some(&admin), |
| 5842 | Some(json!({"name":"Nobody"})) |
| 5843 | ) |
| 5844 | .await |
| 5845 | .status, |
| 5846 | StatusCode::NOT_FOUND |
| 5847 | ); |
| 5848 | } |
| 5849 | |
| 5850 | /// `student_number` through the profile doors: the office numbers a student, |
| 5851 | /// the number rides every surface that shows student identity, a duplicate is |
| 5852 | /// a coded 409, blank clears (on any role — a clear is not a set), only a |
| 5853 | /// student may hold one, and a role change away from `student` clears it. |
| 5854 | #[tokio::test] |
| 5855 | async fn student_number_patches_follow_the_student_role() { |
| 5856 | let (app, db) = app_and_db().await; |
| 5857 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 5858 | let alice = login(&app, "alice").await; |
| 5859 | let alice_id = me_id(&app, &alice).await; |
| 5860 | let bob = login(&app, "bob").await; |
| 5861 | let bob_id = me_id(&app, &bob).await; |
| 5862 | |
| 5863 | // The office numbers alice. |
| 5864 | let res = send( |
| 5865 | &app, |
| 5866 | "PATCH", |
| 5867 | &format!("/users/{alice_id}/profile"), |
| 5868 | Some(&admin), |
| 5869 | Some(json!({ "student_number": " 9-B/17 " })), |
| 5870 | ) |
| 5871 | .await; |
| 5872 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 5873 | assert_eq!(res.body["student_number"], "9-B/17", "stored trimmed"); |
| 5874 | |
| 5875 | // Every reader that shows student identity carries it: the admin's single |
| 5876 | // read, the admin listing, the picker ref, and alice's own session. |
| 5877 | let one = send( |
| 5878 | &app, |
| 5879 | "GET", |
| 5880 | &format!("/users/{alice_id}"), |
| 5881 | Some(&admin), |
| 5882 | None, |
| 5883 | ) |
| 5884 | .await; |
| 5885 | assert_eq!(one.body["student_number"], "9-B/17"); |
| 5886 | let list = send(&app, "GET", "/users", Some(&admin), None).await; |
| 5887 | let listed = common::items(&list.body) |
| 5888 | .iter() |
| 5889 | .find(|u| u["username"] == "alice") |
| 5890 | .expect("alice listed") |
| 5891 | .clone(); |
| 5892 | assert_eq!(listed["student_number"], "9-B/17"); |
| 5893 | let search = send( |
| 5894 | &app, |
| 5895 | "GET", |
| 5896 | "/users/search?q=alice&role=student", |
| 5897 | Some(&admin), |
| 5898 | None, |
| 5899 | ) |
| 5900 | .await; |
| 5901 | let found = common::items(&search.body) |
| 5902 | .iter() |
| 5903 | .find(|u| u["username"] == "alice") |
| 5904 | .expect("alice found") |
| 5905 | .clone(); |
| 5906 | assert_eq!(found["student_number"], "9-B/17"); |
| 5907 | let me = send(&app, "GET", "/auth/me", Some(&alice), None).await; |
| 5908 | assert_eq!(me.body["student_number"], "9-B/17"); |
| 5909 | |
| 5910 | // A student owns the number on their own row: the self door takes it too, |
| 5911 | // under the same rules. An unrelated patch leaves it standing. |
| 5912 | let res = send( |
| 5913 | &app, |
| 5914 | "PATCH", |
| 5915 | "/users/me", |
| 5916 | Some(&alice), |
| 5917 | Some(json!({ "student_number": "9-B/18" })), |
| 5918 | ) |
| 5919 | .await; |
| 5920 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 5921 | assert_eq!(res.body["student_number"], "9-B/18"); |
| 5922 | let res = send( |
| 5923 | &app, |
| 5924 | "PATCH", |
| 5925 | "/users/me", |
| 5926 | Some(&alice), |
| 5927 | Some(json!({ "name": "Alice" })), |
| 5928 | ) |
| 5929 | .await; |
| 5930 | assert_eq!(res.body["student_number"], "9-B/18", "omitted = untouched"); |
| 5931 | |
| 5932 | // Bound: 33 characters are refused through this door too. |
| 5933 | assert_eq!( |
| 5934 | send( |
| 5935 | &app, |
| 5936 | "PATCH", |
| 5937 | "/users/me", |
| 5938 | Some(&alice), |
| 5939 | Some(json!({ "student_number": "9".repeat(33) })), |
| 5940 | ) |
| 5941 | .await |
| 5942 | .status, |
| 5943 | StatusCode::BAD_REQUEST |
| 5944 | ); |
| 5945 | |
| 5946 | // bob takes one of his own; alice claiming it is the index's refusal, and |
| 5947 | // the refused patch left her number exactly as it stood. |
| 5948 | assert_eq!( |
| 5949 | send( |
| 5950 | &app, |
| 5951 | "PATCH", |
| 5952 | &format!("/users/{bob_id}/profile"), |
| 5953 | Some(&admin), |
| 5954 | Some(json!({ "student_number": "1234" })), |
| 5955 | ) |
| 5956 | .await |
| 5957 | .status, |
| 5958 | StatusCode::OK |
| 5959 | ); |
| 5960 | let clash = send( |
| 5961 | &app, |
| 5962 | "PATCH", |
| 5963 | &format!("/users/{alice_id}/profile"), |
| 5964 | Some(&admin), |
| 5965 | Some(json!({ "student_number": "1234" })), |
| 5966 | ) |
| 5967 | .await; |
| 5968 | assert_eq!(clash.status, StatusCode::CONFLICT, "{}", clash.body); |
| 5969 | assert_eq!(clash.body["error"], "student number already taken"); |
| 5970 | assert_eq!(clash.body["code"], "student_number_taken"); |
| 5971 | let one = send( |
| 5972 | &app, |
| 5973 | "GET", |
| 5974 | &format!("/users/{alice_id}"), |
| 5975 | Some(&admin), |
| 5976 | None, |
| 5977 | ) |
| 5978 | .await; |
| 5979 | assert_eq!(one.body["student_number"], "9-B/18"); |
| 5980 | |
| 5981 | // Only students hold one. A teacher target refuses a value outright... |
| 5982 | let teacher = send( |
| 5983 | &app, |
| 5984 | "POST", |
| 5985 | "/users", |
| 5986 | Some(&admin), |
| 5987 | Some(json!({ "username": "hoca", "password": "secret1", "role": "teacher" })), |
| 5988 | ) |
| 5989 | .await; |
| 5990 | assert_eq!(teacher.status, StatusCode::CREATED, "{}", teacher.body); |
| 5991 | let teacher_id = id_of(&teacher.body); |
| 5992 | let refused = send( |
| 5993 | &app, |
| 5994 | "PATCH", |
| 5995 | &format!("/users/{teacher_id}/profile"), |
| 5996 | Some(&admin), |
| 5997 | Some(json!({ "student_number": "5678" })), |
| 5998 | ) |
| 5999 | .await; |
| 6000 | assert_eq!(refused.status, StatusCode::BAD_REQUEST, "{}", refused.body); |
| 6001 | assert_eq!( |
| 6002 | refused.body["error"], |
| 6003 | "student_number: only a student account may hold a student number" |
| 6004 | ); |
| 6005 | // ...and so does the admin's own row through the self door. |
| 6006 | assert_eq!( |
| 6007 | send( |
| 6008 | &app, |
| 6009 | "PATCH", |
| 6010 | "/users/me", |
| 6011 | Some(&admin), |
| 6012 | Some(json!({ "student_number": "9999" })), |
| 6013 | ) |
| 6014 | .await |
| 6015 | .status, |
| 6016 | StatusCode::BAD_REQUEST |
| 6017 | ); |
| 6018 | // A *clear* is not a set: blank on a non-student is the same no-op the |
| 6019 | // omitted field is, never a refusal. |
| 6020 | assert_eq!( |
| 6021 | send( |
| 6022 | &app, |
| 6023 | "PATCH", |
| 6024 | "/users/me", |
| 6025 | Some(&admin), |
| 6026 | Some(json!({ "student_number": "" })), |
| 6027 | ) |
| 6028 | .await |
| 6029 | .status, |
| 6030 | StatusCode::OK |
| 6031 | ); |
| 6032 | |
| 6033 | // Blank (and whitespace) clears a student's number rather than storing an |
| 6034 | // empty string. |
| 6035 | let cleared = send( |
| 6036 | &app, |
| 6037 | "PATCH", |
| 6038 | "/users/me", |
| 6039 | Some(&alice), |
| 6040 | Some(json!({ "student_number": " " })), |
| 6041 | ) |
| 6042 | .await; |
| 6043 | assert_eq!(cleared.status, StatusCode::OK, "{}", cleared.body); |
| 6044 | assert!(cleared.body["student_number"].is_null(), "{}", cleared.body); |
| 6045 | |
| 6046 | // The role cascade is the other half of the rule: a promotion out of |
| 6047 | // `student` clears the number in the same transaction, and a later |
| 6048 | // demotion back to `student` does not restore it — the number is set, not |
| 6049 | // remembered. |
| 6050 | assert_eq!( |
| 6051 | send( |
| 6052 | &app, |
| 6053 | "PATCH", |
| 6054 | &format!("/users/{alice_id}/profile"), |
| 6055 | Some(&admin), |
| 6056 | Some(json!({ "student_number": "9-B/17" })), |
| 6057 | ) |
| 6058 | .await |
| 6059 | .status, |
| 6060 | StatusCode::OK |
| 6061 | ); |
| 6062 | let promoted = send( |
| 6063 | &app, |
| 6064 | "PATCH", |
| 6065 | &format!("/users/{alice_id}/role"), |
| 6066 | Some(&admin), |
| 6067 | Some(json!({ "role": "teacher" })), |
| 6068 | ) |
| 6069 | .await; |
| 6070 | assert_eq!(promoted.status, StatusCode::OK, "{}", promoted.body); |
| 6071 | assert!( |
| 6072 | promoted.body["student_number"].is_null(), |
| 6073 | "the promotion clears the number: {}", |
| 6074 | promoted.body |
| 6075 | ); |
| 6076 | let one = send( |
| 6077 | &app, |
| 6078 | "GET", |
| 6079 | &format!("/users/{alice_id}"), |
| 6080 | Some(&admin), |
| 6081 | None, |
| 6082 | ) |
| 6083 | .await; |
| 6084 | assert!(one.body["student_number"].is_null(), "{}", one.body); |
| 6085 | let demoted = send( |
| 6086 | &app, |
| 6087 | "PATCH", |
| 6088 | &format!("/users/{alice_id}/role"), |
| 6089 | Some(&admin), |
| 6090 | Some(json!({ "role": "student" })), |
| 6091 | ) |
| 6092 | .await; |
| 6093 | assert_eq!(demoted.status, StatusCode::OK, "{}", demoted.body); |
| 6094 | assert!( |
| 6095 | demoted.body["student_number"].is_null(), |
| 6096 | "a role change to student leaves it unset: {}", |
| 6097 | demoted.body |
| 6098 | ); |
| 6099 | } |
| 6100 | |
| 6101 | // --- users: UI preferences (theme, language, palette color) ------------------------------ |
| 6102 | |
| 6103 | #[tokio::test] |
| 6104 | async fn preferences_start_null_and_update_via_me_preferences() { |
| 6105 | let app = mem_app().await; |
| 6106 | let bob = login(&app, "bob").await; |
| 6107 | |
| 6108 | // A fresh account has never chosen — both come back null. |
| 6109 | let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; |
| 6110 | assert_eq!(me.status, StatusCode::OK); |
| 6111 | assert!(me.body["theme"].is_null(), "theme should start null"); |
| 6112 | assert!(me.body["language"].is_null(), "language should start null"); |
| 6113 | assert!( |
| 6114 | me.body["palette_color"].is_null(), |
| 6115 | "palette_color should start null" |
| 6116 | ); |
| 6117 | |
| 6118 | // Set all three through the self-service endpoint. Mixed-case hex is |
| 6119 | // accepted and comes back lowercase. |
| 6120 | let res = send( |
| 6121 | &app, |
| 6122 | "PATCH", |
| 6123 | "/users/me/preferences", |
| 6124 | Some(&bob), |
| 6125 | Some(json!({ "theme": "dark", "language": "tr", "palette_color": "#FEFAE0" })), |
| 6126 | ) |
| 6127 | .await; |
| 6128 | assert_eq!(res.status, StatusCode::OK); |
| 6129 | assert_eq!(res.body["theme"], "dark"); |
| 6130 | assert_eq!(res.body["language"], "tr"); |
| 6131 | assert_eq!(res.body["palette_color"], "#fefae0"); |
| 6132 | |
| 6133 | // Partial patch: only the theme changes, the other two survive. |
| 6134 | let res = send( |
| 6135 | &app, |
| 6136 | "PATCH", |
| 6137 | "/users/me/preferences", |
| 6138 | Some(&bob), |
| 6139 | Some(json!({ "theme": "light" })), |
| 6140 | ) |
| 6141 | .await; |
| 6142 | assert_eq!(res.status, StatusCode::OK); |
| 6143 | assert_eq!(res.body["theme"], "light"); |
| 6144 | assert_eq!(res.body["language"], "tr"); |
| 6145 | assert_eq!(res.body["palette_color"], "#fefae0"); |
| 6146 | |
| 6147 | // …and only the accent color changes, leaving theme and language alone. |
| 6148 | let res = send( |
| 6149 | &app, |
| 6150 | "PATCH", |
| 6151 | "/users/me/preferences", |
| 6152 | Some(&bob), |
| 6153 | Some(json!({ "palette_color": "#283618" })), |
| 6154 | ) |
| 6155 | .await; |
| 6156 | assert_eq!(res.status, StatusCode::OK); |
| 6157 | assert_eq!(res.body["palette_color"], "#283618"); |
| 6158 | assert_eq!(res.body["theme"], "light"); |
| 6159 | assert_eq!(res.body["language"], "tr"); |
| 6160 | |
| 6161 | // Empty string clears back to "never chose"; the others stay. |
| 6162 | let res = send( |
| 6163 | &app, |
| 6164 | "PATCH", |
| 6165 | "/users/me/preferences", |
| 6166 | Some(&bob), |
| 6167 | Some(json!({ "theme": "" })), |
| 6168 | ) |
| 6169 | .await; |
| 6170 | assert_eq!(res.status, StatusCode::OK); |
| 6171 | assert!(res.body["theme"].is_null()); |
| 6172 | assert_eq!(res.body["language"], "tr"); |
| 6173 | assert_eq!(res.body["palette_color"], "#283618"); |
| 6174 | |
| 6175 | let res = send( |
| 6176 | &app, |
| 6177 | "PATCH", |
| 6178 | "/users/me/preferences", |
| 6179 | Some(&bob), |
| 6180 | Some(json!({ "palette_color": "" })), |
| 6181 | ) |
| 6182 | .await; |
| 6183 | assert_eq!(res.status, StatusCode::OK); |
| 6184 | assert!(res.body["palette_color"].is_null()); |
| 6185 | assert_eq!(res.body["language"], "tr"); |
| 6186 | |
| 6187 | // The merged state is what /auth/me reports afterwards. |
| 6188 | let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; |
| 6189 | assert!(me.body["theme"].is_null()); |
| 6190 | assert!(me.body["palette_color"].is_null()); |
| 6191 | assert_eq!(me.body["language"], "tr"); |
| 6192 | |
| 6193 | // No session -> 401. |
| 6194 | assert_eq!( |
| 6195 | send( |
| 6196 | &app, |
| 6197 | "PATCH", |
| 6198 | "/users/me/preferences", |
| 6199 | None, |
| 6200 | Some(json!({"theme":"dark"})) |
| 6201 | ) |
| 6202 | .await |
| 6203 | .status, |
| 6204 | StatusCode::UNAUTHORIZED |
| 6205 | ); |
| 6206 | } |
| 6207 | |
| 6208 | #[tokio::test] |
| 6209 | async fn preferences_reject_invalid_values() { |
| 6210 | let app = mem_app().await; |
| 6211 | let bob = login(&app, "bob").await; |
| 6212 | |
| 6213 | let bad = [ |
| 6214 | json!({ "theme": "solarized" }), |
| 6215 | json!({ "theme": "Dark" }), |
| 6216 | json!({ "language": "turkish" }), |
| 6217 | json!({ "language": "de" }), |
| 6218 | json!({ "theme": "dark", "language": "nope" }), |
| 6219 | json!({ "palette_color": "fefae0" }), // no leading # |
| 6220 | json!({ "palette_color": "#fff" }), // short form |
| 6221 | json!({ "palette_color": "#gggggg" }), // not hex |
| 6222 | json!({ "palette_color": "#fefae0 " }), // untrimmed |
| 6223 | json!({ "palette_color": "rebeccapurple" }), |
| 6224 | // Mixed: a valid theme must not sneak through beside a bad color. |
| 6225 | json!({ "theme": "dark", "palette_color": "#12345" }), |
| 6226 | ]; |
| 6227 | for body in bad { |
| 6228 | let res = send( |
| 6229 | &app, |
| 6230 | "PATCH", |
| 6231 | "/users/me/preferences", |
| 6232 | Some(&bob), |
| 6233 | Some(body.clone()), |
| 6234 | ) |
| 6235 | .await; |
| 6236 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "should reject {body}"); |
| 6237 | } |
| 6238 | |
| 6239 | // A rejected patch must not have half-applied: both are still null. |
| 6240 | let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; |
| 6241 | assert!(me.body["theme"].is_null(), "theme should still be null"); |
| 6242 | assert!( |
| 6243 | me.body["language"].is_null(), |
| 6244 | "language should still be null" |
| 6245 | ); |
| 6246 | assert!( |
| 6247 | me.body["palette_color"].is_null(), |
| 6248 | "palette_color should still be null" |
| 6249 | ); |
| 6250 | } |
| 6251 | |
| 6252 | #[tokio::test] |
| 6253 | async fn admin_edits_any_preferences_with_guards() { |
| 6254 | let (app, db) = app_and_db().await; |
| 6255 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 6256 | let alice = login(&app, "alice").await; |
| 6257 | let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body); |
| 6258 | let admin_id = id_of(&send(&app, "GET", "/auth/me", Some(&admin), None).await.body); |
| 6259 | |
| 6260 | // A student cannot touch someone else's preferences. |
| 6261 | assert_eq!( |
| 6262 | send( |
| 6263 | &app, |
| 6264 | "PATCH", |
| 6265 | &format!("/users/{admin_id}/preferences"), |
| 6266 | Some(&alice), |
| 6267 | Some(json!({"theme":"dark"})) |
| 6268 | ) |
| 6269 | .await |
| 6270 | .status, |
| 6271 | StatusCode::FORBIDDEN |
| 6272 | ); |
| 6273 | |
| 6274 | // Admin sets alice's preferences on her behalf. |
| 6275 | let res = send( |
| 6276 | &app, |
| 6277 | "PATCH", |
| 6278 | &format!("/users/{alice_id}/preferences"), |
| 6279 | Some(&admin), |
| 6280 | Some(json!({ "theme": "dark", "language": "en", "palette_color": "#FEFAE0" })), |
| 6281 | ) |
| 6282 | .await; |
| 6283 | assert_eq!(res.status, StatusCode::OK); |
| 6284 | assert_eq!(res.body["theme"], "dark"); |
| 6285 | assert_eq!(res.body["language"], "en"); |
| 6286 | assert_eq!( |
| 6287 | res.body["palette_color"], "#fefae0", |
| 6288 | "normalized on the admin path too" |
| 6289 | ); |
| 6290 | |
| 6291 | // The admin route patches partially and clears by `""` exactly like the |
| 6292 | // self-service one — one field at a time, the others untouched. |
| 6293 | let res = send( |
| 6294 | &app, |
| 6295 | "PATCH", |
| 6296 | &format!("/users/{alice_id}/preferences"), |
| 6297 | Some(&admin), |
| 6298 | Some(json!({ "palette_color": "#283618" })), |
| 6299 | ) |
| 6300 | .await; |
| 6301 | assert_eq!(res.status, StatusCode::OK); |
| 6302 | assert_eq!(res.body["palette_color"], "#283618"); |
| 6303 | assert_eq!(res.body["theme"], "dark", "theme lost to the color patch"); |
| 6304 | assert_eq!(res.body["language"], "en"); |
| 6305 | |
| 6306 | let res = send( |
| 6307 | &app, |
| 6308 | "PATCH", |
| 6309 | &format!("/users/{alice_id}/preferences"), |
| 6310 | Some(&admin), |
| 6311 | Some(json!({ "palette_color": "" })), |
| 6312 | ) |
| 6313 | .await; |
| 6314 | assert_eq!(res.status, StatusCode::OK); |
| 6315 | assert!(res.body["palette_color"].is_null()); |
| 6316 | assert_eq!(res.body["theme"], "dark", "theme lost to the clear"); |
| 6317 | assert_eq!(res.body["language"], "en"); |
| 6318 | |
| 6319 | // Back to a set value, so the reads below cover it too. |
| 6320 | let res = send( |
| 6321 | &app, |
| 6322 | "PATCH", |
| 6323 | &format!("/users/{alice_id}/preferences"), |
| 6324 | Some(&admin), |
| 6325 | Some(json!({ "palette_color": "#fefae0" })), |
| 6326 | ) |
| 6327 | .await; |
| 6328 | assert_eq!(res.status, StatusCode::OK); |
| 6329 | |
| 6330 | // Admin reads them on the single-user lookup; alice sees them on /auth/me. |
| 6331 | let one = send( |
| 6332 | &app, |
| 6333 | "GET", |
| 6334 | &format!("/users/{alice_id}"), |
| 6335 | Some(&admin), |
| 6336 | None, |
| 6337 | ) |
| 6338 | .await; |
| 6339 | assert_eq!(one.body["theme"], "dark"); |
| 6340 | assert_eq!(one.body["language"], "en"); |
| 6341 | assert_eq!(one.body["palette_color"], "#fefae0"); |
| 6342 | let me = send(&app, "GET", "/auth/me", Some(&alice), None).await; |
| 6343 | assert_eq!(me.body["theme"], "dark"); |
| 6344 | assert_eq!(me.body["language"], "en"); |
| 6345 | assert_eq!(me.body["palette_color"], "#fefae0"); |
| 6346 | |
| 6347 | // Unknown id -> 404. |
| 6348 | assert_eq!( |
| 6349 | send( |
| 6350 | &app, |
| 6351 | "PATCH", |
| 6352 | "/users/does-not-exist/preferences", |
| 6353 | Some(&admin), |
| 6354 | Some(json!({"theme":"dark"})) |
| 6355 | ) |
| 6356 | .await |
| 6357 | .status, |
| 6358 | StatusCode::NOT_FOUND |
| 6359 | ); |
| 6360 | } |
| 6361 | |
| 6362 | // --- regression: race safety, session hygiene, CORS ---------------------- |
| 6363 | |
| 6364 | /// #1 — Many concurrent marks for the *same* (event, user). A find-then-insert |
| 6365 | /// implementation races the unique index and 500s; the atomic composite-id |
| 6366 | /// upsert must let every request succeed and leave exactly one row. |
| 6367 | #[tokio::test] |
| 6368 | async fn concurrent_attendance_marks_never_collide() { |
| 6369 | let (app, db) = app_and_db().await; |
| 6370 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 6371 | let student = login(&app, "student").await; |
| 6372 | let student_id = id_of( |
| 6373 | &send(&app, "GET", "/auth/me", Some(&student), None) |
| 6374 | .await |
| 6375 | .body, |
| 6376 | ); |
| 6377 | let event_id = id_of( |
| 6378 | &send( |
| 6379 | &app, |
| 6380 | "POST", |
| 6381 | "/events", |
| 6382 | Some(&teacher), |
| 6383 | Some(json!({ "title": "e" })), |
| 6384 | ) |
| 6385 | .await |
| 6386 | .body, |
| 6387 | ); |
| 6388 | |
| 6389 | let mut handles = Vec::new(); |
| 6390 | for i in 0..24 { |
| 6391 | let app = app.clone(); |
| 6392 | let teacher = teacher.clone(); |
| 6393 | let uri = format!("/events/{event_id}/attendance"); |
| 6394 | let status = if i % 2 == 0 { "present" } else { "late" }; |
| 6395 | let body = json!({ "status": status, "user_id": student_id }); |
| 6396 | handles.push(tokio::spawn(async move { |
| 6397 | send(&app, "POST", &uri, Some(&teacher), Some(body)) |
| 6398 | .await |
| 6399 | .status |
| 6400 | })); |
| 6401 | } |
| 6402 | for h in handles { |
| 6403 | assert_eq!( |
| 6404 | h.await.unwrap(), |
| 6405 | StatusCode::OK, |
| 6406 | "concurrent mark must not fail" |
| 6407 | ); |
| 6408 | } |
| 6409 | |
| 6410 | let roster = send( |
| 6411 | &app, |
| 6412 | "GET", |
| 6413 | &format!("/events/{event_id}/attendance"), |
| 6414 | Some(&teacher), |
| 6415 | None, |
| 6416 | ) |
| 6417 | .await; |
| 6418 | assert_eq!( |
| 6419 | common::items(&roster.body).len(), |
| 6420 | 1, |
| 6421 | "upsert keeps a single row" |
| 6422 | ); |
| 6423 | } |
| 6424 | |
| 6425 | /// #1 — Same guarantee for exam grading. |
| 6426 | #[tokio::test] |
| 6427 | async fn concurrent_exam_grades_never_collide() { |
| 6428 | let (app, db) = app_and_db().await; |
| 6429 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 6430 | let student = login(&app, "student").await; |
| 6431 | let student_id = me_id(&app, &student).await; |
| 6432 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 6433 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 6434 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 6435 | let exam_id = create_exam(&app, &teacher, &t.instance, &t.term, "e", "yazili").await; |
| 6436 | |
| 6437 | let mut handles = Vec::new(); |
| 6438 | for mark in 0..24i64 { |
| 6439 | let app = app.clone(); |
| 6440 | let teacher = teacher.clone(); |
| 6441 | let uri = format!("/exams/{exam_id}/results"); |
| 6442 | let body = json!({ "mark": mark, "user_id": student_id }); |
| 6443 | handles.push(tokio::spawn(async move { |
| 6444 | send(&app, "POST", &uri, Some(&teacher), Some(body)) |
| 6445 | .await |
| 6446 | .status |
| 6447 | })); |
| 6448 | } |
| 6449 | for h in handles { |
| 6450 | assert_eq!( |
| 6451 | h.await.unwrap(), |
| 6452 | StatusCode::OK, |
| 6453 | "concurrent grade must not fail" |
| 6454 | ); |
| 6455 | } |
| 6456 | |
| 6457 | let results = send( |
| 6458 | &app, |
| 6459 | "GET", |
| 6460 | &format!("/exams/{exam_id}/results"), |
| 6461 | Some(&teacher), |
| 6462 | None, |
| 6463 | ) |
| 6464 | .await; |
| 6465 | assert_eq!( |
| 6466 | common::items(&results.body).len(), |
| 6467 | 1, |
| 6468 | "upsert keeps a single row" |
| 6469 | ); |
| 6470 | } |
| 6471 | |
| 6472 | /// #2 — A successful login sweeps expired session rows but leaves live ones. |
| 6473 | #[tokio::test] |
| 6474 | async fn login_purges_expired_sessions() { |
| 6475 | let (app, db) = app_and_db().await; |
| 6476 | let ali = login(&app, "ali").await; // one live session |
| 6477 | |
| 6478 | // Inject a session that has already expired. The FK forces the row to |
| 6479 | // point at a real user; the old engine allowed a dangling one. |
| 6480 | let ali_id = me_id(&app, &ali).await; |
| 6481 | sqlx::query( |
| 6482 | "INSERT INTO user_session (id, app_user, token, expires_at) \ |
| 6483 | VALUES ($1, $2, 'expired-token', 1)", |
| 6484 | ) |
| 6485 | .bind(Uuid::now_v7()) |
| 6486 | .bind(Uuid::parse_str(&ali_id).expect("user id")) |
| 6487 | .execute(&db) |
| 6488 | .await |
| 6489 | .unwrap(); |
| 6490 | assert!( |
| 6491 | session::find_by_token(&db, "expired-token") |
| 6492 | .await |
| 6493 | .unwrap() |
| 6494 | .is_some() |
| 6495 | ); |
| 6496 | |
| 6497 | // A later successful login sweeps expired rows... |
| 6498 | login(&app, "veli").await; |
| 6499 | assert!( |
| 6500 | session::find_by_token(&db, "expired-token") |
| 6501 | .await |
| 6502 | .unwrap() |
| 6503 | .is_none(), |
| 6504 | "expired session should be purged on login" |
| 6505 | ); |
| 6506 | // ...while the still-valid session keeps working. |
| 6507 | assert_eq!( |
| 6508 | send(&app, "GET", "/auth/me", Some(&ali), None).await.status, |
| 6509 | StatusCode::OK |
| 6510 | ); |
| 6511 | } |
| 6512 | |
| 6513 | /// An expired session row is rejected at auth even while it still exists — |
| 6514 | /// expiry must not depend on the purge sweep having run. |
| 6515 | #[tokio::test] |
| 6516 | async fn expired_session_is_unauthorized_before_any_purge() { |
| 6517 | let (app, db) = app_and_db().await; |
| 6518 | let ali = login(&app, "ali").await; |
| 6519 | |
| 6520 | // Copy ali's live session into a second row that expired long ago |
| 6521 | // (epoch millis 1), pointing at the same real user. |
| 6522 | sqlx::query( |
| 6523 | "INSERT INTO user_session (id, app_user, token, expires_at) \ |
| 6524 | SELECT $1, app_user, 'stale-token', 1 FROM user_session WHERE token = $2", |
| 6525 | ) |
| 6526 | .bind(Uuid::now_v7()) |
| 6527 | .bind(common::cookie_token(&ali).to_string()) |
| 6528 | .execute(&db) |
| 6529 | .await |
| 6530 | .unwrap(); |
| 6531 | |
| 6532 | // Row exists, but the clock says no. |
| 6533 | assert!( |
| 6534 | session::find_by_token(&db, "stale-token") |
| 6535 | .await |
| 6536 | .unwrap() |
| 6537 | .is_some() |
| 6538 | ); |
| 6539 | assert_eq!( |
| 6540 | send(&app, "GET", "/auth/me", Some("session=stale-token"), None) |
| 6541 | .await |
| 6542 | .status, |
| 6543 | StatusCode::UNAUTHORIZED |
| 6544 | ); |
| 6545 | } |
| 6546 | |
| 6547 | /// Regression: `Username::try_new` used to validate the trimmed value but store |
| 6548 | /// the raw input, so `"ali"`, `"ali "` and `" ali"` were three distinct, |
| 6549 | /// visually identical accounts — and a user who registered with padding could |
| 6550 | /// only log in by reproducing it exactly. The name must be canonicalized |
| 6551 | /// (trimmed) at construction and at login lookup. |
| 6552 | #[tokio::test] |
| 6553 | async fn padded_usernames_are_canonicalized_not_distinct_accounts() { |
| 6554 | let (app, db) = app_and_db().await; |
| 6555 | |
| 6556 | let res = send( |
| 6557 | &app, |
| 6558 | "POST", |
| 6559 | "/auth/register", |
| 6560 | None, |
| 6561 | Some( |
| 6562 | json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ali", "password": "secret1" }), |
| 6563 | ), |
| 6564 | ) |
| 6565 | .await; |
| 6566 | assert_eq!(res.status, StatusCode::CREATED); |
| 6567 | |
| 6568 | // Padding must not mint a lookalike account. Register answers 201 either way |
| 6569 | // (username enumeration is denied, see tests/auth_enumeration.rs), so the |
| 6570 | // collision is observed through the account itself: each spoof asks for a |
| 6571 | // different password, and none of them may take effect. |
| 6572 | for spoof in ["ali ", " ali", " ali "] { |
| 6573 | let res = send( |
| 6574 | &app, |
| 6575 | "POST", |
| 6576 | "/auth/register", |
| 6577 | None, |
| 6578 | Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": spoof, "password": "spoof1" })), |
| 6579 | ) |
| 6580 | .await; |
| 6581 | assert_eq!(res.status, StatusCode::CREATED, "{spoof:?}"); |
| 6582 | } |
| 6583 | |
| 6584 | // One row, not four — the padded forms collided with the canonical name. |
| 6585 | let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user WHERE username = 'ali'") |
| 6586 | .fetch_one(&db) |
| 6587 | .await |
| 6588 | .unwrap(); |
| 6589 | assert_eq!(rows, 1, "padding minted a lookalike account"); |
| 6590 | let all: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user") |
| 6591 | .fetch_one(&db) |
| 6592 | .await |
| 6593 | .unwrap(); |
| 6594 | assert_eq!(all, 1, "unexpected extra user rows"); |
| 6595 | |
| 6596 | // That one account still belongs to the first registration, and every |
| 6597 | // spelling of the name resolves to it. |
| 6598 | for attempt in ["ali", "ali ", " ali", " ali "] { |
| 6599 | let res = send( |
| 6600 | &app, |
| 6601 | "POST", |
| 6602 | "/auth/login", |
| 6603 | None, |
| 6604 | Some(json!({ "username": attempt, "password": "secret1" })), |
| 6605 | ) |
| 6606 | .await; |
| 6607 | assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}"); |
| 6608 | let res = send( |
| 6609 | &app, |
| 6610 | "POST", |
| 6611 | "/auth/login", |
| 6612 | None, |
| 6613 | Some(json!({ "username": attempt, "password": "spoof1" })), |
| 6614 | ) |
| 6615 | .await; |
| 6616 | assert_eq!( |
| 6617 | res.status, |
| 6618 | StatusCode::UNAUTHORIZED, |
| 6619 | "a padded register overwrote \"ali\" (as {attempt:?})" |
| 6620 | ); |
| 6621 | } |
| 6622 | |
| 6623 | // A name registered with padding is stored trimmed... |
| 6624 | let res = send( |
| 6625 | &app, |
| 6626 | "POST", |
| 6627 | "/auth/register", |
| 6628 | None, |
| 6629 | Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": " veli ", "password": "secret1" })), |
| 6630 | ) |
| 6631 | .await; |
| 6632 | assert_eq!(res.status, StatusCode::CREATED); |
| 6633 | assert_eq!(res.body["username"], "veli"); |
| 6634 | |
| 6635 | // ...and the login lookup tolerates padding the same way registration does. |
| 6636 | for attempt in ["veli", " veli "] { |
| 6637 | let res = send( |
| 6638 | &app, |
| 6639 | "POST", |
| 6640 | "/auth/login", |
| 6641 | None, |
| 6642 | Some(json!({ "username": attempt, "password": "secret1" })), |
| 6643 | ) |
| 6644 | .await; |
| 6645 | assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}"); |
| 6646 | } |
| 6647 | } |
| 6648 | |
| 6649 | /// Regression: the grade endpoint verified the exam, the mark, and that the |
| 6650 | /// target exists — but never that the grader isn't the target, so any teacher |
| 6651 | /// could write their own mark. "Grading never targets oneself" (README). The |
| 6652 | /// self-check precedes the target-role and enrollment checks, so it holds even |
| 6653 | /// though staff — the only ones who can grade — are never enrolled or |
| 6654 | /// gradeable themselves. |
| 6655 | #[tokio::test] |
| 6656 | async fn graders_cannot_grade_themselves() { |
| 6657 | let (app, db) = app_and_db().await; |
| 6658 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 6659 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 6660 | let teacher_id = me_id(&app, &teacher).await; |
| 6661 | let boss_id = me_id(&app, &boss).await; |
| 6662 | let student = login(&app, "veli").await; |
| 6663 | let student_id = me_id(&app, &student).await; |
| 6664 | |
| 6665 | let mudur = login_as(&app, &db, "mudur2", "manager").await; |
| 6666 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 6667 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 6668 | let exam_id = create_exam(&app, &teacher, &t.instance, &t.term, "t", "yazili").await; |
| 6669 | |
| 6670 | // Self-grading is forbidden at every privilege level, not just for teachers. |
| 6671 | // (The teacher runs the instance; the manager clears the gate by role.) |
| 6672 | for (cookie, own_id) in [(&teacher, &teacher_id), (&boss, &boss_id)] { |
| 6673 | let res = send( |
| 6674 | &app, |
| 6675 | "POST", |
| 6676 | &format!("/exams/{exam_id}/results"), |
| 6677 | Some(cookie), |
| 6678 | Some(json!({ "mark": 100, "user_id": own_id })), |
| 6679 | ) |
| 6680 | .await; |
| 6681 | assert_eq!( |
| 6682 | res.status, |
| 6683 | StatusCode::FORBIDDEN, |
| 6684 | "self-grade must be rejected" |
| 6685 | ); |
| 6686 | } |
| 6687 | |
| 6688 | // And the rejected attempts wrote nothing. |
| 6689 | assert_eq!( |
| 6690 | common::items( |
| 6691 | &send( |
| 6692 | &app, |
| 6693 | "GET", |
| 6694 | &format!("/exams/{exam_id}/results"), |
| 6695 | Some(&teacher), |
| 6696 | None |
| 6697 | ) |
| 6698 | .await |
| 6699 | .body |
| 6700 | ) |
| 6701 | .len(), |
| 6702 | 0 |
| 6703 | ); |
| 6704 | |
| 6705 | // Grading someone *else* still works (boss grades the enrolled student). |
| 6706 | let res = send( |
| 6707 | &app, |
| 6708 | "POST", |
| 6709 | &format!("/exams/{exam_id}/results"), |
| 6710 | Some(&boss), |
| 6711 | Some(json!({ "mark": 90, "user_id": student_id })), |
| 6712 | ) |
| 6713 | .await; |
| 6714 | assert_eq!(res.status, StatusCode::OK); |
| 6715 | } |
| 6716 | |
| 6717 | /// Enrollment is student membership: staff (teacher/manager/admin) can't be |
| 6718 | /// enrolled, so they never gain the seat that gates sitting exams, being |
| 6719 | /// graded, and the class roster. A plain student enrolls fine. |
| 6720 | #[tokio::test] |
| 6721 | async fn only_students_can_be_enrolled() { |
| 6722 | let (app, db) = app_and_db().await; |
| 6723 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 6724 | let colleague = login_as(&app, &db, "colleague", "teacher").await; |
| 6725 | let manager = login_as(&app, &db, "boss", "manager").await; |
| 6726 | let colleague_id = me_id(&app, &colleague).await; |
| 6727 | let manager_id = me_id(&app, &manager).await; |
| 6728 | |
| 6729 | let mudur = login_as(&app, &db, "mudur_of_staff", "manager").await; |
| 6730 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 6731 | |
| 6732 | // A fellow teacher and a manager are both refused — staff don't enroll. |
| 6733 | for staff_id in [&colleague_id, &manager_id] { |
| 6734 | let res = send( |
| 6735 | &app, |
| 6736 | "POST", |
| 6737 | &format!("/instances/{}/enrollments", t.instance), |
| 6738 | Some(&teacher), |
| 6739 | Some(json!({ "user_id": staff_id })), |
| 6740 | ) |
| 6741 | .await; |
| 6742 | assert_eq!( |
| 6743 | res.status, |
| 6744 | StatusCode::BAD_REQUEST, |
| 6745 | "enrolling staff must be rejected" |
| 6746 | ); |
| 6747 | } |
| 6748 | |
| 6749 | // A student enrolls without complaint (the helper asserts 200). |
| 6750 | let student = login(&app, "veli").await; |
| 6751 | let student_id = me_id(&app, &student).await; |
| 6752 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 6753 | } |
| 6754 | |
| 6755 | /// The student-only rule is enforced on the *live* role, not merely at enroll |
| 6756 | /// time. This flips the role directly in the DB (bypassing the admin endpoint, |
| 6757 | /// which also sweeps enrollments — and boot sweeps rows like this one), so the |
| 6758 | /// enrollment row is still present — but inert: they can no longer sit the |
| 6759 | /// exam, save answers, be graded, or be marked present. The action-time checks |
| 6760 | /// alone hold, with no help from roster hygiene. |
| 6761 | #[tokio::test] |
| 6762 | async fn promotion_out_of_student_freezes_the_seat() { |
| 6763 | let (app, db) = app_and_db().await; |
| 6764 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 6765 | let student = login(&app, "veli").await; |
| 6766 | let student_id = me_id(&app, &student).await; |
| 6767 | |
| 6768 | let mudur = login_as(&app, &db, "promo_m", "manager").await; |
| 6769 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 6770 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 6771 | let future = Timestamp::now().as_millis() + 3_600_000; |
| 6772 | let session = create_session(&app, &teacher, &t.instance, future).await; |
| 6773 | let exam = scheduled_exam( |
| 6774 | &app, |
| 6775 | &teacher, |
| 6776 | &t.instance, |
| 6777 | json!({ "term": &t.term, "title": "essay", "kind": "yazili", "mode": "open" }), |
| 6778 | ) |
| 6779 | .await; |
| 6780 | |
| 6781 | // While still a student, the seat works: they can start a sitting. |
| 6782 | let res = send( |
| 6783 | &app, |
| 6784 | "POST", |
| 6785 | &format!("/exams/{exam}/attempt"), |
| 6786 | Some(&student), |
| 6787 | None, |
| 6788 | ) |
| 6789 | .await; |
| 6790 | assert_eq!( |
| 6791 | res.status, |
| 6792 | StatusCode::CREATED, |
| 6793 | "student sits: {}", |
| 6794 | res.body |
| 6795 | ); |
| 6796 | |
| 6797 | // Promote the enrolled student to teacher; the enrollment row survives. |
| 6798 | set_role(&db, "veli", "teacher").await; |
| 6799 | |
| 6800 | // Sitting is now refused — the live role, not the stale seat, decides. |
| 6801 | let res = send( |
| 6802 | &app, |
| 6803 | "POST", |
| 6804 | &format!("/exams/{exam}/attempt"), |
| 6805 | Some(&student), |
| 6806 | None, |
| 6807 | ) |
| 6808 | .await; |
| 6809 | assert_eq!( |
| 6810 | res.status, |
| 6811 | StatusCode::FORBIDDEN, |
| 6812 | "promoted user can't start a sitting" |
| 6813 | ); |
| 6814 | |
| 6815 | // Nor can they save into the attempt they opened while still a student. |
| 6816 | let res = send( |
| 6817 | &app, |
| 6818 | "POST", |
| 6819 | &format!("/exams/{exam}/attempt/answers"), |
| 6820 | Some(&student), |
| 6821 | Some(json!({ "question_id": "nope", "selected": "c0" })), |
| 6822 | ) |
| 6823 | .await; |
| 6824 | assert_eq!( |
| 6825 | res.status, |
| 6826 | StatusCode::FORBIDDEN, |
| 6827 | "promoted user can't save answers" |
| 6828 | ); |
| 6829 | |
| 6830 | // Grading the promoted user is refused — only students carry marks. |
| 6831 | let res = send( |
| 6832 | &app, |
| 6833 | "POST", |
| 6834 | &format!("/exams/{exam}/results"), |
| 6835 | Some(&teacher), |
| 6836 | Some(json!({ "mark": 80, "user_id": student_id })), |
| 6837 | ) |
| 6838 | .await; |
| 6839 | assert_eq!( |
| 6840 | res.status, |
| 6841 | StatusCode::BAD_REQUEST, |
| 6842 | "promoted user can't be graded" |
| 6843 | ); |
| 6844 | |
| 6845 | // Roll call is refused too — only students attend classes. |
| 6846 | let res = send( |
| 6847 | &app, |
| 6848 | "POST", |
| 6849 | &format!("/sessions/{session}/attendance"), |
| 6850 | Some(&teacher), |
| 6851 | Some(json!({ "status": "present", "user_id": student_id })), |
| 6852 | ) |
| 6853 | .await; |
| 6854 | assert_eq!( |
| 6855 | res.status, |
| 6856 | StatusCode::BAD_REQUEST, |
| 6857 | "promoted user can't be rolled" |
| 6858 | ); |
| 6859 | } |
| 6860 | |
| 6861 | /// Promotion through the admin role endpoint doesn't just freeze the seat — |
| 6862 | /// it deletes the user's enrollment rows outright, so a promoted user drops |
| 6863 | /// off course rosters and live-monitor counts instead of lingering. |
| 6864 | #[tokio::test] |
| 6865 | async fn promotion_via_role_endpoint_sweeps_enrollments() { |
| 6866 | let (app, db) = app_and_db().await; |
| 6867 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 6868 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 6869 | let student = login(&app, "veli").await; |
| 6870 | let student_id = me_id(&app, &student).await; |
| 6871 | |
| 6872 | let mudur = login_as(&app, &db, "mudur_of_promotion", "manager").await; |
| 6873 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 6874 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 6875 | let roster = send( |
| 6876 | &app, |
| 6877 | "GET", |
| 6878 | &format!("/instances/{}/enrollments", t.instance), |
| 6879 | Some(&teacher), |
| 6880 | None, |
| 6881 | ) |
| 6882 | .await; |
| 6883 | assert_eq!(common::total(&roster.body), 1); |
| 6884 | |
| 6885 | let res = send( |
| 6886 | &app, |
| 6887 | "PATCH", |
| 6888 | &format!("/users/{student_id}/role"), |
| 6889 | Some(&admin), |
| 6890 | Some(json!({ "role": "teacher" })), |
| 6891 | ) |
| 6892 | .await; |
| 6893 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 6894 | |
| 6895 | let roster = send( |
| 6896 | &app, |
| 6897 | "GET", |
| 6898 | &format!("/instances/{}/enrollments", t.instance), |
| 6899 | Some(&teacher), |
| 6900 | None, |
| 6901 | ) |
| 6902 | .await; |
| 6903 | assert_eq!( |
| 6904 | common::total(&roster.body), |
| 6905 | 0, |
| 6906 | "promoted user left the roster: {}", |
| 6907 | roster.body |
| 6908 | ); |
| 6909 | |
| 6910 | // Really deleted, not merely filtered out of the listing. |
| 6911 | let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM enrollment") |
| 6912 | .fetch_one(&db) |
| 6913 | .await |
| 6914 | .expect("count enrollments"); |
| 6915 | assert_eq!(rows, 0, "enrollment rows deleted from the DB"); |
| 6916 | } |
| 6917 | |
| 6918 | /// Regression: `db::user::create` pre-checks the username and then inserts, so two |
| 6919 | /// concurrent registrations of the same name could both pass the check; the |
| 6920 | /// loser then hit the unique index and surfaced as a raw 500. A lost race must |
| 6921 | /// answer the same uniform 201 as the winner (the "taken" reply is deliberately |
| 6922 | /// indistinguishable), exactly one account may exist afterwards, and the |
| 6923 | /// winner's password must be the one that works. |
| 6924 | #[tokio::test] |
| 6925 | async fn concurrent_duplicate_registrations_conflict_not_500() { |
| 6926 | let (app, db) = app_and_db().await; |
| 6927 | |
| 6928 | let mut handles = Vec::new(); |
| 6929 | for _ in 0..24 { |
| 6930 | let app = app.clone(); |
| 6931 | handles.push(tokio::spawn(async move { |
| 6932 | send( |
| 6933 | &app, |
| 6934 | "POST", |
| 6935 | "/auth/register", |
| 6936 | None, |
| 6937 | Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "dup", "password": "secret1" })), |
| 6938 | ) |
| 6939 | .await |
| 6940 | .status |
| 6941 | })); |
| 6942 | } |
| 6943 | |
| 6944 | for h in handles { |
| 6945 | let status = h.await.unwrap(); |
| 6946 | assert_eq!( |
| 6947 | status, |
| 6948 | StatusCode::CREATED, |
| 6949 | "a lost race must answer 201 like the winner, not a 500" |
| 6950 | ); |
| 6951 | } |
| 6952 | |
| 6953 | // Exactly one row exists for the name. |
| 6954 | let users: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user WHERE username = 'dup'") |
| 6955 | .fetch_one(&db) |
| 6956 | .await |
| 6957 | .unwrap(); |
| 6958 | assert_eq!(users, 1, "exactly one user row for the duplicated name"); |
| 6959 | |
| 6960 | // And the winner's credentials survived the pile-up: a further duplicate |
| 6961 | // asking for a different password does not replace them. |
| 6962 | let res = send( |
| 6963 | &app, |
| 6964 | "POST", |
| 6965 | "/auth/register", |
| 6966 | None, |
| 6967 | Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "dup", "password": "hijack1" })), |
| 6968 | ) |
| 6969 | .await; |
| 6970 | assert_eq!(res.status, StatusCode::CREATED); |
| 6971 | let res = send( |
| 6972 | &app, |
| 6973 | "POST", |
| 6974 | "/auth/login", |
| 6975 | None, |
| 6976 | Some(json!({ "username": "dup", "password": "secret1" })), |
| 6977 | ) |
| 6978 | .await; |
| 6979 | assert_eq!(res.status, StatusCode::OK, "the winning password broke"); |
| 6980 | let res = send( |
| 6981 | &app, |
| 6982 | "POST", |
| 6983 | "/auth/login", |
| 6984 | None, |
| 6985 | Some(json!({ "username": "dup", "password": "hijack1" })), |
| 6986 | ) |
| 6987 | .await; |
| 6988 | assert_eq!( |
| 6989 | res.status, |
| 6990 | StatusCode::UNAUTHORIZED, |
| 6991 | "a duplicate register overwrote the account" |
| 6992 | ); |
| 6993 | } |
| 6994 | |
| 6995 | /// Regression: listing a child collection of a missing parent used to return an |
| 6996 | /// empty 200 list — indistinguishable from "exists but empty". A missing parent |
| 6997 | /// is a 404, matching the write endpoints on the same paths. |
| 6998 | #[tokio::test] |
| 6999 | async fn child_lists_of_missing_parents_are_404() { |
| 7000 | let (app, db) = app_and_db().await; |
| 7001 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 7002 | |
| 7003 | assert_eq!( |
| 7004 | send(&app, "GET", "/events/nope/attendance", Some(&teacher), None) |
| 7005 | .await |
| 7006 | .status, |
| 7007 | StatusCode::NOT_FOUND |
| 7008 | ); |
| 7009 | assert_eq!( |
| 7010 | send(&app, "GET", "/exams/nope/results", Some(&teacher), None) |
| 7011 | .await |
| 7012 | .status, |
| 7013 | StatusCode::NOT_FOUND |
| 7014 | ); |
| 7015 | assert_eq!( |
| 7016 | send( |
| 7017 | &app, |
| 7018 | "GET", |
| 7019 | "/courses/nope/enrollments", |
| 7020 | Some(&teacher), |
| 7021 | None |
| 7022 | ) |
| 7023 | .await |
| 7024 | .status, |
| 7025 | StatusCode::NOT_FOUND |
| 7026 | ); |
| 7027 | assert_eq!( |
| 7028 | send(&app, "GET", "/courses/nope/exams", Some(&teacher), None) |
| 7029 | .await |
| 7030 | .status, |
| 7031 | StatusCode::NOT_FOUND |
| 7032 | ); |
| 7033 | assert_eq!( |
| 7034 | send(&app, "GET", "/exams/nope/statistics", Some(&teacher), None) |
| 7035 | .await |
| 7036 | .status, |
| 7037 | StatusCode::NOT_FOUND |
| 7038 | ); |
| 7039 | assert_eq!( |
| 7040 | send(&app, "GET", "/marks/ghost", Some(&teacher), None) |
| 7041 | .await |
| 7042 | .status, |
| 7043 | StatusCode::NOT_FOUND |
| 7044 | ); |
| 7045 | } |
| 7046 | |
| 7047 | /// Regression: the session cookie never carried the `Secure` attribute, so a |
| 7048 | /// TLS deployment would let browsers replay it over plain HTTP. The attribute |
| 7049 | /// now follows `COOKIE_SECURE` (`Config::cookie_secure`); the default stays off |
| 7050 | /// so plain-HTTP local dev keeps working. |
| 7051 | #[tokio::test] |
| 7052 | async fn session_cookie_secure_attribute_follows_config() { |
| 7053 | async fn login_set_cookie(app: &axum::Router) -> String { |
| 7054 | let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ada", "password": "secret1" }); |
| 7055 | assert_eq!( |
| 7056 | send(app, "POST", "/auth/register", None, Some(creds)) |
| 7057 | .await |
| 7058 | .status, |
| 7059 | StatusCode::CREATED |
| 7060 | ); |
| 7061 | let login = json!({ "username": "ada", "password": "secret1" }); |
| 7062 | let req = Request::builder() |
| 7063 | .method("POST") |
| 7064 | .uri("/auth/login") |
| 7065 | .header("content-type", "application/json") |
| 7066 | .body(Body::from(login.to_string())) |
| 7067 | .unwrap(); |
| 7068 | let res = app.clone().oneshot(req).await.unwrap(); |
| 7069 | assert_eq!(res.status(), StatusCode::OK); |
| 7070 | res.headers() |
| 7071 | .get("set-cookie") |
| 7072 | .unwrap() |
| 7073 | .to_str() |
| 7074 | .unwrap() |
| 7075 | .to_string() |
| 7076 | } |
| 7077 | |
| 7078 | // Default (dev): HttpOnly but not Secure. |
| 7079 | let plain = login_set_cookie(&mem_app().await).await; |
| 7080 | assert!( |
| 7081 | plain.contains("HttpOnly"), |
| 7082 | "cookie must stay HttpOnly: {plain}" |
| 7083 | ); |
| 7084 | assert!( |
| 7085 | !plain.contains("Secure"), |
| 7086 | "dev cookie must not be Secure: {plain}" |
| 7087 | ); |
| 7088 | // SameSite=Lax is the cookie-side half of the CORS defense: dev mirror |
| 7089 | // mode (see `cors_layer`) is only safe as long as this cookie never rides |
| 7090 | // cross-site requests. |
| 7091 | assert!( |
| 7092 | plain.contains("SameSite=Lax"), |
| 7093 | "cookie must stay SameSite=Lax: {plain}" |
| 7094 | ); |
| 7095 | |
| 7096 | // With the flag on: Secure present. |
| 7097 | let (tenants, _db) = common::mem_deployment().await; |
| 7098 | let app = build_router(AppState { |
| 7099 | db: tenants.control().clone(), |
| 7100 | tenants, |
| 7101 | files_path: common::files_dir(), |
| 7102 | cookie_secure: true, |
| 7103 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| 7104 | chatbot_limit: Default::default(), |
| 7105 | rag_limit: Default::default(), |
| 7106 | exam_presence: Default::default(), |
| 7107 | board_hub: Default::default(), |
| 7108 | ai: None, |
| 7109 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 7110 | }); |
| 7111 | let secure = login_set_cookie(&app).await; |
| 7112 | assert!( |
| 7113 | secure.contains("Secure"), |
| 7114 | "cookie must be Secure when configured: {secure}" |
| 7115 | ); |
| 7116 | assert!( |
| 7117 | secure.contains("HttpOnly"), |
| 7118 | "Secure must not displace HttpOnly: {secure}" |
| 7119 | ); |
| 7120 | } |
| 7121 | |
| 7122 | /// A request issued against a closed pool does not wait — the acquire fails at |
| 7123 | /// once and the error is classified as "nothing executed" (`PoolClosed` → |
| 7124 | /// `DbUnavailable`), so the 503 advertises a safe retry. A closed school pool |
| 7125 | /// is the honest stand-in for an unreachable socket: no statement can even be |
| 7126 | /// sent, which is what makes "nothing was written" true by construction. |
| 7127 | #[tokio::test] |
| 7128 | async fn db_down_refuses_before_touching_the_database() { |
| 7129 | async fn count_rows(db: &hezarfen_backend::database::Database, table: &str) -> i64 { |
| 7130 | sqlx::query_scalar::<sqlx::Postgres, i64>(sqlx::AssertSqlSafe(format!( |
| 7131 | "SELECT count(*) FROM {table}" |
| 7132 | ))) |
| 7133 | .fetch_one(db) |
| 7134 | .await |
| 7135 | .expect("count query") |
| 7136 | } |
| 7137 | |
| 7138 | let (tenants, db) = common::mem_deployment().await; |
| 7139 | let app = build_router(AppState { |
| 7140 | db: tenants.control().clone(), |
| 7141 | tenants: tenants.clone(), |
| 7142 | files_path: common::files_dir(), |
| 7143 | cookie_secure: false, |
| 7144 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| 7145 | chatbot_limit: Default::default(), |
| 7146 | rag_limit: Default::default(), |
| 7147 | exam_presence: Default::default(), |
| 7148 | board_hub: Default::default(), |
| 7149 | ai: None, |
| 7150 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 7151 | }); |
| 7152 | |
| 7153 | // Healthy: a login against the seeded user reaches the handler as usual. |
| 7154 | let before: i64 = count_rows(&db, "app_user").await; |
| 7155 | let ok = app |
| 7156 | .clone() |
| 7157 | .oneshot( |
| 7158 | Request::builder() |
| 7159 | .method("POST") |
| 7160 | .uri("/auth/register") |
| 7161 | .header("content-type", "application/json") |
| 7162 | .body(Body::from( |
| 7163 | json!({"school": "019732e3-7b00-7000-8000-00000000dead", "username": "gulsah", "password": "sifre12345"}) |
| 7164 | .to_string(), |
| 7165 | )) |
| 7166 | .unwrap(), |
| 7167 | ) |
| 7168 | .await |
| 7169 | .unwrap(); |
| 7170 | assert_eq!(ok.status(), StatusCode::CREATED); |
| 7171 | assert_eq!( |
| 7172 | count_rows(&db, "app_user").await, |
| 7173 | before + 1, |
| 7174 | "the write landed" |
| 7175 | ); |
| 7176 | |
| 7177 | // Pool closed: refused with a retryable 503. |
| 7178 | db.close().await; |
| 7179 | let refused = app |
| 7180 | .clone() |
| 7181 | .oneshot( |
| 7182 | Request::builder() |
| 7183 | .method("POST") |
| 7184 | .uri("/auth/register") |
| 7185 | .header("content-type", "application/json") |
| 7186 | .body(Body::from( |
| 7187 | json!({"school": "019732e3-7b00-7000-8000-00000000dead", "username": "kerem", "password": "sifre12345"}) |
| 7188 | .to_string(), |
| 7189 | )) |
| 7190 | .unwrap(), |
| 7191 | ) |
| 7192 | .await |
| 7193 | .unwrap(); |
| 7194 | assert_eq!(refused.status(), StatusCode::SERVICE_UNAVAILABLE); |
| 7195 | assert_eq!( |
| 7196 | refused.headers().get("retry-after").unwrap(), |
| 7197 | "1", |
| 7198 | "a pre-execution refusal must advertise that retrying is safe" |
| 7199 | ); |
| 7200 | |
| 7201 | // Recovery is eviction: the dead pool leaves the cache, the next request |
| 7202 | // dials fresh — and the refused write is still not in the database. |
| 7203 | let demo_id: Uuid = sqlx::query_scalar("SELECT id FROM school WHERE id = '019732e3-7b00-7000-8000-00000000dead'") |
| 7204 | .fetch_one(tenants.control()) |
| 7205 | .await |
| 7206 | .expect("demo id"); |
| 7207 | let slug = SchoolId::try_parse(hezarfen_backend::tenant::DEMO_SCHOOL_ID).expect("slug"); |
| 7208 | tenants |
| 7209 | .evict(hezarfen_backend::tenant::SchoolId::from_uuid(demo_id)) |
| 7210 | .await; |
| 7211 | let live = tenants.get(&slug).await.expect("redial after eviction"); |
| 7212 | assert_eq!( |
| 7213 | count_rows(&live, "app_user").await, |
| 7214 | before + 1, |
| 7215 | "a refused request must not have reached the database" |
| 7216 | ); |
| 7217 | let healed = app |
| 7218 | .oneshot( |
| 7219 | Request::builder() |
| 7220 | .method("POST") |
| 7221 | .uri("/auth/register") |
| 7222 | .header("content-type", "application/json") |
| 7223 | .body(Body::from( |
| 7224 | json!({"school": "019732e3-7b00-7000-8000-00000000dead", "username": "kerem", "password": "sifre12345"}) |
| 7225 | .to_string(), |
| 7226 | )) |
| 7227 | .unwrap(), |
| 7228 | ) |
| 7229 | .await |
| 7230 | .unwrap(); |
| 7231 | assert_eq!(healed.status(), StatusCode::CREATED); |
| 7232 | assert_eq!(count_rows(&live, "app_user").await, before + 2); |
| 7233 | } |
| 7234 | |
| 7235 | /// Regression: PATCH could set an event's times but never clear them — a JSON |
| 7236 | /// `null` was indistinguishable from an omitted field and silently kept the old |
| 7237 | /// value. An explicit `null` now clears the field; omitted still keeps it. |
| 7238 | #[tokio::test] |
| 7239 | async fn patch_null_clears_event_times() { |
| 7240 | let (app, db) = app_and_db().await; |
| 7241 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 7242 | let now = Timestamp::now().as_millis(); |
| 7243 | let starts = now + 3_600_000; |
| 7244 | let ends = now + 7_200_000; |
| 7245 | let event_id = id_of( |
| 7246 | &send( |
| 7247 | &app, |
| 7248 | "POST", |
| 7249 | "/events", |
| 7250 | Some(&ali), |
| 7251 | Some(json!({"title":"mtg","starts_at": starts,"ends_at": ends})), |
| 7252 | ) |
| 7253 | .await |
| 7254 | .body, |
| 7255 | ); |
| 7256 | |
| 7257 | // Omitted fields still keep their values. |
| 7258 | let res = send( |
| 7259 | &app, |
| 7260 | "PATCH", |
| 7261 | &format!("/events/{event_id}"), |
| 7262 | Some(&ali), |
| 7263 | Some(json!({"title":"mtg2"})), |
| 7264 | ) |
| 7265 | .await; |
| 7266 | assert_eq!(res.body["starts_at"], starts); |
| 7267 | assert_eq!(res.body["ends_at"], ends); |
| 7268 | |
| 7269 | // An explicit null clears just that field. |
| 7270 | let res = send( |
| 7271 | &app, |
| 7272 | "PATCH", |
| 7273 | &format!("/events/{event_id}"), |
| 7274 | Some(&ali), |
| 7275 | Some(json!({"ends_at": null})), |
| 7276 | ) |
| 7277 | .await; |
| 7278 | assert_eq!(res.status, StatusCode::OK); |
| 7279 | assert_eq!(res.body["starts_at"], starts); |
| 7280 | assert!(res.body["ends_at"].is_null()); |
| 7281 | |
| 7282 | // With ends_at cleared, moving starts_at past the old end is legal... |
| 7283 | assert_eq!( |
| 7284 | send( |
| 7285 | &app, |
| 7286 | "PATCH", |
| 7287 | &format!("/events/{event_id}"), |
| 7288 | Some(&ali), |
| 7289 | Some(json!({"starts_at": now + 9_000_000})) |
| 7290 | ) |
| 7291 | .await |
| 7292 | .status, |
| 7293 | StatusCode::OK |
| 7294 | ); |
| 7295 | // ...and a new ends_at before starts_at is still rejected. |
| 7296 | assert_eq!( |
| 7297 | send( |
| 7298 | &app, |
| 7299 | "PATCH", |
| 7300 | &format!("/events/{event_id}"), |
| 7301 | Some(&ali), |
| 7302 | Some(json!({"ends_at": now + 1_000_000})) |
| 7303 | ) |
| 7304 | .await |
| 7305 | .status, |
| 7306 | StatusCode::BAD_REQUEST |
| 7307 | ); |
| 7308 | |
| 7309 | // Clearing both works. |
| 7310 | let res = send( |
| 7311 | &app, |
| 7312 | "PATCH", |
| 7313 | &format!("/events/{event_id}"), |
| 7314 | Some(&ali), |
| 7315 | Some(json!({"starts_at": null, "ends_at": null})), |
| 7316 | ) |
| 7317 | .await; |
| 7318 | assert!(res.body["starts_at"].is_null()); |
| 7319 | assert!(res.body["ends_at"].is_null()); |
| 7320 | } |
| 7321 | |
| 7322 | /// #4 — mirror mode (no `CORS_ALLOWED_ORIGINS`) reflects the caller's origin, |
| 7323 | /// never `*`, but must NOT advertise credentials: reflecting arbitrary origins |
| 7324 | /// with credentials would let any website ride a visitor's session cookie. |
| 7325 | #[tokio::test] |
| 7326 | async fn cors_mirror_mode_reflects_origin_without_credentials() { |
| 7327 | let app = mem_app().await; |
| 7328 | let req = Request::builder() |
| 7329 | .method("GET") |
| 7330 | .uri("/health") |
| 7331 | .header("origin", "https://evil.example") |
| 7332 | .body(Body::empty()) |
| 7333 | .unwrap(); |
| 7334 | let res = app.oneshot(req).await.unwrap(); |
| 7335 | let headers = res.headers(); |
| 7336 | assert_eq!( |
| 7337 | headers.get("access-control-allow-origin").unwrap(), |
| 7338 | "https://evil.example", |
| 7339 | "origin must be reflected, not wildcarded" |
| 7340 | ); |
| 7341 | // tower-http omits the header entirely when credentials are off. |
| 7342 | assert!( |
| 7343 | headers.get("access-control-allow-credentials").is_none(), |
| 7344 | "mirror mode must never send allow-credentials" |
| 7345 | ); |
| 7346 | } |
| 7347 | |
| 7348 | /// Allowlist mode: a listed origin gets both the origin echo and |
| 7349 | /// `allow-credentials: true`; an unlisted origin gets no origin header at all. |
| 7350 | /// `cors_layer` takes the allowlist as a parameter, so this needs no |
| 7351 | /// process-global env mutation (which would race other tests). |
| 7352 | #[tokio::test] |
| 7353 | async fn cors_allowlist_mode_credits_only_listed_origins() { |
| 7354 | async fn probe(origin: &str) -> axum::http::HeaderMap { |
| 7355 | let app = axum::Router::new() |
| 7356 | .route("/ping", axum::routing::get(|| async { "pong" })) |
| 7357 | .layer(hezarfen_backend::cors_layer(vec![ |
| 7358 | "https://app.example".parse().unwrap(), |
| 7359 | ])); |
| 7360 | let req = Request::builder() |
| 7361 | .method("GET") |
| 7362 | .uri("/ping") |
| 7363 | .header("origin", origin) |
| 7364 | .body(Body::empty()) |
| 7365 | .unwrap(); |
| 7366 | app.oneshot(req).await.unwrap().headers().clone() |
| 7367 | } |
| 7368 | |
| 7369 | let listed = probe("https://app.example").await; |
| 7370 | assert_eq!( |
| 7371 | listed.get("access-control-allow-origin").unwrap(), |
| 7372 | "https://app.example", |
| 7373 | ); |
| 7374 | assert_eq!( |
| 7375 | listed.get("access-control-allow-credentials").unwrap(), |
| 7376 | "true", |
| 7377 | "the allowlisted origin must keep credentialed CORS" |
| 7378 | ); |
| 7379 | |
| 7380 | let unlisted = probe("https://evil.example").await; |
| 7381 | assert!( |
| 7382 | unlisted.get("access-control-allow-origin").is_none(), |
| 7383 | "an unlisted origin must not be echoed" |
| 7384 | ); |
| 7385 | } |
| 7386 | |
| 7387 | /// Star mode (`CORS_ALLOWED_ORIGINS=*`): every origin is reflected AND |
| 7388 | /// credentialed — the deliberate "anywhere, for now" mode for a deployment |
| 7389 | /// whose frontend origins are not settled. `SameSite=Lax` (pinned by its own |
| 7390 | /// test above) is what keeps third-party sites from riding the cookie |
| 7391 | /// cross-site; this opens the door to same-site origins only. |
| 7392 | #[tokio::test] |
| 7393 | async fn cors_star_mode_reflects_any_origin_with_credentials() { |
| 7394 | async fn probe(origin: &str) -> axum::http::HeaderMap { |
| 7395 | let app = axum::Router::new() |
| 7396 | .route("/ping", axum::routing::get(|| async { "pong" })) |
| 7397 | .layer(hezarfen_backend::cors_layer(vec!["*".parse().unwrap()])); |
| 7398 | let req = Request::builder() |
| 7399 | .method("GET") |
| 7400 | .uri("/ping") |
| 7401 | .header("origin", origin) |
| 7402 | .body(Body::empty()) |
| 7403 | .unwrap(); |
| 7404 | app.oneshot(req).await.unwrap().headers().clone() |
| 7405 | } |
| 7406 | |
| 7407 | let any = probe("https://frontends.example").await; |
| 7408 | assert_eq!( |
| 7409 | any.get("access-control-allow-origin").unwrap(), |
| 7410 | "https://frontends.example", |
| 7411 | "star mode must reflect the caller's origin, never the literal `*`" |
| 7412 | ); |
| 7413 | assert_eq!( |
| 7414 | any.get("access-control-allow-credentials").unwrap(), |
| 7415 | "true", |
| 7416 | "star mode exists so unlisted frontends can send the session cookie" |
| 7417 | ); |
| 7418 | |
| 7419 | let other = probe("https://anything-else.example").await; |
| 7420 | assert_eq!( |
| 7421 | other.get("access-control-allow-origin").unwrap(), |
| 7422 | "https://anything-else.example", |
| 7423 | "every origin qualifies in star mode, not just the first one seen" |
| 7424 | ); |
| 7425 | } |
| 7426 | |
| 7427 | /// Both CORS modes share one layer base, so a single probe proves the exposed |
| 7428 | /// headers: without them, cross-origin JS reads `null` for the documented |
| 7429 | /// `Retry-After` (429s) and `Content-Disposition` (download filename) headers. |
| 7430 | #[tokio::test] |
| 7431 | async fn cors_exposes_retry_after_and_content_disposition() { |
| 7432 | let app = mem_app().await; |
| 7433 | let req = Request::builder() |
| 7434 | .method("GET") |
| 7435 | .uri("/health") |
| 7436 | .header("origin", "https://app.example") |
| 7437 | .body(Body::empty()) |
| 7438 | .unwrap(); |
| 7439 | let res = app.oneshot(req).await.unwrap(); |
| 7440 | assert_eq!( |
| 7441 | res.headers().get("access-control-expose-headers").unwrap(), |
| 7442 | "retry-after,content-disposition", |
| 7443 | "contract headers must be readable by cross-origin JS" |
| 7444 | ); |
| 7445 | } |
| 7446 | |
| 7447 | // --- admin seed (ADMIN_USERNAME / ADMIN_PASSWORD bootstrap) ---------------- |
| 7448 | |
| 7449 | /// The seed creates a ready-to-use admin: login works with the configured |
| 7450 | /// credentials and the account can reach admin-only endpoints immediately. |
| 7451 | #[tokio::test] |
| 7452 | async fn admin_seed_creates_working_admin() { |
| 7453 | let (app, _db, tenants) = app_and_tenants().await; |
| 7454 | let username = Username::try_new("root").unwrap(); |
| 7455 | let password = Password::try_new("secret1").unwrap(); |
| 7456 | hezarfen_backend::service::user::ensure_admin( |
| 7457 | &tenants, |
| 7458 | &hezarfen_backend::tenant::SchoolId::try_parse(hezarfen_backend::tenant::DEMO_SCHOOL_ID).unwrap(), |
| 7459 | username, |
| 7460 | password, |
| 7461 | ) |
| 7462 | .await |
| 7463 | .unwrap(); |
| 7464 | |
| 7465 | let creds = json!({ "username": "root", "password": "secret1" }); |
| 7466 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 7467 | assert_eq!(res.status, StatusCode::OK); |
| 7468 | assert_eq!(res.body["role"], "admin"); |
| 7469 | |
| 7470 | let cookie = res.cookie.expect("session cookie"); |
| 7471 | let res = send(&app, "GET", "/users", Some(&cookie), None).await; |
| 7472 | assert_eq!(res.status, StatusCode::OK, "admin-only listing must open"); |
| 7473 | } |
| 7474 | |
| 7475 | /// Re-running the seed (every boot does) must not duplicate the account, |
| 7476 | /// demote it, or overwrite its password. |
| 7477 | #[tokio::test] |
| 7478 | async fn admin_seed_is_idempotent() { |
| 7479 | let (app, _db, tenants) = app_and_tenants().await; |
| 7480 | for _ in 0..2 { |
| 7481 | let username = Username::try_new("root").unwrap(); |
| 7482 | let password = Password::try_new("secret1").unwrap(); |
| 7483 | hezarfen_backend::service::user::ensure_admin( |
| 7484 | &tenants, |
| 7485 | &hezarfen_backend::tenant::SchoolId::try_parse(hezarfen_backend::tenant::DEMO_SCHOOL_ID).unwrap(), |
| 7486 | username, |
| 7487 | password, |
| 7488 | ) |
| 7489 | .await |
| 7490 | .unwrap(); |
| 7491 | } |
| 7492 | |
| 7493 | let cookie = { |
| 7494 | let creds = json!({ "username": "root", "password": "secret1" }); |
| 7495 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 7496 | assert_eq!(res.status, StatusCode::OK); |
| 7497 | res.cookie.expect("session cookie") |
| 7498 | }; |
| 7499 | let res = send(&app, "GET", "/users", Some(&cookie), None).await; |
| 7500 | let listed = common::items(&res.body); |
| 7501 | assert_eq!(listed.len(), 1, "seed must not duplicate the account"); |
| 7502 | assert_eq!(listed[0]["role"], "admin"); |
| 7503 | } |
| 7504 | |
| 7505 | /// A username already registered by someone else is never promoted (or its |
| 7506 | /// password replaced) by the seed — that would be privilege escalation. |
| 7507 | #[tokio::test] |
| 7508 | async fn admin_seed_refuses_existing_non_admin() { |
| 7509 | let (app, _db, tenants) = app_and_tenants().await; |
| 7510 | let cookie = login(&app, "squatter").await; // registers with password `secret1` |
| 7511 | |
| 7512 | let username = Username::try_new("squatter").unwrap(); |
| 7513 | let password = Password::try_new("attacker-pw").unwrap(); |
| 7514 | hezarfen_backend::service::user::ensure_admin( |
| 7515 | &tenants, |
| 7516 | &hezarfen_backend::tenant::SchoolId::try_parse(hezarfen_backend::tenant::DEMO_SCHOOL_ID).unwrap(), |
| 7517 | username, |
| 7518 | password, |
| 7519 | ) |
| 7520 | .await |
| 7521 | .unwrap(); |
| 7522 | |
| 7523 | // Still a student: the admin-only listing stays closed... |
| 7524 | let res = send(&app, "GET", "/users", Some(&cookie), None).await; |
| 7525 | assert_eq!(res.status, StatusCode::FORBIDDEN, "must not be promoted"); |
| 7526 | |
| 7527 | // ...and the original password still logs in (nothing was overwritten). |
| 7528 | let creds = json!({ "username": "squatter", "password": "secret1" }); |
| 7529 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 7530 | assert_eq!(res.status, StatusCode::OK); |
| 7531 | assert_eq!(res.body["role"], "student"); |
| 7532 | } |
| 7533 | |
| 7534 | // --- scheduled exams: sync/async attempts + the live monitor --------------- |
| 7535 | |
| 7536 | /// Create a scheduled exam inside `instance` from a full body (which carries |
| 7537 | /// its own `term`) and return its id (asserts 201). |
| 7538 | async fn scheduled_exam( |
| 7539 | app: &axum::Router, |
| 7540 | cookie: &str, |
| 7541 | instance: &str, |
| 7542 | body: serde_json::Value, |
| 7543 | ) -> String { |
| 7544 | let res = create_exam_with(app, cookie, instance, body).await; |
| 7545 | assert_eq!( |
| 7546 | res.status, |
| 7547 | StatusCode::CREATED, |
| 7548 | "create scheduled exam: {}", |
| 7549 | res.body |
| 7550 | ); |
| 7551 | id_of(&res.body) |
| 7552 | } |
| 7553 | |
| 7554 | /// The kinds this section's probes write with, installed as the school's own |
| 7555 | /// list: exam kinds are settings now (the shipped defaults are |
| 7556 | /// yazili/sozlu/uygulama) and an exam of a kind the school does not list is a |
| 7557 | /// 400. Asserted 200, so a broken settings PATCH fails here, not as a puzzling |
| 7558 | /// 400 three lines later. |
| 7559 | async fn scheduling_kinds(app: &axum::Router, manager: &str) { |
| 7560 | let res = send( |
| 7561 | app, |
| 7562 | "PATCH", |
| 7563 | "/settings", |
| 7564 | Some(manager), |
| 7565 | Some(json!({ "exam_kinds": [ |
| 7566 | {"name": "quiz", "weight": 1}, |
| 7567 | {"name": "midterm", "weight": 1}, |
| 7568 | {"name": "homework", "weight": 1}, |
| 7569 | {"name": "final", "weight": 1}, |
| 7570 | ]})), |
| 7571 | ) |
| 7572 | .await; |
| 7573 | assert_eq!(res.status, StatusCode::OK, "install kinds: {}", res.body); |
| 7574 | } |
| 7575 | |
| 7576 | #[tokio::test] |
| 7577 | async fn exam_scheduling_validates_and_echoes() { |
| 7578 | let (app, db) = app_and_db().await; |
| 7579 | let teacher = login_as(&app, &db, "sched_t", "teacher").await; |
| 7580 | let mudur = login_as(&app, &db, "sched_m", "manager").await; |
| 7581 | scheduling_kinds(&app, &mudur).await; |
| 7582 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 7583 | let now = Timestamp::now().as_millis(); |
| 7584 | |
| 7585 | // Sync: the window is echoed, no duration. |
| 7586 | let res = create_exam_with( |
| 7587 | &app, |
| 7588 | &teacher, |
| 7589 | &t.instance, |
| 7590 | json!({ |
| 7591 | "term": &t.term, "title": "midterm", "kind": "midterm", |
| 7592 | "mode": "sync", "starts_at": now + 60_000, "ends_at": now + 120_000, |
| 7593 | }), |
| 7594 | ) |
| 7595 | .await; |
| 7596 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 7597 | assert_eq!(res.body["mode"], "sync"); |
| 7598 | assert_eq!(res.body["starts_at"].as_i64(), Some(now + 60_000)); |
| 7599 | assert_eq!(res.body["ends_at"].as_i64(), Some(now + 120_000)); |
| 7600 | assert!(res.body["duration_ms"].is_null()); |
| 7601 | |
| 7602 | // Async: adds the per-student duration. |
| 7603 | let res = create_exam_with( |
| 7604 | &app, |
| 7605 | &teacher, |
| 7606 | &t.instance, |
| 7607 | json!({ |
| 7608 | "term": &t.term, "title": "takehome", "kind": "quiz", |
| 7609 | "mode": "async", "starts_at": now, "ends_at": now + 7_200_000, |
| 7610 | "duration_ms": 5_400_000, |
| 7611 | }), |
| 7612 | ) |
| 7613 | .await; |
| 7614 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 7615 | assert_eq!(res.body["mode"], "async"); |
| 7616 | assert_eq!(res.body["duration_ms"].as_i64(), Some(5_400_000)); |
| 7617 | |
| 7618 | // Async: a duration exactly as long as the window is fine — only |
| 7619 | // strictly exceeding it is rejected (see "duration exceeds window" below). |
| 7620 | scheduled_exam( |
| 7621 | &app, |
| 7622 | &teacher, |
| 7623 | &t.instance, |
| 7624 | json!({ |
| 7625 | "term": &t.term, "title": "exact-fit", "kind": "quiz", |
| 7626 | "mode": "async", "starts_at": now, "ends_at": now + 3_600_000, |
| 7627 | "duration_ms": 3_600_000, |
| 7628 | }), |
| 7629 | ) |
| 7630 | .await; |
| 7631 | |
| 7632 | // Unscheduled: every schedule field stays null (pre-schedule behavior), |
| 7633 | // and the attempt policy shows its defaults. |
| 7634 | let res = create_exam_with( |
| 7635 | &app, |
| 7636 | &teacher, |
| 7637 | &t.instance, |
| 7638 | json!({ "term": &t.term, "title": "homework", "kind": "homework" }), |
| 7639 | ) |
| 7640 | .await; |
| 7641 | assert_eq!(res.status, StatusCode::CREATED); |
| 7642 | assert!(res.body["mode"].is_null()); |
| 7643 | assert!(res.body["starts_at"].is_null()); |
| 7644 | assert!(res.body["ends_at"].is_null()); |
| 7645 | assert!(res.body["duration_ms"].is_null()); |
| 7646 | assert_eq!(res.body["max_attempts"], 1); |
| 7647 | assert_eq!(res.body["allow_rejoin"], true); |
| 7648 | |
| 7649 | // Open: no window at all; an optional per-attempt duration is fine, and |
| 7650 | // the attempt policy echoes what was asked for. |
| 7651 | let res = create_exam_with( |
| 7652 | &app, |
| 7653 | &teacher, |
| 7654 | &t.instance, |
| 7655 | json!({ |
| 7656 | "term": &t.term, "title": "practice", "kind": "quiz", "mode": "open", |
| 7657 | "duration_ms": 5_400_000, "max_attempts": 0, "allow_rejoin": false, |
| 7658 | }), |
| 7659 | ) |
| 7660 | .await; |
| 7661 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 7662 | assert_eq!(res.body["mode"], "open"); |
| 7663 | assert!(res.body["starts_at"].is_null()); |
| 7664 | assert!(res.body["ends_at"].is_null()); |
| 7665 | assert_eq!(res.body["duration_ms"].as_i64(), Some(5_400_000)); |
| 7666 | assert_eq!(res.body["max_attempts"], 0); |
| 7667 | assert_eq!(res.body["allow_rejoin"], false); |
| 7668 | |
| 7669 | // Inconsistent schedules are rejected as a unit. |
| 7670 | for (label, body) in [ |
| 7671 | ( |
| 7672 | "unknown mode", |
| 7673 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "weekly", |
| 7674 | "starts_at": now, "ends_at": now + 1_000 }), |
| 7675 | ), |
| 7676 | ( |
| 7677 | "times without mode", |
| 7678 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "starts_at": now }), |
| 7679 | ), |
| 7680 | ( |
| 7681 | "duration without mode", |
| 7682 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "duration_ms": 60_000 }), |
| 7683 | ), |
| 7684 | ( |
| 7685 | "sync missing ends_at", |
| 7686 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "sync", |
| 7687 | "starts_at": now }), |
| 7688 | ), |
| 7689 | ( |
| 7690 | "sync with duration", |
| 7691 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "sync", |
| 7692 | "starts_at": now, "ends_at": now + 1_000, "duration_ms": 60_000 }), |
| 7693 | ), |
| 7694 | ( |
| 7695 | "async without duration", |
| 7696 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "async", |
| 7697 | "starts_at": now, "ends_at": now + 1_000 }), |
| 7698 | ), |
| 7699 | ( |
| 7700 | "backwards window", |
| 7701 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "sync", |
| 7702 | "starts_at": now + 2_000, "ends_at": now + 1_000 }), |
| 7703 | ), |
| 7704 | ( |
| 7705 | "empty window", |
| 7706 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "sync", |
| 7707 | "starts_at": now, "ends_at": now }), |
| 7708 | ), |
| 7709 | ( |
| 7710 | "duration too short", |
| 7711 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "async", |
| 7712 | "starts_at": now, "ends_at": now + 90_000_000, "duration_ms": 59_999 }), |
| 7713 | ), |
| 7714 | ( |
| 7715 | "duration too long", |
| 7716 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "async", |
| 7717 | "starts_at": now, "ends_at": now + 90_000_000, "duration_ms": 86_400_001 }), |
| 7718 | ), |
| 7719 | ( |
| 7720 | // Within the global 1min-24h bounds, but longer than its own |
| 7721 | // window: a 90-minute duration inside a 60-minute window. |
| 7722 | "duration exceeds window", |
| 7723 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "async", |
| 7724 | "starts_at": now, "ends_at": now + 3_600_000, "duration_ms": 5_400_000 }), |
| 7725 | ), |
| 7726 | ( |
| 7727 | "past starts_at", |
| 7728 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "sync", |
| 7729 | "starts_at": now - 3_600_000, "ends_at": now + 3_600_000 }), |
| 7730 | ), |
| 7731 | ( |
| 7732 | // starts_at is future so the rejection can only come from ends_at. |
| 7733 | "past ends_at", |
| 7734 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "sync", |
| 7735 | "starts_at": now + 3_600_000, "ends_at": now - 3_600_000 }), |
| 7736 | ), |
| 7737 | ( |
| 7738 | "open with a window", |
| 7739 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "open", |
| 7740 | "starts_at": now + 60_000, "ends_at": now + 120_000 }), |
| 7741 | ), |
| 7742 | ( |
| 7743 | "open with only an ends_at", |
| 7744 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "mode": "open", |
| 7745 | "ends_at": now + 120_000 }), |
| 7746 | ), |
| 7747 | ( |
| 7748 | "negative attempt limit", |
| 7749 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "max_attempts": -1 }), |
| 7750 | ), |
| 7751 | ( |
| 7752 | "attempt limit over the cap", |
| 7753 | json!({ "term": &t.term, "title": "x", "kind": "quiz", "max_attempts": 101 }), |
| 7754 | ), |
| 7755 | ] { |
| 7756 | let res = create_exam_with(&app, &teacher, &t.instance, body).await; |
| 7757 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{label}: {}", res.body); |
| 7758 | } |
| 7759 | } |
| 7760 | |
| 7761 | /// Nothing can be scheduled to start (or end) in the past — on create and on |
| 7762 | /// any PATCH that sets a time. Values a PATCH merely keeps are exempt, so a |
| 7763 | /// running exam (its `starts_at` naturally behind the clock) stays editable. |
| 7764 | #[tokio::test] |
| 7765 | async fn schedule_times_cannot_be_backdated() { |
| 7766 | let (app, db) = app_and_db().await; |
| 7767 | let teacher = login_as(&app, &db, "past_t", "teacher").await; |
| 7768 | let mudur = login_as(&app, &db, "past_m", "manager").await; |
| 7769 | scheduling_kinds(&app, &mudur).await; |
| 7770 | let t = taught_under(&app, &mudur, &teacher, "history").await; |
| 7771 | let now = Timestamp::now().as_millis(); |
| 7772 | |
| 7773 | // A running exam: started seconds ago (inside the clock-skew grace). |
| 7774 | let exam = scheduled_exam( |
| 7775 | &app, |
| 7776 | &teacher, |
| 7777 | &t.instance, |
| 7778 | json!({ "term": &t.term, "title": "running", "kind": "quiz", |
| 7779 | "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), |
| 7780 | ) |
| 7781 | .await; |
| 7782 | |
| 7783 | // Setting either time to the past is rejected... |
| 7784 | for body in [ |
| 7785 | json!({ "starts_at": now - 3_600_000 }), |
| 7786 | json!({ "ends_at": now - 3_600_000 }), |
| 7787 | ] { |
| 7788 | let res = send( |
| 7789 | &app, |
| 7790 | "PATCH", |
| 7791 | &format!("/exams/{exam}"), |
| 7792 | Some(&teacher), |
| 7793 | Some(body), |
| 7794 | ) |
| 7795 | .await; |
| 7796 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 7797 | } |
| 7798 | |
| 7799 | // ...while edits that only keep the stored (already past) start work: |
| 7800 | // a rename, and a deadline extension. |
| 7801 | let res = send( |
| 7802 | &app, |
| 7803 | "PATCH", |
| 7804 | &format!("/exams/{exam}"), |
| 7805 | Some(&teacher), |
| 7806 | Some(json!({ "term": &t.term, "title": "renamed" })), |
| 7807 | ) |
| 7808 | .await; |
| 7809 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 7810 | let res = send( |
| 7811 | &app, |
| 7812 | "PATCH", |
| 7813 | &format!("/exams/{exam}"), |
| 7814 | Some(&teacher), |
| 7815 | Some(json!({ "ends_at": now + 1_200_000 })), |
| 7816 | ) |
| 7817 | .await; |
| 7818 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 7819 | assert_eq!(res.body["ends_at"].as_i64(), Some(now + 1_200_000)); |
| 7820 | |
| 7821 | // The grace is real: times well inside it (30s < 60s) are accepted, on |
| 7822 | // create and on PATCH alike. |
| 7823 | let res = create_exam_with( |
| 7824 | &app, |
| 7825 | &teacher, |
| 7826 | &t.instance, |
| 7827 | json!({ "term": &t.term, "title": "graced", "kind": "quiz", |
| 7828 | "mode": "sync", "starts_at": now - 30_000, "ends_at": now + 600_000 }), |
| 7829 | ) |
| 7830 | .await; |
| 7831 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 7832 | let graced = id_of(&res.body); |
| 7833 | let res = send( |
| 7834 | &app, |
| 7835 | "PATCH", |
| 7836 | &format!("/exams/{graced}"), |
| 7837 | Some(&teacher), |
| 7838 | Some(json!({ "starts_at": now - 20_000 })), |
| 7839 | ) |
| 7840 | .await; |
| 7841 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 7842 | } |
| 7843 | |
| 7844 | #[tokio::test] |
| 7845 | async fn sync_attempt_lifecycle_feeds_the_live_monitor() { |
| 7846 | let (app, db) = app_and_db().await; |
| 7847 | let teacher = login_as(&app, &db, "live_t", "teacher").await; |
| 7848 | let ayse = login(&app, "ayse").await; |
| 7849 | let veli = login(&app, "veli").await; |
| 7850 | let ayse_id = me_id(&app, &ayse).await; |
| 7851 | let veli_id = me_id(&app, &veli).await; |
| 7852 | let mudur = login_as(&app, &db, "live_m", "manager").await; |
| 7853 | scheduling_kinds(&app, &mudur).await; |
| 7854 | let t = taught_under(&app, &mudur, &teacher, "physics").await; |
| 7855 | enroll(&app, &teacher, &t.instance, &ayse_id).await; |
| 7856 | enroll(&app, &teacher, &t.instance, &veli_id).await; |
| 7857 | |
| 7858 | let now = Timestamp::now().as_millis(); |
| 7859 | let ends = now + 600_000; |
| 7860 | let exam = scheduled_exam( |
| 7861 | &app, |
| 7862 | &teacher, |
| 7863 | &t.instance, |
| 7864 | json!({ "term": &t.term, "title": "final", "kind": "final", |
| 7865 | "mode": "sync", "starts_at": now - 1_000, "ends_at": ends }), |
| 7866 | ) |
| 7867 | .await; |
| 7868 | |
| 7869 | // No attempt yet. |
| 7870 | let res = send( |
| 7871 | &app, |
| 7872 | "GET", |
| 7873 | &format!("/exams/{exam}/attempt"), |
| 7874 | Some(&veli), |
| 7875 | None, |
| 7876 | ) |
| 7877 | .await; |
| 7878 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 7879 | |
| 7880 | // Start: 201, in progress, and (sync) the deadline is the window close. |
| 7881 | let res = send( |
| 7882 | &app, |
| 7883 | "POST", |
| 7884 | &format!("/exams/{exam}/attempt"), |
| 7885 | Some(&veli), |
| 7886 | None, |
| 7887 | ) |
| 7888 | .await; |
| 7889 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 7890 | assert_eq!(res.body["status"], "in_progress"); |
| 7891 | assert_eq!(res.body["user"]["username"], "veli"); |
| 7892 | assert_eq!(res.body["deadline"].as_i64(), Some(ends)); |
| 7893 | assert!(res.body["mark"].is_null()); |
| 7894 | let started_at = res.body["started_at"].as_i64().expect("started_at"); |
| 7895 | let remaining = res.body["remaining_ms"].as_i64().expect("remaining_ms"); |
| 7896 | assert!( |
| 7897 | remaining > 0 && remaining <= 601_000, |
| 7898 | "remaining {remaining}" |
| 7899 | ); |
| 7900 | |
| 7901 | // Re-"start" resumes the same attempt with the original clock: 200. |
| 7902 | let res = send( |
| 7903 | &app, |
| 7904 | "POST", |
| 7905 | &format!("/exams/{exam}/attempt"), |
| 7906 | Some(&veli), |
| 7907 | None, |
| 7908 | ) |
| 7909 | .await; |
| 7910 | assert_eq!(res.status, StatusCode::OK); |
| 7911 | assert_eq!(res.body["started_at"].as_i64(), Some(started_at)); |
| 7912 | |
| 7913 | // The monitor sees one writer and one absentee, sorted by username. |
| 7914 | let res = send( |
| 7915 | &app, |
| 7916 | "GET", |
| 7917 | &format!("/exams/{exam}/live"), |
| 7918 | Some(&teacher), |
| 7919 | None, |
| 7920 | ) |
| 7921 | .await; |
| 7922 | assert_eq!(res.status, StatusCode::OK); |
| 7923 | assert_eq!(res.body["counts"]["enrolled"], 2); |
| 7924 | assert_eq!(res.body["counts"]["in_progress"], 1); |
| 7925 | assert_eq!(res.body["counts"]["not_started"], 1); |
| 7926 | assert!(res.body["now"].as_i64().is_some()); |
| 7927 | let students = res.body["students"].as_array().expect("students"); |
| 7928 | assert_eq!(students[0]["user"]["username"], "ayse"); |
| 7929 | assert_eq!(students[0]["status"], "not_started"); |
| 7930 | assert!(students[0]["started_at"].is_null()); |
| 7931 | assert!(students[0]["deadline"].is_null()); |
| 7932 | assert_eq!(students[1]["user"]["username"], "veli"); |
| 7933 | assert_eq!(students[1]["status"], "in_progress"); |
| 7934 | assert!(students[1]["remaining_ms"].as_i64().expect("remaining") > 0); |
| 7935 | |
| 7936 | // Submit, then grade mid-session; both land in the next snapshot. |
| 7937 | let res = send( |
| 7938 | &app, |
| 7939 | "POST", |
| 7940 | &format!("/exams/{exam}/attempt/finish"), |
| 7941 | Some(&veli), |
| 7942 | None, |
| 7943 | ) |
| 7944 | .await; |
| 7945 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 7946 | assert_eq!(res.body["status"], "submitted"); |
| 7947 | assert!(res.body["finished_at"].as_i64().is_some()); |
| 7948 | assert!(res.body["remaining_ms"].is_null()); |
| 7949 | |
| 7950 | let res = send( |
| 7951 | &app, |
| 7952 | "POST", |
| 7953 | &format!("/exams/{exam}/results"), |
| 7954 | Some(&teacher), |
| 7955 | Some(json!({ "mark": 85, "user_id": veli_id })), |
| 7956 | ) |
| 7957 | .await; |
| 7958 | assert_eq!(res.status, StatusCode::OK); |
| 7959 | |
| 7960 | let res = send( |
| 7961 | &app, |
| 7962 | "GET", |
| 7963 | &format!("/exams/{exam}/live"), |
| 7964 | Some(&teacher), |
| 7965 | None, |
| 7966 | ) |
| 7967 | .await; |
| 7968 | assert_eq!(res.body["counts"]["submitted"], 1); |
| 7969 | assert_eq!(res.body["counts"]["graded"], 1); |
| 7970 | assert_eq!(res.body["students"][1]["mark"], 85); |
| 7971 | |
| 7972 | // The student's own view carries the mark; the monitor stays teacher+. |
| 7973 | let res = send( |
| 7974 | &app, |
| 7975 | "GET", |
| 7976 | &format!("/exams/{exam}/attempt"), |
| 7977 | Some(&veli), |
| 7978 | None, |
| 7979 | ) |
| 7980 | .await; |
| 7981 | assert_eq!(res.body["status"], "submitted"); |
| 7982 | assert_eq!(res.body["mark"], 85); |
| 7983 | let res = send( |
| 7984 | &app, |
| 7985 | "GET", |
| 7986 | &format!("/exams/{exam}/live"), |
| 7987 | Some(&veli), |
| 7988 | None, |
| 7989 | ) |
| 7990 | .await; |
| 7991 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 7992 | } |
| 7993 | |
| 7994 | /// Once the window closes, an enrolled student who never sat turns from |
| 7995 | /// `not_started` into `absent` on the monitor — started-but-unsubmitted stays |
| 7996 | /// `expired`, and an open exam (no window) never flags anyone. |
| 7997 | #[tokio::test] |
| 7998 | async fn closed_window_flags_no_shows_as_absent() { |
| 7999 | let (app, db) = app_and_db().await; |
| 8000 | let teacher = login_as(&app, &db, "abs_t", "teacher").await; |
| 8001 | let ayse = login(&app, "ayse").await; // never shows up |
| 8002 | let veli = login(&app, "veli").await; // submits |
| 8003 | let cem = login(&app, "cem").await; // starts, never submits |
| 8004 | let ayse_id = me_id(&app, &ayse).await; |
| 8005 | let veli_id = me_id(&app, &veli).await; |
| 8006 | let cem_id = me_id(&app, &cem).await; |
| 8007 | let mudur = login_as(&app, &db, "abs_m", "manager").await; |
| 8008 | scheduling_kinds(&app, &mudur).await; |
| 8009 | let t = taught_under(&app, &mudur, &teacher, "history").await; |
| 8010 | enroll(&app, &teacher, &t.instance, &ayse_id).await; |
| 8011 | enroll(&app, &teacher, &t.instance, &veli_id).await; |
| 8012 | enroll(&app, &teacher, &t.instance, &cem_id).await; |
| 8013 | |
| 8014 | let now = Timestamp::now().as_millis(); |
| 8015 | let exam = scheduled_exam( |
| 8016 | &app, |
| 8017 | &teacher, |
| 8018 | &t.instance, |
| 8019 | json!({ "term": &t.term, "title": "midterm", "kind": "midterm", |
| 8020 | "mode": "sync", "starts_at": now - 50_000, "ends_at": now + 600_000 }), |
| 8021 | ) |
| 8022 | .await; |
| 8023 | |
| 8024 | for cookie in [&veli, &cem] { |
| 8025 | let res = send( |
| 8026 | &app, |
| 8027 | "POST", |
| 8028 | &format!("/exams/{exam}/attempt"), |
| 8029 | Some(cookie), |
| 8030 | None, |
| 8031 | ) |
| 8032 | .await; |
| 8033 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 8034 | } |
| 8035 | let res = send( |
| 8036 | &app, |
| 8037 | "POST", |
| 8038 | &format!("/exams/{exam}/attempt/finish"), |
| 8039 | Some(&veli), |
| 8040 | None, |
| 8041 | ) |
| 8042 | .await; |
| 8043 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 8044 | |
| 8045 | // Window still open: the no-show is merely `not_started`. |
| 8046 | let res = send( |
| 8047 | &app, |
| 8048 | "GET", |
| 8049 | &format!("/exams/{exam}/live"), |
| 8050 | Some(&teacher), |
| 8051 | None, |
| 8052 | ) |
| 8053 | .await; |
| 8054 | assert_eq!(res.status, StatusCode::OK); |
| 8055 | assert_eq!(res.body["counts"]["not_started"], 1); |
| 8056 | assert_eq!(res.body["counts"]["absent"], 0); |
| 8057 | assert_eq!(res.body["students"][0]["user"]["username"], "ayse"); |
| 8058 | assert_eq!(res.body["students"][0]["status"], "not_started"); |
| 8059 | |
| 8060 | // The teacher cuts the window short (inside the backdating grace): the |
| 8061 | // exam is over, and the gap hardens into an absence. |
| 8062 | let res = send( |
| 8063 | &app, |
| 8064 | "PATCH", |
| 8065 | &format!("/exams/{exam}"), |
| 8066 | Some(&teacher), |
| 8067 | Some(json!({ "ends_at": now - 10_000 })), |
| 8068 | ) |
| 8069 | .await; |
| 8070 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 8071 | |
| 8072 | let res = send( |
| 8073 | &app, |
| 8074 | "GET", |
| 8075 | &format!("/exams/{exam}/live"), |
| 8076 | Some(&teacher), |
| 8077 | None, |
| 8078 | ) |
| 8079 | .await; |
| 8080 | assert_eq!(res.status, StatusCode::OK); |
| 8081 | assert_eq!(res.body["counts"]["enrolled"], 3); |
| 8082 | assert_eq!(res.body["counts"]["not_started"], 0); |
| 8083 | assert_eq!(res.body["counts"]["absent"], 1); |
| 8084 | assert_eq!(res.body["counts"]["submitted"], 1); |
| 8085 | assert_eq!(res.body["counts"]["expired"], 1); |
| 8086 | let students = res.body["students"].as_array().expect("students"); |
| 8087 | assert_eq!(students[0]["user"]["username"], "ayse"); |
| 8088 | assert_eq!(students[0]["status"], "absent"); |
| 8089 | assert_eq!(students[1]["user"]["username"], "cem"); |
| 8090 | assert_eq!(students[1]["status"], "expired"); |
| 8091 | assert_eq!(students[2]["user"]["username"], "veli"); |
| 8092 | assert_eq!(students[2]["status"], "submitted"); |
| 8093 | |
| 8094 | // Absence is informational — the mark stays a human call, and the |
| 8095 | // teacher may still record one for the no-show. |
| 8096 | assert!(students[0]["mark"].is_null()); |
| 8097 | let res = send( |
| 8098 | &app, |
| 8099 | "POST", |
| 8100 | &format!("/exams/{exam}/results"), |
| 8101 | Some(&teacher), |
| 8102 | Some(json!({ "mark": 0, "user_id": ayse_id })), |
| 8103 | ) |
| 8104 | .await; |
| 8105 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 8106 | |
| 8107 | // An open exam has no window: never started is never absent. |
| 8108 | let open = scheduled_exam( |
| 8109 | &app, |
| 8110 | &teacher, |
| 8111 | &t.instance, |
| 8112 | json!({ "term": &t.term, "title": "essay", "kind": "homework", "mode": "open" }), |
| 8113 | ) |
| 8114 | .await; |
| 8115 | let res = send( |
| 8116 | &app, |
| 8117 | "GET", |
| 8118 | &format!("/exams/{open}/live"), |
| 8119 | Some(&teacher), |
| 8120 | None, |
| 8121 | ) |
| 8122 | .await; |
| 8123 | assert_eq!(res.status, StatusCode::OK); |
| 8124 | assert_eq!(res.body["counts"]["not_started"], 3); |
| 8125 | assert_eq!(res.body["counts"]["absent"], 0); |
| 8126 | } |
| 8127 | |
| 8128 | #[tokio::test] |
| 8129 | async fn async_deadline_is_start_plus_duration_clamped_to_window() { |
| 8130 | let (app, db) = app_and_db().await; |
| 8131 | let teacher = login_as(&app, &db, "async_t", "teacher").await; |
| 8132 | let student = login(&app, "asli").await; |
| 8133 | let student_id = me_id(&app, &student).await; |
| 8134 | let mudur = login_as(&app, &db, "async_m", "manager").await; |
| 8135 | scheduling_kinds(&app, &mudur).await; |
| 8136 | let t = taught_under(&app, &mudur, &teacher, "chem").await; |
| 8137 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 8138 | let now = Timestamp::now().as_millis(); |
| 8139 | |
| 8140 | // Roomy window: the personal duration is the binding constraint. |
| 8141 | let exam = scheduled_exam( |
| 8142 | &app, |
| 8143 | &teacher, |
| 8144 | &t.instance, |
| 8145 | json!({ "term": &t.term, "title": "quiz", "kind": "quiz", |
| 8146 | "mode": "async", "starts_at": now - 1_000, "ends_at": now + 6_000_000, |
| 8147 | "duration_ms": 60_000 }), |
| 8148 | ) |
| 8149 | .await; |
| 8150 | let res = send( |
| 8151 | &app, |
| 8152 | "POST", |
| 8153 | &format!("/exams/{exam}/attempt"), |
| 8154 | Some(&student), |
| 8155 | None, |
| 8156 | ) |
| 8157 | .await; |
| 8158 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 8159 | let started = res.body["started_at"].as_i64().expect("started_at"); |
| 8160 | assert_eq!(res.body["deadline"].as_i64(), Some(started + 60_000)); |
| 8161 | |
| 8162 | // Tight window: starting partway through it still lets `ends_at` clamp |
| 8163 | // the personal deadline (duration_ms can be at most the full window now, |
| 8164 | // so the clamp only bites once a student starts late inside it). |
| 8165 | let starts = now - 40_000; |
| 8166 | let ends = now + 20_000; |
| 8167 | let exam = scheduled_exam( |
| 8168 | &app, |
| 8169 | &teacher, |
| 8170 | &t.instance, |
| 8171 | json!({ "term": &t.term, "title": "quiz2", "kind": "quiz", |
| 8172 | "mode": "async", "starts_at": starts, "ends_at": ends, |
| 8173 | "duration_ms": 60_000 }), |
| 8174 | ) |
| 8175 | .await; |
| 8176 | let res = send( |
| 8177 | &app, |
| 8178 | "POST", |
| 8179 | &format!("/exams/{exam}/attempt"), |
| 8180 | Some(&student), |
| 8181 | None, |
| 8182 | ) |
| 8183 | .await; |
| 8184 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 8185 | assert_eq!(res.body["deadline"].as_i64(), Some(ends)); |
| 8186 | } |
| 8187 | |
| 8188 | #[tokio::test] |
| 8189 | async fn attempts_gate_on_schedule_enrollment_and_window() { |
| 8190 | let (app, db) = app_and_db().await; |
| 8191 | let teacher = login_as(&app, &db, "gate_t", "teacher").await; |
| 8192 | let student = login(&app, "gita").await; |
| 8193 | let student_id = me_id(&app, &student).await; |
| 8194 | let mudur = login_as(&app, &db, "gate_m", "manager").await; |
| 8195 | scheduling_kinds(&app, &mudur).await; |
| 8196 | let t = taught_under(&app, &mudur, &teacher, "bio").await; |
| 8197 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 8198 | let now = Timestamp::now().as_millis(); |
| 8199 | |
| 8200 | // Unscheduled exams cannot be sat at all. |
| 8201 | let unscheduled = create_exam(&app, &teacher, &t.instance, &t.term, "hw", "homework").await; |
| 8202 | let res = send( |
| 8203 | &app, |
| 8204 | "POST", |
| 8205 | &format!("/exams/{unscheduled}/attempt"), |
| 8206 | Some(&student), |
| 8207 | None, |
| 8208 | ) |
| 8209 | .await; |
| 8210 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 8211 | |
| 8212 | // Not-yet-open and already-closed windows are conflicts too. |
| 8213 | let future = scheduled_exam( |
| 8214 | &app, |
| 8215 | &teacher, |
| 8216 | &t.instance, |
| 8217 | json!({ "term": &t.term, "title": "later", "kind": "quiz", |
| 8218 | "mode": "sync", "starts_at": now + 600_000, "ends_at": now + 1_200_000 }), |
| 8219 | ) |
| 8220 | .await; |
| 8221 | let res = send( |
| 8222 | &app, |
| 8223 | "POST", |
| 8224 | &format!("/exams/{future}/attempt"), |
| 8225 | Some(&student), |
| 8226 | None, |
| 8227 | ) |
| 8228 | .await; |
| 8229 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 8230 | |
| 8231 | let past = scheduled_exam( |
| 8232 | &app, |
| 8233 | &teacher, |
| 8234 | &t.instance, |
| 8235 | // Inside the backdating grace, yet already closed by the clock. |
| 8236 | json!({ "term": &t.term, "title": "gone", "kind": "quiz", |
| 8237 | "mode": "sync", "starts_at": now - 50_000, "ends_at": now - 10_000 }), |
| 8238 | ) |
| 8239 | .await; |
| 8240 | let res = send( |
| 8241 | &app, |
| 8242 | "POST", |
| 8243 | &format!("/exams/{past}/attempt"), |
| 8244 | Some(&student), |
| 8245 | None, |
| 8246 | ) |
| 8247 | .await; |
| 8248 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 8249 | |
| 8250 | // Enrollment is required — teachers included (the monitor is their view). |
| 8251 | let open = scheduled_exam( |
| 8252 | &app, |
| 8253 | &teacher, |
| 8254 | &t.instance, |
| 8255 | json!({ "term": &t.term, "title": "open", "kind": "quiz", |
| 8256 | "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), |
| 8257 | ) |
| 8258 | .await; |
| 8259 | let outsider = login(&app, "omer").await; |
| 8260 | let res = send( |
| 8261 | &app, |
| 8262 | "POST", |
| 8263 | &format!("/exams/{open}/attempt"), |
| 8264 | Some(&outsider), |
| 8265 | None, |
| 8266 | ) |
| 8267 | .await; |
| 8268 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 8269 | let res = send( |
| 8270 | &app, |
| 8271 | "POST", |
| 8272 | &format!("/exams/{open}/attempt"), |
| 8273 | Some(&teacher), |
| 8274 | None, |
| 8275 | ) |
| 8276 | .await; |
| 8277 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 8278 | |
| 8279 | // A missing exam is a 404, not a conflict. |
| 8280 | let res = send( |
| 8281 | &app, |
| 8282 | "POST", |
| 8283 | "/exams/does-not-exist/attempt", |
| 8284 | Some(&student), |
| 8285 | None, |
| 8286 | ) |
| 8287 | .await; |
| 8288 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 8289 | } |
| 8290 | |
| 8291 | #[tokio::test] |
| 8292 | async fn finish_rejects_double_submit_missing_attempt_and_expiry() { |
| 8293 | let (app, db) = app_and_db().await; |
| 8294 | let teacher = login_as(&app, &db, "fin_t", "teacher").await; |
| 8295 | let student = login(&app, "fern").await; |
| 8296 | let student_id = me_id(&app, &student).await; |
| 8297 | let mudur = login_as(&app, &db, "fin_m", "manager").await; |
| 8298 | scheduling_kinds(&app, &mudur).await; |
| 8299 | let t = taught_under(&app, &mudur, &teacher, "cs").await; |
| 8300 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 8301 | let now = Timestamp::now().as_millis(); |
| 8302 | |
| 8303 | let exam = scheduled_exam( |
| 8304 | &app, |
| 8305 | &teacher, |
| 8306 | &t.instance, |
| 8307 | json!({ "term": &t.term, "title": "final", "kind": "final", |
| 8308 | "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), |
| 8309 | ) |
| 8310 | .await; |
| 8311 | |
| 8312 | // Finishing before starting: no attempt row to close. |
| 8313 | let res = send( |
| 8314 | &app, |
| 8315 | "POST", |
| 8316 | &format!("/exams/{exam}/attempt/finish"), |
| 8317 | Some(&student), |
| 8318 | None, |
| 8319 | ) |
| 8320 | .await; |
| 8321 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 8322 | |
| 8323 | let res = send( |
| 8324 | &app, |
| 8325 | "POST", |
| 8326 | &format!("/exams/{exam}/attempt"), |
| 8327 | Some(&student), |
| 8328 | None, |
| 8329 | ) |
| 8330 | .await; |
| 8331 | assert_eq!(res.status, StatusCode::CREATED); |
| 8332 | let res = send( |
| 8333 | &app, |
| 8334 | "POST", |
| 8335 | &format!("/exams/{exam}/attempt/finish"), |
| 8336 | Some(&student), |
| 8337 | None, |
| 8338 | ) |
| 8339 | .await; |
| 8340 | assert_eq!(res.status, StatusCode::OK); |
| 8341 | let res = send( |
| 8342 | &app, |
| 8343 | "POST", |
| 8344 | &format!("/exams/{exam}/attempt/finish"), |
| 8345 | Some(&student), |
| 8346 | None, |
| 8347 | ) |
| 8348 | .await; |
| 8349 | assert_eq!(res.status, StatusCode::CONFLICT, "double submit"); |
| 8350 | |
| 8351 | // Expiry: a window that closes right after the start. Real time, not a |
| 8352 | // mocked clock — the server judges expiry by `Timestamp::now()`. |
| 8353 | let brief = scheduled_exam( |
| 8354 | &app, |
| 8355 | &teacher, |
| 8356 | &t.instance, |
| 8357 | json!({ "term": &t.term, "title": "blitz", "kind": "quiz", |
| 8358 | "mode": "sync", "starts_at": now - 1_000, |
| 8359 | "ends_at": Timestamp::now().as_millis() + 1_500 }), |
| 8360 | ) |
| 8361 | .await; |
| 8362 | let res = send( |
| 8363 | &app, |
| 8364 | "POST", |
| 8365 | &format!("/exams/{brief}/attempt"), |
| 8366 | Some(&student), |
| 8367 | None, |
| 8368 | ) |
| 8369 | .await; |
| 8370 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 8371 | assert_eq!(res.body["status"], "in_progress"); |
| 8372 | |
| 8373 | tokio::time::sleep(std::time::Duration::from_millis(1_700)).await; |
| 8374 | |
| 8375 | let res = send( |
| 8376 | &app, |
| 8377 | "POST", |
| 8378 | &format!("/exams/{brief}/attempt/finish"), |
| 8379 | Some(&student), |
| 8380 | None, |
| 8381 | ) |
| 8382 | .await; |
| 8383 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 8384 | let res = send( |
| 8385 | &app, |
| 8386 | "GET", |
| 8387 | &format!("/exams/{brief}/attempt"), |
| 8388 | Some(&student), |
| 8389 | None, |
| 8390 | ) |
| 8391 | .await; |
| 8392 | assert_eq!(res.body["status"], "expired"); |
| 8393 | assert!(res.body["finished_at"].is_null()); |
| 8394 | assert!(res.body["remaining_ms"].is_null()); |
| 8395 | } |
| 8396 | |
| 8397 | #[tokio::test] |
| 8398 | async fn mode_freezes_after_attempts_but_times_extend_live() { |
| 8399 | let (app, db) = app_and_db().await; |
| 8400 | let teacher = login_as(&app, &db, "ext_t", "teacher").await; |
| 8401 | let student = login(&app, "elif").await; |
| 8402 | let student_id = me_id(&app, &student).await; |
| 8403 | let mudur = login_as(&app, &db, "ext_m", "manager").await; |
| 8404 | scheduling_kinds(&app, &mudur).await; |
| 8405 | let t = taught_under(&app, &mudur, &teacher, "math").await; |
| 8406 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 8407 | let now = Timestamp::now().as_millis(); |
| 8408 | let ends = now + 60_000; |
| 8409 | |
| 8410 | let exam = scheduled_exam( |
| 8411 | &app, |
| 8412 | &teacher, |
| 8413 | &t.instance, |
| 8414 | json!({ "term": &t.term, "title": "final", "kind": "final", |
| 8415 | "mode": "sync", "starts_at": now - 1_000, "ends_at": ends }), |
| 8416 | ) |
| 8417 | .await; |
| 8418 | |
| 8419 | // Before any attempt the whole schedule is editable — even the mode... |
| 8420 | let res = send( |
| 8421 | &app, |
| 8422 | "PATCH", |
| 8423 | &format!("/exams/{exam}"), |
| 8424 | Some(&teacher), |
| 8425 | Some(json!({ "mode": "async", "duration_ms": 60_000 })), |
| 8426 | ) |
| 8427 | .await; |
| 8428 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 8429 | assert_eq!(res.body["mode"], "async"); |
| 8430 | |
| 8431 | // ...but a PATCH may not leave a half-schedule behind. |
| 8432 | let res = send( |
| 8433 | &app, |
| 8434 | "PATCH", |
| 8435 | &format!("/exams/{exam}"), |
| 8436 | Some(&teacher), |
| 8437 | Some(json!({ "mode": null })), |
| 8438 | ) |
| 8439 | .await; |
| 8440 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 8441 | |
| 8442 | // Clearing everything unschedules; restoring re-schedules. |
| 8443 | let res = send( |
| 8444 | &app, |
| 8445 | "PATCH", |
| 8446 | &format!("/exams/{exam}"), |
| 8447 | Some(&teacher), |
| 8448 | Some(json!({ "mode": null, "starts_at": null, "ends_at": null, "duration_ms": null })), |
| 8449 | ) |
| 8450 | .await; |
| 8451 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 8452 | assert!(res.body["mode"].is_null()); |
| 8453 | let res = send( |
| 8454 | &app, |
| 8455 | "PATCH", |
| 8456 | &format!("/exams/{exam}"), |
| 8457 | Some(&teacher), |
| 8458 | Some(json!({ "mode": "sync", "starts_at": now - 1_000, "ends_at": ends })), |
| 8459 | ) |
| 8460 | .await; |
| 8461 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 8462 | |
| 8463 | // A student sits down; the mode is now frozen (unscheduling included). |
| 8464 | let res = send( |
| 8465 | &app, |
| 8466 | "POST", |
| 8467 | &format!("/exams/{exam}/attempt"), |
| 8468 | Some(&student), |
| 8469 | None, |
| 8470 | ) |
| 8471 | .await; |
| 8472 | assert_eq!(res.status, StatusCode::CREATED); |
| 8473 | let res = send( |
| 8474 | &app, |
| 8475 | "PATCH", |
| 8476 | &format!("/exams/{exam}"), |
| 8477 | Some(&teacher), |
| 8478 | Some(json!({ "mode": "async", "duration_ms": 60_000 })), |
| 8479 | ) |
| 8480 | .await; |
| 8481 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 8482 | let res = send( |
| 8483 | &app, |
| 8484 | "PATCH", |
| 8485 | &format!("/exams/{exam}"), |
| 8486 | Some(&teacher), |
| 8487 | Some(json!({ "mode": null, "starts_at": null, "ends_at": null })), |
| 8488 | ) |
| 8489 | .await; |
| 8490 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 8491 | |
| 8492 | // ...but extending the window moves the running deadline immediately. |
| 8493 | let extended = ends + 300_000; |
| 8494 | let res = send( |
| 8495 | &app, |
| 8496 | "PATCH", |
| 8497 | &format!("/exams/{exam}"), |
| 8498 | Some(&teacher), |
| 8499 | Some(json!({ "ends_at": extended })), |
| 8500 | ) |
| 8501 | .await; |
| 8502 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 8503 | let res = send( |
| 8504 | &app, |
| 8505 | "GET", |
| 8506 | &format!("/exams/{exam}/attempt"), |
| 8507 | Some(&student), |
| 8508 | None, |
| 8509 | ) |
| 8510 | .await; |
| 8511 | assert_eq!(res.body["status"], "in_progress"); |
| 8512 | assert_eq!(res.body["deadline"].as_i64(), Some(extended)); |
| 8513 | } |
| 8514 | |
| 8515 | #[tokio::test] |
| 8516 | async fn attempts_cascade_with_instance_detach_and_course_delete() { |
| 8517 | let (app, db) = app_and_db().await; |
| 8518 | let teacher = login_as(&app, &db, "casc_t", "teacher").await; |
| 8519 | let student = login(&app, "cansu").await; |
| 8520 | let student_id = me_id(&app, &student).await; |
| 8521 | let mudur = login_as(&app, &db, "casc_m", "manager").await; |
| 8522 | scheduling_kinds(&app, &mudur).await; |
| 8523 | let t = taught_under(&app, &mudur, &teacher, "hist").await; |
| 8524 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 8525 | let now = Timestamp::now().as_millis(); |
| 8526 | let schedule = json!({ "term": &t.term, "title": "final", "kind": "final", |
| 8527 | "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }); |
| 8528 | |
| 8529 | // Deleting the exam removes its attempts. |
| 8530 | let exam = scheduled_exam(&app, &teacher, &t.instance, schedule.clone()).await; |
| 8531 | let res = send( |
| 8532 | &app, |
| 8533 | "POST", |
| 8534 | &format!("/exams/{exam}/attempt"), |
| 8535 | Some(&student), |
| 8536 | None, |
| 8537 | ) |
| 8538 | .await; |
| 8539 | assert_eq!(res.status, StatusCode::CREATED); |
| 8540 | assert!(any_for_exam(&db, &ExamId::from_key(&exam)).await.unwrap()); |
| 8541 | let res = send( |
| 8542 | &app, |
| 8543 | "DELETE", |
| 8544 | &format!("/exams/{exam}"), |
| 8545 | Some(&teacher), |
| 8546 | None, |
| 8547 | ) |
| 8548 | .await; |
| 8549 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 8550 | assert!(!any_for_exam(&db, &ExamId::from_key(&exam)).await.unwrap()); |
| 8551 | |
| 8552 | // Detaching the şube takes the whole chain with it — the instance's exams |
| 8553 | // and their attempts. (A catalog course a şube still teaches is not |
| 8554 | // deletable, so this is where that cascade lives now.) |
| 8555 | let exam = scheduled_exam(&app, &teacher, &t.instance, schedule).await; |
| 8556 | let res = send( |
| 8557 | &app, |
| 8558 | "POST", |
| 8559 | &format!("/exams/{exam}/attempt"), |
| 8560 | Some(&student), |
| 8561 | None, |
| 8562 | ) |
| 8563 | .await; |
| 8564 | assert_eq!(res.status, StatusCode::CREATED); |
| 8565 | unenroll(&app, &teacher, &t.instance, &student_id).await; |
| 8566 | assert_eq!( |
| 8567 | send( |
| 8568 | &app, |
| 8569 | "DELETE", |
| 8570 | &format!("/classes/{}/instances/{}", t.class, t.instance), |
| 8571 | Some(&teacher), |
| 8572 | None |
| 8573 | ) |
| 8574 | .await |
| 8575 | .status, |
| 8576 | StatusCode::NO_CONTENT |
| 8577 | ); |
| 8578 | assert!(!any_for_exam(&db, &ExamId::from_key(&exam)).await.unwrap()); |
| 8579 | |
| 8580 | // The freed catalog row goes too. |
| 8581 | assert_eq!( |
| 8582 | send( |
| 8583 | &app, |
| 8584 | "DELETE", |
| 8585 | &format!("/courses/{}", t.course), |
| 8586 | Some(&teacher), |
| 8587 | None |
| 8588 | ) |
| 8589 | .await |
| 8590 | .status, |
| 8591 | StatusCode::NO_CONTENT |
| 8592 | ); |
| 8593 | } |
| 8594 | |
| 8595 | /// An `open` exam is sittable anytime — no window, no deadline — and |
| 8596 | /// `max_attempts` meters the retakes: every terminal attempt can be followed |
| 8597 | /// by a fresh sitting (blank answer sheet) until the limit is spent, and the |
| 8598 | /// limit is live-editable, `0` meaning unlimited. |
| 8599 | #[tokio::test] |
| 8600 | async fn open_exams_sit_anytime_and_retakes_respect_the_limit() { |
| 8601 | let (app, db) = app_and_db().await; |
| 8602 | let teacher = login_as(&app, &db, "open_t", "teacher").await; |
| 8603 | let student = login(&app, "omer").await; |
| 8604 | let student_id = me_id(&app, &student).await; |
| 8605 | let mudur = login_as(&app, &db, "open_m", "manager").await; |
| 8606 | scheduling_kinds(&app, &mudur).await; |
| 8607 | let t = taught_under(&app, &mudur, &teacher, "practice").await; |
| 8608 | let subject = create_subject(&app, &teacher, &t.course, "drills").await; |
| 8609 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 8610 | let exam = scheduled_exam( |
| 8611 | &app, |
| 8612 | &teacher, |
| 8613 | &t.instance, |
| 8614 | json!({ "term": &t.term, "title": "drill", "kind": "quiz", |
| 8615 | "mode": "open", "max_attempts": 2 }), |
| 8616 | ) |
| 8617 | .await; |
| 8618 | let question_body = create_question_body( |
| 8619 | &app, |
| 8620 | &teacher, |
| 8621 | &exam, |
| 8622 | &subject, |
| 8623 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 8624 | "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), |
| 8625 | ) |
| 8626 | .await; |
| 8627 | let question = id_of(&question_body); |
| 8628 | |
| 8629 | // First sitting starts right away — no window to wait for — and runs |
| 8630 | // without a deadline: it can only end by submission. |
| 8631 | let res = send( |
| 8632 | &app, |
| 8633 | "POST", |
| 8634 | &format!("/exams/{exam}/attempt"), |
| 8635 | Some(&student), |
| 8636 | None, |
| 8637 | ) |
| 8638 | .await; |
| 8639 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 8640 | assert_eq!(res.body["attempt"], 1); |
| 8641 | assert_eq!(res.body["attempts_used"], 1); |
| 8642 | assert_eq!(res.body["max_attempts"], 2); |
| 8643 | assert_eq!(res.body["status"], "in_progress"); |
| 8644 | assert!(res.body["deadline"].is_null()); |
| 8645 | assert!(res.body["remaining_ms"].is_null()); |
| 8646 | |
| 8647 | // Answer, then re-"start": the running attempt resumes (200), same clock. |
| 8648 | let res = send( |
| 8649 | &app, |
| 8650 | "POST", |
| 8651 | &format!("/exams/{exam}/attempt/answers"), |
| 8652 | Some(&student), |
| 8653 | Some(json!({ "question_id": question, "selected": choice_of(&question_body, 1) })), |
| 8654 | ) |
| 8655 | .await; |
| 8656 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 8657 | let res = send( |
| 8658 | &app, |
| 8659 | "POST", |
| 8660 | &format!("/exams/{exam}/attempt"), |
| 8661 | Some(&student), |
| 8662 | None, |
| 8663 | ) |
| 8664 | .await; |
| 8665 | assert_eq!(res.status, StatusCode::OK); |
| 8666 | assert_eq!(res.body["attempt"], 1); |
| 8667 | assert_eq!(res.body["answered"], 1); |
| 8668 | |
| 8669 | // Submit, then start again: sitting #2, and the retake wiped the sheet. |
| 8670 | let res = send( |
| 8671 | &app, |
| 8672 | "POST", |
| 8673 | &format!("/exams/{exam}/attempt/finish"), |
| 8674 | Some(&student), |
| 8675 | None, |
| 8676 | ) |
| 8677 | .await; |
| 8678 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 8679 | let res = send( |
| 8680 | &app, |
| 8681 | "POST", |
| 8682 | &format!("/exams/{exam}/attempt"), |
| 8683 | Some(&student), |
| 8684 | None, |
| 8685 | ) |
| 8686 | .await; |
| 8687 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 8688 | assert_eq!(res.body["attempt"], 2); |
| 8689 | assert_eq!(res.body["attempts_used"], 2); |
| 8690 | assert_eq!(res.body["answered"], 0, "retake starts from a blank sheet"); |
| 8691 | let res = send( |
| 8692 | &app, |
| 8693 | "GET", |
| 8694 | &format!("/exams/{exam}/attempt/questions"), |
| 8695 | Some(&student), |
| 8696 | None, |
| 8697 | ) |
| 8698 | .await; |
| 8699 | assert_eq!(res.status, StatusCode::OK); |
| 8700 | assert!( |
| 8701 | res.body[0]["answer"].is_null(), |
| 8702 | "wiped answer resurfaced: {}", |
| 8703 | res.body |
| 8704 | ); |
| 8705 | |
| 8706 | // The limit is spent after sitting #2 ends: no third start. |
| 8707 | let res = send( |
| 8708 | &app, |
| 8709 | "POST", |
| 8710 | &format!("/exams/{exam}/attempt/finish"), |
| 8711 | Some(&student), |
| 8712 | None, |
| 8713 | ) |
| 8714 | .await; |
| 8715 | assert_eq!(res.status, StatusCode::OK); |
| 8716 | let res = send( |
| 8717 | &app, |
| 8718 | "POST", |
| 8719 | &format!("/exams/{exam}/attempt"), |
| 8720 | Some(&student), |
| 8721 | None, |
| 8722 | ) |
| 8723 | .await; |
| 8724 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 8725 | |
| 8726 | // …until the teacher raises it live. `0` = unlimited: sitting #3 opens. |
| 8727 | let res = send( |
| 8728 | &app, |
| 8729 | "PATCH", |
| 8730 | &format!("/exams/{exam}"), |
| 8731 | Some(&teacher), |
| 8732 | Some(json!({ "max_attempts": 0 })), |
| 8733 | ) |
| 8734 | .await; |
| 8735 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 8736 | assert_eq!(res.body["max_attempts"], 0); |
| 8737 | let res = send( |
| 8738 | &app, |
| 8739 | "POST", |
| 8740 | &format!("/exams/{exam}/attempt"), |
| 8741 | Some(&student), |
| 8742 | None, |
| 8743 | ) |
| 8744 | .await; |
| 8745 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 8746 | assert_eq!(res.body["attempt"], 3); |
| 8747 | assert_eq!(res.body["max_attempts"], 0); |
| 8748 | |
| 8749 | // Lowering the limit below what's used never kills the running attempt — |
| 8750 | // it only blocks the next start once this one is over. |
| 8751 | let res = send( |
| 8752 | &app, |
| 8753 | "PATCH", |
| 8754 | &format!("/exams/{exam}"), |
| 8755 | Some(&teacher), |
| 8756 | Some(json!({ "max_attempts": 1 })), |
| 8757 | ) |
| 8758 | .await; |
| 8759 | assert_eq!(res.status, StatusCode::OK); |
| 8760 | let res = send( |
| 8761 | &app, |
| 8762 | "GET", |
| 8763 | &format!("/exams/{exam}/attempt"), |
| 8764 | Some(&student), |
| 8765 | None, |
| 8766 | ) |
| 8767 | .await; |
| 8768 | assert_eq!(res.status, StatusCode::OK); |
| 8769 | assert_eq!(res.body["status"], "in_progress"); |
| 8770 | let res = send( |
| 8771 | &app, |
| 8772 | "POST", |
| 8773 | &format!("/exams/{exam}/attempt/finish"), |
| 8774 | Some(&student), |
| 8775 | None, |
| 8776 | ) |
| 8777 | .await; |
| 8778 | assert_eq!(res.status, StatusCode::OK); |
| 8779 | let res = send( |
| 8780 | &app, |
| 8781 | "POST", |
| 8782 | &format!("/exams/{exam}/attempt"), |
| 8783 | Some(&student), |
| 8784 | None, |
| 8785 | ) |
| 8786 | .await; |
| 8787 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 8788 | } |
| 8789 | |
| 8790 | /// An `open` exam with a `duration_ms` gives each sitting its own countdown |
| 8791 | /// (`started_at + duration`), and retakes inside a sync window restart the |
| 8792 | /// sheet while the monitor tracks the latest sitting. |
| 8793 | #[tokio::test] |
| 8794 | async fn open_duration_and_sync_retakes_shape_the_deadline_and_monitor() { |
| 8795 | let (app, db) = app_and_db().await; |
| 8796 | let teacher = login_as(&app, &db, "dur_t", "teacher").await; |
| 8797 | let student = login(&app, "duru").await; |
| 8798 | let student_id = me_id(&app, &student).await; |
| 8799 | let mudur = login_as(&app, &db, "dur_m", "manager").await; |
| 8800 | scheduling_kinds(&app, &mudur).await; |
| 8801 | let t = taught_under(&app, &mudur, &teacher, "timing").await; |
| 8802 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 8803 | |
| 8804 | // Open + duration: the deadline is exactly start + budget. |
| 8805 | let timed = scheduled_exam( |
| 8806 | &app, |
| 8807 | &teacher, |
| 8808 | &t.instance, |
| 8809 | json!({ "term": &t.term, "title": "sprint", "kind": "quiz", |
| 8810 | "mode": "open", "duration_ms": 60_000 }), |
| 8811 | ) |
| 8812 | .await; |
| 8813 | let res = send( |
| 8814 | &app, |
| 8815 | "POST", |
| 8816 | &format!("/exams/{timed}/attempt"), |
| 8817 | Some(&student), |
| 8818 | None, |
| 8819 | ) |
| 8820 | .await; |
| 8821 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 8822 | let started_at = res.body["started_at"].as_i64().expect("started_at"); |
| 8823 | assert_eq!(res.body["deadline"].as_i64(), Some(started_at + 60_000)); |
| 8824 | let remaining = res.body["remaining_ms"].as_i64().expect("remaining_ms"); |
| 8825 | assert!( |
| 8826 | remaining > 0 && remaining <= 60_000, |
| 8827 | "remaining {remaining}" |
| 8828 | ); |
| 8829 | |
| 8830 | // Sync exam with retakes: sitting #2 opens inside the window and the |
| 8831 | // monitor shows the latest sitting plus the usage count. |
| 8832 | let now = Timestamp::now().as_millis(); |
| 8833 | let ends = now + 600_000; |
| 8834 | let exam = scheduled_exam( |
| 8835 | &app, |
| 8836 | &teacher, |
| 8837 | &t.instance, |
| 8838 | json!({ "term": &t.term, "title": "final", "kind": "final", |
| 8839 | "mode": "sync", "starts_at": now - 1_000, "ends_at": ends, |
| 8840 | "max_attempts": 3 }), |
| 8841 | ) |
| 8842 | .await; |
| 8843 | for _ in 0..2 { |
| 8844 | let res = send( |
| 8845 | &app, |
| 8846 | "POST", |
| 8847 | &format!("/exams/{exam}/attempt"), |
| 8848 | Some(&student), |
| 8849 | None, |
| 8850 | ) |
| 8851 | .await; |
| 8852 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 8853 | assert_eq!(res.body["deadline"].as_i64(), Some(ends)); |
| 8854 | let res = send( |
| 8855 | &app, |
| 8856 | "POST", |
| 8857 | &format!("/exams/{exam}/attempt/finish"), |
| 8858 | Some(&student), |
| 8859 | None, |
| 8860 | ) |
| 8861 | .await; |
| 8862 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 8863 | } |
| 8864 | let res = send( |
| 8865 | &app, |
| 8866 | "GET", |
| 8867 | &format!("/exams/{exam}/live"), |
| 8868 | Some(&teacher), |
| 8869 | None, |
| 8870 | ) |
| 8871 | .await; |
| 8872 | assert_eq!(res.status, StatusCode::OK); |
| 8873 | assert_eq!(res.body["counts"]["submitted"], 1); |
| 8874 | let row = &res.body["students"][0]; |
| 8875 | assert_eq!(row["user"]["username"], "duru"); |
| 8876 | assert_eq!(row["attempt"], 2); |
| 8877 | assert_eq!(row["attempts_used"], 2); |
| 8878 | assert!(row["left_at"].is_null()); |
| 8879 | |
| 8880 | // The third sitting is the last: the window still gates retakes, so once |
| 8881 | // it shuts (or the limit is spent) starting conflicts. |
| 8882 | let res = send( |
| 8883 | &app, |
| 8884 | "POST", |
| 8885 | &format!("/exams/{exam}/attempt"), |
| 8886 | Some(&student), |
| 8887 | None, |
| 8888 | ) |
| 8889 | .await; |
| 8890 | assert_eq!(res.status, StatusCode::CREATED); |
| 8891 | assert_eq!(res.body["attempt"], 3); |
| 8892 | let res = send( |
| 8893 | &app, |
| 8894 | "POST", |
| 8895 | &format!("/exams/{exam}/attempt/finish"), |
| 8896 | Some(&student), |
| 8897 | None, |
| 8898 | ) |
| 8899 | .await; |
| 8900 | assert_eq!(res.status, StatusCode::OK); |
| 8901 | let res = send( |
| 8902 | &app, |
| 8903 | "POST", |
| 8904 | &format!("/exams/{exam}/attempt"), |
| 8905 | Some(&student), |
| 8906 | None, |
| 8907 | ) |
| 8908 | .await; |
| 8909 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 8910 | } |
| 8911 | |
| 8912 | // --- subjects --------------------------------------------------------------- |
| 8913 | |
| 8914 | #[tokio::test] |
| 8915 | async fn subject_crud_validation_and_rbac() { |
| 8916 | let (app, db) = app_and_db().await; |
| 8917 | let teacher = login_as(&app, &db, "sub_t", "teacher").await; |
| 8918 | let other_teacher = login_as(&app, &db, "sub_t2", "teacher").await; |
| 8919 | let boss = login_as(&app, &db, "sub_m", "manager").await; |
| 8920 | let student = login(&app, "selin").await; |
| 8921 | let student_id = me_id(&app, &student).await; |
| 8922 | let t = taught_under(&app, &boss, &teacher, "calculus").await; |
| 8923 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 8924 | |
| 8925 | // Create echoes the full shape; description defaults to empty. |
| 8926 | let res = send( |
| 8927 | &app, |
| 8928 | "POST", |
| 8929 | &format!("/courses/{}/subjects", t.course), |
| 8930 | Some(&teacher), |
| 8931 | Some(json!({ "name": "limits", "description": "epsilon-delta" })), |
| 8932 | ) |
| 8933 | .await; |
| 8934 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 8935 | assert_eq!(res.body["course"], t.course); |
| 8936 | assert_eq!(res.body["name"], "limits"); |
| 8937 | assert_eq!(res.body["description"], "epsilon-delta"); |
| 8938 | let subject = id_of(&res.body); |
| 8939 | let second = create_subject(&app, &teacher, &t.course, "derivatives").await; |
| 8940 | |
| 8941 | // Validation: a blank name is a 400, a missing course a 404. |
| 8942 | let res = send( |
| 8943 | &app, |
| 8944 | "POST", |
| 8945 | &format!("/courses/{}/subjects", t.course), |
| 8946 | Some(&teacher), |
| 8947 | Some(json!({ "name": " " })), |
| 8948 | ) |
| 8949 | .await; |
| 8950 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 8951 | let res = send( |
| 8952 | &app, |
| 8953 | "POST", |
| 8954 | "/courses/missing/subjects", |
| 8955 | Some(&teacher), |
| 8956 | Some(json!({ "name": "orphan" })), |
| 8957 | ) |
| 8958 | .await; |
| 8959 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 8960 | |
| 8961 | // Writes are management-gated: students lack the role, a rival teacher |
| 8962 | // the rights; a manager passes everywhere. |
| 8963 | let res = send( |
| 8964 | &app, |
| 8965 | "POST", |
| 8966 | &format!("/courses/{}/subjects", t.course), |
| 8967 | Some(&student), |
| 8968 | Some(json!({ "name": "nope" })), |
| 8969 | ) |
| 8970 | .await; |
| 8971 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 8972 | let res = send( |
| 8973 | &app, |
| 8974 | "POST", |
| 8975 | &format!("/courses/{}/subjects", t.course), |
| 8976 | Some(&other_teacher), |
| 8977 | Some(json!({ "name": "nope" })), |
| 8978 | ) |
| 8979 | .await; |
| 8980 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 8981 | let res = send( |
| 8982 | &app, |
| 8983 | "PATCH", |
| 8984 | &format!("/subjects/{subject}"), |
| 8985 | Some(&other_teacher), |
| 8986 | Some(json!({ "name": "hijack" })), |
| 8987 | ) |
| 8988 | .await; |
| 8989 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 8990 | let res = send( |
| 8991 | &app, |
| 8992 | "DELETE", |
| 8993 | &format!("/subjects/{second}"), |
| 8994 | Some(&student), |
| 8995 | None, |
| 8996 | ) |
| 8997 | .await; |
| 8998 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 8999 | |
| 9000 | // Reads follow course visibility: the enrolled student and a manager see |
| 9001 | // the list and the subject, the rival teacher sees neither. |
| 9002 | let res = send( |
| 9003 | &app, |
| 9004 | "GET", |
| 9005 | &format!("/courses/{}/subjects", t.course), |
| 9006 | Some(&student), |
| 9007 | None, |
| 9008 | ) |
| 9009 | .await; |
| 9010 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 9011 | let listed = common::items(&res.body); |
| 9012 | assert_eq!(listed.len(), 2, "creation order"); |
| 9013 | assert_eq!(id_of(&listed[0]), subject); |
| 9014 | assert_eq!(id_of(&listed[1]), second); |
| 9015 | assert_eq!(common::total(&res.body), 2); |
| 9016 | let res = send( |
| 9017 | &app, |
| 9018 | "GET", |
| 9019 | &format!("/subjects/{subject}"), |
| 9020 | Some(&student), |
| 9021 | None, |
| 9022 | ) |
| 9023 | .await; |
| 9024 | assert_eq!(res.status, StatusCode::OK); |
| 9025 | assert_eq!(res.body["name"], "limits"); |
| 9026 | let res = send( |
| 9027 | &app, |
| 9028 | "GET", |
| 9029 | &format!("/courses/{}/subjects", t.course), |
| 9030 | Some(&other_teacher), |
| 9031 | None, |
| 9032 | ) |
| 9033 | .await; |
| 9034 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 9035 | let res = send( |
| 9036 | &app, |
| 9037 | "GET", |
| 9038 | &format!("/subjects/{subject}"), |
| 9039 | Some(&other_teacher), |
| 9040 | None, |
| 9041 | ) |
| 9042 | .await; |
| 9043 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 9044 | |
| 9045 | // PATCH keeps omitted fields; a manager may edit anyone's. |
| 9046 | let res = send( |
| 9047 | &app, |
| 9048 | "PATCH", |
| 9049 | &format!("/subjects/{subject}"), |
| 9050 | Some(&boss), |
| 9051 | Some(json!({ "name": "limits & continuity" })), |
| 9052 | ) |
| 9053 | .await; |
| 9054 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 9055 | assert_eq!(res.body["name"], "limits & continuity"); |
| 9056 | assert_eq!(res.body["description"], "epsilon-delta", "kept by omission"); |
| 9057 | |
| 9058 | // Unknown ids are 404s. |
| 9059 | for (method, body) in [ |
| 9060 | ("GET", None), |
| 9061 | ("PATCH", Some(json!({ "name": "x" }))), |
| 9062 | ("DELETE", None), |
| 9063 | ] { |
| 9064 | let res = send(&app, method, "/subjects/missing", Some(&teacher), body).await; |
| 9065 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{method}"); |
| 9066 | } |
| 9067 | |
| 9068 | // Delete works while nothing references the subject. |
| 9069 | let res = send( |
| 9070 | &app, |
| 9071 | "DELETE", |
| 9072 | &format!("/subjects/{second}"), |
| 9073 | Some(&teacher), |
| 9074 | None, |
| 9075 | ) |
| 9076 | .await; |
| 9077 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 9078 | let res = send( |
| 9079 | &app, |
| 9080 | "GET", |
| 9081 | &format!("/subjects/{second}"), |
| 9082 | Some(&teacher), |
| 9083 | None, |
| 9084 | ) |
| 9085 | .await; |
| 9086 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 9087 | } |
| 9088 | |
| 9089 | #[tokio::test] |
| 9090 | async fn subject_delete_blocks_while_questions_reference_it() { |
| 9091 | let (app, db) = app_and_db().await; |
| 9092 | let teacher = login_as(&app, &db, "sdb_t", "teacher").await; |
| 9093 | let mudur = login_as(&app, &db, "sdb_m", "manager").await; |
| 9094 | scheduling_kinds(&app, &mudur).await; |
| 9095 | let t = taught_under(&app, &mudur, &teacher, "history").await; |
| 9096 | let tagged = create_subject(&app, &teacher, &t.course, "antiquity").await; |
| 9097 | let spare = create_subject(&app, &teacher, &t.course, "middle ages").await; |
| 9098 | select_instance_subject(&app, &teacher, &t.instance, &tagged).await; |
| 9099 | select_instance_subject(&app, &teacher, &t.instance, &spare).await; |
| 9100 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "final", "final").await; |
| 9101 | let question_body = create_question_body( |
| 9102 | &app, |
| 9103 | &teacher, |
| 9104 | &exam, |
| 9105 | &tagged, |
| 9106 | json!({ "text": "When?", "kind": "text", "points": 10 }), |
| 9107 | ) |
| 9108 | .await; |
| 9109 | let question = id_of(&question_body); |
| 9110 | |
| 9111 | // Referenced: the delete is a conflict, and the subject survives. |
| 9112 | let res = send( |
| 9113 | &app, |
| 9114 | "DELETE", |
| 9115 | &format!("/subjects/{tagged}"), |
| 9116 | Some(&teacher), |
| 9117 | None, |
| 9118 | ) |
| 9119 | .await; |
| 9120 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 9121 | let res = send( |
| 9122 | &app, |
| 9123 | "GET", |
| 9124 | &format!("/subjects/{tagged}"), |
| 9125 | Some(&teacher), |
| 9126 | None, |
| 9127 | ) |
| 9128 | .await; |
| 9129 | assert_eq!(res.status, StatusCode::OK); |
| 9130 | |
| 9131 | // Re-tag the question elsewhere: the old subject frees up, the new one |
| 9132 | // locks. |
| 9133 | let res = send( |
| 9134 | &app, |
| 9135 | "PATCH", |
| 9136 | &format!("/exams/{exam}/questions/{question}"), |
| 9137 | Some(&teacher), |
| 9138 | Some(json!({ "subject_id": spare })), |
| 9139 | ) |
| 9140 | .await; |
| 9141 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 9142 | let res = send( |
| 9143 | &app, |
| 9144 | "DELETE", |
| 9145 | &format!("/subjects/{tagged}"), |
| 9146 | Some(&teacher), |
| 9147 | None, |
| 9148 | ) |
| 9149 | .await; |
| 9150 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 9151 | let res = send( |
| 9152 | &app, |
| 9153 | "DELETE", |
| 9154 | &format!("/subjects/{spare}"), |
| 9155 | Some(&teacher), |
| 9156 | None, |
| 9157 | ) |
| 9158 | .await; |
| 9159 | assert_eq!(res.status, StatusCode::CONFLICT); |
| 9160 | |
| 9161 | // Deleting the question releases the last reference. |
| 9162 | let res = send( |
| 9163 | &app, |
| 9164 | "DELETE", |
| 9165 | &format!("/exams/{exam}/questions/{question}"), |
| 9166 | Some(&teacher), |
| 9167 | None, |
| 9168 | ) |
| 9169 | .await; |
| 9170 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 9171 | let res = send( |
| 9172 | &app, |
| 9173 | "DELETE", |
| 9174 | &format!("/subjects/{spare}"), |
| 9175 | Some(&teacher), |
| 9176 | None, |
| 9177 | ) |
| 9178 | .await; |
| 9179 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 9180 | } |
| 9181 | |
| 9182 | // --- exam questions + answers (taking an exam) ----------------------------- |
| 9183 | |
| 9184 | /// Create a question tagged with `subject` via `POST /exams/{exam}/questions` |
| 9185 | /// (asserts 201); returns its id. |
| 9186 | async fn create_question( |
| 9187 | app: &axum::Router, |
| 9188 | cookie: &str, |
| 9189 | exam: &str, |
| 9190 | subject: &str, |
| 9191 | body: serde_json::Value, |
| 9192 | ) -> String { |
| 9193 | id_of(&create_question_body(app, cookie, exam, subject, body).await) |
| 9194 | } |
| 9195 | |
| 9196 | /// Like [`create_question_body`], but hands back the whole response: choice ids are |
| 9197 | /// minted by the server, so a test that answers a question — or pictures one of |
| 9198 | /// its options — has to read them off the response rather than count positions. |
| 9199 | async fn create_question_body( |
| 9200 | app: &axum::Router, |
| 9201 | cookie: &str, |
| 9202 | exam: &str, |
| 9203 | subject: &str, |
| 9204 | mut body: serde_json::Value, |
| 9205 | ) -> serde_json::Value { |
| 9206 | body["subject_id"] = json!(subject); |
| 9207 | let res = send( |
| 9208 | app, |
| 9209 | "POST", |
| 9210 | &format!("/exams/{exam}/questions"), |
| 9211 | Some(cookie), |
| 9212 | Some(body.clone()), |
| 9213 | ) |
| 9214 | .await; |
| 9215 | // The subject-tag gate reads the section's resolved syllabus: a topic the |
| 9216 | // offering never selected is refused. The writer holds a right over the |
| 9217 | // instance (the very gate the question write passed), so take the topic |
| 9218 | // onto the section's own set through the instance door and retry once. |
| 9219 | let res = if res.status == StatusCode::BAD_REQUEST |
| 9220 | && res.body["error"] |
| 9221 | .as_str() |
| 9222 | .is_some_and(|e| e.contains("subject is not in this section's subject set")) |
| 9223 | { |
| 9224 | let exam_row = send(app, "GET", &format!("/exams/{exam}"), Some(cookie), None).await; |
| 9225 | assert_eq!(exam_row.status, StatusCode::OK, "{}", exam_row.body); |
| 9226 | let instance = exam_row.body["class_course"].as_str().expect("class_course"); |
| 9227 | select_instance_subject(app, cookie, instance, subject).await; |
| 9228 | send( |
| 9229 | app, |
| 9230 | "POST", |
| 9231 | &format!("/exams/{exam}/questions"), |
| 9232 | Some(cookie), |
| 9233 | Some(body), |
| 9234 | ) |
| 9235 | .await |
| 9236 | } else { |
| 9237 | res |
| 9238 | }; |
| 9239 | assert_eq!( |
| 9240 | res.status, |
| 9241 | StatusCode::CREATED, |
| 9242 | "create question: {}", |
| 9243 | res.body |
| 9244 | ); |
| 9245 | res.body |
| 9246 | } |
| 9247 | |
| 9248 | /// The minted id of the option at `index` of a question (or bank template) |
| 9249 | /// response — what these tests used to write as a bare choice index. |
| 9250 | fn choice_of(question: &serde_json::Value, index: usize) -> String { |
| 9251 | question["choices"][index]["id"] |
| 9252 | .as_str() |
| 9253 | .unwrap_or_else(|| panic!("choice {index} of {question}")) |
| 9254 | .to_string() |
| 9255 | } |
| 9256 | |
| 9257 | /// A course with an open sync window, one subject, and one enrolled student — |
| 9258 | /// the spine of the question/answer tests. The fixture's dönem is what the |
| 9259 | /// extra exams these tests write file under; the open exam itself is the |
| 9260 | /// `final` of the kinds `scheduling_kinds` installs. |
| 9261 | async fn open_exam_with_student( |
| 9262 | app: &axum::Router, |
| 9263 | db: &Database, |
| 9264 | teacher: &str, |
| 9265 | student_id: &str, |
| 9266 | course_title: &str, |
| 9267 | ) -> (common::Taught, String, String) { |
| 9268 | let mudur = login_as(app, db, "spine_m", "manager").await; |
| 9269 | scheduling_kinds(app, &mudur).await; |
| 9270 | let t = taught_under(app, &mudur, teacher, course_title).await; |
| 9271 | let subject = create_subject(app, teacher, &t.course, "general").await; |
| 9272 | // The student joins the şube: the pump writes the roster row this fixture |
| 9273 | // used to place by hand, so the spine is the route a school actually walks. |
| 9274 | add_member(app, &mudur, &t.class, student_id).await; |
| 9275 | let now = Timestamp::now().as_millis(); |
| 9276 | let exam = scheduled_exam( |
| 9277 | app, |
| 9278 | teacher, |
| 9279 | &t.instance, |
| 9280 | json!({ "term": &t.term, "title": "final", "kind": "final", |
| 9281 | "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), |
| 9282 | ) |
| 9283 | .await; |
| 9284 | (t, exam, subject) |
| 9285 | } |
| 9286 | |
| 9287 | #[tokio::test] |
| 9288 | async fn question_crud_validation_and_rbac() { |
| 9289 | let (app, db) = app_and_db().await; |
| 9290 | let teacher = login_as(&app, &db, "q_t", "teacher").await; |
| 9291 | let other_teacher = login_as(&app, &db, "q_t2", "teacher").await; |
| 9292 | let student = login(&app, "quinn").await; |
| 9293 | let mudur = login_as(&app, &db, "q_m", "manager").await; |
| 9294 | scheduling_kinds(&app, &mudur).await; |
| 9295 | let t = taught_under(&app, &mudur, &teacher, "logic").await; |
| 9296 | let subject = create_subject(&app, &teacher, &t.course, "propositions").await; |
| 9297 | select_instance_subject(&app, &teacher, &t.instance, &subject).await; |
| 9298 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "final", "final").await; |
| 9299 | |
| 9300 | // A choice question echoes its full authoring view, correct included. |
| 9301 | let res = send( |
| 9302 | &app, |
| 9303 | "POST", |
| 9304 | &format!("/exams/{exam}/questions"), |
| 9305 | Some(&teacher), |
| 9306 | Some( |
| 9307 | json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice", "points": 10, |
| 9308 | "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}, {"id": "c2", "text": "5"}], "correct": "c1" }), |
| 9309 | ), |
| 9310 | ) |
| 9311 | .await; |
| 9312 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 9313 | assert_eq!(res.body["exam"], exam); |
| 9314 | assert_eq!(res.body["subject"], subject); |
| 9315 | assert_eq!(res.body["kind"], "choice"); |
| 9316 | assert_eq!(res.body["points"], 10); |
| 9317 | assert_eq!(res.body["choices"][1]["text"], "4"); |
| 9318 | assert_eq!(res.body["correct"], res.body["choices"][1]["id"]); |
| 9319 | let choice_q = id_of(&res.body); |
| 9320 | |
| 9321 | // A text question carries neither choices nor correct. |
| 9322 | let res = send( |
| 9323 | &app, |
| 9324 | "POST", |
| 9325 | &format!("/exams/{exam}/questions"), |
| 9326 | Some(&teacher), |
| 9327 | Some(json!({ "subject_id": subject, "text": "Explain.", "kind": "text", "points": 20 })), |
| 9328 | ) |
| 9329 | .await; |
| 9330 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 9331 | assert!(res.body["choices"].is_null()); |
| 9332 | assert!(res.body["correct"].is_null()); |
| 9333 | let text_q = id_of(&res.body); |
| 9334 | |
| 9335 | // The teacher list shows both, in creation order. |
| 9336 | let res = send( |
| 9337 | &app, |
| 9338 | "GET", |
| 9339 | &format!("/exams/{exam}/questions"), |
| 9340 | Some(&teacher), |
| 9341 | None, |
| 9342 | ) |
| 9343 | .await; |
| 9344 | assert_eq!(res.status, StatusCode::OK); |
| 9345 | let questions = common::items(&res.body); |
| 9346 | assert_eq!(questions.len(), 2); |
| 9347 | assert_eq!(id_of(&questions[0]), choice_q); |
| 9348 | assert_eq!(id_of(&questions[1]), text_q); |
| 9349 | |
| 9350 | // Kind-dependent fields are validated as a unit. |
| 9351 | for (label, body) in [ |
| 9352 | ( |
| 9353 | "unknown kind", |
| 9354 | json!({ "text": "x", "kind": "essay", "points": 1 }), |
| 9355 | ), |
| 9356 | ( |
| 9357 | "zero points", |
| 9358 | json!({ "text": "x", "kind": "text", "points": 0 }), |
| 9359 | ), |
| 9360 | ( |
| 9361 | "oversized points", |
| 9362 | json!({ "text": "x", "kind": "text", "points": 101 }), |
| 9363 | ), |
| 9364 | ( |
| 9365 | "blank text", |
| 9366 | json!({ "text": " ", "kind": "text", "points": 1 }), |
| 9367 | ), |
| 9368 | ( |
| 9369 | "choice without choices", |
| 9370 | json!({ "text": "x", "kind": "choice", "points": 1, "correct": "c0" }), |
| 9371 | ), |
| 9372 | ( |
| 9373 | "choice without correct", |
| 9374 | json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}] }), |
| 9375 | ), |
| 9376 | ( |
| 9377 | "correct names no submitted choice", |
| 9378 | json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c2" }), |
| 9379 | ), |
| 9380 | ( |
| 9381 | "correct is blank", |
| 9382 | json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "" }), |
| 9383 | ), |
| 9384 | ( |
| 9385 | // Two options under one key: the payload can't say which one |
| 9386 | // `correct` (or a picture) means, so it is refused outright. |
| 9387 | "duplicate choice id in one payload", |
| 9388 | json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c0", "text": "b"}], "correct": "c0" }), |
| 9389 | ), |
| 9390 | ( |
| 9391 | // An option with no key cannot be named by `correct`. |
| 9392 | "correct names an unkeyed option", |
| 9393 | json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"text": "a"}, {"text": "b"}], "correct": "c0" }), |
| 9394 | ), |
| 9395 | ( |
| 9396 | "one choice", |
| 9397 | json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}], "correct": "c0" }), |
| 9398 | ), |
| 9399 | ( |
| 9400 | "eleven choices", |
| 9401 | json!({ "text": "x", "kind": "choice", "points": 1, |
| 9402 | "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}, {"id": "c2", "text": "c"}, {"id": "c3", "text": "d"}, {"id": "c4", "text": "e"}, {"id": "c5", "text": "f"}, {"id": "c6", "text": "g"}, {"id": "c7", "text": "h"}, {"id": "c8", "text": "i"}, {"id": "c9", "text": "j"}, {"id": "c10", "text": "k"}], "correct": "c0" }), |
| 9403 | ), |
| 9404 | ( |
| 9405 | "blank choice", |
| 9406 | json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": " "}], "correct": "c0" }), |
| 9407 | ), |
| 9408 | ( |
| 9409 | "text with choices", |
| 9410 | json!({ "text": "x", "kind": "text", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}] }), |
| 9411 | ), |
| 9412 | ( |
| 9413 | "text with correct", |
| 9414 | json!({ "text": "x", "kind": "text", "points": 1, "correct": "c0" }), |
| 9415 | ), |
| 9416 | ] { |
| 9417 | let mut body = body; |
| 9418 | body["subject_id"] = json!(subject); |
| 9419 | let res = send( |
| 9420 | &app, |
| 9421 | "POST", |
| 9422 | &format!("/exams/{exam}/questions"), |
| 9423 | Some(&teacher), |
| 9424 | Some(body), |
| 9425 | ) |
| 9426 | .await; |
| 9427 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{label}: {}", res.body); |
| 9428 | } |
| 9429 | |
| 9430 | // The subject must exist and belong to the exam's own course. |
| 9431 | let other_course = create_course(&app, &teacher, "rhetoric").await; |
| 9432 | let foreign_subject = create_subject(&app, &teacher, &other_course, "fallacies").await; |
| 9433 | for (label, subject_id) in [ |
| 9434 | ("unknown subject", "missing"), |
| 9435 | ("foreign subject", foreign_subject.as_str()), |
| 9436 | ] { |
| 9437 | let res = send( |
| 9438 | &app, |
| 9439 | "POST", |
| 9440 | &format!("/exams/{exam}/questions"), |
| 9441 | Some(&teacher), |
| 9442 | Some(json!({ "subject_id": subject_id, "text": "x", "kind": "text", "points": 1 })), |
| 9443 | ) |
| 9444 | .await; |
| 9445 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{label}: {}", res.body); |
| 9446 | } |
| 9447 | |
| 9448 | // Authoring needs management rights over the course; reading needs teacher+. |
| 9449 | let question_body = json!({ "subject_id": subject, "text": "x", "kind": "text", "points": 1 }); |
| 9450 | let res = send( |
| 9451 | &app, |
| 9452 | "POST", |
| 9453 | &format!("/exams/{exam}/questions"), |
| 9454 | Some(&student), |
| 9455 | Some(question_body.clone()), |
| 9456 | ) |
| 9457 | .await; |
| 9458 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 9459 | let res = send( |
| 9460 | &app, |
| 9461 | "POST", |
| 9462 | &format!("/exams/{exam}/questions"), |
| 9463 | Some(&other_teacher), |
| 9464 | Some(question_body), |
| 9465 | ) |
| 9466 | .await; |
| 9467 | assert_eq!(res.status, StatusCode::FORBIDDEN, "not the course creator"); |
| 9468 | let res = send( |
| 9469 | &app, |
| 9470 | "GET", |
| 9471 | &format!("/exams/{exam}/questions"), |
| 9472 | Some(&student), |
| 9473 | None, |
| 9474 | ) |
| 9475 | .await; |
| 9476 | assert_eq!( |
| 9477 | res.status, |
| 9478 | StatusCode::FORBIDDEN, |
| 9479 | "correct stays teacher-side" |
| 9480 | ); |
| 9481 | |
| 9482 | // PATCH: keep-by-omission, and the kind bundle re-validates as a unit. |
| 9483 | let res = send( |
| 9484 | &app, |
| 9485 | "PATCH", |
| 9486 | &format!("/exams/{exam}/questions/{choice_q}"), |
| 9487 | Some(&teacher), |
| 9488 | Some(json!({ "points": 15 })), |
| 9489 | ) |
| 9490 | .await; |
| 9491 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 9492 | assert_eq!(res.body["points"], 15); |
| 9493 | assert_eq!( |
| 9494 | res.body["correct"], res.body["choices"][1]["id"], |
| 9495 | "kind bundle kept" |
| 9496 | ); |
| 9497 | assert_eq!(res.body["subject"], subject, "subject kept by omission"); |
| 9498 | |
| 9499 | // Re-tagging stays inside the course: another of its subjects is fine, a |
| 9500 | // foreign course's subject is a 400. |
| 9501 | let second_subject = create_subject(&app, &teacher, &t.course, "predicates").await; |
| 9502 | select_instance_subject(&app, &teacher, &t.instance, &second_subject).await; |
| 9503 | let res = send( |
| 9504 | &app, |
| 9505 | "PATCH", |
| 9506 | &format!("/exams/{exam}/questions/{choice_q}"), |
| 9507 | Some(&teacher), |
| 9508 | Some(json!({ "subject_id": second_subject })), |
| 9509 | ) |
| 9510 | .await; |
| 9511 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 9512 | assert_eq!(res.body["subject"], second_subject); |
| 9513 | let res = send( |
| 9514 | &app, |
| 9515 | "PATCH", |
| 9516 | &format!("/exams/{exam}/questions/{choice_q}"), |
| 9517 | Some(&teacher), |
| 9518 | Some(json!({ "subject_id": foreign_subject })), |
| 9519 | ) |
| 9520 | .await; |
| 9521 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 9522 | |
| 9523 | // Switching to text must clear the bundle explicitly... |
| 9524 | let res = send( |
| 9525 | &app, |
| 9526 | "PATCH", |
| 9527 | &format!("/exams/{exam}/questions/{choice_q}"), |
| 9528 | Some(&teacher), |
| 9529 | Some(json!({ "kind": "text" })), |
| 9530 | ) |
| 9531 | .await; |
| 9532 | assert_eq!( |
| 9533 | res.status, |
| 9534 | StatusCode::BAD_REQUEST, |
| 9535 | "half-switch: {}", |
| 9536 | res.body |
| 9537 | ); |
| 9538 | let res = send( |
| 9539 | &app, |
| 9540 | "PATCH", |
| 9541 | &format!("/exams/{exam}/questions/{choice_q}"), |
| 9542 | Some(&teacher), |
| 9543 | Some(json!({ "kind": "text", "choices": null, "correct": null })), |
| 9544 | ) |
| 9545 | .await; |
| 9546 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 9547 | assert!(res.body["choices"].is_null()); |
| 9548 | |
| 9549 | // ...and back, bringing the bundle along. |
| 9550 | let res = send( |
| 9551 | &app, |
| 9552 | "PATCH", |
| 9553 | &format!("/exams/{exam}/questions/{choice_q}"), |
| 9554 | Some(&teacher), |
| 9555 | Some(json!({ "kind": "choice", "choices": [{"id": "c0", "text": "yes"}, {"id": "c1", "text": "no"}], "correct": "c0" })), |
| 9556 | ) |
| 9557 | .await; |
| 9558 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 9559 | |
| 9560 | // Editing is management-gated too. |
| 9561 | let res = send( |
| 9562 | &app, |
| 9563 | "PATCH", |
| 9564 | &format!("/exams/{exam}/questions/{choice_q}"), |
| 9565 | Some(&other_teacher), |
| 9566 | Some(json!({ "points": 1 })), |
| 9567 | ) |
| 9568 | .await; |
| 9569 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 9570 | |
| 9571 | // Unknown ids are 404s — including a question under the wrong exam. |
| 9572 | let other_exam = create_exam(&app, &teacher, &t.instance, &t.term, "rehearsal", "quiz").await; |
| 9573 | for (method, uri) in [ |
| 9574 | ("POST", "/exams/missing/questions".to_string()), |
| 9575 | ("GET", "/exams/missing/questions".to_string()), |
| 9576 | ("PATCH", format!("/exams/{exam}/questions/missing")), |
| 9577 | ("DELETE", format!("/exams/{exam}/questions/missing")), |
| 9578 | ("PATCH", format!("/exams/{other_exam}/questions/{choice_q}")), |
| 9579 | ( |
| 9580 | "DELETE", |
| 9581 | format!("/exams/{other_exam}/questions/{choice_q}"), |
| 9582 | ), |
| 9583 | ] { |
| 9584 | let body = match method { |
| 9585 | "POST" => { |
| 9586 | Some(json!({ "subject_id": subject, "text": "x", "kind": "text", "points": 1 })) |
| 9587 | } |
| 9588 | "PATCH" => Some(json!({ "points": 2 })), |
| 9589 | _ => None, |
| 9590 | }; |
| 9591 | let res = send(&app, method, &uri, Some(&teacher), body).await; |
| 9592 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{method} {uri}"); |
| 9593 | } |
| 9594 | |
| 9595 | // Delete removes from the list; deleting is management-gated. |
| 9596 | let res = send( |
| 9597 | &app, |
| 9598 | "DELETE", |
| 9599 | &format!("/exams/{exam}/questions/{text_q}"), |
| 9600 | Some(&student), |
| 9601 | None, |
| 9602 | ) |
| 9603 | .await; |
| 9604 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 9605 | let res = send( |
| 9606 | &app, |
| 9607 | "DELETE", |
| 9608 | &format!("/exams/{exam}/questions/{text_q}"), |
| 9609 | Some(&teacher), |
| 9610 | None, |
| 9611 | ) |
| 9612 | .await; |
| 9613 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 9614 | let res = send( |
| 9615 | &app, |
| 9616 | "GET", |
| 9617 | &format!("/exams/{exam}/questions"), |
| 9618 | Some(&teacher), |
| 9619 | None, |
| 9620 | ) |
| 9621 | .await; |
| 9622 | assert_eq!(common::items(&res.body).len(), 1); |
| 9623 | } |
| 9624 | |
| 9625 | #[tokio::test] |
| 9626 | async fn questions_freeze_once_attempts_start() { |
| 9627 | let (app, db) = app_and_db().await; |
| 9628 | let teacher = login_as(&app, &db, "frz_t", "teacher").await; |
| 9629 | let student = login(&app, "firat").await; |
| 9630 | let student_id = me_id(&app, &student).await; |
| 9631 | let (_t, exam, subject) = |
| 9632 | open_exam_with_student(&app, &db, &teacher, &student_id, "algo").await; |
| 9633 | let question_body = create_question_body( |
| 9634 | &app, |
| 9635 | &teacher, |
| 9636 | &exam, |
| 9637 | &subject, |
| 9638 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 9639 | "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), |
| 9640 | ) |
| 9641 | .await; |
| 9642 | let question = id_of(&question_body); |
| 9643 | |
| 9644 | let res = send( |
| 9645 | &app, |
| 9646 | "POST", |
| 9647 | &format!("/exams/{exam}/attempt"), |
| 9648 | Some(&student), |
| 9649 | None, |
| 9650 | ) |
| 9651 | .await; |
| 9652 | assert_eq!(res.status, StatusCode::CREATED); |
| 9653 | |
| 9654 | // Create, edit, and delete are all conflicts now. |
| 9655 | let res = send( |
| 9656 | &app, |
| 9657 | "POST", |
| 9658 | &format!("/exams/{exam}/questions"), |
| 9659 | Some(&teacher), |
| 9660 | Some(json!({ "subject_id": subject, "text": "late", "kind": "text", "points": 1 })), |
| 9661 | ) |
| 9662 | .await; |
| 9663 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 9664 | let res = send( |
| 9665 | &app, |
| 9666 | "PATCH", |
| 9667 | &format!("/exams/{exam}/questions/{question}"), |
| 9668 | Some(&teacher), |
| 9669 | Some(json!({ "points": 1 })), |
| 9670 | ) |
| 9671 | .await; |
| 9672 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 9673 | let res = send( |
| 9674 | &app, |
| 9675 | "DELETE", |
| 9676 | &format!("/exams/{exam}/questions/{question}"), |
| 9677 | Some(&teacher), |
| 9678 | None, |
| 9679 | ) |
| 9680 | .await; |
| 9681 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 9682 | } |
| 9683 | |
| 9684 | #[tokio::test] |
| 9685 | async fn student_question_view_hides_correct_and_embeds_answers() { |
| 9686 | let (app, db) = app_and_db().await; |
| 9687 | let teacher = login_as(&app, &db, "sv_t", "teacher").await; |
| 9688 | let student = login(&app, "sona").await; |
| 9689 | let student_id = me_id(&app, &student).await; |
| 9690 | let (_t, exam, subject) = open_exam_with_student(&app, &db, &teacher, &student_id, "art").await; |
| 9691 | let choice_q_body = create_question_body( |
| 9692 | &app, |
| 9693 | &teacher, |
| 9694 | &exam, |
| 9695 | &subject, |
| 9696 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 9697 | "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), |
| 9698 | ) |
| 9699 | .await; |
| 9700 | let choice_q = id_of(&choice_q_body); |
| 9701 | create_question( |
| 9702 | &app, |
| 9703 | &teacher, |
| 9704 | &exam, |
| 9705 | &subject, |
| 9706 | json!({ "text": "Explain.", "kind": "text", "points": 20 }), |
| 9707 | ) |
| 9708 | .await; |
| 9709 | |
| 9710 | // No early peek: the student view requires an attempt. |
| 9711 | let uri = format!("/exams/{exam}/attempt/questions"); |
| 9712 | let res = send(&app, "GET", &uri, Some(&student), None).await; |
| 9713 | assert_eq!(res.status, StatusCode::NOT_FOUND, "attempt first"); |
| 9714 | let res = send( |
| 9715 | &app, |
| 9716 | "POST", |
| 9717 | &format!("/exams/{exam}/attempt"), |
| 9718 | Some(&student), |
| 9719 | None, |
| 9720 | ) |
| 9721 | .await; |
| 9722 | assert_eq!(res.status, StatusCode::CREATED); |
| 9723 | |
| 9724 | // The sitting view: same order, no `correct` key anywhere, answers null. |
| 9725 | let res = send(&app, "GET", &uri, Some(&student), None).await; |
| 9726 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 9727 | let questions = res.body.as_array().expect("questions"); |
| 9728 | assert_eq!(questions.len(), 2); |
| 9729 | assert_eq!(questions[0]["kind"], "choice"); |
| 9730 | assert_eq!(questions[0]["choices"][1]["text"], "4"); |
| 9731 | for question in questions { |
| 9732 | assert!( |
| 9733 | question.as_object().unwrap().get("correct").is_none(), |
| 9734 | "correct must never reach a student: {question}" |
| 9735 | ); |
| 9736 | assert!(question["answer"].is_null()); |
| 9737 | } |
| 9738 | |
| 9739 | // A saved answer comes back embedded on the next read. |
| 9740 | let res = send( |
| 9741 | &app, |
| 9742 | "POST", |
| 9743 | &format!("/exams/{exam}/attempt/answers"), |
| 9744 | Some(&student), |
| 9745 | Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 0) })), |
| 9746 | ) |
| 9747 | .await; |
| 9748 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 9749 | assert_eq!(res.body["question"], choice_q); |
| 9750 | assert_eq!(res.body["selected"], choice_of(&choice_q_body, 0)); |
| 9751 | let saved_at = res.body["updated_at"].as_i64().expect("updated_at"); |
| 9752 | |
| 9753 | let res = send(&app, "GET", &uri, Some(&student), None).await; |
| 9754 | let questions = res.body.as_array().expect("questions"); |
| 9755 | assert_eq!( |
| 9756 | questions[0]["answer"]["selected"], |
| 9757 | choice_of(&choice_q_body, 0) |
| 9758 | ); |
| 9759 | assert_eq!(questions[0]["answer"]["updated_at"], saved_at); |
| 9760 | assert!(questions[1]["answer"].is_null()); |
| 9761 | } |
| 9762 | |
| 9763 | #[tokio::test] |
| 9764 | async fn answer_saves_gate_on_attempt_state_and_kind() { |
| 9765 | let (app, db) = app_and_db().await; |
| 9766 | let teacher = login_as(&app, &db, "ans_t", "teacher").await; |
| 9767 | let student = login(&app, "arda").await; |
| 9768 | let student_id = me_id(&app, &student).await; |
| 9769 | let (t, exam, subject) = open_exam_with_student(&app, &db, &teacher, &student_id, "phys").await; |
| 9770 | let choice_q_body = create_question_body( |
| 9771 | &app, |
| 9772 | &teacher, |
| 9773 | &exam, |
| 9774 | &subject, |
| 9775 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 9776 | "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}, {"id": "c2", "text": "5"}], "correct": "c1" }), |
| 9777 | ) |
| 9778 | .await; |
| 9779 | let choice_q = id_of(&choice_q_body); |
| 9780 | let text_q_body = create_question_body( |
| 9781 | &app, |
| 9782 | &teacher, |
| 9783 | &exam, |
| 9784 | &subject, |
| 9785 | json!({ "text": "Explain.", "kind": "text", "points": 20 }), |
| 9786 | ) |
| 9787 | .await; |
| 9788 | let text_q = id_of(&text_q_body); |
| 9789 | let answers_uri = format!("/exams/{exam}/attempt/answers"); |
| 9790 | |
| 9791 | // Saving needs an attempt (404 before start). |
| 9792 | let res = send( |
| 9793 | &app, |
| 9794 | "POST", |
| 9795 | &answers_uri, |
| 9796 | Some(&student), |
| 9797 | Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 0) })), |
| 9798 | ) |
| 9799 | .await; |
| 9800 | assert_eq!(res.status, StatusCode::NOT_FOUND, "attempt first"); |
| 9801 | let res = send( |
| 9802 | &app, |
| 9803 | "POST", |
| 9804 | &format!("/exams/{exam}/attempt"), |
| 9805 | Some(&student), |
| 9806 | None, |
| 9807 | ) |
| 9808 | .await; |
| 9809 | assert_eq!(res.status, StatusCode::CREATED); |
| 9810 | |
| 9811 | // Upsert: re-answering overwrites the one row and re-stamps its clock. |
| 9812 | let res = send( |
| 9813 | &app, |
| 9814 | "POST", |
| 9815 | &answers_uri, |
| 9816 | Some(&student), |
| 9817 | Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 0) })), |
| 9818 | ) |
| 9819 | .await; |
| 9820 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 9821 | let first_saved_at = res.body["updated_at"].as_i64().expect("updated_at"); |
| 9822 | tokio::time::sleep(std::time::Duration::from_millis(5)).await; |
| 9823 | let res = send( |
| 9824 | &app, |
| 9825 | "POST", |
| 9826 | &answers_uri, |
| 9827 | Some(&student), |
| 9828 | Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 2) })), |
| 9829 | ) |
| 9830 | .await; |
| 9831 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 9832 | assert_eq!(res.body["selected"], choice_of(&choice_q_body, 2)); |
| 9833 | assert!( |
| 9834 | res.body["updated_at"].as_i64().expect("updated_at") > first_saved_at, |
| 9835 | "a re-save moves updated_at forward" |
| 9836 | ); |
| 9837 | let res = send( |
| 9838 | &app, |
| 9839 | "POST", |
| 9840 | &answers_uri, |
| 9841 | Some(&student), |
| 9842 | Some(json!({ "question_id": text_q, "text": "because" })), |
| 9843 | ) |
| 9844 | .await; |
| 9845 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 9846 | assert_eq!(res.body["text"], "because"); |
| 9847 | |
| 9848 | // The attempt view counts distinct questions answered, not saves. |
| 9849 | let res = send( |
| 9850 | &app, |
| 9851 | "GET", |
| 9852 | &format!("/exams/{exam}/attempt"), |
| 9853 | Some(&student), |
| 9854 | None, |
| 9855 | ) |
| 9856 | .await; |
| 9857 | assert_eq!(res.body["answered"], 2); |
| 9858 | assert_eq!(res.body["question_count"], 2); |
| 9859 | |
| 9860 | // Payloads that don't fit the question's kind are 400s. |
| 9861 | for (label, body) in [ |
| 9862 | ( |
| 9863 | "text on a choice question", |
| 9864 | json!({ "question_id": choice_q, "text": "4" }), |
| 9865 | ), |
| 9866 | ( |
| 9867 | "both fields", |
| 9868 | json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 1), "text": "4" }), |
| 9869 | ), |
| 9870 | ( |
| 9871 | "selected names no choice of this question", |
| 9872 | json!({ "question_id": choice_q, "selected": "01NOTACHOICEOFTHISQUEST" }), |
| 9873 | ), |
| 9874 | ("nothing to save", json!({ "question_id": choice_q })), |
| 9875 | ( |
| 9876 | "selected on a text question", |
| 9877 | json!({ "question_id": text_q, "selected": choice_of(&choice_q_body, 0) }), |
| 9878 | ), |
| 9879 | ( |
| 9880 | "oversized text", |
| 9881 | json!({ "question_id": text_q, "text": "x".repeat(10_001) }), |
| 9882 | ), |
| 9883 | ] { |
| 9884 | let res = send(&app, "POST", &answers_uri, Some(&student), Some(body)).await; |
| 9885 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{label}: {}", res.body); |
| 9886 | } |
| 9887 | |
| 9888 | // Unknown questions — and questions of *other* exams — are 404s. |
| 9889 | let res = send( |
| 9890 | &app, |
| 9891 | "POST", |
| 9892 | &answers_uri, |
| 9893 | Some(&student), |
| 9894 | Some(json!({ "question_id": "missing", "selected": "c0" })), |
| 9895 | ) |
| 9896 | .await; |
| 9897 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 9898 | let foreign_exam = create_exam(&app, &teacher, &t.instance, &t.term, "other", "quiz").await; |
| 9899 | let foreign_q_body = create_question_body( |
| 9900 | &app, |
| 9901 | &teacher, |
| 9902 | &foreign_exam, |
| 9903 | &subject, |
| 9904 | json!({ "text": "not yours", "kind": "choice", "points": 1, |
| 9905 | "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }), |
| 9906 | ) |
| 9907 | .await; |
| 9908 | let foreign_q = id_of(&foreign_q_body); |
| 9909 | let res = send( |
| 9910 | &app, |
| 9911 | "POST", |
| 9912 | &answers_uri, |
| 9913 | Some(&student), |
| 9914 | Some(json!({ "question_id": foreign_q, "selected": choice_of(&foreign_q_body, 0) })), |
| 9915 | ) |
| 9916 | .await; |
| 9917 | assert_eq!( |
| 9918 | res.status, |
| 9919 | StatusCode::NOT_FOUND, |
| 9920 | "a real question under the wrong exam: {}", |
| 9921 | res.body |
| 9922 | ); |
| 9923 | |
| 9924 | // Submitting closes the write path. |
| 9925 | let res = send( |
| 9926 | &app, |
| 9927 | "POST", |
| 9928 | &format!("/exams/{exam}/attempt/finish"), |
| 9929 | Some(&student), |
| 9930 | None, |
| 9931 | ) |
| 9932 | .await; |
| 9933 | assert_eq!(res.status, StatusCode::OK); |
| 9934 | let res = send( |
| 9935 | &app, |
| 9936 | "POST", |
| 9937 | &answers_uri, |
| 9938 | Some(&student), |
| 9939 | Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 1) })), |
| 9940 | ) |
| 9941 | .await; |
| 9942 | assert_eq!( |
| 9943 | res.status, |
| 9944 | StatusCode::CONFLICT, |
| 9945 | "after submit: {}", |
| 9946 | res.body |
| 9947 | ); |
| 9948 | |
| 9949 | // ...but the sitting view stays readable for review, answers intact. |
| 9950 | let res = send( |
| 9951 | &app, |
| 9952 | "GET", |
| 9953 | &format!("/exams/{exam}/attempt/questions"), |
| 9954 | Some(&student), |
| 9955 | None, |
| 9956 | ) |
| 9957 | .await; |
| 9958 | assert_eq!( |
| 9959 | res.status, |
| 9960 | StatusCode::OK, |
| 9961 | "review after submit: {}", |
| 9962 | res.body |
| 9963 | ); |
| 9964 | assert_eq!( |
| 9965 | res.body[0]["answer"]["selected"], |
| 9966 | choice_of(&choice_q_body, 2) |
| 9967 | ); |
| 9968 | assert_eq!(res.body[1]["answer"]["text"], "because"); |
| 9969 | } |
| 9970 | |
| 9971 | #[tokio::test] |
| 9972 | async fn unenrollment_cuts_the_sittings_reads_and_writes() { |
| 9973 | let (app, db) = app_and_db().await; |
| 9974 | let teacher = login_as(&app, &db, "cut_t", "teacher").await; |
| 9975 | let student = login(&app, "cansu").await; |
| 9976 | let student_id = me_id(&app, &student).await; |
| 9977 | let (t, exam, subject) = open_exam_with_student(&app, &db, &teacher, &student_id, "chem").await; |
| 9978 | let question_body = create_question_body( |
| 9979 | &app, |
| 9980 | &teacher, |
| 9981 | &exam, |
| 9982 | &subject, |
| 9983 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 9984 | "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), |
| 9985 | ) |
| 9986 | .await; |
| 9987 | let question = id_of(&question_body); |
| 9988 | |
| 9989 | // Enrolled: start the attempt, read the questions, save an answer. |
| 9990 | let res = send( |
| 9991 | &app, |
| 9992 | "POST", |
| 9993 | &format!("/exams/{exam}/attempt"), |
| 9994 | Some(&student), |
| 9995 | None, |
| 9996 | ) |
| 9997 | .await; |
| 9998 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 9999 | let res = send( |
| 10000 | &app, |
| 10001 | "GET", |
| 10002 | &format!("/exams/{exam}/attempt/questions"), |
| 10003 | Some(&student), |
| 10004 | None, |
| 10005 | ) |
| 10006 | .await; |
| 10007 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 10008 | let res = send( |
| 10009 | &app, |
| 10010 | "POST", |
| 10011 | &format!("/exams/{exam}/attempt/answers"), |
| 10012 | Some(&student), |
| 10013 | Some(json!({ "question_id": question, "selected": choice_of(&question_body, 1) })), |
| 10014 | ) |
| 10015 | .await; |
| 10016 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 10017 | |
| 10018 | // Unenrolled mid-exam: the instance wall closes over the sitting too. The |
| 10019 | // question list is instance content (`GET /exams/{id}` is already walled), |
| 10020 | // and answering from outside the roster would dodge the same wall the |
| 10021 | // exam room enforces on entry. |
| 10022 | let res = send( |
| 10023 | &app, |
| 10024 | "DELETE", |
| 10025 | &format!("/instances/{}/enrollments/{student_id}", t.instance), |
| 10026 | Some(&teacher), |
| 10027 | None, |
| 10028 | ) |
| 10029 | .await; |
| 10030 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 10031 | let res = send( |
| 10032 | &app, |
| 10033 | "GET", |
| 10034 | &format!("/exams/{exam}/attempt/questions"), |
| 10035 | Some(&student), |
| 10036 | None, |
| 10037 | ) |
| 10038 | .await; |
| 10039 | assert_eq!( |
| 10040 | res.status, |
| 10041 | StatusCode::FORBIDDEN, |
| 10042 | "question list after unenrollment: {}", |
| 10043 | res.body |
| 10044 | ); |
| 10045 | let res = send( |
| 10046 | &app, |
| 10047 | "POST", |
| 10048 | &format!("/exams/{exam}/attempt/answers"), |
| 10049 | Some(&student), |
| 10050 | Some(json!({ "question_id": question, "selected": choice_of(&question_body, 0) })), |
| 10051 | ) |
| 10052 | .await; |
| 10053 | assert_eq!( |
| 10054 | res.status, |
| 10055 | StatusCode::FORBIDDEN, |
| 10056 | "answer save after unenrollment: {}", |
| 10057 | res.body |
| 10058 | ); |
| 10059 | |
| 10060 | // Their own status and submission stay theirs: like the rejoin lock, |
| 10061 | // finishing submits what's already saved and writes nothing new. |
| 10062 | let res = send( |
| 10063 | &app, |
| 10064 | "GET", |
| 10065 | &format!("/exams/{exam}/attempt"), |
| 10066 | Some(&student), |
| 10067 | None, |
| 10068 | ) |
| 10069 | .await; |
| 10070 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 10071 | let res = send( |
| 10072 | &app, |
| 10073 | "POST", |
| 10074 | &format!("/exams/{exam}/attempt/finish"), |
| 10075 | Some(&student), |
| 10076 | None, |
| 10077 | ) |
| 10078 | .await; |
| 10079 | assert_eq!( |
| 10080 | res.status, |
| 10081 | StatusCode::OK, |
| 10082 | "finish stays open: {}", |
| 10083 | res.body |
| 10084 | ); |
| 10085 | assert_eq!(res.body["status"], "submitted"); |
| 10086 | assert_eq!(res.body["answered"], 1, "the enrolled-time answer survives"); |
| 10087 | } |
| 10088 | |
| 10089 | #[tokio::test] |
| 10090 | async fn answer_saves_stop_at_the_deadline() { |
| 10091 | let (app, db) = app_and_db().await; |
| 10092 | let teacher = login_as(&app, &db, "dl_t", "teacher").await; |
| 10093 | let student = login(&app, "dila").await; |
| 10094 | let student_id = me_id(&app, &student).await; |
| 10095 | let mudur = login_as(&app, &db, "dl_m", "manager").await; |
| 10096 | scheduling_kinds(&app, &mudur).await; |
| 10097 | let t = taught_under(&app, &mudur, &teacher, "geo").await; |
| 10098 | let subject = create_subject(&app, &teacher, &t.course, "general").await; |
| 10099 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 10100 | let now = Timestamp::now().as_millis(); |
| 10101 | |
| 10102 | // A window that closes right after the start — real time, the server |
| 10103 | // judges expiry by `Timestamp::now()`. |
| 10104 | let exam = scheduled_exam( |
| 10105 | &app, |
| 10106 | &teacher, |
| 10107 | &t.instance, |
| 10108 | json!({ "term": &t.term, "title": "blitz", "kind": "quiz", |
| 10109 | "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 1_500 }), |
| 10110 | ) |
| 10111 | .await; |
| 10112 | let question_body = create_question_body( |
| 10113 | &app, |
| 10114 | &teacher, |
| 10115 | &exam, |
| 10116 | &subject, |
| 10117 | json!({ "text": "quick", "kind": "choice", "points": 1, |
| 10118 | "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }), |
| 10119 | ) |
| 10120 | .await; |
| 10121 | let question = id_of(&question_body); |
| 10122 | let res = send( |
| 10123 | &app, |
| 10124 | "POST", |
| 10125 | &format!("/exams/{exam}/attempt"), |
| 10126 | Some(&student), |
| 10127 | None, |
| 10128 | ) |
| 10129 | .await; |
| 10130 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 10131 | let res = send( |
| 10132 | &app, |
| 10133 | "POST", |
| 10134 | &format!("/exams/{exam}/attempt/answers"), |
| 10135 | Some(&student), |
| 10136 | Some(json!({ "question_id": question, "selected": choice_of(&question_body, 0) })), |
| 10137 | ) |
| 10138 | .await; |
| 10139 | assert_eq!( |
| 10140 | res.status, |
| 10141 | StatusCode::OK, |
| 10142 | "inside the window: {}", |
| 10143 | res.body |
| 10144 | ); |
| 10145 | |
| 10146 | tokio::time::sleep(std::time::Duration::from_millis(1_700)).await; |
| 10147 | |
| 10148 | let res = send( |
| 10149 | &app, |
| 10150 | "POST", |
| 10151 | &format!("/exams/{exam}/attempt/answers"), |
| 10152 | Some(&student), |
| 10153 | Some(json!({ "question_id": question, "selected": choice_of(&question_body, 1) })), |
| 10154 | ) |
| 10155 | .await; |
| 10156 | assert_eq!(res.status, StatusCode::CONFLICT, "expired: {}", res.body); |
| 10157 | |
| 10158 | // The pre-deadline answer survives untouched for grading. |
| 10159 | let res = send( |
| 10160 | &app, |
| 10161 | "GET", |
| 10162 | &format!("/exams/{exam}/attempts/{student_id}/answers"), |
| 10163 | Some(&teacher), |
| 10164 | None, |
| 10165 | ) |
| 10166 | .await; |
| 10167 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 10168 | assert_eq!( |
| 10169 | res.body["answers"][0]["selected"], |
| 10170 | choice_of(&question_body, 0) |
| 10171 | ); |
| 10172 | } |
| 10173 | |
| 10174 | #[tokio::test] |
| 10175 | async fn teacher_answer_sheet_judges_choices_and_suggests_a_score() { |
| 10176 | let (app, db) = app_and_db().await; |
| 10177 | let teacher = login_as(&app, &db, "sc_t", "teacher").await; |
| 10178 | let student = login(&app, "sena").await; |
| 10179 | let student_id = me_id(&app, &student).await; |
| 10180 | let (_t, exam, subject) = |
| 10181 | open_exam_with_student(&app, &db, &teacher, &student_id, "chem").await; |
| 10182 | let q1_body = create_question_body( |
| 10183 | &app, |
| 10184 | &teacher, |
| 10185 | &exam, |
| 10186 | &subject, |
| 10187 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 10188 | "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), |
| 10189 | ) |
| 10190 | .await; |
| 10191 | let q1 = id_of(&q1_body); |
| 10192 | let q2_body = create_question_body( |
| 10193 | &app, |
| 10194 | &teacher, |
| 10195 | &exam, |
| 10196 | &subject, |
| 10197 | json!({ "text": "3 + 3?", "kind": "choice", "points": 20, |
| 10198 | "choices": [{"id": "c0", "text": "6"}, {"id": "c1", "text": "7"}], "correct": "c0" }), |
| 10199 | ) |
| 10200 | .await; |
| 10201 | let q2 = id_of(&q2_body); |
| 10202 | let q3 = create_question( |
| 10203 | &app, |
| 10204 | &teacher, |
| 10205 | &exam, |
| 10206 | &subject, |
| 10207 | json!({ "text": "Explain.", "kind": "text", "points": 30 }), |
| 10208 | ) |
| 10209 | .await; |
| 10210 | let sheet_uri = format!("/exams/{exam}/attempts/{student_id}/answers"); |
| 10211 | |
| 10212 | // No attempt yet: no sheet to read. |
| 10213 | let res = send(&app, "GET", &sheet_uri, Some(&teacher), None).await; |
| 10214 | assert_eq!(res.status, StatusCode::NOT_FOUND, "no attempt yet"); |
| 10215 | |
| 10216 | let res = send( |
| 10217 | &app, |
| 10218 | "POST", |
| 10219 | &format!("/exams/{exam}/attempt"), |
| 10220 | Some(&student), |
| 10221 | None, |
| 10222 | ) |
| 10223 | .await; |
| 10224 | assert_eq!(res.status, StatusCode::CREATED); |
| 10225 | for body in [ |
| 10226 | json!({ "question_id": q1, "selected": choice_of(&q1_body, 1) }), // right |
| 10227 | json!({ "question_id": q2, "selected": choice_of(&q2_body, 1) }), // wrong |
| 10228 | json!({ "question_id": q3, "text": "entropy grows" }), |
| 10229 | ] { |
| 10230 | let res = send( |
| 10231 | &app, |
| 10232 | "POST", |
| 10233 | &format!("/exams/{exam}/attempt/answers"), |
| 10234 | Some(&student), |
| 10235 | Some(body), |
| 10236 | ) |
| 10237 | .await; |
| 10238 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 10239 | } |
| 10240 | |
| 10241 | // The grader's view: judged rows plus the suggested score. |
| 10242 | let res = send(&app, "GET", &sheet_uri, Some(&teacher), None).await; |
| 10243 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 10244 | assert_eq!(res.body["exam"], exam); |
| 10245 | assert_eq!(res.body["user"]["username"], "sena"); |
| 10246 | let answers = res.body["answers"].as_array().expect("answers"); |
| 10247 | assert_eq!(answers.len(), 3); |
| 10248 | assert_eq!(answers[0]["question"], q1); |
| 10249 | assert_eq!(answers[0]["is_correct"], true); |
| 10250 | assert_eq!(answers[1]["is_correct"], false); |
| 10251 | assert_eq!(answers[2]["text"], "entropy grows"); |
| 10252 | assert!( |
| 10253 | answers[2]["is_correct"].is_null(), |
| 10254 | "text is the grader's call" |
| 10255 | ); |
| 10256 | assert_eq!(res.body["auto_score"]["earned"], 10); |
| 10257 | assert_eq!( |
| 10258 | res.body["auto_score"]["possible"], 30, |
| 10259 | "text points never counted" |
| 10260 | ); |
| 10261 | |
| 10262 | // The sheet is teacher-side only; students keep using their own view. |
| 10263 | let res = send(&app, "GET", &sheet_uri, Some(&student), None).await; |
| 10264 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 10265 | } |
| 10266 | |
| 10267 | #[tokio::test] |
| 10268 | async fn live_monitor_tracks_answer_progress() { |
| 10269 | let (app, db) = app_and_db().await; |
| 10270 | let teacher = login_as(&app, &db, "prg_t", "teacher").await; |
| 10271 | let ayla = login(&app, "ayla").await; |
| 10272 | let bora = login(&app, "bora").await; |
| 10273 | let ayla_id = me_id(&app, &ayla).await; |
| 10274 | let bora_id = me_id(&app, &bora).await; |
| 10275 | let (t, exam, subject) = open_exam_with_student(&app, &db, &teacher, &ayla_id, "stats").await; |
| 10276 | enroll(&app, &teacher, &t.instance, &bora_id).await; |
| 10277 | let question_body = create_question_body( |
| 10278 | &app, |
| 10279 | &teacher, |
| 10280 | &exam, |
| 10281 | &subject, |
| 10282 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 10283 | "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), |
| 10284 | ) |
| 10285 | .await; |
| 10286 | let question = id_of(&question_body); |
| 10287 | create_question( |
| 10288 | &app, |
| 10289 | &teacher, |
| 10290 | &exam, |
| 10291 | &subject, |
| 10292 | json!({ "text": "Explain.", "kind": "text", "points": 20 }), |
| 10293 | ) |
| 10294 | .await; |
| 10295 | |
| 10296 | // Starting reports zero progress out of two questions. |
| 10297 | let res = send( |
| 10298 | &app, |
| 10299 | "POST", |
| 10300 | &format!("/exams/{exam}/attempt"), |
| 10301 | Some(&ayla), |
| 10302 | None, |
| 10303 | ) |
| 10304 | .await; |
| 10305 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 10306 | assert_eq!(res.body["answered"], 0); |
| 10307 | assert_eq!(res.body["question_count"], 2); |
| 10308 | |
| 10309 | let res = send( |
| 10310 | &app, |
| 10311 | "POST", |
| 10312 | &format!("/exams/{exam}/attempt/answers"), |
| 10313 | Some(&ayla), |
| 10314 | Some(json!({ "question_id": question, "selected": choice_of(&question_body, 1) })), |
| 10315 | ) |
| 10316 | .await; |
| 10317 | assert_eq!(res.status, StatusCode::OK); |
| 10318 | let saved_at = res.body["updated_at"].as_i64().expect("updated_at"); |
| 10319 | |
| 10320 | // The monitor: per-student progress and last activity, plus the total. |
| 10321 | let res = send( |
| 10322 | &app, |
| 10323 | "GET", |
| 10324 | &format!("/exams/{exam}/live"), |
| 10325 | Some(&teacher), |
| 10326 | None, |
| 10327 | ) |
| 10328 | .await; |
| 10329 | assert_eq!(res.status, StatusCode::OK); |
| 10330 | assert_eq!(res.body["question_count"], 2); |
| 10331 | let students = res.body["students"].as_array().expect("students"); |
| 10332 | assert_eq!(students[0]["user"]["username"], "ayla"); |
| 10333 | assert_eq!(students[0]["answered"], 1); |
| 10334 | assert_eq!(students[0]["last_activity"].as_i64(), Some(saved_at)); |
| 10335 | assert_eq!(students[1]["user"]["username"], "bora"); |
| 10336 | assert_eq!(students[1]["answered"], 0); |
| 10337 | assert!(students[1]["last_activity"].is_null()); |
| 10338 | } |
| 10339 | |
| 10340 | #[tokio::test] |
| 10341 | async fn questions_and_answers_cascade_with_deletes() { |
| 10342 | use hezarfen_backend::db::exam_answer; |
| 10343 | use hezarfen_backend::db::exam_question; |
| 10344 | |
| 10345 | let (app, db) = app_and_db().await; |
| 10346 | let teacher = login_as(&app, &db, "qc_t", "teacher").await; |
| 10347 | let student = login(&app, "cem").await; |
| 10348 | let student_id = me_id(&app, &student).await; |
| 10349 | let (t, exam, subject) = open_exam_with_student(&app, &db, &teacher, &student_id, "geo2").await; |
| 10350 | let q1_body = create_question_body( |
| 10351 | &app, |
| 10352 | &teacher, |
| 10353 | &exam, |
| 10354 | &subject, |
| 10355 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 10356 | "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), |
| 10357 | ) |
| 10358 | .await; |
| 10359 | let q1 = id_of(&q1_body); |
| 10360 | let q2_body = create_question_body( |
| 10361 | &app, |
| 10362 | &teacher, |
| 10363 | &exam, |
| 10364 | &subject, |
| 10365 | json!({ "text": "Explain.", "kind": "text", "points": 20 }), |
| 10366 | ) |
| 10367 | .await; |
| 10368 | let q2 = id_of(&q2_body); |
| 10369 | let res = send( |
| 10370 | &app, |
| 10371 | "POST", |
| 10372 | &format!("/exams/{exam}/attempt"), |
| 10373 | Some(&student), |
| 10374 | None, |
| 10375 | ) |
| 10376 | .await; |
| 10377 | assert_eq!(res.status, StatusCode::CREATED); |
| 10378 | for body in [ |
| 10379 | json!({ "question_id": q1, "selected": choice_of(&q1_body, 1) }), |
| 10380 | json!({ "question_id": q2, "text": "so" }), |
| 10381 | ] { |
| 10382 | let res = send( |
| 10383 | &app, |
| 10384 | "POST", |
| 10385 | &format!("/exams/{exam}/attempt/answers"), |
| 10386 | Some(&student), |
| 10387 | Some(body), |
| 10388 | ) |
| 10389 | .await; |
| 10390 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 10391 | } |
| 10392 | let exam_id = ExamId::from_key(&exam); |
| 10393 | assert_eq!( |
| 10394 | exam_question::list_for_exam(&db, &exam_id, None, 0) |
| 10395 | .await |
| 10396 | .unwrap() |
| 10397 | .0 |
| 10398 | .len(), |
| 10399 | 2 |
| 10400 | ); |
| 10401 | assert_eq!( |
| 10402 | exam_answer::list_for_exam(&db, &exam_id) |
| 10403 | .await |
| 10404 | .unwrap() |
| 10405 | .len(), |
| 10406 | 2 |
| 10407 | ); |
| 10408 | |
| 10409 | // Deleting one question takes its answers with it. The freeze gate now |
| 10410 | // lives inside `db::exam_question::delete`'s own transaction (not in a lock the |
| 10411 | // handler held), so the attempt has to go first for the cascade to be |
| 10412 | // exercised at all — that refusal is asserted here before it is cleared. |
| 10413 | let frozen = exam_question::list_for_exam(&db, &exam_id, None, 0) |
| 10414 | .await |
| 10415 | .unwrap() |
| 10416 | .0 |
| 10417 | .into_iter() |
| 10418 | .next() |
| 10419 | .unwrap(); |
| 10420 | assert!( |
| 10421 | matches!(exam_question::delete(&db, frozen).await, Err(err) if err.to_string().contains("after attempts")), |
| 10422 | "the gate must refuse a question delete while an attempt exists" |
| 10423 | ); |
| 10424 | sqlx::query("DELETE FROM exam_attempt WHERE exam = $1") |
| 10425 | .bind(exam_id.uuid()) |
| 10426 | .execute(&db) |
| 10427 | .await |
| 10428 | .unwrap(); |
| 10429 | let question = exam_question::list_for_exam(&db, &exam_id, None, 0) |
| 10430 | .await |
| 10431 | .unwrap() |
| 10432 | .0 |
| 10433 | .into_iter() |
| 10434 | .next() |
| 10435 | .unwrap(); |
| 10436 | exam_question::delete(&db, question).await.unwrap(); |
| 10437 | assert_eq!( |
| 10438 | exam_question::list_for_exam(&db, &exam_id, None, 0) |
| 10439 | .await |
| 10440 | .unwrap() |
| 10441 | .0 |
| 10442 | .len(), |
| 10443 | 1 |
| 10444 | ); |
| 10445 | assert_eq!( |
| 10446 | exam_answer::list_for_exam(&db, &exam_id) |
| 10447 | .await |
| 10448 | .unwrap() |
| 10449 | .len(), |
| 10450 | 1, |
| 10451 | "only the deleted question's answer goes" |
| 10452 | ); |
| 10453 | |
| 10454 | // Deleting the exam clears the rest. |
| 10455 | let res = send( |
| 10456 | &app, |
| 10457 | "DELETE", |
| 10458 | &format!("/exams/{exam}"), |
| 10459 | Some(&teacher), |
| 10460 | None, |
| 10461 | ) |
| 10462 | .await; |
| 10463 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 10464 | assert!( |
| 10465 | exam_question::list_for_exam(&db, &exam_id, None, 0) |
| 10466 | .await |
| 10467 | .unwrap() |
| 10468 | .0 |
| 10469 | .is_empty() |
| 10470 | ); |
| 10471 | assert!( |
| 10472 | exam_answer::list_for_exam(&db, &exam_id) |
| 10473 | .await |
| 10474 | .unwrap() |
| 10475 | .is_empty() |
| 10476 | ); |
| 10477 | |
| 10478 | // And detaching the şube cascades through its exams' questions and |
| 10479 | // answers. (A catalog course a şube still teaches is not deletable, so the |
| 10480 | // detach is where this cascade lives now.) |
| 10481 | let now = Timestamp::now().as_millis(); |
| 10482 | let exam2 = scheduled_exam( |
| 10483 | &app, |
| 10484 | &teacher, |
| 10485 | &t.instance, |
| 10486 | json!({ "term": &t.term, "title": "retake", "kind": "quiz", |
| 10487 | "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), |
| 10488 | ) |
| 10489 | .await; |
| 10490 | let q_body = create_question_body( |
| 10491 | &app, |
| 10492 | &teacher, |
| 10493 | &exam2, |
| 10494 | &subject, |
| 10495 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 10496 | "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), |
| 10497 | ) |
| 10498 | .await; |
| 10499 | let q = id_of(&q_body); |
| 10500 | let res = send( |
| 10501 | &app, |
| 10502 | "POST", |
| 10503 | &format!("/exams/{exam2}/attempt"), |
| 10504 | Some(&student), |
| 10505 | None, |
| 10506 | ) |
| 10507 | .await; |
| 10508 | assert_eq!(res.status, StatusCode::CREATED); |
| 10509 | let res = send( |
| 10510 | &app, |
| 10511 | "POST", |
| 10512 | &format!("/exams/{exam2}/attempt/answers"), |
| 10513 | Some(&student), |
| 10514 | Some(json!({ "question_id": q, "selected": choice_of(&q_body, 1) })), |
| 10515 | ) |
| 10516 | .await; |
| 10517 | assert_eq!(res.status, StatusCode::OK); |
| 10518 | |
| 10519 | unenroll(&app, &teacher, &t.instance, &student_id).await; |
| 10520 | assert_eq!( |
| 10521 | send( |
| 10522 | &app, |
| 10523 | "DELETE", |
| 10524 | &format!("/classes/{}/instances/{}", t.class, t.instance), |
| 10525 | Some(&teacher), |
| 10526 | None |
| 10527 | ) |
| 10528 | .await |
| 10529 | .status, |
| 10530 | StatusCode::NO_CONTENT |
| 10531 | ); |
| 10532 | let res = send( |
| 10533 | &app, |
| 10534 | "DELETE", |
| 10535 | &format!("/courses/{}", t.course), |
| 10536 | Some(&teacher), |
| 10537 | None, |
| 10538 | ) |
| 10539 | .await; |
| 10540 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 10541 | let exam2_id = ExamId::from_key(&exam2); |
| 10542 | assert!( |
| 10543 | exam_question::list_for_exam(&db, &exam2_id, None, 0) |
| 10544 | .await |
| 10545 | .unwrap() |
| 10546 | .0 |
| 10547 | .is_empty() |
| 10548 | ); |
| 10549 | assert!( |
| 10550 | exam_answer::list_for_exam(&db, &exam2_id) |
| 10551 | .await |
| 10552 | .unwrap() |
| 10553 | .is_empty() |
| 10554 | ); |
| 10555 | // The course's subjects go down with it too. |
| 10556 | let res = send( |
| 10557 | &app, |
| 10558 | "GET", |
| 10559 | &format!("/subjects/{subject}"), |
| 10560 | Some(&teacher), |
| 10561 | None, |
| 10562 | ) |
| 10563 | .await; |
| 10564 | assert_eq!(res.status, StatusCode::NOT_FOUND, "subject cascaded"); |
| 10565 | } |
| 10566 | |
| 10567 | #[tokio::test] |
| 10568 | async fn question_patch_revalidates_the_stale_kind_bundle() { |
| 10569 | let (app, db) = app_and_db().await; |
| 10570 | let teacher = login_as(&app, &db, "rv_t", "teacher").await; |
| 10571 | let mudur = login_as(&app, &db, "rv_m", "manager").await; |
| 10572 | scheduling_kinds(&app, &mudur).await; |
| 10573 | let t = taught_under(&app, &mudur, &teacher, "sets").await; |
| 10574 | let subject = create_subject(&app, &teacher, &t.course, "unions").await; |
| 10575 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "final", "final").await; |
| 10576 | let question_body = create_question_body( |
| 10577 | &app, |
| 10578 | &teacher, |
| 10579 | &exam, |
| 10580 | &subject, |
| 10581 | json!({ "text": "pick", "kind": "choice", "points": 10, |
| 10582 | "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}, {"id": "c2", "text": "c"}], "correct": "c2" }), |
| 10583 | ) |
| 10584 | .await; |
| 10585 | let question = id_of(&question_body); |
| 10586 | let uri = format!("/exams/{exam}/questions/{question}"); |
| 10587 | |
| 10588 | // Shrinking the options while keeping the old `correct` would leave it |
| 10589 | // dangling past the end — the merge must re-validate the bundle. |
| 10590 | let res = send( |
| 10591 | &app, |
| 10592 | "PATCH", |
| 10593 | &uri, |
| 10594 | Some(&teacher), |
| 10595 | Some(json!({ "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}] })), |
| 10596 | ) |
| 10597 | .await; |
| 10598 | assert_eq!( |
| 10599 | res.status, |
| 10600 | StatusCode::BAD_REQUEST, |
| 10601 | "kept correct=2 dangles: {}", |
| 10602 | res.body |
| 10603 | ); |
| 10604 | |
| 10605 | // Same shrink with `correct` brought along is fine. |
| 10606 | let res = send( |
| 10607 | &app, |
| 10608 | "PATCH", |
| 10609 | &uri, |
| 10610 | Some(&teacher), |
| 10611 | Some(json!({ "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c1" })), |
| 10612 | ) |
| 10613 | .await; |
| 10614 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 10615 | assert_eq!(res.body["correct"], res.body["choices"][1]["id"]); |
| 10616 | |
| 10617 | // A lone out-of-range `correct` against the kept choices is caught too. |
| 10618 | let res = send( |
| 10619 | &app, |
| 10620 | "PATCH", |
| 10621 | &uri, |
| 10622 | Some(&teacher), |
| 10623 | Some(json!({ "correct": "c5" })), |
| 10624 | ) |
| 10625 | .await; |
| 10626 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 10627 | |
| 10628 | // Clearing just one half of the bundle can't leave a half-question. |
| 10629 | let res = send( |
| 10630 | &app, |
| 10631 | "PATCH", |
| 10632 | &uri, |
| 10633 | Some(&teacher), |
| 10634 | Some(json!({ "correct": null })), |
| 10635 | ) |
| 10636 | .await; |
| 10637 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 10638 | |
| 10639 | // Nothing of the failed PATCHes stuck. |
| 10640 | let res = send( |
| 10641 | &app, |
| 10642 | "GET", |
| 10643 | &format!("/exams/{exam}/questions"), |
| 10644 | Some(&teacher), |
| 10645 | None, |
| 10646 | ) |
| 10647 | .await; |
| 10648 | assert_eq!( |
| 10649 | common::items(&res.body)[0]["choices"] |
| 10650 | .as_array() |
| 10651 | .unwrap() |
| 10652 | .len(), |
| 10653 | 2 |
| 10654 | ); |
| 10655 | assert_eq!( |
| 10656 | common::items(&res.body)[0]["correct"], |
| 10657 | common::items(&res.body)[0]["choices"][1]["id"] |
| 10658 | ); |
| 10659 | } |
| 10660 | |
| 10661 | #[tokio::test] |
| 10662 | async fn question_authoring_follows_course_management() { |
| 10663 | let (app, db) = app_and_db().await; |
| 10664 | let teacher = login_as(&app, &db, "own_t", "teacher").await; |
| 10665 | let boss = login_as(&app, &db, "own_m", "manager").await; |
| 10666 | scheduling_kinds(&app, &boss).await; |
| 10667 | let t = taught_under(&app, &boss, &teacher, "greek").await; |
| 10668 | let subject = create_subject(&app, &boss, &t.course, "alphabet").await; |
| 10669 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "final", "final").await; |
| 10670 | |
| 10671 | // A manager+ authors questions in anyone's instance, like every other |
| 10672 | // instance-management write. |
| 10673 | let question_body = create_question_body( |
| 10674 | &app, |
| 10675 | &boss, |
| 10676 | &exam, |
| 10677 | &subject, |
| 10678 | json!({ "text": "pick", "kind": "choice", "points": 10, |
| 10679 | "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }), |
| 10680 | ) |
| 10681 | .await; |
| 10682 | let question = id_of(&question_body); |
| 10683 | let res = send( |
| 10684 | &app, |
| 10685 | "PATCH", |
| 10686 | &format!("/exams/{exam}/questions/{question}"), |
| 10687 | Some(&boss), |
| 10688 | Some(json!({ "points": 20 })), |
| 10689 | ) |
| 10690 | .await; |
| 10691 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 10692 | let res = send( |
| 10693 | &app, |
| 10694 | "DELETE", |
| 10695 | &format!("/exams/{exam}/questions/{question}"), |
| 10696 | Some(&boss), |
| 10697 | None, |
| 10698 | ) |
| 10699 | .await; |
| 10700 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 10701 | } |
| 10702 | |
| 10703 | #[tokio::test] |
| 10704 | async fn concurrent_answer_saves_never_collide() { |
| 10705 | let (app, db) = app_and_db().await; |
| 10706 | let teacher = login_as(&app, &db, "cc_t", "teacher").await; |
| 10707 | let student = login(&app, "cana").await; |
| 10708 | let student_id = me_id(&app, &student).await; |
| 10709 | let (_t, exam, subject) = |
| 10710 | open_exam_with_student(&app, &db, &teacher, &student_id, "race").await; |
| 10711 | let question_body = create_question_body( |
| 10712 | &app, |
| 10713 | &teacher, |
| 10714 | &exam, |
| 10715 | &subject, |
| 10716 | json!({ "text": "pick", "kind": "choice", "points": 10, |
| 10717 | "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}, {"id": "c2", "text": "c"}], "correct": "c0" }), |
| 10718 | ) |
| 10719 | .await; |
| 10720 | let question = id_of(&question_body); |
| 10721 | let res = send( |
| 10722 | &app, |
| 10723 | "POST", |
| 10724 | &format!("/exams/{exam}/attempt"), |
| 10725 | Some(&student), |
| 10726 | None, |
| 10727 | ) |
| 10728 | .await; |
| 10729 | assert_eq!(res.status, StatusCode::CREATED); |
| 10730 | |
| 10731 | // A burst of autosaves for the same question (fast clicking / reconnect |
| 10732 | // races): the composite-id upsert must converge, never 500. |
| 10733 | let mut handles = Vec::new(); |
| 10734 | for i in 0..24i64 { |
| 10735 | let app = app.clone(); |
| 10736 | let student = student.clone(); |
| 10737 | let uri = format!("/exams/{exam}/attempt/answers"); |
| 10738 | let body = json!({ "question_id": question, "selected": choice_of(&question_body, (i % 3) as usize) }); |
| 10739 | handles.push(tokio::spawn(async move { |
| 10740 | send(&app, "POST", &uri, Some(&student), Some(body)) |
| 10741 | .await |
| 10742 | .status |
| 10743 | })); |
| 10744 | } |
| 10745 | for h in handles { |
| 10746 | assert_eq!( |
| 10747 | h.await.unwrap(), |
| 10748 | StatusCode::OK, |
| 10749 | "concurrent save must not fail" |
| 10750 | ); |
| 10751 | } |
| 10752 | |
| 10753 | // One row survives, whichever save won. |
| 10754 | let res = send( |
| 10755 | &app, |
| 10756 | "GET", |
| 10757 | &format!("/exams/{exam}/attempts/{student_id}/answers"), |
| 10758 | Some(&teacher), |
| 10759 | None, |
| 10760 | ) |
| 10761 | .await; |
| 10762 | assert_eq!(res.body["answers"].as_array().unwrap().len(), 1); |
| 10763 | let res = send( |
| 10764 | &app, |
| 10765 | "GET", |
| 10766 | &format!("/exams/{exam}/attempt"), |
| 10767 | Some(&student), |
| 10768 | None, |
| 10769 | ) |
| 10770 | .await; |
| 10771 | assert_eq!(res.body["answered"], 1, "24 saves, one answer"); |
| 10772 | } |
| 10773 | |
| 10774 | // --- course sessions + roll call ------------------------------------------ |
| 10775 | |
| 10776 | #[tokio::test] |
| 10777 | async fn session_crud_follows_course_management() { |
| 10778 | let (app, db) = app_and_db().await; |
| 10779 | let owner = login_as(&app, &db, "owner", "teacher").await; |
| 10780 | let rival = login_as(&app, &db, "rival", "teacher").await; |
| 10781 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 10782 | let student = login(&app, "ali").await; |
| 10783 | let mudur = login_as(&app, &db, "mudur_of_sessions", "manager").await; |
| 10784 | let t = taught_under(&app, &mudur, &owner, "algebra").await; |
| 10785 | let now = Timestamp::now().as_millis(); |
| 10786 | let start = now + 3_600_000; |
| 10787 | |
| 10788 | // Create: student 403, unrelated teacher 403, owner 201, manager+ 201. |
| 10789 | let body = json!({ "topic": "limits", "starts_at": start }); |
| 10790 | let res = send( |
| 10791 | &app, |
| 10792 | "POST", |
| 10793 | &format!("/instances/{}/sessions", t.instance), |
| 10794 | Some(&student), |
| 10795 | Some(body.clone()), |
| 10796 | ) |
| 10797 | .await; |
| 10798 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 10799 | let res = send( |
| 10800 | &app, |
| 10801 | "POST", |
| 10802 | &format!("/instances/{}/sessions", t.instance), |
| 10803 | Some(&rival), |
| 10804 | Some(body.clone()), |
| 10805 | ) |
| 10806 | .await; |
| 10807 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 10808 | let res = send( |
| 10809 | &app, |
| 10810 | "POST", |
| 10811 | &format!("/instances/{}/sessions", t.instance), |
| 10812 | Some(&owner), |
| 10813 | Some(body.clone()), |
| 10814 | ) |
| 10815 | .await; |
| 10816 | assert_eq!(res.status, StatusCode::CREATED); |
| 10817 | let session = id_of(&res.body); |
| 10818 | // The teacher defaults to the caller, rendered as a PersonRef. |
| 10819 | assert_eq!(res.body["teacher"]["username"], "owner"); |
| 10820 | assert_eq!(res.body["topic"], "limits"); |
| 10821 | assert_eq!(res.body["starts_at"], start); |
| 10822 | assert!(res.body["ends_at"].is_null()); |
| 10823 | // A distinct instant on purpose: `UNIQUE (class_course, starts_at)` makes |
| 10824 | // two lessons of one section unable to start together, so re-using |
| 10825 | // `start` here would measure that wall, not the manager's rights. |
| 10826 | let res = send( |
| 10827 | &app, |
| 10828 | "POST", |
| 10829 | &format!("/instances/{}/sessions", t.instance), |
| 10830 | Some(&boss), |
| 10831 | Some(json!({ "topic": "limits", "starts_at": start + 60_000 })), |
| 10832 | ) |
| 10833 | .await; |
| 10834 | assert_eq!( |
| 10835 | res.status, |
| 10836 | StatusCode::CREATED, |
| 10837 | "manager+ manages any course" |
| 10838 | ); |
| 10839 | |
| 10840 | // Explicit teacher_id: must exist and be teacher+. |
| 10841 | let res = send( |
| 10842 | &app, |
| 10843 | "POST", |
| 10844 | &format!("/instances/{}/sessions", t.instance), |
| 10845 | Some(&owner), |
| 10846 | Some(json!({ "starts_at": now + 60_000, "teacher_id": "01UNKNOWN" })), |
| 10847 | ) |
| 10848 | .await; |
| 10849 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "unknown teacher"); |
| 10850 | let ali_id = me_id(&app, &student).await; |
| 10851 | let res = send( |
| 10852 | &app, |
| 10853 | "POST", |
| 10854 | &format!("/instances/{}/sessions", t.instance), |
| 10855 | Some(&owner), |
| 10856 | Some(json!({ "starts_at": now + 60_000, "teacher_id": ali_id })), |
| 10857 | ) |
| 10858 | .await; |
| 10859 | assert_eq!( |
| 10860 | res.status, |
| 10861 | StatusCode::BAD_REQUEST, |
| 10862 | "a student cannot teach" |
| 10863 | ); |
| 10864 | let rival_id = me_id(&app, &rival).await; |
| 10865 | let res = send( |
| 10866 | &app, |
| 10867 | "POST", |
| 10868 | &format!("/instances/{}/sessions", t.instance), |
| 10869 | Some(&owner), |
| 10870 | Some(json!({ "starts_at": now + 120_000, "teacher_id": rival_id })), |
| 10871 | ) |
| 10872 | .await; |
| 10873 | assert_eq!(res.status, StatusCode::CREATED); |
| 10874 | assert_eq!(res.body["teacher"]["username"], "rival"); |
| 10875 | let rival_session = id_of(&res.body); |
| 10876 | |
| 10877 | // Time range validated on create and update. |
| 10878 | let res = send( |
| 10879 | &app, |
| 10880 | "POST", |
| 10881 | &format!("/instances/{}/sessions", t.instance), |
| 10882 | Some(&owner), |
| 10883 | Some(json!({ "starts_at": now + 10_000, "ends_at": now + 5_000 })), |
| 10884 | ) |
| 10885 | .await; |
| 10886 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 10887 | |
| 10888 | // Past lessons cannot be scheduled — on create or by a later PATCH, |
| 10889 | // whichever end carries the past value. |
| 10890 | let res = send( |
| 10891 | &app, |
| 10892 | "POST", |
| 10893 | &format!("/instances/{}/sessions", t.instance), |
| 10894 | Some(&owner), |
| 10895 | Some(json!({ "starts_at": now - 3_600_000 })), |
| 10896 | ) |
| 10897 | .await; |
| 10898 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 10899 | let res = send( |
| 10900 | &app, |
| 10901 | "POST", |
| 10902 | &format!("/instances/{}/sessions", t.instance), |
| 10903 | Some(&owner), |
| 10904 | Some(json!({ "starts_at": now + 3_600_000, "ends_at": now - 3_600_000 })), |
| 10905 | ) |
| 10906 | .await; |
| 10907 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "past ends_at"); |
| 10908 | |
| 10909 | // Reads follow course visibility: an unenrolled student is refused … |
| 10910 | let res = send( |
| 10911 | &app, |
| 10912 | "GET", |
| 10913 | &format!("/instances/{}/sessions", t.instance), |
| 10914 | Some(&student), |
| 10915 | None, |
| 10916 | ) |
| 10917 | .await; |
| 10918 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 10919 | |
| 10920 | // … an enrolled one reads; parents must exist. |
| 10921 | let res = send( |
| 10922 | &app, |
| 10923 | "POST", |
| 10924 | &format!("/instances/{}/enrollments", t.instance), |
| 10925 | Some(&owner), |
| 10926 | Some(json!({ "user_id": ali_id })), |
| 10927 | ) |
| 10928 | .await; |
| 10929 | assert_eq!(res.status, StatusCode::OK); |
| 10930 | let res = send( |
| 10931 | &app, |
| 10932 | "GET", |
| 10933 | &format!("/instances/{}/sessions", t.instance), |
| 10934 | Some(&student), |
| 10935 | None, |
| 10936 | ) |
| 10937 | .await; |
| 10938 | assert_eq!(res.status, StatusCode::OK); |
| 10939 | // owner's, the manager's, and the one taught by `rival` — newest starts_at |
| 10940 | // first, so the two later lessons precede the earlier `rival` one. |
| 10941 | assert_eq!(common::items(&res.body).len(), 3); |
| 10942 | assert_eq!(common::items(&res.body)[2]["starts_at"], now + 120_000); |
| 10943 | let res = send(&app, "GET", "/courses/nope/sessions", Some(&student), None).await; |
| 10944 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 10945 | let res = send( |
| 10946 | &app, |
| 10947 | "GET", |
| 10948 | &format!("/sessions/{session}"), |
| 10949 | Some(&student), |
| 10950 | None, |
| 10951 | ) |
| 10952 | .await; |
| 10953 | assert_eq!(res.status, StatusCode::OK); |
| 10954 | // The session's own teacher reads it without course rights; a session of |
| 10955 | // someone else's course stays out of reach. |
| 10956 | let res = send( |
| 10957 | &app, |
| 10958 | "GET", |
| 10959 | &format!("/sessions/{rival_session}"), |
| 10960 | Some(&rival), |
| 10961 | None, |
| 10962 | ) |
| 10963 | .await; |
| 10964 | assert_eq!(res.status, StatusCode::OK); |
| 10965 | let res = send( |
| 10966 | &app, |
| 10967 | "GET", |
| 10968 | &format!("/sessions/{session}"), |
| 10969 | Some(&rival), |
| 10970 | None, |
| 10971 | ) |
| 10972 | .await; |
| 10973 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 10974 | let res = send(&app, "GET", "/sessions/nope", Some(&student), None).await; |
| 10975 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 10976 | |
| 10977 | // PATCH: management rights; set/keep/clear semantics; range check. |
| 10978 | let res = send( |
| 10979 | &app, |
| 10980 | "PATCH", |
| 10981 | &format!("/sessions/{session}"), |
| 10982 | Some(&rival), |
| 10983 | Some(json!({ "topic": "hijack" })), |
| 10984 | ) |
| 10985 | .await; |
| 10986 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 10987 | let res = send( |
| 10988 | &app, |
| 10989 | "PATCH", |
| 10990 | &format!("/sessions/{session}"), |
| 10991 | Some(&owner), |
| 10992 | Some(json!({ "topic": "derivatives", "ends_at": start + 100_000 })), |
| 10993 | ) |
| 10994 | .await; |
| 10995 | assert_eq!(res.status, StatusCode::OK); |
| 10996 | assert_eq!(res.body["topic"], "derivatives"); |
| 10997 | assert_eq!(res.body["ends_at"], start + 100_000); |
| 10998 | assert_eq!(res.body["starts_at"], start, "omitted keeps"); |
| 10999 | let res = send( |
| 11000 | &app, |
| 11001 | "PATCH", |
| 11002 | &format!("/sessions/{session}"), |
| 11003 | Some(&owner), |
| 11004 | Some(json!({ "ends_at": null })), |
| 11005 | ) |
| 11006 | .await; |
| 11007 | assert_eq!(res.status, StatusCode::OK); |
| 11008 | assert!(res.body["ends_at"].is_null(), "explicit null clears"); |
| 11009 | let res = send( |
| 11010 | &app, |
| 11011 | "PATCH", |
| 11012 | &format!("/sessions/{session}"), |
| 11013 | Some(&owner), |
| 11014 | Some(json!({ "ends_at": now + 1_800_000 })), |
| 11015 | ) |
| 11016 | .await; |
| 11017 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "ends before starts"); |
| 11018 | let res = send( |
| 11019 | &app, |
| 11020 | "PATCH", |
| 11021 | &format!("/sessions/{session}"), |
| 11022 | Some(&owner), |
| 11023 | Some(json!({ "starts_at": now - 3_600_000 })), |
| 11024 | ) |
| 11025 | .await; |
| 11026 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "backdated start"); |
| 11027 | let res = send( |
| 11028 | &app, |
| 11029 | "PATCH", |
| 11030 | &format!("/sessions/{session}"), |
| 11031 | Some(&owner), |
| 11032 | Some(json!({ "ends_at": now - 3_600_000 })), |
| 11033 | ) |
| 11034 | .await; |
| 11035 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "backdated end"); |
| 11036 | // A lesson already underway (start inside the grace) stays editable as |
| 11037 | // long as the past time is only kept, not re-sent. |
| 11038 | let res = send( |
| 11039 | &app, |
| 11040 | "POST", |
| 11041 | &format!("/instances/{}/sessions", t.instance), |
| 11042 | Some(&owner), |
| 11043 | Some(json!({ "topic": "underway", "starts_at": now - 1_000 })), |
| 11044 | ) |
| 11045 | .await; |
| 11046 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 11047 | let underway = id_of(&res.body); |
| 11048 | let res = send( |
| 11049 | &app, |
| 11050 | "PATCH", |
| 11051 | &format!("/sessions/{underway}"), |
| 11052 | Some(&owner), |
| 11053 | Some(json!({ "topic": "still editable" })), |
| 11054 | ) |
| 11055 | .await; |
| 11056 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 11057 | // Reassigning the teacher revalidates the target. |
| 11058 | let res = send( |
| 11059 | &app, |
| 11060 | "PATCH", |
| 11061 | &format!("/sessions/{rival_session}"), |
| 11062 | Some(&boss), |
| 11063 | Some(json!({ "teacher_id": ali_id })), |
| 11064 | ) |
| 11065 | .await; |
| 11066 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 11067 | |
| 11068 | // DELETE: management rights. |
| 11069 | let res = send( |
| 11070 | &app, |
| 11071 | "DELETE", |
| 11072 | &format!("/sessions/{session}"), |
| 11073 | Some(&rival), |
| 11074 | None, |
| 11075 | ) |
| 11076 | .await; |
| 11077 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11078 | let res = send( |
| 11079 | &app, |
| 11080 | "DELETE", |
| 11081 | &format!("/sessions/{session}"), |
| 11082 | Some(&owner), |
| 11083 | None, |
| 11084 | ) |
| 11085 | .await; |
| 11086 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 11087 | let res = send( |
| 11088 | &app, |
| 11089 | "GET", |
| 11090 | &format!("/sessions/{session}"), |
| 11091 | Some(&owner), |
| 11092 | None, |
| 11093 | ) |
| 11094 | .await; |
| 11095 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 11096 | } |
| 11097 | |
| 11098 | #[tokio::test] |
| 11099 | async fn roll_call_rbac_and_upsert() { |
| 11100 | let (app, db) = app_and_db().await; |
| 11101 | let owner = login_as(&app, &db, "owner", "teacher").await; |
| 11102 | let hoca = login_as(&app, &db, "hoca", "teacher").await; |
| 11103 | let rival = login_as(&app, &db, "rival", "teacher").await; |
| 11104 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 11105 | let ali = login(&app, "ali").await; |
| 11106 | let veli = login(&app, "veli").await; |
| 11107 | let ali_id = me_id(&app, &ali).await; |
| 11108 | let veli_id = me_id(&app, &veli).await; |
| 11109 | let hoca_id = me_id(&app, &hoca).await; |
| 11110 | |
| 11111 | let mudur = login_as(&app, &db, "mudur_of_roll_call", "manager").await; |
| 11112 | let t = taught_under(&app, &mudur, &owner, "algebra").await; |
| 11113 | enroll(&app, &owner, &t.instance, &ali_id).await; |
| 11114 | let res = send( |
| 11115 | &app, |
| 11116 | "POST", |
| 11117 | &format!("/instances/{}/sessions", t.instance), |
| 11118 | Some(&owner), |
| 11119 | Some( |
| 11120 | json!({ "starts_at": Timestamp::now().as_millis() + 3_600_000, "teacher_id": hoca_id }), |
| 11121 | ), |
| 11122 | ) |
| 11123 | .await; |
| 11124 | assert_eq!(res.status, StatusCode::CREATED); |
| 11125 | let session = id_of(&res.body); |
| 11126 | let mark_uri = format!("/sessions/{session}/attendance"); |
| 11127 | |
| 11128 | // The session's teacher takes roll even without course-management rights. |
| 11129 | let res = send( |
| 11130 | &app, |
| 11131 | "POST", |
| 11132 | &mark_uri, |
| 11133 | Some(&hoca), |
| 11134 | Some(json!({ "status": "present", "user_id": ali_id })), |
| 11135 | ) |
| 11136 | .await; |
| 11137 | assert_eq!(res.status, StatusCode::OK); |
| 11138 | assert_eq!(res.body["user"]["username"], "ali"); |
| 11139 | assert_eq!(res.body["marked_by"]["username"], "hoca"); |
| 11140 | assert_eq!(res.body["class_course"].as_str().unwrap(), t.instance); |
| 11141 | |
| 11142 | // Re-marking overwrites — one row per session+user (course manager may too). |
| 11143 | let res = send( |
| 11144 | &app, |
| 11145 | "POST", |
| 11146 | &mark_uri, |
| 11147 | Some(&owner), |
| 11148 | Some(json!({ "status": "absent", "user_id": ali_id })), |
| 11149 | ) |
| 11150 | .await; |
| 11151 | assert_eq!(res.status, StatusCode::OK); |
| 11152 | // The roster follows roll-call rights: the session teacher reads it, a |
| 11153 | // student (even a listed one) and an unrelated teacher do not — students |
| 11154 | // get their own tallies via `/attendance/me`. |
| 11155 | let res = send(&app, "GET", &mark_uri, Some(&hoca), None).await; |
| 11156 | assert_eq!(res.status, StatusCode::OK); |
| 11157 | let roster = common::items(&res.body); |
| 11158 | assert_eq!(roster.len(), 1); |
| 11159 | assert_eq!(roster[0]["status"], "absent"); |
| 11160 | let res = send(&app, "GET", &mark_uri, Some(&ali), None).await; |
| 11161 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11162 | let res = send(&app, "GET", &mark_uri, Some(&rival), None).await; |
| 11163 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11164 | |
| 11165 | // Neither an unrelated teacher nor the student themselves may mark. |
| 11166 | let res = send( |
| 11167 | &app, |
| 11168 | "POST", |
| 11169 | &mark_uri, |
| 11170 | Some(&rival), |
| 11171 | Some(json!({ "status": "present", "user_id": ali_id })), |
| 11172 | ) |
| 11173 | .await; |
| 11174 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11175 | let res = send( |
| 11176 | &app, |
| 11177 | "POST", |
| 11178 | &mark_uri, |
| 11179 | Some(&ali), |
| 11180 | Some(json!({ "status": "present", "user_id": ali_id })), |
| 11181 | ) |
| 11182 | .await; |
| 11183 | assert_eq!( |
| 11184 | res.status, |
| 11185 | StatusCode::FORBIDDEN, |
| 11186 | "students never self-mark" |
| 11187 | ); |
| 11188 | |
| 11189 | // The roster comes from enrollment; targets must exist; statuses are closed. |
| 11190 | let res = send( |
| 11191 | &app, |
| 11192 | "POST", |
| 11193 | &mark_uri, |
| 11194 | Some(&hoca), |
| 11195 | Some(json!({ "status": "present", "user_id": veli_id })), |
| 11196 | ) |
| 11197 | .await; |
| 11198 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "not enrolled"); |
| 11199 | let res = send( |
| 11200 | &app, |
| 11201 | "POST", |
| 11202 | &mark_uri, |
| 11203 | Some(&hoca), |
| 11204 | Some(json!({ "status": "present", "user_id": "01UNKNOWN" })), |
| 11205 | ) |
| 11206 | .await; |
| 11207 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 11208 | let res = send( |
| 11209 | &app, |
| 11210 | "POST", |
| 11211 | &mark_uri, |
| 11212 | Some(&hoca), |
| 11213 | Some(json!({ "status": "sleeping", "user_id": ali_id })), |
| 11214 | ) |
| 11215 | .await; |
| 11216 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 11217 | let res = send( |
| 11218 | &app, |
| 11219 | "POST", |
| 11220 | "/sessions/nope/attendance", |
| 11221 | Some(&hoca), |
| 11222 | Some(json!({ "status": "present", "user_id": ali_id })), |
| 11223 | ) |
| 11224 | .await; |
| 11225 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 11226 | |
| 11227 | // The session teacher's own row is management's call: even the course |
| 11228 | // creator (teacher role) can't write it; a manager can. |
| 11229 | let res = send( |
| 11230 | &app, |
| 11231 | "POST", |
| 11232 | &mark_uri, |
| 11233 | Some(&hoca), |
| 11234 | Some(json!({ "status": "present", "user_id": hoca_id })), |
| 11235 | ) |
| 11236 | .await; |
| 11237 | assert_eq!( |
| 11238 | res.status, |
| 11239 | StatusCode::FORBIDDEN, |
| 11240 | "no self-declared presence" |
| 11241 | ); |
| 11242 | let res = send( |
| 11243 | &app, |
| 11244 | "POST", |
| 11245 | &mark_uri, |
| 11246 | Some(&owner), |
| 11247 | Some(json!({ "status": "present", "user_id": hoca_id })), |
| 11248 | ) |
| 11249 | .await; |
| 11250 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11251 | let res = send( |
| 11252 | &app, |
| 11253 | "POST", |
| 11254 | &mark_uri, |
| 11255 | Some(&boss), |
| 11256 | Some(json!({ "status": "late", "user_id": hoca_id })), |
| 11257 | ) |
| 11258 | .await; |
| 11259 | assert_eq!(res.status, StatusCode::OK); |
| 11260 | |
| 11261 | // Removal mirrors marking rights. |
| 11262 | let res = send( |
| 11263 | &app, |
| 11264 | "DELETE", |
| 11265 | &format!("{mark_uri}/{ali_id}"), |
| 11266 | Some(&rival), |
| 11267 | None, |
| 11268 | ) |
| 11269 | .await; |
| 11270 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11271 | let res = send( |
| 11272 | &app, |
| 11273 | "DELETE", |
| 11274 | &format!("{mark_uri}/{hoca_id}"), |
| 11275 | Some(&hoca), |
| 11276 | None, |
| 11277 | ) |
| 11278 | .await; |
| 11279 | assert_eq!( |
| 11280 | res.status, |
| 11281 | StatusCode::FORBIDDEN, |
| 11282 | "teacher row needs manager+" |
| 11283 | ); |
| 11284 | let res = send( |
| 11285 | &app, |
| 11286 | "DELETE", |
| 11287 | &format!("{mark_uri}/{hoca_id}"), |
| 11288 | Some(&boss), |
| 11289 | None, |
| 11290 | ) |
| 11291 | .await; |
| 11292 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 11293 | let res = send( |
| 11294 | &app, |
| 11295 | "DELETE", |
| 11296 | &format!("{mark_uri}/{ali_id}"), |
| 11297 | Some(&hoca), |
| 11298 | None, |
| 11299 | ) |
| 11300 | .await; |
| 11301 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 11302 | let res = send( |
| 11303 | &app, |
| 11304 | "DELETE", |
| 11305 | &format!("{mark_uri}/{ali_id}"), |
| 11306 | Some(&hoca), |
| 11307 | None, |
| 11308 | ) |
| 11309 | .await; |
| 11310 | assert_eq!(res.status, StatusCode::NOT_FOUND, "row already gone"); |
| 11311 | } |
| 11312 | |
| 11313 | #[tokio::test] |
| 11314 | async fn deleting_session_or_course_cascades_roll_call() { |
| 11315 | let (app, db) = app_and_db().await; |
| 11316 | let owner = login_as(&app, &db, "owner", "teacher").await; |
| 11317 | let ali = login(&app, "ali").await; |
| 11318 | let ali_id = me_id(&app, &ali).await; |
| 11319 | |
| 11320 | let mudur = login_as(&app, &db, "cascade_m", "manager").await; |
| 11321 | let t = taught_under(&app, &mudur, &owner, "algebra").await; |
| 11322 | enroll(&app, &owner, &t.instance, &ali_id).await; |
| 11323 | let now = Timestamp::now().as_millis(); |
| 11324 | let s1 = create_session(&app, &owner, &t.instance, now + 3_600_000).await; |
| 11325 | let s2 = create_session(&app, &owner, &t.instance, now + 7_200_000).await; |
| 11326 | for s in [&s1, &s2] { |
| 11327 | let res = send( |
| 11328 | &app, |
| 11329 | "POST", |
| 11330 | &format!("/sessions/{s}/attendance"), |
| 11331 | Some(&owner), |
| 11332 | Some(json!({ "status": "present", "user_id": ali_id })), |
| 11333 | ) |
| 11334 | .await; |
| 11335 | assert_eq!(res.status, StatusCode::OK); |
| 11336 | } |
| 11337 | let report = send(&app, "GET", "/attendance/me", Some(&ali), None).await; |
| 11338 | assert_eq!(report.body["sessions"]["total"], 2); |
| 11339 | |
| 11340 | // Deleting one session removes exactly its rows... |
| 11341 | let res = send( |
| 11342 | &app, |
| 11343 | "DELETE", |
| 11344 | &format!("/sessions/{s1}"), |
| 11345 | Some(&owner), |
| 11346 | None, |
| 11347 | ) |
| 11348 | .await; |
| 11349 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 11350 | let report = send(&app, "GET", "/attendance/me", Some(&ali), None).await; |
| 11351 | assert_eq!(report.body["sessions"]["total"], 1); |
| 11352 | |
| 11353 | // ...and tearing the teaching down removes the rest, sessions included: |
| 11354 | // detaching the instance sweeps its lessons and their roll call, which |
| 11355 | // frees the catalog row to go with them. |
| 11356 | unenroll(&app, &owner, &t.instance, &ali_id).await; |
| 11357 | let res = send( |
| 11358 | &app, |
| 11359 | "DELETE", |
| 11360 | &format!("/classes/{}/instances/{}", t.class, t.instance), |
| 11361 | Some(&owner), |
| 11362 | None, |
| 11363 | ) |
| 11364 | .await; |
| 11365 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 11366 | let res = send(&app, "GET", &format!("/sessions/{s2}"), Some(&ali), None).await; |
| 11367 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 11368 | let report = send(&app, "GET", "/attendance/me", Some(&ali), None).await; |
| 11369 | assert_eq!(report.body["sessions"]["total"], 0); |
| 11370 | assert!(report.body["courses"].as_array().unwrap().is_empty()); |
| 11371 | // The catalog row is free now, and goes the same way. |
| 11372 | let res = send( |
| 11373 | &app, |
| 11374 | "DELETE", |
| 11375 | &format!("/courses/{}", t.course), |
| 11376 | Some(&owner), |
| 11377 | None, |
| 11378 | ) |
| 11379 | .await; |
| 11380 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 11381 | } |
| 11382 | |
| 11383 | // --- work log --------------------------------------------------------------- |
| 11384 | |
| 11385 | #[tokio::test] |
| 11386 | async fn work_log_lifecycle_is_server_stamped_and_exclusive() { |
| 11387 | let (app, db) = app_and_db().await; |
| 11388 | let hoca = login_as(&app, &db, "hoca", "teacher").await; |
| 11389 | let ali = login(&app, "ali").await; |
| 11390 | |
| 11391 | // Staff only. |
| 11392 | let res = send(&app, "POST", "/work/check-in", Some(&ali), None).await; |
| 11393 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11394 | let res = send(&app, "GET", "/work/me", Some(&ali), None).await; |
| 11395 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11396 | |
| 11397 | // Check out before check-in conflicts. |
| 11398 | let res = send(&app, "POST", "/work/check-out", Some(&hoca), None).await; |
| 11399 | assert_eq!(res.status, StatusCode::CONFLICT); |
| 11400 | |
| 11401 | let res = send(&app, "POST", "/work/check-in", Some(&hoca), None).await; |
| 11402 | assert_eq!(res.status, StatusCode::CREATED); |
| 11403 | assert!(res.body["check_out"].is_null()); |
| 11404 | let first_in = res.body["check_in"].as_i64().unwrap(); |
| 11405 | |
| 11406 | // A second check-in neither opens a second stint nor resets the clock. |
| 11407 | let res = send(&app, "POST", "/work/check-in", Some(&hoca), None).await; |
| 11408 | assert_eq!(res.status, StatusCode::CONFLICT); |
| 11409 | let res = send(&app, "GET", "/work/me", Some(&hoca), None).await; |
| 11410 | let log = common::items(&res.body); |
| 11411 | assert_eq!(log.len(), 1); |
| 11412 | assert_eq!(log[0]["check_in"].as_i64().unwrap(), first_in); |
| 11413 | |
| 11414 | let res = send(&app, "POST", "/work/check-out", Some(&hoca), None).await; |
| 11415 | assert_eq!(res.status, StatusCode::OK); |
| 11416 | let out = res.body["check_out"].as_i64().unwrap(); |
| 11417 | assert!(out >= first_in); |
| 11418 | assert_eq!(res.body["duration_ms"].as_i64().unwrap(), out - first_in); |
| 11419 | let res = send(&app, "POST", "/work/check-out", Some(&hoca), None).await; |
| 11420 | assert_eq!(res.status, StatusCode::CONFLICT, "already checked out"); |
| 11421 | |
| 11422 | // The open slot is free again; the log keeps both stints, newest first. |
| 11423 | let res = send(&app, "POST", "/work/check-in", Some(&hoca), None).await; |
| 11424 | assert_eq!(res.status, StatusCode::CREATED); |
| 11425 | let res = send(&app, "GET", "/work/me", Some(&hoca), None).await; |
| 11426 | let log = common::items(&res.body); |
| 11427 | assert_eq!(log.len(), 2); |
| 11428 | assert!(log[0]["check_out"].is_null(), "open stint sorts newest"); |
| 11429 | assert!(!log[1]["check_out"].is_null()); |
| 11430 | } |
| 11431 | |
| 11432 | // --- pomodoro ---------------------------------------------------------------- |
| 11433 | |
| 11434 | #[tokio::test] |
| 11435 | async fn pomodoro_restart_replaces_finish_closes_and_teachers_read() { |
| 11436 | let (app, db) = app_and_db().await; |
| 11437 | let ali = login(&app, "ali").await; |
| 11438 | let hoca = login_as(&app, &db, "hoca", "teacher").await; |
| 11439 | let ali_id = me_id(&app, &ali).await; |
| 11440 | |
| 11441 | // Students only on start; finishing with nothing running conflicts. |
| 11442 | let res = send(&app, "POST", "/pomodoro/start", Some(&hoca), None).await; |
| 11443 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11444 | let res = send(&app, "POST", "/pomodoro/finish", Some(&ali), None).await; |
| 11445 | assert_eq!(res.status, StatusCode::CONFLICT); |
| 11446 | |
| 11447 | let res = send(&app, "POST", "/pomodoro/start", Some(&ali), None).await; |
| 11448 | assert_eq!(res.status, StatusCode::CREATED); |
| 11449 | assert!(res.body["finished_at"].is_null()); |
| 11450 | assert!(res.body["label"].is_null()); |
| 11451 | let first_start = res.body["started_at"].as_i64().unwrap(); |
| 11452 | |
| 11453 | // A restart discards the dangling session: one row, clock reset allowed. |
| 11454 | let res = send(&app, "POST", "/pomodoro/start", Some(&ali), None).await; |
| 11455 | assert_eq!(res.status, StatusCode::CREATED); |
| 11456 | assert!(res.body["started_at"].as_i64().unwrap() >= first_start); |
| 11457 | let res = send(&app, "GET", "/pomodoro/me", Some(&ali), None).await; |
| 11458 | assert_eq!(common::items(&res.body).len(), 1); |
| 11459 | assert_eq!( |
| 11460 | res.body["total_focus_ms"], 0, |
| 11461 | "running session counts nothing" |
| 11462 | ); |
| 11463 | |
| 11464 | let res = send(&app, "POST", "/pomodoro/finish", Some(&ali), None).await; |
| 11465 | assert_eq!(res.status, StatusCode::OK); |
| 11466 | let finished_at = res.body["finished_at"].as_i64().unwrap(); |
| 11467 | let duration = res.body["duration_ms"].as_i64().unwrap(); |
| 11468 | assert_eq!( |
| 11469 | duration, |
| 11470 | finished_at - res.body["started_at"].as_i64().unwrap() |
| 11471 | ); |
| 11472 | let res = send(&app, "POST", "/pomodoro/finish", Some(&ali), None).await; |
| 11473 | assert_eq!(res.status, StatusCode::CONFLICT, "already finished"); |
| 11474 | |
| 11475 | // The open slot is free again; the log keeps both sessions, newest first, |
| 11476 | // and the focus total sums only the finished one. |
| 11477 | let res = send(&app, "POST", "/pomodoro/start", Some(&ali), None).await; |
| 11478 | assert_eq!(res.status, StatusCode::CREATED); |
| 11479 | let res = send(&app, "GET", "/pomodoro/me", Some(&ali), None).await; |
| 11480 | let log = common::items(&res.body); |
| 11481 | assert_eq!(log.len(), 2); |
| 11482 | assert!(log[0]["finished_at"].is_null(), "open session sorts newest"); |
| 11483 | assert_eq!(res.body["total_focus_ms"].as_i64().unwrap(), duration); |
| 11484 | |
| 11485 | // Reading someone's log is teacher+; unknown users are 404. |
| 11486 | let res = send( |
| 11487 | &app, |
| 11488 | "GET", |
| 11489 | &format!("/pomodoro/{ali_id}"), |
| 11490 | Some(&ali), |
| 11491 | None, |
| 11492 | ) |
| 11493 | .await; |
| 11494 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11495 | let res = send( |
| 11496 | &app, |
| 11497 | "GET", |
| 11498 | &format!("/pomodoro/{ali_id}"), |
| 11499 | Some(&hoca), |
| 11500 | None, |
| 11501 | ) |
| 11502 | .await; |
| 11503 | assert_eq!(res.status, StatusCode::OK); |
| 11504 | assert_eq!(common::items(&res.body).len(), 2); |
| 11505 | let res = send(&app, "GET", "/pomodoro/01UNKNOWN", Some(&hoca), None).await; |
| 11506 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 11507 | |
| 11508 | // The start body is optional and names the stint: the label comes back |
| 11509 | // on start, reads the same from the log, and survives the close. |
| 11510 | let res = send( |
| 11511 | &app, |
| 11512 | "POST", |
| 11513 | "/pomodoro/start", |
| 11514 | Some(&ali), |
| 11515 | Some(json!({ "label": "math" })), |
| 11516 | ) |
| 11517 | .await; |
| 11518 | assert_eq!(res.status, StatusCode::CREATED); |
| 11519 | assert_eq!(res.body["label"], "math"); |
| 11520 | let res = send(&app, "GET", "/pomodoro/me", Some(&ali), None).await; |
| 11521 | assert_eq!(common::items(&res.body)[0]["label"], "math"); |
| 11522 | let res = send(&app, "POST", "/pomodoro/finish", Some(&ali), None).await; |
| 11523 | assert_eq!(res.status, StatusCode::OK); |
| 11524 | assert_eq!(res.body["label"], "math", "the close keeps the label"); |
| 11525 | let res = send(&app, "GET", "/pomodoro/me", Some(&ali), None).await; |
| 11526 | assert_eq!( |
| 11527 | common::items(&res.body)[0]["label"], |
| 11528 | "math", |
| 11529 | "so does the log afterwards" |
| 11530 | ); |
| 11531 | |
| 11532 | // An over-long label answers the same 400 every other optional |
| 11533 | // free-text field does, and starts nothing. |
| 11534 | let res = send( |
| 11535 | &app, |
| 11536 | "POST", |
| 11537 | "/pomodoro/start", |
| 11538 | Some(&ali), |
| 11539 | Some(json!({ "label": "x".repeat(101) })), |
| 11540 | ) |
| 11541 | .await; |
| 11542 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 11543 | |
| 11544 | // A blank label is no label: the stint starts unnamed. |
| 11545 | let res = send( |
| 11546 | &app, |
| 11547 | "POST", |
| 11548 | "/pomodoro/start", |
| 11549 | Some(&ali), |
| 11550 | Some(json!({ "label": " " })), |
| 11551 | ) |
| 11552 | .await; |
| 11553 | assert_eq!(res.status, StatusCode::CREATED); |
| 11554 | assert!(res.body["label"].is_null()); |
| 11555 | } |
| 11556 | |
| 11557 | #[tokio::test] |
| 11558 | async fn work_log_manager_reads_and_corrections() { |
| 11559 | let (app, db) = app_and_db().await; |
| 11560 | let hoca = login_as(&app, &db, "hoca", "teacher").await; |
| 11561 | let other = login_as(&app, &db, "other", "teacher").await; |
| 11562 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 11563 | let hoca_id = me_id(&app, &hoca).await; |
| 11564 | |
| 11565 | // One closed stint and one open stint for hoca. |
| 11566 | send(&app, "POST", "/work/check-in", Some(&hoca), None).await; |
| 11567 | let closed = send(&app, "POST", "/work/check-out", Some(&hoca), None).await; |
| 11568 | let closed_id = id_of(&closed.body); |
| 11569 | let open = send(&app, "POST", "/work/check-in", Some(&hoca), None).await; |
| 11570 | let open_id = id_of(&open.body); |
| 11571 | |
| 11572 | // Reading someone's log is manager+; unknown users are 404. |
| 11573 | let res = send(&app, "GET", &format!("/work/{hoca_id}"), Some(&other), None).await; |
| 11574 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11575 | let res = send(&app, "GET", &format!("/work/{hoca_id}"), Some(&boss), None).await; |
| 11576 | assert_eq!(res.status, StatusCode::OK); |
| 11577 | assert_eq!(common::items(&res.body).len(), 2); |
| 11578 | let res = send(&app, "GET", "/work/01UNKNOWN", Some(&boss), None).await; |
| 11579 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 11580 | |
| 11581 | // Corrections: manager+ only, closed entries only, ordered instants only. |
| 11582 | let res = send( |
| 11583 | &app, |
| 11584 | "PATCH", |
| 11585 | &format!("/work/entries/{closed_id}"), |
| 11586 | Some(&hoca), |
| 11587 | Some(json!({ "check_in": 1000 })), |
| 11588 | ) |
| 11589 | .await; |
| 11590 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11591 | let res = send( |
| 11592 | &app, |
| 11593 | "PATCH", |
| 11594 | &format!("/work/entries/{closed_id}"), |
| 11595 | Some(&boss), |
| 11596 | Some(json!({ "check_in": 1000, "check_out": 2000 })), |
| 11597 | ) |
| 11598 | .await; |
| 11599 | assert_eq!(res.status, StatusCode::OK); |
| 11600 | assert_eq!(res.body["check_in"], 1000); |
| 11601 | assert_eq!(res.body["check_out"], 2000); |
| 11602 | assert_eq!(res.body["duration_ms"], 1000); |
| 11603 | let res = send( |
| 11604 | &app, |
| 11605 | "PATCH", |
| 11606 | &format!("/work/entries/{closed_id}"), |
| 11607 | Some(&boss), |
| 11608 | Some(json!({ "check_out": 500 })), |
| 11609 | ) |
| 11610 | .await; |
| 11611 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "out precedes in"); |
| 11612 | let res = send( |
| 11613 | &app, |
| 11614 | "PATCH", |
| 11615 | &format!("/work/entries/{open_id}"), |
| 11616 | Some(&boss), |
| 11617 | Some(json!({ "check_in": 1 })), |
| 11618 | ) |
| 11619 | .await; |
| 11620 | assert_eq!( |
| 11621 | res.status, |
| 11622 | StatusCode::CONFLICT, |
| 11623 | "open entries aren't correctable" |
| 11624 | ); |
| 11625 | let res = send( |
| 11626 | &app, |
| 11627 | "PATCH", |
| 11628 | "/work/entries/nope", |
| 11629 | Some(&boss), |
| 11630 | Some(json!({})), |
| 11631 | ) |
| 11632 | .await; |
| 11633 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 11634 | |
| 11635 | // Deletion: manager+, any entry (open ones included — the stray-row broom). |
| 11636 | let res = send( |
| 11637 | &app, |
| 11638 | "DELETE", |
| 11639 | &format!("/work/entries/{closed_id}"), |
| 11640 | Some(&hoca), |
| 11641 | None, |
| 11642 | ) |
| 11643 | .await; |
| 11644 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11645 | let res = send( |
| 11646 | &app, |
| 11647 | "DELETE", |
| 11648 | &format!("/work/entries/{open_id}"), |
| 11649 | Some(&boss), |
| 11650 | None, |
| 11651 | ) |
| 11652 | .await; |
| 11653 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 11654 | let res = send( |
| 11655 | &app, |
| 11656 | "DELETE", |
| 11657 | &format!("/work/entries/{open_id}"), |
| 11658 | Some(&boss), |
| 11659 | None, |
| 11660 | ) |
| 11661 | .await; |
| 11662 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 11663 | // With the open row swept, hoca can check in again. |
| 11664 | let res = send(&app, "POST", "/work/check-in", Some(&hoca), None).await; |
| 11665 | assert_eq!(res.status, StatusCode::CREATED); |
| 11666 | } |
| 11667 | |
| 11668 | #[tokio::test] |
| 11669 | async fn work_duration_survives_absurd_corrected_instants() { |
| 11670 | let (app, db) = app_and_db().await; |
| 11671 | let hoca = login_as(&app, &db, "wid_t", "teacher").await; |
| 11672 | let boss = login_as(&app, &db, "wid_m", "manager").await; |
| 11673 | send(&app, "POST", "/work/check-in", Some(&hoca), None).await; |
| 11674 | let closed = send(&app, "POST", "/work/check-out", Some(&hoca), None).await; |
| 11675 | let closed_id = id_of(&closed.body); |
| 11676 | |
| 11677 | // Corrected instants are arbitrary i64 millis; the widest legal pair must |
| 11678 | // not overflow the `check_out - check_in` duration (a wrapped negative in |
| 11679 | // release, a panicking 500 in debug) — it saturates instead. |
| 11680 | let res = send( |
| 11681 | &app, |
| 11682 | "PATCH", |
| 11683 | &format!("/work/entries/{closed_id}"), |
| 11684 | Some(&boss), |
| 11685 | Some(json!({ "check_in": i64::MIN, "check_out": i64::MAX })), |
| 11686 | ) |
| 11687 | .await; |
| 11688 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 11689 | assert_eq!( |
| 11690 | res.body["duration_ms"].as_i64(), |
| 11691 | Some(i64::MAX), |
| 11692 | "the over-wide stint saturates: {}", |
| 11693 | res.body |
| 11694 | ); |
| 11695 | // The stored row must stay readable, not a permanent 500. |
| 11696 | let res = send(&app, "GET", "/work/me", Some(&hoca), None).await; |
| 11697 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 11698 | } |
| 11699 | |
| 11700 | // --- attendance reports ------------------------------------------------------- |
| 11701 | |
| 11702 | #[tokio::test] |
| 11703 | async fn attendance_report_tallies_events_and_sessions_per_course() { |
| 11704 | let (app, db) = app_and_db().await; |
| 11705 | let owner = login_as(&app, &db, "owner", "teacher").await; |
| 11706 | let ali = login(&app, "ali").await; |
| 11707 | let veli = login(&app, "veli").await; |
| 11708 | let ali_id = me_id(&app, &ali).await; |
| 11709 | |
| 11710 | // A fresh user's report is all zeros with null rates. |
| 11711 | let res = send(&app, "GET", "/attendance/me", Some(&ali), None).await; |
| 11712 | assert_eq!(res.status, StatusCode::OK); |
| 11713 | assert_eq!(res.body["events"]["total"], 0); |
| 11714 | assert!(res.body["events"]["rate"].is_null()); |
| 11715 | assert!(res.body["courses"].as_array().unwrap().is_empty()); |
| 11716 | |
| 11717 | // Two event rows, both teacher-marked (students never mark). |
| 11718 | let ev1 = send( |
| 11719 | &app, |
| 11720 | "POST", |
| 11721 | "/events", |
| 11722 | Some(&owner), |
| 11723 | Some(json!({ "title": "assembly" })), |
| 11724 | ) |
| 11725 | .await; |
| 11726 | let ev2 = send( |
| 11727 | &app, |
| 11728 | "POST", |
| 11729 | "/events", |
| 11730 | Some(&owner), |
| 11731 | Some(json!({ "title": "trip" })), |
| 11732 | ) |
| 11733 | .await; |
| 11734 | let (ev1, ev2) = (id_of(&ev1.body), id_of(&ev2.body)); |
| 11735 | send( |
| 11736 | &app, |
| 11737 | "POST", |
| 11738 | &format!("/events/{ev1}/attendance"), |
| 11739 | Some(&owner), |
| 11740 | Some(json!({ "status": "present", "user_id": ali_id })), |
| 11741 | ) |
| 11742 | .await; |
| 11743 | send( |
| 11744 | &app, |
| 11745 | "POST", |
| 11746 | &format!("/events/{ev2}/attendance"), |
| 11747 | Some(&owner), |
| 11748 | Some(json!({ "status": "absent", "user_id": ali_id })), |
| 11749 | ) |
| 11750 | .await; |
| 11751 | |
| 11752 | // Roll call across two instances: algebra present+late, physics |
| 11753 | // absent+excused. |
| 11754 | let mudur = login_as(&app, &db, "att_m", "manager").await; |
| 11755 | let algebra = taught_under(&app, &mudur, &owner, "algebra").await; |
| 11756 | let physics = taught_under(&app, &mudur, &owner, "physics").await; |
| 11757 | for (t, statuses) in [ |
| 11758 | (&algebra, ["present", "late"]), |
| 11759 | (&physics, ["absent", "excused"]), |
| 11760 | ] { |
| 11761 | enroll(&app, &owner, &t.instance, &ali_id).await; |
| 11762 | for (n, status) in statuses.iter().enumerate() { |
| 11763 | let session = create_session( |
| 11764 | &app, |
| 11765 | &owner, |
| 11766 | &t.instance, |
| 11767 | Timestamp::now().as_millis() + (n as i64 + 1) * 3_600_000, |
| 11768 | ) |
| 11769 | .await; |
| 11770 | let res = send( |
| 11771 | &app, |
| 11772 | "POST", |
| 11773 | &format!("/sessions/{session}/attendance"), |
| 11774 | Some(&owner), |
| 11775 | Some(json!({ "status": status, "user_id": ali_id })), |
| 11776 | ) |
| 11777 | .await; |
| 11778 | assert_eq!(res.status, StatusCode::OK); |
| 11779 | } |
| 11780 | } |
| 11781 | |
| 11782 | let res = send(&app, "GET", "/attendance/me", Some(&ali), None).await; |
| 11783 | assert_eq!(res.status, StatusCode::OK); |
| 11784 | assert_eq!(res.body["user"].as_str().unwrap(), ali_id); |
| 11785 | // Events: 1 present + 1 absent → rate 1/2. |
| 11786 | assert_eq!(res.body["events"]["present"], 1); |
| 11787 | assert_eq!(res.body["events"]["absent"], 1); |
| 11788 | assert_eq!(res.body["events"]["total"], 2); |
| 11789 | assert_eq!(res.body["events"]["rate"].as_f64().unwrap(), 0.5); |
| 11790 | // Sessions overall: present+late+absent+excused → rate (1+1)/3. |
| 11791 | assert_eq!(res.body["sessions"]["total"], 4); |
| 11792 | assert_eq!(res.body["sessions"]["excused"], 1); |
| 11793 | let rate = res.body["sessions"]["rate"].as_f64().unwrap(); |
| 11794 | assert!( |
| 11795 | (rate - 2.0 / 3.0).abs() < 1e-12, |
| 11796 | "excused stays out: {rate}" |
| 11797 | ); |
| 11798 | // Per-course blocks: algebra 100% attended, physics 0% (excused uncounted). |
| 11799 | let courses = res.body["courses"].as_array().unwrap(); |
| 11800 | assert_eq!(courses.len(), 2); |
| 11801 | let block = |title: &str| { |
| 11802 | courses |
| 11803 | .iter() |
| 11804 | .find(|b| b["course"]["title"] == title) |
| 11805 | .unwrap_or_else(|| panic!("missing course block {title}")) |
| 11806 | .clone() |
| 11807 | }; |
| 11808 | assert_eq!(block("algebra")["counts"]["rate"].as_f64().unwrap(), 1.0); |
| 11809 | assert_eq!(block("algebra")["counts"]["late"], 1); |
| 11810 | assert_eq!(block("physics")["counts"]["rate"].as_f64().unwrap(), 0.0); |
| 11811 | assert_eq!(block("physics")["counts"]["excused"], 1); |
| 11812 | |
| 11813 | // Unenrolling hides marks, never absences: the physics block stays. |
| 11814 | unenroll(&app, &owner, &physics.instance, &ali_id).await; |
| 11815 | let res = send(&app, "GET", "/attendance/me", Some(&ali), None).await; |
| 11816 | assert_eq!(res.body["courses"].as_array().unwrap().len(), 2); |
| 11817 | |
| 11818 | // Someone else's report: teacher+ only; unknown users are 404. |
| 11819 | let res = send( |
| 11820 | &app, |
| 11821 | "GET", |
| 11822 | &format!("/attendance/{ali_id}"), |
| 11823 | Some(&veli), |
| 11824 | None, |
| 11825 | ) |
| 11826 | .await; |
| 11827 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11828 | let res = send( |
| 11829 | &app, |
| 11830 | "GET", |
| 11831 | &format!("/attendance/{ali_id}"), |
| 11832 | Some(&owner), |
| 11833 | None, |
| 11834 | ) |
| 11835 | .await; |
| 11836 | assert_eq!(res.status, StatusCode::OK); |
| 11837 | assert_eq!(res.body["sessions"]["total"], 4); |
| 11838 | |
| 11839 | // A teacher's view narrows to the courses they manage: rival runs only |
| 11840 | // chemistry, so ali's report shows that block alone — the overall session |
| 11841 | // tally follows, while event tallies stay school-wide. |
| 11842 | let rival = login_as(&app, &db, "rival", "teacher").await; |
| 11843 | let chemistry = taught_under(&app, &mudur, &rival, "chemistry").await; |
| 11844 | enroll(&app, &rival, &chemistry.instance, &ali_id).await; |
| 11845 | let session = create_session( |
| 11846 | &app, |
| 11847 | &rival, |
| 11848 | &chemistry.instance, |
| 11849 | Timestamp::now().as_millis() + 10 * 3_600_000, |
| 11850 | ) |
| 11851 | .await; |
| 11852 | let res = send( |
| 11853 | &app, |
| 11854 | "POST", |
| 11855 | &format!("/sessions/{session}/attendance"), |
| 11856 | Some(&rival), |
| 11857 | Some(json!({ "status": "present", "user_id": ali_id })), |
| 11858 | ) |
| 11859 | .await; |
| 11860 | assert_eq!(res.status, StatusCode::OK); |
| 11861 | |
| 11862 | let res = send( |
| 11863 | &app, |
| 11864 | "GET", |
| 11865 | &format!("/attendance/{ali_id}"), |
| 11866 | Some(&rival), |
| 11867 | None, |
| 11868 | ) |
| 11869 | .await; |
| 11870 | assert_eq!(res.status, StatusCode::OK); |
| 11871 | assert_eq!(res.body["events"]["total"], 2, "events stay school-wide"); |
| 11872 | assert_eq!(res.body["sessions"]["total"], 1); |
| 11873 | let blocks = res.body["courses"].as_array().unwrap(); |
| 11874 | assert_eq!(blocks.len(), 1); |
| 11875 | assert_eq!(blocks[0]["course"]["title"], "chemistry"); |
| 11876 | |
| 11877 | // The owner's view still carries only their own two courses … |
| 11878 | let res = send( |
| 11879 | &app, |
| 11880 | "GET", |
| 11881 | &format!("/attendance/{ali_id}"), |
| 11882 | Some(&owner), |
| 11883 | None, |
| 11884 | ) |
| 11885 | .await; |
| 11886 | assert_eq!(res.body["courses"].as_array().unwrap().len(), 2); |
| 11887 | assert_eq!(res.body["sessions"]["total"], 4); |
| 11888 | |
| 11889 | // … and the self view stays complete: all three courses, every row. |
| 11890 | let res = send(&app, "GET", "/attendance/me", Some(&ali), None).await; |
| 11891 | assert_eq!(res.body["courses"].as_array().unwrap().len(), 3); |
| 11892 | assert_eq!(res.body["sessions"]["total"], 5); |
| 11893 | |
| 11894 | let res = send(&app, "GET", "/attendance/01UNKNOWN", Some(&owner), None).await; |
| 11895 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 11896 | } |
| 11897 | |
| 11898 | /// Issue #24: a student or parent needs a way to find the teacher they are |
| 11899 | /// allowed to write to, so `/users/search` is no longer teacher+ — but below |
| 11900 | /// staff it shows staff *only*, in the items and in `total` alike (the |
| 11901 | /// restriction is in the query, not a post-filter over one page). |
| 11902 | #[tokio::test] |
| 11903 | async fn search_below_staff_sees_only_staff() { |
| 11904 | let (app, db) = app_and_db().await; |
| 11905 | // Both match `q=ay`: one student, one teacher. |
| 11906 | let ayse = login(&app, "ayse").await; |
| 11907 | let _ayhan = login_as(&app, &db, "ayhan", "teacher").await; |
| 11908 | let anne = login_as(&app, &db, "anne", "parent").await; |
| 11909 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 11910 | |
| 11911 | for (who, cookie) in [("student", &ayse), ("parent", &anne)] { |
| 11912 | let res = send(&app, "GET", "/users/search?q=ay", Some(cookie), None).await; |
| 11913 | assert_eq!(res.status, StatusCode::OK, "{who}: {}", res.body); |
| 11914 | let items = common::items(&res.body); |
| 11915 | assert_eq!( |
| 11916 | items.len(), |
| 11917 | 1, |
| 11918 | "{who} must see only the teacher: {}", |
| 11919 | res.body |
| 11920 | ); |
| 11921 | assert_eq!(items[0]["username"], "ayhan", "{who}"); |
| 11922 | assert_eq!( |
| 11923 | res.body["total"], 1, |
| 11924 | "{who}: total counts the visible set only" |
| 11925 | ); |
| 11926 | // Only the picker fields, as before — never contact details. |
| 11927 | assert!(items[0].get("email").is_none(), "{who}"); |
| 11928 | |
| 11929 | // Naming a role they may not message is a refusal, not an empty page. |
| 11930 | let res = send( |
| 11931 | &app, |
| 11932 | "GET", |
| 11933 | "/users/search?q=ay&role=student", |
| 11934 | Some(cookie), |
| 11935 | None, |
| 11936 | ) |
| 11937 | .await; |
| 11938 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{who}: {}", res.body); |
| 11939 | // A staff role they may message filters as usual. |
| 11940 | let res = send( |
| 11941 | &app, |
| 11942 | "GET", |
| 11943 | "/users/search?q=ay&role=teacher", |
| 11944 | Some(cookie), |
| 11945 | None, |
| 11946 | ) |
| 11947 | .await; |
| 11948 | assert_eq!(res.status, StatusCode::OK, "{who}: {}", res.body); |
| 11949 | assert_eq!(common::items(&res.body).len(), 1, "{who}"); |
| 11950 | } |
| 11951 | |
| 11952 | // Staff keep the unrestricted picker: the student is back in the results. |
| 11953 | let res = send(&app, "GET", "/users/search?q=ay", Some(&mudur), None).await; |
| 11954 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 11955 | assert_eq!(res.body["total"], 2, "{}", res.body); |
| 11956 | let res = send( |
| 11957 | &app, |
| 11958 | "GET", |
| 11959 | "/users/search?q=ay&role=student", |
| 11960 | Some(&mudur), |
| 11961 | None, |
| 11962 | ) |
| 11963 | .await; |
| 11964 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 11965 | assert_eq!(common::items(&res.body)[0]["username"], "ayse"); |
| 11966 | |
| 11967 | // A blank `q` opens the directory, and below staff that directory is |
| 11968 | // still staff only: the narrowing lives in the query, so it holds for the |
| 11969 | // whole list and not just for a fragment. |
| 11970 | for (who, cookie) in [("student", &ayse), ("parent", &anne)] { |
| 11971 | let res = send(&app, "GET", "/users/search?q=", Some(cookie), None).await; |
| 11972 | assert_eq!(res.status, StatusCode::OK, "{who}: {}", res.body); |
| 11973 | let items = common::items(&res.body); |
| 11974 | assert_eq!(res.body["total"], items.len(), "{who}: {}", res.body); |
| 11975 | assert!( |
| 11976 | !items |
| 11977 | .iter() |
| 11978 | .any(|user| user["username"] == "ayse" || user["username"] == "anne"), |
| 11979 | "{who} must not see students or parents: {items:?}" |
| 11980 | ); |
| 11981 | assert!( |
| 11982 | items.iter().any(|user| user["username"] == "ayhan"), |
| 11983 | "{who} must see the teacher: {items:?}" |
| 11984 | ); |
| 11985 | } |
| 11986 | } |
| 11987 | |
| 11988 | // --- users: search matching semantics -------------------------------------- |
| 11989 | |
| 11990 | /// The search fragment is matched with literal `CONTAINS` semantics — never |
| 11991 | /// SQL-`LIKE`. A regression to a `LIKE '%{q}%'` pattern would turn `%` and `_` |
| 11992 | /// in the query into wildcards: `q=%` would dump every named user and `q=_` |
| 11993 | /// every username, defeating the "real substring only" intent of the picker. |
| 11994 | /// `%` and `_` must match only users who literally carry those characters. |
| 11995 | #[tokio::test] |
| 11996 | async fn search_matches_are_literal_not_like_wildcards() { |
| 11997 | let (app, db) = app_and_db().await; |
| 11998 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 11999 | |
| 12000 | // Three students: one plainly named, one with a literal `%` in their name, |
| 12001 | // one with a literal `_` in their username. |
| 12002 | let alice = login(&app, "alice").await; |
| 12003 | let res = send( |
| 12004 | &app, |
| 12005 | "PATCH", |
| 12006 | "/users/me", |
| 12007 | Some(&alice), |
| 12008 | Some(json!({ "name": "Plain", "surname": "Jane" })), |
| 12009 | ) |
| 12010 | .await; |
| 12011 | assert_eq!(res.status, StatusCode::OK); |
| 12012 | |
| 12013 | let percy = login(&app, "percy").await; |
| 12014 | let res = send( |
| 12015 | &app, |
| 12016 | "PATCH", |
| 12017 | "/users/me", |
| 12018 | Some(&percy), |
| 12019 | Some(json!({ "name": "100% legend" })), |
| 12020 | ) |
| 12021 | .await; |
| 12022 | assert_eq!(res.status, StatusCode::OK); |
| 12023 | |
| 12024 | login(&app, "under_score").await; |
| 12025 | |
| 12026 | // `q=%` (url-encoded %25) is a literal percent sign: only percy matches. |
| 12027 | // Under LIKE semantics it would match every user with a name. |
| 12028 | let res = send(&app, "GET", "/users/search?q=%25", Some(&teacher), None).await; |
| 12029 | assert_eq!(res.status, StatusCode::OK); |
| 12030 | let hits = common::items(&res.body); |
| 12031 | assert_eq!(hits.len(), 1, "`%` must match literally: {hits:?}"); |
| 12032 | assert_eq!(hits[0]["username"], "percy"); |
| 12033 | |
| 12034 | // `q=_` is a literal underscore: only under_score matches. Under LIKE |
| 12035 | // semantics `_` is any-single-character and would match everyone. |
| 12036 | let res = send(&app, "GET", "/users/search?q=_", Some(&teacher), None).await; |
| 12037 | assert_eq!(res.status, StatusCode::OK); |
| 12038 | let hits = common::items(&res.body); |
| 12039 | assert_eq!(hits.len(), 1, "`_` must match literally: {hits:?}"); |
| 12040 | assert_eq!(hits[0]["username"], "under_score"); |
| 12041 | } |
| 12042 | |
| 12043 | /// A blank search fragment is the pickers' opening directory: it lists |
| 12044 | /// everyone the caller may see, exactly like a blank `q` scoped to a role. |
| 12045 | #[tokio::test] |
| 12046 | async fn search_allows_a_blank_query() { |
| 12047 | let (app, db) = app_and_db().await; |
| 12048 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 12049 | login(&app, "alice").await; |
| 12050 | |
| 12051 | // Whitespace-only (url-encoded spaces) is the same blank, not an error. |
| 12052 | let res = send(&app, "GET", "/users/search?q=%20%20", Some(&teacher), None).await; |
| 12053 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 12054 | let blank = common::items(&res.body); |
| 12055 | assert!( |
| 12056 | blank.iter().any(|user| user["username"] == "alice"), |
| 12057 | "{blank:?}" |
| 12058 | ); |
| 12059 | assert_eq!(res.body["total"], blank.len(), "{}", res.body); |
| 12060 | |
| 12061 | // An omitted `q` is the same blank. |
| 12062 | let res = send(&app, "GET", "/users/search", Some(&teacher), None).await; |
| 12063 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 12064 | assert_eq!(common::items(&res.body), blank); |
| 12065 | |
| 12066 | // So is an explicit empty one. |
| 12067 | let res = send(&app, "GET", "/users/search?q=", Some(&teacher), None).await; |
| 12068 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 12069 | assert_eq!(common::items(&res.body), blank); |
| 12070 | |
| 12071 | // The blank directory still honors the paging window. |
| 12072 | let res = send( |
| 12073 | &app, |
| 12074 | "GET", |
| 12075 | "/users/search?q=&limit=1&offset=1", |
| 12076 | Some(&teacher), |
| 12077 | None, |
| 12078 | ) |
| 12079 | .await; |
| 12080 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 12081 | assert_eq!(common::items(&res.body).len(), 1); |
| 12082 | assert_eq!(res.body["total"], blank.len()); |
| 12083 | } |
| 12084 | |
| 12085 | /// The app is EN/TR, so the user picker must fold Turkish casing: `İ` (U+0130) |
| 12086 | /// lowercases to `i` + U+0307 in both Rust and SQL, which used to make |
| 12087 | /// `ilker` and `İLKER` two disjoint searches — a teacher typing lowercase got |
| 12088 | /// an empty picker. Same defect, same fix as the bank-question search. |
| 12089 | #[tokio::test] |
| 12090 | async fn user_search_folds_turkish_casing() { |
| 12091 | let (app, db) = app_and_db().await; |
| 12092 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 12093 | |
| 12094 | let ilker = login(&app, "ilker_a").await; |
| 12095 | let res = send( |
| 12096 | &app, |
| 12097 | "PATCH", |
| 12098 | "/users/me", |
| 12099 | Some(&ilker), |
| 12100 | Some(json!({ "name": "İLKER", "surname": "ÇAĞLAR" })), |
| 12101 | ) |
| 12102 | .await; |
| 12103 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 12104 | |
| 12105 | let ilknur = login(&app, "ilknur_b").await; |
| 12106 | let res = send( |
| 12107 | &app, |
| 12108 | "PATCH", |
| 12109 | "/users/me", |
| 12110 | Some(&ilknur), |
| 12111 | Some(json!({ "name": "ilknur", "surname": "Işık" })), |
| 12112 | ) |
| 12113 | .await; |
| 12114 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 12115 | |
| 12116 | // Every casing of the shared `ilk` prefix finds both, in both directions: |
| 12117 | // `ilk`, `İLK`, `ılk`, `ILK`. |
| 12118 | for needle in ["ilk", "%C4%B0LK", "%C4%B1lk", "ILK"] { |
| 12119 | let res = send( |
| 12120 | &app, |
| 12121 | "GET", |
| 12122 | &format!("/users/search?q={needle}"), |
| 12123 | Some(&teacher), |
| 12124 | None, |
| 12125 | ) |
| 12126 | .await; |
| 12127 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 12128 | let hits = common::items(&res.body); |
| 12129 | assert_eq!(hits.len(), 2, "needle {needle} missed: {hits:?}"); |
| 12130 | } |
| 12131 | |
| 12132 | // Diacritics fold on the surname too, both ways (`ÇAĞLAR` ↔ `caglar`, |
| 12133 | // `Işık` ↔ `isik`). |
| 12134 | for (needle, username) in [ |
| 12135 | ("caglar", "ilker_a"), |
| 12136 | ("%C3%A7a%C4%9Flar", "ilker_a"), |
| 12137 | ("isik", "ilknur_b"), |
| 12138 | ("I%C5%9F%C4%B1k", "ilknur_b"), |
| 12139 | ] { |
| 12140 | let res = send( |
| 12141 | &app, |
| 12142 | "GET", |
| 12143 | &format!("/users/search?q={needle}"), |
| 12144 | Some(&teacher), |
| 12145 | None, |
| 12146 | ) |
| 12147 | .await; |
| 12148 | let hits = common::items(&res.body); |
| 12149 | assert_eq!(hits.len(), 1, "needle {needle} missed: {hits:?}"); |
| 12150 | assert_eq!(hits[0]["username"], username); |
| 12151 | } |
| 12152 | |
| 12153 | // Folding widens the match, it does not match everything. |
| 12154 | let res = send(&app, "GET", "/users/search?q=zeynep", Some(&teacher), None).await; |
| 12155 | assert_eq!(common::items(&res.body).len(), 0); |
| 12156 | } |
| 12157 | |
| 12158 | // --- courses: catalog dedup ------------------------------------------------- |
| 12159 | |
| 12160 | /// A user who both created a course (while staff) and is enrolled in it (after |
| 12161 | /// a demotion to student) sees it once in the catalog, not twice — the created |
| 12162 | /// and enrolled sources are deduplicated. Enrollment is student-only now, so |
| 12163 | /// that overlap can only arise across a role change; the dedup must still hold. |
| 12164 | #[tokio::test] |
| 12165 | async fn course_catalog_follows_reach_not_creation() { |
| 12166 | let (app, db) = app_and_db().await; |
| 12167 | let creator = login_as(&app, &db, "teacher", "teacher").await; |
| 12168 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 12169 | let creator_id = me_id(&app, &creator).await; |
| 12170 | |
| 12171 | let t = taught_under(&app, &boss, &creator, "algebra").await; |
| 12172 | // Author the exam while still staff, before the demotion below. |
| 12173 | let exam = create_exam(&app, &creator, &t.instance, &t.term, "mt", "yazili").await; |
| 12174 | |
| 12175 | // Demoted to student the ex-creator owns nothing: the catalog is the |
| 12176 | // courses a caller is *reached* by, and creation is not a source any more. |
| 12177 | set_role(&db, "teacher", "student").await; |
| 12178 | let res = send(&app, "GET", "/courses", Some(&creator), None).await; |
| 12179 | assert_eq!(res.status, StatusCode::OK); |
| 12180 | assert!( |
| 12181 | common::items(&res.body).is_empty(), |
| 12182 | "a demoted creator's catalog is empty: {}", |
| 12183 | res.body |
| 12184 | ); |
| 12185 | |
| 12186 | // The şube enrolls them into the instance its course carries: now they are |
| 12187 | // reached by it, and it is listed exactly once. |
| 12188 | add_member(&app, &boss, &t.class, &creator_id).await; |
| 12189 | let res = send(&app, "GET", "/courses", Some(&creator), None).await; |
| 12190 | let courses = common::items(&res.body); |
| 12191 | assert_eq!(courses.len(), 1, "reached once, listed once: {courses:?}"); |
| 12192 | assert_eq!(courses[0]["id"], json!(t.course)); |
| 12193 | |
| 12194 | // The exam catalog derives from the same visible set and lists the exam |
| 12195 | // once. |
| 12196 | let res = send(&app, "GET", "/exams", Some(&creator), None).await; |
| 12197 | let exams = common::items(&res.body); |
| 12198 | assert_eq!(exams.len(), 1, "one exam listed once: {exams:?}"); |
| 12199 | assert_eq!(exams[0]["id"], json!(exam)); |
| 12200 | } |
| 12201 | |
| 12202 | // --- school settings + terms ---------------------------------------------- |
| 12203 | |
| 12204 | #[tokio::test] |
| 12205 | async fn settings_serve_defaults_and_gate_edits_to_manager() { |
| 12206 | let (app, db) = app_and_db().await; |
| 12207 | let student = login(&app, "set.student").await; |
| 12208 | let teacher = login_as(&app, &db, "set.teacher", "teacher").await; |
| 12209 | let manager = login_as(&app, &db, "set.manager", "manager").await; |
| 12210 | |
| 12211 | // Reading requires a session; the policy is not public. |
| 12212 | let res = send(&app, "GET", "/settings", None, None).await; |
| 12213 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); |
| 12214 | |
| 12215 | // Any authenticated user reads. The defaults are the Turkish K12 |
| 12216 | // classroom's own — yazılı, sözlü, uygulama, each weighing 1 until the |
| 12217 | // school says otherwise — over the Türkiye 5-point band scale, so a mark |
| 12218 | // always labels. |
| 12219 | let res = send(&app, "GET", "/settings", Some(&student), None).await; |
| 12220 | assert_eq!(res.status, StatusCode::OK); |
| 12221 | assert_eq!( |
| 12222 | res.body["exam_kinds"], |
| 12223 | json!([ |
| 12224 | {"name": "yazili", "weight": 1}, |
| 12225 | {"name": "sozlu", "weight": 1}, |
| 12226 | {"name": "uygulama", "weight": 1}, |
| 12227 | ]) |
| 12228 | ); |
| 12229 | assert_eq!( |
| 12230 | res.body["attendance_statuses"], |
| 12231 | json!(["absent", "excused", "late", "present"]) |
| 12232 | ); |
| 12233 | assert_eq!( |
| 12234 | res.body["grade_bands"], |
| 12235 | json!([ |
| 12236 | {"min": 85, "label": "5"}, |
| 12237 | {"min": 70, "label": "4"}, |
| 12238 | {"min": 55, "label": "3"}, |
| 12239 | {"min": 45, "label": "2"}, |
| 12240 | {"min": 0, "label": "1"}, |
| 12241 | ]) |
| 12242 | ); |
| 12243 | |
| 12244 | // Students and teachers cannot edit school policy. |
| 12245 | for cookie in [&student, &teacher] { |
| 12246 | let res = send( |
| 12247 | &app, |
| 12248 | "PATCH", |
| 12249 | "/settings", |
| 12250 | Some(cookie), |
| 12251 | Some(json!({ "exam_kinds": [{"name": "lab", "weight": 1}] })), |
| 12252 | ) |
| 12253 | .await; |
| 12254 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 12255 | } |
| 12256 | |
| 12257 | // A manager edits one field; omitted fields keep their value. |
| 12258 | let res = send( |
| 12259 | &app, |
| 12260 | "PATCH", |
| 12261 | "/settings", |
| 12262 | Some(&manager), |
| 12263 | Some(json!({ "exam_kinds": [ |
| 12264 | {"name": "lab", "weight": 2}, |
| 12265 | {"name": "Quiz", "weight": 1}, |
| 12266 | ]})), |
| 12267 | ) |
| 12268 | .await; |
| 12269 | assert_eq!(res.status, StatusCode::OK); |
| 12270 | assert_eq!( |
| 12271 | res.body["exam_kinds"], |
| 12272 | json!([ |
| 12273 | {"name": "lab", "weight": 2}, |
| 12274 | {"name": "Quiz", "weight": 1}, |
| 12275 | ]) |
| 12276 | ); |
| 12277 | assert_eq!( |
| 12278 | res.body["attendance_statuses"], |
| 12279 | json!(["absent", "excused", "late", "present"]) |
| 12280 | ); |
| 12281 | |
| 12282 | // Every reader sees the new policy at once. |
| 12283 | let res = send(&app, "GET", "/settings", Some(&student), None).await; |
| 12284 | assert_eq!(res.body["exam_kinds"][0]["name"], "lab"); |
| 12285 | assert_eq!(res.body["exam_kinds"][0]["weight"], 2); |
| 12286 | } |
| 12287 | |
| 12288 | #[tokio::test] |
| 12289 | async fn settings_validation_rejects_bad_lists_and_bands() { |
| 12290 | let (app, db) = app_and_db().await; |
| 12291 | let manager = login_as(&app, &db, "val.manager", "manager").await; |
| 12292 | |
| 12293 | let bad = [ |
| 12294 | json!({ "exam_kinds": [] }), // a school needs at least one kind |
| 12295 | json!({ "exam_kinds": [{"name": " ", "weight": 1}] }), // blank name |
| 12296 | // Case-insensitive duplicate names. |
| 12297 | json!({ "exam_kinds": [ |
| 12298 | {"name": "Lab", "weight": 1}, |
| 12299 | {"name": "lab", "weight": 2}, |
| 12300 | ]}), |
| 12301 | // Weights are held to 1–100. |
| 12302 | json!({ "exam_kinds": [{"name": "quiz", "weight": 0}] }), |
| 12303 | json!({ "exam_kinds": [{"name": "quiz", "weight": 101}] }), |
| 12304 | json!({ "exam_kinds": [{"name": "quiz", "weight": -1}] }), |
| 12305 | json!({ "attendance_statuses": ["present", "absent", "late"] }), // core dropped |
| 12306 | json!({ "grade_bands": [{ "min": 50, "label": "CC" }] }), // no band starts at 0 |
| 12307 | json!({ "grade_bands": [{ "min": 0, "label": "F" }, { "min": 0, "label": "E" }] }), |
| 12308 | json!({ "grade_bands": [{ "min": -1, "label": "F" }] }), |
| 12309 | json!({ "grade_bands": [{ "min": 101, "label": "A" }] }), |
| 12310 | json!({ "grade_bands": [{ "min": 0, "label": " " }] }), |
| 12311 | ]; |
| 12312 | for body in bad { |
| 12313 | let res = send( |
| 12314 | &app, |
| 12315 | "PATCH", |
| 12316 | "/settings", |
| 12317 | Some(&manager), |
| 12318 | Some(body.clone()), |
| 12319 | ) |
| 12320 | .await; |
| 12321 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "should reject {body}"); |
| 12322 | } |
| 12323 | |
| 12324 | // No failed PATCH half-applied anything: the school still carries the |
| 12325 | // shipped policy. |
| 12326 | let res = send(&app, "GET", "/settings", Some(&manager), None).await; |
| 12327 | assert_eq!( |
| 12328 | res.body["exam_kinds"], |
| 12329 | json!([ |
| 12330 | {"name": "yazili", "weight": 1}, |
| 12331 | {"name": "sozlu", "weight": 1}, |
| 12332 | {"name": "uygulama", "weight": 1}, |
| 12333 | ]) |
| 12334 | ); |
| 12335 | assert_eq!( |
| 12336 | res.body["grade_bands"], |
| 12337 | json!([ |
| 12338 | {"min": 85, "label": "5"}, |
| 12339 | {"min": 70, "label": "4"}, |
| 12340 | {"min": 55, "label": "3"}, |
| 12341 | {"min": 45, "label": "2"}, |
| 12342 | {"min": 0, "label": "1"}, |
| 12343 | ]) |
| 12344 | ); |
| 12345 | } |
| 12346 | |
| 12347 | #[tokio::test] |
| 12348 | async fn exam_kinds_follow_settings_for_new_writes_only() { |
| 12349 | let (app, db) = app_and_db().await; |
| 12350 | let teacher = login_as(&app, &db, "kind.teacher", "teacher").await; |
| 12351 | let manager = login_as(&app, &db, "kind.manager", "manager").await; |
| 12352 | |
| 12353 | // The school's own list, naming the kind the first exam is written with |
| 12354 | // (the shipped defaults are yazili/sozlu/uygulama). |
| 12355 | let res = send( |
| 12356 | &app, |
| 12357 | "PATCH", |
| 12358 | "/settings", |
| 12359 | Some(&manager), |
| 12360 | Some(json!({ "exam_kinds": [{"name": "midterm", "weight": 1}] })), |
| 12361 | ) |
| 12362 | .await; |
| 12363 | assert_eq!(res.status, StatusCode::OK); |
| 12364 | |
| 12365 | let t = taught_under(&app, &manager, &teacher, "Chemistry").await; |
| 12366 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "Midterm", "midterm").await; |
| 12367 | |
| 12368 | // The school swaps its kind list wholesale. |
| 12369 | let res = send( |
| 12370 | &app, |
| 12371 | "PATCH", |
| 12372 | "/settings", |
| 12373 | Some(&manager), |
| 12374 | Some(json!({ "exam_kinds": [{"name": "lab", "weight": 1}] })), |
| 12375 | ) |
| 12376 | .await; |
| 12377 | assert_eq!(res.status, StatusCode::OK); |
| 12378 | |
| 12379 | // New exams are held to the new list. |
| 12380 | let res = create_exam_with( |
| 12381 | &app, |
| 12382 | &teacher, |
| 12383 | &t.instance, |
| 12384 | json!({ "term": &t.term, "title": "Retired kind", "kind": "midterm" }), |
| 12385 | ) |
| 12386 | .await; |
| 12387 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 12388 | let res = create_exam_with( |
| 12389 | &app, |
| 12390 | &teacher, |
| 12391 | &t.instance, |
| 12392 | json!({ "term": &t.term, "title": "Lab 1", "kind": "lab" }), |
| 12393 | ) |
| 12394 | .await; |
| 12395 | assert_eq!(res.status, StatusCode::CREATED); |
| 12396 | |
| 12397 | // The stored exam keeps its retired kind: a title-only PATCH passes… |
| 12398 | let res = send( |
| 12399 | &app, |
| 12400 | "PATCH", |
| 12401 | &format!("/exams/{exam}"), |
| 12402 | Some(&teacher), |
| 12403 | Some(json!({ "title": "Midterm A" })), |
| 12404 | ) |
| 12405 | .await; |
| 12406 | assert_eq!(res.status, StatusCode::OK); |
| 12407 | assert_eq!(res.body["kind"], "midterm"); |
| 12408 | // …but a kind this request sets is validated against the current list. |
| 12409 | let res = send( |
| 12410 | &app, |
| 12411 | "PATCH", |
| 12412 | &format!("/exams/{exam}"), |
| 12413 | Some(&teacher), |
| 12414 | Some(json!({ "kind": "midterm" })), |
| 12415 | ) |
| 12416 | .await; |
| 12417 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 12418 | let res = send( |
| 12419 | &app, |
| 12420 | "PATCH", |
| 12421 | &format!("/exams/{exam}"), |
| 12422 | Some(&teacher), |
| 12423 | Some(json!({ "kind": "lab" })), |
| 12424 | ) |
| 12425 | .await; |
| 12426 | assert_eq!(res.status, StatusCode::OK); |
| 12427 | assert_eq!(res.body["kind"], "lab"); |
| 12428 | } |
| 12429 | |
| 12430 | #[tokio::test] |
| 12431 | async fn attendance_statuses_follow_settings_and_bucket_in_reports() { |
| 12432 | let (app, db) = app_and_db().await; |
| 12433 | let manager = login_as(&app, &db, "att.manager", "manager").await; |
| 12434 | let student = login(&app, "att.student").await; |
| 12435 | let student_id = me_id(&app, &student).await; |
| 12436 | |
| 12437 | // Add a school-specific status on top of the mandatory core. |
| 12438 | let res = send( |
| 12439 | &app, |
| 12440 | "PATCH", |
| 12441 | "/settings", |
| 12442 | Some(&manager), |
| 12443 | Some(json!({ |
| 12444 | "attendance_statuses": ["present", "absent", "late", "excused", "online"] |
| 12445 | })), |
| 12446 | ) |
| 12447 | .await; |
| 12448 | assert_eq!(res.status, StatusCode::OK); |
| 12449 | |
| 12450 | let res = send( |
| 12451 | &app, |
| 12452 | "POST", |
| 12453 | "/events", |
| 12454 | Some(&manager), |
| 12455 | Some(json!({ "title": "Assembly" })), |
| 12456 | ) |
| 12457 | .await; |
| 12458 | assert_eq!(res.status, StatusCode::CREATED); |
| 12459 | let event = id_of(&res.body); |
| 12460 | |
| 12461 | // The custom status is markable; garbage still is not. |
| 12462 | let res = send( |
| 12463 | &app, |
| 12464 | "POST", |
| 12465 | &format!("/events/{event}/attendance"), |
| 12466 | Some(&manager), |
| 12467 | Some(json!({ "status": "online", "user_id": student_id })), |
| 12468 | ) |
| 12469 | .await; |
| 12470 | assert_eq!(res.status, StatusCode::OK); |
| 12471 | let res = send( |
| 12472 | &app, |
| 12473 | "POST", |
| 12474 | &format!("/events/{event}/attendance"), |
| 12475 | Some(&manager), |
| 12476 | Some(json!({ "status": "maybe", "user_id": student_id })), |
| 12477 | ) |
| 12478 | .await; |
| 12479 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 12480 | |
| 12481 | // The report buckets it under `custom` and keeps it out of the rate. |
| 12482 | let res = send(&app, "GET", "/attendance/me", Some(&student), None).await; |
| 12483 | assert_eq!(res.status, StatusCode::OK); |
| 12484 | assert_eq!(res.body["events"]["custom"]["online"], 1); |
| 12485 | assert_eq!(res.body["events"]["total"], 1); |
| 12486 | assert_eq!(res.body["events"]["rate"], serde_json::Value::Null); |
| 12487 | |
| 12488 | // Retiring the status blocks new marks; the stored row keeps reporting. |
| 12489 | let res = send( |
| 12490 | &app, |
| 12491 | "PATCH", |
| 12492 | "/settings", |
| 12493 | Some(&manager), |
| 12494 | Some(json!({ |
| 12495 | "attendance_statuses": ["present", "absent", "late", "excused"] |
| 12496 | })), |
| 12497 | ) |
| 12498 | .await; |
| 12499 | assert_eq!(res.status, StatusCode::OK); |
| 12500 | let res = send( |
| 12501 | &app, |
| 12502 | "POST", |
| 12503 | &format!("/events/{event}/attendance"), |
| 12504 | Some(&manager), |
| 12505 | Some(json!({ "status": "online", "user_id": student_id })), |
| 12506 | ) |
| 12507 | .await; |
| 12508 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 12509 | let res = send(&app, "GET", "/attendance/me", Some(&student), None).await; |
| 12510 | assert_eq!(res.body["events"]["custom"]["online"], 1); |
| 12511 | } |
| 12512 | |
| 12513 | #[tokio::test] |
| 12514 | async fn grade_bands_label_the_marks_report() { |
| 12515 | let (app, db) = app_and_db().await; |
| 12516 | let teacher = login_as(&app, &db, "band.teacher", "teacher").await; |
| 12517 | let manager = login_as(&app, &db, "band.manager", "manager").await; |
| 12518 | let student = login(&app, "band.student").await; |
| 12519 | let student_id = me_id(&app, &student).await; |
| 12520 | |
| 12521 | let res = send( |
| 12522 | &app, |
| 12523 | "PATCH", |
| 12524 | "/settings", |
| 12525 | Some(&manager), |
| 12526 | Some(json!({ |
| 12527 | "grade_bands": [ |
| 12528 | { "min": 0, "label": "FF" }, |
| 12529 | { "min": 50, "label": "CC" }, |
| 12530 | { "min": 85, "label": "AA" }, |
| 12531 | ] |
| 12532 | })), |
| 12533 | ) |
| 12534 | .await; |
| 12535 | assert_eq!(res.status, StatusCode::OK); |
| 12536 | // Bands echo highest-first — the canonical order. |
| 12537 | assert_eq!(res.body["grade_bands"][0]["label"], "AA"); |
| 12538 | |
| 12539 | let t = taught_under(&app, &manager, &teacher, "Physics").await; |
| 12540 | add_member(&app, &manager, &t.class, &student_id).await; |
| 12541 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "Final", "yazili").await; |
| 12542 | let res = send( |
| 12543 | &app, |
| 12544 | "POST", |
| 12545 | &format!("/exams/{exam}/results"), |
| 12546 | Some(&teacher), |
| 12547 | Some(json!({ "user_id": student_id, "mark": 90 })), |
| 12548 | ) |
| 12549 | .await; |
| 12550 | assert_eq!(res.status, StatusCode::OK); |
| 12551 | |
| 12552 | let res = send(&app, "GET", "/marks/me", Some(&student), None).await; |
| 12553 | assert_eq!(res.status, StatusCode::OK); |
| 12554 | let block = &res.body["courses"][0]; |
| 12555 | assert_eq!(block["results"][0]["mark"], 90); |
| 12556 | assert_eq!(block["results"][0]["grade"], "AA"); |
| 12557 | assert_eq!(block["average"], 90.0); |
| 12558 | assert_eq!(block["average_grade"], "AA"); |
| 12559 | assert_eq!(res.body["overall_grade"], "AA"); |
| 12560 | |
| 12561 | // Clearing the bands turns labels off without touching the numbers. |
| 12562 | let res = send( |
| 12563 | &app, |
| 12564 | "PATCH", |
| 12565 | "/settings", |
| 12566 | Some(&manager), |
| 12567 | Some(json!({ "grade_bands": [] })), |
| 12568 | ) |
| 12569 | .await; |
| 12570 | assert_eq!(res.status, StatusCode::OK); |
| 12571 | let res = send(&app, "GET", "/marks/me", Some(&student), None).await; |
| 12572 | assert_eq!(res.body["courses"][0]["results"][0]["mark"], 90); |
| 12573 | assert_eq!( |
| 12574 | res.body["courses"][0]["results"][0]["grade"], |
| 12575 | serde_json::Value::Null |
| 12576 | ); |
| 12577 | assert_eq!(res.body["overall_grade"], serde_json::Value::Null); |
| 12578 | } |
| 12579 | |
| 12580 | #[tokio::test] |
| 12581 | async fn terms_crud_gates_and_the_catalog_lives_outside_the_calendar() { |
| 12582 | let (app, db) = app_and_db().await; |
| 12583 | let manager = login_as(&app, &db, "term.manager", "manager").await; |
| 12584 | let teacher = login_as(&app, &db, "term.teacher", "teacher").await; |
| 12585 | let student = login(&app, "term.student").await; |
| 12586 | |
| 12587 | // A dönem is a slice of an academic year since the K12 remodel, so the |
| 12588 | // calendar above it is minted first. |
| 12589 | let res = send( |
| 12590 | &app, |
| 12591 | "POST", |
| 12592 | "/academic-years", |
| 12593 | Some(&manager), |
| 12594 | Some(json!({ |
| 12595 | "name": "2025-2026", |
| 12596 | "starts_at": 1_590_000_000_000_i64, |
| 12597 | "ends_at": 1_620_000_000_000_i64, |
| 12598 | })), |
| 12599 | ) |
| 12600 | .await; |
| 12601 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 12602 | let year = id_of(&res.body); |
| 12603 | |
| 12604 | // Writes are manager+; and a term may lie fully in the past — a school |
| 12605 | // adopting the app mid-year backfills its calendar, unlike the no-past |
| 12606 | // rule on exams/lessons/events. |
| 12607 | let past_term = json!({ |
| 12608 | "name": "2025 Fall", |
| 12609 | "year": year, |
| 12610 | "starts_at": 1_600_000_000_000_i64, |
| 12611 | "ends_at": 1_610_000_000_000_i64, |
| 12612 | }); |
| 12613 | let res = send( |
| 12614 | &app, |
| 12615 | "POST", |
| 12616 | "/terms", |
| 12617 | Some(&teacher), |
| 12618 | Some(past_term.clone()), |
| 12619 | ) |
| 12620 | .await; |
| 12621 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 12622 | let res = send(&app, "POST", "/terms", Some(&manager), Some(past_term)).await; |
| 12623 | assert_eq!(res.status, StatusCode::CREATED); |
| 12624 | let term = id_of(&res.body); |
| 12625 | |
| 12626 | // The range stays ordered, merged PATCHes included. |
| 12627 | let res = send( |
| 12628 | &app, |
| 12629 | "POST", |
| 12630 | "/terms", |
| 12631 | Some(&manager), |
| 12632 | Some(json!({ "name": "Broken", "year": year, "starts_at": 2, "ends_at": 1 })), |
| 12633 | ) |
| 12634 | .await; |
| 12635 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 12636 | let res = send( |
| 12637 | &app, |
| 12638 | "PATCH", |
| 12639 | &format!("/terms/{term}"), |
| 12640 | Some(&manager), |
| 12641 | Some(json!({ "ends_at": 1_500_000_000_000_i64 })), |
| 12642 | ) |
| 12643 | .await; |
| 12644 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 12645 | let res = send( |
| 12646 | &app, |
| 12647 | "PATCH", |
| 12648 | &format!("/terms/{term}"), |
| 12649 | Some(&manager), |
| 12650 | Some(json!({ "name": "2025/26 Fall" })), |
| 12651 | ) |
| 12652 | .await; |
| 12653 | assert_eq!(res.status, StatusCode::OK); |
| 12654 | assert_eq!(res.body["name"], "2025/26 Fall"); |
| 12655 | |
| 12656 | // Any authenticated user reads the calendar. |
| 12657 | let res = send(&app, "GET", "/terms", Some(&student), None).await; |
| 12658 | assert_eq!(res.status, StatusCode::OK); |
| 12659 | assert_eq!(common::items(&res.body).len(), 1); |
| 12660 | |
| 12661 | // The catalog is outside the calendar now: a course carries no dönem to |
| 12662 | // link, unlink or be judged by. What a dönem's delete guard counts is the |
| 12663 | // *exams* filed under it (its own section pins that), so the two are |
| 12664 | // independent — which is what this arm now says. |
| 12665 | let res = send( |
| 12666 | &app, |
| 12667 | "POST", |
| 12668 | "/courses", |
| 12669 | Some(&teacher), |
| 12670 | Some(json!({ "title": "History" })), |
| 12671 | ) |
| 12672 | .await; |
| 12673 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 12674 | let course = id_of(&res.body); |
| 12675 | assert!( |
| 12676 | res.body.get("term").is_none(), |
| 12677 | "a catalog course has no dönem to carry: {}", |
| 12678 | res.body |
| 12679 | ); |
| 12680 | |
| 12681 | // Its own PATCH is what changes it, and the calendar does not ride along. |
| 12682 | let res = send( |
| 12683 | &app, |
| 12684 | "PATCH", |
| 12685 | &format!("/courses/{course}"), |
| 12686 | Some(&teacher), |
| 12687 | Some(json!({ "title": "History II" })), |
| 12688 | ) |
| 12689 | .await; |
| 12690 | assert_eq!(res.status, StatusCode::OK); |
| 12691 | |
| 12692 | // Deleting the dönem leaves the catalog row standing. |
| 12693 | let res = send( |
| 12694 | &app, |
| 12695 | "DELETE", |
| 12696 | &format!("/terms/{term}"), |
| 12697 | Some(&manager), |
| 12698 | None, |
| 12699 | ) |
| 12700 | .await; |
| 12701 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 12702 | let res = send(&app, "GET", &format!("/terms/{term}"), Some(&student), None).await; |
| 12703 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 12704 | let res = send( |
| 12705 | &app, |
| 12706 | "GET", |
| 12707 | &format!("/courses/{course}"), |
| 12708 | Some(&teacher), |
| 12709 | None, |
| 12710 | ) |
| 12711 | .await; |
| 12712 | assert_eq!(res.status, StatusCode::OK); |
| 12713 | assert_eq!(res.body["title"], "History II"); |
| 12714 | assert_eq!(res.body["term"], serde_json::Value::Null); |
| 12715 | } |
| 12716 | |
| 12717 | #[tokio::test] |
| 12718 | async fn roll_call_accepts_school_statuses_and_buckets_session_reports() { |
| 12719 | let (app, db) = app_and_db().await; |
| 12720 | let manager = login_as(&app, &db, "roll.manager", "manager").await; |
| 12721 | let teacher = login_as(&app, &db, "roll.teacher", "teacher").await; |
| 12722 | let student = login(&app, "roll.student").await; |
| 12723 | let student_id = me_id(&app, &student).await; |
| 12724 | |
| 12725 | // The event path is already covered; this proves the second marking |
| 12726 | // path — lesson roll call — reads the same settings list. |
| 12727 | let res = send( |
| 12728 | &app, |
| 12729 | "PATCH", |
| 12730 | "/settings", |
| 12731 | Some(&manager), |
| 12732 | Some(json!({ |
| 12733 | "attendance_statuses": ["present", "absent", "late", "excused", "online"] |
| 12734 | })), |
| 12735 | ) |
| 12736 | .await; |
| 12737 | assert_eq!(res.status, StatusCode::OK); |
| 12738 | |
| 12739 | let t = taught_under(&app, &manager, &teacher, "Biology").await; |
| 12740 | add_member(&app, &manager, &t.class, &student_id).await; |
| 12741 | let future = Timestamp::now().as_millis() + 3_600_000; |
| 12742 | let session = create_session(&app, &teacher, &t.instance, future).await; |
| 12743 | |
| 12744 | // Custom status marks; garbage still dies. |
| 12745 | let res = send( |
| 12746 | &app, |
| 12747 | "POST", |
| 12748 | &format!("/sessions/{session}/attendance"), |
| 12749 | Some(&teacher), |
| 12750 | Some(json!({ "status": "online", "user_id": student_id })), |
| 12751 | ) |
| 12752 | .await; |
| 12753 | assert_eq!(res.status, StatusCode::OK); |
| 12754 | assert_eq!(res.body["status"], "online"); |
| 12755 | let res = send( |
| 12756 | &app, |
| 12757 | "POST", |
| 12758 | &format!("/sessions/{session}/attendance"), |
| 12759 | Some(&teacher), |
| 12760 | Some(json!({ "status": "onsite", "user_id": student_id })), |
| 12761 | ) |
| 12762 | .await; |
| 12763 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 12764 | |
| 12765 | // Both the overall session tally and the per-course block bucket it |
| 12766 | // under `custom`, rate-neutral. |
| 12767 | let res = send(&app, "GET", "/attendance/me", Some(&student), None).await; |
| 12768 | assert_eq!(res.status, StatusCode::OK); |
| 12769 | assert_eq!(res.body["sessions"]["custom"]["online"], 1); |
| 12770 | assert_eq!(res.body["sessions"]["total"], 1); |
| 12771 | assert_eq!(res.body["sessions"]["rate"], serde_json::Value::Null); |
| 12772 | let block = &res.body["courses"][0]; |
| 12773 | assert_eq!(block["counts"]["custom"]["online"], 1); |
| 12774 | assert_eq!(block["counts"]["rate"], serde_json::Value::Null); |
| 12775 | } |
| 12776 | |
| 12777 | #[tokio::test] |
| 12778 | async fn terms_list_newest_first_require_auth_and_guard_delete_per_term() { |
| 12779 | let (app, db) = app_and_db().await; |
| 12780 | let manager = login_as(&app, &db, "bulk.manager", "manager").await; |
| 12781 | let teacher = login_as(&app, &db, "bulk.teacher", "teacher").await; |
| 12782 | |
| 12783 | // The calendar is not public. |
| 12784 | let res = send(&app, "GET", "/terms", None, None).await; |
| 12785 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); |
| 12786 | |
| 12787 | let year = create_year(&app, &manager, "2025-2026").await; |
| 12788 | let older = send( |
| 12789 | &app, |
| 12790 | "POST", |
| 12791 | "/terms", |
| 12792 | Some(&manager), |
| 12793 | Some(json!({ |
| 12794 | "name": "2025 Fall", "year": year, |
| 12795 | "starts_at": 1_000, "ends_at": 2_000, |
| 12796 | })), |
| 12797 | ) |
| 12798 | .await; |
| 12799 | let newer = send( |
| 12800 | &app, |
| 12801 | "POST", |
| 12802 | "/terms", |
| 12803 | Some(&manager), |
| 12804 | Some(json!({ |
| 12805 | "name": "2026 Spring", "year": year, |
| 12806 | "starts_at": 5_000, "ends_at": 6_000, |
| 12807 | })), |
| 12808 | ) |
| 12809 | .await; |
| 12810 | let (older, newer) = (id_of(&older.body), id_of(&newer.body)); |
| 12811 | |
| 12812 | // Newest (by starts_at) first. |
| 12813 | let res = send(&app, "GET", "/terms", Some(&teacher), None).await; |
| 12814 | let names: Vec<&str> = common::items(&res.body) |
| 12815 | .iter() |
| 12816 | .map(|t| t["name"].as_str().unwrap()) |
| 12817 | .collect(); |
| 12818 | assert_eq!(names, ["2026 Spring", "2025 Fall"]); |
| 12819 | |
| 12820 | // The delete guard counts EVERY exam filed under the dönem — removing one |
| 12821 | // of two is not enough — and it is per dönem: an exam on another dönem |
| 12822 | // never blocks this one. |
| 12823 | let t = taught_under(&app, &manager, &teacher, "Algebra").await; |
| 12824 | let mut linked = Vec::new(); |
| 12825 | for title in ["Midterm", "Final"] { |
| 12826 | linked.push(create_exam(&app, &teacher, &t.instance, &newer, title, "yazili").await); |
| 12827 | } |
| 12828 | let unrelated = create_exam(&app, &teacher, &t.instance, &older, "History", "yazili").await; |
| 12829 | |
| 12830 | assert_eq!( |
| 12831 | send( |
| 12832 | &app, |
| 12833 | "DELETE", |
| 12834 | &format!("/terms/{newer}"), |
| 12835 | Some(&manager), |
| 12836 | None |
| 12837 | ) |
| 12838 | .await |
| 12839 | .status, |
| 12840 | StatusCode::CONFLICT |
| 12841 | ); |
| 12842 | |
| 12843 | for (i, exam) in linked.iter().enumerate() { |
| 12844 | assert_eq!( |
| 12845 | send( |
| 12846 | &app, |
| 12847 | "DELETE", |
| 12848 | &format!("/exams/{exam}"), |
| 12849 | Some(&teacher), |
| 12850 | None |
| 12851 | ) |
| 12852 | .await |
| 12853 | .status, |
| 12854 | StatusCode::NO_CONTENT |
| 12855 | ); |
| 12856 | // Still blocked until the LAST exam lets go. |
| 12857 | let res = send( |
| 12858 | &app, |
| 12859 | "DELETE", |
| 12860 | &format!("/terms/{newer}"), |
| 12861 | Some(&manager), |
| 12862 | None, |
| 12863 | ) |
| 12864 | .await; |
| 12865 | let expected = if i + 1 == linked.len() { |
| 12866 | StatusCode::NO_CONTENT |
| 12867 | } else { |
| 12868 | StatusCode::CONFLICT |
| 12869 | }; |
| 12870 | assert_eq!(res.status, expected, "after deleting {exam}"); |
| 12871 | } |
| 12872 | |
| 12873 | // The unrelated exam is filed under the other dönem and never blocked |
| 12874 | // this one: it is gone from the calendar's view only when its own dönem |
| 12875 | // goes, and that dönem is blocked by its own exam. |
| 12876 | assert_eq!( |
| 12877 | send( |
| 12878 | &app, |
| 12879 | "GET", |
| 12880 | &format!("/exams/{unrelated}"), |
| 12881 | Some(&teacher), |
| 12882 | None |
| 12883 | ) |
| 12884 | .await |
| 12885 | .body["term"], |
| 12886 | older |
| 12887 | ); |
| 12888 | assert_eq!( |
| 12889 | send( |
| 12890 | &app, |
| 12891 | "DELETE", |
| 12892 | &format!("/terms/{older}"), |
| 12893 | Some(&manager), |
| 12894 | None |
| 12895 | ) |
| 12896 | .await |
| 12897 | .status, |
| 12898 | StatusCode::CONFLICT |
| 12899 | ); |
| 12900 | assert_eq!( |
| 12901 | send( |
| 12902 | &app, |
| 12903 | "DELETE", |
| 12904 | &format!("/exams/{unrelated}"), |
| 12905 | Some(&teacher), |
| 12906 | None |
| 12907 | ) |
| 12908 | .await |
| 12909 | .status, |
| 12910 | StatusCode::NO_CONTENT |
| 12911 | ); |
| 12912 | assert_eq!( |
| 12913 | send( |
| 12914 | &app, |
| 12915 | "DELETE", |
| 12916 | &format!("/terms/{older}"), |
| 12917 | Some(&manager), |
| 12918 | None |
| 12919 | ) |
| 12920 | .await |
| 12921 | .status, |
| 12922 | StatusCode::NO_CONTENT |
| 12923 | ); |
| 12924 | } |
| 12925 | |
| 12926 | #[tokio::test] |
| 12927 | async fn grade_band_boundary_applies_to_the_weighted_average() { |
| 12928 | let (app, db) = app_and_db().await; |
| 12929 | let teacher = login_as(&app, &db, "edge.teacher", "teacher").await; |
| 12930 | let manager = login_as(&app, &db, "edge.manager", "manager").await; |
| 12931 | let student = login(&app, "edge.student").await; |
| 12932 | let student_id = me_id(&app, &student).await; |
| 12933 | |
| 12934 | let res = send( |
| 12935 | &app, |
| 12936 | "PATCH", |
| 12937 | "/settings", |
| 12938 | Some(&manager), |
| 12939 | Some(json!({ |
| 12940 | "grade_bands": [{ "min": 0, "label": "FF" }, { "min": 85, "label": "AA" }] |
| 12941 | })), |
| 12942 | ) |
| 12943 | .await; |
| 12944 | assert_eq!(res.status, StatusCode::OK); |
| 12945 | |
| 12946 | // Two equal-weight marks straddling the band edge: 80 and 90 → average |
| 12947 | // exactly 85.0, which is INSIDE the AA band (min is inclusive), while |
| 12948 | // the 80 itself still reads FF. |
| 12949 | let t = taught_under(&app, &manager, &teacher, "Calculus").await; |
| 12950 | add_member(&app, &manager, &t.class, &student_id).await; |
| 12951 | for (title, mark) in [("Quiz A", 80), ("Quiz B", 90)] { |
| 12952 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, title, "yazili").await; |
| 12953 | let res = send( |
| 12954 | &app, |
| 12955 | "POST", |
| 12956 | &format!("/exams/{exam}/results"), |
| 12957 | Some(&teacher), |
| 12958 | Some(json!({ "user_id": student_id, "mark": mark })), |
| 12959 | ) |
| 12960 | .await; |
| 12961 | assert_eq!(res.status, StatusCode::OK); |
| 12962 | } |
| 12963 | |
| 12964 | let res = send(&app, "GET", "/marks/me", Some(&student), None).await; |
| 12965 | let block = &res.body["courses"][0]; |
| 12966 | assert_eq!(block["average"], 85.0); |
| 12967 | assert_eq!(block["average_grade"], "AA"); |
| 12968 | let grades: Vec<(&str, &str)> = block["results"] |
| 12969 | .as_array() |
| 12970 | .unwrap() |
| 12971 | .iter() |
| 12972 | .map(|r| (r["title"].as_str().unwrap(), r["grade"].as_str().unwrap())) |
| 12973 | .collect(); |
| 12974 | assert!(grades.contains(&("Quiz A", "FF"))); |
| 12975 | assert!(grades.contains(&("Quiz B", "AA"))); |
| 12976 | assert_eq!(res.body["overall_grade"], "AA"); |
| 12977 | } |
| 12978 | |
| 12979 | /// Two managers patch DIFFERENT fields concurrently. Neither edit may be lost |
| 12980 | /// and neither request may 500 — the compare-and-set loop absorbs the |
| 12981 | /// conflict and re-merges (the guard `save_if_unchanged` exists for). |
| 12982 | #[tokio::test] |
| 12983 | async fn concurrent_settings_patches_both_land() { |
| 12984 | for _round in 0..10 { |
| 12985 | let (app, db) = app_and_db().await; |
| 12986 | let mavi = login_as(&app, &db, "mavi", "manager").await; |
| 12987 | let kara = login_as(&app, &db, "kara", "manager").await; |
| 12988 | |
| 12989 | let (a, b) = tokio::join!( |
| 12990 | send( |
| 12991 | &app, |
| 12992 | "PATCH", |
| 12993 | "/settings", |
| 12994 | Some(&mavi), |
| 12995 | Some( |
| 12996 | json!({ "grade_bands": [ { "min": 0, "label": "F" }, { "min": 50, "label": "P" } ] }) |
| 12997 | ), |
| 12998 | ), |
| 12999 | send( |
| 13000 | &app, |
| 13001 | "PATCH", |
| 13002 | "/settings", |
| 13003 | Some(&kara), |
| 13004 | Some(json!({ "max_file_bytes": 4096 })), |
| 13005 | ), |
| 13006 | ); |
| 13007 | assert_eq!(a.status, StatusCode::OK, "bands patch: {}", a.body); |
| 13008 | assert_eq!(b.status, StatusCode::OK, "bytes patch: {}", b.body); |
| 13009 | |
| 13010 | let after = send(&app, "GET", "/settings", Some(&mavi), None).await; |
| 13011 | assert_eq!(after.body["max_file_bytes"], 4096, "{}", after.body); |
| 13012 | assert_eq!( |
| 13013 | after.body["grade_bands"].as_array().unwrap().len(), |
| 13014 | 2, |
| 13015 | "both concurrent edits must survive: {}", |
| 13016 | after.body |
| 13017 | ); |
| 13018 | } |
| 13019 | } |
| 13020 | |
| 13021 | #[tokio::test] |
| 13022 | async fn settings_accept_admin_edits_trim_entries_and_noop_on_empty_patch() { |
| 13023 | let (app, db) = app_and_db().await; |
| 13024 | let admin = login_as(&app, &db, "adm.admin", "admin").await; |
| 13025 | |
| 13026 | // An empty PATCH is a valid no-op: current policy back, nothing changed. |
| 13027 | let res = send(&app, "PATCH", "/settings", Some(&admin), Some(json!({}))).await; |
| 13028 | assert_eq!(res.status, StatusCode::OK); |
| 13029 | let kinds: Vec<&str> = res.body["exam_kinds"] |
| 13030 | .as_array() |
| 13031 | .unwrap() |
| 13032 | .iter() |
| 13033 | .map(|kind| kind["name"].as_str().unwrap()) |
| 13034 | .collect(); |
| 13035 | assert_eq!( |
| 13036 | kinds, |
| 13037 | ["yazili", "sozlu", "uygulama"], |
| 13038 | "the shipped default kinds: {}", |
| 13039 | res.body |
| 13040 | ); |
| 13041 | |
| 13042 | // Admin clears the manager bar (hierarchy, not equality), and kind names |
| 13043 | // arrive trimmed on the wire. |
| 13044 | let res = send( |
| 13045 | &app, |
| 13046 | "PATCH", |
| 13047 | "/settings", |
| 13048 | Some(&admin), |
| 13049 | Some(json!({ "exam_kinds": [ |
| 13050 | {"name": " lab ", "weight": 2}, |
| 13051 | {"name": "quiz", "weight": 1}, |
| 13052 | ]})), |
| 13053 | ) |
| 13054 | .await; |
| 13055 | assert_eq!(res.status, StatusCode::OK); |
| 13056 | assert_eq!( |
| 13057 | res.body["exam_kinds"], |
| 13058 | json!([ |
| 13059 | {"name": "lab", "weight": 2}, |
| 13060 | {"name": "quiz", "weight": 1}, |
| 13061 | ]) |
| 13062 | ); |
| 13063 | } |
| 13064 | |
| 13065 | /// The food-program knobs are `option<…>` columns, and every settings save |
| 13066 | /// rewrites the whole row — so a PATCH that never mentions them must still |
| 13067 | /// round-trip them. (A `DEFAULT []` column plus a struct that dropped the field |
| 13068 | /// aborts the transaction with a coercion error instead.) |
| 13069 | #[tokio::test] |
| 13070 | async fn settings_round_trip_the_food_program_knobs() { |
| 13071 | let (app, db) = app_and_db().await; |
| 13072 | let manager = login_as(&app, &db, "meal.manager", "manager").await; |
| 13073 | |
| 13074 | // Unset columns read as the built-in seeds; an absent cutoff is no cutoff. |
| 13075 | let res = send(&app, "GET", "/settings", Some(&manager), None).await; |
| 13076 | assert_eq!( |
| 13077 | res.body["meal_slots"], |
| 13078 | json!([ |
| 13079 | {"name": "breakfast", "serving_minute": null}, |
| 13080 | {"name": "lunch", "serving_minute": null}, |
| 13081 | {"name": "snack", "serving_minute": null}, |
| 13082 | ]), |
| 13083 | "the shipped defaults carry no serving time, so the cutoff keeps its \ |
| 13084 | midnight-UTC meaning until a school sets real hours" |
| 13085 | ); |
| 13086 | assert_eq!( |
| 13087 | res.body["dietary_tags"], |
| 13088 | json!([ |
| 13089 | "vegetarian", |
| 13090 | "vegan", |
| 13091 | "gluten_free", |
| 13092 | "lactose_free", |
| 13093 | "nut_allergy" |
| 13094 | ]) |
| 13095 | ); |
| 13096 | assert_eq!(res.body["meal_cancel_cutoff_minutes"], json!(null)); |
| 13097 | |
| 13098 | // A PATCH of an unrelated field still writes the whole row. |
| 13099 | let res = send( |
| 13100 | &app, |
| 13101 | "PATCH", |
| 13102 | "/settings", |
| 13103 | Some(&manager), |
| 13104 | Some(json!({ "max_file_bytes": 4096 })), |
| 13105 | ) |
| 13106 | .await; |
| 13107 | assert_eq!(res.status, StatusCode::OK); |
| 13108 | assert_eq!(res.body["meal_slots"].as_array().unwrap().len(), 3); |
| 13109 | |
| 13110 | // All three set at once; slot names arrive trimmed. |
| 13111 | let res = send( |
| 13112 | &app, |
| 13113 | "PATCH", |
| 13114 | "/settings", |
| 13115 | Some(&manager), |
| 13116 | Some(json!({ |
| 13117 | "meal_slots": [ |
| 13118 | {"name": "lunch", "serving_minute": 720}, |
| 13119 | {"name": " snack "}, |
| 13120 | ], |
| 13121 | "dietary_tags": ["vegan"], |
| 13122 | "meal_cancel_cutoff_minutes": 120, |
| 13123 | })), |
| 13124 | ) |
| 13125 | .await; |
| 13126 | assert_eq!(res.status, StatusCode::OK); |
| 13127 | assert_eq!( |
| 13128 | res.body["meal_slots"], |
| 13129 | json!([ |
| 13130 | {"name": "lunch", "serving_minute": 720}, |
| 13131 | {"name": "snack", "serving_minute": null}, |
| 13132 | ]), |
| 13133 | "slots round-trip with and without a serving time" |
| 13134 | ); |
| 13135 | assert_eq!(res.body["dietary_tags"], json!(["vegan"])); |
| 13136 | assert_eq!(res.body["meal_cancel_cutoff_minutes"], 120); |
| 13137 | |
| 13138 | // A later PATCH that omits them keeps them — now over a row that really |
| 13139 | // carries the columns. |
| 13140 | let res = send( |
| 13141 | &app, |
| 13142 | "PATCH", |
| 13143 | "/settings", |
| 13144 | Some(&manager), |
| 13145 | Some(json!({ "chatbot_history_turns": 3 })), |
| 13146 | ) |
| 13147 | .await; |
| 13148 | assert_eq!(res.status, StatusCode::OK); |
| 13149 | assert_eq!(res.body["meal_slots"].as_array().unwrap().len(), 2); |
| 13150 | assert_eq!(res.body["meal_cancel_cutoff_minutes"], 120); |
| 13151 | |
| 13152 | // `null` clears the cutoff (no cutoff at all); the lists stay. |
| 13153 | let res = send( |
| 13154 | &app, |
| 13155 | "PATCH", |
| 13156 | "/settings", |
| 13157 | Some(&manager), |
| 13158 | Some(json!({ "meal_cancel_cutoff_minutes": null })), |
| 13159 | ) |
| 13160 | .await; |
| 13161 | assert_eq!(res.status, StatusCode::OK); |
| 13162 | assert_eq!(res.body["meal_cancel_cutoff_minutes"], json!(null)); |
| 13163 | assert_eq!(res.body["meal_slots"].as_array().unwrap().len(), 2); |
| 13164 | |
| 13165 | // Bounds hold on the way in. |
| 13166 | for body in [ |
| 13167 | json!({ "meal_cancel_cutoff_minutes": 10_081 }), |
| 13168 | json!({ "meal_cancel_cutoff_minutes": -1 }), |
| 13169 | json!({ "meal_slots": [{"name": " "}] }), |
| 13170 | json!({ "meal_slots": [{"name": "Lunch"}, {"name": "lunch"}] }), |
| 13171 | json!({ "meal_slots": [{"name": "lunch", "serving_minute": 1440}] }), |
| 13172 | json!({ "meal_slots": [{"name": "lunch", "serving_minute": -1}] }), |
| 13173 | json!({ "dietary_tags": ["vegan", "VEGAN"] }), |
| 13174 | ] { |
| 13175 | let res = send( |
| 13176 | &app, |
| 13177 | "PATCH", |
| 13178 | "/settings", |
| 13179 | Some(&manager), |
| 13180 | Some(body.clone()), |
| 13181 | ) |
| 13182 | .await; |
| 13183 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "should reject {body}"); |
| 13184 | } |
| 13185 | |
| 13186 | // A published menu pins the slot it snapshotted: dropping it is a 409. |
| 13187 | let menu = send( |
| 13188 | &app, |
| 13189 | "POST", |
| 13190 | "/meals/menus", |
| 13191 | Some(&manager), |
| 13192 | Some(json!({ "date": "2099-07-27", "slot": "lunch" })), |
| 13193 | ) |
| 13194 | .await; |
| 13195 | assert_eq!(menu.status, StatusCode::CREATED, "{}", menu.body); |
| 13196 | let res = send( |
| 13197 | &app, |
| 13198 | "PATCH", |
| 13199 | "/settings", |
| 13200 | Some(&manager), |
| 13201 | Some(json!({ "meal_slots": [{"name": "snack"}] })), |
| 13202 | ) |
| 13203 | .await; |
| 13204 | assert_eq!(res.status, StatusCode::CONFLICT); |
| 13205 | // Keeping it is fine; an unused slot still leaves freely. |
| 13206 | let res = send( |
| 13207 | &app, |
| 13208 | "PATCH", |
| 13209 | "/settings", |
| 13210 | Some(&manager), |
| 13211 | Some(json!({ "meal_slots": [{"name": "lunch"}, {"name": "dinner"}] })), |
| 13212 | ) |
| 13213 | .await; |
| 13214 | assert_eq!(res.status, StatusCode::OK); |
| 13215 | assert_eq!( |
| 13216 | res.body["meal_slots"], |
| 13217 | json!([ |
| 13218 | {"name": "lunch", "serving_minute": null}, |
| 13219 | {"name": "dinner", "serving_minute": null}, |
| 13220 | ]) |
| 13221 | ); |
| 13222 | } |
| 13223 | |
| 13224 | // --- question images --------------------------------------------------------- |
| 13225 | |
| 13226 | /// POST `bytes` as a multipart image upload to `path`; returns (status, json). |
| 13227 | async fn post_image( |
| 13228 | app: &axum::Router, |
| 13229 | cookie: &str, |
| 13230 | path: &str, |
| 13231 | content_type: &str, |
| 13232 | bytes: &[u8], |
| 13233 | ) -> (StatusCode, serde_json::Value) { |
| 13234 | let (status, _, body) = common::send_raw( |
| 13235 | app, |
| 13236 | "POST", |
| 13237 | path, |
| 13238 | Some(cookie), |
| 13239 | Some("multipart/form-data; boundary=hezarfen-test-boundary"), |
| 13240 | common::multipart_file("pic.png", content_type, bytes), |
| 13241 | ) |
| 13242 | .await; |
| 13243 | let body = if body.is_empty() { |
| 13244 | serde_json::Value::Null |
| 13245 | } else { |
| 13246 | serde_json::from_slice(&body).unwrap_or(serde_json::Value::Null) |
| 13247 | }; |
| 13248 | (status, body) |
| 13249 | } |
| 13250 | |
| 13251 | /// Every stored question-image blob name, straight from the table. |
| 13252 | async fn image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { |
| 13253 | sqlx::query_scalar("SELECT file FROM question_image") |
| 13254 | .fetch_all(db) |
| 13255 | .await |
| 13256 | .unwrap() |
| 13257 | } |
| 13258 | |
| 13259 | /// Every stored bank-question-image blob name, straight from the table. |
| 13260 | async fn bank_image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { |
| 13261 | sqlx::query_scalar("SELECT file FROM bank_question_image") |
| 13262 | .fetch_all(db) |
| 13263 | .await |
| 13264 | .unwrap() |
| 13265 | } |
| 13266 | |
| 13267 | /// Every stored answer-image (student drawing) blob name, straight from the table. |
| 13268 | async fn answer_image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { |
| 13269 | sqlx::query_scalar("SELECT file FROM answer_image") |
| 13270 | .fetch_all(db) |
| 13271 | .await |
| 13272 | .unwrap() |
| 13273 | } |
| 13274 | |
| 13275 | /// The full life of question images: teacher uploads (question + choice slots, |
| 13276 | /// rasters only, choice slots bounded), metadata on both question views, |
| 13277 | /// bytes behind the sitting wall, replace swaps the blob, a choices PATCH |
| 13278 | /// drops the option pictures, and every delete path takes the blobs with it. |
| 13279 | #[tokio::test] |
| 13280 | async fn question_images_author_serve_and_cascade() { |
| 13281 | let (app, db) = app_and_db().await; |
| 13282 | let teacher = login_as(&app, &db, "img_t", "teacher").await; |
| 13283 | let student = login(&app, "img_s").await; |
| 13284 | let student_id = me_id(&app, &student).await; |
| 13285 | let outsider = login(&app, "img_o").await; |
| 13286 | |
| 13287 | let mudur = login_as(&app, &db, "img_m", "manager").await; |
| 13288 | let t = taught_under(&app, &mudur, &teacher, "geography").await; |
| 13289 | let subject = create_subject(&app, &teacher, &t.course, "maps").await; |
| 13290 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 13291 | let exam = scheduled_exam( |
| 13292 | &app, |
| 13293 | &teacher, |
| 13294 | &t.instance, |
| 13295 | json!({ "term": &t.term, "title": "map quiz", "kind": "yazili", "mode": "open" }), |
| 13296 | ) |
| 13297 | .await; |
| 13298 | let question_body = create_question_body( |
| 13299 | &app, |
| 13300 | &teacher, |
| 13301 | &exam, |
| 13302 | &subject, |
| 13303 | json!({ "text": "Which city is marked?", "kind": "choice", "points": 10, |
| 13304 | "choices": [{"id": "c0", "text": "Ankara"}, {"id": "c1", "text": "İzmir"}], "correct": "c0" }), |
| 13305 | ) |
| 13306 | .await; |
| 13307 | let question = id_of(&question_body); |
| 13308 | let essay = create_question( |
| 13309 | &app, |
| 13310 | &teacher, |
| 13311 | &exam, |
| 13312 | &subject, |
| 13313 | json!({ "text": "Describe the marked region.", "kind": "text", "points": 10 }), |
| 13314 | ) |
| 13315 | .await; |
| 13316 | |
| 13317 | let q_image = format!("/exams/{exam}/questions/{question}/image"); |
| 13318 | let png = b"png-bytes-question".as_slice(); |
| 13319 | |
| 13320 | // SVG is out (script risk); unknown types are out; rasters land. |
| 13321 | let (status, body) = post_image(&app, &teacher, &q_image, "image/svg+xml", b"<svg/>").await; |
| 13322 | assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); |
| 13323 | let (status, body) = post_image(&app, &teacher, &q_image, "application/pdf", b"%PDF").await; |
| 13324 | assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); |
| 13325 | let (status, body) = post_image(&app, &teacher, &q_image, "image/png", png).await; |
| 13326 | assert_eq!(status, StatusCode::CREATED, "{body}"); |
| 13327 | assert_eq!(body["content_type"], "image/png"); |
| 13328 | assert_eq!(body["size"], png.len() as i64); |
| 13329 | |
| 13330 | // A classical (text) question takes an illustration too — but no option |
| 13331 | // pictures, and no out-of-range slot anywhere. |
| 13332 | let (status, body) = post_image( |
| 13333 | &app, |
| 13334 | &teacher, |
| 13335 | &format!("/exams/{exam}/questions/{essay}/image"), |
| 13336 | "image/jpeg", |
| 13337 | b"jpeg-essay", |
| 13338 | ) |
| 13339 | .await; |
| 13340 | assert_eq!(status, StatusCode::CREATED, "{body}"); |
| 13341 | let (status, _) = post_image( |
| 13342 | &app, |
| 13343 | &teacher, |
| 13344 | &format!( |
| 13345 | "/exams/{exam}/questions/{essay}/choices/{}/image", |
| 13346 | choice_of(&question_body, 0) |
| 13347 | ), |
| 13348 | "image/png", |
| 13349 | b"x", |
| 13350 | ) |
| 13351 | .await; |
| 13352 | assert_eq!( |
| 13353 | status, |
| 13354 | StatusCode::BAD_REQUEST, |
| 13355 | "text questions take no option pictures" |
| 13356 | ); |
| 13357 | let (status, _) = post_image( |
| 13358 | &app, |
| 13359 | &teacher, |
| 13360 | &format!("/exams/{exam}/questions/{question}/choices/01NOTACHOICEOFTHISQUEST/image"), |
| 13361 | "image/png", |
| 13362 | b"x", |
| 13363 | ) |
| 13364 | .await; |
| 13365 | assert_eq!(status, StatusCode::BAD_REQUEST, "slot must name a choice"); |
| 13366 | |
| 13367 | // Option picture on choice 1, and the author view carries all the metas. |
| 13368 | let choice_image = format!( |
| 13369 | "/exams/{exam}/questions/{question}/choices/{}/image", |
| 13370 | choice_of(&question_body, 1) |
| 13371 | ); |
| 13372 | let (status, _) = post_image(&app, &teacher, &choice_image, "image/webp", b"webp-choice").await; |
| 13373 | assert_eq!(status, StatusCode::CREATED); |
| 13374 | let res = send( |
| 13375 | &app, |
| 13376 | "GET", |
| 13377 | &format!("/exams/{exam}/questions"), |
| 13378 | Some(&teacher), |
| 13379 | None, |
| 13380 | ) |
| 13381 | .await; |
| 13382 | assert_eq!(res.status, StatusCode::OK); |
| 13383 | let listed = &common::items(&res.body)[0]; |
| 13384 | assert_eq!(listed["image"]["content_type"], "image/png"); |
| 13385 | assert!(listed["choice_images"][0].is_null()); |
| 13386 | assert_eq!(listed["choice_images"][1]["content_type"], "image/webp"); |
| 13387 | |
| 13388 | // Replace swaps the blob under the same slot: one row, fresh bytes. |
| 13389 | let keys_before = image_blob_keys(&db).await; |
| 13390 | let png2 = b"png-bytes-question-v2".as_slice(); |
| 13391 | let (status, body) = post_image(&app, &teacher, &q_image, "image/png", png2).await; |
| 13392 | assert_eq!(status, StatusCode::CREATED); |
| 13393 | assert_eq!(body["size"], png2.len() as i64); |
| 13394 | let keys_after = image_blob_keys(&db).await; |
| 13395 | assert_eq!(keys_before.len(), keys_after.len(), "replace adds no row"); |
| 13396 | for stale in keys_before.iter().filter(|k| !keys_after.contains(k)) { |
| 13397 | assert!( |
| 13398 | !common::blob_dir().join(stale).exists(), |
| 13399 | "replaced blob lingers on disk" |
| 13400 | ); |
| 13401 | } |
| 13402 | |
| 13403 | // The bytes sit behind the sitting wall: outsiders 403, enrolled students |
| 13404 | // 404 until an attempt exists, then 200 with the guard headers on. |
| 13405 | let (status, _, _) = |
| 13406 | common::send_raw(&app, "GET", &q_image, Some(&outsider), None, Vec::new()).await; |
| 13407 | assert_eq!(status, StatusCode::FORBIDDEN); |
| 13408 | let (status, _, _) = |
| 13409 | common::send_raw(&app, "GET", &q_image, Some(&student), None, Vec::new()).await; |
| 13410 | assert_eq!( |
| 13411 | status, |
| 13412 | StatusCode::NOT_FOUND, |
| 13413 | "no early peek before the attempt" |
| 13414 | ); |
| 13415 | let res = send( |
| 13416 | &app, |
| 13417 | "POST", |
| 13418 | &format!("/exams/{exam}/attempt"), |
| 13419 | Some(&student), |
| 13420 | None, |
| 13421 | ) |
| 13422 | .await; |
| 13423 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 13424 | let (status, headers, bytes) = |
| 13425 | common::send_raw(&app, "GET", &q_image, Some(&student), None, Vec::new()).await; |
| 13426 | assert_eq!(status, StatusCode::OK); |
| 13427 | assert_eq!(bytes, png2); |
| 13428 | assert_eq!(headers["content-type"], "image/png"); |
| 13429 | assert_eq!(headers["x-content-type-options"], "nosniff"); |
| 13430 | assert_eq!(headers["cache-control"], "private, no-store"); |
| 13431 | let (status, _, bytes) = |
| 13432 | common::send_raw(&app, "GET", &choice_image, Some(&student), None, Vec::new()).await; |
| 13433 | assert_eq!(status, StatusCode::OK); |
| 13434 | assert_eq!(bytes, b"webp-choice"); |
| 13435 | |
| 13436 | // The sitting view embeds the same metadata the author sees (sans key). |
| 13437 | let res = send( |
| 13438 | &app, |
| 13439 | "GET", |
| 13440 | &format!("/exams/{exam}/attempt/questions"), |
| 13441 | Some(&student), |
| 13442 | None, |
| 13443 | ) |
| 13444 | .await; |
| 13445 | assert_eq!(res.status, StatusCode::OK); |
| 13446 | assert_eq!(res.body[0]["image"]["content_type"], "image/png"); |
| 13447 | assert_eq!( |
| 13448 | res.body[0]["choice_images"][1]["content_type"], |
| 13449 | "image/webp" |
| 13450 | ); |
| 13451 | assert_eq!(res.body[1]["image"]["content_type"], "image/jpeg"); |
| 13452 | assert!(res.body[1]["choice_images"].is_null()); |
| 13453 | |
| 13454 | // Images freeze with the rest of the question once attempts exist. |
| 13455 | let (status, body) = post_image(&app, &teacher, &q_image, "image/png", b"late").await; |
| 13456 | assert_eq!(status, StatusCode::CONFLICT, "{body}"); |
| 13457 | let res = send(&app, "DELETE", &q_image, Some(&teacher), None).await; |
| 13458 | assert_eq!(res.status, StatusCode::CONFLICT); |
| 13459 | |
| 13460 | // Deleting the exam takes every image row and blob with it. |
| 13461 | let keys = image_blob_keys(&db).await; |
| 13462 | assert_eq!(keys.len(), 3); |
| 13463 | let res = send( |
| 13464 | &app, |
| 13465 | "DELETE", |
| 13466 | &format!("/exams/{exam}"), |
| 13467 | Some(&teacher), |
| 13468 | None, |
| 13469 | ) |
| 13470 | .await; |
| 13471 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 13472 | assert!( |
| 13473 | image_blob_keys(&db).await.is_empty(), |
| 13474 | "rows survived the cascade" |
| 13475 | ); |
| 13476 | for key in &keys { |
| 13477 | assert!( |
| 13478 | !common::blob_dir().join(key).exists(), |
| 13479 | "blob {key} survived the exam delete" |
| 13480 | ); |
| 13481 | } |
| 13482 | } |
| 13483 | |
| 13484 | /// The full life of a student's answer drawing: the student is the uploader |
| 13485 | /// (rasters only), the bytes sit behind the sitting wall (own GET 404 before an |
| 13486 | /// attempt, 200 after with the guard headers), the drawing meta rides both the |
| 13487 | /// student's own sitting view and the teacher grading sheet, the teacher reads |
| 13488 | /// the bytes via `/attempts/{user}/...` while an outsider cannot, a retake wipes |
| 13489 | /// the row *and* its on-disk blob, and deleting the exam takes rows + blobs. |
| 13490 | #[tokio::test] |
| 13491 | async fn student_answer_images_serve_and_cascade() { |
| 13492 | let (app, db) = app_and_db().await; |
| 13493 | let teacher = login_as(&app, &db, "ans_t", "teacher").await; |
| 13494 | let student = login(&app, "ans_s").await; |
| 13495 | let student_id = me_id(&app, &student).await; |
| 13496 | let outsider = login(&app, "ans_o").await; |
| 13497 | |
| 13498 | let mudur = login_as(&app, &db, "ans_m", "manager").await; |
| 13499 | let t = taught_under(&app, &mudur, &teacher, "science").await; |
| 13500 | let subject = create_subject(&app, &teacher, &t.course, "biology").await; |
| 13501 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 13502 | // Retakes allowed (max_attempts: 2) so the wipe path is reachable. |
| 13503 | let exam = scheduled_exam( |
| 13504 | &app, |
| 13505 | &teacher, |
| 13506 | &t.instance, |
| 13507 | json!({ "term": &t.term, "title": "cell quiz", "kind": "yazili", |
| 13508 | "mode": "open", "max_attempts": 2 }), |
| 13509 | ) |
| 13510 | .await; |
| 13511 | let question_body = create_question_body( |
| 13512 | &app, |
| 13513 | &teacher, |
| 13514 | &exam, |
| 13515 | &subject, |
| 13516 | json!({ "text": "Draw a cell.", "kind": "text", "points": 10 }), |
| 13517 | ) |
| 13518 | .await; |
| 13519 | let question = id_of(&question_body); |
| 13520 | |
| 13521 | let own = format!("/exams/{exam}/attempt/answers/{question}/image"); |
| 13522 | let png = b"png-drawing".as_slice(); |
| 13523 | |
| 13524 | // Before an attempt exists there is nothing to write into and no early |
| 13525 | // peek: the write path 404s (no attempt), the own-read 404s too. |
| 13526 | let (status, _) = post_image(&app, &student, &own, "image/png", png).await; |
| 13527 | assert_eq!(status, StatusCode::NOT_FOUND, "no attempt yet"); |
| 13528 | let (status, _, _) = |
| 13529 | common::send_raw(&app, "GET", &own, Some(&student), None, Vec::new()).await; |
| 13530 | assert_eq!( |
| 13531 | status, |
| 13532 | StatusCode::NOT_FOUND, |
| 13533 | "no early peek before the attempt" |
| 13534 | ); |
| 13535 | |
| 13536 | // The student sits the exam. |
| 13537 | let res = send( |
| 13538 | &app, |
| 13539 | "POST", |
| 13540 | &format!("/exams/{exam}/attempt"), |
| 13541 | Some(&student), |
| 13542 | None, |
| 13543 | ) |
| 13544 | .await; |
| 13545 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 13546 | |
| 13547 | // The raster wall holds on the student's own upload: SVG/PDF out, rasters in. |
| 13548 | let (status, body) = post_image(&app, &student, &own, "image/svg+xml", b"<svg/>").await; |
| 13549 | assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); |
| 13550 | let (status, body) = post_image(&app, &student, &own, "application/pdf", b"%PDF").await; |
| 13551 | assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); |
| 13552 | for ct in ["image/png", "image/jpeg", "image/webp"] { |
| 13553 | let (status, body) = post_image(&app, &student, &own, ct, png).await; |
| 13554 | assert_eq!(status, StatusCode::CREATED, "{ct}: {body}"); |
| 13555 | assert_eq!(body["content_type"], ct); |
| 13556 | assert_eq!(body["size"], png.len() as i64); |
| 13557 | } |
| 13558 | // Same (question, user) slot: three uploads collapse to one upserted row. |
| 13559 | assert_eq!( |
| 13560 | answer_image_blob_keys(&db).await.len(), |
| 13561 | 1, |
| 13562 | "own slot upserts, adds no row" |
| 13563 | ); |
| 13564 | |
| 13565 | // The student reads their own drawing back: 200, the guard headers, the |
| 13566 | // bytes, and the content type of the last upload (webp). |
| 13567 | let (status, headers, bytes) = |
| 13568 | common::send_raw(&app, "GET", &own, Some(&student), None, Vec::new()).await; |
| 13569 | assert_eq!(status, StatusCode::OK); |
| 13570 | assert_eq!(bytes, png); |
| 13571 | assert_eq!(headers["content-type"], "image/webp"); |
| 13572 | assert_eq!(headers["x-content-type-options"], "nosniff"); |
| 13573 | assert_eq!(headers["cache-control"], "private, no-store"); |
| 13574 | |
| 13575 | // An outsider (not enrolled) can't read the student's own route. |
| 13576 | let (status, _, _) = |
| 13577 | common::send_raw(&app, "GET", &own, Some(&outsider), None, Vec::new()).await; |
| 13578 | assert_eq!(status, StatusCode::FORBIDDEN, "outsiders can't peek"); |
| 13579 | |
| 13580 | // The drawing rides the student's own answer state — save the text answer |
| 13581 | // it accompanies, then the sitting view embeds the drawing meta. |
| 13582 | let res = send( |
| 13583 | &app, |
| 13584 | "POST", |
| 13585 | &format!("/exams/{exam}/attempt/answers"), |
| 13586 | Some(&student), |
| 13587 | Some(json!({ "question_id": question, "text": "a cell, drawn and described" })), |
| 13588 | ) |
| 13589 | .await; |
| 13590 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 13591 | let res = send( |
| 13592 | &app, |
| 13593 | "GET", |
| 13594 | &format!("/exams/{exam}/attempt/questions"), |
| 13595 | Some(&student), |
| 13596 | None, |
| 13597 | ) |
| 13598 | .await; |
| 13599 | assert_eq!(res.status, StatusCode::OK); |
| 13600 | assert_eq!( |
| 13601 | res.body[0]["answer"]["answer_image"]["content_type"], |
| 13602 | "image/webp" |
| 13603 | ); |
| 13604 | |
| 13605 | // The teacher grading sheet carries the drawing meta and serves the bytes |
| 13606 | // via the teacher route; the sheet row also exposes the flag. |
| 13607 | let teacher_bytes = format!("/exams/{exam}/attempts/{student_id}/answers/{question}/image"); |
| 13608 | let res = send( |
| 13609 | &app, |
| 13610 | "GET", |
| 13611 | &format!("/exams/{exam}/attempts/{student_id}/answers"), |
| 13612 | Some(&teacher), |
| 13613 | None, |
| 13614 | ) |
| 13615 | .await; |
| 13616 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 13617 | assert_eq!( |
| 13618 | res.body["answers"][0]["answer_image"]["content_type"], |
| 13619 | "image/webp" |
| 13620 | ); |
| 13621 | let (status, _, bytes) = common::send_raw( |
| 13622 | &app, |
| 13623 | "GET", |
| 13624 | &teacher_bytes, |
| 13625 | Some(&teacher), |
| 13626 | None, |
| 13627 | Vec::new(), |
| 13628 | ) |
| 13629 | .await; |
| 13630 | assert_eq!(status, StatusCode::OK); |
| 13631 | assert_eq!(bytes, png); |
| 13632 | // An outsider student can't read the teacher grading route (not a teacher). |
| 13633 | let (status, _, _) = common::send_raw( |
| 13634 | &app, |
| 13635 | "GET", |
| 13636 | &teacher_bytes, |
| 13637 | Some(&outsider), |
| 13638 | None, |
| 13639 | Vec::new(), |
| 13640 | ) |
| 13641 | .await; |
| 13642 | assert_eq!(status, StatusCode::FORBIDDEN); |
| 13643 | |
| 13644 | // A retake keeps the prior sitting's sheet — per-attempt history — so the |
| 13645 | // seq-1 answer-image row *and* its on-disk blob survive the new sitting. |
| 13646 | let pre = answer_image_blob_keys(&db).await; |
| 13647 | assert_eq!(pre.len(), 1); |
| 13648 | assert!(common::blob_dir().join(&pre[0]).exists()); |
| 13649 | let res = send( |
| 13650 | &app, |
| 13651 | "POST", |
| 13652 | &format!("/exams/{exam}/attempt/finish"), |
| 13653 | Some(&student), |
| 13654 | None, |
| 13655 | ) |
| 13656 | .await; |
| 13657 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 13658 | let res = send( |
| 13659 | &app, |
| 13660 | "POST", |
| 13661 | &format!("/exams/{exam}/attempt"), |
| 13662 | Some(&student), |
| 13663 | None, |
| 13664 | ) |
| 13665 | .await; |
| 13666 | assert_eq!(res.status, StatusCode::CREATED, "retake: {}", res.body); |
| 13667 | assert_eq!(res.body["attempt"], 2, "the retake is the second sitting"); |
| 13668 | assert_eq!( |
| 13669 | answer_image_blob_keys(&db).await.len(), |
| 13670 | 1, |
| 13671 | "the retake kept the prior sitting's answer-image row (history)" |
| 13672 | ); |
| 13673 | assert!( |
| 13674 | common::blob_dir().join(&pre[0]).exists(), |
| 13675 | "the retake kept the prior sitting's answer-image blob on disk" |
| 13676 | ); |
| 13677 | |
| 13678 | // A fresh drawing in the new sitting adds a second row alongside the kept |
| 13679 | // one; deleting the exam then sweeps every sitting's rows and blobs. |
| 13680 | let (status, _) = post_image(&app, &student, &own, "image/png", png).await; |
| 13681 | assert_eq!(status, StatusCode::CREATED); |
| 13682 | let keys = answer_image_blob_keys(&db).await; |
| 13683 | assert_eq!(keys.len(), 2, "seq-1 and seq-2 drawings coexist"); |
| 13684 | let res = send( |
| 13685 | &app, |
| 13686 | "DELETE", |
| 13687 | &format!("/exams/{exam}"), |
| 13688 | Some(&teacher), |
| 13689 | None, |
| 13690 | ) |
| 13691 | .await; |
| 13692 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 13693 | assert!( |
| 13694 | answer_image_blob_keys(&db).await.is_empty(), |
| 13695 | "answer-image rows survived the exam delete" |
| 13696 | ); |
| 13697 | for key in &keys { |
| 13698 | assert!( |
| 13699 | !common::blob_dir().join(key).exists(), |
| 13700 | "answer-image blob {key} survived the exam delete" |
| 13701 | ); |
| 13702 | } |
| 13703 | } |
| 13704 | |
| 13705 | /// A student who draws but types nothing still has their drawing surface in |
| 13706 | /// both the sitting view and the teacher grading sheet — the upload creates the |
| 13707 | /// backing (blank-text) answer row, since `answer_image` rides the answer payload. |
| 13708 | #[tokio::test] |
| 13709 | async fn answer_image_surfaces_for_a_drawing_only_answer() { |
| 13710 | let (app, db) = app_and_db().await; |
| 13711 | let teacher = login_as(&app, &db, "draw_t", "teacher").await; |
| 13712 | let student = login(&app, "draw_s").await; |
| 13713 | let student_id = me_id(&app, &student).await; |
| 13714 | |
| 13715 | let mudur = login_as(&app, &db, "draw_m", "manager").await; |
| 13716 | let t = taught_under(&app, &mudur, &teacher, "art").await; |
| 13717 | let subject = create_subject(&app, &teacher, &t.course, "drawing").await; |
| 13718 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 13719 | let exam = scheduled_exam( |
| 13720 | &app, |
| 13721 | &teacher, |
| 13722 | &t.instance, |
| 13723 | json!({ "term": &t.term, "title": "sketch", "kind": "yazili", "mode": "open" }), |
| 13724 | ) |
| 13725 | .await; |
| 13726 | let question_body = create_question_body( |
| 13727 | &app, |
| 13728 | &teacher, |
| 13729 | &exam, |
| 13730 | &subject, |
| 13731 | json!({ "text": "Draw a triangle.", "kind": "text", "points": 5 }), |
| 13732 | ) |
| 13733 | .await; |
| 13734 | let question = id_of(&question_body); |
| 13735 | |
| 13736 | // Sit, then upload a drawing WITHOUT ever saving a text answer. |
| 13737 | let res = send( |
| 13738 | &app, |
| 13739 | "POST", |
| 13740 | &format!("/exams/{exam}/attempt"), |
| 13741 | Some(&student), |
| 13742 | None, |
| 13743 | ) |
| 13744 | .await; |
| 13745 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 13746 | let own = format!("/exams/{exam}/attempt/answers/{question}/image"); |
| 13747 | let (status, body) = post_image(&app, &student, &own, "image/png", b"tri").await; |
| 13748 | assert_eq!(status, StatusCode::CREATED, "{body}"); |
| 13749 | |
| 13750 | // The sitting view carries the drawing meta with an empty typed answer. |
| 13751 | let res = send( |
| 13752 | &app, |
| 13753 | "GET", |
| 13754 | &format!("/exams/{exam}/attempt/questions"), |
| 13755 | Some(&student), |
| 13756 | None, |
| 13757 | ) |
| 13758 | .await; |
| 13759 | assert_eq!(res.status, StatusCode::OK); |
| 13760 | assert_eq!( |
| 13761 | res.body[0]["answer"]["answer_image"]["content_type"], |
| 13762 | "image/png" |
| 13763 | ); |
| 13764 | assert_eq!(res.body[0]["answer"]["text"], ""); |
| 13765 | |
| 13766 | // The teacher grading sheet shows it too. |
| 13767 | let res = send( |
| 13768 | &app, |
| 13769 | "GET", |
| 13770 | &format!("/exams/{exam}/attempts/{student_id}/answers"), |
| 13771 | Some(&teacher), |
| 13772 | None, |
| 13773 | ) |
| 13774 | .await; |
| 13775 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 13776 | assert_eq!( |
| 13777 | res.body["answers"][0]["answer_image"]["content_type"], |
| 13778 | "image/png" |
| 13779 | ); |
| 13780 | |
| 13781 | // Removing the drawing drops the blank answer row it created — the question |
| 13782 | // stops showing as answered rather than lingering as an empty text answer. |
| 13783 | let (status, _, _) = |
| 13784 | common::send_raw(&app, "DELETE", &own, Some(&student), None, Vec::new()).await; |
| 13785 | assert_eq!(status, StatusCode::NO_CONTENT); |
| 13786 | let res = send( |
| 13787 | &app, |
| 13788 | "GET", |
| 13789 | &format!("/exams/{exam}/attempt/questions"), |
| 13790 | Some(&student), |
| 13791 | None, |
| 13792 | ) |
| 13793 | .await; |
| 13794 | assert_eq!(res.status, StatusCode::OK); |
| 13795 | assert!( |
| 13796 | res.body[0]["answer"].is_null(), |
| 13797 | "blank answer row dropped with its drawing" |
| 13798 | ); |
| 13799 | } |
| 13800 | |
| 13801 | /// The authoring edits that reshape a question also groom its images — and |
| 13802 | /// **only** the pictures of options that are actually gone. Reordering the list |
| 13803 | /// and deleting one option leaves every surviving option's picture attached to |
| 13804 | /// *that option*, and leaves `correct` naming the option the author marked. |
| 13805 | /// This is the behaviour stable choice ids exist for: the images used to be |
| 13806 | /// keyed by position, so any edit that carried a `choices` key wiped all of |
| 13807 | /// them. |
| 13808 | #[tokio::test] |
| 13809 | async fn question_image_edits_follow_the_choices() { |
| 13810 | let (app, db) = app_and_db().await; |
| 13811 | let teacher = login_as(&app, &db, "imge_t", "teacher").await; |
| 13812 | let mudur = login_as(&app, &db, "imge_m", "manager").await; |
| 13813 | let t = taught_under(&app, &mudur, &teacher, "history").await; |
| 13814 | let subject = create_subject(&app, &teacher, &t.course, "eras").await; |
| 13815 | let exam = scheduled_exam( |
| 13816 | &app, |
| 13817 | &teacher, |
| 13818 | &t.instance, |
| 13819 | json!({ "term": &t.term, "title": "eras", "kind": "yazili", "mode": "open" }), |
| 13820 | ) |
| 13821 | .await; |
| 13822 | let question_body = create_question_body( |
| 13823 | &app, |
| 13824 | &teacher, |
| 13825 | &exam, |
| 13826 | &subject, |
| 13827 | json!({ "text": "Pick the era.", "kind": "choice", "points": 5, |
| 13828 | "choices": [{"id": "c0", "text": "Stone"}, {"id": "c1", "text": "Bronze"}, |
| 13829 | {"id": "c2", "text": "Iron"}], "correct": "c2" }), |
| 13830 | ) |
| 13831 | .await; |
| 13832 | let question = id_of(&question_body); |
| 13833 | let (stone, bronze, iron) = ( |
| 13834 | choice_of(&question_body, 0), |
| 13835 | choice_of(&question_body, 1), |
| 13836 | choice_of(&question_body, 2), |
| 13837 | ); |
| 13838 | let base = format!("/exams/{exam}/questions/{question}"); |
| 13839 | for (path, bytes) in [ |
| 13840 | (format!("{base}/image"), b"illustration".as_slice()), |
| 13841 | (format!("{base}/choices/{stone}/image"), b"stone".as_slice()), |
| 13842 | ( |
| 13843 | format!("{base}/choices/{bronze}/image"), |
| 13844 | b"bronze".as_slice(), |
| 13845 | ), |
| 13846 | (format!("{base}/choices/{iron}/image"), b"iron".as_slice()), |
| 13847 | ] { |
| 13848 | let (status, body) = post_image(&app, &teacher, &path, "image/png", bytes).await; |
| 13849 | assert_eq!(status, StatusCode::CREATED, "{body}"); |
| 13850 | } |
| 13851 | |
| 13852 | // A points-only PATCH touches no images. |
| 13853 | let res = send( |
| 13854 | &app, |
| 13855 | "PATCH", |
| 13856 | &base, |
| 13857 | Some(&teacher), |
| 13858 | Some(json!({ "points": 7 })), |
| 13859 | ) |
| 13860 | .await; |
| 13861 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 13862 | assert!(res.body["image"].is_object()); |
| 13863 | for slot in 0..3 { |
| 13864 | assert!(res.body["choice_images"][slot].is_object()); |
| 13865 | } |
| 13866 | assert_eq!(res.body["correct"], iron, "the answer key must not move"); |
| 13867 | |
| 13868 | // The edit this whole remodel exists for: reorder the list (Iron first), |
| 13869 | // rename one option, and drop Bronze entirely. |
| 13870 | let keys_before = image_blob_keys(&db).await; |
| 13871 | let res = send( |
| 13872 | &app, |
| 13873 | "PATCH", |
| 13874 | &base, |
| 13875 | Some(&teacher), |
| 13876 | Some(json!({ "choices": [ |
| 13877 | {"id": iron, "text": "Iron Age"}, |
| 13878 | {"id": stone, "text": "Stone"}, |
| 13879 | ], "correct": iron })), |
| 13880 | ) |
| 13881 | .await; |
| 13882 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 13883 | // The surviving options kept their identities, in their new order… |
| 13884 | assert_eq!(res.body["choices"][0]["id"], iron); |
| 13885 | assert_eq!(res.body["choices"][0]["text"], "Iron Age"); |
| 13886 | assert_eq!(res.body["choices"][1]["id"], stone); |
| 13887 | // …the answer key still names the option the author marked, though it moved |
| 13888 | // from position 2 to position 0… |
| 13889 | assert_eq!(res.body["correct"], iron, "correct must follow its option"); |
| 13890 | // …and each survivor kept *its own* picture, illustration included. |
| 13891 | assert!(res.body["image"].is_object(), "illustration must survive"); |
| 13892 | assert!( |
| 13893 | res.body["choice_images"][0].is_object(), |
| 13894 | "Iron kept its picture across the reorder" |
| 13895 | ); |
| 13896 | assert!( |
| 13897 | res.body["choice_images"][1].is_object(), |
| 13898 | "Stone kept its picture across the reorder" |
| 13899 | ); |
| 13900 | |
| 13901 | // Exactly one blob went: the removed option's. |
| 13902 | let keys_after = image_blob_keys(&db).await; |
| 13903 | assert_eq!( |
| 13904 | keys_after.len(), |
| 13905 | 3, |
| 13906 | "illustration + two surviving option pictures" |
| 13907 | ); |
| 13908 | let dropped: Vec<_> = keys_before |
| 13909 | .iter() |
| 13910 | .filter(|k| !keys_after.contains(k)) |
| 13911 | .collect(); |
| 13912 | assert_eq!(dropped.len(), 1, "only the removed option's blob may go"); |
| 13913 | for key in dropped { |
| 13914 | assert!( |
| 13915 | !common::blob_dir().join(key).exists(), |
| 13916 | "dropped option blob lingers" |
| 13917 | ); |
| 13918 | } |
| 13919 | |
| 13920 | // The remaining wipe path, now opt-in: a list of all-new options (no id |
| 13921 | // matches a stored one) is a genuinely new set, so every option picture |
| 13922 | // goes — and the illustration still stays. |
| 13923 | let res = send( |
| 13924 | &app, |
| 13925 | "PATCH", |
| 13926 | &base, |
| 13927 | Some(&teacher), |
| 13928 | Some(json!({ "choices": [{"id": "fresh-a", "text": "Iron"}, {"id": "fresh-b", "text": "Stone"}], |
| 13929 | "correct": "fresh-a" })), |
| 13930 | ) |
| 13931 | .await; |
| 13932 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 13933 | assert_ne!(res.body["choices"][0]["id"], iron, "a new option, not Iron"); |
| 13934 | assert_eq!( |
| 13935 | res.body["choice_images"], |
| 13936 | json!([null, null]), |
| 13937 | "an all-new option list keeps no pictures" |
| 13938 | ); |
| 13939 | assert!(res.body["image"].is_object(), "illustration must survive"); |
| 13940 | assert_eq!(image_blob_keys(&db).await.len(), 1); |
| 13941 | |
| 13942 | // Explicit image DELETE: 204 once, 404 after, blob gone. |
| 13943 | let fresh = choice_of(&res.body, 0); |
| 13944 | let (status, _) = post_image( |
| 13945 | &app, |
| 13946 | &teacher, |
| 13947 | &format!("{base}/choices/{fresh}/image"), |
| 13948 | "image/gif", |
| 13949 | b"gif", |
| 13950 | ) |
| 13951 | .await; |
| 13952 | assert_eq!(status, StatusCode::CREATED); |
| 13953 | let res = send( |
| 13954 | &app, |
| 13955 | "DELETE", |
| 13956 | &format!("{base}/choices/{fresh}/image"), |
| 13957 | Some(&teacher), |
| 13958 | None, |
| 13959 | ) |
| 13960 | .await; |
| 13961 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 13962 | let res = send( |
| 13963 | &app, |
| 13964 | "DELETE", |
| 13965 | &format!("{base}/choices/{fresh}/image"), |
| 13966 | Some(&teacher), |
| 13967 | None, |
| 13968 | ) |
| 13969 | .await; |
| 13970 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 13971 | |
| 13972 | // Deleting the question sweeps its remaining image rows and blobs. |
| 13973 | let keys = image_blob_keys(&db).await; |
| 13974 | assert_eq!(keys.len(), 1); |
| 13975 | let res = send(&app, "DELETE", &base, Some(&teacher), None).await; |
| 13976 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 13977 | assert!(image_blob_keys(&db).await.is_empty()); |
| 13978 | for key in &keys { |
| 13979 | assert!( |
| 13980 | !common::blob_dir().join(key).exists(), |
| 13981 | "blob {key} survived the question delete" |
| 13982 | ); |
| 13983 | } |
| 13984 | } |
| 13985 | |
| 13986 | // --- exam drafts --------------------------------------------------------- |
| 13987 | |
| 13988 | #[tokio::test] |
| 13989 | async fn draft_exams_hide_from_students_until_published() { |
| 13990 | let (app, db) = app_and_db().await; |
| 13991 | let teacher = login_as(&app, &db, "draft_t", "teacher").await; |
| 13992 | let student = login(&app, "draft_s").await; |
| 13993 | let student_id = me_id(&app, &student).await; |
| 13994 | let mudur = login_as(&app, &db, "mudur_of_drafts", "manager").await; |
| 13995 | let t = taught_under(&app, &mudur, &teacher, "history").await; |
| 13996 | // The student's seat is the şube's: that is what puts them in the instance |
| 13997 | // the section teaches, and what the exam lists resolve against. |
| 13998 | add_member(&app, &mudur, &t.class, &student_id).await; |
| 13999 | |
| 14000 | // Saved as a draft: an open (sittable-were-it-published) exam. |
| 14001 | let res = create_exam_with( |
| 14002 | &app, |
| 14003 | &teacher, |
| 14004 | &t.instance, |
| 14005 | json!({ "title": "wip final", "kind": "yazili", "term": t.term, "mode": "open", "draft": true }), |
| 14006 | ) |
| 14007 | .await; |
| 14008 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 14009 | assert_eq!(res.body["draft"], true); |
| 14010 | let exam = id_of(&res.body); |
| 14011 | |
| 14012 | // The manager sees it everywhere, flagged. |
| 14013 | let mine = send(&app, "GET", "/exams", Some(&teacher), None).await; |
| 14014 | assert_eq!(common::items(&mine.body).len(), 1); |
| 14015 | assert_eq!(common::items(&mine.body)[0]["draft"], true); |
| 14016 | |
| 14017 | // The enrolled student sees nothing: not in either list, a 404 on direct |
| 14018 | // read, and a 404 (not a telltale 409) on sitting. |
| 14019 | let listed = send(&app, "GET", "/exams", Some(&student), None).await; |
| 14020 | assert_eq!(common::items(&listed.body).len(), 0); |
| 14021 | let in_course = send( |
| 14022 | &app, |
| 14023 | "GET", |
| 14024 | &format!("/instances/{}/exams", t.instance), |
| 14025 | Some(&student), |
| 14026 | None, |
| 14027 | ) |
| 14028 | .await; |
| 14029 | assert_eq!(common::items(&in_course.body).len(), 0); |
| 14030 | for (method, path) in [ |
| 14031 | ("GET", format!("/exams/{exam}")), |
| 14032 | ("POST", format!("/exams/{exam}/attempt")), |
| 14033 | ] { |
| 14034 | let res = send(&app, method, &path, Some(&student), None).await; |
| 14035 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{method} {path}"); |
| 14036 | } |
| 14037 | |
| 14038 | // Grading a draft is refused — a mark must never point at a hidden exam. |
| 14039 | let res = send( |
| 14040 | &app, |
| 14041 | "POST", |
| 14042 | &format!("/exams/{exam}/results"), |
| 14043 | Some(&teacher), |
| 14044 | Some(json!({ "mark": 90, "user_id": student_id })), |
| 14045 | ) |
| 14046 | .await; |
| 14047 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 14048 | |
| 14049 | // Publish. The student now sees and sits it. |
| 14050 | let res = send( |
| 14051 | &app, |
| 14052 | "PATCH", |
| 14053 | &format!("/exams/{exam}"), |
| 14054 | Some(&teacher), |
| 14055 | Some(json!({ "draft": false })), |
| 14056 | ) |
| 14057 | .await; |
| 14058 | assert_eq!(res.status, StatusCode::OK); |
| 14059 | assert_eq!(res.body["draft"], false); |
| 14060 | let listed = send(&app, "GET", "/exams", Some(&student), None).await; |
| 14061 | assert_eq!(common::items(&listed.body).len(), 1); |
| 14062 | let res = send( |
| 14063 | &app, |
| 14064 | "POST", |
| 14065 | &format!("/exams/{exam}/attempt"), |
| 14066 | Some(&student), |
| 14067 | None, |
| 14068 | ) |
| 14069 | .await; |
| 14070 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 14071 | |
| 14072 | // Once sat, the exam can't be pulled back into hiding. |
| 14073 | let res = send( |
| 14074 | &app, |
| 14075 | "PATCH", |
| 14076 | &format!("/exams/{exam}"), |
| 14077 | Some(&teacher), |
| 14078 | Some(json!({ "draft": true })), |
| 14079 | ) |
| 14080 | .await; |
| 14081 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 14082 | } |
| 14083 | |
| 14084 | #[tokio::test] |
| 14085 | async fn results_alone_also_freeze_re_drafting() { |
| 14086 | let (app, db) = app_and_db().await; |
| 14087 | let teacher = login_as(&app, &db, "redraft_t", "teacher").await; |
| 14088 | let student = login(&app, "redraft_s").await; |
| 14089 | let student_id = me_id(&app, &student).await; |
| 14090 | let mudur = login_as(&app, &db, "redraft_m", "manager").await; |
| 14091 | let t = taught_under(&app, &mudur, &teacher, "geo").await; |
| 14092 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 14093 | |
| 14094 | // A published offline-graded exam (no mode, no attempts — marks by hand). |
| 14095 | let exam = create_exam( |
| 14096 | &app, |
| 14097 | &teacher, |
| 14098 | &t.instance, |
| 14099 | &t.term, |
| 14100 | "field trip report", |
| 14101 | "yazili", |
| 14102 | ) |
| 14103 | .await; |
| 14104 | let res = send( |
| 14105 | &app, |
| 14106 | "POST", |
| 14107 | &format!("/exams/{exam}/results"), |
| 14108 | Some(&teacher), |
| 14109 | Some(json!({ "mark": 75, "user_id": student_id })), |
| 14110 | ) |
| 14111 | .await; |
| 14112 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14113 | |
| 14114 | // No attempts exist, but the graded result freezes re-drafting too. |
| 14115 | let res = send( |
| 14116 | &app, |
| 14117 | "PATCH", |
| 14118 | &format!("/exams/{exam}"), |
| 14119 | Some(&teacher), |
| 14120 | Some(json!({ "draft": true })), |
| 14121 | ) |
| 14122 | .await; |
| 14123 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 14124 | |
| 14125 | // Ungraded siblings still re-draft freely. |
| 14126 | let other = create_exam(&app, &teacher, &t.instance, &t.term, "map quiz", "sozlu").await; |
| 14127 | let res = send( |
| 14128 | &app, |
| 14129 | "PATCH", |
| 14130 | &format!("/exams/{other}"), |
| 14131 | Some(&teacher), |
| 14132 | Some(json!({ "draft": true })), |
| 14133 | ) |
| 14134 | .await; |
| 14135 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14136 | assert_eq!(res.body["draft"], true); |
| 14137 | } |
| 14138 | |
| 14139 | // --- parent role --------------------------------------------------------- |
| 14140 | |
| 14141 | /// The tie lifecycle: admin-only, role-checked on both ends, idempotent, and |
| 14142 | /// symmetric between the admin listing and the parent's own `/me/students`. |
| 14143 | #[tokio::test] |
| 14144 | async fn parent_links_are_admin_managed_and_role_checked() { |
| 14145 | let (app, db) = app_and_db().await; |
| 14146 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 14147 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 14148 | let parent = login_as(&app, &db, "mom", "parent").await; |
| 14149 | let parent_id = me_id(&app, &parent).await; |
| 14150 | let ali = login(&app, "ali").await; |
| 14151 | let ali_id = me_id(&app, &ali).await; |
| 14152 | let teacher_id = me_id(&app, &teacher).await; |
| 14153 | |
| 14154 | // Only an admin ties. |
| 14155 | let res = send( |
| 14156 | &app, |
| 14157 | "POST", |
| 14158 | &format!("/users/{parent_id}/students"), |
| 14159 | Some(&teacher), |
| 14160 | Some(json!({ "user_id": ali_id })), |
| 14161 | ) |
| 14162 | .await; |
| 14163 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 14164 | |
| 14165 | // Both ends are role-checked: the target must be a parent… |
| 14166 | let res = send( |
| 14167 | &app, |
| 14168 | "POST", |
| 14169 | &format!("/users/{teacher_id}/students"), |
| 14170 | Some(&admin), |
| 14171 | Some(json!({ "user_id": ali_id })), |
| 14172 | ) |
| 14173 | .await; |
| 14174 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 14175 | // …the student must be a student… |
| 14176 | let res = send( |
| 14177 | &app, |
| 14178 | "POST", |
| 14179 | &format!("/users/{parent_id}/students"), |
| 14180 | Some(&admin), |
| 14181 | Some(json!({ "user_id": teacher_id })), |
| 14182 | ) |
| 14183 | .await; |
| 14184 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 14185 | // …and both must exist. |
| 14186 | let res = send( |
| 14187 | &app, |
| 14188 | "POST", |
| 14189 | &format!("/users/{parent_id}/students"), |
| 14190 | Some(&admin), |
| 14191 | Some(json!({ "user_id": common::ABSENT_ID })), |
| 14192 | ) |
| 14193 | .await; |
| 14194 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 14195 | let res = send( |
| 14196 | &app, |
| 14197 | "POST", |
| 14198 | &format!("/users/{}/students", common::ABSENT_ID), |
| 14199 | Some(&admin), |
| 14200 | Some(json!({ "user_id": ali_id })), |
| 14201 | ) |
| 14202 | .await; |
| 14203 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 14204 | |
| 14205 | // A valid tie lands, and linking again is a no-op returning the same tie. |
| 14206 | for _ in 0..2 { |
| 14207 | let res = send( |
| 14208 | &app, |
| 14209 | "POST", |
| 14210 | &format!("/users/{parent_id}/students"), |
| 14211 | Some(&admin), |
| 14212 | Some(json!({ "user_id": ali_id })), |
| 14213 | ) |
| 14214 | .await; |
| 14215 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14216 | assert_eq!(res.body["student"]["id"], json!(ali_id)); |
| 14217 | assert_eq!(res.body["parent"]["id"], json!(parent_id)); |
| 14218 | } |
| 14219 | |
| 14220 | // Admin listing and the parent's own listing agree. |
| 14221 | let res = send( |
| 14222 | &app, |
| 14223 | "GET", |
| 14224 | &format!("/users/{parent_id}/students"), |
| 14225 | Some(&admin), |
| 14226 | None, |
| 14227 | ) |
| 14228 | .await; |
| 14229 | assert_eq!(res.status, StatusCode::OK); |
| 14230 | assert_eq!(common::total(&res.body), 1); |
| 14231 | let res = send(&app, "GET", "/users/me/students", Some(&parent), None).await; |
| 14232 | assert_eq!(res.status, StatusCode::OK); |
| 14233 | assert_eq!(common::items(&res.body)[0]["id"], json!(ali_id)); |
| 14234 | // /me/students is the parent's view — everyone else is refused. |
| 14235 | let res = send(&app, "GET", "/users/me/students", Some(&ali), None).await; |
| 14236 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 14237 | |
| 14238 | // Untie: once, then the tie is gone. |
| 14239 | let res = send( |
| 14240 | &app, |
| 14241 | "DELETE", |
| 14242 | &format!("/users/{parent_id}/students/{ali_id}"), |
| 14243 | Some(&admin), |
| 14244 | None, |
| 14245 | ) |
| 14246 | .await; |
| 14247 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 14248 | let res = send( |
| 14249 | &app, |
| 14250 | "DELETE", |
| 14251 | &format!("/users/{parent_id}/students/{ali_id}"), |
| 14252 | Some(&admin), |
| 14253 | None, |
| 14254 | ) |
| 14255 | .await; |
| 14256 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 14257 | } |
| 14258 | |
| 14259 | /// The tie is the parent's whole power: linked students' reports open up (in |
| 14260 | /// full — no course narrowing), everyone else's stay walled, and every write |
| 14261 | /// a parent might try is refused. |
| 14262 | #[tokio::test] |
| 14263 | async fn parent_observes_linked_students_and_nothing_else() { |
| 14264 | let (app, db) = app_and_db().await; |
| 14265 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 14266 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 14267 | let parent = login_as(&app, &db, "mom", "parent").await; |
| 14268 | let parent_id = me_id(&app, &parent).await; |
| 14269 | let ali = login(&app, "ali").await; |
| 14270 | let ali_id = me_id(&app, &ali).await; |
| 14271 | let bob = login(&app, "bob").await; |
| 14272 | let bob_id = me_id(&app, &bob).await; |
| 14273 | |
| 14274 | // ali gets a graded exam in a şube the parent has nothing to do with. |
| 14275 | let t = taught_under(&app, &admin, &teacher, "algebra").await; |
| 14276 | add_member(&app, &admin, &t.class, &ali_id).await; |
| 14277 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "yazili").await; |
| 14278 | let res = send( |
| 14279 | &app, |
| 14280 | "POST", |
| 14281 | &format!("/exams/{exam}/results"), |
| 14282 | Some(&teacher), |
| 14283 | Some(json!({ "mark": 70, "user_id": ali_id })), |
| 14284 | ) |
| 14285 | .await; |
| 14286 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14287 | |
| 14288 | let res = send( |
| 14289 | &app, |
| 14290 | "POST", |
| 14291 | &format!("/users/{parent_id}/students"), |
| 14292 | Some(&admin), |
| 14293 | Some(json!({ "user_id": ali_id })), |
| 14294 | ) |
| 14295 | .await; |
| 14296 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14297 | |
| 14298 | // Linked student: all three reports open, and the mark report is FULL — |
| 14299 | // the parent manages no courses, so narrowing would blank it. |
| 14300 | let res = send( |
| 14301 | &app, |
| 14302 | "GET", |
| 14303 | &format!("/marks/{ali_id}"), |
| 14304 | Some(&parent), |
| 14305 | None, |
| 14306 | ) |
| 14307 | .await; |
| 14308 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14309 | assert_eq!(res.body["courses"][0]["results"][0]["mark"], 70); |
| 14310 | let res = send( |
| 14311 | &app, |
| 14312 | "GET", |
| 14313 | &format!("/attendance/{ali_id}"), |
| 14314 | Some(&parent), |
| 14315 | None, |
| 14316 | ) |
| 14317 | .await; |
| 14318 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14319 | let res = send( |
| 14320 | &app, |
| 14321 | "GET", |
| 14322 | &format!("/pomodoro/{ali_id}"), |
| 14323 | Some(&parent), |
| 14324 | None, |
| 14325 | ) |
| 14326 | .await; |
| 14327 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14328 | |
| 14329 | // Unlinked student: every report stays walled. |
| 14330 | for uri in [ |
| 14331 | format!("/marks/{bob_id}"), |
| 14332 | format!("/attendance/{bob_id}"), |
| 14333 | format!("/pomodoro/{bob_id}"), |
| 14334 | ] { |
| 14335 | let res = send(&app, "GET", &uri, Some(&parent), None).await; |
| 14336 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri} must stay walled"); |
| 14337 | } |
| 14338 | |
| 14339 | // A parent writes nothing: not a student (pomodoro, sitting), not staff |
| 14340 | // (courses, grading, search), and the tie grants no write-through. |
| 14341 | let res = send(&app, "POST", "/pomodoro/start", Some(&parent), None).await; |
| 14342 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 14343 | let res = send( |
| 14344 | &app, |
| 14345 | "POST", |
| 14346 | "/courses", |
| 14347 | Some(&parent), |
| 14348 | Some(json!({ "title": "sneaky" })), |
| 14349 | ) |
| 14350 | .await; |
| 14351 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 14352 | // A sittable exam (the modeless `exam` would 409 as unsittable before any |
| 14353 | // role question arises): the student-only wall answers first. |
| 14354 | let sittable = create_exam_with( |
| 14355 | &app, |
| 14356 | &teacher, |
| 14357 | &t.instance, |
| 14358 | json!({ "term": &t.term, "title": "anytime", "kind": "sozlu", "mode": "open" }), |
| 14359 | ) |
| 14360 | .await; |
| 14361 | assert_eq!(sittable.status, StatusCode::CREATED, "{}", sittable.body); |
| 14362 | let res = send( |
| 14363 | &app, |
| 14364 | "POST", |
| 14365 | &format!("/exams/{}/attempt", id_of(&sittable.body)), |
| 14366 | Some(&parent), |
| 14367 | None, |
| 14368 | ) |
| 14369 | .await; |
| 14370 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 14371 | // Search is open to a parent since #24, but only onto staff: the linked |
| 14372 | // student is a match by name and still must not come back. |
| 14373 | let res = send(&app, "GET", "/users/search?q=ali", Some(&parent), None).await; |
| 14374 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14375 | assert_eq!(common::items(&res.body).len(), 0, "{}", res.body); |
| 14376 | assert_eq!(res.body["total"], 0); |
| 14377 | } |
| 14378 | |
| 14379 | /// A role change off either end of a tie sweeps it, exactly like promotion |
| 14380 | /// sweeps enrollments — no dead read grants left behind. |
| 14381 | #[tokio::test] |
| 14382 | async fn role_change_sweeps_parent_links() { |
| 14383 | let (app, db) = app_and_db().await; |
| 14384 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 14385 | let parent = login_as(&app, &db, "mom", "parent").await; |
| 14386 | let parent_id = me_id(&app, &parent).await; |
| 14387 | let ali = login(&app, "ali").await; |
| 14388 | let ali_id = me_id(&app, &ali).await; |
| 14389 | |
| 14390 | let res = send( |
| 14391 | &app, |
| 14392 | "POST", |
| 14393 | &format!("/users/{parent_id}/students"), |
| 14394 | Some(&admin), |
| 14395 | Some(json!({ "user_id": ali_id })), |
| 14396 | ) |
| 14397 | .await; |
| 14398 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14399 | |
| 14400 | // The student side leaves the student role: the tie dies with it. |
| 14401 | let res = send( |
| 14402 | &app, |
| 14403 | "PATCH", |
| 14404 | &format!("/users/{ali_id}/role"), |
| 14405 | Some(&admin), |
| 14406 | Some(json!({ "role": "teacher" })), |
| 14407 | ) |
| 14408 | .await; |
| 14409 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14410 | let res = send(&app, "GET", "/users/me/students", Some(&parent), None).await; |
| 14411 | assert_eq!(common::total(&res.body), 0, "tie must die with the role"); |
| 14412 | let res = send( |
| 14413 | &app, |
| 14414 | "GET", |
| 14415 | &format!("/marks/{ali_id}"), |
| 14416 | Some(&parent), |
| 14417 | None, |
| 14418 | ) |
| 14419 | .await; |
| 14420 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 14421 | |
| 14422 | // The parent side leaves the parent role: its remaining ties die too. |
| 14423 | let bob = login(&app, "bob").await; |
| 14424 | let bob_id = me_id(&app, &bob).await; |
| 14425 | let res = send( |
| 14426 | &app, |
| 14427 | "POST", |
| 14428 | &format!("/users/{parent_id}/students"), |
| 14429 | Some(&admin), |
| 14430 | Some(json!({ "user_id": bob_id })), |
| 14431 | ) |
| 14432 | .await; |
| 14433 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14434 | let res = send( |
| 14435 | &app, |
| 14436 | "PATCH", |
| 14437 | &format!("/users/{parent_id}/role"), |
| 14438 | Some(&admin), |
| 14439 | Some(json!({ "role": "student" })), |
| 14440 | ) |
| 14441 | .await; |
| 14442 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14443 | |
| 14444 | // Really deleted, not merely hidden by the role checks. |
| 14445 | let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM parent_link") |
| 14446 | .fetch_one(&db) |
| 14447 | .await |
| 14448 | .expect("count parent links"); |
| 14449 | assert_eq!(rows, 0, "parent_link rows deleted from the DB"); |
| 14450 | } |
| 14451 | |
| 14452 | // --- messages ------------------------------------------------------------ |
| 14453 | |
| 14454 | #[tokio::test] |
| 14455 | async fn messages_flow_through_folders_per_side() { |
| 14456 | let (app, db) = app_and_db().await; |
| 14457 | let ali = login(&app, "ali").await; // student |
| 14458 | let hoca = login_as(&app, &db, "hoca", "teacher").await; |
| 14459 | let hoca_id = me_id(&app, &hoca).await; |
| 14460 | |
| 14461 | // Send lands in the recipient's inbox unread; the sender holds a `sent` copy. |
| 14462 | let res = send( |
| 14463 | &app, |
| 14464 | "POST", |
| 14465 | "/messages", |
| 14466 | Some(&ali), |
| 14467 | Some(json!({ "recipient_id": hoca_id, "subject": "etüt", "body": "10 dk gecikebilirim", "label": " Etüt " })), |
| 14468 | ) |
| 14469 | .await; |
| 14470 | assert_eq!(res.status, StatusCode::CREATED); |
| 14471 | assert_eq!(res.body["folder"], "sent"); |
| 14472 | assert_eq!(res.body["read"], false); |
| 14473 | assert_eq!(res.body["label"], "Etüt", "label stored trimmed"); |
| 14474 | assert_eq!(res.body["sender"]["username"], "ali"); |
| 14475 | assert_eq!(res.body["sender_role"], "student"); |
| 14476 | assert_eq!(res.body["recipient_role"], "teacher"); |
| 14477 | let msg_id = id_of(&res.body); |
| 14478 | |
| 14479 | // Recipient's inbox shows it; their copy says `inbox`. |
| 14480 | let inbox = send(&app, "GET", "/messages", Some(&hoca), None).await; |
| 14481 | let items = common::items(&inbox.body); |
| 14482 | assert_eq!(items.len(), 1); |
| 14483 | assert_eq!(items[0]["folder"], "inbox"); |
| 14484 | assert_eq!(items[0]["subject"], "etüt"); |
| 14485 | |
| 14486 | // Only the recipient flips the read flag; the sender sees the receipt. |
| 14487 | let res = send( |
| 14488 | &app, |
| 14489 | "PATCH", |
| 14490 | &format!("/messages/{msg_id}"), |
| 14491 | Some(&ali), |
| 14492 | Some(json!({ "read": true })), |
| 14493 | ) |
| 14494 | .await; |
| 14495 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 14496 | // `?read=` narrows; `total` on the filtered view is the unread badge. |
| 14497 | let unread = send( |
| 14498 | &app, |
| 14499 | "GET", |
| 14500 | "/messages?folder=inbox&read=false&limit=1", |
| 14501 | Some(&hoca), |
| 14502 | None, |
| 14503 | ) |
| 14504 | .await; |
| 14505 | assert_eq!(unread.body["total"], 1); |
| 14506 | let res = send( |
| 14507 | &app, |
| 14508 | "PATCH", |
| 14509 | &format!("/messages/{msg_id}"), |
| 14510 | Some(&hoca), |
| 14511 | Some(json!({ "read": true })), |
| 14512 | ) |
| 14513 | .await; |
| 14514 | assert_eq!(res.status, StatusCode::OK); |
| 14515 | let unread = send( |
| 14516 | &app, |
| 14517 | "GET", |
| 14518 | "/messages?folder=inbox&read=false&limit=1", |
| 14519 | Some(&hoca), |
| 14520 | None, |
| 14521 | ) |
| 14522 | .await; |
| 14523 | assert_eq!(unread.body["total"], 0); |
| 14524 | let sent = send(&app, "GET", "/messages?folder=sent", Some(&ali), None).await; |
| 14525 | assert_eq!(common::items(&sent.body)[0]["read"], true); |
| 14526 | |
| 14527 | // Each side only moves through its own folders. |
| 14528 | let res = send( |
| 14529 | &app, |
| 14530 | "PATCH", |
| 14531 | &format!("/messages/{msg_id}"), |
| 14532 | Some(&hoca), |
| 14533 | Some(json!({ "folder": "sent" })), |
| 14534 | ) |
| 14535 | .await; |
| 14536 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 14537 | let res = send( |
| 14538 | &app, |
| 14539 | "PATCH", |
| 14540 | &format!("/messages/{msg_id}"), |
| 14541 | Some(&hoca), |
| 14542 | Some(json!({ "folder": "archive" })), |
| 14543 | ) |
| 14544 | .await; |
| 14545 | assert_eq!(res.status, StatusCode::OK); |
| 14546 | let inbox = send(&app, "GET", "/messages", Some(&hoca), None).await; |
| 14547 | assert_eq!(common::items(&inbox.body).len(), 0); |
| 14548 | let archive = send(&app, "GET", "/messages?folder=archive", Some(&hoca), None).await; |
| 14549 | assert_eq!(common::items(&archive.body).len(), 1); |
| 14550 | |
| 14551 | // Permanent delete only from the trash; it never touches the other copy. |
| 14552 | let res = send( |
| 14553 | &app, |
| 14554 | "DELETE", |
| 14555 | &format!("/messages/{msg_id}"), |
| 14556 | Some(&hoca), |
| 14557 | None, |
| 14558 | ) |
| 14559 | .await; |
| 14560 | assert_eq!(res.status, StatusCode::CONFLICT); |
| 14561 | send( |
| 14562 | &app, |
| 14563 | "PATCH", |
| 14564 | &format!("/messages/{msg_id}"), |
| 14565 | Some(&hoca), |
| 14566 | Some(json!({ "folder": "trash" })), |
| 14567 | ) |
| 14568 | .await; |
| 14569 | let trash = send(&app, "GET", "/messages?folder=trash", Some(&hoca), None).await; |
| 14570 | assert_eq!(common::items(&trash.body).len(), 1); |
| 14571 | let res = send( |
| 14572 | &app, |
| 14573 | "DELETE", |
| 14574 | &format!("/messages/{msg_id}"), |
| 14575 | Some(&hoca), |
| 14576 | None, |
| 14577 | ) |
| 14578 | .await; |
| 14579 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 14580 | let trash = send(&app, "GET", "/messages?folder=trash", Some(&hoca), None).await; |
| 14581 | assert_eq!(common::items(&trash.body).len(), 0); |
| 14582 | // Deleted side is no longer a party at all. |
| 14583 | let res = send( |
| 14584 | &app, |
| 14585 | "PATCH", |
| 14586 | &format!("/messages/{msg_id}"), |
| 14587 | Some(&hoca), |
| 14588 | Some(json!({ "folder": "inbox" })), |
| 14589 | ) |
| 14590 | .await; |
| 14591 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 14592 | // Sender still holds their copy… |
| 14593 | let sent = send(&app, "GET", "/messages?folder=sent", Some(&ali), None).await; |
| 14594 | assert_eq!(common::items(&sent.body).len(), 1); |
| 14595 | |
| 14596 | // …and once the sender trashes + deletes too, the row itself is gone. |
| 14597 | send( |
| 14598 | &app, |
| 14599 | "PATCH", |
| 14600 | &format!("/messages/{msg_id}"), |
| 14601 | Some(&ali), |
| 14602 | Some(json!({ "folder": "trash" })), |
| 14603 | ) |
| 14604 | .await; |
| 14605 | let res = send( |
| 14606 | &app, |
| 14607 | "DELETE", |
| 14608 | &format!("/messages/{msg_id}"), |
| 14609 | Some(&ali), |
| 14610 | None, |
| 14611 | ) |
| 14612 | .await; |
| 14613 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 14614 | let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM message") |
| 14615 | .fetch_one(&db) |
| 14616 | .await |
| 14617 | .expect("count messages"); |
| 14618 | assert_eq!(rows, 0, "both-sides-deleted row is removed"); |
| 14619 | } |
| 14620 | |
| 14621 | /// A filed copy remembers the folder it left, so restoring lands where it |
| 14622 | /// came from instead of always in the inbox. |
| 14623 | #[tokio::test] |
| 14624 | async fn messages_remember_the_folder_a_filed_copy_came_from() { |
| 14625 | let (app, db) = app_and_db().await; |
| 14626 | let ali = login(&app, "ali").await; // student |
| 14627 | let hoca = login_as(&app, &db, "hoca", "teacher").await; |
| 14628 | let hoca_id = me_id(&app, &hoca).await; |
| 14629 | |
| 14630 | let res = send( |
| 14631 | &app, |
| 14632 | "POST", |
| 14633 | "/messages", |
| 14634 | Some(&ali), |
| 14635 | Some(json!({ "recipient_id": hoca_id, "subject": "etüt" })), |
| 14636 | ) |
| 14637 | .await; |
| 14638 | let msg_id = res.body["id"].as_str().expect("message id").to_string(); |
| 14639 | assert!( |
| 14640 | res.body["previous_folder"].is_null(), |
| 14641 | "a home copy has none" |
| 14642 | ); |
| 14643 | |
| 14644 | let file = |actor: &'static str, folder: &'static str| { |
| 14645 | let app = app.clone(); |
| 14646 | let (ali, hoca) = (ali.clone(), hoca.clone()); |
| 14647 | let msg_id = msg_id.clone(); |
| 14648 | async move { |
| 14649 | let session = if actor == "ali" { ali } else { hoca }; |
| 14650 | let res = send( |
| 14651 | &app, |
| 14652 | "PATCH", |
| 14653 | &format!("/messages/{msg_id}"), |
| 14654 | Some(&session), |
| 14655 | Some(json!({ "folder": folder })), |
| 14656 | ) |
| 14657 | .await; |
| 14658 | assert_eq!(res.status, StatusCode::OK, "move to {folder}"); |
| 14659 | res.body["previous_folder"].clone() |
| 14660 | } |
| 14661 | }; |
| 14662 | |
| 14663 | // inbox → archive → trash walks the memory one hop at a time. |
| 14664 | assert_eq!(file("hoca", "archive").await, json!("inbox")); |
| 14665 | assert_eq!(file("hoca", "trash").await, json!("archive")); |
| 14666 | // Restoring to the remembered folder puts the copy back there — with no |
| 14667 | // memory of its own, since it came out of the trash and the trash is |
| 14668 | // never a restore target. It falls back to the home folder. |
| 14669 | assert!(file("hoca", "archive").await.is_null()); |
| 14670 | let archive = send(&app, "GET", "/messages?folder=archive", Some(&hoca), None).await; |
| 14671 | assert_eq!(common::items(&archive.body).len(), 1); |
| 14672 | // Back home clears the stamp for good. |
| 14673 | assert!(file("hoca", "inbox").await.is_null()); |
| 14674 | |
| 14675 | // A no-op move keeps the memory it already had. |
| 14676 | assert_eq!(file("hoca", "archive").await, json!("inbox")); |
| 14677 | assert_eq!(file("hoca", "archive").await, json!("inbox")); |
| 14678 | |
| 14679 | // The sender's side has only one home, so its trash always points at it. |
| 14680 | assert_eq!(file("ali", "trash").await, json!("sent")); |
| 14681 | // The two sides' memories are independent. |
| 14682 | let trash = send(&app, "GET", "/messages?folder=trash", Some(&ali), None).await; |
| 14683 | assert_eq!(common::items(&trash.body)[0]["previous_folder"], "sent"); |
| 14684 | let archive = send(&app, "GET", "/messages?folder=archive", Some(&hoca), None).await; |
| 14685 | assert_eq!(common::items(&archive.body)[0]["previous_folder"], "inbox"); |
| 14686 | |
| 14687 | // Deleting drops the stamp with the rest of that side's copy. |
| 14688 | let res = send( |
| 14689 | &app, |
| 14690 | "DELETE", |
| 14691 | &format!("/messages/{msg_id}"), |
| 14692 | Some(&ali), |
| 14693 | None, |
| 14694 | ) |
| 14695 | .await; |
| 14696 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 14697 | let origins: Vec<Option<String>> = sqlx::query_scalar("SELECT sender_origin FROM message") |
| 14698 | .fetch_all(&db) |
| 14699 | .await |
| 14700 | .expect("read origins"); |
| 14701 | assert_eq!(origins, vec![None], "the deleted side keeps no origin"); |
| 14702 | } |
| 14703 | |
| 14704 | /// Issue #23: messaging is upward only below staff. A student or parent writes |
| 14705 | /// to teacher+ and to nobody else; staff write in any direction. |
| 14706 | #[tokio::test] |
| 14707 | async fn messages_from_below_staff_go_upward_only() { |
| 14708 | let (app, db) = app_and_db().await; |
| 14709 | let ali = login(&app, "ali").await; // student |
| 14710 | let ali_id = me_id(&app, &ali).await; |
| 14711 | let veli = login(&app, "veli").await; // student |
| 14712 | let veli_id = me_id(&app, &veli).await; |
| 14713 | let anne = login_as(&app, &db, "anne", "parent").await; |
| 14714 | let hoca = login_as(&app, &db, "hoca", "teacher").await; |
| 14715 | let hoca_id = me_id(&app, &hoca).await; |
| 14716 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 14717 | |
| 14718 | let write = async |from: &str, to: &str| { |
| 14719 | send( |
| 14720 | &app, |
| 14721 | "POST", |
| 14722 | "/messages", |
| 14723 | Some(from), |
| 14724 | Some(json!({ "recipient_id": to, "subject": "selam" })), |
| 14725 | ) |
| 14726 | .await |
| 14727 | }; |
| 14728 | |
| 14729 | // Sideways and downward from below staff: refused, with the rule spelled out. |
| 14730 | let res = write(&ali, &veli_id).await; |
| 14731 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 14732 | assert!( |
| 14733 | res.body["error"] |
| 14734 | .as_str() |
| 14735 | .unwrap_or_default() |
| 14736 | .contains("staff"), |
| 14737 | "{}", |
| 14738 | res.body |
| 14739 | ); |
| 14740 | assert_eq!(write(&anne, &ali_id).await.status, StatusCode::FORBIDDEN); |
| 14741 | |
| 14742 | // Upward: allowed for both. |
| 14743 | assert_eq!(write(&ali, &hoca_id).await.status, StatusCode::CREATED); |
| 14744 | assert_eq!(write(&anne, &hoca_id).await.status, StatusCode::CREATED); |
| 14745 | |
| 14746 | // Staff write anywhere — down to a student, sideways to a colleague. |
| 14747 | assert_eq!(write(&hoca, &ali_id).await.status, StatusCode::CREATED); |
| 14748 | assert_eq!(write(&mudur, &hoca_id).await.status, StatusCode::CREATED); |
| 14749 | |
| 14750 | // The refused sends left nothing behind. |
| 14751 | let inbox = send(&app, "GET", "/messages", Some(&veli), None).await; |
| 14752 | assert_eq!(common::items(&inbox.body).len(), 0, "{}", inbox.body); |
| 14753 | } |
| 14754 | |
| 14755 | #[tokio::test] |
| 14756 | async fn messages_guard_parties_recipients_and_folders() { |
| 14757 | let (app, db) = app_and_db().await; |
| 14758 | let ali = login(&app, "ali").await; |
| 14759 | let ali_id = me_id(&app, &ali).await; |
| 14760 | let veli = login(&app, "veli").await; |
| 14761 | let parent = login_as(&app, &db, "anne", "parent").await; |
| 14762 | let hoca = login_as(&app, &db, "hoca", "teacher").await; |
| 14763 | let hoca_id = me_id(&app, &hoca).await; |
| 14764 | |
| 14765 | // Sending to yourself or to nobody fails. |
| 14766 | let res = send( |
| 14767 | &app, |
| 14768 | "POST", |
| 14769 | "/messages", |
| 14770 | Some(&ali), |
| 14771 | Some(json!({ "recipient_id": ali_id, "subject": "hi" })), |
| 14772 | ) |
| 14773 | .await; |
| 14774 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 14775 | let res = send( |
| 14776 | &app, |
| 14777 | "POST", |
| 14778 | "/messages", |
| 14779 | Some(&ali), |
| 14780 | Some(json!({ "recipient_id": common::GHOST_ID, "subject": "hi" })), |
| 14781 | ) |
| 14782 | .await; |
| 14783 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 14784 | |
| 14785 | // A parent writes — messaging is the role's one pen — but upward only: to |
| 14786 | // the teacher, not to the student. |
| 14787 | let res = send( |
| 14788 | &app, |
| 14789 | "POST", |
| 14790 | "/messages", |
| 14791 | Some(&parent), |
| 14792 | Some(json!({ "recipient_id": ali_id, "subject": "görüşme", "body": "uygun mu?" })), |
| 14793 | ) |
| 14794 | .await; |
| 14795 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 14796 | let res = send( |
| 14797 | &app, |
| 14798 | "POST", |
| 14799 | "/messages", |
| 14800 | Some(&parent), |
| 14801 | Some(json!({ "recipient_id": hoca_id, "subject": "görüşme", "body": "uygun mu?" })), |
| 14802 | ) |
| 14803 | .await; |
| 14804 | assert_eq!(res.status, StatusCode::CREATED); |
| 14805 | assert_eq!(res.body["sender_role"], "parent"); |
| 14806 | assert_eq!( |
| 14807 | res.body["label"], |
| 14808 | serde_json::Value::Null, |
| 14809 | "no label sent, none stored" |
| 14810 | ); |
| 14811 | let msg_id = id_of(&res.body); |
| 14812 | |
| 14813 | // A third user is not a party: sees nothing, touches nothing. |
| 14814 | let inbox = send(&app, "GET", "/messages", Some(&veli), None).await; |
| 14815 | assert_eq!(common::items(&inbox.body).len(), 0); |
| 14816 | let res = send( |
| 14817 | &app, |
| 14818 | "PATCH", |
| 14819 | &format!("/messages/{msg_id}"), |
| 14820 | Some(&veli), |
| 14821 | Some(json!({ "read": true })), |
| 14822 | ) |
| 14823 | .await; |
| 14824 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 14825 | let res = send( |
| 14826 | &app, |
| 14827 | "DELETE", |
| 14828 | &format!("/messages/{msg_id}"), |
| 14829 | Some(&veli), |
| 14830 | None, |
| 14831 | ) |
| 14832 | .await; |
| 14833 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 14834 | |
| 14835 | // Unknown folder names and oversized labels are refused. |
| 14836 | let res = send(&app, "GET", "/messages?folder=spam", Some(&ali), None).await; |
| 14837 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 14838 | let veli_id = me_id(&app, &veli).await; |
| 14839 | let res = send( |
| 14840 | &app, |
| 14841 | "POST", |
| 14842 | "/messages", |
| 14843 | Some(&ali), |
| 14844 | Some(json!({ "recipient_id": veli_id, "subject": "hi", "label": "x".repeat(51) })), |
| 14845 | ) |
| 14846 | .await; |
| 14847 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 14848 | } |
| 14849 | |
| 14850 | /// A patch that fails validation must not half-apply: the read flag stays |
| 14851 | /// untouched when the folder part of the same body is rejected. |
| 14852 | #[tokio::test] |
| 14853 | async fn messages_rejected_patch_leaves_no_side_effects() { |
| 14854 | let (app, db) = app_and_db().await; |
| 14855 | let ali = login(&app, "ali").await; |
| 14856 | let hoca = login_as(&app, &db, "hoca", "teacher").await; |
| 14857 | let hoca_id = me_id(&app, &hoca).await; |
| 14858 | |
| 14859 | let res = send( |
| 14860 | &app, |
| 14861 | "POST", |
| 14862 | "/messages", |
| 14863 | Some(&ali), |
| 14864 | Some(json!({ "recipient_id": hoca_id, "subject": "s", "body": "b" })), |
| 14865 | ) |
| 14866 | .await; |
| 14867 | assert_eq!(res.status, StatusCode::CREATED); |
| 14868 | let msg_id = id_of(&res.body); |
| 14869 | let res = send( |
| 14870 | &app, |
| 14871 | "PATCH", |
| 14872 | &format!("/messages/{msg_id}"), |
| 14873 | Some(&hoca), |
| 14874 | Some(json!({ "read": true })), |
| 14875 | ) |
| 14876 | .await; |
| 14877 | assert_eq!(res.status, StatusCode::OK); |
| 14878 | |
| 14879 | // Recipient can't move to `sent`; the bundled read flip must not land. |
| 14880 | let res = send( |
| 14881 | &app, |
| 14882 | "PATCH", |
| 14883 | &format!("/messages/{msg_id}"), |
| 14884 | Some(&hoca), |
| 14885 | Some(json!({ "read": false, "folder": "sent" })), |
| 14886 | ) |
| 14887 | .await; |
| 14888 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 14889 | let unread = send( |
| 14890 | &app, |
| 14891 | "GET", |
| 14892 | "/messages?folder=inbox&read=false", |
| 14893 | Some(&hoca), |
| 14894 | None, |
| 14895 | ) |
| 14896 | .await; |
| 14897 | assert_eq!( |
| 14898 | common::items(&unread.body).len(), |
| 14899 | 0, |
| 14900 | "rejected patch must not flip the read flag" |
| 14901 | ); |
| 14902 | } |
| 14903 | |
| 14904 | /// Notes carry no role bar: they are own-scoped personal data with no other |
| 14905 | /// reader, so the read-only `parent` keeps theirs like everybody else. The |
| 14906 | /// `student` bar this route family used to hold was a defect — see |
| 14907 | /// `a_demotion_to_parent_strands_no_note_and_no_blob`. |
| 14908 | #[tokio::test] |
| 14909 | async fn parent_role_keeps_its_own_notes() { |
| 14910 | let (app, db) = app_and_db().await; |
| 14911 | let parent = login_as(&app, &db, "baba", "parent").await; |
| 14912 | |
| 14913 | let res = send( |
| 14914 | &app, |
| 14915 | "POST", |
| 14916 | "/notes", |
| 14917 | Some(&parent), |
| 14918 | Some(json!({ "title": "mine" })), |
| 14919 | ) |
| 14920 | .await; |
| 14921 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 14922 | let res = send(&app, "GET", "/notes", Some(&parent), None).await; |
| 14923 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14924 | assert_eq!(common::items(&res.body).len(), 1); |
| 14925 | |
| 14926 | // Student and up keep the pen. |
| 14927 | let ali = login(&app, "ali").await; |
| 14928 | let res = send( |
| 14929 | &app, |
| 14930 | "POST", |
| 14931 | "/notes", |
| 14932 | Some(&ali), |
| 14933 | Some(json!({ "title": "ok" })), |
| 14934 | ) |
| 14935 | .await; |
| 14936 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 14937 | } |
| 14938 | |
| 14939 | /// A parent link whose student side stopped being a student (a role sweep |
| 14940 | /// losing a race with link creation) must be inert, exactly like a stale |
| 14941 | /// enrollment: the report reads re-check the live role. |
| 14942 | #[tokio::test] |
| 14943 | async fn stale_parent_link_is_inert_after_role_change() { |
| 14944 | let (app, db) = app_and_db().await; |
| 14945 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 14946 | let parent = login_as(&app, &db, "anne", "parent").await; |
| 14947 | let parent_id = me_id(&app, &parent).await; |
| 14948 | let ali = login(&app, "ali").await; |
| 14949 | let ali_id = me_id(&app, &ali).await; |
| 14950 | |
| 14951 | let res = send( |
| 14952 | &app, |
| 14953 | "POST", |
| 14954 | &format!("/users/{parent_id}/students"), |
| 14955 | Some(&admin), |
| 14956 | Some(json!({ "user_id": ali_id })), |
| 14957 | ) |
| 14958 | .await; |
| 14959 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14960 | let res = send( |
| 14961 | &app, |
| 14962 | "GET", |
| 14963 | &format!("/marks/{ali_id}"), |
| 14964 | Some(&parent), |
| 14965 | None, |
| 14966 | ) |
| 14967 | .await; |
| 14968 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 14969 | |
| 14970 | // Promote the student straight in the DB — the endpoint's sweep never |
| 14971 | // fires, leaving the link row behind like a lost race would. |
| 14972 | common::set_role(&db, "ali", "teacher").await; |
| 14973 | |
| 14974 | for path in [ |
| 14975 | format!("/marks/{ali_id}"), |
| 14976 | format!("/attendance/{ali_id}"), |
| 14977 | format!("/pomodoro/{ali_id}"), |
| 14978 | ] { |
| 14979 | let res = send(&app, "GET", &path, Some(&parent), None).await; |
| 14980 | assert_eq!( |
| 14981 | res.status, |
| 14982 | StatusCode::FORBIDDEN, |
| 14983 | "stale link must not grant {path}" |
| 14984 | ); |
| 14985 | } |
| 14986 | } |
| 14987 | |
| 14988 | // --- the question pool --------------------------------------------------- |
| 14989 | |
| 14990 | /// The pool lifecycle end to end: a student asks (pending — invisible to |
| 14991 | /// other students, listed for teachers), a teacher approves (one-way, 409 on |
| 14992 | /// repeat), the pool opens school-wide, anyone offers solutions, and |
| 14993 | /// moderation deletes cascade. |
| 14994 | #[tokio::test] |
| 14995 | async fn question_pool_lifecycle() { |
| 14996 | let (app, db) = app_and_db().await; |
| 14997 | let asker = login(&app, "ali").await; |
| 14998 | let stranger = login(&app, "veli").await; |
| 14999 | let teacher = login_as(&app, &db, "hoca", "teacher").await; |
| 15000 | |
| 15001 | // Only students ask: the teacher is refused. |
| 15002 | let ask = json!({ "title": "Integral", "body": "∫x·eˣ dx?" }); |
| 15003 | let res = send( |
| 15004 | &app, |
| 15005 | "POST", |
| 15006 | "/questions", |
| 15007 | Some(&teacher), |
| 15008 | Some(ask.clone()), |
| 15009 | ) |
| 15010 | .await; |
| 15011 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 15012 | |
| 15013 | let res = send(&app, "POST", "/questions", Some(&asker), Some(ask)).await; |
| 15014 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 15015 | assert_eq!(res.body["status"], "pending"); |
| 15016 | let qid = id_of(&res.body); |
| 15017 | |
| 15018 | // Pending: the asker and the teacher see it; another student must not |
| 15019 | // even learn it exists — and it takes no solutions yet. |
| 15020 | for (cookie, visible) in [(&asker, true), (&teacher, true), (&stranger, false)] { |
| 15021 | let res = send( |
| 15022 | &app, |
| 15023 | "GET", |
| 15024 | &format!("/questions/{qid}"), |
| 15025 | Some(cookie), |
| 15026 | None, |
| 15027 | ) |
| 15028 | .await; |
| 15029 | let expected = if visible { |
| 15030 | StatusCode::OK |
| 15031 | } else { |
| 15032 | StatusCode::NOT_FOUND |
| 15033 | }; |
| 15034 | assert_eq!(res.status, expected, "{}", res.body); |
| 15035 | } |
| 15036 | let offer = json!({ "body": "Kısmi integrasyon." }); |
| 15037 | let res = send( |
| 15038 | &app, |
| 15039 | "POST", |
| 15040 | &format!("/questions/{qid}/solutions"), |
| 15041 | Some(&asker), |
| 15042 | Some(offer.clone()), |
| 15043 | ) |
| 15044 | .await; |
| 15045 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 15046 | |
| 15047 | // The teacher's ?status=pending list is the approval queue; approval is |
| 15048 | // teacher-gated and one-way. |
| 15049 | let res = send( |
| 15050 | &app, |
| 15051 | "GET", |
| 15052 | "/questions?status=pending", |
| 15053 | Some(&teacher), |
| 15054 | None, |
| 15055 | ) |
| 15056 | .await; |
| 15057 | assert_eq!(common::total(&res.body), 1); |
| 15058 | let res = send( |
| 15059 | &app, |
| 15060 | "POST", |
| 15061 | &format!("/questions/{qid}/approve"), |
| 15062 | Some(&stranger), |
| 15063 | None, |
| 15064 | ) |
| 15065 | .await; |
| 15066 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 15067 | let res = send( |
| 15068 | &app, |
| 15069 | "POST", |
| 15070 | &format!("/questions/{qid}/approve"), |
| 15071 | Some(&teacher), |
| 15072 | None, |
| 15073 | ) |
| 15074 | .await; |
| 15075 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 15076 | assert_eq!(res.body["status"], "approved"); |
| 15077 | assert_eq!(res.body["approved_by"]["username"], "hoca"); |
| 15078 | let res = send( |
| 15079 | &app, |
| 15080 | "POST", |
| 15081 | &format!("/questions/{qid}/approve"), |
| 15082 | Some(&teacher), |
| 15083 | None, |
| 15084 | ) |
| 15085 | .await; |
| 15086 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 15087 | |
| 15088 | // Approved: school-wide — the stranger reads it and answers it. |
| 15089 | let res = send(&app, "GET", "/questions", Some(&stranger), None).await; |
| 15090 | assert_eq!(common::total(&res.body), 1); |
| 15091 | let res = send( |
| 15092 | &app, |
| 15093 | "POST", |
| 15094 | &format!("/questions/{qid}/solutions"), |
| 15095 | Some(&stranger), |
| 15096 | Some(offer), |
| 15097 | ) |
| 15098 | .await; |
| 15099 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 15100 | let sid = id_of(&res.body); |
| 15101 | |
| 15102 | // Deleting the solution: a third party may not, its author may. |
| 15103 | let res = send( |
| 15104 | &app, |
| 15105 | "DELETE", |
| 15106 | &format!("/questions/{qid}/solutions/{sid}"), |
| 15107 | Some(&asker), |
| 15108 | None, |
| 15109 | ) |
| 15110 | .await; |
| 15111 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 15112 | let res = send( |
| 15113 | &app, |
| 15114 | "DELETE", |
| 15115 | &format!("/questions/{qid}/solutions/{sid}"), |
| 15116 | Some(&stranger), |
| 15117 | None, |
| 15118 | ) |
| 15119 | .await; |
| 15120 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 15121 | |
| 15122 | // Question delete (asker withdraws) cascades what's left. |
| 15123 | let res = send( |
| 15124 | &app, |
| 15125 | "DELETE", |
| 15126 | &format!("/questions/{qid}"), |
| 15127 | Some(&asker), |
| 15128 | None, |
| 15129 | ) |
| 15130 | .await; |
| 15131 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 15132 | let res = send( |
| 15133 | &app, |
| 15134 | "GET", |
| 15135 | &format!("/questions/{qid}"), |
| 15136 | Some(&teacher), |
| 15137 | None, |
| 15138 | ) |
| 15139 | .await; |
| 15140 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 15141 | } |
| 15142 | |
| 15143 | /// Parents are observers: every pool surface (list, ask, answer) is closed to |
| 15144 | /// them. |
| 15145 | #[tokio::test] |
| 15146 | async fn question_pool_locks_parents_out() { |
| 15147 | let (app, db) = app_and_db().await; |
| 15148 | let parent = login_as(&app, &db, "anne", "parent").await; |
| 15149 | let res = send(&app, "GET", "/questions", Some(&parent), None).await; |
| 15150 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 15151 | let res = send( |
| 15152 | &app, |
| 15153 | "POST", |
| 15154 | "/questions", |
| 15155 | Some(&parent), |
| 15156 | Some(json!({ "title": "t", "body": "b" })), |
| 15157 | ) |
| 15158 | .await; |
| 15159 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 15160 | } |
| 15161 | |
| 15162 | /// The question photo: asker-only upload while pending, SVG refused, bytes |
| 15163 | /// served under the question's visibility, approval freezes the slot. |
| 15164 | #[tokio::test] |
| 15165 | async fn question_pool_image_upload_and_freeze() { |
| 15166 | let (app, db) = app_and_db().await; |
| 15167 | let asker = login(&app, "ali").await; |
| 15168 | let stranger = login(&app, "veli").await; |
| 15169 | let teacher = login_as(&app, &db, "hoca", "teacher").await; |
| 15170 | |
| 15171 | let res = send( |
| 15172 | &app, |
| 15173 | "POST", |
| 15174 | "/questions", |
| 15175 | Some(&asker), |
| 15176 | Some(json!({ "title": "Harita", "body": "Hangi şehir?" })), |
| 15177 | ) |
| 15178 | .await; |
| 15179 | let qid = id_of(&res.body); |
| 15180 | let upload = |cookie: &str, content_type: &str| { |
| 15181 | let uri = format!("/questions/{qid}/image"); |
| 15182 | let body = common::multipart_file("soru.png", content_type, b"png-bytes"); |
| 15183 | let cookie = cookie.to_string(); |
| 15184 | let app = app.clone(); |
| 15185 | async move { |
| 15186 | common::send_raw( |
| 15187 | &app, |
| 15188 | "POST", |
| 15189 | &uri, |
| 15190 | Some(&cookie), |
| 15191 | Some("multipart/form-data; boundary=hezarfen-test-boundary"), |
| 15192 | body, |
| 15193 | ) |
| 15194 | .await |
| 15195 | } |
| 15196 | }; |
| 15197 | |
| 15198 | // SVG is out; the teacher isn't the asker; the asker's PNG lands. |
| 15199 | let (status, _, _) = upload(&asker, "image/svg+xml").await; |
| 15200 | assert_eq!(status, StatusCode::BAD_REQUEST); |
| 15201 | let (status, _, _) = upload(&teacher, "image/png").await; |
| 15202 | assert_eq!(status, StatusCode::FORBIDDEN); |
| 15203 | let (status, _, _) = upload(&asker, "image/png").await; |
| 15204 | assert_eq!(status, StatusCode::CREATED); |
| 15205 | |
| 15206 | // Pending bytes follow pending visibility: asker yes, stranger no. |
| 15207 | let uri = format!("/questions/{qid}/image"); |
| 15208 | let (status, headers, bytes) = |
| 15209 | common::send_raw(&app, "GET", &uri, Some(&asker), None, Vec::new()).await; |
| 15210 | assert_eq!(status, StatusCode::OK); |
| 15211 | assert_eq!(headers["content-type"], "image/png"); |
| 15212 | assert_eq!(bytes, b"png-bytes"); |
| 15213 | let (status, _, _) = |
| 15214 | common::send_raw(&app, "GET", &uri, Some(&stranger), None, Vec::new()).await; |
| 15215 | assert_eq!(status, StatusCode::NOT_FOUND); |
| 15216 | |
| 15217 | // Approval freezes the image with the text: replace and remove both 409. |
| 15218 | let res = send( |
| 15219 | &app, |
| 15220 | "POST", |
| 15221 | &format!("/questions/{qid}/approve"), |
| 15222 | Some(&teacher), |
| 15223 | None, |
| 15224 | ) |
| 15225 | .await; |
| 15226 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 15227 | let (status, _, _) = upload(&asker, "image/png").await; |
| 15228 | assert_eq!(status, StatusCode::CONFLICT); |
| 15229 | let (status, _, _) = |
| 15230 | common::send_raw(&app, "DELETE", &uri, Some(&asker), None, Vec::new()).await; |
| 15231 | assert_eq!(status, StatusCode::CONFLICT); |
| 15232 | |
| 15233 | // But the approved bytes are now school-wide, and ride the question meta. |
| 15234 | let (status, _, _) = |
| 15235 | common::send_raw(&app, "GET", &uri, Some(&stranger), None, Vec::new()).await; |
| 15236 | assert_eq!(status, StatusCode::OK); |
| 15237 | let res = send( |
| 15238 | &app, |
| 15239 | "GET", |
| 15240 | &format!("/questions/{qid}"), |
| 15241 | Some(&stranger), |
| 15242 | None, |
| 15243 | ) |
| 15244 | .await; |
| 15245 | assert_eq!(res.body["image"]["content_type"], "image/png"); |
| 15246 | } |
| 15247 | |
| 15248 | /// The solution's photo and body stay the author's alone (no freeze — no |
| 15249 | /// moderation state to protect), bytes follow the question's visibility, and |
| 15250 | /// question rows tally their solutions. |
| 15251 | #[tokio::test] |
| 15252 | async fn solution_images_edits_and_counts() { |
| 15253 | let (app, db) = app_and_db().await; |
| 15254 | let asker = login(&app, "ali").await; |
| 15255 | let helper = login(&app, "veli").await; |
| 15256 | let teacher = login_as(&app, &db, "hoca", "teacher").await; |
| 15257 | |
| 15258 | // An approved question with the helper's solution under it. |
| 15259 | let res = send( |
| 15260 | &app, |
| 15261 | "POST", |
| 15262 | "/questions", |
| 15263 | Some(&asker), |
| 15264 | Some(json!({ "title": "Limit", "body": "x→0 iken sin(x)/x?" })), |
| 15265 | ) |
| 15266 | .await; |
| 15267 | let qid = id_of(&res.body); |
| 15268 | let res = send( |
| 15269 | &app, |
| 15270 | "POST", |
| 15271 | &format!("/questions/{qid}/approve"), |
| 15272 | Some(&teacher), |
| 15273 | None, |
| 15274 | ) |
| 15275 | .await; |
| 15276 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 15277 | let res = send( |
| 15278 | &app, |
| 15279 | "POST", |
| 15280 | &format!("/questions/{qid}/solutions"), |
| 15281 | Some(&helper), |
| 15282 | Some(json!({ "body": "Birebir 1'e gider." })), |
| 15283 | ) |
| 15284 | .await; |
| 15285 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 15286 | assert!(res.body["image"].is_null()); |
| 15287 | let sid = id_of(&res.body); |
| 15288 | |
| 15289 | // Image writes are the author's: the asker is refused, the helper lands. |
| 15290 | let uri = format!("/questions/{qid}/solutions/{sid}/image"); |
| 15291 | let upload = |cookie: &str| { |
| 15292 | let uri = uri.clone(); |
| 15293 | let body = common::multipart_file("cozum.png", "image/png", b"png-bytes"); |
| 15294 | let cookie = cookie.to_string(); |
| 15295 | let app = app.clone(); |
| 15296 | async move { |
| 15297 | common::send_raw( |
| 15298 | &app, |
| 15299 | "POST", |
| 15300 | &uri, |
| 15301 | Some(&cookie), |
| 15302 | Some("multipart/form-data; boundary=hezarfen-test-boundary"), |
| 15303 | body, |
| 15304 | ) |
| 15305 | .await |
| 15306 | } |
| 15307 | }; |
| 15308 | let (status, _, _) = upload(&asker).await; |
| 15309 | assert_eq!(status, StatusCode::FORBIDDEN); |
| 15310 | let (status, _, _) = upload(&teacher).await; |
| 15311 | assert_eq!(status, StatusCode::FORBIDDEN); |
| 15312 | let (status, _, _) = upload(&helper).await; |
| 15313 | assert_eq!(status, StatusCode::CREATED); |
| 15314 | |
| 15315 | // Bytes follow the question's visibility — approved, so any student |
| 15316 | // reads them — and the meta rides the solution row. |
| 15317 | let (status, headers, bytes) = |
| 15318 | common::send_raw(&app, "GET", &uri, Some(&asker), None, Vec::new()).await; |
| 15319 | assert_eq!(status, StatusCode::OK); |
| 15320 | assert_eq!(headers["content-type"], "image/png"); |
| 15321 | assert_eq!(bytes, b"png-bytes"); |
| 15322 | let res = send( |
| 15323 | &app, |
| 15324 | "GET", |
| 15325 | &format!("/questions/{qid}/solutions"), |
| 15326 | Some(&asker), |
| 15327 | None, |
| 15328 | ) |
| 15329 | .await; |
| 15330 | assert_eq!(res.body["items"][0]["image"]["content_type"], "image/png"); |
| 15331 | |
| 15332 | // Body edits are author-only too — teacher+ moderate by deleting, never |
| 15333 | // by rewriting. |
| 15334 | let edit = json!({ "body": "Standart limit: sin(x)/x → 1." }); |
| 15335 | let res = send( |
| 15336 | &app, |
| 15337 | "PATCH", |
| 15338 | &format!("/questions/{qid}/solutions/{sid}"), |
| 15339 | Some(&asker), |
| 15340 | Some(edit.clone()), |
| 15341 | ) |
| 15342 | .await; |
| 15343 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 15344 | let res = send( |
| 15345 | &app, |
| 15346 | "PATCH", |
| 15347 | &format!("/questions/{qid}/solutions/{sid}"), |
| 15348 | Some(&helper), |
| 15349 | Some(edit), |
| 15350 | ) |
| 15351 | .await; |
| 15352 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 15353 | assert_eq!(res.body["body"], "Standart limit: sin(x)/x → 1."); |
| 15354 | assert_eq!(res.body["image"]["content_type"], "image/png"); |
| 15355 | |
| 15356 | // Question rows tally their solutions, in the list and the single GET. |
| 15357 | let res = send(&app, "GET", "/questions?limit=5", Some(&asker), None).await; |
| 15358 | assert_eq!(res.body["items"][0]["solution_count"], 1); |
| 15359 | let res = send( |
| 15360 | &app, |
| 15361 | "GET", |
| 15362 | &format!("/questions/{qid}"), |
| 15363 | Some(&asker), |
| 15364 | None, |
| 15365 | ) |
| 15366 | .await; |
| 15367 | assert_eq!(res.body["solution_count"], 1); |
| 15368 | |
| 15369 | // The author drops the photo; a second removal finds nothing. |
| 15370 | let (status, _, _) = |
| 15371 | common::send_raw(&app, "DELETE", &uri, Some(&helper), None, Vec::new()).await; |
| 15372 | assert_eq!(status, StatusCode::NO_CONTENT); |
| 15373 | let (status, _, _) = common::send_raw(&app, "GET", &uri, Some(&asker), None, Vec::new()).await; |
| 15374 | assert_eq!(status, StatusCode::NOT_FOUND); |
| 15375 | let (status, _, _) = |
| 15376 | common::send_raw(&app, "DELETE", &uri, Some(&helper), None, Vec::new()).await; |
| 15377 | assert_eq!(status, StatusCode::NOT_FOUND); |
| 15378 | |
| 15379 | // And the question delete still sweeps everything under it. |
| 15380 | let res = send( |
| 15381 | &app, |
| 15382 | "DELETE", |
| 15383 | &format!("/questions/{qid}"), |
| 15384 | Some(&asker), |
| 15385 | None, |
| 15386 | ) |
| 15387 | .await; |
| 15388 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 15389 | } |
| 15390 | |
| 15391 | // --- drawing byte-fidelity (stroke-JSON tEXt passthrough) ------------------- |
| 15392 | // The frontend's canvas saves a drawing as a PNG that also carries its |
| 15393 | // editable stroke JSON inside a custom `tEXt` chunk; the backend only ever |
| 15394 | // stores and re-serves the uploaded bytes (see `read_upload` / `serve_inline_blob` |
| 15395 | // in web/mod.rs). These tests build a real (if minimal) PNG with a `tEXt` |
| 15396 | // chunk and assert the round trip is byte-for-byte — if anyone ever adds |
| 15397 | // image re-encoding, compression, or thumbnailing, every stored drawing |
| 15398 | // silently stops being replayable, and this is what would catch it. |
| 15399 | |
| 15400 | /// CRC-32 (ISO-HDLC — the checksum PNG chunks and zlib both use), bit by bit: |
| 15401 | /// no table, since this only ever runs over a few dozen fixture bytes. No new |
| 15402 | /// crate for one checksum used to hand-build a PNG below. |
| 15403 | fn crc32(bytes: &[u8]) -> u32 { |
| 15404 | let mut crc = 0xFFFF_FFFFu32; |
| 15405 | for &byte in bytes { |
| 15406 | crc ^= byte as u32; |
| 15407 | for _ in 0..8 { |
| 15408 | crc = if crc & 1 == 1 { |
| 15409 | (crc >> 1) ^ 0xEDB8_8320 |
| 15410 | } else { |
| 15411 | crc >> 1 |
| 15412 | }; |
| 15413 | } |
| 15414 | } |
| 15415 | !crc |
| 15416 | } |
| 15417 | |
| 15418 | /// Pin the hand-rolled checksum against the standard CRC-32 check value. |
| 15419 | /// Nothing downstream ever validates a chunk's CRC (the server never parses |
| 15420 | /// PNG structure), so a broken implementation here would silently build |
| 15421 | /// fixtures that only *look* like PNGs — this is the one thing that would |
| 15422 | /// catch that. |
| 15423 | #[tokio::test] |
| 15424 | async fn crc32_matches_the_standard_check_value() { |
| 15425 | assert_eq!(crc32(b"123456789"), 0xCBF4_3926); |
| 15426 | } |
| 15427 | |
| 15428 | /// Frame one PNG chunk: 4-byte big-endian length, 4-byte type, the data, then |
| 15429 | /// the CRC-32 over type+data. |
| 15430 | fn png_chunk(kind: &[u8; 4], data: &[u8]) -> Vec<u8> { |
| 15431 | let mut chunk = Vec::with_capacity(12 + data.len()); |
| 15432 | chunk.extend_from_slice(&(data.len() as u32).to_be_bytes()); |
| 15433 | chunk.extend_from_slice(kind); |
| 15434 | chunk.extend_from_slice(data); |
| 15435 | let crc_body: Vec<u8> = kind.iter().chain(data.iter()).copied().collect(); |
| 15436 | chunk.extend_from_slice(&crc32(&crc_body).to_be_bytes()); |
| 15437 | chunk |
| 15438 | } |
| 15439 | |
| 15440 | /// A genuinely valid, minimal (1x1 grayscale) PNG carrying a custom `tEXt` |
| 15441 | /// chunk whose text is `marker` — the same trick the frontend uses to smuggle |
| 15442 | /// its editable stroke JSON inside a drawing's PNG bytes. Built inline (no |
| 15443 | /// binary fixture file) so the test commits exactly the bytes it later |
| 15444 | /// asserts on. |
| 15445 | fn png_with_text_chunk(marker: &str) -> Vec<u8> { |
| 15446 | let mut png = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; |
| 15447 | // IHDR: 1x1 pixel, 8-bit depth, grayscale, no interlace. |
| 15448 | png.extend(png_chunk(b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 0, 0, 0, 0])); |
| 15449 | // tEXt: keyword "Comment", NUL, then the marker — exactly where a real |
| 15450 | // drawing's stroke JSON rides. |
| 15451 | let mut text = b"Comment\0".to_vec(); |
| 15452 | text.extend_from_slice(marker.as_bytes()); |
| 15453 | png.extend(png_chunk(b"tEXt", &text)); |
| 15454 | // IDAT: one stored (uncompressed) deflate block over the single |
| 15455 | // [filter=None, pixel=0] scanline, so this decodes as a real black pixel. |
| 15456 | png.extend(png_chunk( |
| 15457 | b"IDAT", |
| 15458 | &[ |
| 15459 | 0x78, 0x01, // zlib header |
| 15460 | 0x01, 0x02, 0x00, 0xFD, 0xFF, // stored block: BFINAL+BTYPE, LEN, NLEN |
| 15461 | 0x00, 0x00, // scanline: filter=None, pixel=0 |
| 15462 | 0x00, 0x02, 0x00, 0x01, // Adler-32 of the scanline bytes |
| 15463 | ], |
| 15464 | )); |
| 15465 | png.extend(png_chunk(b"IEND", &[])); |
| 15466 | png |
| 15467 | } |
| 15468 | |
| 15469 | /// The primary invariant: a student's answer drawing survives its round trip |
| 15470 | /// byte-for-byte, `tEXt` chunk included — on both read paths that matter, the |
| 15471 | /// student's own (for editing) and the teacher's grading read (for replay). |
| 15472 | /// If the backend ever re-encodes or strips metadata from this PNG, the |
| 15473 | /// stroke JSON in the `tEXt` chunk is gone and the drawing stops replaying. |
| 15474 | #[tokio::test] |
| 15475 | async fn answer_image_round_trip_keeps_the_stroke_text_chunk_intact() { |
| 15476 | let (app, db) = app_and_db().await; |
| 15477 | let teacher = login_as(&app, &db, "rt_t", "teacher").await; |
| 15478 | let student = login(&app, "rt_s").await; |
| 15479 | let student_id = me_id(&app, &student).await; |
| 15480 | |
| 15481 | let mudur = login_as(&app, &db, "rt_m", "manager").await; |
| 15482 | let t = taught_under(&app, &mudur, &teacher, "art").await; |
| 15483 | let subject = create_subject(&app, &teacher, &t.course, "sketching").await; |
| 15484 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 15485 | let exam = scheduled_exam( |
| 15486 | &app, |
| 15487 | &teacher, |
| 15488 | &t.instance, |
| 15489 | json!({ "term": &t.term, "title": "sketch quiz", "kind": "yazili", "mode": "open" }), |
| 15490 | ) |
| 15491 | .await; |
| 15492 | let question_body = create_question_body( |
| 15493 | &app, |
| 15494 | &teacher, |
| 15495 | &exam, |
| 15496 | &subject, |
| 15497 | json!({ "text": "Draw a triangle.", "kind": "text", "points": 10 }), |
| 15498 | ) |
| 15499 | .await; |
| 15500 | let question = id_of(&question_body); |
| 15501 | let res = send( |
| 15502 | &app, |
| 15503 | "POST", |
| 15504 | &format!("/exams/{exam}/attempt"), |
| 15505 | Some(&student), |
| 15506 | None, |
| 15507 | ) |
| 15508 | .await; |
| 15509 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 15510 | |
| 15511 | let png = png_with_text_chunk(r#"{"strokes":[[1,1],[2,2],[3,3]]}"#); |
| 15512 | let own = format!("/exams/{exam}/attempt/answers/{question}/image"); |
| 15513 | let (status, body) = post_image(&app, &student, &own, "image/png", &png).await; |
| 15514 | assert_eq!(status, StatusCode::CREATED, "{}", body); |
| 15515 | |
| 15516 | // The student replays their own drawing from this route. |
| 15517 | let (status, headers, bytes) = |
| 15518 | common::send_raw(&app, "GET", &own, Some(&student), None, Vec::new()).await; |
| 15519 | assert_eq!(status, StatusCode::OK); |
| 15520 | assert_eq!(headers["content-type"], "image/png"); |
| 15521 | assert_eq!(bytes, png, "the student's own read must be byte-identical"); |
| 15522 | |
| 15523 | // The teacher replays it too, via the grading route — same requirement. |
| 15524 | let teacher_uri = format!("/exams/{exam}/attempts/{student_id}/answers/{question}/image"); |
| 15525 | let (status, _, bytes) = |
| 15526 | common::send_raw(&app, "GET", &teacher_uri, Some(&teacher), None, Vec::new()).await; |
| 15527 | assert_eq!(status, StatusCode::OK); |
| 15528 | assert_eq!(bytes, png, "the grader read must be byte-identical too"); |
| 15529 | } |
| 15530 | |
| 15531 | /// The pool question photo is a drawing too (a student can attach a photo or |
| 15532 | /// a canvas sketch of the problem) — same byte-for-byte requirement as an |
| 15533 | /// answer image, or a teacher replaying a hand-drawn question loses the |
| 15534 | /// stroke JSON in its `tEXt` chunk. |
| 15535 | #[tokio::test] |
| 15536 | async fn question_photo_round_trip_keeps_the_stroke_text_chunk_intact() { |
| 15537 | let app = mem_app().await; |
| 15538 | let asker = login(&app, "ali").await; |
| 15539 | let res = send( |
| 15540 | &app, |
| 15541 | "POST", |
| 15542 | "/questions", |
| 15543 | Some(&asker), |
| 15544 | Some(json!({ "title": "Şekil", "body": "Çizim ekli" })), |
| 15545 | ) |
| 15546 | .await; |
| 15547 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 15548 | let qid = id_of(&res.body); |
| 15549 | |
| 15550 | let png = png_with_text_chunk(r#"{"strokes":[[4,4],[5,5]]}"#); |
| 15551 | let uri = format!("/questions/{qid}/image"); |
| 15552 | let (status, body) = post_image(&app, &asker, &uri, "image/png", &png).await; |
| 15553 | assert_eq!(status, StatusCode::CREATED, "{}", body); |
| 15554 | |
| 15555 | let (status, headers, bytes) = |
| 15556 | common::send_raw(&app, "GET", &uri, Some(&asker), None, Vec::new()).await; |
| 15557 | assert_eq!(status, StatusCode::OK); |
| 15558 | assert_eq!(headers["content-type"], "image/png"); |
| 15559 | assert_eq!( |
| 15560 | bytes, png, |
| 15561 | "the pool question photo must round-trip byte-for-byte" |
| 15562 | ); |
| 15563 | } |
| 15564 | |
| 15565 | /// Same story on a solution's worked-steps photo: the backend must never |
| 15566 | /// touch these bytes, or a replayed solution drawing loses its stroke JSON. |
| 15567 | #[tokio::test] |
| 15568 | async fn solution_photo_round_trip_keeps_the_stroke_text_chunk_intact() { |
| 15569 | let (app, db) = app_and_db().await; |
| 15570 | let asker = login(&app, "ali").await; |
| 15571 | let helper = login(&app, "veli").await; |
| 15572 | let teacher = login_as(&app, &db, "hoca", "teacher").await; |
| 15573 | |
| 15574 | let res = send( |
| 15575 | &app, |
| 15576 | "POST", |
| 15577 | "/questions", |
| 15578 | Some(&asker), |
| 15579 | Some(json!({ "title": "Limit", "body": "Çözüm arıyorum" })), |
| 15580 | ) |
| 15581 | .await; |
| 15582 | let qid = id_of(&res.body); |
| 15583 | let res = send( |
| 15584 | &app, |
| 15585 | "POST", |
| 15586 | &format!("/questions/{qid}/approve"), |
| 15587 | Some(&teacher), |
| 15588 | None, |
| 15589 | ) |
| 15590 | .await; |
| 15591 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 15592 | let res = send( |
| 15593 | &app, |
| 15594 | "POST", |
| 15595 | &format!("/questions/{qid}/solutions"), |
| 15596 | Some(&helper), |
| 15597 | Some(json!({ "body": "İşte çözüm." })), |
| 15598 | ) |
| 15599 | .await; |
| 15600 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 15601 | let sid = id_of(&res.body); |
| 15602 | |
| 15603 | let png = png_with_text_chunk(r#"{"strokes":[[6,6],[7,7]]}"#); |
| 15604 | let uri = format!("/questions/{qid}/solutions/{sid}/image"); |
| 15605 | let (status, body) = post_image(&app, &helper, &uri, "image/png", &png).await; |
| 15606 | assert_eq!(status, StatusCode::CREATED, "{}", body); |
| 15607 | |
| 15608 | let (status, headers, bytes) = |
| 15609 | common::send_raw(&app, "GET", &uri, Some(&asker), None, Vec::new()).await; |
| 15610 | assert_eq!(status, StatusCode::OK); |
| 15611 | assert_eq!(headers["content-type"], "image/png"); |
| 15612 | assert_eq!( |
| 15613 | bytes, png, |
| 15614 | "the solution photo must round-trip byte-for-byte" |
| 15615 | ); |
| 15616 | } |
| 15617 | |
| 15618 | /// The contrast to `question_pool_image_upload_and_freeze`'s 409-after-approval: |
| 15619 | /// a solution carries no moderation state, so its author replaces the photo |
| 15620 | /// freely at any time, even on a long-approved question. |
| 15621 | #[tokio::test] |
| 15622 | async fn solution_photo_replaces_freely_unlike_the_frozen_question_photo() { |
| 15623 | let (app, db) = app_and_db().await; |
| 15624 | let asker = login(&app, "ali").await; |
| 15625 | let helper = login(&app, "veli").await; |
| 15626 | let teacher = login_as(&app, &db, "hoca", "teacher").await; |
| 15627 | |
| 15628 | let res = send( |
| 15629 | &app, |
| 15630 | "POST", |
| 15631 | "/questions", |
| 15632 | Some(&asker), |
| 15633 | Some(json!({ "title": "Türev", "body": "Nasıl alınır?" })), |
| 15634 | ) |
| 15635 | .await; |
| 15636 | let qid = id_of(&res.body); |
| 15637 | let res = send( |
| 15638 | &app, |
| 15639 | "POST", |
| 15640 | &format!("/questions/{qid}/approve"), |
| 15641 | Some(&teacher), |
| 15642 | None, |
| 15643 | ) |
| 15644 | .await; |
| 15645 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 15646 | let res = send( |
| 15647 | &app, |
| 15648 | "POST", |
| 15649 | &format!("/questions/{qid}/solutions"), |
| 15650 | Some(&helper), |
| 15651 | Some(json!({ "body": "Cevap burada." })), |
| 15652 | ) |
| 15653 | .await; |
| 15654 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 15655 | let sid = id_of(&res.body); |
| 15656 | |
| 15657 | let uri = format!("/questions/{qid}/solutions/{sid}/image"); |
| 15658 | let (status, _) = post_image(&app, &helper, &uri, "image/png", b"first-draft").await; |
| 15659 | assert_eq!(status, StatusCode::CREATED); |
| 15660 | // No freeze: a second replace on the same long-approved question still lands. |
| 15661 | let (status, _) = post_image(&app, &helper, &uri, "image/png", b"second-draft").await; |
| 15662 | assert_eq!( |
| 15663 | status, |
| 15664 | StatusCode::CREATED, |
| 15665 | "a solution photo must never freeze" |
| 15666 | ); |
| 15667 | let (status, _, bytes) = |
| 15668 | common::send_raw(&app, "GET", &uri, Some(&helper), None, Vec::new()).await; |
| 15669 | assert_eq!(status, StatusCode::OK); |
| 15670 | assert_eq!(bytes, b"second-draft"); |
| 15671 | } |
| 15672 | |
| 15673 | /// The other half of a pending question's photo visibility (the asker-vs-stranger |
| 15674 | /// half is already pinned by `question_pool_image_upload_and_freeze`): teacher+ |
| 15675 | /// is the approval queue's other reader, so a pending photo must reach them too. |
| 15676 | #[tokio::test] |
| 15677 | async fn pool_question_pending_photo_reaches_teacher_too() { |
| 15678 | let (app, db) = app_and_db().await; |
| 15679 | let asker = login(&app, "ali").await; |
| 15680 | let teacher = login_as(&app, &db, "hoca", "teacher").await; |
| 15681 | |
| 15682 | let res = send( |
| 15683 | &app, |
| 15684 | "POST", |
| 15685 | "/questions", |
| 15686 | Some(&asker), |
| 15687 | Some(json!({ "title": "Soru", "body": "Yardım lazım" })), |
| 15688 | ) |
| 15689 | .await; |
| 15690 | let qid = id_of(&res.body); |
| 15691 | let uri = format!("/questions/{qid}/image"); |
| 15692 | let (status, _) = post_image(&app, &asker, &uri, "image/png", b"png-bytes").await; |
| 15693 | assert_eq!(status, StatusCode::CREATED); |
| 15694 | |
| 15695 | let (status, _, bytes) = |
| 15696 | common::send_raw(&app, "GET", &uri, Some(&teacher), None, Vec::new()).await; |
| 15697 | assert_eq!( |
| 15698 | status, |
| 15699 | StatusCode::OK, |
| 15700 | "teacher+ must see a pending photo too" |
| 15701 | ); |
| 15702 | assert_eq!(bytes, b"png-bytes"); |
| 15703 | } |
| 15704 | |
| 15705 | /// `GET` on a pool photo needs student role or higher; parents are read-only |
| 15706 | /// report observers (see `question_pool_locks_parents_out`), so both photo |
| 15707 | /// routes must refuse them exactly like the rest of the pool. |
| 15708 | #[tokio::test] |
| 15709 | async fn pool_photo_reads_require_student_role() { |
| 15710 | let (app, db) = app_and_db().await; |
| 15711 | let asker = login(&app, "ali").await; |
| 15712 | let helper = login(&app, "veli").await; |
| 15713 | let teacher = login_as(&app, &db, "hoca", "teacher").await; |
| 15714 | let parent = login_as(&app, &db, "anne", "parent").await; |
| 15715 | |
| 15716 | let res = send( |
| 15717 | &app, |
| 15718 | "POST", |
| 15719 | "/questions", |
| 15720 | Some(&asker), |
| 15721 | Some(json!({ "title": "Soru", "body": "Yardım lazım" })), |
| 15722 | ) |
| 15723 | .await; |
| 15724 | let qid = id_of(&res.body); |
| 15725 | let q_uri = format!("/questions/{qid}/image"); |
| 15726 | let (status, _) = post_image(&app, &asker, &q_uri, "image/png", b"q-bytes").await; |
| 15727 | assert_eq!(status, StatusCode::CREATED); |
| 15728 | let res = send( |
| 15729 | &app, |
| 15730 | "POST", |
| 15731 | &format!("/questions/{qid}/approve"), |
| 15732 | Some(&teacher), |
| 15733 | None, |
| 15734 | ) |
| 15735 | .await; |
| 15736 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 15737 | let res = send( |
| 15738 | &app, |
| 15739 | "POST", |
| 15740 | &format!("/questions/{qid}/solutions"), |
| 15741 | Some(&helper), |
| 15742 | Some(json!({ "body": "Cevap burada." })), |
| 15743 | ) |
| 15744 | .await; |
| 15745 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 15746 | let sid = id_of(&res.body); |
| 15747 | let s_uri = format!("/questions/{qid}/solutions/{sid}/image"); |
| 15748 | let (status, _) = post_image(&app, &helper, &s_uri, "image/png", b"s-bytes").await; |
| 15749 | assert_eq!(status, StatusCode::CREATED); |
| 15750 | |
| 15751 | let (status, _, _) = |
| 15752 | common::send_raw(&app, "GET", &q_uri, Some(&parent), None, Vec::new()).await; |
| 15753 | assert_eq!( |
| 15754 | status, |
| 15755 | StatusCode::FORBIDDEN, |
| 15756 | "parents can't read a question photo" |
| 15757 | ); |
| 15758 | let (status, _, _) = |
| 15759 | common::send_raw(&app, "GET", &s_uri, Some(&parent), None, Vec::new()).await; |
| 15760 | assert_eq!( |
| 15761 | status, |
| 15762 | StatusCode::FORBIDDEN, |
| 15763 | "parents can't read a solution photo" |
| 15764 | ); |
| 15765 | } |
| 15766 | |
| 15767 | // --- homework ------------------------------------------------------------- |
| 15768 | |
| 15769 | /// A teacher-run şube with a subject and two students in it — the stage most |
| 15770 | /// homework tests play on. The homework itself keys on the instance (the pair |
| 15771 | /// of catalog course and şube), so that is what the fields below name: `course` |
| 15772 | /// is the catalog row, `instance` the anchor every `/instances/{id}/…` route and |
| 15773 | /// every homework takes. |
| 15774 | struct HwWorld { |
| 15775 | teacher: String, |
| 15776 | ali: String, |
| 15777 | ali_id: String, |
| 15778 | veli: String, |
| 15779 | veli_id: String, |
| 15780 | course: String, |
| 15781 | class: String, |
| 15782 | instance: String, |
| 15783 | subject: String, |
| 15784 | } |
| 15785 | |
| 15786 | async fn hw_world(app: &axum::Router, db: &hezarfen_backend::database::Database) -> HwWorld { |
| 15787 | let teacher = login_as(app, db, "teacher", "teacher").await; |
| 15788 | let mudur = login_as(app, db, "hw.mudur", "manager").await; |
| 15789 | let ali = login(app, "ali").await; |
| 15790 | let ali_id = me_id(app, &ali).await; |
| 15791 | let veli = login(app, "veli").await; |
| 15792 | let veli_id = me_id(app, &veli).await; |
| 15793 | let t = taught_under(app, &mudur, &teacher, "math").await; |
| 15794 | let subject = create_subject(app, &teacher, &t.course, "algebra").await; |
| 15795 | select_instance_subject(app, &teacher, &t.instance, &subject).await; |
| 15796 | // The students sit in the şube: the pump enrolls them into the instance. |
| 15797 | add_member(app, &mudur, &t.class, &ali_id).await; |
| 15798 | add_member(app, &mudur, &t.class, &veli_id).await; |
| 15799 | HwWorld { |
| 15800 | teacher, |
| 15801 | ali, |
| 15802 | ali_id, |
| 15803 | veli, |
| 15804 | veli_id, |
| 15805 | course: t.course, |
| 15806 | class: t.class, |
| 15807 | instance: t.instance, |
| 15808 | subject, |
| 15809 | } |
| 15810 | } |
| 15811 | |
| 15812 | /// POST the caller's submission (optional text) to `hw` — no assertion. |
| 15813 | async fn submit_hw(app: &axum::Router, cookie: &str, hw: &str, text: Option<&str>) -> common::Res { |
| 15814 | let body = match text { |
| 15815 | Some(text) => json!({ "text": text }), |
| 15816 | None => json!({}), |
| 15817 | }; |
| 15818 | send( |
| 15819 | app, |
| 15820 | "POST", |
| 15821 | &format!("/homework/{hw}/submission"), |
| 15822 | Some(cookie), |
| 15823 | Some(body), |
| 15824 | ) |
| 15825 | .await |
| 15826 | } |
| 15827 | |
| 15828 | /// Upload `bytes` as a file onto the caller's submission to `hw` — no |
| 15829 | /// assertion. Parses the JSON body like `send`. |
| 15830 | async fn upload_hw_file( |
| 15831 | app: &axum::Router, |
| 15832 | cookie: &str, |
| 15833 | hw: &str, |
| 15834 | filename: &str, |
| 15835 | content_type: &str, |
| 15836 | bytes: &[u8], |
| 15837 | ) -> common::Res { |
| 15838 | let (status, _, body) = common::send_raw( |
| 15839 | app, |
| 15840 | "POST", |
| 15841 | &format!("/homework/{hw}/submission/files"), |
| 15842 | Some(cookie), |
| 15843 | Some("multipart/form-data; boundary=hezarfen-test-boundary"), |
| 15844 | common::multipart_file(filename, content_type, bytes), |
| 15845 | ) |
| 15846 | .await; |
| 15847 | let body = if body.is_empty() { |
| 15848 | serde_json::Value::Null |
| 15849 | } else { |
| 15850 | serde_json::from_slice(&body).unwrap_or(serde_json::Value::Null) |
| 15851 | }; |
| 15852 | common::Res { |
| 15853 | status, |
| 15854 | body, |
| 15855 | cookie: None, |
| 15856 | } |
| 15857 | } |
| 15858 | |
| 15859 | /// POST a grade for `user` onto `hw` — no assertion. |
| 15860 | async fn grade_hw( |
| 15861 | app: &axum::Router, |
| 15862 | cookie: &str, |
| 15863 | hw: &str, |
| 15864 | user: &str, |
| 15865 | status: &str, |
| 15866 | mark: Option<i64>, |
| 15867 | ) -> common::Res { |
| 15868 | let mut body = json!({ "user": user, "status": status }); |
| 15869 | if let Some(mark) = mark { |
| 15870 | body["mark"] = json!(mark); |
| 15871 | } |
| 15872 | send( |
| 15873 | app, |
| 15874 | "POST", |
| 15875 | &format!("/homework/{hw}/results"), |
| 15876 | Some(cookie), |
| 15877 | Some(body), |
| 15878 | ) |
| 15879 | .await |
| 15880 | } |
| 15881 | |
| 15882 | /// Every stored homework-file blob name, straight from the table. |
| 15883 | async fn homework_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { |
| 15884 | sqlx::query_scalar("SELECT file FROM homework_file") |
| 15885 | .fetch_all(db) |
| 15886 | .await |
| 15887 | .unwrap() |
| 15888 | } |
| 15889 | |
| 15890 | /// Row count of `table`, straight from the database — a cascade must really |
| 15891 | /// delete, not merely hide behind the role checks. |
| 15892 | async fn hw_row_count(db: &hezarfen_backend::database::Database, table: &str) -> i64 { |
| 15893 | sqlx::query_scalar::<sqlx::Postgres, i64>(sqlx::AssertSqlSafe(format!( |
| 15894 | "SELECT count(*) FROM {table}" |
| 15895 | ))) |
| 15896 | .fetch_one(db) |
| 15897 | .await |
| 15898 | .unwrap() |
| 15899 | } |
| 15900 | |
| 15901 | /// Creation validates the due date (60s grace), the subject's course, the |
| 15902 | /// subset's enrollment, and the subset cap — and stays teacher-only. |
| 15903 | #[tokio::test] |
| 15904 | async fn homework_create_validates_due_subject_and_subset() { |
| 15905 | let (app, db) = app_and_db().await; |
| 15906 | let w = hw_world(&app, &db).await; |
| 15907 | let now = Timestamp::now().as_millis(); |
| 15908 | |
| 15909 | // due_at beyond the 60s grace lies in the past — rejected. |
| 15910 | let res = common::create_homework_with( |
| 15911 | &app, |
| 15912 | &w.teacher, |
| 15913 | &w.instance, |
| 15914 | json!({ "title": "old", "subject_id": w.subject, "due_at": now - 120_000 }), |
| 15915 | ) |
| 15916 | .await; |
| 15917 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 15918 | |
| 15919 | // The subject must belong to this very course. |
| 15920 | let other_course = create_course(&app, &w.teacher, "physics").await; |
| 15921 | let foreign = create_subject(&app, &w.teacher, &other_course, "optics").await; |
| 15922 | let res = common::create_homework_with( |
| 15923 | &app, |
| 15924 | &w.teacher, |
| 15925 | &w.instance, |
| 15926 | json!({ "title": "x", "subject_id": foreign, "due_at": now + 3_600_000 }), |
| 15927 | ) |
| 15928 | .await; |
| 15929 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 15930 | |
| 15931 | // Every assigned student must be enrolled… |
| 15932 | let mehmet = login(&app, "mehmet").await; |
| 15933 | let mehmet_id = me_id(&app, &mehmet).await; |
| 15934 | let res = common::create_homework_with( |
| 15935 | &app, |
| 15936 | &w.teacher, |
| 15937 | &w.instance, |
| 15938 | json!({ "title": "x", "subject_id": w.subject, "due_at": now + 3_600_000, |
| 15939 | "assigned": [mehmet_id] }), |
| 15940 | ) |
| 15941 | .await; |
| 15942 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 15943 | |
| 15944 | // …and the subset caps at 200 names (checked before enrollment, so fakes |
| 15945 | // trip it without 201 signups). |
| 15946 | let fakes: Vec<String> = (0..201).map(|i| format!("01FAKE{i:020}")).collect(); |
| 15947 | let res = common::create_homework_with( |
| 15948 | &app, |
| 15949 | &w.teacher, |
| 15950 | &w.instance, |
| 15951 | json!({ "title": "x", "subject_id": w.subject, "due_at": now + 3_600_000, |
| 15952 | "assigned": fakes }), |
| 15953 | ) |
| 15954 | .await; |
| 15955 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 15956 | |
| 15957 | // Students don't assign homework. |
| 15958 | let res = common::create_homework_with( |
| 15959 | &app, |
| 15960 | &w.ali, |
| 15961 | &w.instance, |
| 15962 | json!({ "title": "x", "subject_id": w.subject, "due_at": now + 3_600_000 }), |
| 15963 | ) |
| 15964 | .await; |
| 15965 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 15966 | |
| 15967 | // Within the grace counts as "due now" — accepted, like a plain future one. |
| 15968 | let res = common::create_homework_with( |
| 15969 | &app, |
| 15970 | &w.teacher, |
| 15971 | &w.instance, |
| 15972 | json!({ "title": "just now", "subject_id": w.subject, "due_at": now - 30_000 }), |
| 15973 | ) |
| 15974 | .await; |
| 15975 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 15976 | let hw = create_homework( |
| 15977 | &app, |
| 15978 | &w.teacher, |
| 15979 | &w.instance, |
| 15980 | &w.subject, |
| 15981 | "ch. 3", |
| 15982 | now + 3_600_000, |
| 15983 | ) |
| 15984 | .await; |
| 15985 | let res = send(&app, "GET", &format!("/homework/{hw}"), Some(&w.ali), None).await; |
| 15986 | assert_eq!(res.status, StatusCode::OK); |
| 15987 | assert_eq!(res.body["title"], "ch. 3"); |
| 15988 | assert_eq!(res.body["subject"], w.subject.as_str()); |
| 15989 | assert!( |
| 15990 | res.body["assigned"].is_null(), |
| 15991 | "whole-course stores no subset" |
| 15992 | ); |
| 15993 | } |
| 15994 | |
| 15995 | /// A subset assignment must never leak to the students it leaves out (404s, |
| 15996 | /// list omissions), off-course teachers are walled off, the cross-course list |
| 15997 | /// narrows per caller, and staff never submit. |
| 15998 | #[tokio::test] |
| 15999 | async fn homework_subset_hides_from_outsiders() { |
| 16000 | let (app, db) = app_and_db().await; |
| 16001 | let w = hw_world(&app, &db).await; |
| 16002 | let now = Timestamp::now().as_millis(); |
| 16003 | |
| 16004 | let res = common::create_homework_with( |
| 16005 | &app, |
| 16006 | &w.teacher, |
| 16007 | &w.instance, |
| 16008 | json!({ "title": "secret drill", "subject_id": w.subject, "due_at": now + 3_600_000, |
| 16009 | "assigned": [w.ali_id] }), |
| 16010 | ) |
| 16011 | .await; |
| 16012 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16013 | let hw = id_of(&res.body); |
| 16014 | |
| 16015 | // ali is named: both lists carry it and the fetch works. |
| 16016 | let uri = format!("/instances/{}/homework", w.instance); |
| 16017 | let res = send(&app, "GET", &uri, Some(&w.ali), None).await; |
| 16018 | assert_eq!(common::total(&res.body), 1); |
| 16019 | let res = send(&app, "GET", "/homework", Some(&w.ali), None).await; |
| 16020 | assert_eq!(common::total(&res.body), 1); |
| 16021 | // veli is enrolled but unnamed: the homework must not even seem to exist. |
| 16022 | let res = send(&app, "GET", &uri, Some(&w.veli), None).await; |
| 16023 | assert_eq!( |
| 16024 | common::total(&res.body), |
| 16025 | 0, |
| 16026 | "unnamed student sees no subset" |
| 16027 | ); |
| 16028 | let res = send(&app, "GET", "/homework", Some(&w.veli), None).await; |
| 16029 | assert_eq!(common::total(&res.body), 0); |
| 16030 | let res = send(&app, "GET", &format!("/homework/{hw}"), Some(&w.veli), None).await; |
| 16031 | assert_eq!(res.status, StatusCode::NOT_FOUND, "404, never a 403 leak"); |
| 16032 | let res = submit_hw(&app, &w.veli, &hw, Some("hi")).await; |
| 16033 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 16034 | |
| 16035 | // A teacher without management rights over the course is walled off. |
| 16036 | let rival = login_as(&app, &db, "rival", "teacher").await; |
| 16037 | let res = send(&app, "GET", &format!("/homework/{hw}"), Some(&rival), None).await; |
| 16038 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 16039 | let res = send( |
| 16040 | &app, |
| 16041 | "PATCH", |
| 16042 | &format!("/homework/{hw}"), |
| 16043 | Some(&rival), |
| 16044 | Some(json!({ "title": "hijack" })), |
| 16045 | ) |
| 16046 | .await; |
| 16047 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 16048 | let res = send( |
| 16049 | &app, |
| 16050 | "GET", |
| 16051 | &format!("/homework/{hw}/submissions"), |
| 16052 | Some(&rival), |
| 16053 | None, |
| 16054 | ) |
| 16055 | .await; |
| 16056 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 16057 | let res = grade_hw(&app, &rival, &hw, &w.ali_id, "done", None).await; |
| 16058 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 16059 | let res = send( |
| 16060 | &app, |
| 16061 | "DELETE", |
| 16062 | &format!("/homework/{hw}"), |
| 16063 | Some(&rival), |
| 16064 | None, |
| 16065 | ) |
| 16066 | .await; |
| 16067 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 16068 | |
| 16069 | // The cross-course list narrows per caller: manager+ everything, an |
| 16070 | // off-course teacher nothing, the managing teacher their course's rows. |
| 16071 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 16072 | let res = send(&app, "GET", "/homework", Some(&boss), None).await; |
| 16073 | assert_eq!(common::total(&res.body), 1); |
| 16074 | let res = send(&app, "GET", "/homework", Some(&rival), None).await; |
| 16075 | assert_eq!(common::total(&res.body), 0); |
| 16076 | let res = send(&app, "GET", "/homework", Some(&w.teacher), None).await; |
| 16077 | assert_eq!(common::total(&res.body), 1); |
| 16078 | |
| 16079 | // Staff never submit — a 403 on the live role, whatever they can see. |
| 16080 | let res = submit_hw(&app, &boss, &hw, Some("i am staff")).await; |
| 16081 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 16082 | let res = submit_hw(&app, &w.teacher, &hw, Some("me neither")).await; |
| 16083 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 16084 | } |
| 16085 | |
| 16086 | /// PATCH re-checks a newly set due date and subject, refuses a narrowing that |
| 16087 | /// would orphan existing work (naming the blockers), and leaves stored past |
| 16088 | /// due dates alone on unrelated edits. |
| 16089 | #[tokio::test] |
| 16090 | async fn homework_patch_rechecks_and_blocks_orphaning() { |
| 16091 | let (app, db) = app_and_db().await; |
| 16092 | let w = hw_world(&app, &db).await; |
| 16093 | let now = Timestamp::now().as_millis(); |
| 16094 | let res = common::create_homework_with( |
| 16095 | &app, |
| 16096 | &w.teacher, |
| 16097 | &w.instance, |
| 16098 | json!({ "title": "drill", "subject_id": w.subject, "due_at": now + 3_600_000, |
| 16099 | "assigned": [w.ali_id, w.veli_id] }), |
| 16100 | ) |
| 16101 | .await; |
| 16102 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16103 | let hw = id_of(&res.body); |
| 16104 | |
| 16105 | // A newly set due date must not be past… |
| 16106 | let res = send( |
| 16107 | &app, |
| 16108 | "PATCH", |
| 16109 | &format!("/homework/{hw}"), |
| 16110 | Some(&w.teacher), |
| 16111 | Some(json!({ "due_at": now - 120_000 })), |
| 16112 | ) |
| 16113 | .await; |
| 16114 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 16115 | |
| 16116 | // …and a new subject must be the course's own. |
| 16117 | let other_course = create_course(&app, &w.teacher, "physics").await; |
| 16118 | let foreign = create_subject(&app, &w.teacher, &other_course, "optics").await; |
| 16119 | let res = send( |
| 16120 | &app, |
| 16121 | "PATCH", |
| 16122 | &format!("/homework/{hw}"), |
| 16123 | Some(&w.teacher), |
| 16124 | Some(json!({ "subject_id": foreign })), |
| 16125 | ) |
| 16126 | .await; |
| 16127 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 16128 | let algebra2 = create_subject(&app, &w.teacher, &w.course, "algebra II").await; |
| 16129 | select_instance_subject(&app, &w.teacher, &w.instance, &algebra2).await; |
| 16130 | let res = send( |
| 16131 | &app, |
| 16132 | "PATCH", |
| 16133 | &format!("/homework/{hw}"), |
| 16134 | Some(&w.teacher), |
| 16135 | Some(json!({ "subject_id": algebra2 })), |
| 16136 | ) |
| 16137 | .await; |
| 16138 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16139 | assert_eq!(res.body["subject"], algebra2.as_str()); |
| 16140 | |
| 16141 | // ali submits; narrowing to veli alone would strand that work — refused, |
| 16142 | // naming the blocker. Narrowing to exactly ali passes. |
| 16143 | let res = submit_hw(&app, &w.ali, &hw, Some("done")).await; |
| 16144 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16145 | let res = send( |
| 16146 | &app, |
| 16147 | "PATCH", |
| 16148 | &format!("/homework/{hw}"), |
| 16149 | Some(&w.teacher), |
| 16150 | Some(json!({ "assigned": [w.veli_id] })), |
| 16151 | ) |
| 16152 | .await; |
| 16153 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 16154 | assert!( |
| 16155 | res.body["error"].as_str().unwrap().contains(&w.ali_id), |
| 16156 | "the 409 names whose work blocks: {}", |
| 16157 | res.body |
| 16158 | ); |
| 16159 | let res = send( |
| 16160 | &app, |
| 16161 | "PATCH", |
| 16162 | &format!("/homework/{hw}"), |
| 16163 | Some(&w.teacher), |
| 16164 | Some(json!({ "assigned": [w.ali_id] })), |
| 16165 | ) |
| 16166 | .await; |
| 16167 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16168 | |
| 16169 | // Widening back to the whole course always passes. |
| 16170 | let res = send( |
| 16171 | &app, |
| 16172 | "PATCH", |
| 16173 | &format!("/homework/{hw}"), |
| 16174 | Some(&w.teacher), |
| 16175 | Some(json!({ "assigned": [] })), |
| 16176 | ) |
| 16177 | .await; |
| 16178 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16179 | assert!(res.body["assigned"].is_null()); |
| 16180 | |
| 16181 | // A title-only edit on a graced, already-due homework keeps its stored |
| 16182 | // due date without tripping the not-past check. |
| 16183 | let old = create_homework( |
| 16184 | &app, |
| 16185 | &w.teacher, |
| 16186 | &w.instance, |
| 16187 | &w.subject, |
| 16188 | "old", |
| 16189 | now - 30_000, |
| 16190 | ) |
| 16191 | .await; |
| 16192 | let res = send( |
| 16193 | &app, |
| 16194 | "PATCH", |
| 16195 | &format!("/homework/{old}"), |
| 16196 | Some(&w.teacher), |
| 16197 | Some(json!({ "title": "renamed" })), |
| 16198 | ) |
| 16199 | .await; |
| 16200 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16201 | } |
| 16202 | |
| 16203 | /// Submitting creates once (201) and edits in place after (200): the |
| 16204 | /// first-hand-in stamp is pinned, text is replaced whole (omitting clears), |
| 16205 | /// and withdrawal removes it all. |
| 16206 | #[tokio::test] |
| 16207 | async fn homework_submission_lifecycle_and_stamps() { |
| 16208 | let (app, db) = app_and_db().await; |
| 16209 | let w = hw_world(&app, &db).await; |
| 16210 | let now = Timestamp::now().as_millis(); |
| 16211 | let hw = create_homework( |
| 16212 | &app, |
| 16213 | &w.teacher, |
| 16214 | &w.instance, |
| 16215 | &w.subject, |
| 16216 | "essay", |
| 16217 | now + 3_600_000, |
| 16218 | ) |
| 16219 | .await; |
| 16220 | |
| 16221 | let uri = format!("/homework/{hw}/submission"); |
| 16222 | let res = send(&app, "GET", &uri, Some(&w.ali), None).await; |
| 16223 | assert_eq!(res.status, StatusCode::NOT_FOUND, "nothing submitted yet"); |
| 16224 | |
| 16225 | let res = submit_hw(&app, &w.ali, &hw, Some("draft one")).await; |
| 16226 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16227 | assert_eq!(res.body["text"], "draft one"); |
| 16228 | assert_eq!(res.body["late"], false); |
| 16229 | let submitted_at = res.body["submitted_at"].as_i64().unwrap(); |
| 16230 | |
| 16231 | let res = submit_hw(&app, &w.ali, &hw, Some("draft two")).await; |
| 16232 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16233 | assert_eq!(res.body["text"], "draft two"); |
| 16234 | assert_eq!( |
| 16235 | res.body["submitted_at"].as_i64().unwrap(), |
| 16236 | submitted_at, |
| 16237 | "the first-submit stamp never moves" |
| 16238 | ); |
| 16239 | assert!(res.body["updated_at"].as_i64().unwrap() >= submitted_at); |
| 16240 | |
| 16241 | // The text rides whole in each submit: omitting it clears. |
| 16242 | let res = submit_hw(&app, &w.ali, &hw, None).await; |
| 16243 | assert_eq!(res.status, StatusCode::OK); |
| 16244 | assert!(res.body["text"].is_null()); |
| 16245 | |
| 16246 | // Reads are strictly own: veli asking gets veli's (absent) submission. |
| 16247 | let res = send(&app, "GET", &uri, Some(&w.ali), None).await; |
| 16248 | assert_eq!(res.status, StatusCode::OK); |
| 16249 | assert!(res.body["result"].is_null()); |
| 16250 | let res = send(&app, "GET", &uri, Some(&w.veli), None).await; |
| 16251 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 16252 | |
| 16253 | // Withdrawal, twice: gone, then nothing left to withdraw. |
| 16254 | let res = send(&app, "DELETE", &uri, Some(&w.ali), None).await; |
| 16255 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 16256 | let res = send(&app, "GET", &uri, Some(&w.ali), None).await; |
| 16257 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 16258 | let res = send(&app, "DELETE", &uri, Some(&w.ali), None).await; |
| 16259 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 16260 | } |
| 16261 | |
| 16262 | /// The late flag is computed against `due_at` on every read, and the roster |
| 16263 | /// computes `missing` for unsubmitted-past-due rows — no sleeping: a graced |
| 16264 | /// creation plants the due date ~30s in the past. |
| 16265 | #[tokio::test] |
| 16266 | async fn homework_lateness_is_computed_across_due() { |
| 16267 | let (app, db) = app_and_db().await; |
| 16268 | let w = hw_world(&app, &db).await; |
| 16269 | let now = Timestamp::now().as_millis(); |
| 16270 | |
| 16271 | let overdue = create_homework( |
| 16272 | &app, |
| 16273 | &w.teacher, |
| 16274 | &w.instance, |
| 16275 | &w.subject, |
| 16276 | "late one", |
| 16277 | now - 30_000, |
| 16278 | ) |
| 16279 | .await; |
| 16280 | let res = submit_hw(&app, &w.ali, &overdue, Some("sorry")).await; |
| 16281 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16282 | assert_eq!(res.body["late"], true, "touched after due_at"); |
| 16283 | |
| 16284 | let open = create_homework( |
| 16285 | &app, |
| 16286 | &w.teacher, |
| 16287 | &w.instance, |
| 16288 | &w.subject, |
| 16289 | "open one", |
| 16290 | now + 3_600_000, |
| 16291 | ) |
| 16292 | .await; |
| 16293 | let res = submit_hw(&app, &w.ali, &open, Some("early")).await; |
| 16294 | assert_eq!(res.body["late"], false); |
| 16295 | |
| 16296 | // The roster mirrors the flag and derives `missing` for veli, who never |
| 16297 | // submitted — a computation, not a teacher verdict. |
| 16298 | let res = send( |
| 16299 | &app, |
| 16300 | "GET", |
| 16301 | &format!("/homework/{overdue}/submissions"), |
| 16302 | Some(&w.teacher), |
| 16303 | None, |
| 16304 | ) |
| 16305 | .await; |
| 16306 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16307 | assert_eq!(common::total(&res.body), 2); |
| 16308 | let rows = common::items(&res.body); |
| 16309 | let ali_row = rows |
| 16310 | .iter() |
| 16311 | .find(|row| row["user"] == w.ali_id.as_str()) |
| 16312 | .unwrap(); |
| 16313 | assert_eq!(ali_row["submission"]["late"], true); |
| 16314 | assert_eq!(ali_row["missing"], false); |
| 16315 | assert_eq!(ali_row["unenrolled"], false); |
| 16316 | let veli_row = rows |
| 16317 | .iter() |
| 16318 | .find(|row| row["user"] == w.veli_id.as_str()) |
| 16319 | .unwrap(); |
| 16320 | assert!(veli_row["submission"].is_null()); |
| 16321 | assert_eq!(veli_row["missing"], true, "unsubmitted past due"); |
| 16322 | } |
| 16323 | |
| 16324 | /// Grading walls: students never grade, nobody grades themselves, and the |
| 16325 | /// target must exist, hold the student role, be enrolled, and be in the |
| 16326 | /// audience; the verdict set is closed and the mark bounded. A regrade |
| 16327 | /// overwrites its one row, and the student reads the verdict back. |
| 16328 | #[tokio::test] |
| 16329 | async fn homework_grading_gates_and_bounds() { |
| 16330 | let (app, db) = app_and_db().await; |
| 16331 | let w = hw_world(&app, &db).await; |
| 16332 | let now = Timestamp::now().as_millis(); |
| 16333 | let res = common::create_homework_with( |
| 16334 | &app, |
| 16335 | &w.teacher, |
| 16336 | &w.instance, |
| 16337 | json!({ "title": "drill", "subject_id": w.subject, "due_at": now + 3_600_000, |
| 16338 | "assigned": [w.ali_id] }), |
| 16339 | ) |
| 16340 | .await; |
| 16341 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16342 | let hw = id_of(&res.body); |
| 16343 | let teacher_id = me_id(&app, &w.teacher).await; |
| 16344 | |
| 16345 | let res = grade_hw(&app, &w.ali, &hw, &w.ali_id, "done", None).await; |
| 16346 | assert_eq!(res.status, StatusCode::FORBIDDEN, "students never grade"); |
| 16347 | let res = grade_hw(&app, &w.teacher, &hw, &teacher_id, "done", None).await; |
| 16348 | assert_eq!(res.status, StatusCode::FORBIDDEN, "no self-grading"); |
| 16349 | let res = grade_hw(&app, &w.teacher, &hw, common::ABSENT_ID, "done", None).await; |
| 16350 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "target must exist"); |
| 16351 | let rival = login_as(&app, &db, "rival", "teacher").await; |
| 16352 | let rival_id = me_id(&app, &rival).await; |
| 16353 | let res = grade_hw(&app, &w.teacher, &hw, &rival_id, "done", None).await; |
| 16354 | assert_eq!( |
| 16355 | res.status, |
| 16356 | StatusCode::BAD_REQUEST, |
| 16357 | "only students carry grades" |
| 16358 | ); |
| 16359 | let mehmet = login(&app, "mehmet").await; |
| 16360 | let mehmet_id = me_id(&app, &mehmet).await; |
| 16361 | let res = grade_hw(&app, &w.teacher, &hw, &mehmet_id, "done", None).await; |
| 16362 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "must be enrolled"); |
| 16363 | let res = grade_hw(&app, &w.teacher, &hw, &w.veli_id, "done", None).await; |
| 16364 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "outside the audience"); |
| 16365 | let res = grade_hw(&app, &w.teacher, &hw, &w.ali_id, "late", None).await; |
| 16366 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "junk status"); |
| 16367 | let res = grade_hw(&app, &w.teacher, &hw, &w.ali_id, "done", Some(101)).await; |
| 16368 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "mark over 100"); |
| 16369 | let res = grade_hw(&app, &w.teacher, &hw, &w.ali_id, "done", Some(-1)).await; |
| 16370 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "negative mark"); |
| 16371 | |
| 16372 | // 200 upsert semantics: the regrade overwrites, never stacks. |
| 16373 | let res = grade_hw(&app, &w.teacher, &hw, &w.ali_id, "incomplete", None).await; |
| 16374 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16375 | assert_eq!(res.body["status"], "incomplete"); |
| 16376 | assert!(res.body["mark"].is_null()); |
| 16377 | let res = grade_hw(&app, &w.teacher, &hw, &w.ali_id, "done", Some(85)).await; |
| 16378 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16379 | assert_eq!(res.body["mark"], 85); |
| 16380 | assert_eq!(hw_row_count(&db, "homework_result").await, 1); |
| 16381 | |
| 16382 | // The student reads their own verdict; ungraded means 404, for anyone. |
| 16383 | let uri = format!("/homework/{hw}/result"); |
| 16384 | let res = send(&app, "GET", &uri, Some(&w.ali), None).await; |
| 16385 | assert_eq!(res.status, StatusCode::OK); |
| 16386 | assert_eq!(res.body["status"], "done"); |
| 16387 | assert_eq!(res.body["mark"], 85); |
| 16388 | let res = send(&app, "GET", &uri, Some(&w.veli), None).await; |
| 16389 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 16390 | } |
| 16391 | |
| 16392 | /// A stored grade freezes the submission — text, files, withdrawal — until |
| 16393 | /// The files-per-submission cap is the same counter guard as the note-file one, |
| 16394 | /// on the submission row. Nine seeded files plus four racers for the last slot: |
| 16395 | /// exactly one may win, and the delete must give the slot back or the next |
| 16396 | /// upload is refused forever. |
| 16397 | #[tokio::test] |
| 16398 | async fn concurrent_homework_uploads_never_exceed_the_file_cap() { |
| 16399 | let (app, db) = app_and_db().await; |
| 16400 | let w = hw_world(&app, &db).await; |
| 16401 | let now = Timestamp::now().as_millis(); |
| 16402 | let hw = create_homework( |
| 16403 | &app, |
| 16404 | &w.teacher, |
| 16405 | &w.instance, |
| 16406 | &w.subject, |
| 16407 | "essay", |
| 16408 | now + 3_600_000, |
| 16409 | ) |
| 16410 | .await; |
| 16411 | let res = submit_hw(&app, &w.ali, &hw, Some("v1")).await; |
| 16412 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16413 | for i in 0..9 { |
| 16414 | let up = upload_hw_file(&app, &w.ali, &hw, &format!("f{i}.txt"), "text/plain", b"x").await; |
| 16415 | assert_eq!(up.status, StatusCode::CREATED, "seed file {i}: {}", up.body); |
| 16416 | } |
| 16417 | |
| 16418 | let racers = tokio::join!( |
| 16419 | upload_hw_file(&app, &w.ali, &hw, "r0.txt", "text/plain", b"x"), |
| 16420 | upload_hw_file(&app, &w.ali, &hw, "r1.txt", "text/plain", b"x"), |
| 16421 | upload_hw_file(&app, &w.ali, &hw, "r2.txt", "text/plain", b"x"), |
| 16422 | upload_hw_file(&app, &w.ali, &hw, "r3.txt", "text/plain", b"x"), |
| 16423 | ); |
| 16424 | let statuses = [ |
| 16425 | racers.0.status, |
| 16426 | racers.1.status, |
| 16427 | racers.2.status, |
| 16428 | racers.3.status, |
| 16429 | ]; |
| 16430 | for status in statuses { |
| 16431 | assert!( |
| 16432 | status == StatusCode::CREATED || status == StatusCode::CONFLICT, |
| 16433 | "a lost cap race must be a 409, got {status}" |
| 16434 | ); |
| 16435 | } |
| 16436 | let list = send( |
| 16437 | &app, |
| 16438 | "GET", |
| 16439 | &format!("/homework/{hw}/submission"), |
| 16440 | Some(&w.ali), |
| 16441 | None, |
| 16442 | ) |
| 16443 | .await; |
| 16444 | let files = list.body["files"].as_array().expect("files").clone(); |
| 16445 | assert_eq!( |
| 16446 | files.len(), |
| 16447 | 10, |
| 16448 | "the cap must hold exactly under concurrency, statuses={statuses:?}" |
| 16449 | ); |
| 16450 | |
| 16451 | // A deleted file frees its slot again — the counter is not a ratchet. |
| 16452 | let fid = files[0]["id"].as_str().expect("file id").to_string(); |
| 16453 | let res = send( |
| 16454 | &app, |
| 16455 | "DELETE", |
| 16456 | &format!("/homework/{hw}/submission/files/{fid}"), |
| 16457 | Some(&w.ali), |
| 16458 | None, |
| 16459 | ) |
| 16460 | .await; |
| 16461 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 16462 | let up = upload_hw_file(&app, &w.ali, &hw, "after.txt", "text/plain", b"x").await; |
| 16463 | assert_eq!( |
| 16464 | up.status, |
| 16465 | StatusCode::CREATED, |
| 16466 | "the freed slot must be reusable: {}", |
| 16467 | up.body |
| 16468 | ); |
| 16469 | } |
| 16470 | |
| 16471 | /// the teacher removes it; and work never handed in can be graded `missing`, |
| 16472 | /// a verdict the student reads from `/result` despite having no submission. |
| 16473 | #[tokio::test] |
| 16474 | async fn homework_grade_freezes_until_removed() { |
| 16475 | let (app, db) = app_and_db().await; |
| 16476 | let w = hw_world(&app, &db).await; |
| 16477 | let now = Timestamp::now().as_millis(); |
| 16478 | let hw = create_homework( |
| 16479 | &app, |
| 16480 | &w.teacher, |
| 16481 | &w.instance, |
| 16482 | &w.subject, |
| 16483 | "essay", |
| 16484 | now + 3_600_000, |
| 16485 | ) |
| 16486 | .await; |
| 16487 | |
| 16488 | let res = submit_hw(&app, &w.ali, &hw, Some("v1")).await; |
| 16489 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16490 | let up = upload_hw_file(&app, &w.ali, &hw, "draft.txt", "text/plain", b"notes").await; |
| 16491 | assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); |
| 16492 | let fid = id_of(&up.body); |
| 16493 | |
| 16494 | let res = grade_hw(&app, &w.teacher, &hw, &w.ali_id, "incomplete", None).await; |
| 16495 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16496 | let res = submit_hw(&app, &w.ali, &hw, Some("v2")).await; |
| 16497 | assert_eq!(res.status, StatusCode::CONFLICT, "text frozen"); |
| 16498 | let res = upload_hw_file(&app, &w.ali, &hw, "late.txt", "text/plain", b"more").await; |
| 16499 | assert_eq!(res.status, StatusCode::CONFLICT, "file add frozen"); |
| 16500 | let res = send( |
| 16501 | &app, |
| 16502 | "DELETE", |
| 16503 | &format!("/homework/{hw}/submission/files/{fid}"), |
| 16504 | Some(&w.ali), |
| 16505 | None, |
| 16506 | ) |
| 16507 | .await; |
| 16508 | assert_eq!(res.status, StatusCode::CONFLICT, "file delete frozen"); |
| 16509 | let res = send( |
| 16510 | &app, |
| 16511 | "DELETE", |
| 16512 | &format!("/homework/{hw}/submission"), |
| 16513 | Some(&w.ali), |
| 16514 | None, |
| 16515 | ) |
| 16516 | .await; |
| 16517 | assert_eq!(res.status, StatusCode::CONFLICT, "withdrawal frozen"); |
| 16518 | // The grade rides on the student's own submission read. |
| 16519 | let res = send( |
| 16520 | &app, |
| 16521 | "GET", |
| 16522 | &format!("/homework/{hw}/submission"), |
| 16523 | Some(&w.ali), |
| 16524 | None, |
| 16525 | ) |
| 16526 | .await; |
| 16527 | assert_eq!(res.body["result"]["status"], "incomplete"); |
| 16528 | |
| 16529 | // Un-grading reopens the work; a second removal finds nothing. |
| 16530 | let uri = format!("/homework/{hw}/results/{}", w.ali_id); |
| 16531 | let res = send(&app, "DELETE", &uri, Some(&w.teacher), None).await; |
| 16532 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 16533 | let res = submit_hw(&app, &w.ali, &hw, Some("v2")).await; |
| 16534 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16535 | let res = send(&app, "DELETE", &uri, Some(&w.teacher), None).await; |
| 16536 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 16537 | |
| 16538 | // Never-submitted work still takes a `missing` verdict, and `/result` is |
| 16539 | // where its student reads it — the submission endpoints have nothing. |
| 16540 | let res = grade_hw(&app, &w.teacher, &hw, &w.veli_id, "missing", None).await; |
| 16541 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16542 | let res = send( |
| 16543 | &app, |
| 16544 | "GET", |
| 16545 | &format!("/homework/{hw}/submission"), |
| 16546 | Some(&w.veli), |
| 16547 | None, |
| 16548 | ) |
| 16549 | .await; |
| 16550 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 16551 | let res = send( |
| 16552 | &app, |
| 16553 | "GET", |
| 16554 | &format!("/homework/{hw}/result"), |
| 16555 | Some(&w.veli), |
| 16556 | None, |
| 16557 | ) |
| 16558 | .await; |
| 16559 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16560 | assert_eq!(res.body["status"], "missing"); |
| 16561 | } |
| 16562 | |
| 16563 | /// Files round-trip: a photo-first upload auto-creates the submission, the |
| 16564 | /// owner and the managing teacher download the exact bytes as a forced |
| 16565 | /// attachment, file ids are scoped to their homework, other students see |
| 16566 | /// nothing, and a delete unlinks the blob. |
| 16567 | #[tokio::test] |
| 16568 | async fn homework_files_roundtrip_and_scope() { |
| 16569 | let (app, db) = app_and_db().await; |
| 16570 | let w = hw_world(&app, &db).await; |
| 16571 | let now = Timestamp::now().as_millis(); |
| 16572 | let hw = create_homework( |
| 16573 | &app, |
| 16574 | &w.teacher, |
| 16575 | &w.instance, |
| 16576 | &w.subject, |
| 16577 | "photo hw", |
| 16578 | now + 3_600_000, |
| 16579 | ) |
| 16580 | .await; |
| 16581 | |
| 16582 | let bytes = b"%PDF-1.4 homework \x00\x01".to_vec(); |
| 16583 | let up = upload_hw_file(&app, &w.ali, &hw, "odev.pdf", "application/pdf", &bytes).await; |
| 16584 | assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); |
| 16585 | assert_eq!(up.body["name"], "odev.pdf"); |
| 16586 | assert_eq!(up.body["content_type"], "application/pdf"); |
| 16587 | assert_eq!(up.body["size"], bytes.len() as i64); |
| 16588 | let fid = id_of(&up.body); |
| 16589 | let res = send( |
| 16590 | &app, |
| 16591 | "GET", |
| 16592 | &format!("/homework/{hw}/submission"), |
| 16593 | Some(&w.ali), |
| 16594 | None, |
| 16595 | ) |
| 16596 | .await; |
| 16597 | assert_eq!(res.status, StatusCode::OK, "photo-first auto-creates"); |
| 16598 | assert!(res.body["text"].is_null()); |
| 16599 | assert_eq!(res.body["files"].as_array().unwrap().len(), 1); |
| 16600 | |
| 16601 | // Owner and managing teacher read the same bytes — always an attachment: |
| 16602 | // homework files take any content type, so inline HTML/SVG would be XSS. |
| 16603 | let file_uri = format!("/homework/{hw}/submission/files/{fid}"); |
| 16604 | for viewer in [&w.ali, &w.teacher] { |
| 16605 | let (status, headers, body) = |
| 16606 | common::send_raw(&app, "GET", &file_uri, Some(viewer), None, Vec::new()).await; |
| 16607 | assert_eq!(status, StatusCode::OK); |
| 16608 | assert_eq!(body, bytes); |
| 16609 | assert_eq!(headers["content-type"], "application/pdf"); |
| 16610 | assert_eq!( |
| 16611 | headers["content-disposition"], |
| 16612 | "attachment; filename=\"odev.pdf\"; filename*=UTF-8''odev.pdf" |
| 16613 | ); |
| 16614 | } |
| 16615 | // The id only resolves under its own homework, and never for a classmate. |
| 16616 | let other = create_homework( |
| 16617 | &app, |
| 16618 | &w.teacher, |
| 16619 | &w.instance, |
| 16620 | &w.subject, |
| 16621 | "other", |
| 16622 | now + 3_600_000, |
| 16623 | ) |
| 16624 | .await; |
| 16625 | let (status, _, _) = common::send_raw( |
| 16626 | &app, |
| 16627 | "GET", |
| 16628 | &format!("/homework/{other}/submission/files/{fid}"), |
| 16629 | Some(&w.teacher), |
| 16630 | None, |
| 16631 | Vec::new(), |
| 16632 | ) |
| 16633 | .await; |
| 16634 | assert_eq!(status, StatusCode::NOT_FOUND, "scoped to its homework"); |
| 16635 | let (status, _, _) = |
| 16636 | common::send_raw(&app, "GET", &file_uri, Some(&w.veli), None, Vec::new()).await; |
| 16637 | assert_eq!(status, StatusCode::NOT_FOUND, "classmates see nothing"); |
| 16638 | |
| 16639 | // Delete removes the row and unlinks the blob. |
| 16640 | let keys = homework_blob_keys(&db).await; |
| 16641 | assert_eq!(keys.len(), 1); |
| 16642 | let res = send(&app, "DELETE", &file_uri, Some(&w.ali), None).await; |
| 16643 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 16644 | assert!( |
| 16645 | !common::blob_dir().join(&keys[0]).exists(), |
| 16646 | "blob must be unlinked with its row" |
| 16647 | ); |
| 16648 | let res = send( |
| 16649 | &app, |
| 16650 | "GET", |
| 16651 | &format!("/homework/{hw}/submission"), |
| 16652 | Some(&w.ali), |
| 16653 | None, |
| 16654 | ) |
| 16655 | .await; |
| 16656 | assert_eq!(res.body["files"].as_array().unwrap().len(), 0); |
| 16657 | } |
| 16658 | |
| 16659 | /// File limits: empty uploads are rejected, the 11th file trips the cap, and |
| 16660 | /// the school's `max_file_bytes` bounds each file (413 over, 201 at). |
| 16661 | #[tokio::test] |
| 16662 | async fn homework_file_limits_follow_cap_and_settings() { |
| 16663 | let (app, db) = app_and_db().await; |
| 16664 | let w = hw_world(&app, &db).await; |
| 16665 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 16666 | let now = Timestamp::now().as_millis(); |
| 16667 | let hw = create_homework( |
| 16668 | &app, |
| 16669 | &w.teacher, |
| 16670 | &w.instance, |
| 16671 | &w.subject, |
| 16672 | "many files", |
| 16673 | now + 3_600_000, |
| 16674 | ) |
| 16675 | .await; |
| 16676 | |
| 16677 | let res = upload_hw_file(&app, &w.ali, &hw, "empty.txt", "text/plain", b"").await; |
| 16678 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 16679 | |
| 16680 | for i in 0..10 { |
| 16681 | let res = upload_hw_file(&app, &w.ali, &hw, &format!("f{i}.txt"), "text/plain", b"x").await; |
| 16682 | assert_eq!(res.status, StatusCode::CREATED, "file {i}: {}", res.body); |
| 16683 | } |
| 16684 | let res = upload_hw_file(&app, &w.ali, &hw, "f10.txt", "text/plain", b"x").await; |
| 16685 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 16686 | assert_eq!( |
| 16687 | homework_blob_keys(&db).await.len(), |
| 16688 | 10, |
| 16689 | "the losing upload leaves no row" |
| 16690 | ); |
| 16691 | |
| 16692 | let res = send( |
| 16693 | &app, |
| 16694 | "PATCH", |
| 16695 | "/settings", |
| 16696 | Some(&boss), |
| 16697 | Some(json!({ "max_file_bytes": 1024 })), |
| 16698 | ) |
| 16699 | .await; |
| 16700 | assert_eq!(res.status, StatusCode::OK); |
| 16701 | let hw2 = create_homework( |
| 16702 | &app, |
| 16703 | &w.teacher, |
| 16704 | &w.instance, |
| 16705 | &w.subject, |
| 16706 | "sized", |
| 16707 | now + 3_600_000, |
| 16708 | ) |
| 16709 | .await; |
| 16710 | let res = upload_hw_file(&app, &w.ali, &hw2, "big.bin", "", &vec![7u8; 1025]).await; |
| 16711 | assert_eq!(res.status, StatusCode::PAYLOAD_TOO_LARGE, "{}", res.body); |
| 16712 | let res = upload_hw_file(&app, &w.ali, &hw2, "fits.bin", "", &vec![7u8; 1024]).await; |
| 16713 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16714 | assert_eq!(res.body["content_type"], "application/octet-stream"); |
| 16715 | } |
| 16716 | |
| 16717 | /// The roster carries the whole audience — and keeps a straggler's work |
| 16718 | /// visible (flagged `unenrolled`) instead of letting it vanish; a subset |
| 16719 | /// roster lists the named students only; the list pages. |
| 16720 | #[tokio::test] |
| 16721 | async fn homework_roster_covers_audience_and_stragglers() { |
| 16722 | let (app, db) = app_and_db().await; |
| 16723 | let w = hw_world(&app, &db).await; |
| 16724 | let now = Timestamp::now().as_millis(); |
| 16725 | |
| 16726 | let hw = create_homework( |
| 16727 | &app, |
| 16728 | &w.teacher, |
| 16729 | &w.instance, |
| 16730 | &w.subject, |
| 16731 | "for all", |
| 16732 | now + 3_600_000, |
| 16733 | ) |
| 16734 | .await; |
| 16735 | let roster_uri = format!("/homework/{hw}/submissions"); |
| 16736 | let res = send(&app, "GET", &roster_uri, Some(&w.teacher), None).await; |
| 16737 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16738 | assert_eq!(common::total(&res.body), 2, "whole course, both enrolled"); |
| 16739 | |
| 16740 | // ali submits, then leaves the course: the work stays on the roster, |
| 16741 | // flagged — and grading the straggler is refused. |
| 16742 | let res = submit_hw(&app, &w.ali, &hw, Some("mine")).await; |
| 16743 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16744 | let res = send( |
| 16745 | &app, |
| 16746 | "DELETE", |
| 16747 | &format!("/instances/{}/enrollments/{}", w.instance, w.ali_id), |
| 16748 | Some(&w.teacher), |
| 16749 | None, |
| 16750 | ) |
| 16751 | .await; |
| 16752 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 16753 | let res = send(&app, "GET", &roster_uri, Some(&w.teacher), None).await; |
| 16754 | assert_eq!(common::total(&res.body), 2, "the straggler's work stays"); |
| 16755 | let rows = common::items(&res.body); |
| 16756 | let ali_row = rows |
| 16757 | .iter() |
| 16758 | .find(|row| row["user"] == w.ali_id.as_str()) |
| 16759 | .unwrap(); |
| 16760 | assert_eq!(ali_row["unenrolled"], true); |
| 16761 | assert_eq!(ali_row["submission"]["text"], "mine"); |
| 16762 | let res = grade_hw(&app, &w.teacher, &hw, &w.ali_id, "done", None).await; |
| 16763 | assert_eq!( |
| 16764 | res.status, |
| 16765 | StatusCode::BAD_REQUEST, |
| 16766 | "no grading the unenrolled" |
| 16767 | ); |
| 16768 | |
| 16769 | // The roster pages like every list. |
| 16770 | let res = send( |
| 16771 | &app, |
| 16772 | "GET", |
| 16773 | &format!("{roster_uri}?limit=1&offset=1"), |
| 16774 | Some(&w.teacher), |
| 16775 | None, |
| 16776 | ) |
| 16777 | .await; |
| 16778 | assert_eq!(common::total(&res.body), 2); |
| 16779 | assert_eq!(common::items(&res.body).len(), 1); |
| 16780 | assert_eq!(res.body["limit"], 1); |
| 16781 | assert_eq!(res.body["offset"], 1); |
| 16782 | |
| 16783 | // A subset roster is the named students, nobody else. |
| 16784 | enroll(&app, &w.teacher, &w.instance, &w.ali_id).await; |
| 16785 | let res = common::create_homework_with( |
| 16786 | &app, |
| 16787 | &w.teacher, |
| 16788 | &w.instance, |
| 16789 | json!({ "title": "subset", "subject_id": w.subject, "due_at": now + 3_600_000, |
| 16790 | "assigned": [w.ali_id] }), |
| 16791 | ) |
| 16792 | .await; |
| 16793 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16794 | let subset_hw = id_of(&res.body); |
| 16795 | let res = send( |
| 16796 | &app, |
| 16797 | "GET", |
| 16798 | &format!("/homework/{subset_hw}/submissions"), |
| 16799 | Some(&w.teacher), |
| 16800 | None, |
| 16801 | ) |
| 16802 | .await; |
| 16803 | assert_eq!(common::total(&res.body), 1); |
| 16804 | assert_eq!(common::items(&res.body)[0]["user"], w.ali_id.as_str()); |
| 16805 | } |
| 16806 | |
| 16807 | /// The observer report: full for manager+ and a linked parent, narrowed to |
| 16808 | /// managed courses for a teacher, walled for everyone else — and it carries |
| 16809 | /// statuses, marks, and flags, never file bytes. |
| 16810 | #[tokio::test] |
| 16811 | async fn homework_report_serves_observers_only() { |
| 16812 | let (app, db) = app_and_db().await; |
| 16813 | let w = hw_world(&app, &db).await; |
| 16814 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 16815 | let now = Timestamp::now().as_millis(); |
| 16816 | |
| 16817 | // A second şube under another teacher; ali sits in both. |
| 16818 | let rival = login_as(&app, &db, "rival", "teacher").await; |
| 16819 | let mudur2 = login_as(&app, &db, "hw.mudur2", "manager").await; |
| 16820 | let t2 = taught_under(&app, &mudur2, &rival, "physics").await; |
| 16821 | let subject2 = create_subject(&app, &rival, &t2.course, "optics").await; |
| 16822 | add_member(&app, &mudur2, &t2.class, &w.ali_id).await; |
| 16823 | |
| 16824 | // Three states across the two courses: graded, submitted-late, missing. |
| 16825 | let graded = create_homework( |
| 16826 | &app, |
| 16827 | &w.teacher, |
| 16828 | &w.instance, |
| 16829 | &w.subject, |
| 16830 | "graded", |
| 16831 | now + 3_600_000, |
| 16832 | ) |
| 16833 | .await; |
| 16834 | let res = submit_hw(&app, &w.ali, &graded, Some("done")).await; |
| 16835 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16836 | let res = grade_hw(&app, &w.teacher, &graded, &w.ali_id, "done", Some(90)).await; |
| 16837 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16838 | let overdue = create_homework( |
| 16839 | &app, |
| 16840 | &rival, |
| 16841 | &t2.instance, |
| 16842 | &subject2, |
| 16843 | "overdue", |
| 16844 | now - 30_000, |
| 16845 | ) |
| 16846 | .await; |
| 16847 | let res = submit_hw(&app, &w.ali, &overdue, Some("late")).await; |
| 16848 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 16849 | let missing = create_homework( |
| 16850 | &app, |
| 16851 | &rival, |
| 16852 | &t2.instance, |
| 16853 | &subject2, |
| 16854 | "skipped", |
| 16855 | now - 30_000, |
| 16856 | ) |
| 16857 | .await; |
| 16858 | |
| 16859 | // The admin reads all three rows, each in its computed state. |
| 16860 | let report_uri = format!("/homework/report/{}", w.ali_id); |
| 16861 | let res = send(&app, "GET", &report_uri, Some(&admin), None).await; |
| 16862 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16863 | assert_eq!(common::total(&res.body), 3); |
| 16864 | let rows = common::items(&res.body); |
| 16865 | let graded_row = rows |
| 16866 | .iter() |
| 16867 | .find(|row| row["homework"] == graded.as_str()) |
| 16868 | .unwrap(); |
| 16869 | assert_eq!(graded_row["submitted"], true); |
| 16870 | assert_eq!(graded_row["late"], false); |
| 16871 | assert_eq!(graded_row["result"]["status"], "done"); |
| 16872 | assert_eq!(graded_row["result"]["mark"], 90); |
| 16873 | let late_row = rows |
| 16874 | .iter() |
| 16875 | .find(|row| row["homework"] == overdue.as_str()) |
| 16876 | .unwrap(); |
| 16877 | assert_eq!(late_row["late"], true); |
| 16878 | assert_eq!(late_row["missing"], false); |
| 16879 | assert!(late_row["result"].is_null()); |
| 16880 | let missing_row = rows |
| 16881 | .iter() |
| 16882 | .find(|row| row["homework"] == missing.as_str()) |
| 16883 | .unwrap(); |
| 16884 | assert_eq!(missing_row["submitted"], false); |
| 16885 | assert_eq!(missing_row["missing"], true); |
| 16886 | |
| 16887 | // A teacher reads only the slice they manage. |
| 16888 | let res = send(&app, "GET", &report_uri, Some(&w.teacher), None).await; |
| 16889 | assert_eq!(common::total(&res.body), 1); |
| 16890 | assert_eq!( |
| 16891 | common::items(&res.body)[0]["class_course"], |
| 16892 | w.instance.as_str() |
| 16893 | ); |
| 16894 | |
| 16895 | // A linked parent reads all of it (paged like every list)… |
| 16896 | let mom = login_as(&app, &db, "mom", "parent").await; |
| 16897 | let mom_id = me_id(&app, &mom).await; |
| 16898 | let res = send( |
| 16899 | &app, |
| 16900 | "POST", |
| 16901 | &format!("/users/{mom_id}/students"), |
| 16902 | Some(&admin), |
| 16903 | Some(json!({ "user_id": w.ali_id })), |
| 16904 | ) |
| 16905 | .await; |
| 16906 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 16907 | let res = send(&app, "GET", &report_uri, Some(&mom), None).await; |
| 16908 | assert_eq!(res.status, StatusCode::OK); |
| 16909 | assert_eq!(common::total(&res.body), 3); |
| 16910 | let res = send( |
| 16911 | &app, |
| 16912 | "GET", |
| 16913 | &format!("{report_uri}?limit=2&offset=2"), |
| 16914 | Some(&mom), |
| 16915 | None, |
| 16916 | ) |
| 16917 | .await; |
| 16918 | assert_eq!(common::total(&res.body), 3); |
| 16919 | assert_eq!(common::items(&res.body).len(), 1); |
| 16920 | |
| 16921 | // …but never the underlying work: no submission reads, no file bytes. |
| 16922 | let up = upload_hw_file(&app, &w.ali, &overdue, "p.png", "image/png", b"png").await; |
| 16923 | assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); |
| 16924 | let fid = id_of(&up.body); |
| 16925 | let res = send( |
| 16926 | &app, |
| 16927 | "GET", |
| 16928 | &format!("/homework/{overdue}/submission"), |
| 16929 | Some(&mom), |
| 16930 | None, |
| 16931 | ) |
| 16932 | .await; |
| 16933 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 16934 | let (status, _, _) = common::send_raw( |
| 16935 | &app, |
| 16936 | "GET", |
| 16937 | &format!("/homework/{overdue}/submission/files/{fid}"), |
| 16938 | Some(&mom), |
| 16939 | None, |
| 16940 | Vec::new(), |
| 16941 | ) |
| 16942 | .await; |
| 16943 | assert_eq!(status, StatusCode::FORBIDDEN, "reports, never bytes"); |
| 16944 | |
| 16945 | // Unlinked parent, the student themselves, and a ghost target all fail. |
| 16946 | let dad = login_as(&app, &db, "dad", "parent").await; |
| 16947 | let res = send(&app, "GET", &report_uri, Some(&dad), None).await; |
| 16948 | assert_eq!(res.status, StatusCode::FORBIDDEN, "unlinked parent"); |
| 16949 | let res = send(&app, "GET", &report_uri, Some(&w.ali), None).await; |
| 16950 | assert_eq!( |
| 16951 | res.status, |
| 16952 | StatusCode::FORBIDDEN, |
| 16953 | "self-reads use /homework" |
| 16954 | ); |
| 16955 | let res = send( |
| 16956 | &app, |
| 16957 | "GET", |
| 16958 | &format!("/homework/report/{}", common::ABSENT_ID), |
| 16959 | Some(&admin), |
| 16960 | None, |
| 16961 | ) |
| 16962 | .await; |
| 16963 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 16964 | } |
| 16965 | |
| 16966 | /// Every delete path collects its garbage: withdrawing a submission, deleting |
| 16967 | /// a homework, and deleting the whole course each remove the database rows |
| 16968 | /// *and* the blobs on disk. |
| 16969 | #[tokio::test] |
| 16970 | async fn homework_gc_removes_rows_and_blobs() { |
| 16971 | let (app, db) = app_and_db().await; |
| 16972 | let w = hw_world(&app, &db).await; |
| 16973 | let now = Timestamp::now().as_millis(); |
| 16974 | |
| 16975 | let hw1 = create_homework( |
| 16976 | &app, |
| 16977 | &w.teacher, |
| 16978 | &w.instance, |
| 16979 | &w.subject, |
| 16980 | "one", |
| 16981 | now + 3_600_000, |
| 16982 | ) |
| 16983 | .await; |
| 16984 | let hw2 = create_homework( |
| 16985 | &app, |
| 16986 | &w.teacher, |
| 16987 | &w.instance, |
| 16988 | &w.subject, |
| 16989 | "two", |
| 16990 | now + 3_600_000, |
| 16991 | ) |
| 16992 | .await; |
| 16993 | for (cookie, hw, name) in [ |
| 16994 | (&w.ali, &hw1, "a.txt"), |
| 16995 | (&w.veli, &hw1, "b.txt"), |
| 16996 | (&w.ali, &hw2, "c.txt"), |
| 16997 | ] { |
| 16998 | let res = upload_hw_file(&app, cookie, hw, name, "text/plain", b"data").await; |
| 16999 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 17000 | } |
| 17001 | let res = grade_hw(&app, &w.teacher, &hw1, &w.veli_id, "done", None).await; |
| 17002 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17003 | let keys = homework_blob_keys(&db).await; |
| 17004 | assert_eq!(keys.len(), 3); |
| 17005 | for key in &keys { |
| 17006 | assert!(common::blob_dir().join(key).exists(), "blob {key} on disk"); |
| 17007 | } |
| 17008 | |
| 17009 | // Withdrawing a submission takes its file rows and blobs. |
| 17010 | let res = send( |
| 17011 | &app, |
| 17012 | "DELETE", |
| 17013 | &format!("/homework/{hw2}/submission"), |
| 17014 | Some(&w.ali), |
| 17015 | None, |
| 17016 | ) |
| 17017 | .await; |
| 17018 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 17019 | let remaining = homework_blob_keys(&db).await; |
| 17020 | assert_eq!(remaining.len(), 2); |
| 17021 | for gone in keys.iter().filter(|key| !remaining.contains(key)) { |
| 17022 | assert!( |
| 17023 | !common::blob_dir().join(gone).exists(), |
| 17024 | "withdrawn blob {gone} must be unlinked" |
| 17025 | ); |
| 17026 | } |
| 17027 | |
| 17028 | // Deleting the homework cascades submissions, files, and grades — blobs |
| 17029 | // included. |
| 17030 | let res = send( |
| 17031 | &app, |
| 17032 | "DELETE", |
| 17033 | &format!("/homework/{hw1}"), |
| 17034 | Some(&w.teacher), |
| 17035 | None, |
| 17036 | ) |
| 17037 | .await; |
| 17038 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 17039 | assert_eq!(hw_row_count(&db, "homework_submission").await, 0); |
| 17040 | assert_eq!(hw_row_count(&db, "homework_file").await, 0); |
| 17041 | assert_eq!(hw_row_count(&db, "homework_result").await, 0); |
| 17042 | assert_eq!(hw_row_count(&db, "homework").await, 1, "hw2 remains"); |
| 17043 | for key in &remaining { |
| 17044 | assert!( |
| 17045 | !common::blob_dir().join(key).exists(), |
| 17046 | "blob {key} must die with the homework" |
| 17047 | ); |
| 17048 | } |
| 17049 | |
| 17050 | // Detaching the şube takes everything left. |
| 17051 | let res = upload_hw_file(&app, &w.ali, &hw2, "d.txt", "text/plain", b"data").await; |
| 17052 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 17053 | let res = grade_hw(&app, &w.teacher, &hw2, &w.veli_id, "missing", None).await; |
| 17054 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17055 | let keys = homework_blob_keys(&db).await; |
| 17056 | assert_eq!(keys.len(), 1); |
| 17057 | unenroll(&app, &w.teacher, &w.instance, &w.ali_id).await; |
| 17058 | unenroll(&app, &w.teacher, &w.instance, &w.veli_id).await; |
| 17059 | // Detaching the şube takes the whole chain with it. |
| 17060 | assert_eq!( |
| 17061 | send( |
| 17062 | &app, |
| 17063 | "DELETE", |
| 17064 | &format!("/classes/{}/instances/{}", w.class, w.instance), |
| 17065 | Some(&w.teacher), |
| 17066 | None |
| 17067 | ) |
| 17068 | .await |
| 17069 | .status, |
| 17070 | StatusCode::NO_CONTENT |
| 17071 | ); |
| 17072 | for table in [ |
| 17073 | "homework", |
| 17074 | "homework_submission", |
| 17075 | "homework_file", |
| 17076 | "homework_result", |
| 17077 | ] { |
| 17078 | assert_eq!( |
| 17079 | hw_row_count(&db, table).await, |
| 17080 | 0, |
| 17081 | "{table} died with the instance" |
| 17082 | ); |
| 17083 | } |
| 17084 | for key in &keys { |
| 17085 | assert!( |
| 17086 | !common::blob_dir().join(key).exists(), |
| 17087 | "blob {key} must die with the instance" |
| 17088 | ); |
| 17089 | } |
| 17090 | |
| 17091 | // The freed catalog row goes too. |
| 17092 | assert_eq!( |
| 17093 | send( |
| 17094 | &app, |
| 17095 | "DELETE", |
| 17096 | &format!("/courses/{}", w.course), |
| 17097 | Some(&w.teacher), |
| 17098 | None |
| 17099 | ) |
| 17100 | .await |
| 17101 | .status, |
| 17102 | StatusCode::NO_CONTENT |
| 17103 | ); |
| 17104 | } |
| 17105 | |
| 17106 | /// A promotion sweeps the enrollment but never the homework rows; the gates |
| 17107 | /// re-read the live role and deny, and the roster keeps the stale work |
| 17108 | /// visible, flagged `unenrolled`. |
| 17109 | #[tokio::test] |
| 17110 | async fn homework_rows_survive_promotion_but_gates_deny() { |
| 17111 | let (app, db) = app_and_db().await; |
| 17112 | let w = hw_world(&app, &db).await; |
| 17113 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 17114 | let now = Timestamp::now().as_millis(); |
| 17115 | let hw = create_homework( |
| 17116 | &app, |
| 17117 | &w.teacher, |
| 17118 | &w.instance, |
| 17119 | &w.subject, |
| 17120 | "before", |
| 17121 | now + 3_600_000, |
| 17122 | ) |
| 17123 | .await; |
| 17124 | let res = submit_hw(&app, &w.ali, &hw, Some("as a student")).await; |
| 17125 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 17126 | let res = grade_hw(&app, &w.teacher, &hw, &w.ali_id, "done", Some(70)).await; |
| 17127 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17128 | |
| 17129 | let res = send( |
| 17130 | &app, |
| 17131 | "PATCH", |
| 17132 | &format!("/users/{}/role", w.ali_id), |
| 17133 | Some(&admin), |
| 17134 | Some(json!({ "role": "teacher" })), |
| 17135 | ) |
| 17136 | .await; |
| 17137 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17138 | assert_eq!(hw_row_count(&db, "homework_submission").await, 1); |
| 17139 | assert_eq!(hw_row_count(&db, "homework_result").await, 1); |
| 17140 | |
| 17141 | // Live-role gates: no submission access, no fresh grades onto staff. |
| 17142 | let res = send( |
| 17143 | &app, |
| 17144 | "GET", |
| 17145 | &format!("/homework/{hw}/submission"), |
| 17146 | Some(&w.ali), |
| 17147 | None, |
| 17148 | ) |
| 17149 | .await; |
| 17150 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 17151 | let res = submit_hw(&app, &w.ali, &hw, Some("as staff")).await; |
| 17152 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 17153 | let res = grade_hw(&app, &w.teacher, &hw, &w.ali_id, "done", None).await; |
| 17154 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "no longer a student"); |
| 17155 | |
| 17156 | // The roster keeps the stale work, flagged (the promotion swept the |
| 17157 | // enrollment). |
| 17158 | let res = send( |
| 17159 | &app, |
| 17160 | "GET", |
| 17161 | &format!("/homework/{hw}/submissions"), |
| 17162 | Some(&w.teacher), |
| 17163 | None, |
| 17164 | ) |
| 17165 | .await; |
| 17166 | let rows = common::items(&res.body); |
| 17167 | let row = rows |
| 17168 | .iter() |
| 17169 | .find(|row| row["user"] == w.ali_id.as_str()) |
| 17170 | .unwrap(); |
| 17171 | assert_eq!(row["unenrolled"], true); |
| 17172 | assert_eq!(row["result"]["mark"], 70); |
| 17173 | } |
| 17174 | |
| 17175 | /// A subject with homework can't be deleted (409 naming homework) until the |
| 17176 | /// homework is re-tagged or removed — the guard the exam questions already |
| 17177 | /// have. |
| 17178 | #[tokio::test] |
| 17179 | async fn homework_blocks_subject_delete_until_retagged() { |
| 17180 | let (app, db) = app_and_db().await; |
| 17181 | let w = hw_world(&app, &db).await; |
| 17182 | let now = Timestamp::now().as_millis(); |
| 17183 | let hw = create_homework( |
| 17184 | &app, |
| 17185 | &w.teacher, |
| 17186 | &w.instance, |
| 17187 | &w.subject, |
| 17188 | "tagged", |
| 17189 | now + 3_600_000, |
| 17190 | ) |
| 17191 | .await; |
| 17192 | |
| 17193 | let res = send( |
| 17194 | &app, |
| 17195 | "DELETE", |
| 17196 | &format!("/subjects/{}", w.subject), |
| 17197 | Some(&w.teacher), |
| 17198 | None, |
| 17199 | ) |
| 17200 | .await; |
| 17201 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 17202 | assert!( |
| 17203 | res.body["error"].as_str().unwrap().contains("homework"), |
| 17204 | "{}", |
| 17205 | res.body |
| 17206 | ); |
| 17207 | |
| 17208 | // Re-tagging frees the old subject and guards the new one. |
| 17209 | let second = create_subject(&app, &w.teacher, &w.course, "geometry").await; |
| 17210 | select_instance_subject(&app, &w.teacher, &w.instance, &second).await; |
| 17211 | let res = send( |
| 17212 | &app, |
| 17213 | "PATCH", |
| 17214 | &format!("/homework/{hw}"), |
| 17215 | Some(&w.teacher), |
| 17216 | Some(json!({ "subject_id": second })), |
| 17217 | ) |
| 17218 | .await; |
| 17219 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17220 | let res = send( |
| 17221 | &app, |
| 17222 | "DELETE", |
| 17223 | &format!("/subjects/{}", w.subject), |
| 17224 | Some(&w.teacher), |
| 17225 | None, |
| 17226 | ) |
| 17227 | .await; |
| 17228 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 17229 | let res = send( |
| 17230 | &app, |
| 17231 | "DELETE", |
| 17232 | &format!("/subjects/{second}"), |
| 17233 | Some(&w.teacher), |
| 17234 | None, |
| 17235 | ) |
| 17236 | .await; |
| 17237 | assert_eq!(res.status, StatusCode::CONFLICT); |
| 17238 | } |
| 17239 | |
| 17240 | /// The two homework lists page through the standard envelope. |
| 17241 | #[tokio::test] |
| 17242 | async fn homework_lists_paginate() { |
| 17243 | let (app, db) = app_and_db().await; |
| 17244 | let w = hw_world(&app, &db).await; |
| 17245 | let now = Timestamp::now().as_millis(); |
| 17246 | for i in 0..3 { |
| 17247 | create_homework( |
| 17248 | &app, |
| 17249 | &w.teacher, |
| 17250 | &w.instance, |
| 17251 | &w.subject, |
| 17252 | &format!("hw {i}"), |
| 17253 | now + 3_600_000, |
| 17254 | ) |
| 17255 | .await; |
| 17256 | } |
| 17257 | for uri in [ |
| 17258 | format!("/instances/{}/homework?limit=2&offset=2", w.instance), |
| 17259 | "/homework?limit=2&offset=2".to_string(), |
| 17260 | ] { |
| 17261 | let res = send(&app, "GET", &uri, Some(&w.ali), None).await; |
| 17262 | assert_eq!(res.status, StatusCode::OK, "{uri}"); |
| 17263 | assert_eq!(common::total(&res.body), 3, "{uri}"); |
| 17264 | assert_eq!(common::items(&res.body).len(), 1, "{uri}"); |
| 17265 | assert_eq!(res.body["limit"], 2); |
| 17266 | assert_eq!(res.body["offset"], 2); |
| 17267 | } |
| 17268 | } |
| 17269 | |
| 17270 | /// A course carrying students can't be deleted (409) until they are detached — |
| 17271 | /// the cascade would otherwise take the membership with it. A club or etüt |
| 17272 | /// carries students on its own member list; a ders carries them through the |
| 17273 | /// şubeler that teach it (see |
| 17274 | /// `deleting_course_cascades_enrollments_exams_and_results`). |
| 17275 | #[tokio::test] |
| 17276 | async fn course_delete_blocks_while_students_are_attached() { |
| 17277 | let (app, db) = app_and_db().await; |
| 17278 | let teacher = login_as(&app, &db, "cdb_t", "teacher").await; |
| 17279 | let student = login(&app, "cdb_s").await; |
| 17280 | let student_id = me_id(&app, &student).await; |
| 17281 | |
| 17282 | let res = send( |
| 17283 | &app, |
| 17284 | "POST", |
| 17285 | "/courses", |
| 17286 | Some(&teacher), |
| 17287 | Some(json!({ "title": "Chemistry club", "kind": "club" })), |
| 17288 | ) |
| 17289 | .await; |
| 17290 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 17291 | let course = id_of(&res.body); |
| 17292 | let res = send( |
| 17293 | &app, |
| 17294 | "POST", |
| 17295 | &format!("/courses/{course}/members"), |
| 17296 | Some(&teacher), |
| 17297 | Some(json!({ "user_id": student_id })), |
| 17298 | ) |
| 17299 | .await; |
| 17300 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17301 | |
| 17302 | let res = send( |
| 17303 | &app, |
| 17304 | "DELETE", |
| 17305 | &format!("/courses/{course}"), |
| 17306 | Some(&teacher), |
| 17307 | None, |
| 17308 | ) |
| 17309 | .await; |
| 17310 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 17311 | let res = send( |
| 17312 | &app, |
| 17313 | "GET", |
| 17314 | &format!("/courses/{course}"), |
| 17315 | Some(&teacher), |
| 17316 | None, |
| 17317 | ) |
| 17318 | .await; |
| 17319 | assert_eq!(res.status, StatusCode::OK); |
| 17320 | |
| 17321 | // Detach the member: the delete goes through. |
| 17322 | let res = send( |
| 17323 | &app, |
| 17324 | "DELETE", |
| 17325 | &format!("/courses/{course}/members/{student_id}"), |
| 17326 | Some(&teacher), |
| 17327 | None, |
| 17328 | ) |
| 17329 | .await; |
| 17330 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 17331 | let res = send( |
| 17332 | &app, |
| 17333 | "DELETE", |
| 17334 | &format!("/courses/{course}"), |
| 17335 | Some(&teacher), |
| 17336 | None, |
| 17337 | ) |
| 17338 | .await; |
| 17339 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 17340 | } |
| 17341 | |
| 17342 | /// An exam kind whose exams already carry marks can't leave the settings list |
| 17343 | /// (409) — weights are read live, so those marks would silently re-weight. |
| 17344 | /// Ungraded kinds still leave freely. |
| 17345 | #[tokio::test] |
| 17346 | async fn exam_kind_removal_blocks_while_marks_exist() { |
| 17347 | let (app, db) = app_and_db().await; |
| 17348 | let teacher = login_as(&app, &db, "ekd_t", "teacher").await; |
| 17349 | let manager = login_as(&app, &db, "ekd_m", "manager").await; |
| 17350 | let student = login(&app, "ekd_s").await; |
| 17351 | let student_id = me_id(&app, &student).await; |
| 17352 | |
| 17353 | // The school lists the two kinds this test weighs against each other. |
| 17354 | let res = send( |
| 17355 | &app, |
| 17356 | "PATCH", |
| 17357 | "/settings", |
| 17358 | Some(&manager), |
| 17359 | Some(json!({ "exam_kinds": [ |
| 17360 | {"name": "final", "weight": 1}, |
| 17361 | {"name": "quiz", "weight": 1}, |
| 17362 | ]})), |
| 17363 | ) |
| 17364 | .await; |
| 17365 | assert_eq!(res.status, StatusCode::OK); |
| 17366 | |
| 17367 | let t = taught_under(&app, &manager, &teacher, "Biology").await; |
| 17368 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 17369 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "Final", "final").await; |
| 17370 | let res = send( |
| 17371 | &app, |
| 17372 | "POST", |
| 17373 | &format!("/exams/{exam}/results"), |
| 17374 | Some(&teacher), |
| 17375 | Some(json!({ "user_id": student_id, "mark": 70 })), |
| 17376 | ) |
| 17377 | .await; |
| 17378 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17379 | |
| 17380 | // Dropping the graded kind is refused; the list is untouched. |
| 17381 | let res = send( |
| 17382 | &app, |
| 17383 | "PATCH", |
| 17384 | "/settings", |
| 17385 | Some(&manager), |
| 17386 | Some(json!({ "exam_kinds": [{ "name": "quiz", "weight": 1 }] })), |
| 17387 | ) |
| 17388 | .await; |
| 17389 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 17390 | let res = send(&app, "GET", "/settings", Some(&manager), None).await; |
| 17391 | let kinds: Vec<String> = res.body["exam_kinds"] |
| 17392 | .as_array() |
| 17393 | .unwrap() |
| 17394 | .iter() |
| 17395 | .map(|kind| kind["name"].as_str().unwrap().to_string()) |
| 17396 | .collect(); |
| 17397 | assert!(kinds.contains(&"final".to_string()), "{}", res.body); |
| 17398 | assert!(kinds.contains(&"quiz".to_string()), "{}", res.body); |
| 17399 | |
| 17400 | // Keeping the graded kind, dropping the ungraded ones, is fine. |
| 17401 | let res = send( |
| 17402 | &app, |
| 17403 | "PATCH", |
| 17404 | "/settings", |
| 17405 | Some(&manager), |
| 17406 | Some(json!({ "exam_kinds": [{ "name": "final", "weight": 5 }] })), |
| 17407 | ) |
| 17408 | .await; |
| 17409 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17410 | assert_eq!(res.body["exam_kinds"].as_array().unwrap().len(), 1); |
| 17411 | assert_eq!(res.body["exam_kinds"][0]["weight"], 5); |
| 17412 | } |
| 17413 | |
| 17414 | // --- chatbot relay ------------------------------------------------------- |
| 17415 | // |
| 17416 | // What the `POST` itself decides: the receipt, the availability gate, the |
| 17417 | // limits, and who may see a thread. The bridge round trip and the answer that |
| 17418 | // comes back are `ai_bridge.rs`'s job — the fake service dialled in here |
| 17419 | // completes the handshake and then stays quiet on purpose, so nothing in this |
| 17420 | // file depends on an answer arriving. |
| 17421 | |
| 17422 | use hezarfen_backend::ai::protocol::{Greeting, Hello, read_frame, write_frame}; |
| 17423 | use hezarfen_backend::ai::{AiBridge, BridgeConfig}; |
| 17424 | use hezarfen_backend::constant::{AI_ALPN, AI_CHAT_CAPABILITY, AI_PROTOCOL}; |
| 17425 | use hezarfen_backend::database::Database; |
| 17426 | |
| 17427 | const CHAT_TOKEN: &str = "integration-ai-token"; |
| 17428 | |
| 17429 | /// A bridge with one registered — but silent — `chat.reply` service. Holding |
| 17430 | /// it keeps the registration alive: the control stream's closure is a goodbye. |
| 17431 | struct ChatBridge { |
| 17432 | bridge: AiBridge, |
| 17433 | _endpoint: quinn::Endpoint, |
| 17434 | _conn: quinn::Connection, |
| 17435 | _control: (quinn::SendStream, quinn::RecvStream), |
| 17436 | } |
| 17437 | |
| 17438 | async fn chat_bridge() -> ChatBridge { |
| 17439 | let bridge = AiBridge::bind(BridgeConfig { |
| 17440 | addr: "127.0.0.1:0".parse().unwrap(), |
| 17441 | token: CHAT_TOKEN.to_string(), |
| 17442 | cert_path: None, |
| 17443 | key_path: None, |
| 17444 | request_timeout: std::time::Duration::from_secs(5), |
| 17445 | }) |
| 17446 | .await |
| 17447 | .expect("bridge binds on an ephemeral port"); |
| 17448 | |
| 17449 | hezarfen_backend::ai::tls::install_crypto_provider(); |
| 17450 | let mut roots = rustls::RootCertStore::empty(); |
| 17451 | roots.add(bridge.certificate()).expect("pin the leaf"); |
| 17452 | let mut tls = rustls::ClientConfig::builder() |
| 17453 | .with_root_certificates(roots) |
| 17454 | .with_no_client_auth(); |
| 17455 | tls.alpn_protocols = vec![AI_ALPN.to_vec()]; |
| 17456 | let config = quinn::ClientConfig::new(std::sync::Arc::new( |
| 17457 | quinn::crypto::rustls::QuicClientConfig::try_from(tls).expect("QUIC-usable TLS"), |
| 17458 | )); |
| 17459 | let mut endpoint = |
| 17460 | quinn::Endpoint::client("127.0.0.1:0".parse().unwrap()).expect("client bind"); |
| 17461 | endpoint.set_default_client_config(config); |
| 17462 | let conn = endpoint |
| 17463 | .connect(bridge.local_addr().unwrap(), "localhost") |
| 17464 | .expect("dial") |
| 17465 | .await |
| 17466 | .expect("QUIC handshake"); |
| 17467 | |
| 17468 | let (mut send_stream, mut recv_stream) = conn.open_bi().await.expect("control stream"); |
| 17469 | write_frame( |
| 17470 | &mut send_stream, |
| 17471 | &Hello { |
| 17472 | protocol: AI_PROTOCOL.to_string(), |
| 17473 | service: "fake-chat".to_string(), |
| 17474 | capabilities: vec![AI_CHAT_CAPABILITY.to_string()], |
| 17475 | token: CHAT_TOKEN.to_string(), |
| 17476 | max_concurrent: None, |
| 17477 | }, |
| 17478 | ) |
| 17479 | .await |
| 17480 | .expect("send Hello"); |
| 17481 | let greeting: Greeting = read_frame(&mut recv_stream).await.expect("read Greeting"); |
| 17482 | assert!(matches!(greeting, Greeting::Welcome { .. }), "{greeting:?}"); |
| 17483 | |
| 17484 | // Registration completes after the welcome is on the wire, so wait for it |
| 17485 | // rather than racing it. |
| 17486 | for _ in 0..300 { |
| 17487 | if bridge.has_capability(AI_CHAT_CAPABILITY) { |
| 17488 | break; |
| 17489 | } |
| 17490 | tokio::time::sleep(std::time::Duration::from_millis(10)).await; |
| 17491 | } |
| 17492 | assert!( |
| 17493 | bridge.has_capability(AI_CHAT_CAPABILITY), |
| 17494 | "service never registered" |
| 17495 | ); |
| 17496 | |
| 17497 | ChatBridge { |
| 17498 | bridge, |
| 17499 | _endpoint: endpoint, |
| 17500 | _conn: conn, |
| 17501 | _control: (send_stream, recv_stream), |
| 17502 | } |
| 17503 | } |
| 17504 | |
| 17505 | /// A router whose AI bridge is `ai`, plus a handle to its database. |
| 17506 | async fn chat_app(ai: Option<AiBridge>) -> (axum::Router, Database) { |
| 17507 | chat_app_limited(ai, Default::default()).await |
| 17508 | } |
| 17509 | |
| 17510 | /// The same, with an explicit per-user chat tier — what |
| 17511 | /// `RATE_LIMIT_CHATBOT_PER_MINUTE` configures in production. |
| 17512 | async fn chat_app_limited( |
| 17513 | ai: Option<AiBridge>, |
| 17514 | chatbot_limit: hezarfen_backend::rate_limit::UserRateLimiter, |
| 17515 | ) -> (axum::Router, Database) { |
| 17516 | let (tenants, db) = common::mem_deployment().await; |
| 17517 | let app = build_router(AppState { |
| 17518 | db: tenants.control().clone(), |
| 17519 | tenants, |
| 17520 | files_path: common::files_dir(), |
| 17521 | cookie_secure: false, |
| 17522 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| 17523 | chatbot_limit, |
| 17524 | rag_limit: Default::default(), |
| 17525 | exam_presence: Default::default(), |
| 17526 | board_hub: Default::default(), |
| 17527 | ai, |
| 17528 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 17529 | }); |
| 17530 | (app, db) |
| 17531 | } |
| 17532 | |
| 17533 | /// How many `thread` and `chatbot_message` rows exist, anywhere. |
| 17534 | async fn chat_rows(db: &Database) -> (usize, usize) { |
| 17535 | let threads: i64 = sqlx::query_scalar("SELECT count(*) FROM chatbot_thread") |
| 17536 | .fetch_one(db) |
| 17537 | .await |
| 17538 | .expect("count query"); |
| 17539 | let messages: i64 = sqlx::query_scalar("SELECT count(*) FROM chatbot_message") |
| 17540 | .fetch_one(db) |
| 17541 | .await |
| 17542 | .expect("count check"); |
| 17543 | (threads as usize, messages as usize) |
| 17544 | } |
| 17545 | |
| 17546 | /// Open a thread (asserts 201) and return its id. |
| 17547 | async fn new_thread(app: &axum::Router, cookie: &str) -> String { |
| 17548 | let res = send( |
| 17549 | app, |
| 17550 | "POST", |
| 17551 | "/chatbot/threads", |
| 17552 | Some(cookie), |
| 17553 | Some(json!({})), |
| 17554 | ) |
| 17555 | .await; |
| 17556 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 17557 | id_of(&res.body) |
| 17558 | } |
| 17559 | |
| 17560 | async fn post_turn(app: &axum::Router, cookie: &str, thread: &str, content: &str) -> common::Res { |
| 17561 | send( |
| 17562 | app, |
| 17563 | "POST", |
| 17564 | &format!("/chatbot/threads/{thread}/messages"), |
| 17565 | Some(cookie), |
| 17566 | Some(json!({ "content": content })), |
| 17567 | ) |
| 17568 | .await |
| 17569 | } |
| 17570 | |
| 17571 | /// Open the SSE stream without draining it — a `pending` turn's stream stays |
| 17572 | /// open, so reading its body here would hang. |
| 17573 | async fn open_stream(app: &axum::Router, cookie: &str, thread: &str, mid: &str) -> StatusCode { |
| 17574 | let request = Request::builder() |
| 17575 | .method("GET") |
| 17576 | .uri(format!("/chatbot/threads/{thread}/messages/{mid}/stream")) |
| 17577 | .header("cookie", cookie) |
| 17578 | .body(Body::empty()) |
| 17579 | .unwrap(); |
| 17580 | app.clone().oneshot(request).await.unwrap().status() |
| 17581 | } |
| 17582 | |
| 17583 | #[tokio::test] |
| 17584 | async fn chat_send_is_accepted_with_a_reserved_assistant_row() { |
| 17585 | let ai = chat_bridge().await; |
| 17586 | let (app, db) = chat_app(Some(ai.bridge.clone())).await; |
| 17587 | let cookie = login(&app, "ali").await; |
| 17588 | |
| 17589 | let res = send( |
| 17590 | &app, |
| 17591 | "POST", |
| 17592 | "/chatbot/threads", |
| 17593 | Some(&cookie), |
| 17594 | Some(json!({ "title": "Fizik" })), |
| 17595 | ) |
| 17596 | .await; |
| 17597 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 17598 | assert_eq!(res.body["title"], "Fizik"); |
| 17599 | assert!(res.body["created_at"].is_i64(), "{}", res.body); |
| 17600 | assert!(res.body["updated_at"].is_i64(), "{}", res.body); |
| 17601 | let thread = id_of(&res.body); |
| 17602 | |
| 17603 | // The receipt: the reserved row's id and nothing else. The answer is not |
| 17604 | // here — it is being fetched. |
| 17605 | let res = post_turn(&app, &cookie, &thread, "ikinci yasa nedir?").await; |
| 17606 | assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); |
| 17607 | assert_eq!(res.body["status"], "pending"); |
| 17608 | let mid = res.body["message_id"].as_str().expect("message_id"); |
| 17609 | assert!(!mid.is_empty()); |
| 17610 | assert_eq!( |
| 17611 | res.body.as_object().expect("object body").len(), |
| 17612 | 2, |
| 17613 | "{}", |
| 17614 | res.body |
| 17615 | ); |
| 17616 | |
| 17617 | // Both rows are already durable, and the reserved one reads back empty. |
| 17618 | assert_eq!(chat_rows(&db).await, (1, 2)); |
| 17619 | let res = send( |
| 17620 | &app, |
| 17621 | "GET", |
| 17622 | &format!("/chatbot/threads/{thread}/messages/{mid}"), |
| 17623 | Some(&cookie), |
| 17624 | None, |
| 17625 | ) |
| 17626 | .await; |
| 17627 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17628 | assert_eq!(res.body["thread_id"], thread); |
| 17629 | assert_eq!(res.body["role"], "assistant"); |
| 17630 | assert_eq!(res.body["status"], "pending"); |
| 17631 | assert_eq!(res.body["content"], ""); |
| 17632 | assert!(res.body["error_code"].is_null(), "{}", res.body); |
| 17633 | assert!(res.body["completed_at"].is_null(), "{}", res.body); |
| 17634 | assert!(res.body["created_at"].is_i64(), "{}", res.body); |
| 17635 | |
| 17636 | // The thread holds the question and its reserved answer, in that order — |
| 17637 | // the two rows one POST writes share a millisecond, so this is the id |
| 17638 | // tie-break of the route's `ORDER BY` doing its job. |
| 17639 | let res = send( |
| 17640 | &app, |
| 17641 | "GET", |
| 17642 | &format!("/chatbot/threads/{thread}/messages"), |
| 17643 | Some(&cookie), |
| 17644 | None, |
| 17645 | ) |
| 17646 | .await; |
| 17647 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17648 | let turns = common::items(&res.body); |
| 17649 | assert_eq!(turns.len(), 2, "{}", res.body); |
| 17650 | assert_eq!(turns[0]["role"], "user", "{}", res.body); |
| 17651 | assert_eq!(turns[0]["content"], "ikinci yasa nedir?", "{}", res.body); |
| 17652 | assert_eq!(turns[1]["role"], "assistant", "{}", res.body); |
| 17653 | assert_eq!(turns[1]["id"], mid, "{}", res.body); |
| 17654 | } |
| 17655 | |
| 17656 | #[tokio::test] |
| 17657 | async fn chat_send_without_a_service_is_503_and_writes_nothing() { |
| 17658 | // Both ways the gate can say no: no bridge on this deployment at all, and |
| 17659 | // a bridge with nothing declaring `chat.reply`. Neither may leave a user |
| 17660 | // turn stranded next to a pending row nothing could ever answer. |
| 17661 | let idle = AiBridge::bind(BridgeConfig { |
| 17662 | addr: "127.0.0.1:0".parse().unwrap(), |
| 17663 | token: CHAT_TOKEN.to_string(), |
| 17664 | cert_path: None, |
| 17665 | key_path: None, |
| 17666 | request_timeout: std::time::Duration::from_secs(5), |
| 17667 | }) |
| 17668 | .await |
| 17669 | .expect("bridge binds"); |
| 17670 | |
| 17671 | for ai in [None, Some(idle)] { |
| 17672 | let (app, db) = chat_app(ai).await; |
| 17673 | let cookie = login(&app, "ali").await; |
| 17674 | let thread = new_thread(&app, &cookie).await; |
| 17675 | |
| 17676 | let res = post_turn(&app, &cookie, &thread, "bir soru").await; |
| 17677 | assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); |
| 17678 | assert!( |
| 17679 | res.body["error"] |
| 17680 | .as_str() |
| 17681 | .unwrap_or_default() |
| 17682 | .contains("AI"), |
| 17683 | "{}", |
| 17684 | res.body |
| 17685 | ); |
| 17686 | // The thread exists (it was created), but the turn left no trace: no |
| 17687 | // user message, no pending assistant row. |
| 17688 | assert_eq!(chat_rows(&db).await, (1, 0), "a refused turn wrote rows"); |
| 17689 | } |
| 17690 | } |
| 17691 | |
| 17692 | #[tokio::test] |
| 17693 | async fn chat_lists_are_paged() { |
| 17694 | let ai = chat_bridge().await; |
| 17695 | let (app, _db) = chat_app(Some(ai.bridge.clone())).await; |
| 17696 | let cookie = login(&app, "ali").await; |
| 17697 | |
| 17698 | // Three threads, and three turns (six rows) inside the first. |
| 17699 | let mut threads = Vec::new(); |
| 17700 | for _ in 0..3 { |
| 17701 | threads.push(new_thread(&app, &cookie).await); |
| 17702 | } |
| 17703 | for n in 0..3 { |
| 17704 | let res = post_turn(&app, &cookie, &threads[0], &format!("soru {n}")).await; |
| 17705 | assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); |
| 17706 | } |
| 17707 | |
| 17708 | // Both routes answer the same envelope, and the pages partition the whole |
| 17709 | // list. Order is compared element for element: the id tie-break makes it |
| 17710 | // deterministic even for the two rows one POST writes in a millisecond. |
| 17711 | for (uri, expected) in [ |
| 17712 | ("/chatbot/threads".to_string(), 3), |
| 17713 | (format!("/chatbot/threads/{}/messages", threads[0]), 6), |
| 17714 | ] { |
| 17715 | let res = send( |
| 17716 | &app, |
| 17717 | "GET", |
| 17718 | &format!("{uri}?limit=2&offset=0"), |
| 17719 | Some(&cookie), |
| 17720 | None, |
| 17721 | ) |
| 17722 | .await; |
| 17723 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17724 | assert_eq!(common::total(&res.body), expected, "{}", res.body); |
| 17725 | assert_eq!(res.body["limit"], 2, "{}", res.body); |
| 17726 | assert_eq!(res.body["offset"], 0, "{}", res.body); |
| 17727 | let mut ids: Vec<String> = common::items(&res.body).iter().map(id_of).collect(); |
| 17728 | assert_eq!(ids.len(), 2); |
| 17729 | |
| 17730 | let res = send( |
| 17731 | &app, |
| 17732 | "GET", |
| 17733 | &format!("{uri}?limit=99&offset=2"), |
| 17734 | Some(&cookie), |
| 17735 | None, |
| 17736 | ) |
| 17737 | .await; |
| 17738 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17739 | assert_eq!(common::total(&res.body), expected, "{}", res.body); |
| 17740 | assert_eq!(res.body["offset"], 2, "{}", res.body); |
| 17741 | ids.extend(common::items(&res.body).iter().map(id_of)); |
| 17742 | |
| 17743 | // Paging is a window on one stable order, not a reshuffle: the pages |
| 17744 | // concatenated must reproduce the unpaged list exactly. |
| 17745 | let res = send(&app, "GET", &uri, Some(&cookie), None).await; |
| 17746 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17747 | let whole: Vec<String> = common::items(&res.body).iter().map(id_of).collect(); |
| 17748 | assert_eq!(ids, whole, "the pages must reproduce {uri} in order"); |
| 17749 | |
| 17750 | let mut unique = ids.clone(); |
| 17751 | unique.sort(); |
| 17752 | unique.dedup(); |
| 17753 | assert_eq!( |
| 17754 | unique.len() as i64, |
| 17755 | expected, |
| 17756 | "the pages must partition {uri}, not overlap or skip" |
| 17757 | ); |
| 17758 | |
| 17759 | // Past the end is an empty page, not an error. |
| 17760 | let res = send( |
| 17761 | &app, |
| 17762 | "GET", |
| 17763 | &format!("{uri}?limit=5&offset=999"), |
| 17764 | Some(&cookie), |
| 17765 | None, |
| 17766 | ) |
| 17767 | .await; |
| 17768 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17769 | assert!(common::items(&res.body).is_empty(), "{}", res.body); |
| 17770 | assert_eq!(common::total(&res.body), expected, "{}", res.body); |
| 17771 | } |
| 17772 | } |
| 17773 | |
| 17774 | #[tokio::test] |
| 17775 | async fn chat_threads_are_invisible_to_everyone_else() { |
| 17776 | // Nobody reads someone else's thread — not a teacher, not an admin. A |
| 17777 | // foreign id is a 404, never a 403: its existence is not leaked either. |
| 17778 | let ai = chat_bridge().await; |
| 17779 | let (app, db) = chat_app(Some(ai.bridge.clone())).await; |
| 17780 | let ali = login(&app, "ali").await; |
| 17781 | let thread = new_thread(&app, &ali).await; |
| 17782 | let res = post_turn(&app, &ali, &thread, "bir soru").await; |
| 17783 | assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); |
| 17784 | let mid = res.body["message_id"].as_str().unwrap().to_string(); |
| 17785 | |
| 17786 | for (name, role) in [ |
| 17787 | ("veli", "student"), |
| 17788 | ("hoca", "teacher"), |
| 17789 | ("patron", "admin"), |
| 17790 | ] { |
| 17791 | let other = login_as(&app, &db, name, role).await; |
| 17792 | for (method, uri) in [ |
| 17793 | ("GET", format!("/chatbot/threads/{thread}/messages")), |
| 17794 | ("GET", format!("/chatbot/threads/{thread}/messages/{mid}")), |
| 17795 | ( |
| 17796 | "GET", |
| 17797 | format!("/chatbot/threads/{thread}/messages/{mid}/stream"), |
| 17798 | ), |
| 17799 | ("DELETE", format!("/chatbot/threads/{thread}")), |
| 17800 | ("PATCH", format!("/chatbot/threads/{thread}")), |
| 17801 | ("POST", format!("/chatbot/threads/{thread}/messages")), |
| 17802 | ] { |
| 17803 | let body = match method { |
| 17804 | "POST" => Some(json!({ "content": "sızıntı" })), |
| 17805 | "PATCH" => Some(json!({ "title": "benim artık" })), |
| 17806 | _ => None, |
| 17807 | }; |
| 17808 | let res = send(&app, method, &uri, Some(&other), body).await; |
| 17809 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{name} {method} {uri}"); |
| 17810 | } |
| 17811 | // Nor does someone else's thread show up in their own list. |
| 17812 | let res = send(&app, "GET", "/chatbot/threads", Some(&other), None).await; |
| 17813 | assert!(common::items(&res.body).is_empty(), "{}", res.body); |
| 17814 | } |
| 17815 | |
| 17816 | // And the owner still has everything, untouched. |
| 17817 | assert_eq!(chat_rows(&db).await, (1, 2)); |
| 17818 | let res = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await; |
| 17819 | assert_eq!(common::items(&res.body).len(), 1, "{}", res.body); |
| 17820 | } |
| 17821 | |
| 17822 | #[tokio::test] |
| 17823 | async fn chat_thread_count_is_capped_by_the_school() { |
| 17824 | let (app, db) = chat_app(None).await; |
| 17825 | let manager = login_as(&app, &db, "mudur", "manager").await; |
| 17826 | let res = send( |
| 17827 | &app, |
| 17828 | "PATCH", |
| 17829 | "/settings", |
| 17830 | Some(&manager), |
| 17831 | Some(json!({ "max_chatbot_threads": 1 })), |
| 17832 | ) |
| 17833 | .await; |
| 17834 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17835 | |
| 17836 | let ali = login(&app, "ali").await; |
| 17837 | let first = new_thread(&app, &ali).await; |
| 17838 | let res = send( |
| 17839 | &app, |
| 17840 | "POST", |
| 17841 | "/chatbot/threads", |
| 17842 | Some(&ali), |
| 17843 | Some(json!({})), |
| 17844 | ) |
| 17845 | .await; |
| 17846 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 17847 | |
| 17848 | // The cap is storage protection, per user: another user is unaffected, and |
| 17849 | // deleting a thread frees the slot. |
| 17850 | let veli = login(&app, "veli").await; |
| 17851 | let _ = new_thread(&app, &veli).await; |
| 17852 | |
| 17853 | let res = send( |
| 17854 | &app, |
| 17855 | "DELETE", |
| 17856 | &format!("/chatbot/threads/{first}"), |
| 17857 | Some(&ali), |
| 17858 | None, |
| 17859 | ) |
| 17860 | .await; |
| 17861 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 17862 | let _ = new_thread(&app, &ali).await; |
| 17863 | } |
| 17864 | |
| 17865 | #[tokio::test(flavor = "multi_thread", worker_threads = 8)] |
| 17866 | async fn concurrent_thread_creation_never_passes_the_cap() { |
| 17867 | // The sequential test above cannot see this: count-then-create is only a |
| 17868 | // cap if something serializes the two, and the database's transactions do |
| 17869 | // not serialize a count against concurrent inserts. Sixteen simultaneous |
| 17870 | // creators against a cap of five must still leave five rows. |
| 17871 | const CAP: usize = 5; |
| 17872 | const RACERS: usize = 16; |
| 17873 | |
| 17874 | let (app, db) = chat_app(None).await; |
| 17875 | let manager = login_as(&app, &db, "mudur", "manager").await; |
| 17876 | let res = send( |
| 17877 | &app, |
| 17878 | "PATCH", |
| 17879 | "/settings", |
| 17880 | Some(&manager), |
| 17881 | Some(json!({ "max_chatbot_threads": CAP })), |
| 17882 | ) |
| 17883 | .await; |
| 17884 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 17885 | let ali = login(&app, "ali").await; |
| 17886 | |
| 17887 | // A barrier, so every request is inside the check-then-write window at |
| 17888 | // once rather than trickling in. |
| 17889 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(RACERS)); |
| 17890 | let racers: Vec<_> = (0..RACERS) |
| 17891 | .map(|_| { |
| 17892 | let (app, cookie, gate) = (app.clone(), ali.clone(), gate.clone()); |
| 17893 | tokio::spawn(async move { |
| 17894 | gate.wait().await; |
| 17895 | send( |
| 17896 | &app, |
| 17897 | "POST", |
| 17898 | "/chatbot/threads", |
| 17899 | Some(&cookie), |
| 17900 | Some(json!({})), |
| 17901 | ) |
| 17902 | .await |
| 17903 | .status |
| 17904 | }) |
| 17905 | }) |
| 17906 | .collect(); |
| 17907 | |
| 17908 | let mut created = 0; |
| 17909 | for racer in racers { |
| 17910 | match racer.await.expect("no panic in a racer") { |
| 17911 | StatusCode::CREATED => created += 1, |
| 17912 | StatusCode::CONFLICT => {} |
| 17913 | other => panic!("unexpected {other}"), |
| 17914 | } |
| 17915 | } |
| 17916 | assert_eq!(created, CAP, "the cap was over-admitted"); |
| 17917 | assert_eq!( |
| 17918 | chat_rows(&db).await.0, |
| 17919 | CAP, |
| 17920 | "rows past the cap were written" |
| 17921 | ); |
| 17922 | } |
| 17923 | |
| 17924 | #[tokio::test] |
| 17925 | async fn chat_turn_stamps_thread_activity() { |
| 17926 | // The `updated_at` bump is best-effort (a failure must never strand the |
| 17927 | // pending row it follows) — but it still has to happen. |
| 17928 | let ai = chat_bridge().await; |
| 17929 | let (app, _db) = chat_app(Some(ai.bridge.clone())).await; |
| 17930 | let ali = login(&app, "ali").await; |
| 17931 | let thread = new_thread(&app, &ali).await; |
| 17932 | let before = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await; |
| 17933 | let opened = common::items(&before.body)[0]["updated_at"] |
| 17934 | .as_i64() |
| 17935 | .unwrap(); |
| 17936 | |
| 17937 | // The stamp is in whole milliseconds; make sure the clock has moved. |
| 17938 | tokio::time::sleep(std::time::Duration::from_millis(5)).await; |
| 17939 | let res = post_turn(&app, &ali, &thread, "bir soru").await; |
| 17940 | assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); |
| 17941 | |
| 17942 | let after = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await; |
| 17943 | let stamped = common::items(&after.body)[0]["updated_at"] |
| 17944 | .as_i64() |
| 17945 | .unwrap(); |
| 17946 | assert!(stamped > opened, "{stamped} !> {opened}"); |
| 17947 | } |
| 17948 | |
| 17949 | #[tokio::test(flavor = "multi_thread", worker_threads = 2)] |
| 17950 | async fn chat_stream_stops_polling_when_the_client_hangs_up() { |
| 17951 | // A `pending` turn sends nothing, so nothing used to notice a vanished |
| 17952 | // client: the poll task kept re-reading the row every 200ms for the whole |
| 17953 | // 300-second staleness window, and `/stream` is not rate-limited. Dropping |
| 17954 | // the response body is exactly what axum does when a connection dies. |
| 17955 | // No bridge here: the pending row is written straight to the database, so |
| 17956 | // the only task this runtime gains is the stream's own poll loop and the |
| 17957 | // count below is not drowned in the QUIC service's task churn. |
| 17958 | let (app, db) = chat_app(None).await; |
| 17959 | let ali = login(&app, "ali").await; |
| 17960 | let thread = new_thread(&app, &ali).await; |
| 17961 | let me = send(&app, "GET", "/auth/me", Some(&ali), None).await; |
| 17962 | let user = UserId::from_key(me.body["id"].as_str().unwrap()); |
| 17963 | let pending = hezarfen_backend::db::chatbot_message::append_pending_assistant( |
| 17964 | &db, |
| 17965 | &ChatbotThreadId::from_key(&thread), |
| 17966 | &user, |
| 17967 | ) |
| 17968 | .await |
| 17969 | .expect("reserve an assistant row"); |
| 17970 | let mid = pending.get_id().key().to_string(); |
| 17971 | // The witness is the runtime's task count, so it is read only once the |
| 17972 | // setup's short-lived database tasks have drained — otherwise one of those |
| 17973 | // finishing mid-measurement looks like the stream's own task. |
| 17974 | let metrics = tokio::runtime::Handle::current().metrics(); |
| 17975 | let mut before = metrics.num_alive_tasks(); |
| 17976 | for _ in 0..50 { |
| 17977 | tokio::time::sleep(std::time::Duration::from_millis(20)).await; |
| 17978 | let now = metrics.num_alive_tasks(); |
| 17979 | if now == before { |
| 17980 | break; |
| 17981 | } |
| 17982 | before = now; |
| 17983 | } |
| 17984 | let request = Request::builder() |
| 17985 | .method("GET") |
| 17986 | .uri(format!("/chatbot/threads/{thread}/messages/{mid}/stream")) |
| 17987 | .header("cookie", &ali) |
| 17988 | .body(Body::empty()) |
| 17989 | .unwrap(); |
| 17990 | let response = app.clone().oneshot(request).await.unwrap(); |
| 17991 | assert_eq!(response.status(), StatusCode::OK); |
| 17992 | assert!( |
| 17993 | metrics.num_alive_tasks() > before, |
| 17994 | "the stream's poll task should be running" |
| 17995 | ); |
| 17996 | |
| 17997 | drop(response); |
| 17998 | for _ in 0..20 { |
| 17999 | if metrics.num_alive_tasks() <= before { |
| 18000 | return; |
| 18001 | } |
| 18002 | tokio::time::sleep(std::time::Duration::from_millis(50)).await; |
| 18003 | } |
| 18004 | panic!("the stream kept polling after its client hung up"); |
| 18005 | } |
| 18006 | |
| 18007 | #[tokio::test] |
| 18008 | async fn chat_content_is_required_and_capped_by_the_school() { |
| 18009 | let ai = chat_bridge().await; |
| 18010 | let (app, db) = chat_app(Some(ai.bridge.clone())).await; |
| 18011 | let manager = login_as(&app, &db, "mudur", "manager").await; |
| 18012 | let res = send( |
| 18013 | &app, |
| 18014 | "PATCH", |
| 18015 | "/settings", |
| 18016 | Some(&manager), |
| 18017 | Some(json!({ "max_chatbot_message_len": 100 })), |
| 18018 | ) |
| 18019 | .await; |
| 18020 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18021 | |
| 18022 | let ali = login(&app, "ali").await; |
| 18023 | let thread = new_thread(&app, &ali).await; |
| 18024 | |
| 18025 | for empty in ["", " ", "\n\t"] { |
| 18026 | let res = post_turn(&app, &ali, &thread, empty).await; |
| 18027 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{empty:?} accepted"); |
| 18028 | } |
| 18029 | // Counted in characters, not bytes: 101 multi-byte characters is 101. |
| 18030 | let res = post_turn(&app, &ali, &thread, &"é".repeat(101)).await; |
| 18031 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 18032 | // Nothing rejected was written. |
| 18033 | assert_eq!(chat_rows(&db).await, (1, 0)); |
| 18034 | |
| 18035 | let res = post_turn(&app, &ali, &thread, &"é".repeat(100)).await; |
| 18036 | assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); |
| 18037 | } |
| 18038 | |
| 18039 | #[tokio::test] |
| 18040 | async fn chat_rate_limit_refuses_before_anything_is_written() { |
| 18041 | // 20 messages a minute per user (the documented tier). The limiter is |
| 18042 | // charged first, so the refused turn leaves no row behind — and no other |
| 18043 | // user inherits the window. The tier is pinned, not the shipped default: |
| 18044 | // production budgets are far higher, and the test wants the refusal a |
| 18045 | // couple of turns away, not two thousand. |
| 18046 | use hezarfen_backend::rate_limit::UserRateLimiter; |
| 18047 | |
| 18048 | let ai = chat_bridge().await; |
| 18049 | let (app, db) = |
| 18050 | chat_app_limited(Some(ai.bridge.clone()), UserRateLimiter::per_user_minute(20)).await; |
| 18051 | let ali = login(&app, "ali").await; |
| 18052 | let thread = new_thread(&app, &ali).await; |
| 18053 | |
| 18054 | for n in 1..=20 { |
| 18055 | let res = post_turn(&app, &ali, &thread, &format!("soru {n}")).await; |
| 18056 | assert_eq!(res.status, StatusCode::ACCEPTED, "turn {n}: {}", res.body); |
| 18057 | } |
| 18058 | let before = chat_rows(&db).await; |
| 18059 | assert_eq!(before, (1, 40)); |
| 18060 | |
| 18061 | let (status, headers, _) = common::send_raw( |
| 18062 | &app, |
| 18063 | "POST", |
| 18064 | &format!("/chatbot/threads/{thread}/messages"), |
| 18065 | Some(&ali), |
| 18066 | Some("application/json"), |
| 18067 | json!({ "content": "yirmi birinci" }) |
| 18068 | .to_string() |
| 18069 | .into_bytes(), |
| 18070 | ) |
| 18071 | .await; |
| 18072 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); |
| 18073 | let retry_after = headers |
| 18074 | .get("retry-after") |
| 18075 | .expect("Retry-After tells the client when to come back") |
| 18076 | .to_str() |
| 18077 | .unwrap() |
| 18078 | .parse::<u64>() |
| 18079 | .expect("whole seconds"); |
| 18080 | assert!((1..=60).contains(&retry_after), "{retry_after}"); |
| 18081 | assert_eq!(chat_rows(&db).await, before, "a refused turn wrote rows"); |
| 18082 | |
| 18083 | let veli = login(&app, "veli").await; |
| 18084 | let other = new_thread(&app, &veli).await; |
| 18085 | let res = post_turn(&app, &veli, &other, "benim ilk sorum").await; |
| 18086 | assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); |
| 18087 | } |
| 18088 | |
| 18089 | #[tokio::test] |
| 18090 | async fn every_role_may_chat_parents_included() { |
| 18091 | // Deliberate, not an oversight: the chatbot is a `CurrentUser` route for |
| 18092 | // every role the school has, parents among them. |
| 18093 | let ai = chat_bridge().await; |
| 18094 | let (app, db) = chat_app(Some(ai.bridge.clone())).await; |
| 18095 | |
| 18096 | for (name, role) in [ |
| 18097 | ("veli", "parent"), |
| 18098 | ("ogrenci", "student"), |
| 18099 | ("hoca", "teacher"), |
| 18100 | ("mudur", "manager"), |
| 18101 | ("patron", "admin"), |
| 18102 | ] { |
| 18103 | let cookie = login_as(&app, &db, name, role).await; |
| 18104 | let thread = new_thread(&app, &cookie).await; |
| 18105 | |
| 18106 | let res = post_turn(&app, &cookie, &thread, "bir soru").await; |
| 18107 | assert_eq!(res.status, StatusCode::ACCEPTED, "{role}: {}", res.body); |
| 18108 | let mid = res.body["message_id"].as_str().unwrap().to_string(); |
| 18109 | |
| 18110 | let res = send( |
| 18111 | &app, |
| 18112 | "GET", |
| 18113 | &format!("/chatbot/threads/{thread}/messages/{mid}"), |
| 18114 | Some(&cookie), |
| 18115 | None, |
| 18116 | ) |
| 18117 | .await; |
| 18118 | assert_eq!(res.status, StatusCode::OK, "{role}: {}", res.body); |
| 18119 | |
| 18120 | let res = send( |
| 18121 | &app, |
| 18122 | "GET", |
| 18123 | &format!("/chatbot/threads/{thread}/messages"), |
| 18124 | Some(&cookie), |
| 18125 | None, |
| 18126 | ) |
| 18127 | .await; |
| 18128 | assert_eq!(res.status, StatusCode::OK, "{role}: {}", res.body); |
| 18129 | assert_eq!(common::items(&res.body).len(), 2, "{role}: {}", res.body); |
| 18130 | |
| 18131 | assert_eq!( |
| 18132 | open_stream(&app, &cookie, &thread, &mid).await, |
| 18133 | StatusCode::OK, |
| 18134 | "{role} may open the stream" |
| 18135 | ); |
| 18136 | |
| 18137 | let res = send(&app, "GET", "/chatbot/threads", Some(&cookie), None).await; |
| 18138 | assert_eq!(res.status, StatusCode::OK, "{role}: {}", res.body); |
| 18139 | assert_eq!(common::items(&res.body).len(), 1, "{role}: {}", res.body); |
| 18140 | |
| 18141 | let res = send( |
| 18142 | &app, |
| 18143 | "DELETE", |
| 18144 | &format!("/chatbot/threads/{thread}"), |
| 18145 | Some(&cookie), |
| 18146 | None, |
| 18147 | ) |
| 18148 | .await; |
| 18149 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{role}: {}", res.body); |
| 18150 | } |
| 18151 | // Every thread deleted, every turn cascaded with it. |
| 18152 | assert_eq!(chat_rows(&db).await, (0, 0)); |
| 18153 | } |
| 18154 | |
| 18155 | #[tokio::test] |
| 18156 | async fn chat_thread_can_be_renamed_and_cleared() { |
| 18157 | // Renaming is how a user files a thread, so it counts as activity and the |
| 18158 | // thread moves to the top of the list. Nothing renames a thread by itself: |
| 18159 | // there is no auto-titling from the first message. |
| 18160 | let (app, _db) = chat_app(None).await; |
| 18161 | let ali = login(&app, "ali").await; |
| 18162 | let first = new_thread(&app, &ali).await; |
| 18163 | tokio::time::sleep(std::time::Duration::from_millis(5)).await; |
| 18164 | let second = new_thread(&app, &ali).await; |
| 18165 | |
| 18166 | let listed = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await; |
| 18167 | let items = common::items(&listed.body); |
| 18168 | assert_eq!(id_of(&items[0]), second, "newest activity first"); |
| 18169 | let before = items[1]["updated_at"].as_i64().expect("updated_at"); |
| 18170 | assert!(items[1]["title"].is_null(), "{}", listed.body); |
| 18171 | |
| 18172 | // The stamp is in whole milliseconds; make sure the clock has moved. |
| 18173 | tokio::time::sleep(std::time::Duration::from_millis(5)).await; |
| 18174 | let res = send( |
| 18175 | &app, |
| 18176 | "PATCH", |
| 18177 | &format!("/chatbot/threads/{first}"), |
| 18178 | Some(&ali), |
| 18179 | Some(json!({ "title": " Fizik ödevi " })), |
| 18180 | ) |
| 18181 | .await; |
| 18182 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18183 | assert_eq!(res.body["title"], "Fizik ödevi", "trimmed, not stored raw"); |
| 18184 | assert_eq!(id_of(&res.body), first); |
| 18185 | let stamped = res.body["updated_at"].as_i64().expect("updated_at"); |
| 18186 | assert!(stamped > before, "{stamped} !> {before}"); |
| 18187 | |
| 18188 | // The rename is durable and re-sorted the list. |
| 18189 | let listed = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await; |
| 18190 | let items = common::items(&listed.body); |
| 18191 | assert_eq!(id_of(&items[0]), first, "the renamed thread is now first"); |
| 18192 | assert_eq!(items[0]["title"], "Fizik ödevi"); |
| 18193 | |
| 18194 | // `null` — and a blank string — clear the name back to untitled. |
| 18195 | for clearing in [json!({ "title": null }), json!({ "title": " " })] { |
| 18196 | let res = send( |
| 18197 | &app, |
| 18198 | "PATCH", |
| 18199 | &format!("/chatbot/threads/{first}"), |
| 18200 | Some(&ali), |
| 18201 | Some(clearing.clone()), |
| 18202 | ) |
| 18203 | .await; |
| 18204 | assert_eq!(res.status, StatusCode::OK, "{clearing}: {}", res.body); |
| 18205 | assert!(res.body["title"].is_null(), "{clearing}: {}", res.body); |
| 18206 | |
| 18207 | // Restore a name so the next iteration has something to clear. |
| 18208 | send( |
| 18209 | &app, |
| 18210 | "PATCH", |
| 18211 | &format!("/chatbot/threads/{first}"), |
| 18212 | Some(&ali), |
| 18213 | Some(json!({ "title": "geri" })), |
| 18214 | ) |
| 18215 | .await; |
| 18216 | } |
| 18217 | |
| 18218 | // Too long is a 400, and the stored name is untouched. |
| 18219 | let res = send( |
| 18220 | &app, |
| 18221 | "PATCH", |
| 18222 | &format!("/chatbot/threads/{first}"), |
| 18223 | Some(&ali), |
| 18224 | Some(json!({ "title": "é".repeat(201) })), |
| 18225 | ) |
| 18226 | .await; |
| 18227 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 18228 | let res = send( |
| 18229 | &app, |
| 18230 | "PATCH", |
| 18231 | &format!("/chatbot/threads/{first}"), |
| 18232 | Some(&ali), |
| 18233 | Some(json!({ "title": "é".repeat(200) })), |
| 18234 | ) |
| 18235 | .await; |
| 18236 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18237 | |
| 18238 | // A thread that never existed is the same 404 a foreign one gets. |
| 18239 | let res = send( |
| 18240 | &app, |
| 18241 | "PATCH", |
| 18242 | "/chatbot/threads/nosuchthread", |
| 18243 | Some(&ali), |
| 18244 | Some(json!({ "title": "hayalet" })), |
| 18245 | ) |
| 18246 | .await; |
| 18247 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 18248 | // And `second` was never touched by any of it. |
| 18249 | let res = send( |
| 18250 | &app, |
| 18251 | "GET", |
| 18252 | &format!("/chatbot/threads/{second}/messages"), |
| 18253 | Some(&ali), |
| 18254 | None, |
| 18255 | ) |
| 18256 | .await; |
| 18257 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18258 | } |
| 18259 | |
| 18260 | #[tokio::test] |
| 18261 | async fn chat_rate_limit_tier_is_configurable_and_zero_disables_it() { |
| 18262 | // `RATE_LIMIT_CHATBOT_PER_MINUTE`, the third tier, behaves like the two IP |
| 18263 | // ones: the configured number is honoured exactly and `0` switches it off. |
| 18264 | // No bridge is needed — the limiter is charged before the availability |
| 18265 | // gate, so a metered turn answers 503 and only the refused one answers 429. |
| 18266 | use hezarfen_backend::rate_limit::UserRateLimiter; |
| 18267 | |
| 18268 | let (app, _db) = chat_app_limited(None, UserRateLimiter::per_user_minute(3)).await; |
| 18269 | let ali = login(&app, "ali").await; |
| 18270 | let thread = new_thread(&app, &ali).await; |
| 18271 | for n in 1..=3 { |
| 18272 | let res = post_turn(&app, &ali, &thread, &format!("soru {n}")).await; |
| 18273 | assert_eq!( |
| 18274 | res.status, |
| 18275 | StatusCode::SERVICE_UNAVAILABLE, |
| 18276 | "turn {n} was inside the budget: {}", |
| 18277 | res.body |
| 18278 | ); |
| 18279 | } |
| 18280 | let res = post_turn(&app, &ali, &thread, "dorduncu").await; |
| 18281 | assert_eq!(res.status, StatusCode::TOO_MANY_REQUESTS, "{}", res.body); |
| 18282 | // Per user, still: a second caller starts with a full budget. |
| 18283 | let veli = login(&app, "veli").await; |
| 18284 | let other = new_thread(&app, &veli).await; |
| 18285 | assert_eq!( |
| 18286 | post_turn(&app, &veli, &other, "benim ilk sorum") |
| 18287 | .await |
| 18288 | .status, |
| 18289 | StatusCode::SERVICE_UNAVAILABLE |
| 18290 | ); |
| 18291 | |
| 18292 | // `0` disables the tier: well past the shipped default, nothing is refused. |
| 18293 | let (app, _db) = chat_app_limited(None, UserRateLimiter::per_user_minute(0)).await; |
| 18294 | let ali = login(&app, "ali").await; |
| 18295 | let thread = new_thread(&app, &ali).await; |
| 18296 | for n in 1..=40 { |
| 18297 | let res = post_turn(&app, &ali, &thread, &format!("soru {n}")).await; |
| 18298 | assert_eq!( |
| 18299 | res.status, |
| 18300 | StatusCode::SERVICE_UNAVAILABLE, |
| 18301 | "turn {n} was rate-limited with the tier off: {}", |
| 18302 | res.body |
| 18303 | ); |
| 18304 | } |
| 18305 | } |
| 18306 | |
| 18307 | // --- appointments ---------------------------------------------------------- |
| 18308 | |
| 18309 | const HOUR_MS: i64 = 3_600_000; |
| 18310 | const WEEK_MS: i64 = 7 * 24 * HOUR_MS; |
| 18311 | |
| 18312 | /// Publish availability from a full JSON body (no assertion). The response is |
| 18313 | /// always an array: one element for a one-off, one per occurrence for a weekly. |
| 18314 | async fn publish_slots(app: &axum::Router, cookie: &str, body: serde_json::Value) -> common::Res { |
| 18315 | send(app, "POST", "/appointments/slots", Some(cookie), Some(body)).await |
| 18316 | } |
| 18317 | |
| 18318 | /// Publish one slot as `cookie` (asserts 201); returns its id. |
| 18319 | async fn publish_slot(app: &axum::Router, cookie: &str, starts_at: i64, ends_at: i64) -> String { |
| 18320 | let res = publish_slots( |
| 18321 | app, |
| 18322 | cookie, |
| 18323 | json!({ "starts_at": starts_at, "ends_at": ends_at }), |
| 18324 | ) |
| 18325 | .await; |
| 18326 | assert_eq!( |
| 18327 | res.status, |
| 18328 | StatusCode::CREATED, |
| 18329 | "publish slot: {}", |
| 18330 | res.body |
| 18331 | ); |
| 18332 | res.body[0]["id"].as_str().expect("slot id").to_string() |
| 18333 | } |
| 18334 | |
| 18335 | /// Ask for a meeting on `slot` (no assertion). |
| 18336 | async fn book_slot(app: &axum::Router, cookie: &str, slot: &str) -> common::Res { |
| 18337 | send( |
| 18338 | app, |
| 18339 | "POST", |
| 18340 | "/appointments", |
| 18341 | Some(cookie), |
| 18342 | Some(json!({ "slot": slot, "reason": "görüşmek istiyorum" })), |
| 18343 | ) |
| 18344 | .await |
| 18345 | } |
| 18346 | |
| 18347 | /// Book `slot`, asserting it lands pending; returns the booking id. |
| 18348 | async fn book_ok(app: &axum::Router, cookie: &str, slot: &str) -> String { |
| 18349 | let res = book_slot(app, cookie, slot).await; |
| 18350 | assert_eq!(res.status, StatusCode::CREATED, "book slot: {}", res.body); |
| 18351 | assert_eq!(res.body["status"], "pending"); |
| 18352 | id_of(&res.body) |
| 18353 | } |
| 18354 | |
| 18355 | /// `PATCH /appointments/{id}/{action}` — approve, reject, cancel, or either |
| 18356 | /// answer to a counter-proposal (no assertion, no body). |
| 18357 | async fn decide(app: &axum::Router, cookie: &str, id: &str, action: &str) -> common::Res { |
| 18358 | send( |
| 18359 | app, |
| 18360 | "PATCH", |
| 18361 | &format!("/appointments/{id}/{action}"), |
| 18362 | Some(cookie), |
| 18363 | None, |
| 18364 | ) |
| 18365 | .await |
| 18366 | } |
| 18367 | |
| 18368 | /// Counter-propose another window for `id` (no assertion). |
| 18369 | async fn propose( |
| 18370 | app: &axum::Router, |
| 18371 | cookie: &str, |
| 18372 | id: &str, |
| 18373 | starts_at: i64, |
| 18374 | ends_at: i64, |
| 18375 | ) -> common::Res { |
| 18376 | send( |
| 18377 | app, |
| 18378 | "PATCH", |
| 18379 | &format!("/appointments/{id}/reschedule"), |
| 18380 | Some(cookie), |
| 18381 | Some(json!({ "starts_at": starts_at, "ends_at": ends_at })), |
| 18382 | ) |
| 18383 | .await |
| 18384 | } |
| 18385 | |
| 18386 | /// Accept the standing counter-proposal on `id`, naming the window the |
| 18387 | /// requester read — the accept pins *which* proposal it answers, so the body |
| 18388 | /// is required (a bodyless PATCH is a `415`, not a `400`). |
| 18389 | async fn accept_reschedule( |
| 18390 | app: &axum::Router, |
| 18391 | cookie: &str, |
| 18392 | id: &str, |
| 18393 | starts_at: i64, |
| 18394 | ends_at: i64, |
| 18395 | ) -> common::Res { |
| 18396 | send( |
| 18397 | app, |
| 18398 | "PATCH", |
| 18399 | &format!("/appointments/{id}/reschedule/accept"), |
| 18400 | Some(cookie), |
| 18401 | Some(json!({ "proposed_starts_at": starts_at, "proposed_ends_at": ends_at })), |
| 18402 | ) |
| 18403 | .await |
| 18404 | } |
| 18405 | |
| 18406 | #[tokio::test] |
| 18407 | async fn appointment_book_and_approve_holds_the_slot() { |
| 18408 | let (app, db) = app_and_db().await; |
| 18409 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18410 | let ali_id = me_id(&app, &ali).await; |
| 18411 | let veli = login(&app, "veli").await; |
| 18412 | let veli_id = me_id(&app, &veli).await; |
| 18413 | let ayse = login(&app, "ayse").await; |
| 18414 | let now = Timestamp::now().as_millis(); |
| 18415 | |
| 18416 | let res = publish_slots( |
| 18417 | &app, |
| 18418 | &ali, |
| 18419 | json!({ "starts_at": now + HOUR_MS, "ends_at": now + 2 * HOUR_MS, |
| 18420 | "note": "ofis saati" }), |
| 18421 | ) |
| 18422 | .await; |
| 18423 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 18424 | assert_eq!(res.body.as_array().expect("array body").len(), 1); |
| 18425 | let slot = res.body[0]["id"].as_str().expect("slot id").to_string(); |
| 18426 | assert_eq!(res.body[0]["teacher"]["id"], ali_id.as_str()); |
| 18427 | assert_eq!(res.body[0]["note"], "ofis saati"); |
| 18428 | assert!(res.body[0]["series"].is_null(), "a one-off has no series"); |
| 18429 | |
| 18430 | // Booking lands pending, echoing the slot's own window. |
| 18431 | let res = book_slot(&app, &veli, &slot).await; |
| 18432 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 18433 | assert_eq!(res.body["status"], "pending"); |
| 18434 | assert_eq!(res.body["requester"]["id"], veli_id.as_str()); |
| 18435 | assert_eq!(res.body["teacher"]["id"], ali_id.as_str()); |
| 18436 | assert_eq!(res.body["starts_at"], now + HOUR_MS); |
| 18437 | assert!(res.body["decided_by"].is_null(), "pending has no decider"); |
| 18438 | let booking = id_of(&res.body); |
| 18439 | |
| 18440 | // The pending request already holds the slot against everyone else. |
| 18441 | let res = book_slot(&app, &ayse, &slot).await; |
| 18442 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 18443 | |
| 18444 | let res = decide(&app, &ali, &booking, "approve").await; |
| 18445 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18446 | assert_eq!(res.body["status"], "approved"); |
| 18447 | assert_eq!(res.body["decided_by"]["id"], ali_id.as_str()); |
| 18448 | |
| 18449 | // Both sides read it back from their own list. |
| 18450 | let mine = send(&app, "GET", "/appointments", Some(&veli), None).await; |
| 18451 | assert_eq!(common::items(&mine.body).len(), 1); |
| 18452 | let inbox = send(&app, "GET", "/appointments", Some(&ali), None).await; |
| 18453 | assert_eq!(common::items(&inbox.body)[0]["id"], booking.as_str()); |
| 18454 | } |
| 18455 | |
| 18456 | #[tokio::test] |
| 18457 | async fn rejecting_a_booking_frees_the_slot() { |
| 18458 | let (app, db) = app_and_db().await; |
| 18459 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18460 | let ali_id = me_id(&app, &ali).await; |
| 18461 | let veli = login(&app, "veli").await; |
| 18462 | let ayse = login(&app, "ayse").await; |
| 18463 | let now = Timestamp::now().as_millis(); |
| 18464 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18465 | |
| 18466 | // A bodyless reject records the decider and no reason. |
| 18467 | let booking = book_ok(&app, &veli, &slot).await; |
| 18468 | let res = decide(&app, &ali, &booking, "reject").await; |
| 18469 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18470 | assert_eq!(res.body["status"], "rejected"); |
| 18471 | assert_eq!(res.body["decided_by"]["id"], ali_id.as_str()); |
| 18472 | assert!(res.body["reject_reason"].is_null(), "no reason was given"); |
| 18473 | |
| 18474 | // A reject carrying a reason records both the decider and the reason, and |
| 18475 | // an over-long reason is refused before the row changes. |
| 18476 | let booking = book_ok(&app, &ayse, &slot).await; |
| 18477 | let res = send( |
| 18478 | &app, |
| 18479 | "PATCH", |
| 18480 | &format!("/appointments/{booking}/reject"), |
| 18481 | Some(&ali), |
| 18482 | Some(json!({ "reason": "x".repeat(2000) })), |
| 18483 | ) |
| 18484 | .await; |
| 18485 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 18486 | let res = send( |
| 18487 | &app, |
| 18488 | "PATCH", |
| 18489 | &format!("/appointments/{booking}/reject"), |
| 18490 | Some(&ali), |
| 18491 | Some(json!({ "reason": "Bu saatte müsait değilim" })), |
| 18492 | ) |
| 18493 | .await; |
| 18494 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18495 | assert_eq!(res.body["status"], "rejected"); |
| 18496 | assert_eq!(res.body["decided_by"]["id"], ali_id.as_str()); |
| 18497 | assert_eq!(res.body["reject_reason"], "Bu saatte müsait değilim"); |
| 18498 | |
| 18499 | // Occupancy counts live rows only, so the next person may take it. |
| 18500 | let res = book_slot(&app, &ayse, &slot).await; |
| 18501 | assert_eq!( |
| 18502 | res.status, |
| 18503 | StatusCode::CREATED, |
| 18504 | "a rejected booking must not keep the seat: {}", |
| 18505 | res.body |
| 18506 | ); |
| 18507 | // And the rejected one cannot be decided twice. |
| 18508 | let res = decide(&app, &ali, &booking, "approve").await; |
| 18509 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 18510 | } |
| 18511 | |
| 18512 | #[tokio::test] |
| 18513 | async fn approval_refuses_a_teacher_double_booking() { |
| 18514 | let (app, db) = app_and_db().await; |
| 18515 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18516 | let veli = login(&app, "veli").await; |
| 18517 | let ayse = login(&app, "ayse").await; |
| 18518 | let now = Timestamp::now().as_millis(); |
| 18519 | |
| 18520 | // A teacher can no longer publish two colliding slots, so the collision is |
| 18521 | // reached the only way left: two non-overlapping slots, then a reschedule |
| 18522 | // proposal that drags the second onto the first's just-approved window. |
| 18523 | let first = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18524 | let second = publish_slot(&app, &ali, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; |
| 18525 | let one = book_ok(&app, &veli, &first).await; |
| 18526 | let two = book_ok(&app, &ayse, &second).await; |
| 18527 | |
| 18528 | assert_eq!( |
| 18529 | decide(&app, &ali, &one, "approve").await.status, |
| 18530 | StatusCode::OK |
| 18531 | ); |
| 18532 | // Teacher counter-proposes a window overlapping the just-approved meeting; |
| 18533 | // accepting it is approval at the proposed time, and that collision is what |
| 18534 | // must be refused. |
| 18535 | let res = propose( |
| 18536 | &app, |
| 18537 | &ali, |
| 18538 | &two, |
| 18539 | now + HOUR_MS + 600_000, |
| 18540 | now + 2 * HOUR_MS + 600_000, |
| 18541 | ) |
| 18542 | .await; |
| 18543 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18544 | let res = accept_reschedule( |
| 18545 | &app, |
| 18546 | &ayse, |
| 18547 | &two, |
| 18548 | now + HOUR_MS + 600_000, |
| 18549 | now + 2 * HOUR_MS + 600_000, |
| 18550 | ) |
| 18551 | .await; |
| 18552 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 18553 | // Refused, not half-applied: it is still pending and still decidable. |
| 18554 | let res = decide(&app, &ali, &two, "reject").await; |
| 18555 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18556 | } |
| 18557 | |
| 18558 | #[tokio::test] |
| 18559 | async fn approval_refuses_a_requester_double_booking() { |
| 18560 | let (app, db) = app_and_db().await; |
| 18561 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18562 | let mert = login_as(&app, &db, "mert", "teacher").await; |
| 18563 | let veli = login(&app, "veli").await; |
| 18564 | let now = Timestamp::now().as_millis(); |
| 18565 | |
| 18566 | // One student, two different teachers, overlapping times. Both requests |
| 18567 | // stand (nothing is committed yet); the second approval collides. |
| 18568 | let first = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18569 | let second = publish_slot(&app, &mert, now + HOUR_MS + 600_000, now + 3 * HOUR_MS).await; |
| 18570 | let one = book_ok(&app, &veli, &first).await; |
| 18571 | let two = book_ok(&app, &veli, &second).await; |
| 18572 | |
| 18573 | assert_eq!( |
| 18574 | decide(&app, &ali, &one, "approve").await.status, |
| 18575 | StatusCode::OK |
| 18576 | ); |
| 18577 | let res = decide(&app, &mert, &two, "approve").await; |
| 18578 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 18579 | |
| 18580 | // Booking a fresh overlap once one is committed is refused up front. The |
| 18581 | // slot comes from a third teacher: mert's calendar already holds `second`, |
| 18582 | // which a same-teacher slot at this window would now overlap at publish. |
| 18583 | let ahmet = login_as(&app, &db, "ahmet", "teacher").await; |
| 18584 | let third = publish_slot(&app, &ahmet, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18585 | let res = book_slot(&app, &veli, &third).await; |
| 18586 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 18587 | } |
| 18588 | |
| 18589 | #[tokio::test] |
| 18590 | async fn touching_windows_never_collide() { |
| 18591 | let (app, db) = app_and_db().await; |
| 18592 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18593 | let veli = login(&app, "veli").await; |
| 18594 | let now = Timestamp::now().as_millis(); |
| 18595 | |
| 18596 | // Half-open windows: 10:00–11:00 and 11:00–12:00 are back-to-back, not a |
| 18597 | // clash — for the teacher and for the student alike. |
| 18598 | let first = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18599 | let second = publish_slot(&app, &ali, now + 2 * HOUR_MS, now + 3 * HOUR_MS).await; |
| 18600 | let one = book_ok(&app, &veli, &first).await; |
| 18601 | let two = book_ok(&app, &veli, &second).await; |
| 18602 | |
| 18603 | for booking in [&one, &two] { |
| 18604 | let res = decide(&app, &ali, booking, "approve").await; |
| 18605 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18606 | assert_eq!(res.body["status"], "approved"); |
| 18607 | } |
| 18608 | } |
| 18609 | |
| 18610 | #[tokio::test] |
| 18611 | async fn reschedule_returns_to_pending_until_the_requester_accepts() { |
| 18612 | let (app, db) = app_and_db().await; |
| 18613 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18614 | let ali_id = me_id(&app, &ali).await; |
| 18615 | let veli = login(&app, "veli").await; |
| 18616 | let ayse = login(&app, "ayse").await; |
| 18617 | let now = Timestamp::now().as_millis(); |
| 18618 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18619 | let booking = book_ok(&app, &veli, &slot).await; |
| 18620 | assert_eq!( |
| 18621 | decide(&app, &ali, &booking, "approve").await.status, |
| 18622 | StatusCode::OK |
| 18623 | ); |
| 18624 | |
| 18625 | // A counter-proposal un-commits the approved meeting rather than moving it |
| 18626 | // silently. |
| 18627 | let res = propose(&app, &ali, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; |
| 18628 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18629 | assert_eq!(res.body["status"], "pending"); |
| 18630 | assert!(res.body["decided_by"].is_null(), "approval was withdrawn"); |
| 18631 | assert_eq!(res.body["proposed_starts_at"], now + 3 * HOUR_MS); |
| 18632 | assert_eq!(res.body["proposed_ends_at"], now + 4 * HOUR_MS); |
| 18633 | assert_eq!(res.body["proposed_by"]["id"], ali_id.as_str()); |
| 18634 | // The effective window already reads as the proposed one. |
| 18635 | assert_eq!(res.body["starts_at"], now + 3 * HOUR_MS); |
| 18636 | |
| 18637 | // Only the requester may answer it. A valid pin still 403s for the wrong |
| 18638 | // caller: `ensure_requester` runs ahead of the domain either way. |
| 18639 | let res = accept_reschedule(&app, &ayse, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; |
| 18640 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 18641 | let res = accept_reschedule(&app, &ali, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; |
| 18642 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 18643 | |
| 18644 | let res = accept_reschedule(&app, &veli, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; |
| 18645 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18646 | assert_eq!(res.body["status"], "approved"); |
| 18647 | assert_eq!(res.body["starts_at"], now + 3 * HOUR_MS); |
| 18648 | assert_eq!(res.body["ends_at"], now + 4 * HOUR_MS); |
| 18649 | } |
| 18650 | |
| 18651 | #[tokio::test] |
| 18652 | async fn a_started_proposal_is_refused() { |
| 18653 | let (app, db) = app_and_db().await; |
| 18654 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18655 | let veli = login(&app, "veli").await; |
| 18656 | let now = Timestamp::now().as_millis(); |
| 18657 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18658 | let booking = book_ok(&app, &veli, &slot).await; |
| 18659 | |
| 18660 | // A proposal 30s into the past is inside the publishing grace, so the times |
| 18661 | // themselves validate — but the window is already underway, and a meeting |
| 18662 | // that began is one `cancel` refuses to undo. Refused at the proposal, not |
| 18663 | // left for the requester to agree to. |
| 18664 | let res = propose(&app, &ali, &booking, now - 30_000, now + HOUR_MS).await; |
| 18665 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 18666 | // Refused, not half-applied: the teacher can still propose a real time. |
| 18667 | let res = send(&app, "GET", "/appointments", Some(&veli), None).await; |
| 18668 | assert_eq!(common::items(&res.body)[0]["status"], "pending"); |
| 18669 | assert!( |
| 18670 | common::items(&res.body)[0]["proposed_starts_at"].is_null(), |
| 18671 | "a refused proposal leaves nothing behind" |
| 18672 | ); |
| 18673 | |
| 18674 | assert_eq!( |
| 18675 | propose(&app, &ali, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS) |
| 18676 | .await |
| 18677 | .status, |
| 18678 | StatusCode::OK |
| 18679 | ); |
| 18680 | let res = accept_reschedule(&app, &veli, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; |
| 18681 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18682 | assert_eq!(res.body["status"], "approved"); |
| 18683 | } |
| 18684 | |
| 18685 | #[tokio::test] |
| 18686 | async fn declining_a_reschedule_cancels_the_booking() { |
| 18687 | let (app, db) = app_and_db().await; |
| 18688 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18689 | let veli = login(&app, "veli").await; |
| 18690 | let veli_id = me_id(&app, &veli).await; |
| 18691 | let ayse = login(&app, "ayse").await; |
| 18692 | let now = Timestamp::now().as_millis(); |
| 18693 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18694 | let booking = book_ok(&app, &veli, &slot).await; |
| 18695 | |
| 18696 | // Nothing proposed yet: there is nothing to decline. |
| 18697 | let res = decide(&app, &veli, &booking, "reschedule/decline").await; |
| 18698 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 18699 | |
| 18700 | assert_eq!( |
| 18701 | propose(&app, &ali, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS) |
| 18702 | .await |
| 18703 | .status, |
| 18704 | StatusCode::OK |
| 18705 | ); |
| 18706 | let res = decide(&app, &veli, &booking, "reschedule/decline").await; |
| 18707 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18708 | assert_eq!(res.body["status"], "cancelled"); |
| 18709 | // The decliner is recorded as the canceller, with no reason. |
| 18710 | assert_eq!(res.body["cancelled_by"]["id"], veli_id.as_str()); |
| 18711 | assert!(res.body["cancel_reason"].is_null()); |
| 18712 | // The refused proposal stays readable on the cancelled row. |
| 18713 | assert_eq!(res.body["proposed_starts_at"], now + 3 * HOUR_MS); |
| 18714 | |
| 18715 | // And the slot is free again. |
| 18716 | let res = book_slot(&app, &ayse, &slot).await; |
| 18717 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 18718 | } |
| 18719 | |
| 18720 | /// Declining cancels, so it answers to the cancel deadline. The guard lives in |
| 18721 | /// `service::appointment::cancel` itself — when it sat in the cancel *handler*, decline |
| 18722 | /// went straight past it and called off a meeting already underway. |
| 18723 | #[tokio::test] |
| 18724 | async fn declining_a_started_reschedule_is_refused() { |
| 18725 | let (app, db) = app_and_db().await; |
| 18726 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18727 | let veli = login(&app, "veli").await; |
| 18728 | let now = Timestamp::now().as_millis(); |
| 18729 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18730 | let booking = book_ok(&app, &veli, &slot).await; |
| 18731 | |
| 18732 | // A proposal that is still ahead when made, and underway a moment later: |
| 18733 | // the only way an effective window opens with the booking still live. |
| 18734 | let opens_at = Timestamp::now().as_millis() + 700; |
| 18735 | assert_eq!( |
| 18736 | propose(&app, &ali, &booking, opens_at, opens_at + HOUR_MS) |
| 18737 | .await |
| 18738 | .status, |
| 18739 | StatusCode::OK |
| 18740 | ); |
| 18741 | tokio::time::sleep(std::time::Duration::from_millis(800)).await; |
| 18742 | let res = decide(&app, &veli, &booking, "reschedule/decline").await; |
| 18743 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 18744 | // The plain cancel door answers the same, and the booking survives both. |
| 18745 | let res = decide(&app, &veli, &booking, "cancel").await; |
| 18746 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 18747 | let res = send(&app, "GET", "/appointments", Some(&veli), None).await; |
| 18748 | assert_eq!(common::items(&res.body)[0]["status"], "pending"); |
| 18749 | |
| 18750 | // Moved back into the future, declining cancels as it always did. |
| 18751 | assert_eq!( |
| 18752 | propose(&app, &ali, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS) |
| 18753 | .await |
| 18754 | .status, |
| 18755 | StatusCode::OK |
| 18756 | ); |
| 18757 | let res = decide(&app, &veli, &booking, "reschedule/decline").await; |
| 18758 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18759 | assert_eq!(res.body["status"], "cancelled"); |
| 18760 | } |
| 18761 | |
| 18762 | #[tokio::test] |
| 18763 | async fn accepting_a_reschedule_re_runs_the_overlap_guard() { |
| 18764 | let (app, db) = app_and_db().await; |
| 18765 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18766 | let mert = login_as(&app, &db, "mert", "teacher").await; |
| 18767 | let veli = login(&app, "veli").await; |
| 18768 | let now = Timestamp::now().as_millis(); |
| 18769 | |
| 18770 | // Committed with ali at +5h. |
| 18771 | let taken = publish_slot(&app, &ali, now + 5 * HOUR_MS, now + 6 * HOUR_MS).await; |
| 18772 | let committed = book_ok(&app, &veli, &taken).await; |
| 18773 | assert_eq!( |
| 18774 | decide(&app, &ali, &committed, "approve").await.status, |
| 18775 | StatusCode::OK |
| 18776 | ); |
| 18777 | |
| 18778 | // Mert counter-proposes straight onto that hour; accepting would commit |
| 18779 | // the student twice, so it is refused. |
| 18780 | let slot = publish_slot(&app, &mert, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18781 | let booking = book_ok(&app, &veli, &slot).await; |
| 18782 | assert_eq!( |
| 18783 | propose(&app, &mert, &booking, now + 5 * HOUR_MS, now + 6 * HOUR_MS) |
| 18784 | .await |
| 18785 | .status, |
| 18786 | StatusCode::OK |
| 18787 | ); |
| 18788 | let res = accept_reschedule(&app, &veli, &booking, now + 5 * HOUR_MS, now + 6 * HOUR_MS).await; |
| 18789 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 18790 | assert_eq!( |
| 18791 | send(&app, "GET", "/appointments", Some(&veli), None) |
| 18792 | .await |
| 18793 | .body["items"][0]["status"], |
| 18794 | "pending", |
| 18795 | "a refused acceptance leaves the booking pending" |
| 18796 | ); |
| 18797 | } |
| 18798 | |
| 18799 | /// Only the requester (student/parent) may cancel a booking — not the slot's |
| 18800 | /// teacher, not an unrelated student. Deciders reject or reschedule instead. |
| 18801 | #[tokio::test] |
| 18802 | async fn only_the_requester_cancels() { |
| 18803 | let (app, db) = app_and_db().await; |
| 18804 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18805 | let veli = login(&app, "veli").await; |
| 18806 | let veli_id = me_id(&app, &veli).await; |
| 18807 | let ayse = login(&app, "ayse").await; |
| 18808 | let now = Timestamp::now().as_millis(); |
| 18809 | |
| 18810 | // The requester's own call, on an approved meeting. A bodyless cancel |
| 18811 | // records the actor and no reason. |
| 18812 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18813 | let booking = book_ok(&app, &veli, &slot).await; |
| 18814 | assert_eq!( |
| 18815 | decide(&app, &ali, &booking, "approve").await.status, |
| 18816 | StatusCode::OK |
| 18817 | ); |
| 18818 | let res = decide(&app, &veli, &booking, "cancel").await; |
| 18819 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18820 | assert_eq!(res.body["status"], "cancelled"); |
| 18821 | assert_eq!(res.body["cancelled_by"]["id"], veli_id.as_str()); |
| 18822 | assert!(res.body["cancel_reason"].is_null(), "no reason was given"); |
| 18823 | |
| 18824 | // A cancel carrying a reason records both the actor and the reason, and an |
| 18825 | // over-long reason is refused before the row changes. |
| 18826 | let booking = book_ok(&app, &veli, &slot).await; |
| 18827 | let res = send( |
| 18828 | &app, |
| 18829 | "PATCH", |
| 18830 | &format!("/appointments/{booking}/cancel"), |
| 18831 | Some(&veli), |
| 18832 | Some(json!({ "reason": "x".repeat(2000) })), |
| 18833 | ) |
| 18834 | .await; |
| 18835 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 18836 | let res = send( |
| 18837 | &app, |
| 18838 | "PATCH", |
| 18839 | &format!("/appointments/{booking}/cancel"), |
| 18840 | Some(&veli), |
| 18841 | Some(json!({ "reason": "Rahatsızlandım" })), |
| 18842 | ) |
| 18843 | .await; |
| 18844 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 18845 | assert_eq!(res.body["status"], "cancelled"); |
| 18846 | assert_eq!(res.body["cancelled_by"]["id"], veli_id.as_str()); |
| 18847 | assert_eq!(res.body["cancel_reason"], "Rahatsızlandım"); |
| 18848 | |
| 18849 | // The slot's teacher may NOT cancel — cancelling is the requester's lever; |
| 18850 | // a decider ends a booking by rejecting (pending) or rescheduling. |
| 18851 | let booking = book_ok(&app, &ayse, &slot).await; |
| 18852 | let res = decide(&app, &ali, &booking, "cancel").await; |
| 18853 | assert_eq!( |
| 18854 | res.status, |
| 18855 | StatusCode::FORBIDDEN, |
| 18856 | "owner-teacher: {}", |
| 18857 | res.body |
| 18858 | ); |
| 18859 | // An unrelated student may not either. |
| 18860 | let res = decide(&app, &veli, &booking, "cancel").await; |
| 18861 | assert_eq!(res.status, StatusCode::FORBIDDEN, "outsider: {}", res.body); |
| 18862 | // The requester can, and a settled booking cannot be cancelled twice. |
| 18863 | assert_eq!( |
| 18864 | decide(&app, &ayse, &booking, "cancel").await.status, |
| 18865 | StatusCode::OK |
| 18866 | ); |
| 18867 | let res = decide(&app, &ayse, &booking, "cancel").await; |
| 18868 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 18869 | } |
| 18870 | |
| 18871 | /// A student is not a decider: rejecting a booking is a teacher/manager call, |
| 18872 | /// so the requester calling `reject` on their own booking is refused. |
| 18873 | #[tokio::test] |
| 18874 | async fn student_cannot_reject_a_booking() { |
| 18875 | let (app, db) = app_and_db().await; |
| 18876 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18877 | let veli = login(&app, "veli").await; |
| 18878 | let now = Timestamp::now().as_millis(); |
| 18879 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18880 | let booking = book_ok(&app, &veli, &slot).await; |
| 18881 | |
| 18882 | let res = decide(&app, &veli, &booking, "reject").await; |
| 18883 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 18884 | } |
| 18885 | |
| 18886 | /// A slot-owning teacher may not *cancel* a booking — rejecting (pending) or |
| 18887 | /// rescheduling is their lever; cancelling belongs to the requester alone. |
| 18888 | #[tokio::test] |
| 18889 | async fn teacher_cannot_cancel_a_booking() { |
| 18890 | let (app, db) = app_and_db().await; |
| 18891 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18892 | let veli = login(&app, "veli").await; |
| 18893 | let now = Timestamp::now().as_millis(); |
| 18894 | |
| 18895 | // Pending booking: owner-teacher cancel is refused (the booking stays live). |
| 18896 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18897 | let booking = book_ok(&app, &veli, &slot).await; |
| 18898 | let res = decide(&app, &ali, &booking, "cancel").await; |
| 18899 | assert_eq!(res.status, StatusCode::FORBIDDEN, "pending: {}", res.body); |
| 18900 | |
| 18901 | // Approved booking on a fresh slot: same refusal. |
| 18902 | let slot2 = publish_slot(&app, &ali, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; |
| 18903 | let booking = book_ok(&app, &veli, &slot2).await; |
| 18904 | assert_eq!( |
| 18905 | decide(&app, &ali, &booking, "approve").await.status, |
| 18906 | StatusCode::OK |
| 18907 | ); |
| 18908 | let res = decide(&app, &ali, &booking, "cancel").await; |
| 18909 | assert_eq!(res.status, StatusCode::FORBIDDEN, "approved: {}", res.body); |
| 18910 | } |
| 18911 | |
| 18912 | /// A manager who is not the requester also cannot cancel — no oversight override |
| 18913 | /// exists; only the requester (student/parent) cancels. |
| 18914 | #[tokio::test] |
| 18915 | async fn manager_cannot_cancel_a_booking() { |
| 18916 | let (app, db) = app_and_db().await; |
| 18917 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18918 | let mgr = login_as(&app, &db, "mgr", "manager").await; |
| 18919 | let veli = login(&app, "veli").await; |
| 18920 | let now = Timestamp::now().as_millis(); |
| 18921 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18922 | let booking = book_ok(&app, &veli, &slot).await; |
| 18923 | |
| 18924 | let res = decide(&app, &mgr, &booking, "cancel").await; |
| 18925 | assert_eq!(res.status, StatusCode::FORBIDDEN, "manager: {}", res.body); |
| 18926 | } |
| 18927 | |
| 18928 | #[tokio::test] |
| 18929 | async fn a_started_slot_cannot_be_booked() { |
| 18930 | let (app, db) = app_and_db().await; |
| 18931 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18932 | let veli = login(&app, "veli").await; |
| 18933 | let now = Timestamp::now().as_millis(); |
| 18934 | |
| 18935 | // A window that opened 30s ago is inside the publishing grace, so the slot |
| 18936 | // is created — but the meeting has begun, and a meeting that began is |
| 18937 | // history, not a plan. Booking it would land a row `cancel` refuses to |
| 18938 | // undo, stuck for good. |
| 18939 | let underway = publish_slot(&app, &ali, now - 30_000, now + HOUR_MS).await; |
| 18940 | let res = book_slot(&app, &veli, &underway).await; |
| 18941 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 18942 | |
| 18943 | // A window still ahead is untouched by the guard. |
| 18944 | let upcoming = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18945 | let res = book_slot(&app, &veli, &upcoming).await; |
| 18946 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 18947 | |
| 18948 | // ...and the calendar the student browses is bounded the same way: the |
| 18949 | // underway slot is still a live row (the `409` above proves it), but |
| 18950 | // offering it would be an entry that can only be refused. |
| 18951 | let res = send(&app, "GET", "/appointments/slots", Some(&veli), None).await; |
| 18952 | let offered: Vec<&str> = common::items(&res.body) |
| 18953 | .iter() |
| 18954 | .map(|slot| slot["id"].as_str().expect("slot id")) |
| 18955 | .collect(); |
| 18956 | assert_eq!(offered, [upcoming.as_str()], "{}", res.body); |
| 18957 | // The teacher's own calendar keeps it: past occurrences are their history. |
| 18958 | let res = send(&app, "GET", "/appointments/slots", Some(&ali), None).await; |
| 18959 | assert_eq!(common::total(&res.body), 2, "{}", res.body); |
| 18960 | } |
| 18961 | |
| 18962 | #[tokio::test] |
| 18963 | async fn slot_delete_waits_for_the_booking_to_settle() { |
| 18964 | let (app, db) = app_and_db().await; |
| 18965 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 18966 | let veli = login(&app, "veli").await; |
| 18967 | let now = Timestamp::now().as_millis(); |
| 18968 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 18969 | let booking = book_ok(&app, &veli, &slot).await; |
| 18970 | |
| 18971 | let uri = format!("/appointments/slots/{slot}"); |
| 18972 | let res = send(&app, "DELETE", &uri, Some(&ali), None).await; |
| 18973 | assert_eq!( |
| 18974 | res.status, |
| 18975 | StatusCode::CONFLICT, |
| 18976 | "someone is waiting on this slot: {}", |
| 18977 | res.body |
| 18978 | ); |
| 18979 | assert_eq!( |
| 18980 | decide(&app, &veli, &booking, "cancel").await.status, |
| 18981 | StatusCode::OK |
| 18982 | ); |
| 18983 | let res = send(&app, "DELETE", &uri, Some(&ali), None).await; |
| 18984 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 18985 | // The settled booking goes with the slot, in the same transaction — it is |
| 18986 | // history of a meeting that no longer exists, and a row left pointing at a |
| 18987 | // deleted slot is a dangling link every read of it has to survive. The |
| 18988 | // `204` alone never proved the cascade ran, so the count is read from the |
| 18989 | // database (`pay_row_count` is this file's plain table count). |
| 18990 | assert_eq!( |
| 18991 | pay_row_count(&db, "appointment").await, |
| 18992 | 0, |
| 18993 | "the cancelled booking {booking} outlived its slot" |
| 18994 | ); |
| 18995 | assert_eq!( |
| 18996 | send(&app, "DELETE", &uri, Some(&ali), None).await.status, |
| 18997 | StatusCode::NOT_FOUND |
| 18998 | ); |
| 18999 | } |
| 19000 | |
| 19001 | #[tokio::test] |
| 19002 | async fn weekly_slots_share_a_series_and_are_dropped_together() { |
| 19003 | let (app, db) = app_and_db().await; |
| 19004 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 19005 | let veli = login(&app, "veli").await; |
| 19006 | let now = Timestamp::now().as_millis(); |
| 19007 | let starts_at = now + HOUR_MS; |
| 19008 | |
| 19009 | // `until` is inclusive, so three weeks out is four occurrences. |
| 19010 | let res = publish_slots( |
| 19011 | &app, |
| 19012 | &ali, |
| 19013 | json!({ "starts_at": starts_at, "ends_at": starts_at + HOUR_MS, |
| 19014 | "repeat_weekly": true, "until": starts_at + 3 * WEEK_MS }), |
| 19015 | ) |
| 19016 | .await; |
| 19017 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 19018 | let slots = res.body.as_array().expect("array body").clone(); |
| 19019 | assert_eq!(slots.len(), 4); |
| 19020 | let series = slots[0]["series"].as_str().expect("series id").to_string(); |
| 19021 | for (week, slot) in slots.iter().enumerate() { |
| 19022 | assert_eq!(slot["series"], series.as_str(), "one publish, one series"); |
| 19023 | assert_eq!(slot["starts_at"], starts_at + week as i64 * WEEK_MS); |
| 19024 | } |
| 19025 | |
| 19026 | // `repeat_weekly` without an end, and past the 52-occurrence cap. |
| 19027 | let res = publish_slots( |
| 19028 | &app, |
| 19029 | &ali, |
| 19030 | json!({ "starts_at": starts_at, "ends_at": starts_at + HOUR_MS, |
| 19031 | "repeat_weekly": true }), |
| 19032 | ) |
| 19033 | .await; |
| 19034 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 19035 | let res = publish_slots( |
| 19036 | &app, |
| 19037 | &ali, |
| 19038 | json!({ "starts_at": starts_at, "ends_at": starts_at + HOUR_MS, |
| 19039 | "repeat_weekly": true, "until": starts_at + 52 * WEEK_MS }), |
| 19040 | ) |
| 19041 | .await; |
| 19042 | assert_eq!( |
| 19043 | res.status, |
| 19044 | StatusCode::BAD_REQUEST, |
| 19045 | "53 occurrences: {}", |
| 19046 | res.body |
| 19047 | ); |
| 19048 | |
| 19049 | // An end at `i64::MAX` clears every gate — future, not inverted, 52 |
| 19050 | // occurrences — and then overflows on the first weekly shift. Unchecked it |
| 19051 | // wrapped the end below the start, and an inverted window never overlaps |
| 19052 | // anything, so the double-booking guard would have gone blind. |
| 19053 | let res = publish_slots( |
| 19054 | &app, |
| 19055 | &ali, |
| 19056 | json!({ "starts_at": starts_at, "ends_at": i64::MAX, |
| 19057 | "repeat_weekly": true, "until": starts_at + 51 * WEEK_MS }), |
| 19058 | ) |
| 19059 | .await; |
| 19060 | assert_eq!( |
| 19061 | res.status, |
| 19062 | StatusCode::BAD_REQUEST, |
| 19063 | "a shift that overflows: {}", |
| 19064 | res.body |
| 19065 | ); |
| 19066 | |
| 19067 | // All-or-nothing: one waiting requester anywhere in the series blocks it. |
| 19068 | let booked = slots[1]["id"].as_str().expect("slot id"); |
| 19069 | let booking = book_ok(&app, &veli, booked).await; |
| 19070 | let uri = format!("/appointments/slots/series/{series}"); |
| 19071 | let res = send(&app, "DELETE", &uri, Some(&ali), None).await; |
| 19072 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 19073 | |
| 19074 | assert_eq!( |
| 19075 | decide(&app, &ali, &booking, "reject").await.status, |
| 19076 | StatusCode::OK |
| 19077 | ); |
| 19078 | let res = send(&app, "DELETE", &uri, Some(&ali), None).await; |
| 19079 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 19080 | let res = send(&app, "GET", "/appointments/slots", Some(&ali), None).await; |
| 19081 | assert_eq!(common::total(&res.body), 0, "the whole series went"); |
| 19082 | assert_eq!( |
| 19083 | send(&app, "DELETE", &uri, Some(&ali), None).await.status, |
| 19084 | StatusCode::NOT_FOUND |
| 19085 | ); |
| 19086 | } |
| 19087 | |
| 19088 | #[tokio::test] |
| 19089 | async fn only_students_and_parents_book_appointments() { |
| 19090 | let (app, db) = app_and_db().await; |
| 19091 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 19092 | let mert = login_as(&app, &db, "mert", "teacher").await; |
| 19093 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 19094 | let admin = login_as(&app, &db, "yonetici", "admin").await; |
| 19095 | let anne = login_as(&app, &db, "anne", "parent").await; |
| 19096 | let veli = login(&app, "veli").await; |
| 19097 | let now = Timestamp::now().as_millis(); |
| 19098 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 19099 | |
| 19100 | // Staff arrange between themselves off this API. |
| 19101 | for (who, label) in [(&mert, "teacher"), (&mudur, "manager"), (&admin, "admin")] { |
| 19102 | let res = book_slot(&app, who, &slot).await; |
| 19103 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{label}: {}", res.body); |
| 19104 | } |
| 19105 | // A parent books for themselves — the parent-teacher conference. |
| 19106 | let res = book_slot(&app, &anne, &slot).await; |
| 19107 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 19108 | let second = publish_slot(&app, &ali, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; |
| 19109 | let res = book_slot(&app, &veli, &second).await; |
| 19110 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 19111 | } |
| 19112 | |
| 19113 | #[tokio::test] |
| 19114 | async fn only_the_slots_teacher_decides_its_bookings() { |
| 19115 | let (app, db) = app_and_db().await; |
| 19116 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 19117 | let mert = login_as(&app, &db, "mert", "teacher").await; |
| 19118 | let mudur = login_as(&app, &db, "mudur", "manager").await; |
| 19119 | let veli = login(&app, "veli").await; |
| 19120 | let now = Timestamp::now().as_millis(); |
| 19121 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 19122 | let booking = book_ok(&app, &veli, &slot).await; |
| 19123 | |
| 19124 | // Another teacher's calendar is not theirs to run. |
| 19125 | for action in ["approve", "reject"] { |
| 19126 | let res = decide(&app, &mert, &booking, action).await; |
| 19127 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{action}: {}", res.body); |
| 19128 | } |
| 19129 | let res = propose(&app, &mert, &booking, now + 3 * HOUR_MS, now + 4 * HOUR_MS).await; |
| 19130 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 19131 | let res = send( |
| 19132 | &app, |
| 19133 | "DELETE", |
| 19134 | &format!("/appointments/slots/{slot}"), |
| 19135 | Some(&mert), |
| 19136 | None, |
| 19137 | ) |
| 19138 | .await; |
| 19139 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 19140 | // The requester cannot approve their own request either. |
| 19141 | assert_eq!( |
| 19142 | decide(&app, &veli, &booking, "approve").await.status, |
| 19143 | StatusCode::FORBIDDEN |
| 19144 | ); |
| 19145 | // A manager may decide anyone's. |
| 19146 | let res = decide(&app, &mudur, &booking, "approve").await; |
| 19147 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 19148 | assert_eq!(res.body["status"], "approved"); |
| 19149 | } |
| 19150 | |
| 19151 | #[tokio::test] |
| 19152 | async fn appointment_times_must_be_sane_and_future() { |
| 19153 | let (app, db) = app_and_db().await; |
| 19154 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 19155 | let veli = login(&app, "veli").await; |
| 19156 | let now = Timestamp::now().as_millis(); |
| 19157 | |
| 19158 | // Past (beyond the 60s grace), empty, and inverted windows. |
| 19159 | for (body, label) in [ |
| 19160 | ( |
| 19161 | json!({ "starts_at": now - 10 * HOUR_MS, "ends_at": now - 9 * HOUR_MS }), |
| 19162 | "past", |
| 19163 | ), |
| 19164 | ( |
| 19165 | json!({ "starts_at": now + HOUR_MS, "ends_at": now + HOUR_MS }), |
| 19166 | "empty", |
| 19167 | ), |
| 19168 | ( |
| 19169 | json!({ "starts_at": now + 2 * HOUR_MS, "ends_at": now + HOUR_MS }), |
| 19170 | "inverted", |
| 19171 | ), |
| 19172 | ] { |
| 19173 | let res = publish_slots(&app, &ali, body).await; |
| 19174 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{label}: {}", res.body); |
| 19175 | } |
| 19176 | |
| 19177 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 19178 | let booking = book_ok(&app, &veli, &slot).await; |
| 19179 | // A counter-proposal answers to the same rules. |
| 19180 | for (starts_at, ends_at, label) in [ |
| 19181 | (now - 10 * HOUR_MS, now - 9 * HOUR_MS, "past"), |
| 19182 | (now + HOUR_MS, now + HOUR_MS, "empty"), |
| 19183 | (now + 2 * HOUR_MS, now + HOUR_MS, "inverted"), |
| 19184 | ] { |
| 19185 | let res = propose(&app, &ali, &booking, starts_at, ends_at).await; |
| 19186 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{label}: {}", res.body); |
| 19187 | } |
| 19188 | // A blank reason is refused too — the teacher decides on it. |
| 19189 | let res = send( |
| 19190 | &app, |
| 19191 | "POST", |
| 19192 | "/appointments", |
| 19193 | Some(&veli), |
| 19194 | Some(json!({ "slot": slot, "reason": "" })), |
| 19195 | ) |
| 19196 | .await; |
| 19197 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 19198 | } |
| 19199 | |
| 19200 | #[tokio::test] |
| 19201 | async fn a_demoted_teachers_slots_go_inert() { |
| 19202 | let (app, db) = app_and_db().await; |
| 19203 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 19204 | let veli = login(&app, "veli").await; |
| 19205 | let now = Timestamp::now().as_millis(); |
| 19206 | let slot = publish_slot(&app, &ali, now + HOUR_MS, now + 2 * HOUR_MS).await; |
| 19207 | |
| 19208 | let res = send(&app, "GET", "/appointments/slots", Some(&veli), None).await; |
| 19209 | assert_eq!(common::items(&res.body).len(), 1, "{}", res.body); |
| 19210 | |
| 19211 | // The row survives the demotion; the offer does not. |
| 19212 | set_role(&db, "ali", "student").await; |
| 19213 | let res = send(&app, "GET", "/appointments/slots", Some(&veli), None).await; |
| 19214 | assert_eq!(common::total(&res.body), 0, "an inert slot is not offered"); |
| 19215 | let res = book_slot(&app, &veli, &slot).await; |
| 19216 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 19217 | } |
| 19218 | |
| 19219 | // --- per-attempt history (retakes preserve prior sittings) ------------------ |
| 19220 | |
| 19221 | /// Sit an exam, answer + draw, retake, answer + draw differently — then the |
| 19222 | /// teacher's per-attempt history endpoints still surface the seq-1 sitting |
| 19223 | /// alongside seq-2: the attempts list is `[1, 2]`, and each seq's answer text |
| 19224 | /// and drawing bytes are its own, not the latest sitting's. |
| 19225 | #[tokio::test] |
| 19226 | async fn attempt_history_preserves_each_prior_sitting() { |
| 19227 | let (app, db) = app_and_db().await; |
| 19228 | let teacher = login_as(&app, &db, "hist_t", "teacher").await; |
| 19229 | let student = login(&app, "hist_s").await; |
| 19230 | let student_id = me_id(&app, &student).await; |
| 19231 | |
| 19232 | let mudur = login_as(&app, &db, "hist_m", "manager").await; |
| 19233 | let t = taught_under(&app, &mudur, &teacher, "biology").await; |
| 19234 | let subject = create_subject(&app, &teacher, &t.course, "cells").await; |
| 19235 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 19236 | let exam = scheduled_exam( |
| 19237 | &app, |
| 19238 | &teacher, |
| 19239 | &t.instance, |
| 19240 | json!({ "term": &t.term, "title": "cell quiz", "kind": "yazili", |
| 19241 | "mode": "open", "max_attempts": 2 }), |
| 19242 | ) |
| 19243 | .await; |
| 19244 | let question_body = create_question_body( |
| 19245 | &app, |
| 19246 | &teacher, |
| 19247 | &exam, |
| 19248 | &subject, |
| 19249 | json!({ "text": "Name an organelle.", "kind": "text", "points": 10 }), |
| 19250 | ) |
| 19251 | .await; |
| 19252 | let question = id_of(&question_body); |
| 19253 | let own_image = format!("/exams/{exam}/attempt/answers/{question}/image"); |
| 19254 | |
| 19255 | // Seq 1: answer, draw, finish. |
| 19256 | let res = send( |
| 19257 | &app, |
| 19258 | "POST", |
| 19259 | &format!("/exams/{exam}/attempt"), |
| 19260 | Some(&student), |
| 19261 | None, |
| 19262 | ) |
| 19263 | .await; |
| 19264 | assert_eq!(res.status, StatusCode::CREATED, "sit seq 1: {}", res.body); |
| 19265 | let res = send( |
| 19266 | &app, |
| 19267 | "POST", |
| 19268 | &format!("/exams/{exam}/attempt/answers"), |
| 19269 | Some(&student), |
| 19270 | Some(json!({ "question_id": question, "text": "mitochondria" })), |
| 19271 | ) |
| 19272 | .await; |
| 19273 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 19274 | let (status, _) = post_image(&app, &student, &own_image, "image/png", b"seq1-draw").await; |
| 19275 | assert_eq!(status, StatusCode::CREATED); |
| 19276 | send( |
| 19277 | &app, |
| 19278 | "POST", |
| 19279 | &format!("/exams/{exam}/attempt/finish"), |
| 19280 | Some(&student), |
| 19281 | None, |
| 19282 | ) |
| 19283 | .await; |
| 19284 | // Seq 2: retake, answer + draw differently. |
| 19285 | let res = send( |
| 19286 | &app, |
| 19287 | "POST", |
| 19288 | &format!("/exams/{exam}/attempt"), |
| 19289 | Some(&student), |
| 19290 | None, |
| 19291 | ) |
| 19292 | .await; |
| 19293 | assert_eq!(res.body["attempt"], 2, "retake is the second sitting"); |
| 19294 | let res = send( |
| 19295 | &app, |
| 19296 | "POST", |
| 19297 | &format!("/exams/{exam}/attempt/answers"), |
| 19298 | Some(&student), |
| 19299 | Some(json!({ "question_id": question, "text": "chloroplast" })), |
| 19300 | ) |
| 19301 | .await; |
| 19302 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 19303 | let (status, _) = post_image(&app, &student, &own_image, "image/png", b"seq2-draw").await; |
| 19304 | assert_eq!(status, StatusCode::CREATED); |
| 19305 | |
| 19306 | // The attempts list carries both sittings, ascending. |
| 19307 | let res = send( |
| 19308 | &app, |
| 19309 | "GET", |
| 19310 | &format!("/exams/{exam}/students/{student_id}/attempts"), |
| 19311 | Some(&teacher), |
| 19312 | None, |
| 19313 | ) |
| 19314 | .await; |
| 19315 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 19316 | assert_eq!(res.body, json!([1, 2])); |
| 19317 | |
| 19318 | // Each sitting keeps its own answer text — seq 1 was NOT overwritten. |
| 19319 | let seq1 = send( |
| 19320 | &app, |
| 19321 | "GET", |
| 19322 | &format!("/exams/{exam}/students/{student_id}/attempts/1/answers"), |
| 19323 | Some(&teacher), |
| 19324 | None, |
| 19325 | ) |
| 19326 | .await; |
| 19327 | let seq2 = send( |
| 19328 | &app, |
| 19329 | "GET", |
| 19330 | &format!("/exams/{exam}/students/{student_id}/attempts/2/answers"), |
| 19331 | Some(&teacher), |
| 19332 | None, |
| 19333 | ) |
| 19334 | .await; |
| 19335 | assert_eq!(seq1.body["answers"][0]["text"], "mitochondria"); |
| 19336 | assert_eq!(seq2.body["answers"][0]["text"], "chloroplast"); |
| 19337 | assert_ne!( |
| 19338 | seq1.body["answers"][0]["text"], |
| 19339 | seq2.body["answers"][0]["text"] |
| 19340 | ); |
| 19341 | |
| 19342 | // Each sitting keeps its own drawing bytes. |
| 19343 | for (seq, want) in [(1, b"seq1-draw".as_slice()), (2, b"seq2-draw".as_slice())] { |
| 19344 | let uri = |
| 19345 | format!("/exams/{exam}/students/{student_id}/attempts/{seq}/answers/{question}/image"); |
| 19346 | let (status, _, bytes) = |
| 19347 | common::send_raw(&app, "GET", &uri, Some(&teacher), None, Vec::new()).await; |
| 19348 | assert_eq!(status, StatusCode::OK, "seq {seq} image"); |
| 19349 | assert_eq!(bytes, want, "seq {seq} kept its own drawing"); |
| 19350 | } |
| 19351 | } |
| 19352 | |
| 19353 | /// The grade-of-record follows the latest sitting: grading seq 1, then seq 2 |
| 19354 | /// with a different mark, leaves the roster read showing seq 2's mark — while |
| 19355 | /// the full mark-history endpoint returns both, oldest first. |
| 19356 | #[tokio::test] |
| 19357 | async fn grade_of_record_is_latest_but_history_keeps_both() { |
| 19358 | let (app, db) = app_and_db().await; |
| 19359 | let teacher = login_as(&app, &db, "grd_t", "teacher").await; |
| 19360 | let student = login(&app, "grd_s").await; |
| 19361 | let student_id = me_id(&app, &student).await; |
| 19362 | |
| 19363 | let mudur = login_as(&app, &db, "grd_m", "manager").await; |
| 19364 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 19365 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 19366 | let exam = scheduled_exam( |
| 19367 | &app, |
| 19368 | &teacher, |
| 19369 | &t.instance, |
| 19370 | json!({ "term": &t.term, "title": "drill", "kind": "yazili", |
| 19371 | "mode": "open", "max_attempts": 2 }), |
| 19372 | ) |
| 19373 | .await; |
| 19374 | |
| 19375 | let results_uri = format!("/exams/{exam}/results"); |
| 19376 | |
| 19377 | // Seq 1: sit, grade 40, finish. |
| 19378 | send( |
| 19379 | &app, |
| 19380 | "POST", |
| 19381 | &format!("/exams/{exam}/attempt"), |
| 19382 | Some(&student), |
| 19383 | None, |
| 19384 | ) |
| 19385 | .await; |
| 19386 | let res = send( |
| 19387 | &app, |
| 19388 | "POST", |
| 19389 | &results_uri, |
| 19390 | Some(&teacher), |
| 19391 | Some(json!({ "mark": 40, "user_id": student_id })), |
| 19392 | ) |
| 19393 | .await; |
| 19394 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 19395 | send( |
| 19396 | &app, |
| 19397 | "POST", |
| 19398 | &format!("/exams/{exam}/attempt/finish"), |
| 19399 | Some(&student), |
| 19400 | None, |
| 19401 | ) |
| 19402 | .await; |
| 19403 | // Seq 2: retake, grade 90 — the mark lands on the new sitting. |
| 19404 | send( |
| 19405 | &app, |
| 19406 | "POST", |
| 19407 | &format!("/exams/{exam}/attempt"), |
| 19408 | Some(&student), |
| 19409 | None, |
| 19410 | ) |
| 19411 | .await; |
| 19412 | let res = send( |
| 19413 | &app, |
| 19414 | "POST", |
| 19415 | &results_uri, |
| 19416 | Some(&teacher), |
| 19417 | Some(json!({ "mark": 90, "user_id": student_id })), |
| 19418 | ) |
| 19419 | .await; |
| 19420 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 19421 | |
| 19422 | // The roster (latest-per-pair) reports one row, at seq 2's mark. |
| 19423 | let res = send( |
| 19424 | &app, |
| 19425 | "GET", |
| 19426 | &format!("/exams/{exam}/results"), |
| 19427 | Some(&teacher), |
| 19428 | None, |
| 19429 | ) |
| 19430 | .await; |
| 19431 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 19432 | let rows = common::items(&res.body); |
| 19433 | assert_eq!(rows.len(), 1, "one grade-of-record per student"); |
| 19434 | assert_eq!(rows[0]["mark"], 90, "latest sitting is the grade-of-record"); |
| 19435 | |
| 19436 | // The history endpoint keeps both marks, oldest first. |
| 19437 | let res = send( |
| 19438 | &app, |
| 19439 | "GET", |
| 19440 | &format!("/exams/{exam}/students/{student_id}/marks"), |
| 19441 | Some(&teacher), |
| 19442 | None, |
| 19443 | ) |
| 19444 | .await; |
| 19445 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 19446 | let marks: Vec<i64> = res |
| 19447 | .body |
| 19448 | .as_array() |
| 19449 | .unwrap() |
| 19450 | .iter() |
| 19451 | .map(|r| r["mark"].as_i64().unwrap()) |
| 19452 | .collect(); |
| 19453 | assert_eq!(marks, vec![40, 90], "both sittings' marks, oldest first"); |
| 19454 | } |
| 19455 | |
| 19456 | /// The per-attempt history endpoints are teacher-only: an enrolled student |
| 19457 | /// asking for another student's history is refused, like every grader read. |
| 19458 | #[tokio::test] |
| 19459 | async fn attempt_history_endpoints_are_teacher_walled() { |
| 19460 | let (app, db) = app_and_db().await; |
| 19461 | let teacher = login_as(&app, &db, "wall_t", "teacher").await; |
| 19462 | let student = login(&app, "wall_s").await; |
| 19463 | let student_id = me_id(&app, &student).await; |
| 19464 | let snooper = login(&app, "wall_o").await; |
| 19465 | |
| 19466 | let mudur = login_as(&app, &db, "wall_m", "manager").await; |
| 19467 | let t = taught_under(&app, &mudur, &teacher, "history").await; |
| 19468 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 19469 | let exam = scheduled_exam( |
| 19470 | &app, |
| 19471 | &teacher, |
| 19472 | &t.instance, |
| 19473 | json!({ "term": &t.term, "title": "quiz", "kind": "yazili", "mode": "open" }), |
| 19474 | ) |
| 19475 | .await; |
| 19476 | |
| 19477 | // A non-teacher student is refused on every history route for another student. |
| 19478 | for uri in [ |
| 19479 | format!("/exams/{exam}/students/{student_id}/attempts"), |
| 19480 | format!("/exams/{exam}/students/{student_id}/attempts/1/answers"), |
| 19481 | format!("/exams/{exam}/students/{student_id}/marks"), |
| 19482 | ] { |
| 19483 | let res = send(&app, "GET", &uri, Some(&snooper), None).await; |
| 19484 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri}"); |
| 19485 | } |
| 19486 | } |
| 19487 | |
| 19488 | // --- student self-review (own-scoped, allow_review + a mark gate it) --------- |
| 19489 | |
| 19490 | /// Sit, answer, teacher grades — but with `allow_review` left at its default |
| 19491 | /// (false), the student's own review read is refused: 403, "review not enabled". |
| 19492 | #[tokio::test] |
| 19493 | async fn self_review_is_forbidden_until_the_teacher_enables_it() { |
| 19494 | let (app, db) = app_and_db().await; |
| 19495 | let teacher = login_as(&app, &db, "rev_off_t", "teacher").await; |
| 19496 | let student = login(&app, "rev_off_s").await; |
| 19497 | let student_id = me_id(&app, &student).await; |
| 19498 | |
| 19499 | let mudur = login_as(&app, &db, "physics_m", "manager").await; |
| 19500 | let t = taught_under(&app, &mudur, &teacher, "physics").await; |
| 19501 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 19502 | let exam = scheduled_exam( |
| 19503 | &app, |
| 19504 | &teacher, |
| 19505 | &t.instance, |
| 19506 | json!({ "term": &t.term, "title": "kinematics", "kind": "yazili", "mode": "open" }), |
| 19507 | ) |
| 19508 | .await; |
| 19509 | |
| 19510 | send( |
| 19511 | &app, |
| 19512 | "POST", |
| 19513 | &format!("/exams/{exam}/attempt"), |
| 19514 | Some(&student), |
| 19515 | None, |
| 19516 | ) |
| 19517 | .await; |
| 19518 | let res = send( |
| 19519 | &app, |
| 19520 | "POST", |
| 19521 | &format!("/exams/{exam}/results"), |
| 19522 | Some(&teacher), |
| 19523 | Some(json!({ "mark": 55, "user_id": student_id })), |
| 19524 | ) |
| 19525 | .await; |
| 19526 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 19527 | |
| 19528 | let res = send( |
| 19529 | &app, |
| 19530 | "GET", |
| 19531 | &format!("/exams/{exam}/review/attempts"), |
| 19532 | Some(&student), |
| 19533 | None, |
| 19534 | ) |
| 19535 | .await; |
| 19536 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 19537 | } |
| 19538 | |
| 19539 | /// `allow_review` on, but the student has no mark yet — nothing to review, so |
| 19540 | /// the gate 404s rather than leaking an empty (or in-progress) sheet. |
| 19541 | #[tokio::test] |
| 19542 | async fn self_review_is_not_found_until_a_mark_exists() { |
| 19543 | let (app, db) = app_and_db().await; |
| 19544 | let teacher = login_as(&app, &db, "rev_ungraded_t", "teacher").await; |
| 19545 | let student = login(&app, "rev_ungraded_s").await; |
| 19546 | let student_id = me_id(&app, &student).await; |
| 19547 | |
| 19548 | let mudur = login_as(&app, &db, "chemistry_m", "manager").await; |
| 19549 | let t = taught_under(&app, &mudur, &teacher, "chemistry").await; |
| 19550 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 19551 | let exam = scheduled_exam( |
| 19552 | &app, |
| 19553 | &teacher, |
| 19554 | &t.instance, |
| 19555 | json!({ "term": &t.term, "title": "moles", "kind": "yazili", |
| 19556 | "mode": "open", "allow_review": true }), |
| 19557 | ) |
| 19558 | .await; |
| 19559 | |
| 19560 | // Sat, but never graded — no ExamResult row. |
| 19561 | send( |
| 19562 | &app, |
| 19563 | "POST", |
| 19564 | &format!("/exams/{exam}/attempt"), |
| 19565 | Some(&student), |
| 19566 | None, |
| 19567 | ) |
| 19568 | .await; |
| 19569 | |
| 19570 | let res = send( |
| 19571 | &app, |
| 19572 | "GET", |
| 19573 | &format!("/exams/{exam}/review/attempts"), |
| 19574 | Some(&student), |
| 19575 | None, |
| 19576 | ) |
| 19577 | .await; |
| 19578 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 19579 | } |
| 19580 | |
| 19581 | /// A draft exam is invisible to students even with review on and a mark in hand: |
| 19582 | /// the draft check comes first, so every self-review read is a flat 404. |
| 19583 | #[tokio::test] |
| 19584 | async fn self_review_of_a_draft_exam_is_not_found() { |
| 19585 | let (app, db) = app_and_db().await; |
| 19586 | let teacher = login_as(&app, &db, "rev_draft_t", "teacher").await; |
| 19587 | let student = login(&app, "rev_draft_s").await; |
| 19588 | let student_id = me_id(&app, &student).await; |
| 19589 | |
| 19590 | let mudur = login_as(&app, &db, "geography_m", "manager").await; |
| 19591 | let t = taught_under(&app, &mudur, &teacher, "geography").await; |
| 19592 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 19593 | let exam = scheduled_exam( |
| 19594 | &app, |
| 19595 | &teacher, |
| 19596 | &t.instance, |
| 19597 | json!({ |
| 19598 | "term": &t.term, "title": "maps", "kind": "yazili", "mode": "open", |
| 19599 | "allow_review": true, "draft": true, |
| 19600 | }), |
| 19601 | ) |
| 19602 | .await; |
| 19603 | |
| 19604 | for uri in [ |
| 19605 | format!("/exams/{exam}/review/attempts"), |
| 19606 | format!("/exams/{exam}/review/attempts/1/answers"), |
| 19607 | ] { |
| 19608 | let res = send(&app, "GET", &uri, Some(&student), None).await; |
| 19609 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{uri}: {}", res.body); |
| 19610 | } |
| 19611 | } |
| 19612 | |
| 19613 | /// The happy path across retakes: review on, both sittings graded, and the |
| 19614 | /// student reads their own seqs `[1, 2]` plus each sitting's own answer text — |
| 19615 | /// seq 1 was not overwritten by the retake. |
| 19616 | #[tokio::test] |
| 19617 | async fn self_review_returns_own_seqs_and_per_sitting_answers() { |
| 19618 | let (app, db) = app_and_db().await; |
| 19619 | let teacher = login_as(&app, &db, "rev_ok_t", "teacher").await; |
| 19620 | let student = login(&app, "rev_ok_s").await; |
| 19621 | let student_id = me_id(&app, &student).await; |
| 19622 | |
| 19623 | let mudur = login_as(&app, &db, "biology_m", "manager").await; |
| 19624 | let t = taught_under(&app, &mudur, &teacher, "biology").await; |
| 19625 | let subject = create_subject(&app, &teacher, &t.course, "cells").await; |
| 19626 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 19627 | let exam = scheduled_exam( |
| 19628 | &app, |
| 19629 | &teacher, |
| 19630 | &t.instance, |
| 19631 | json!({ |
| 19632 | "term": &t.term, "title": "cell quiz", "kind": "yazili", "mode": "open", |
| 19633 | "max_attempts": 2, "allow_review": true, |
| 19634 | }), |
| 19635 | ) |
| 19636 | .await; |
| 19637 | let question_body = create_question_body( |
| 19638 | &app, |
| 19639 | &teacher, |
| 19640 | &exam, |
| 19641 | &subject, |
| 19642 | json!({ "text": "Name an organelle.", "kind": "text", "points": 10 }), |
| 19643 | ) |
| 19644 | .await; |
| 19645 | let question = id_of(&question_body); |
| 19646 | let results_uri = format!("/exams/{exam}/results"); |
| 19647 | |
| 19648 | // Seq 1: answer, grade, finish. |
| 19649 | send( |
| 19650 | &app, |
| 19651 | "POST", |
| 19652 | &format!("/exams/{exam}/attempt"), |
| 19653 | Some(&student), |
| 19654 | None, |
| 19655 | ) |
| 19656 | .await; |
| 19657 | send( |
| 19658 | &app, |
| 19659 | "POST", |
| 19660 | &format!("/exams/{exam}/attempt/answers"), |
| 19661 | Some(&student), |
| 19662 | Some(json!({ "question_id": question, "text": "mitochondria" })), |
| 19663 | ) |
| 19664 | .await; |
| 19665 | send( |
| 19666 | &app, |
| 19667 | "POST", |
| 19668 | &results_uri, |
| 19669 | Some(&teacher), |
| 19670 | Some(json!({ "mark": 40, "user_id": student_id })), |
| 19671 | ) |
| 19672 | .await; |
| 19673 | send( |
| 19674 | &app, |
| 19675 | "POST", |
| 19676 | &format!("/exams/{exam}/attempt/finish"), |
| 19677 | Some(&student), |
| 19678 | None, |
| 19679 | ) |
| 19680 | .await; |
| 19681 | // Seq 2: retake, answer differently, grade. |
| 19682 | send( |
| 19683 | &app, |
| 19684 | "POST", |
| 19685 | &format!("/exams/{exam}/attempt"), |
| 19686 | Some(&student), |
| 19687 | None, |
| 19688 | ) |
| 19689 | .await; |
| 19690 | send( |
| 19691 | &app, |
| 19692 | "POST", |
| 19693 | &format!("/exams/{exam}/attempt/answers"), |
| 19694 | Some(&student), |
| 19695 | Some(json!({ "question_id": question, "text": "chloroplast" })), |
| 19696 | ) |
| 19697 | .await; |
| 19698 | send( |
| 19699 | &app, |
| 19700 | "POST", |
| 19701 | &results_uri, |
| 19702 | Some(&teacher), |
| 19703 | Some(json!({ "mark": 90, "user_id": student_id })), |
| 19704 | ) |
| 19705 | .await; |
| 19706 | // Review refuses while the sitting is still writable, so submit it first. |
| 19707 | send( |
| 19708 | &app, |
| 19709 | "POST", |
| 19710 | &format!("/exams/{exam}/attempt/finish"), |
| 19711 | Some(&student), |
| 19712 | None, |
| 19713 | ) |
| 19714 | .await; |
| 19715 | |
| 19716 | // Own seqs, ascending. |
| 19717 | let res = send( |
| 19718 | &app, |
| 19719 | "GET", |
| 19720 | &format!("/exams/{exam}/review/attempts"), |
| 19721 | Some(&student), |
| 19722 | None, |
| 19723 | ) |
| 19724 | .await; |
| 19725 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 19726 | assert_eq!(res.body, json!([1, 2])); |
| 19727 | |
| 19728 | // Each sitting keeps its own answer text. |
| 19729 | let seq1 = send( |
| 19730 | &app, |
| 19731 | "GET", |
| 19732 | &format!("/exams/{exam}/review/attempts/1/answers"), |
| 19733 | Some(&student), |
| 19734 | None, |
| 19735 | ) |
| 19736 | .await; |
| 19737 | let seq2 = send( |
| 19738 | &app, |
| 19739 | "GET", |
| 19740 | &format!("/exams/{exam}/review/attempts/2/answers"), |
| 19741 | Some(&student), |
| 19742 | None, |
| 19743 | ) |
| 19744 | .await; |
| 19745 | assert_eq!(seq1.status, StatusCode::OK, "{}", seq1.body); |
| 19746 | assert_eq!(seq1.body["answers"][0]["text"], "mitochondria"); |
| 19747 | assert_eq!(seq2.body["answers"][0]["text"], "chloroplast"); |
| 19748 | |
| 19749 | // The answer key: a marked student reads the questions with `correct` |
| 19750 | // exposed (the whole point of review) — the same list the teacher sees. |
| 19751 | let key = send( |
| 19752 | &app, |
| 19753 | "GET", |
| 19754 | &format!("/exams/{exam}/review/questions"), |
| 19755 | Some(&student), |
| 19756 | None, |
| 19757 | ) |
| 19758 | .await; |
| 19759 | assert_eq!(key.status, StatusCode::OK, "{}", key.body); |
| 19760 | assert_eq!(key.body["items"][0]["id"], question); |
| 19761 | assert!( |
| 19762 | key.body["items"][0] |
| 19763 | .as_object() |
| 19764 | .unwrap() |
| 19765 | .contains_key("correct"), |
| 19766 | "review/questions must expose `correct`: {}", |
| 19767 | key.body |
| 19768 | ); |
| 19769 | } |
| 19770 | |
| 19771 | /// Own-scoped isolation: two graded students, review on. There is no `{user}` |
| 19772 | /// path param, so student A's token resolves to A — A sees A's own seqs and |
| 19773 | /// answer text, never B's, even though both are graded on the same exam. |
| 19774 | #[tokio::test] |
| 19775 | async fn self_review_is_own_scoped_between_students() { |
| 19776 | let (app, db) = app_and_db().await; |
| 19777 | let teacher = login_as(&app, &db, "rev_iso_t", "teacher").await; |
| 19778 | let alice = login(&app, "rev_iso_a").await; |
| 19779 | let alice_id = me_id(&app, &alice).await; |
| 19780 | let bob = login(&app, "rev_iso_b").await; |
| 19781 | let bob_id = me_id(&app, &bob).await; |
| 19782 | |
| 19783 | let mudur = login_as(&app, &db, "history_m", "manager").await; |
| 19784 | let t = taught_under(&app, &mudur, &teacher, "history").await; |
| 19785 | let subject = create_subject(&app, &teacher, &t.course, "rome").await; |
| 19786 | enroll(&app, &teacher, &t.instance, &alice_id).await; |
| 19787 | enroll(&app, &teacher, &t.instance, &bob_id).await; |
| 19788 | let exam = scheduled_exam( |
| 19789 | &app, |
| 19790 | &teacher, |
| 19791 | &t.instance, |
| 19792 | json!({ "term": &t.term, "title": "quiz", "kind": "yazili", |
| 19793 | "mode": "open", "allow_review": true }), |
| 19794 | ) |
| 19795 | .await; |
| 19796 | let question_body = create_question_body( |
| 19797 | &app, |
| 19798 | &teacher, |
| 19799 | &exam, |
| 19800 | &subject, |
| 19801 | json!({ "text": "Name a consul.", "kind": "text", "points": 10 }), |
| 19802 | ) |
| 19803 | .await; |
| 19804 | let question = id_of(&question_body); |
| 19805 | let results_uri = format!("/exams/{exam}/results"); |
| 19806 | |
| 19807 | for (who, id, text, mark) in [ |
| 19808 | (&alice, &alice_id, "cicero", 70), |
| 19809 | (&bob, &bob_id, "cato", 30), |
| 19810 | ] { |
| 19811 | send( |
| 19812 | &app, |
| 19813 | "POST", |
| 19814 | &format!("/exams/{exam}/attempt"), |
| 19815 | Some(who), |
| 19816 | None, |
| 19817 | ) |
| 19818 | .await; |
| 19819 | send( |
| 19820 | &app, |
| 19821 | "POST", |
| 19822 | &format!("/exams/{exam}/attempt/answers"), |
| 19823 | Some(who), |
| 19824 | Some(json!({ "question_id": question, "text": text })), |
| 19825 | ) |
| 19826 | .await; |
| 19827 | send( |
| 19828 | &app, |
| 19829 | "POST", |
| 19830 | &results_uri, |
| 19831 | Some(&teacher), |
| 19832 | Some(json!({ "mark": mark, "user_id": id })), |
| 19833 | ) |
| 19834 | .await; |
| 19835 | // Review refuses while the sitting is still writable. |
| 19836 | send( |
| 19837 | &app, |
| 19838 | "POST", |
| 19839 | &format!("/exams/{exam}/attempt/finish"), |
| 19840 | Some(who), |
| 19841 | None, |
| 19842 | ) |
| 19843 | .await; |
| 19844 | } |
| 19845 | |
| 19846 | // Alice's token sees only Alice's data — one seq, her own answer. |
| 19847 | let res = send( |
| 19848 | &app, |
| 19849 | "GET", |
| 19850 | &format!("/exams/{exam}/review/attempts"), |
| 19851 | Some(&alice), |
| 19852 | None, |
| 19853 | ) |
| 19854 | .await; |
| 19855 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 19856 | assert_eq!(res.body, json!([1])); |
| 19857 | let sheet = send( |
| 19858 | &app, |
| 19859 | "GET", |
| 19860 | &format!("/exams/{exam}/review/attempts/1/answers"), |
| 19861 | Some(&alice), |
| 19862 | None, |
| 19863 | ) |
| 19864 | .await; |
| 19865 | assert_eq!( |
| 19866 | sheet.body["answers"][0]["text"], "cicero", |
| 19867 | "A sees her own answer" |
| 19868 | ); |
| 19869 | assert_ne!(sheet.body["answers"][0]["text"], "cato", "never B's answer"); |
| 19870 | } |
| 19871 | |
| 19872 | // --- question bank ----------------------------------------------------------- |
| 19873 | |
| 19874 | #[tokio::test] |
| 19875 | async fn bank_question_create_get_list_and_instantiate() { |
| 19876 | let (app, db) = app_and_db().await; |
| 19877 | let teacher = login_as(&app, &db, "bank_t", "teacher").await; |
| 19878 | let mudur = login_as(&app, &db, "algebra_m", "manager").await; |
| 19879 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 19880 | let subject = create_subject(&app, &teacher, &t.course, "linear").await; |
| 19881 | select_instance_subject(&app, &teacher, &t.instance, &subject).await; |
| 19882 | |
| 19883 | // Create a template — subject is origin metadata, not held to a course. |
| 19884 | let res = send( |
| 19885 | &app, |
| 19886 | "POST", |
| 19887 | "/bank-questions", |
| 19888 | Some(&teacher), |
| 19889 | Some(json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice", |
| 19890 | "points": 10, "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}, {"id": "c2", "text": "5"}], "correct": "c1" })), |
| 19891 | ) |
| 19892 | .await; |
| 19893 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 19894 | assert_eq!(res.body["kind"], "choice"); |
| 19895 | assert_eq!(res.body["correct"], res.body["choices"][1]["id"]); |
| 19896 | assert_eq!(res.body["subject"], subject); |
| 19897 | let bid = id_of(&res.body); |
| 19898 | |
| 19899 | // School-wide read + list. |
| 19900 | let res = send( |
| 19901 | &app, |
| 19902 | "GET", |
| 19903 | &format!("/bank-questions/{bid}"), |
| 19904 | Some(&teacher), |
| 19905 | None, |
| 19906 | ) |
| 19907 | .await; |
| 19908 | assert_eq!(res.status, StatusCode::OK); |
| 19909 | assert_eq!(res.body["text"], "2 + 2?"); |
| 19910 | let res = send(&app, "GET", "/bank-questions", Some(&teacher), None).await; |
| 19911 | assert_eq!(common::items(&res.body).len(), 1); |
| 19912 | |
| 19913 | // `?subject=` matches, a valid foreign id excludes — and a malformed key |
| 19914 | // is the 400 that names the field, never a silent empty page (the same |
| 19915 | // rule the offerings filter follows). |
| 19916 | let res = send( |
| 19917 | &app, |
| 19918 | "GET", |
| 19919 | &format!("/bank-questions?subject={subject}"), |
| 19920 | Some(&teacher), |
| 19921 | None, |
| 19922 | ) |
| 19923 | .await; |
| 19924 | assert_eq!(common::items(&res.body).len(), 1); |
| 19925 | let res = send( |
| 19926 | &app, |
| 19927 | "GET", |
| 19928 | &format!("/bank-questions?subject={}", Uuid::new_v4()), |
| 19929 | Some(&teacher), |
| 19930 | None, |
| 19931 | ) |
| 19932 | .await; |
| 19933 | assert_eq!(common::items(&res.body).len(), 0); |
| 19934 | let res = send( |
| 19935 | &app, |
| 19936 | "GET", |
| 19937 | "/bank-questions?subject=nope", |
| 19938 | Some(&teacher), |
| 19939 | None, |
| 19940 | ) |
| 19941 | .await; |
| 19942 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 19943 | assert_eq!(res.body["error"], "subject: must be a hyphenated uuid"); |
| 19944 | |
| 19945 | // Instantiate into an exam under one of the course's subjects. |
| 19946 | let now = Timestamp::now().as_millis(); |
| 19947 | let exam = scheduled_exam( |
| 19948 | &app, |
| 19949 | &teacher, |
| 19950 | &t.instance, |
| 19951 | json!({ "term": &t.term, "title": "midterm", "kind": "yazili", "mode": "sync", |
| 19952 | "starts_at": now - 1_000, "ends_at": now + 600_000 }), |
| 19953 | ) |
| 19954 | .await; |
| 19955 | let res = send( |
| 19956 | &app, |
| 19957 | "POST", |
| 19958 | &format!("/exams/{exam}/questions/from-bank/{bid}"), |
| 19959 | Some(&teacher), |
| 19960 | Some(json!({ "subject_id": subject })), |
| 19961 | ) |
| 19962 | .await; |
| 19963 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 19964 | assert_eq!(res.body["exam"], exam); |
| 19965 | assert_eq!(res.body["subject"], subject); |
| 19966 | assert_eq!(res.body["correct"], res.body["choices"][1]["id"]); |
| 19967 | assert_eq!(res.body["choices"][1]["text"], "4"); |
| 19968 | |
| 19969 | // The copy is independent — the template still stands. |
| 19970 | let res = send( |
| 19971 | &app, |
| 19972 | "GET", |
| 19973 | &format!("/bank-questions/{bid}"), |
| 19974 | Some(&teacher), |
| 19975 | None, |
| 19976 | ) |
| 19977 | .await; |
| 19978 | assert_eq!(res.status, StatusCode::OK); |
| 19979 | } |
| 19980 | |
| 19981 | /// The bank list pages in SQL: newest first, every row reachable by offset, |
| 19982 | /// `total` counting the matches rather than the page, and `?q=` filtering |
| 19983 | /// server-side. Regression for the whole-table-then-slice version, which hid |
| 19984 | /// template #101 onward from a client asking for `limit=100`. |
| 19985 | #[tokio::test] |
| 19986 | async fn bank_question_list_pages_filters_and_names() { |
| 19987 | let (app, db) = app_and_db().await; |
| 19988 | let teacher = login_as(&app, &db, "bank_p", "teacher").await; |
| 19989 | let other = login_as(&app, &db, "bank_p2", "teacher").await; |
| 19990 | let mudur = login_as(&app, &db, "algebra_m", "manager").await; |
| 19991 | let t = taught_under(&app, &mudur, &teacher, "algebra").await; |
| 19992 | let subject = create_subject(&app, &teacher, &t.course, "linear").await; |
| 19993 | select_instance_subject(&app, &teacher, &t.instance, &subject).await; |
| 19994 | let other_subject = create_subject(&app, &teacher, &t.course, "quadratic").await; |
| 19995 | |
| 19996 | // 120 templates — more than the clients' `limit=100`. |
| 19997 | for i in 0..120 { |
| 19998 | let res = send( |
| 19999 | &app, |
| 20000 | "POST", |
| 20001 | "/bank-questions", |
| 20002 | Some(&teacher), |
| 20003 | Some( |
| 20004 | json!({ "subject_id": subject, "text": format!("template {i:03}"), |
| 20005 | "kind": "text", "points": 1 }), |
| 20006 | ), |
| 20007 | ) |
| 20008 | .await; |
| 20009 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20010 | } |
| 20011 | // A foreign owner + subject, to prove the filters actually narrow. |
| 20012 | let res = send( |
| 20013 | &app, |
| 20014 | "POST", |
| 20015 | "/bank-questions", |
| 20016 | Some(&other), |
| 20017 | Some( |
| 20018 | json!({ "subject_id": other_subject, "text": "someone else's", |
| 20019 | "kind": "text", "points": 1 }), |
| 20020 | ), |
| 20021 | ) |
| 20022 | .await; |
| 20023 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20024 | // Published, so it shows up in the first teacher's paging assertions below; |
| 20025 | // a private one would (correctly) be invisible to them. |
| 20026 | let foreign = id_of(&res.body); |
| 20027 | let res = send( |
| 20028 | &app, |
| 20029 | "PATCH", |
| 20030 | &format!("/bank-questions/{foreign}"), |
| 20031 | Some(&other), |
| 20032 | Some(json!({ "visibility": "school" })), |
| 20033 | ) |
| 20034 | .await; |
| 20035 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 20036 | |
| 20037 | // Page 1: newest first, full window, honest total. |
| 20038 | let res = send( |
| 20039 | &app, |
| 20040 | "GET", |
| 20041 | "/bank-questions?limit=100", |
| 20042 | Some(&teacher), |
| 20043 | None, |
| 20044 | ) |
| 20045 | .await; |
| 20046 | assert_eq!(common::items(&res.body).len(), 100); |
| 20047 | assert_eq!(res.body["total"], 121); |
| 20048 | assert_eq!(common::items(&res.body)[0]["text"], "someone else's"); |
| 20049 | assert_eq!(common::items(&res.body)[1]["text"], "template 119"); |
| 20050 | // The names are joined on, not left for the client to look up per row. |
| 20051 | assert_eq!(common::items(&res.body)[1]["subject_name"], "linear"); |
| 20052 | assert_eq!(common::items(&res.body)[1]["owner_name"], "bank_p"); |
| 20053 | |
| 20054 | // Item #101 onward is reachable — the bug was that it never was. |
| 20055 | let res = send( |
| 20056 | &app, |
| 20057 | "GET", |
| 20058 | "/bank-questions?limit=100&offset=100", |
| 20059 | Some(&teacher), |
| 20060 | None, |
| 20061 | ) |
| 20062 | .await; |
| 20063 | assert_eq!(common::items(&res.body).len(), 21); |
| 20064 | assert_eq!(res.body["total"], 121); |
| 20065 | assert_eq!(common::items(&res.body)[0]["text"], "template 020"); |
| 20066 | assert_eq!(common::items(&res.body)[20]["text"], "template 000"); |
| 20067 | |
| 20068 | // `?q=` filters server-side: "template 005" sits on page 2 unfiltered, but |
| 20069 | // leads page 1 once filtered — and matches case-insensitively. |
| 20070 | let res = send( |
| 20071 | &app, |
| 20072 | "GET", |
| 20073 | "/bank-questions?limit=100&q=TEMPLATE%20005", |
| 20074 | Some(&teacher), |
| 20075 | None, |
| 20076 | ) |
| 20077 | .await; |
| 20078 | assert_eq!(res.body["total"], 1); |
| 20079 | assert_eq!(common::items(&res.body).len(), 1); |
| 20080 | assert_eq!(common::items(&res.body)[0]["text"], "template 005"); |
| 20081 | // A blank `q` is no filter at all. |
| 20082 | let res = send(&app, "GET", "/bank-questions?q=", Some(&teacher), None).await; |
| 20083 | assert_eq!(res.body["total"], 121); |
| 20084 | |
| 20085 | // `owner=me` + `subject=` combine, and still page. |
| 20086 | let res = send( |
| 20087 | &app, |
| 20088 | "GET", |
| 20089 | &format!("/bank-questions?owner=me&subject={subject}&limit=100&offset=100"), |
| 20090 | Some(&teacher), |
| 20091 | None, |
| 20092 | ) |
| 20093 | .await; |
| 20094 | assert_eq!(res.body["total"], 120); |
| 20095 | assert_eq!(common::items(&res.body).len(), 20); |
| 20096 | assert_eq!(common::items(&res.body)[0]["text"], "template 019"); |
| 20097 | // The other teacher's `me` is their own single template. |
| 20098 | let res = send(&app, "GET", "/bank-questions?owner=me", Some(&other), None).await; |
| 20099 | assert_eq!(res.body["total"], 1); |
| 20100 | assert_eq!(common::items(&res.body)[0]["owner_name"], "bank_p2"); |
| 20101 | // Owner and subject that never co-occur → an empty page, total 0. |
| 20102 | let res = send( |
| 20103 | &app, |
| 20104 | "GET", |
| 20105 | &format!("/bank-questions?owner=me&subject={other_subject}"), |
| 20106 | Some(&teacher), |
| 20107 | None, |
| 20108 | ) |
| 20109 | .await; |
| 20110 | assert_eq!(res.body["total"], 0); |
| 20111 | assert!(common::items(&res.body).is_empty()); |
| 20112 | } |
| 20113 | |
| 20114 | /// `?visibility=` is a real SQL filter (so the client never has to fetch the |
| 20115 | /// bank unpaged and window it in memory — the very bug the SQL paging fixed), |
| 20116 | /// and it narrows the caller's view without ever widening it. |
| 20117 | #[tokio::test] |
| 20118 | async fn bank_question_list_filters_by_visibility() { |
| 20119 | let (app, db) = app_and_db().await; |
| 20120 | let teacher = login_as(&app, &db, "bank_v", "teacher").await; |
| 20121 | let other = login_as(&app, &db, "bank_v2", "teacher").await; |
| 20122 | let mudur = login_as(&app, &db, "biology_m", "manager").await; |
| 20123 | let t = taught_under(&app, &mudur, &teacher, "biology").await; |
| 20124 | let subject = create_subject(&app, &teacher, &t.course, "cells").await; |
| 20125 | let other_subject = create_subject(&app, &teacher, &t.course, "genes").await; |
| 20126 | |
| 20127 | // Mine: 3 drafts on `subject`, 2 published on `other_subject`. |
| 20128 | let mut published = Vec::new(); |
| 20129 | for i in 0..5 { |
| 20130 | let on = if i < 3 { &subject } else { &other_subject }; |
| 20131 | let res = send( |
| 20132 | &app, |
| 20133 | "POST", |
| 20134 | "/bank-questions", |
| 20135 | Some(&teacher), |
| 20136 | Some(json!({ "subject_id": on, "text": format!("mine {i}"), |
| 20137 | "kind": "text", "points": 1 })), |
| 20138 | ) |
| 20139 | .await; |
| 20140 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20141 | if i >= 3 { |
| 20142 | published.push(id_of(&res.body)); |
| 20143 | } |
| 20144 | } |
| 20145 | for bid in &published { |
| 20146 | let res = send( |
| 20147 | &app, |
| 20148 | "PATCH", |
| 20149 | &format!("/bank-questions/{bid}"), |
| 20150 | Some(&teacher), |
| 20151 | Some(json!({ "visibility": "school" })), |
| 20152 | ) |
| 20153 | .await; |
| 20154 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 20155 | } |
| 20156 | // The other teacher keeps one private template — nobody else may ever see |
| 20157 | // it, whatever they pass in `?visibility=`. |
| 20158 | let res = send( |
| 20159 | &app, |
| 20160 | "POST", |
| 20161 | "/bank-questions", |
| 20162 | Some(&other), |
| 20163 | Some(json!({ "subject_id": subject, "text": "their secret", |
| 20164 | "kind": "text", "points": 1 })), |
| 20165 | ) |
| 20166 | .await; |
| 20167 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20168 | |
| 20169 | // `private` = my drafts; `total` honours the filter, not the whole bank. |
| 20170 | let res = send( |
| 20171 | &app, |
| 20172 | "GET", |
| 20173 | "/bank-questions?visibility=private", |
| 20174 | Some(&teacher), |
| 20175 | None, |
| 20176 | ) |
| 20177 | .await; |
| 20178 | assert_eq!(res.body["total"], 3, "{}", res.body); |
| 20179 | assert_eq!(common::items(&res.body).len(), 3); |
| 20180 | assert_eq!(common::items(&res.body)[0]["text"], "mine 2"); |
| 20181 | // `school` = the published shelf — and NOT the other teacher's private row. |
| 20182 | let res = send( |
| 20183 | &app, |
| 20184 | "GET", |
| 20185 | "/bank-questions?visibility=school", |
| 20186 | Some(&teacher), |
| 20187 | None, |
| 20188 | ) |
| 20189 | .await; |
| 20190 | assert_eq!(res.body["total"], 2, "{}", res.body); |
| 20191 | let texts: Vec<&str> = common::items(&res.body) |
| 20192 | .iter() |
| 20193 | .map(|item| item["text"].as_str().unwrap()) |
| 20194 | .collect(); |
| 20195 | assert_eq!(texts, ["mine 4", "mine 3"]); |
| 20196 | assert!(!texts.contains(&"their secret")); |
| 20197 | // The stranger's `private` view is empty: the filter can't widen the gate. |
| 20198 | let res = send( |
| 20199 | &app, |
| 20200 | "GET", |
| 20201 | "/bank-questions?visibility=private", |
| 20202 | Some(&teacher), |
| 20203 | None, |
| 20204 | ) |
| 20205 | .await; |
| 20206 | assert!( |
| 20207 | !common::items(&res.body) |
| 20208 | .iter() |
| 20209 | .any(|item| item["text"] == "their secret") |
| 20210 | ); |
| 20211 | let res = send( |
| 20212 | &app, |
| 20213 | "GET", |
| 20214 | "/bank-questions?visibility=private", |
| 20215 | Some(&other), |
| 20216 | None, |
| 20217 | ) |
| 20218 | .await; |
| 20219 | assert_eq!(res.body["total"], 1, "{}", res.body); |
| 20220 | assert_eq!(common::items(&res.body)[0]["text"], "their secret"); |
| 20221 | |
| 20222 | // Composes with `q`, `subject`, `owner`, and with paging. |
| 20223 | let res = send( |
| 20224 | &app, |
| 20225 | "GET", |
| 20226 | &format!("/bank-questions?visibility=private&subject={subject}&owner=me&q=MINE%201"), |
| 20227 | Some(&teacher), |
| 20228 | None, |
| 20229 | ) |
| 20230 | .await; |
| 20231 | assert_eq!(res.body["total"], 1, "{}", res.body); |
| 20232 | assert_eq!(common::items(&res.body)[0]["text"], "mine 1"); |
| 20233 | // Right owner and subject, wrong shelf → nothing. |
| 20234 | let res = send( |
| 20235 | &app, |
| 20236 | "GET", |
| 20237 | &format!("/bank-questions?visibility=school&subject={subject}&owner=me"), |
| 20238 | Some(&teacher), |
| 20239 | None, |
| 20240 | ) |
| 20241 | .await; |
| 20242 | assert_eq!(res.body["total"], 0, "{}", res.body); |
| 20243 | assert!(common::items(&res.body).is_empty()); |
| 20244 | // Paging windows the filtered set, and `total` stays the filtered total. |
| 20245 | let res = send( |
| 20246 | &app, |
| 20247 | "GET", |
| 20248 | "/bank-questions?visibility=private&limit=2&offset=2", |
| 20249 | Some(&teacher), |
| 20250 | None, |
| 20251 | ) |
| 20252 | .await; |
| 20253 | assert_eq!(res.body["total"], 3, "{}", res.body); |
| 20254 | assert_eq!(common::items(&res.body).len(), 1); |
| 20255 | assert_eq!(common::items(&res.body)[0]["text"], "mine 0"); |
| 20256 | |
| 20257 | // An unknown shelf is a 400, worded like the other param errors. |
| 20258 | let res = send( |
| 20259 | &app, |
| 20260 | "GET", |
| 20261 | "/bank-questions?visibility=public", |
| 20262 | Some(&teacher), |
| 20263 | None, |
| 20264 | ) |
| 20265 | .await; |
| 20266 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 20267 | assert!( |
| 20268 | res.body["error"] |
| 20269 | .as_str() |
| 20270 | .unwrap() |
| 20271 | .contains("must be private or school"), |
| 20272 | "{}", |
| 20273 | res.body |
| 20274 | ); |
| 20275 | } |
| 20276 | |
| 20277 | /// The app is EN/TR, so `?q=` must fold Turkish casing: `İ` lowercases to |
| 20278 | /// `i` + U+0307 in both Rust and SQL, which used to make `istanbul` and |
| 20279 | /// `İSTANBUL` two disjoint searches — a teacher typing lowercase got an empty |
| 20280 | /// bank. |
| 20281 | #[tokio::test] |
| 20282 | async fn bank_question_search_folds_turkish_casing() { |
| 20283 | let (app, db) = app_and_db().await; |
| 20284 | let teacher = login_as(&app, &db, "bank_tr", "teacher").await; |
| 20285 | let mudur = login_as(&app, &db, "cografya_m", "manager").await; |
| 20286 | let t = taught_under(&app, &mudur, &teacher, "cografya").await; |
| 20287 | let subject = create_subject(&app, &teacher, &t.course, "iller").await; |
| 20288 | for text in ["İSTANBUL kaç ilçedir?", "istanbul boğazı nerededir?"] { |
| 20289 | let res = send( |
| 20290 | &app, |
| 20291 | "POST", |
| 20292 | "/bank-questions", |
| 20293 | Some(&teacher), |
| 20294 | Some(json!({ "subject_id": subject, "text": text, |
| 20295 | "kind": "text", "points": 1 })), |
| 20296 | ) |
| 20297 | .await; |
| 20298 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20299 | } |
| 20300 | |
| 20301 | // Lowercase needle finds the uppercase row, and every casing finds both. |
| 20302 | for needle in ["istanbul", "%C4%B0STANBUL", "%C4%B1stanbul", "ISTANBUL"] { |
| 20303 | let res = send( |
| 20304 | &app, |
| 20305 | "GET", |
| 20306 | &format!("/bank-questions?q={needle}"), |
| 20307 | Some(&teacher), |
| 20308 | None, |
| 20309 | ) |
| 20310 | .await; |
| 20311 | assert_eq!(res.body["total"], 2, "needle {needle} missed: {}", res.body); |
| 20312 | } |
| 20313 | // Diacritics fold too, in both directions. |
| 20314 | for needle in ["ilce", "il%C3%A7e", "bogaz", "bo%C4%9Faz"] { |
| 20315 | let res = send( |
| 20316 | &app, |
| 20317 | "GET", |
| 20318 | &format!("/bank-questions?q={needle}"), |
| 20319 | Some(&teacher), |
| 20320 | None, |
| 20321 | ) |
| 20322 | .await; |
| 20323 | assert_eq!(res.body["total"], 1, "needle {needle} missed: {}", res.body); |
| 20324 | } |
| 20325 | // Folding widens the match, it does not match everything. |
| 20326 | let res = send( |
| 20327 | &app, |
| 20328 | "GET", |
| 20329 | "/bank-questions?q=ankara", |
| 20330 | Some(&teacher), |
| 20331 | None, |
| 20332 | ) |
| 20333 | .await; |
| 20334 | assert_eq!(res.body["total"], 0); |
| 20335 | } |
| 20336 | |
| 20337 | #[tokio::test] |
| 20338 | async fn bank_question_owner_gate_cross_course_and_freeze() { |
| 20339 | let (app, db) = app_and_db().await; |
| 20340 | let owner = login_as(&app, &db, "bank_o", "teacher").await; |
| 20341 | let other = login_as(&app, &db, "bank_x", "teacher").await; |
| 20342 | let admin = login_as(&app, &db, "bank_a", "admin").await; |
| 20343 | |
| 20344 | let mudur = login_as(&app, &db, "bank_m", "manager").await; |
| 20345 | scheduling_kinds(&app, &mudur).await; |
| 20346 | let t = taught_under(&app, &mudur, &owner, "geo").await; |
| 20347 | let subject = create_subject(&app, &owner, &t.course, "angles").await; |
| 20348 | let res = send( |
| 20349 | &app, |
| 20350 | "POST", |
| 20351 | "/bank-questions", |
| 20352 | Some(&owner), |
| 20353 | Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), |
| 20354 | ) |
| 20355 | .await; |
| 20356 | let bid = id_of(&res.body); |
| 20357 | // Published, so this test is about the *owner* gate alone — the visibility |
| 20358 | // gate (404 while private) has its own test below. |
| 20359 | let res = send( |
| 20360 | &app, |
| 20361 | "PATCH", |
| 20362 | &format!("/bank-questions/{bid}"), |
| 20363 | Some(&owner), |
| 20364 | Some(json!({ "visibility": "school" })), |
| 20365 | ) |
| 20366 | .await; |
| 20367 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 20368 | |
| 20369 | // A non-owner teacher reads it, but may not edit or delete. |
| 20370 | let res = send( |
| 20371 | &app, |
| 20372 | "GET", |
| 20373 | &format!("/bank-questions/{bid}"), |
| 20374 | Some(&other), |
| 20375 | None, |
| 20376 | ) |
| 20377 | .await; |
| 20378 | assert_eq!(res.status, StatusCode::OK); |
| 20379 | let res = send( |
| 20380 | &app, |
| 20381 | "PATCH", |
| 20382 | &format!("/bank-questions/{bid}"), |
| 20383 | Some(&other), |
| 20384 | Some(json!({ "points": 7 })), |
| 20385 | ) |
| 20386 | .await; |
| 20387 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 20388 | let res = send( |
| 20389 | &app, |
| 20390 | "DELETE", |
| 20391 | &format!("/bank-questions/{bid}"), |
| 20392 | Some(&other), |
| 20393 | None, |
| 20394 | ) |
| 20395 | .await; |
| 20396 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 20397 | // Admin bypasses ownership. |
| 20398 | let res = send( |
| 20399 | &app, |
| 20400 | "PATCH", |
| 20401 | &format!("/bank-questions/{bid}"), |
| 20402 | Some(&admin), |
| 20403 | Some(json!({ "points": 7 })), |
| 20404 | ) |
| 20405 | .await; |
| 20406 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 20407 | assert_eq!(res.body["points"], 7); |
| 20408 | |
| 20409 | // Instantiate with a subject from ANOTHER course is a 400. |
| 20410 | let t2 = taught_under(&app, &mudur, &owner, "chem").await; |
| 20411 | let subject2 = create_subject(&app, &owner, &t2.course, "bonds").await; |
| 20412 | let now = Timestamp::now().as_millis(); |
| 20413 | let exam = scheduled_exam( |
| 20414 | &app, |
| 20415 | &owner, |
| 20416 | &t.instance, |
| 20417 | json!({ "term": &t.term, "title": "t", "kind": "final", "mode": "sync", |
| 20418 | "starts_at": now - 1_000, "ends_at": now + 600_000 }), |
| 20419 | ) |
| 20420 | .await; |
| 20421 | let res = send( |
| 20422 | &app, |
| 20423 | "POST", |
| 20424 | &format!("/exams/{exam}/questions/from-bank/{bid}"), |
| 20425 | Some(&owner), |
| 20426 | Some(json!({ "subject_id": subject2 })), |
| 20427 | ) |
| 20428 | .await; |
| 20429 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 20430 | |
| 20431 | // Once a student sits the exam, instantiate freezes (409). |
| 20432 | let student = login(&app, "sinem").await; |
| 20433 | let student_id = me_id(&app, &student).await; |
| 20434 | enroll(&app, &owner, &t.instance, &student_id).await; |
| 20435 | let res = send( |
| 20436 | &app, |
| 20437 | "POST", |
| 20438 | &format!("/exams/{exam}/attempt"), |
| 20439 | Some(&student), |
| 20440 | None, |
| 20441 | ) |
| 20442 | .await; |
| 20443 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20444 | let res = send( |
| 20445 | &app, |
| 20446 | "POST", |
| 20447 | &format!("/exams/{exam}/questions/from-bank/{bid}"), |
| 20448 | Some(&owner), |
| 20449 | Some(json!({ "subject_id": subject })), |
| 20450 | ) |
| 20451 | .await; |
| 20452 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 20453 | } |
| 20454 | |
| 20455 | /// A bank template carries `correct` — the answer key — so it is `private` |
| 20456 | /// until its owner publishes it. Regression for the one-click answer-key |
| 20457 | /// broadcast: saving a live exam's question to the bank used to hand the key |
| 20458 | /// (and the pictures) to every teacher in the school, permanently and silently. |
| 20459 | /// |
| 20460 | /// Every read path is checked from a second teacher's seat, and each one must |
| 20461 | /// answer **404, not 403** — a 403 confirms the template exists. |
| 20462 | #[tokio::test] |
| 20463 | async fn bank_private_template_is_invisible_until_published() { |
| 20464 | let (app, db) = app_and_db().await; |
| 20465 | let owner = login_as(&app, &db, "bvis_o", "teacher").await; |
| 20466 | let other = login_as(&app, &db, "bvis_x", "teacher").await; |
| 20467 | let mudur = login_as(&app, &db, "bvis_m", "manager").await; |
| 20468 | scheduling_kinds(&app, &mudur).await; |
| 20469 | let t = taught_under(&app, &mudur, &owner, "bio").await; |
| 20470 | let subject = create_subject(&app, &owner, &t.course, "cells").await; |
| 20471 | select_instance_subject(&app, &owner, &t.instance, &subject).await; |
| 20472 | |
| 20473 | // Two templates; only the second is ever published. |
| 20474 | let res = send( |
| 20475 | &app, |
| 20476 | "POST", |
| 20477 | "/bank-questions", |
| 20478 | Some(&owner), |
| 20479 | Some(json!({ "subject_id": subject, "text": "Which organelle?", "kind": "choice", |
| 20480 | "points": 10, "choices": [{"id": "c0", "text": "nucleus"}, {"id": "c1", "text": "ribosome"}], "correct": "c0" })), |
| 20481 | ) |
| 20482 | .await; |
| 20483 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20484 | // New templates are born private — nothing has to opt in to be safe. |
| 20485 | assert_eq!(res.body["visibility"], "private"); |
| 20486 | let secret = id_of(&res.body); |
| 20487 | let opt = choice_of(&res.body, 0); |
| 20488 | let res = send( |
| 20489 | &app, |
| 20490 | "POST", |
| 20491 | "/bank-questions", |
| 20492 | Some(&owner), |
| 20493 | Some(json!({ "subject_id": subject, "text": "shared later", "kind": "text", "points": 1 })), |
| 20494 | ) |
| 20495 | .await; |
| 20496 | let shared = id_of(&res.body); |
| 20497 | |
| 20498 | let illus = b"private-illustration".as_slice(); |
| 20499 | let pic = b"private-choice-pic".as_slice(); |
| 20500 | let (status, _) = post_image( |
| 20501 | &app, |
| 20502 | &owner, |
| 20503 | &format!("/bank-questions/{secret}/image"), |
| 20504 | "image/png", |
| 20505 | illus, |
| 20506 | ) |
| 20507 | .await; |
| 20508 | assert_eq!(status, StatusCode::CREATED); |
| 20509 | let (status, _) = post_image( |
| 20510 | &app, |
| 20511 | &owner, |
| 20512 | &format!("/bank-questions/{secret}/choices/{opt}/image"), |
| 20513 | "image/webp", |
| 20514 | pic, |
| 20515 | ) |
| 20516 | .await; |
| 20517 | assert_eq!(status, StatusCode::CREATED); |
| 20518 | |
| 20519 | // The other teacher's own exam, to attempt an instantiate from. |
| 20520 | let t2 = taught_under(&app, &mudur, &other, "bio2").await; |
| 20521 | let subject2 = create_subject(&app, &other, &t2.course, "cells2").await; |
| 20522 | select_instance_subject(&app, &other, &t2.instance, &subject2).await; |
| 20523 | let exam2 = create_exam(&app, &other, &t2.instance, &t2.term, "quiz", "final").await; |
| 20524 | let owner_id = me_id(&app, &owner).await; |
| 20525 | |
| 20526 | // --- the stranger sees nothing, and is told nothing --- |
| 20527 | let res = send(&app, "GET", "/bank-questions", Some(&other), None).await; |
| 20528 | assert!(common::items(&res.body).is_empty()); |
| 20529 | assert_eq!( |
| 20530 | res.body["total"], 0, |
| 20531 | "total must count only visible templates" |
| 20532 | ); |
| 20533 | let res = send( |
| 20534 | &app, |
| 20535 | "GET", |
| 20536 | &format!("/bank-questions/{secret}"), |
| 20537 | Some(&other), |
| 20538 | None, |
| 20539 | ) |
| 20540 | .await; |
| 20541 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 20542 | let (status, _, _) = common::send_raw( |
| 20543 | &app, |
| 20544 | "GET", |
| 20545 | &format!("/bank-questions/{secret}/image"), |
| 20546 | Some(&other), |
| 20547 | None, |
| 20548 | Vec::new(), |
| 20549 | ) |
| 20550 | .await; |
| 20551 | assert_eq!(status, StatusCode::NOT_FOUND); |
| 20552 | let (status, _, _) = common::send_raw( |
| 20553 | &app, |
| 20554 | "GET", |
| 20555 | &format!("/bank-questions/{secret}/choices/{opt}/image"), |
| 20556 | Some(&other), |
| 20557 | None, |
| 20558 | Vec::new(), |
| 20559 | ) |
| 20560 | .await; |
| 20561 | assert_eq!(status, StatusCode::NOT_FOUND); |
| 20562 | let res = send( |
| 20563 | &app, |
| 20564 | "POST", |
| 20565 | &format!("/exams/{exam2}/questions/from-bank/{secret}"), |
| 20566 | Some(&other), |
| 20567 | Some(json!({ "subject_id": subject2 })), |
| 20568 | ) |
| 20569 | .await; |
| 20570 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 20571 | // Not even by asking for the owner's templates by name. |
| 20572 | let res = send( |
| 20573 | &app, |
| 20574 | "GET", |
| 20575 | &format!("/bank-questions?owner={owner_id}"), |
| 20576 | Some(&other), |
| 20577 | None, |
| 20578 | ) |
| 20579 | .await; |
| 20580 | assert_eq!(res.body["total"], 0); |
| 20581 | |
| 20582 | // --- the owner still has full use of their own template --- |
| 20583 | let res = send(&app, "GET", "/bank-questions", Some(&owner), None).await; |
| 20584 | assert_eq!(res.body["total"], 2); |
| 20585 | let res = send( |
| 20586 | &app, |
| 20587 | "GET", |
| 20588 | &format!("/bank-questions/{secret}"), |
| 20589 | Some(&owner), |
| 20590 | None, |
| 20591 | ) |
| 20592 | .await; |
| 20593 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 20594 | assert_eq!(res.body["correct"], res.body["choices"][0]["id"]); |
| 20595 | let (status, _, bytes) = common::send_raw( |
| 20596 | &app, |
| 20597 | "GET", |
| 20598 | &format!("/bank-questions/{secret}/image"), |
| 20599 | Some(&owner), |
| 20600 | None, |
| 20601 | Vec::new(), |
| 20602 | ) |
| 20603 | .await; |
| 20604 | assert_eq!((status, bytes.as_slice()), (StatusCode::OK, illus)); |
| 20605 | let (status, _, bytes) = common::send_raw( |
| 20606 | &app, |
| 20607 | "GET", |
| 20608 | &format!("/bank-questions/{secret}/choices/{opt}/image"), |
| 20609 | Some(&owner), |
| 20610 | None, |
| 20611 | Vec::new(), |
| 20612 | ) |
| 20613 | .await; |
| 20614 | assert_eq!((status, bytes.as_slice()), (StatusCode::OK, pic)); |
| 20615 | let exam = create_exam(&app, &owner, &t.instance, &t.term, "midterm", "final").await; |
| 20616 | let res = send( |
| 20617 | &app, |
| 20618 | "POST", |
| 20619 | &format!("/exams/{exam}/questions/from-bank/{secret}"), |
| 20620 | Some(&owner), |
| 20621 | Some(json!({ "subject_id": subject })), |
| 20622 | ) |
| 20623 | .await; |
| 20624 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20625 | |
| 20626 | // --- publishing one template opens exactly that one --- |
| 20627 | let res = send( |
| 20628 | &app, |
| 20629 | "PATCH", |
| 20630 | &format!("/bank-questions/{shared}"), |
| 20631 | Some(&owner), |
| 20632 | Some(json!({ "visibility": "school" })), |
| 20633 | ) |
| 20634 | .await; |
| 20635 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 20636 | assert_eq!(res.body["visibility"], "school"); |
| 20637 | let res = send(&app, "GET", "/bank-questions", Some(&other), None).await; |
| 20638 | assert_eq!(res.body["total"], 1, "the private one must still be hidden"); |
| 20639 | assert_eq!(common::items(&res.body)[0]["id"], shared); |
| 20640 | let res = send( |
| 20641 | &app, |
| 20642 | "GET", |
| 20643 | &format!("/bank-questions/{shared}"), |
| 20644 | Some(&other), |
| 20645 | None, |
| 20646 | ) |
| 20647 | .await; |
| 20648 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 20649 | let res = send( |
| 20650 | &app, |
| 20651 | "POST", |
| 20652 | &format!("/exams/{exam2}/questions/from-bank/{shared}"), |
| 20653 | Some(&other), |
| 20654 | Some(json!({ "subject_id": subject2 })), |
| 20655 | ) |
| 20656 | .await; |
| 20657 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20658 | // The still-private one stays shut on every path. |
| 20659 | let res = send( |
| 20660 | &app, |
| 20661 | "GET", |
| 20662 | &format!("/bank-questions/{secret}"), |
| 20663 | Some(&other), |
| 20664 | None, |
| 20665 | ) |
| 20666 | .await; |
| 20667 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 20668 | let res = send( |
| 20669 | &app, |
| 20670 | "POST", |
| 20671 | &format!("/exams/{exam2}/questions/from-bank/{secret}"), |
| 20672 | Some(&other), |
| 20673 | Some(json!({ "subject_id": subject2 })), |
| 20674 | ) |
| 20675 | .await; |
| 20676 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 20677 | // Unpublishing closes it again. |
| 20678 | let res = send( |
| 20679 | &app, |
| 20680 | "PATCH", |
| 20681 | &format!("/bank-questions/{shared}"), |
| 20682 | Some(&owner), |
| 20683 | Some(json!({ "visibility": "private" })), |
| 20684 | ) |
| 20685 | .await; |
| 20686 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 20687 | let res = send( |
| 20688 | &app, |
| 20689 | "GET", |
| 20690 | &format!("/bank-questions/{shared}"), |
| 20691 | Some(&other), |
| 20692 | None, |
| 20693 | ) |
| 20694 | .await; |
| 20695 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 20696 | // A bogus value is a 400, not a silent publish. |
| 20697 | let res = send( |
| 20698 | &app, |
| 20699 | "PATCH", |
| 20700 | &format!("/bank-questions/{shared}"), |
| 20701 | Some(&owner), |
| 20702 | Some(json!({ "visibility": "public" })), |
| 20703 | ) |
| 20704 | .await; |
| 20705 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 20706 | } |
| 20707 | |
| 20708 | /// Admins see private templates: they already read every exam's `correct` via |
| 20709 | /// course management, and they may already delete any template. |
| 20710 | #[tokio::test] |
| 20711 | async fn bank_private_template_is_visible_to_admins() { |
| 20712 | let (app, db) = app_and_db().await; |
| 20713 | let owner = login_as(&app, &db, "badm_o", "teacher").await; |
| 20714 | let admin = login_as(&app, &db, "badm_a", "admin").await; |
| 20715 | let mudur = login_as(&app, &db, "hist_m", "manager").await; |
| 20716 | let t = taught_under(&app, &mudur, &owner, "hist").await; |
| 20717 | let subject = create_subject(&app, &owner, &t.course, "ottoman").await; |
| 20718 | let res = send( |
| 20719 | &app, |
| 20720 | "POST", |
| 20721 | "/bank-questions", |
| 20722 | Some(&owner), |
| 20723 | Some(json!({ "subject_id": subject, "text": "when?", "kind": "text", "points": 1 })), |
| 20724 | ) |
| 20725 | .await; |
| 20726 | let bid = id_of(&res.body); |
| 20727 | |
| 20728 | let res = send( |
| 20729 | &app, |
| 20730 | "GET", |
| 20731 | &format!("/bank-questions/{bid}"), |
| 20732 | Some(&admin), |
| 20733 | None, |
| 20734 | ) |
| 20735 | .await; |
| 20736 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 20737 | let res = send(&app, "GET", "/bank-questions", Some(&admin), None).await; |
| 20738 | assert_eq!(res.body["total"], 1); |
| 20739 | } |
| 20740 | |
| 20741 | #[tokio::test] |
| 20742 | async fn exam_question_saves_to_bank() { |
| 20743 | let (app, db) = app_and_db().await; |
| 20744 | let teacher = login_as(&app, &db, "s2b_t", "teacher").await; |
| 20745 | let mudur = login_as(&app, &db, "phys_m", "manager").await; |
| 20746 | scheduling_kinds(&app, &mudur).await; |
| 20747 | let t = taught_under(&app, &mudur, &teacher, "phys").await; |
| 20748 | let subject = create_subject(&app, &teacher, &t.course, "kinematics").await; |
| 20749 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "final", "final").await; |
| 20750 | let qid = create_question( |
| 20751 | &app, |
| 20752 | &teacher, |
| 20753 | &exam, |
| 20754 | &subject, |
| 20755 | json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }), |
| 20756 | ) |
| 20757 | .await; |
| 20758 | |
| 20759 | let res = send( |
| 20760 | &app, |
| 20761 | "POST", |
| 20762 | &format!("/exams/{exam}/questions/{qid}/to-bank"), |
| 20763 | Some(&teacher), |
| 20764 | None, |
| 20765 | ) |
| 20766 | .await; |
| 20767 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20768 | assert_eq!(res.body["text"], "v=?"); |
| 20769 | assert_eq!(res.body["correct"], res.body["choices"][0]["id"]); |
| 20770 | assert_eq!(res.body["subject"], subject); |
| 20771 | assert_eq!(res.body["owner"], me_id(&app, &teacher).await); |
| 20772 | // The one-click broadcast that was: the saved key stays the teacher's until |
| 20773 | // they publish it. |
| 20774 | assert_eq!(res.body["visibility"], "private"); |
| 20775 | let bid = id_of(&res.body); |
| 20776 | |
| 20777 | // It now lives in their bank. |
| 20778 | let res = send( |
| 20779 | &app, |
| 20780 | "GET", |
| 20781 | &format!("/bank-questions/{bid}"), |
| 20782 | Some(&teacher), |
| 20783 | None, |
| 20784 | ) |
| 20785 | .await; |
| 20786 | assert_eq!(res.status, StatusCode::OK); |
| 20787 | } |
| 20788 | |
| 20789 | /// Instantiating a bank template copies its image blobs to fresh files under the |
| 20790 | /// new exam question, byte-for-byte, and leaves the source template's images |
| 20791 | /// untouched. |
| 20792 | #[tokio::test] |
| 20793 | async fn bank_instantiate_copies_images() { |
| 20794 | let (app, db) = app_and_db().await; |
| 20795 | let teacher = login_as(&app, &db, "bimg_t", "teacher").await; |
| 20796 | let mudur = login_as(&app, &db, "geo1_m", "manager").await; |
| 20797 | scheduling_kinds(&app, &mudur).await; |
| 20798 | let t = taught_under(&app, &mudur, &teacher, "geo1").await; |
| 20799 | let subject = create_subject(&app, &teacher, &t.course, "maps1").await; |
| 20800 | select_instance_subject(&app, &teacher, &t.instance, &subject).await; |
| 20801 | |
| 20802 | // A choice template with an illustration and one option picture. |
| 20803 | let res = send( |
| 20804 | &app, |
| 20805 | "POST", |
| 20806 | "/bank-questions", |
| 20807 | Some(&teacher), |
| 20808 | Some(json!({ "subject_id": subject, "text": "Which city?", "kind": "choice", |
| 20809 | "points": 10, "choices": [{"id": "c0", "text": "Ankara"}, {"id": "c1", "text": "İzmir"}], "correct": "c0" })), |
| 20810 | ) |
| 20811 | .await; |
| 20812 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20813 | let bid = id_of(&res.body); |
| 20814 | let opt = choice_of(&res.body, 0); |
| 20815 | |
| 20816 | let illus = b"bank-illustration".as_slice(); |
| 20817 | let choice = b"bank-choice-pic".as_slice(); |
| 20818 | let (status, _) = post_image( |
| 20819 | &app, |
| 20820 | &teacher, |
| 20821 | &format!("/bank-questions/{bid}/image"), |
| 20822 | "image/png", |
| 20823 | illus, |
| 20824 | ) |
| 20825 | .await; |
| 20826 | assert_eq!(status, StatusCode::CREATED); |
| 20827 | let (status, _) = post_image( |
| 20828 | &app, |
| 20829 | &teacher, |
| 20830 | &format!("/bank-questions/{bid}/choices/{opt}/image"), |
| 20831 | "image/webp", |
| 20832 | choice, |
| 20833 | ) |
| 20834 | .await; |
| 20835 | assert_eq!(status, StatusCode::CREATED); |
| 20836 | let src_bank_keys = bank_image_blob_keys(&db).await; |
| 20837 | assert_eq!(src_bank_keys.len(), 2); |
| 20838 | |
| 20839 | // Instantiate into an exam. |
| 20840 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "final").await; |
| 20841 | let res = send( |
| 20842 | &app, |
| 20843 | "POST", |
| 20844 | &format!("/exams/{exam}/questions/from-bank/{bid}"), |
| 20845 | Some(&teacher), |
| 20846 | Some(json!({ "subject_id": subject })), |
| 20847 | ) |
| 20848 | .await; |
| 20849 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20850 | let qid = id_of(&res.body); |
| 20851 | |
| 20852 | // Both images retrievable on the new exam question, bytes equal to source. |
| 20853 | let (status, _, bytes) = common::send_raw( |
| 20854 | &app, |
| 20855 | "GET", |
| 20856 | &format!("/exams/{exam}/questions/{qid}/image"), |
| 20857 | Some(&teacher), |
| 20858 | None, |
| 20859 | Vec::new(), |
| 20860 | ) |
| 20861 | .await; |
| 20862 | assert_eq!(status, StatusCode::OK); |
| 20863 | assert_eq!(bytes, illus); |
| 20864 | let (status, _, bytes) = common::send_raw( |
| 20865 | &app, |
| 20866 | "GET", |
| 20867 | &format!("/exams/{exam}/questions/{qid}/choices/{opt}/image"), |
| 20868 | Some(&teacher), |
| 20869 | None, |
| 20870 | Vec::new(), |
| 20871 | ) |
| 20872 | .await; |
| 20873 | assert_eq!(status, StatusCode::OK); |
| 20874 | assert_eq!(bytes, choice); |
| 20875 | |
| 20876 | // Copies are fresh files — new keys, none shared with the bank. |
| 20877 | let exam_keys = image_blob_keys(&db).await; |
| 20878 | assert_eq!(exam_keys.len(), 2); |
| 20879 | for k in &exam_keys { |
| 20880 | assert!( |
| 20881 | !src_bank_keys.contains(k), |
| 20882 | "copied blob reused a source file" |
| 20883 | ); |
| 20884 | } |
| 20885 | |
| 20886 | // Source bank images untouched — still 200 with the same bytes and keys. |
| 20887 | let (status, _, bytes) = common::send_raw( |
| 20888 | &app, |
| 20889 | "GET", |
| 20890 | &format!("/bank-questions/{bid}/image"), |
| 20891 | Some(&teacher), |
| 20892 | None, |
| 20893 | Vec::new(), |
| 20894 | ) |
| 20895 | .await; |
| 20896 | assert_eq!(status, StatusCode::OK); |
| 20897 | assert_eq!(bytes, illus); |
| 20898 | let (status, _, bytes) = common::send_raw( |
| 20899 | &app, |
| 20900 | "GET", |
| 20901 | &format!("/bank-questions/{bid}/choices/{opt}/image"), |
| 20902 | Some(&teacher), |
| 20903 | None, |
| 20904 | Vec::new(), |
| 20905 | ) |
| 20906 | .await; |
| 20907 | assert_eq!(status, StatusCode::OK); |
| 20908 | assert_eq!(bytes, choice); |
| 20909 | assert_eq!( |
| 20910 | bank_image_blob_keys(&db).await, |
| 20911 | src_bank_keys, |
| 20912 | "source keys changed" |
| 20913 | ); |
| 20914 | } |
| 20915 | |
| 20916 | /// Saving an exam question to the bank copies its image blobs to fresh files |
| 20917 | /// under the new template, byte-for-byte, source exam images untouched. |
| 20918 | #[tokio::test] |
| 20919 | async fn bank_save_copies_images() { |
| 20920 | let (app, db) = app_and_db().await; |
| 20921 | let teacher = login_as(&app, &db, "simg_t", "teacher").await; |
| 20922 | let mudur = login_as(&app, &db, "phys1_m", "manager").await; |
| 20923 | scheduling_kinds(&app, &mudur).await; |
| 20924 | let t = taught_under(&app, &mudur, &teacher, "phys1").await; |
| 20925 | let subject = create_subject(&app, &teacher, &t.course, "kin1").await; |
| 20926 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "final", "final").await; |
| 20927 | let qid_body = create_question_body( |
| 20928 | &app, |
| 20929 | &teacher, |
| 20930 | &exam, |
| 20931 | &subject, |
| 20932 | json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }), |
| 20933 | ) |
| 20934 | .await; |
| 20935 | let qid = id_of(&qid_body); |
| 20936 | let opt = choice_of(&qid_body, 0); |
| 20937 | |
| 20938 | let illus = b"exam-illustration".as_slice(); |
| 20939 | let choice = b"exam-choice-pic".as_slice(); |
| 20940 | let (status, _) = post_image( |
| 20941 | &app, |
| 20942 | &teacher, |
| 20943 | &format!("/exams/{exam}/questions/{qid}/image"), |
| 20944 | "image/png", |
| 20945 | illus, |
| 20946 | ) |
| 20947 | .await; |
| 20948 | assert_eq!(status, StatusCode::CREATED); |
| 20949 | let (status, _) = post_image( |
| 20950 | &app, |
| 20951 | &teacher, |
| 20952 | &format!("/exams/{exam}/questions/{qid}/choices/{opt}/image"), |
| 20953 | "image/jpeg", |
| 20954 | choice, |
| 20955 | ) |
| 20956 | .await; |
| 20957 | assert_eq!(status, StatusCode::CREATED); |
| 20958 | let src_exam_keys = image_blob_keys(&db).await; |
| 20959 | assert_eq!(src_exam_keys.len(), 2); |
| 20960 | |
| 20961 | let res = send( |
| 20962 | &app, |
| 20963 | "POST", |
| 20964 | &format!("/exams/{exam}/questions/{qid}/to-bank"), |
| 20965 | Some(&teacher), |
| 20966 | None, |
| 20967 | ) |
| 20968 | .await; |
| 20969 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 20970 | let bid = id_of(&res.body); |
| 20971 | let opt = choice_of(&res.body, 0); |
| 20972 | |
| 20973 | // The new bank question carries both images, bytes equal. |
| 20974 | let (status, _, bytes) = common::send_raw( |
| 20975 | &app, |
| 20976 | "GET", |
| 20977 | &format!("/bank-questions/{bid}/image"), |
| 20978 | Some(&teacher), |
| 20979 | None, |
| 20980 | Vec::new(), |
| 20981 | ) |
| 20982 | .await; |
| 20983 | assert_eq!(status, StatusCode::OK); |
| 20984 | assert_eq!(bytes, illus); |
| 20985 | let (status, _, bytes) = common::send_raw( |
| 20986 | &app, |
| 20987 | "GET", |
| 20988 | &format!("/bank-questions/{bid}/choices/{opt}/image"), |
| 20989 | Some(&teacher), |
| 20990 | None, |
| 20991 | Vec::new(), |
| 20992 | ) |
| 20993 | .await; |
| 20994 | assert_eq!(status, StatusCode::OK); |
| 20995 | assert_eq!(bytes, choice); |
| 20996 | |
| 20997 | // Fresh keys; source exam images untouched. |
| 20998 | let bank_keys = bank_image_blob_keys(&db).await; |
| 20999 | assert_eq!(bank_keys.len(), 2); |
| 21000 | for k in &bank_keys { |
| 21001 | assert!( |
| 21002 | !src_exam_keys.contains(k), |
| 21003 | "copied blob reused a source file" |
| 21004 | ); |
| 21005 | } |
| 21006 | assert_eq!( |
| 21007 | image_blob_keys(&db).await, |
| 21008 | src_exam_keys, |
| 21009 | "source keys changed" |
| 21010 | ); |
| 21011 | let (status, _, bytes) = common::send_raw( |
| 21012 | &app, |
| 21013 | "GET", |
| 21014 | &format!("/exams/{exam}/questions/{qid}/image"), |
| 21015 | Some(&teacher), |
| 21016 | None, |
| 21017 | Vec::new(), |
| 21018 | ) |
| 21019 | .await; |
| 21020 | assert_eq!(status, StatusCode::OK); |
| 21021 | assert_eq!(bytes, illus); |
| 21022 | } |
| 21023 | |
| 21024 | /// An image survives a full round trip: exam question -> bank -> a second exam, |
| 21025 | /// with the bytes intact at the far end. |
| 21026 | #[tokio::test] |
| 21027 | async fn bank_round_trip_preserves_image_bytes() { |
| 21028 | let (app, db) = app_and_db().await; |
| 21029 | let teacher = login_as(&app, &db, "rt_t", "teacher").await; |
| 21030 | let mudur = login_as(&app, &db, "hist1_m", "manager").await; |
| 21031 | scheduling_kinds(&app, &mudur).await; |
| 21032 | let t = taught_under(&app, &mudur, &teacher, "hist1").await; |
| 21033 | let subject = create_subject(&app, &teacher, &t.course, "eras1").await; |
| 21034 | let exam1 = create_exam(&app, &teacher, &t.instance, &t.term, "e1", "final").await; |
| 21035 | let qid = create_question( |
| 21036 | &app, |
| 21037 | &teacher, |
| 21038 | &exam1, |
| 21039 | &subject, |
| 21040 | json!({ "text": "When?", "kind": "text", "points": 10 }), |
| 21041 | ) |
| 21042 | .await; |
| 21043 | let pic = b"round-trip-illustration".as_slice(); |
| 21044 | let (status, _) = post_image( |
| 21045 | &app, |
| 21046 | &teacher, |
| 21047 | &format!("/exams/{exam1}/questions/{qid}/image"), |
| 21048 | "image/png", |
| 21049 | pic, |
| 21050 | ) |
| 21051 | .await; |
| 21052 | assert_eq!(status, StatusCode::CREATED); |
| 21053 | |
| 21054 | // Hop one: exam -> bank. |
| 21055 | let res = send( |
| 21056 | &app, |
| 21057 | "POST", |
| 21058 | &format!("/exams/{exam1}/questions/{qid}/to-bank"), |
| 21059 | Some(&teacher), |
| 21060 | None, |
| 21061 | ) |
| 21062 | .await; |
| 21063 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 21064 | let bid = id_of(&res.body); |
| 21065 | |
| 21066 | // Hop two: bank -> a second exam. |
| 21067 | let exam2 = create_exam(&app, &teacher, &t.instance, &t.term, "e2", "final").await; |
| 21068 | let res = send( |
| 21069 | &app, |
| 21070 | "POST", |
| 21071 | &format!("/exams/{exam2}/questions/from-bank/{bid}"), |
| 21072 | Some(&teacher), |
| 21073 | Some(json!({ "subject_id": subject })), |
| 21074 | ) |
| 21075 | .await; |
| 21076 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 21077 | let qid2 = id_of(&res.body); |
| 21078 | |
| 21079 | let (status, _, bytes) = common::send_raw( |
| 21080 | &app, |
| 21081 | "GET", |
| 21082 | &format!("/exams/{exam2}/questions/{qid2}/image"), |
| 21083 | Some(&teacher), |
| 21084 | None, |
| 21085 | Vec::new(), |
| 21086 | ) |
| 21087 | .await; |
| 21088 | assert_eq!(status, StatusCode::OK); |
| 21089 | assert_eq!(bytes, pic, "bytes drifted across the round trip"); |
| 21090 | } |
| 21091 | |
| 21092 | /// Gap-1 guard: a missing source blob mid-copy is all-or-nothing — the |
| 21093 | /// instantiate 500s and leaves NO partial destination (no exam question row, no |
| 21094 | /// exam image rows), while the source template survives intact. |
| 21095 | #[tokio::test] |
| 21096 | async fn bank_instantiate_rolls_back_on_missing_source_blob() { |
| 21097 | let (app, db) = app_and_db().await; |
| 21098 | let teacher = login_as(&app, &db, "rb_t", "teacher").await; |
| 21099 | let mudur = login_as(&app, &db, "geo2_m", "manager").await; |
| 21100 | scheduling_kinds(&app, &mudur).await; |
| 21101 | let t = taught_under(&app, &mudur, &teacher, "geo2").await; |
| 21102 | let subject = create_subject(&app, &teacher, &t.course, "maps2").await; |
| 21103 | select_instance_subject(&app, &teacher, &t.instance, &subject).await; |
| 21104 | |
| 21105 | // Two images so the copy loop has multiple steps. |
| 21106 | let res = send( |
| 21107 | &app, |
| 21108 | "POST", |
| 21109 | "/bank-questions", |
| 21110 | Some(&teacher), |
| 21111 | Some(json!({ "subject_id": subject, "text": "q", "kind": "choice", |
| 21112 | "points": 10, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" })), |
| 21113 | ) |
| 21114 | .await; |
| 21115 | let bid = id_of(&res.body); |
| 21116 | let opt = choice_of(&res.body, 0); |
| 21117 | let (status, _) = post_image( |
| 21118 | &app, |
| 21119 | &teacher, |
| 21120 | &format!("/bank-questions/{bid}/image"), |
| 21121 | "image/png", |
| 21122 | b"illus", |
| 21123 | ) |
| 21124 | .await; |
| 21125 | assert_eq!(status, StatusCode::CREATED); |
| 21126 | let (status, _) = post_image( |
| 21127 | &app, |
| 21128 | &teacher, |
| 21129 | &format!("/bank-questions/{bid}/choices/{opt}/image"), |
| 21130 | "image/png", |
| 21131 | b"opt", |
| 21132 | ) |
| 21133 | .await; |
| 21134 | assert_eq!(status, StatusCode::CREATED); |
| 21135 | |
| 21136 | // Corrupt the source on disk: delete one blob so the copy loop hits an |
| 21137 | // unreadable source mid-flight. |
| 21138 | let src_keys = bank_image_blob_keys(&db).await; |
| 21139 | assert_eq!(src_keys.len(), 2); |
| 21140 | tokio::fs::remove_file(common::blob_dir().join(&src_keys[0])) |
| 21141 | .await |
| 21142 | .unwrap(); |
| 21143 | |
| 21144 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "final").await; |
| 21145 | let res = send( |
| 21146 | &app, |
| 21147 | "POST", |
| 21148 | &format!("/exams/{exam}/questions/from-bank/{bid}"), |
| 21149 | Some(&teacher), |
| 21150 | Some(json!({ "subject_id": subject })), |
| 21151 | ) |
| 21152 | .await; |
| 21153 | assert_eq!( |
| 21154 | res.status, |
| 21155 | StatusCode::INTERNAL_SERVER_ERROR, |
| 21156 | "{}", |
| 21157 | res.body |
| 21158 | ); |
| 21159 | |
| 21160 | // No partial destination: no question row, no exam image rows (isolated |
| 21161 | // per-test DB is the race-safe source of truth; the shared parallel blob |
| 21162 | // dir rules out an exact on-disk diff). |
| 21163 | let res = send( |
| 21164 | &app, |
| 21165 | "GET", |
| 21166 | &format!("/exams/{exam}/questions"), |
| 21167 | Some(&teacher), |
| 21168 | None, |
| 21169 | ) |
| 21170 | .await; |
| 21171 | assert!( |
| 21172 | common::items(&res.body).is_empty(), |
| 21173 | "orphan question survived rollback" |
| 21174 | ); |
| 21175 | assert!( |
| 21176 | image_blob_keys(&db).await.is_empty(), |
| 21177 | "orphan exam image rows survived rollback" |
| 21178 | ); |
| 21179 | |
| 21180 | // Source intact: the template still reads, and its surviving blob is still |
| 21181 | // on disk. |
| 21182 | let res = send( |
| 21183 | &app, |
| 21184 | "GET", |
| 21185 | &format!("/bank-questions/{bid}"), |
| 21186 | Some(&teacher), |
| 21187 | None, |
| 21188 | ) |
| 21189 | .await; |
| 21190 | assert_eq!(res.status, StatusCode::OK); |
| 21191 | assert_eq!( |
| 21192 | bank_image_blob_keys(&db).await, |
| 21193 | src_keys, |
| 21194 | "source bank rows changed" |
| 21195 | ); |
| 21196 | assert!( |
| 21197 | common::blob_dir().join(&src_keys[1]).exists(), |
| 21198 | "surviving source blob vanished" |
| 21199 | ); |
| 21200 | } |
| 21201 | |
| 21202 | /// A bank template's subject is origin metadata, but it must still exist: |
| 21203 | /// create and update both 400 on an unknown subject id. |
| 21204 | #[tokio::test] |
| 21205 | async fn bank_rejects_unknown_subject() { |
| 21206 | let (app, db) = app_and_db().await; |
| 21207 | let teacher = login_as(&app, &db, "bsub_t", "teacher").await; |
| 21208 | let mudur = login_as(&app, &db, "bsub_c_m", "manager").await; |
| 21209 | let t = taught_under(&app, &mudur, &teacher, "bsub_c").await; |
| 21210 | let subject = create_subject(&app, &teacher, &t.course, "bsub_s").await; |
| 21211 | |
| 21212 | // Create with a bogus subject id — 400, not a stored row. |
| 21213 | let res = send( |
| 21214 | &app, |
| 21215 | "POST", |
| 21216 | "/bank-questions", |
| 21217 | Some(&teacher), |
| 21218 | Some(json!({ "subject_id": "nope", "text": "q", "kind": "text", "points": 5 })), |
| 21219 | ) |
| 21220 | .await; |
| 21221 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 21222 | |
| 21223 | // Create a real one, then PATCH its subject to a bogus id — also 400. |
| 21224 | let res = send( |
| 21225 | &app, |
| 21226 | "POST", |
| 21227 | "/bank-questions", |
| 21228 | Some(&teacher), |
| 21229 | Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), |
| 21230 | ) |
| 21231 | .await; |
| 21232 | let bid = id_of(&res.body); |
| 21233 | let res = send( |
| 21234 | &app, |
| 21235 | "PATCH", |
| 21236 | &format!("/bank-questions/{bid}"), |
| 21237 | Some(&teacher), |
| 21238 | Some(json!({ "subject_id": "nope" })), |
| 21239 | ) |
| 21240 | .await; |
| 21241 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 21242 | } |
| 21243 | |
| 21244 | /// Deleting a subject clears it off the bank templates that carried it as |
| 21245 | /// origin metadata, instead of being refused. Blocking would have been a dead |
| 21246 | /// end (only a template's owner may re-tag it, so a manager could not clear |
| 21247 | /// their own 409) and an existence oracle for other teachers' private |
| 21248 | /// templates — hence the cascade. |
| 21249 | #[tokio::test] |
| 21250 | async fn subject_delete_clears_the_bank_templates_subject() { |
| 21251 | let (app, db) = app_and_db().await; |
| 21252 | let teacher = login_as(&app, &db, "bdel_t", "teacher").await; |
| 21253 | let manager = login_as(&app, &db, "bdel_m", "manager").await; |
| 21254 | let mudur = login_as(&app, &db, "bdel_c_m", "manager").await; |
| 21255 | let t = taught_under(&app, &mudur, &teacher, "bdel_c").await; |
| 21256 | let subject = create_subject(&app, &teacher, &t.course, "bdel_s").await; |
| 21257 | let other = create_subject(&app, &teacher, &t.course, "bdel_s2").await; |
| 21258 | |
| 21259 | let mut ids = Vec::new(); |
| 21260 | for subject_id in [&subject, &other] { |
| 21261 | let res = send( |
| 21262 | &app, |
| 21263 | "POST", |
| 21264 | "/bank-questions", |
| 21265 | Some(&teacher), |
| 21266 | Some(json!({ "subject_id": subject_id, "text": "q", "kind": "text", "points": 5 })), |
| 21267 | ) |
| 21268 | .await; |
| 21269 | ids.push(id_of(&res.body)); |
| 21270 | } |
| 21271 | let (bid, kept) = (&ids[0], &ids[1]); |
| 21272 | |
| 21273 | // The manager owns none of these templates, yet the delete goes through. |
| 21274 | let res = send( |
| 21275 | &app, |
| 21276 | "DELETE", |
| 21277 | &format!("/subjects/{subject}"), |
| 21278 | Some(&manager), |
| 21279 | None, |
| 21280 | ) |
| 21281 | .await; |
| 21282 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 21283 | |
| 21284 | // The template survives with a cleared origin; the other one is untouched. |
| 21285 | let res = send( |
| 21286 | &app, |
| 21287 | "GET", |
| 21288 | &format!("/bank-questions/{bid}"), |
| 21289 | Some(&teacher), |
| 21290 | None, |
| 21291 | ) |
| 21292 | .await; |
| 21293 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 21294 | assert_eq!(res.body["subject"], serde_json::Value::Null); |
| 21295 | assert_eq!(res.body["text"], "q"); |
| 21296 | let res = send( |
| 21297 | &app, |
| 21298 | "GET", |
| 21299 | &format!("/bank-questions/{kept}"), |
| 21300 | Some(&teacher), |
| 21301 | None, |
| 21302 | ) |
| 21303 | .await; |
| 21304 | assert_eq!(res.body["subject"], json!(other)); |
| 21305 | |
| 21306 | // The list join renders the cleared one with an empty subject name. |
| 21307 | let res = send(&app, "GET", "/bank-questions", Some(&teacher), None).await; |
| 21308 | let cleared = common::items(&res.body) |
| 21309 | .iter() |
| 21310 | .find(|q| q["id"] == *bid) |
| 21311 | .expect("template in list") |
| 21312 | .clone(); |
| 21313 | assert_eq!(cleared["subject"], serde_json::Value::Null); |
| 21314 | assert_eq!(cleared["subject_name"], ""); |
| 21315 | |
| 21316 | // A cleared template still edits: PATCH without `subject_id` keeps it null. |
| 21317 | let res = send( |
| 21318 | &app, |
| 21319 | "PATCH", |
| 21320 | &format!("/bank-questions/{bid}"), |
| 21321 | Some(&teacher), |
| 21322 | Some(json!({ "text": "still editable" })), |
| 21323 | ) |
| 21324 | .await; |
| 21325 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 21326 | assert_eq!(res.body["subject"], serde_json::Value::Null); |
| 21327 | assert_eq!(res.body["text"], "still editable"); |
| 21328 | } |
| 21329 | |
| 21330 | /// `?owner=me` (and an explicit owner id) narrows the bank to one owner's |
| 21331 | /// templates — on top of the visibility gate, never around it. |
| 21332 | #[tokio::test] |
| 21333 | async fn bank_owner_filter() { |
| 21334 | let (app, db) = app_and_db().await; |
| 21335 | let alice = login_as(&app, &db, "bown_a", "teacher").await; |
| 21336 | let bob = login_as(&app, &db, "bown_b", "teacher").await; |
| 21337 | let mudur = login_as(&app, &db, "bown_c_m", "manager").await; |
| 21338 | let t = taught_under(&app, &mudur, &alice, "bown_c").await; |
| 21339 | let subject = create_subject(&app, &alice, &t.course, "bown_s").await; |
| 21340 | |
| 21341 | for who in [&alice, &bob] { |
| 21342 | let res = send( |
| 21343 | &app, |
| 21344 | "POST", |
| 21345 | "/bank-questions", |
| 21346 | Some(who), |
| 21347 | Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), |
| 21348 | ) |
| 21349 | .await; |
| 21350 | // Published, so this test is about the owner filter, not visibility. |
| 21351 | let bid = id_of(&res.body); |
| 21352 | let res = send( |
| 21353 | &app, |
| 21354 | "PATCH", |
| 21355 | &format!("/bank-questions/{bid}"), |
| 21356 | Some(who), |
| 21357 | Some(json!({ "visibility": "school" })), |
| 21358 | ) |
| 21359 | .await; |
| 21360 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 21361 | } |
| 21362 | let alice_id = me_id(&app, &alice).await; |
| 21363 | let bob_id = me_id(&app, &bob).await; |
| 21364 | |
| 21365 | // Whole bank has both. |
| 21366 | let res = send(&app, "GET", "/bank-questions", Some(&alice), None).await; |
| 21367 | assert_eq!(common::items(&res.body).len(), 2); |
| 21368 | |
| 21369 | // `me` resolves to the caller. |
| 21370 | let res = send(&app, "GET", "/bank-questions?owner=me", Some(&alice), None).await; |
| 21371 | let items = common::items(&res.body); |
| 21372 | assert_eq!(items.len(), 1); |
| 21373 | assert_eq!(items[0]["owner"], alice_id); |
| 21374 | |
| 21375 | // An explicit id filters to that owner. |
| 21376 | let res = send( |
| 21377 | &app, |
| 21378 | "GET", |
| 21379 | &format!("/bank-questions?owner={bob_id}"), |
| 21380 | Some(&alice), |
| 21381 | None, |
| 21382 | ) |
| 21383 | .await; |
| 21384 | let items = common::items(&res.body); |
| 21385 | assert_eq!(items.len(), 1); |
| 21386 | assert_eq!(items[0]["owner"], bob_id); |
| 21387 | } |
| 21388 | |
| 21389 | /// A template's response carries its image metadata (illustration + per-choice |
| 21390 | /// slots) once images are uploaded — the same shape the exam side returns. |
| 21391 | #[tokio::test] |
| 21392 | async fn bank_response_carries_image_metas() { |
| 21393 | let (app, db) = app_and_db().await; |
| 21394 | let teacher = login_as(&app, &db, "bmeta_t", "teacher").await; |
| 21395 | let mudur = login_as(&app, &db, "bmeta_c_m", "manager").await; |
| 21396 | let t = taught_under(&app, &mudur, &teacher, "bmeta_c").await; |
| 21397 | let subject = create_subject(&app, &teacher, &t.course, "bmeta_s").await; |
| 21398 | let res = send( |
| 21399 | &app, |
| 21400 | "POST", |
| 21401 | "/bank-questions", |
| 21402 | Some(&teacher), |
| 21403 | Some(json!({ "subject_id": subject, "text": "q", "kind": "choice", |
| 21404 | "points": 10, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" })), |
| 21405 | ) |
| 21406 | .await; |
| 21407 | let bid = id_of(&res.body); |
| 21408 | let opt = choice_of(&res.body, 0); |
| 21409 | |
| 21410 | // No images yet: metas are null / all-empty. |
| 21411 | assert!(res.body["image"].is_null()); |
| 21412 | assert_eq!(res.body["choice_images"], json!([null, null])); |
| 21413 | |
| 21414 | let (status, _) = post_image( |
| 21415 | &app, |
| 21416 | &teacher, |
| 21417 | &format!("/bank-questions/{bid}/image"), |
| 21418 | "image/png", |
| 21419 | b"illus", |
| 21420 | ) |
| 21421 | .await; |
| 21422 | assert_eq!(status, StatusCode::CREATED); |
| 21423 | let (status, _) = post_image( |
| 21424 | &app, |
| 21425 | &teacher, |
| 21426 | &format!("/bank-questions/{bid}/choices/{opt}/image"), |
| 21427 | "image/jpeg", |
| 21428 | b"opt", |
| 21429 | ) |
| 21430 | .await; |
| 21431 | assert_eq!(status, StatusCode::CREATED); |
| 21432 | |
| 21433 | let res = send( |
| 21434 | &app, |
| 21435 | "GET", |
| 21436 | &format!("/bank-questions/{bid}"), |
| 21437 | Some(&teacher), |
| 21438 | None, |
| 21439 | ) |
| 21440 | .await; |
| 21441 | assert_eq!(res.body["image"]["content_type"], "image/png"); |
| 21442 | assert_eq!(res.body["image"]["size"], 5); |
| 21443 | assert_eq!(res.body["choice_images"][0]["content_type"], "image/jpeg"); |
| 21444 | assert!(res.body["choice_images"][1].is_null()); |
| 21445 | |
| 21446 | // The list carries them too (batched, not per-row). |
| 21447 | let res = send( |
| 21448 | &app, |
| 21449 | "GET", |
| 21450 | "/bank-questions?owner=me", |
| 21451 | Some(&teacher), |
| 21452 | None, |
| 21453 | ) |
| 21454 | .await; |
| 21455 | let items = common::items(&res.body); |
| 21456 | assert_eq!(items[0]["image"]["content_type"], "image/png"); |
| 21457 | assert_eq!(items[0]["choice_images"][0]["content_type"], "image/jpeg"); |
| 21458 | } |
| 21459 | |
| 21460 | /// Provenance rides both directions, one column per direction: instantiate |
| 21461 | /// records `from_bank` on the new exam question (and leaves `banked_as` null — |
| 21462 | /// coming *from* the bank is not being saved *to* it); save-to-bank records |
| 21463 | /// `source_exam` on the new template and `banked_as` on the question, without |
| 21464 | /// touching `from_bank`. |
| 21465 | #[tokio::test] |
| 21466 | async fn bank_provenance_both_directions() { |
| 21467 | let (app, db) = app_and_db().await; |
| 21468 | let teacher = login_as(&app, &db, "bprov_t", "teacher").await; |
| 21469 | let mudur = login_as(&app, &db, "bprov_c_m", "manager").await; |
| 21470 | scheduling_kinds(&app, &mudur).await; |
| 21471 | let t = taught_under(&app, &mudur, &teacher, "bprov_c").await; |
| 21472 | let subject = create_subject(&app, &teacher, &t.course, "bprov_s").await; |
| 21473 | select_instance_subject(&app, &teacher, &t.instance, &subject).await; |
| 21474 | |
| 21475 | // Bank -> exam: from_bank is the template id, banked_as stays null. |
| 21476 | let res = send( |
| 21477 | &app, |
| 21478 | "POST", |
| 21479 | "/bank-questions", |
| 21480 | Some(&teacher), |
| 21481 | Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), |
| 21482 | ) |
| 21483 | .await; |
| 21484 | let bid = id_of(&res.body); |
| 21485 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "final").await; |
| 21486 | let res = send( |
| 21487 | &app, |
| 21488 | "POST", |
| 21489 | &format!("/exams/{exam}/questions/from-bank/{bid}"), |
| 21490 | Some(&teacher), |
| 21491 | Some(json!({ "subject_id": subject })), |
| 21492 | ) |
| 21493 | .await; |
| 21494 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 21495 | assert_eq!(res.body["from_bank"], bid); |
| 21496 | // The lie the split fixes: an inserted question must not read as banked. |
| 21497 | assert!(res.body["banked_as"].is_null(), "{}", res.body); |
| 21498 | let inserted = id_of(&res.body); |
| 21499 | |
| 21500 | // Saving that inserted question sets banked_as and leaves from_bank alone. |
| 21501 | let res = send( |
| 21502 | &app, |
| 21503 | "POST", |
| 21504 | &format!("/exams/{exam}/questions/{inserted}/to-bank"), |
| 21505 | Some(&teacher), |
| 21506 | None, |
| 21507 | ) |
| 21508 | .await; |
| 21509 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 21510 | let template = id_of(&res.body); |
| 21511 | let res = send( |
| 21512 | &app, |
| 21513 | "GET", |
| 21514 | &format!("/exams/{exam}/questions"), |
| 21515 | Some(&teacher), |
| 21516 | None, |
| 21517 | ) |
| 21518 | .await; |
| 21519 | let question = common::items(&res.body) |
| 21520 | .iter() |
| 21521 | .find(|q| q["id"] == inserted) |
| 21522 | .expect("question in list") |
| 21523 | .clone(); |
| 21524 | assert_eq!(question["from_bank"], bid, "{question}"); |
| 21525 | assert_eq!(question["banked_as"], template, "{question}"); |
| 21526 | |
| 21527 | // A directly authored exam question has neither link. |
| 21528 | let qid = create_question( |
| 21529 | &app, |
| 21530 | &teacher, |
| 21531 | &exam, |
| 21532 | &subject, |
| 21533 | json!({ "text": "plain", "kind": "text", "points": 5 }), |
| 21534 | ) |
| 21535 | .await; |
| 21536 | |
| 21537 | // Exam -> bank: source_exam is the origin exam id. |
| 21538 | let res = send( |
| 21539 | &app, |
| 21540 | "POST", |
| 21541 | &format!("/exams/{exam}/questions/{qid}/to-bank"), |
| 21542 | Some(&teacher), |
| 21543 | None, |
| 21544 | ) |
| 21545 | .await; |
| 21546 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 21547 | assert_eq!(res.body["source_exam"], exam); |
| 21548 | |
| 21549 | // A directly authored template has no source_exam. |
| 21550 | let res = send( |
| 21551 | &app, |
| 21552 | "GET", |
| 21553 | &format!("/bank-questions/{bid}"), |
| 21554 | Some(&teacher), |
| 21555 | None, |
| 21556 | ) |
| 21557 | .await; |
| 21558 | assert!(res.body["source_exam"].is_null()); |
| 21559 | } |
| 21560 | |
| 21561 | /// Save-to-bank also links the *question* back at the template it produced, so |
| 21562 | /// a client can tell it was already banked. A repeat save is allowed and |
| 21563 | /// repoints the link at the newer template. |
| 21564 | #[tokio::test] |
| 21565 | async fn to_bank_links_the_question_at_the_new_template() { |
| 21566 | let (app, db) = app_and_db().await; |
| 21567 | let teacher = login_as(&app, &db, "bback_t", "teacher").await; |
| 21568 | let mudur = login_as(&app, &db, "bback_c_m", "manager").await; |
| 21569 | scheduling_kinds(&app, &mudur).await; |
| 21570 | let t = taught_under(&app, &mudur, &teacher, "bback_c").await; |
| 21571 | let subject = create_subject(&app, &teacher, &t.course, "bback_s").await; |
| 21572 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "final").await; |
| 21573 | let qid = create_question( |
| 21574 | &app, |
| 21575 | &teacher, |
| 21576 | &exam, |
| 21577 | &subject, |
| 21578 | json!({ "text": "plain", "kind": "text", "points": 5 }), |
| 21579 | ) |
| 21580 | .await; |
| 21581 | |
| 21582 | // Fresh question: no link yet. |
| 21583 | let banked_as_of = |body: &serde_json::Value| -> serde_json::Value { |
| 21584 | common::items(body) |
| 21585 | .iter() |
| 21586 | .find(|q| q["id"] == qid) |
| 21587 | .expect("question in list")["banked_as"] |
| 21588 | .clone() |
| 21589 | }; |
| 21590 | let res = send( |
| 21591 | &app, |
| 21592 | "GET", |
| 21593 | &format!("/exams/{exam}/questions"), |
| 21594 | Some(&teacher), |
| 21595 | None, |
| 21596 | ) |
| 21597 | .await; |
| 21598 | assert!(banked_as_of(&res.body).is_null()); |
| 21599 | |
| 21600 | let res = send( |
| 21601 | &app, |
| 21602 | "POST", |
| 21603 | &format!("/exams/{exam}/questions/{qid}/to-bank"), |
| 21604 | Some(&teacher), |
| 21605 | None, |
| 21606 | ) |
| 21607 | .await; |
| 21608 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 21609 | let first = id_of(&res.body); |
| 21610 | let res = send( |
| 21611 | &app, |
| 21612 | "GET", |
| 21613 | &format!("/exams/{exam}/questions"), |
| 21614 | Some(&teacher), |
| 21615 | None, |
| 21616 | ) |
| 21617 | .await; |
| 21618 | assert_eq!(banked_as_of(&res.body), json!(first)); |
| 21619 | |
| 21620 | // Second save: still 201, a distinct template, and the link follows it. |
| 21621 | let res = send( |
| 21622 | &app, |
| 21623 | "POST", |
| 21624 | &format!("/exams/{exam}/questions/{qid}/to-bank"), |
| 21625 | Some(&teacher), |
| 21626 | None, |
| 21627 | ) |
| 21628 | .await; |
| 21629 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 21630 | let second = id_of(&res.body); |
| 21631 | assert_ne!(first, second); |
| 21632 | let res = send( |
| 21633 | &app, |
| 21634 | "GET", |
| 21635 | &format!("/exams/{exam}/questions"), |
| 21636 | Some(&teacher), |
| 21637 | None, |
| 21638 | ) |
| 21639 | .await; |
| 21640 | assert_eq!(banked_as_of(&res.body), json!(second)); |
| 21641 | } |
| 21642 | |
| 21643 | /// The back-link is a field-scoped write. `question_to_bank` reads the question, |
| 21644 | /// then awaits a bank insert and the whole blob-copy loop before linking, holding |
| 21645 | /// no lock over `exam_question` — so a `PATCH` can land in that window. A |
| 21646 | /// whole-row save from the stale struct would silently revert it. Driven at the |
| 21647 | /// domain level: HTTP offers no way to interleave inside the handler. |
| 21648 | #[tokio::test] |
| 21649 | async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() { |
| 21650 | use hezarfen_backend::db::exam_question; |
| 21651 | use hezarfen_backend::domain::bank_question::BankQuestionId; |
| 21652 | use hezarfen_backend::domain::exam_question::ExamQuestionId; |
| 21653 | |
| 21654 | let (app, db) = app_and_db().await; |
| 21655 | let teacher = login_as(&app, &db, "bclob_t", "teacher").await; |
| 21656 | let mudur = login_as(&app, &db, "bclob_m", "manager").await; |
| 21657 | scheduling_kinds(&app, &mudur).await; |
| 21658 | let t = taught_under(&app, &mudur, &teacher, "bclob_c").await; |
| 21659 | let subject = create_subject(&app, &teacher, &t.course, "bclob_s").await; |
| 21660 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "final").await; |
| 21661 | let qid = create_question( |
| 21662 | &app, |
| 21663 | &teacher, |
| 21664 | &exam, |
| 21665 | &subject, |
| 21666 | json!({ "text": "original", "kind": "text", "points": 5 }), |
| 21667 | ) |
| 21668 | .await; |
| 21669 | let res = send( |
| 21670 | &app, |
| 21671 | "POST", |
| 21672 | "/bank-questions", |
| 21673 | Some(&teacher), |
| 21674 | Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), |
| 21675 | ) |
| 21676 | .await; |
| 21677 | let bid = id_of(&res.body); |
| 21678 | |
| 21679 | // The handler's read, then someone else's edit lands mid-window. |
| 21680 | let stale = exam_question::read(&db, &ExamQuestionId::from_key(&qid)) |
| 21681 | .await |
| 21682 | .unwrap() |
| 21683 | .expect("question exists"); |
| 21684 | let res = send( |
| 21685 | &app, |
| 21686 | "PATCH", |
| 21687 | &format!("/exams/{exam}/questions/{qid}"), |
| 21688 | Some(&teacher), |
| 21689 | Some(json!({ "text": "edited by someone else", "points": 9 })), |
| 21690 | ) |
| 21691 | .await; |
| 21692 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 21693 | |
| 21694 | exam_question::link_banked_as(&db, stale, BankQuestionId::from_key(&bid)) |
| 21695 | .await |
| 21696 | .expect("link written"); |
| 21697 | |
| 21698 | // The edit survives and the link is set. |
| 21699 | let res = send( |
| 21700 | &app, |
| 21701 | "GET", |
| 21702 | &format!("/exams/{exam}/questions"), |
| 21703 | Some(&teacher), |
| 21704 | None, |
| 21705 | ) |
| 21706 | .await; |
| 21707 | let question = common::items(&res.body) |
| 21708 | .iter() |
| 21709 | .find(|q| q["id"] == qid) |
| 21710 | .expect("question in list") |
| 21711 | .clone(); |
| 21712 | assert_eq!(question["text"], "edited by someone else"); |
| 21713 | assert_eq!(question["points"], 9); |
| 21714 | assert_eq!(question["banked_as"], bid); |
| 21715 | } |
| 21716 | |
| 21717 | /// A bank PATCH writes only the fields it was given: the handler reads the |
| 21718 | /// template, then awaits an ownership check, a subject lookup and (on a choice |
| 21719 | /// replace) an image sweep, so another write can land in that window — here the |
| 21720 | /// exam-delete cascade clearing `source_exam`, a field the PATCH never sets. |
| 21721 | /// A whole-row save from the stale struct would resurrect the dead exam link. |
| 21722 | #[tokio::test] |
| 21723 | async fn a_bank_patch_does_not_clobber_a_concurrent_write() { |
| 21724 | use hezarfen_backend::db::bank_question::{read, update_if_unchanged}; |
| 21725 | use hezarfen_backend::domain::bank_question::{BankQuestionId, BankVisibility}; |
| 21726 | use hezarfen_backend::domain::exam_question::{ |
| 21727 | QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 21728 | }; |
| 21729 | |
| 21730 | let (app, db) = app_and_db().await; |
| 21731 | let teacher = login_as(&app, &db, "bpatch_t", "teacher").await; |
| 21732 | let mudur = login_as(&app, &db, "bpatch_m", "manager").await; |
| 21733 | scheduling_kinds(&app, &mudur).await; |
| 21734 | let t = taught_under(&app, &mudur, &teacher, "bpatch_c").await; |
| 21735 | let subject = create_subject(&app, &teacher, &t.course, "bpatch_s").await; |
| 21736 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "final").await; |
| 21737 | let qid = create_question( |
| 21738 | &app, |
| 21739 | &teacher, |
| 21740 | &exam, |
| 21741 | &subject, |
| 21742 | json!({ "text": "original", "kind": "text", "points": 5 }), |
| 21743 | ) |
| 21744 | .await; |
| 21745 | let res = send( |
| 21746 | &app, |
| 21747 | "POST", |
| 21748 | &format!("/exams/{exam}/questions/{qid}/to-bank"), |
| 21749 | Some(&teacher), |
| 21750 | None, |
| 21751 | ) |
| 21752 | .await; |
| 21753 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 21754 | let bid = id_of(&res.body); |
| 21755 | assert_eq!(res.body["source_exam"], json!(exam)); |
| 21756 | |
| 21757 | // The handler's read, then the exam delete lands mid-window and clears the |
| 21758 | // template's `source_exam`. |
| 21759 | let stale = read(&db, &BankQuestionId::from_key(&bid)) |
| 21760 | .await |
| 21761 | .unwrap() |
| 21762 | .expect("template exists"); |
| 21763 | assert!(stale.get_source_exam().is_some()); |
| 21764 | let res = send( |
| 21765 | &app, |
| 21766 | "DELETE", |
| 21767 | &format!("/exams/{exam}"), |
| 21768 | Some(&teacher), |
| 21769 | None, |
| 21770 | ) |
| 21771 | .await; |
| 21772 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 21773 | |
| 21774 | // The stale struct writes its own fields only. |
| 21775 | let updated = update_if_unchanged( |
| 21776 | &db, |
| 21777 | stale, |
| 21778 | None, |
| 21779 | QuestionText::try_new("edited").unwrap(), |
| 21780 | QuestionPoints::try_new(7).unwrap(), |
| 21781 | QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), |
| 21782 | BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), |
| 21783 | ) |
| 21784 | .await |
| 21785 | .expect("update ran") |
| 21786 | .expect("update written — the exam delete touched no compared column"); |
| 21787 | assert_eq!(updated.get_text().as_str(), "edited"); |
| 21788 | assert!( |
| 21789 | updated.get_source_exam().is_none(), |
| 21790 | "the dead exam link came back" |
| 21791 | ); |
| 21792 | |
| 21793 | // The edit landed and the cleared provenance stayed cleared. |
| 21794 | let res = send( |
| 21795 | &app, |
| 21796 | "GET", |
| 21797 | &format!("/bank-questions/{bid}"), |
| 21798 | Some(&teacher), |
| 21799 | None, |
| 21800 | ) |
| 21801 | .await; |
| 21802 | assert_eq!(res.body["source_exam"], serde_json::Value::Null); |
| 21803 | assert_eq!(res.body["subject"], serde_json::Value::Null); |
| 21804 | assert_eq!(res.body["text"], "edited"); |
| 21805 | assert_eq!(res.body["points"], 7); |
| 21806 | assert_eq!(res.body["visibility"], "school"); |
| 21807 | } |
| 21808 | |
| 21809 | /// Deleting a bank template clears *both* provenance links that can point at |
| 21810 | /// it — `from_bank` on the questions instantiated from it and `banked_as` on |
| 21811 | /// the question it was saved out of — instead of leaving either pointing at a |
| 21812 | /// dead row. |
| 21813 | #[tokio::test] |
| 21814 | async fn deleting_a_template_clears_both_question_links() { |
| 21815 | let (app, db) = app_and_db().await; |
| 21816 | let teacher = login_as(&app, &db, "bdang_t", "teacher").await; |
| 21817 | let mudur = login_as(&app, &db, "bdang_c_m", "manager").await; |
| 21818 | scheduling_kinds(&app, &mudur).await; |
| 21819 | let t = taught_under(&app, &mudur, &teacher, "bdang_c").await; |
| 21820 | let subject = create_subject(&app, &teacher, &t.course, "bdang_s").await; |
| 21821 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "final").await; |
| 21822 | |
| 21823 | // Question A: authored here, then saved to the bank -> banked_as = saved. |
| 21824 | let authored = create_question( |
| 21825 | &app, |
| 21826 | &teacher, |
| 21827 | &exam, |
| 21828 | &subject, |
| 21829 | json!({ "text": "plain", "kind": "text", "points": 5 }), |
| 21830 | ) |
| 21831 | .await; |
| 21832 | let res = send( |
| 21833 | &app, |
| 21834 | "POST", |
| 21835 | &format!("/exams/{exam}/questions/{authored}/to-bank"), |
| 21836 | Some(&teacher), |
| 21837 | None, |
| 21838 | ) |
| 21839 | .await; |
| 21840 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 21841 | let saved = id_of(&res.body); |
| 21842 | |
| 21843 | // Question B: instantiated from a separate template -> from_bank = origin. |
| 21844 | let res = send( |
| 21845 | &app, |
| 21846 | "POST", |
| 21847 | "/bank-questions", |
| 21848 | Some(&teacher), |
| 21849 | Some(json!({ "subject_id": subject, "text": "t", "kind": "text", "points": 5 })), |
| 21850 | ) |
| 21851 | .await; |
| 21852 | let origin = id_of(&res.body); |
| 21853 | let res = send( |
| 21854 | &app, |
| 21855 | "POST", |
| 21856 | &format!("/exams/{exam}/questions/from-bank/{origin}"), |
| 21857 | Some(&teacher), |
| 21858 | Some(json!({ "subject_id": subject })), |
| 21859 | ) |
| 21860 | .await; |
| 21861 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 21862 | let inserted = id_of(&res.body); |
| 21863 | |
| 21864 | let link_of = |body: &serde_json::Value, qid: &str, field: &str| -> serde_json::Value { |
| 21865 | common::items(body) |
| 21866 | .iter() |
| 21867 | .find(|q| q["id"] == qid) |
| 21868 | .expect("question in list")[field] |
| 21869 | .clone() |
| 21870 | }; |
| 21871 | let res = send( |
| 21872 | &app, |
| 21873 | "GET", |
| 21874 | &format!("/exams/{exam}/questions"), |
| 21875 | Some(&teacher), |
| 21876 | None, |
| 21877 | ) |
| 21878 | .await; |
| 21879 | assert_eq!(link_of(&res.body, &authored, "banked_as"), json!(saved)); |
| 21880 | assert_eq!(link_of(&res.body, &inserted, "from_bank"), json!(origin)); |
| 21881 | |
| 21882 | for bid in [&saved, &origin] { |
| 21883 | let res = send( |
| 21884 | &app, |
| 21885 | "DELETE", |
| 21886 | &format!("/bank-questions/{bid}"), |
| 21887 | Some(&teacher), |
| 21888 | None, |
| 21889 | ) |
| 21890 | .await; |
| 21891 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 21892 | } |
| 21893 | |
| 21894 | // Both questions survive their templates with no dangling link. |
| 21895 | let res = send( |
| 21896 | &app, |
| 21897 | "GET", |
| 21898 | &format!("/exams/{exam}/questions"), |
| 21899 | Some(&teacher), |
| 21900 | None, |
| 21901 | ) |
| 21902 | .await; |
| 21903 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 21904 | assert!( |
| 21905 | link_of(&res.body, &authored, "banked_as").is_null(), |
| 21906 | "{}", |
| 21907 | res.body |
| 21908 | ); |
| 21909 | assert!( |
| 21910 | link_of(&res.body, &inserted, "from_bank").is_null(), |
| 21911 | "{}", |
| 21912 | res.body |
| 21913 | ); |
| 21914 | } |
| 21915 | |
| 21916 | /// The mirror: deleting the origin exam clears `source_exam` on the templates |
| 21917 | /// saved out of it — the template is a reusable library row and outlives the |
| 21918 | /// exam, but the bank page must not read a link to a dead exam. |
| 21919 | #[tokio::test] |
| 21920 | async fn deleting_an_exam_clears_the_templates_source_exam() { |
| 21921 | let (app, db) = app_and_db().await; |
| 21922 | let teacher = login_as(&app, &db, "edang_t", "teacher").await; |
| 21923 | let mudur = login_as(&app, &db, "edang_c_m", "manager").await; |
| 21924 | scheduling_kinds(&app, &mudur).await; |
| 21925 | let t = taught_under(&app, &mudur, &teacher, "edang_c").await; |
| 21926 | let subject = create_subject(&app, &teacher, &t.course, "edang_s").await; |
| 21927 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "final").await; |
| 21928 | let qid = create_question( |
| 21929 | &app, |
| 21930 | &teacher, |
| 21931 | &exam, |
| 21932 | &subject, |
| 21933 | json!({ "text": "plain", "kind": "text", "points": 5 }), |
| 21934 | ) |
| 21935 | .await; |
| 21936 | |
| 21937 | let res = send( |
| 21938 | &app, |
| 21939 | "POST", |
| 21940 | &format!("/exams/{exam}/questions/{qid}/to-bank"), |
| 21941 | Some(&teacher), |
| 21942 | None, |
| 21943 | ) |
| 21944 | .await; |
| 21945 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 21946 | let bid = id_of(&res.body); |
| 21947 | assert_eq!(res.body["source_exam"], exam); |
| 21948 | |
| 21949 | let res = send( |
| 21950 | &app, |
| 21951 | "DELETE", |
| 21952 | &format!("/exams/{exam}"), |
| 21953 | Some(&teacher), |
| 21954 | None, |
| 21955 | ) |
| 21956 | .await; |
| 21957 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 21958 | |
| 21959 | let res = send( |
| 21960 | &app, |
| 21961 | "GET", |
| 21962 | &format!("/bank-questions/{bid}"), |
| 21963 | Some(&teacher), |
| 21964 | None, |
| 21965 | ) |
| 21966 | .await; |
| 21967 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 21968 | assert!(res.body["source_exam"].is_null(), "{}", res.body); |
| 21969 | } |
| 21970 | |
| 21971 | /// `used_count` on the bank list: how many exam questions were copied out of |
| 21972 | /// each template. It is the divergence surface made visible — every one of |
| 21973 | /// those copies is detached, so an edit here never reaches them. Joined once |
| 21974 | /// for the whole page (one grouped query), list-only exactly like |
| 21975 | /// `subject_name`/`owner_name`. |
| 21976 | #[tokio::test] |
| 21977 | async fn bank_list_counts_the_copies_made_from_each_template() { |
| 21978 | let (app, db) = app_and_db().await; |
| 21979 | let teacher = login_as(&app, &db, "buse_t", "teacher").await; |
| 21980 | let mudur = login_as(&app, &db, "buse_c_m", "manager").await; |
| 21981 | scheduling_kinds(&app, &mudur).await; |
| 21982 | let t = taught_under(&app, &mudur, &teacher, "buse_c").await; |
| 21983 | let subject = create_subject(&app, &teacher, &t.course, "buse_s").await; |
| 21984 | select_instance_subject(&app, &teacher, &t.instance, &subject).await; |
| 21985 | |
| 21986 | let template = |text: &'static str| { |
| 21987 | send( |
| 21988 | &app, |
| 21989 | "POST", |
| 21990 | "/bank-questions", |
| 21991 | Some(&teacher), |
| 21992 | Some(json!({ "subject_id": subject, "text": text, "kind": "text", "points": 4 })), |
| 21993 | ) |
| 21994 | }; |
| 21995 | let used = id_of(&template("reused").await.body); |
| 21996 | let unused = id_of(&template("never used").await.body); |
| 21997 | |
| 21998 | // Two exams, three copies: twice out of `used` in one exam, once in the other. |
| 21999 | let mut exams = Vec::new(); |
| 22000 | for title in ["one", "two"] { |
| 22001 | exams.push(create_exam(&app, &teacher, &t.instance, &t.term, title, "final").await); |
| 22002 | } |
| 22003 | for (exam, times) in [(&exams[0], 2), (&exams[1], 1)] { |
| 22004 | for _ in 0..times { |
| 22005 | let res = send( |
| 22006 | &app, |
| 22007 | "POST", |
| 22008 | &format!("/exams/{exam}/questions/from-bank/{used}"), |
| 22009 | Some(&teacher), |
| 22010 | Some(json!({ "subject_id": subject })), |
| 22011 | ) |
| 22012 | .await; |
| 22013 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 22014 | } |
| 22015 | } |
| 22016 | // A hand-authored question in the same exam has no template and must not |
| 22017 | // be tallied against one. |
| 22018 | create_question( |
| 22019 | &app, |
| 22020 | &teacher, |
| 22021 | &exams[0], |
| 22022 | &subject, |
| 22023 | json!({ "text": "mine alone", "kind": "text", "points": 1 }), |
| 22024 | ) |
| 22025 | .await; |
| 22026 | |
| 22027 | let res = send( |
| 22028 | &app, |
| 22029 | "GET", |
| 22030 | "/bank-questions?limit=100", |
| 22031 | Some(&teacher), |
| 22032 | None, |
| 22033 | ) |
| 22034 | .await; |
| 22035 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 22036 | let counts: std::collections::HashMap<String, i64> = common::items(&res.body) |
| 22037 | .iter() |
| 22038 | .map(|item| (id_of(item), item["used_count"].as_i64().unwrap())) |
| 22039 | .collect(); |
| 22040 | assert_eq!(counts.get(&used).copied(), Some(3), "{}", res.body); |
| 22041 | assert_eq!(counts.get(&unused).copied(), Some(0), "{}", res.body); |
| 22042 | |
| 22043 | // Deleting a copy takes it back off the tally (its `from_bank` goes with it). |
| 22044 | let res = send( |
| 22045 | &app, |
| 22046 | "GET", |
| 22047 | &format!("/exams/{}/questions", exams[1]), |
| 22048 | Some(&teacher), |
| 22049 | None, |
| 22050 | ) |
| 22051 | .await; |
| 22052 | let qid = id_of(&common::items(&res.body)[0]); |
| 22053 | let res = send( |
| 22054 | &app, |
| 22055 | "DELETE", |
| 22056 | &format!("/exams/{}/questions/{qid}", exams[1]), |
| 22057 | Some(&teacher), |
| 22058 | None, |
| 22059 | ) |
| 22060 | .await; |
| 22061 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 22062 | let res = send( |
| 22063 | &app, |
| 22064 | "GET", |
| 22065 | "/bank-questions?limit=100", |
| 22066 | Some(&teacher), |
| 22067 | None, |
| 22068 | ) |
| 22069 | .await; |
| 22070 | let after = common::items(&res.body) |
| 22071 | .iter() |
| 22072 | .find(|item| id_of(item) == used) |
| 22073 | .cloned() |
| 22074 | .unwrap(); |
| 22075 | assert_eq!(after["used_count"], 2, "{}", res.body); |
| 22076 | |
| 22077 | // List-only, like the other joined fields: the single-template GET says 0. |
| 22078 | let res = send( |
| 22079 | &app, |
| 22080 | "GET", |
| 22081 | &format!("/bank-questions/{used}"), |
| 22082 | Some(&teacher), |
| 22083 | None, |
| 22084 | ) |
| 22085 | .await; |
| 22086 | assert_eq!(res.body["used_count"], 0, "{}", res.body); |
| 22087 | } |
| 22088 | |
| 22089 | /// The escape hatch out of the divergence trap: re-copy a template's *current* |
| 22090 | /// content over the exam question that was instantiated from it. |
| 22091 | /// |
| 22092 | /// Choice ids come from the template — the same funnel the original insert |
| 22093 | /// used — so pictures land back on the right options and a stale option's |
| 22094 | /// picture goes with it. A student's recorded `selected` can never be stranded |
| 22095 | /// by that: the route dies on `ensure_questions_editable` (409) the moment any |
| 22096 | /// attempt exists, and answers only exist under attempts. |
| 22097 | #[tokio::test] |
| 22098 | async fn refreshing_a_question_recopies_its_template() { |
| 22099 | let (app, db) = app_and_db().await; |
| 22100 | let teacher = login_as(&app, &db, "bref_t", "teacher").await; |
| 22101 | let manager = login_as(&app, &db, "bref_m", "manager").await; |
| 22102 | let mudur = login_as(&app, &db, "bref_c_m", "manager").await; |
| 22103 | scheduling_kinds(&app, &mudur).await; |
| 22104 | let t = taught_under(&app, &mudur, &teacher, "bref_c").await; |
| 22105 | let subject = create_subject(&app, &teacher, &t.course, "bref_s").await; |
| 22106 | select_instance_subject(&app, &teacher, &t.instance, &subject).await; |
| 22107 | |
| 22108 | // A template with an illustration and a picture on its first option. |
| 22109 | let res = send( |
| 22110 | &app, |
| 22111 | "POST", |
| 22112 | "/bank-questions", |
| 22113 | Some(&teacher), |
| 22114 | Some(json!({ "subject_id": subject, "text": "capitol of France?", "kind": "choice", |
| 22115 | "points": 5, "choices": [{"id": "a", "text": "Paris"}, {"id": "b", "text": "Lyon"}], |
| 22116 | "correct": "a" })), |
| 22117 | ) |
| 22118 | .await; |
| 22119 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 22120 | let bid = id_of(&res.body); |
| 22121 | let keep_choice = choice_of(&res.body, 0); |
| 22122 | let drop_choice = choice_of(&res.body, 1); |
| 22123 | let (status, _) = post_image( |
| 22124 | &app, |
| 22125 | &teacher, |
| 22126 | &format!("/bank-questions/{bid}/image"), |
| 22127 | "image/png", |
| 22128 | b"old-illustration", |
| 22129 | ) |
| 22130 | .await; |
| 22131 | assert_eq!(status, StatusCode::CREATED); |
| 22132 | let (status, _) = post_image( |
| 22133 | &app, |
| 22134 | &teacher, |
| 22135 | &format!("/bank-questions/{bid}/choices/{drop_choice}/image"), |
| 22136 | "image/png", |
| 22137 | b"lyon-picture", |
| 22138 | ) |
| 22139 | .await; |
| 22140 | assert_eq!(status, StatusCode::CREATED); |
| 22141 | |
| 22142 | let exam = create_exam(&app, &teacher, &t.instance, &t.term, "midterm", "final").await; |
| 22143 | let res = send( |
| 22144 | &app, |
| 22145 | "POST", |
| 22146 | &format!("/exams/{exam}/questions/from-bank/{bid}"), |
| 22147 | Some(&teacher), |
| 22148 | Some(json!({ "subject_id": subject })), |
| 22149 | ) |
| 22150 | .await; |
| 22151 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 22152 | let qid = id_of(&res.body); |
| 22153 | |
| 22154 | // The exam copy drifts (a local edit), and the template is fixed and |
| 22155 | // reshaped: the typo goes, "Lyon" is replaced by a new option (a new id), |
| 22156 | // points change, and the illustration is replaced. |
| 22157 | let res = send( |
| 22158 | &app, |
| 22159 | "PATCH", |
| 22160 | &format!("/exams/{exam}/questions/{qid}"), |
| 22161 | Some(&teacher), |
| 22162 | Some(json!({ "text": "local edit that will be lost", "points": 99 })), |
| 22163 | ) |
| 22164 | .await; |
| 22165 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 22166 | let res = send( |
| 22167 | &app, |
| 22168 | "PATCH", |
| 22169 | &format!("/bank-questions/{bid}"), |
| 22170 | Some(&teacher), |
| 22171 | Some(json!({ "text": "capital of France?", "points": 7, |
| 22172 | "choices": [{"id": keep_choice, "text": "Paris"}, {"id": "new", "text": "Marseille"}], |
| 22173 | "correct": keep_choice })), |
| 22174 | ) |
| 22175 | .await; |
| 22176 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 22177 | let fresh_choice = choice_of(&res.body, 1); |
| 22178 | assert_ne!(fresh_choice, drop_choice, "the replaced option is a new id"); |
| 22179 | let (status, _) = post_image( |
| 22180 | &app, |
| 22181 | &teacher, |
| 22182 | &format!("/bank-questions/{bid}/image"), |
| 22183 | "image/png", |
| 22184 | b"new-illustration", |
| 22185 | ) |
| 22186 | .await; |
| 22187 | assert_eq!(status, StatusCode::CREATED); |
| 22188 | |
| 22189 | // A template the caller cannot see is a 404 on this route too — never a |
| 22190 | // 403, which would confirm it exists. (A manager may manage the course but |
| 22191 | // is not the template's owner, and the template is private.) |
| 22192 | let res = send( |
| 22193 | &app, |
| 22194 | "POST", |
| 22195 | &format!("/exams/{exam}/questions/{qid}/refresh-from-bank"), |
| 22196 | Some(&manager), |
| 22197 | None, |
| 22198 | ) |
| 22199 | .await; |
| 22200 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 22201 | |
| 22202 | // The refresh itself: content, points, choices (ids and all), and correct |
| 22203 | // come back from the template; the local edit is gone. |
| 22204 | let res = send( |
| 22205 | &app, |
| 22206 | "POST", |
| 22207 | &format!("/exams/{exam}/questions/{qid}/refresh-from-bank"), |
| 22208 | Some(&teacher), |
| 22209 | None, |
| 22210 | ) |
| 22211 | .await; |
| 22212 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 22213 | assert_eq!(res.body["id"], qid, "the question keeps its id"); |
| 22214 | assert_eq!(res.body["text"], "capital of France?"); |
| 22215 | assert_eq!(res.body["points"], 7); |
| 22216 | assert_eq!(res.body["subject"], subject, "the exam-side subject stays"); |
| 22217 | assert_eq!(res.body["from_bank"], bid, "provenance survives"); |
| 22218 | assert_eq!( |
| 22219 | choice_of(&res.body, 0), |
| 22220 | keep_choice, |
| 22221 | "template choice ids adopted" |
| 22222 | ); |
| 22223 | assert_eq!(choice_of(&res.body, 1), fresh_choice); |
| 22224 | assert_eq!(res.body["choices"][1]["text"], "Marseille"); |
| 22225 | assert_eq!(res.body["correct"], keep_choice); |
| 22226 | // Pictures match the template: the new illustration landed, and the |
| 22227 | // dropped option's picture is gone rather than orphaned on a stale slot. |
| 22228 | assert_eq!( |
| 22229 | res.body["image"]["content_type"], "image/png", |
| 22230 | "{}", |
| 22231 | res.body |
| 22232 | ); |
| 22233 | assert!(res.body["choice_images"][0].is_null(), "{}", res.body); |
| 22234 | assert!(res.body["choice_images"][1].is_null(), "{}", res.body); |
| 22235 | let (status, _, bytes) = common::send_raw( |
| 22236 | &app, |
| 22237 | "GET", |
| 22238 | &format!("/exams/{exam}/questions/{qid}/image"), |
| 22239 | Some(&teacher), |
| 22240 | None, |
| 22241 | Vec::new(), |
| 22242 | ) |
| 22243 | .await; |
| 22244 | assert_eq!(status, StatusCode::OK); |
| 22245 | assert_eq!( |
| 22246 | bytes, b"new-illustration", |
| 22247 | "the blob was re-copied, not kept" |
| 22248 | ); |
| 22249 | // No orphan blob rows left behind by the dropped option. |
| 22250 | assert_eq!(image_blob_keys(&db).await.len(), 1); |
| 22251 | |
| 22252 | // A hand-authored question has nothing to refresh from — 400, not a 404 |
| 22253 | // that would read as "your exam is gone". |
| 22254 | let plain = create_question( |
| 22255 | &app, |
| 22256 | &teacher, |
| 22257 | &exam, |
| 22258 | &subject, |
| 22259 | json!({ "text": "mine alone", "kind": "text", "points": 1 }), |
| 22260 | ) |
| 22261 | .await; |
| 22262 | let res = send( |
| 22263 | &app, |
| 22264 | "POST", |
| 22265 | &format!("/exams/{exam}/questions/{plain}/refresh-from-bank"), |
| 22266 | Some(&teacher), |
| 22267 | None, |
| 22268 | ) |
| 22269 | .await; |
| 22270 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 22271 | |
| 22272 | // Once a student sits an exam, its questions freeze — the refresh answers |
| 22273 | // to the same guard as every other question mutation. |
| 22274 | let now = Timestamp::now().as_millis(); |
| 22275 | let live = scheduled_exam( |
| 22276 | &app, |
| 22277 | &teacher, |
| 22278 | &t.instance, |
| 22279 | json!({ "term": &t.term, "title": "live", "kind": "final", "mode": "sync", |
| 22280 | "starts_at": now - 1_000, "ends_at": now + 600_000 }), |
| 22281 | ) |
| 22282 | .await; |
| 22283 | let res = send( |
| 22284 | &app, |
| 22285 | "POST", |
| 22286 | &format!("/exams/{live}/questions/from-bank/{bid}"), |
| 22287 | Some(&teacher), |
| 22288 | Some(json!({ "subject_id": subject })), |
| 22289 | ) |
| 22290 | .await; |
| 22291 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 22292 | let live_qid = id_of(&res.body); |
| 22293 | let student = login(&app, "bref_s").await; |
| 22294 | let student_id = me_id(&app, &student).await; |
| 22295 | enroll(&app, &teacher, &t.instance, &student_id).await; |
| 22296 | let res = send( |
| 22297 | &app, |
| 22298 | "POST", |
| 22299 | &format!("/exams/{live}/attempt"), |
| 22300 | Some(&student), |
| 22301 | None, |
| 22302 | ) |
| 22303 | .await; |
| 22304 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 22305 | let res = send( |
| 22306 | &app, |
| 22307 | "POST", |
| 22308 | &format!("/exams/{live}/questions/{live_qid}/refresh-from-bank"), |
| 22309 | Some(&teacher), |
| 22310 | None, |
| 22311 | ) |
| 22312 | .await; |
| 22313 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 22314 | |
| 22315 | // Deleting the template clears `from_bank`, so the copy has nothing left to |
| 22316 | // refresh from — the action stops existing rather than half-working. |
| 22317 | let res = send( |
| 22318 | &app, |
| 22319 | "DELETE", |
| 22320 | &format!("/bank-questions/{bid}"), |
| 22321 | Some(&teacher), |
| 22322 | None, |
| 22323 | ) |
| 22324 | .await; |
| 22325 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 22326 | let res = send( |
| 22327 | &app, |
| 22328 | "GET", |
| 22329 | &format!("/exams/{exam}/questions"), |
| 22330 | Some(&teacher), |
| 22331 | None, |
| 22332 | ) |
| 22333 | .await; |
| 22334 | let refreshed = common::items(&res.body) |
| 22335 | .iter() |
| 22336 | .find(|item| id_of(item) == qid) |
| 22337 | .cloned() |
| 22338 | .unwrap(); |
| 22339 | assert!(refreshed["from_bank"].is_null(), "{}", res.body); |
| 22340 | let res = send( |
| 22341 | &app, |
| 22342 | "POST", |
| 22343 | &format!("/exams/{exam}/questions/{qid}/refresh-from-bank"), |
| 22344 | Some(&teacher), |
| 22345 | None, |
| 22346 | ) |
| 22347 | .await; |
| 22348 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 22349 | } |
| 22350 | |
| 22351 | /// A course PATCH is a field-scoped write: the handler reads the course, then |
| 22352 | /// saves only the fields the request actually carried, holding nothing over |
| 22353 | /// the row — so a second PATCH of another field can land in that window. A |
| 22354 | /// whole-row save from the stale struct would silently revert it. |
| 22355 | /// Driven at the domain level: HTTP offers no way to interleave inside the |
| 22356 | /// handler. |
| 22357 | #[tokio::test] |
| 22358 | async fn a_course_patch_does_not_clobber_a_concurrent_edit() { |
| 22359 | use hezarfen_backend::db::course; |
| 22360 | use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseTitle}; |
| 22361 | |
| 22362 | let (app, db) = app_and_db().await; |
| 22363 | let owner = login_as(&app, &db, "cclob_o", "teacher").await; |
| 22364 | let boss = login_as(&app, &db, "cclob_m", "manager").await; |
| 22365 | let course = create_course(&app, &owner, "cclob_c").await; |
| 22366 | |
| 22367 | // The handler's read, then the other field's PATCH lands mid-window. |
| 22368 | let stale = course::read(&db, &CourseId::from_key(&course)) |
| 22369 | .await |
| 22370 | .unwrap() |
| 22371 | .expect("course exists"); |
| 22372 | let res = send( |
| 22373 | &app, |
| 22374 | "PATCH", |
| 22375 | &format!("/courses/{course}"), |
| 22376 | Some(&boss), |
| 22377 | Some(json!({ "kind": "study" })), |
| 22378 | ) |
| 22379 | .await; |
| 22380 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 22381 | |
| 22382 | let updated = course::update( |
| 22383 | &db, |
| 22384 | stale, |
| 22385 | Some(CourseTitle::try_new("renamed").unwrap()), |
| 22386 | Some(CourseDescription::try_new("").unwrap()), |
| 22387 | None, |
| 22388 | ) |
| 22389 | .await |
| 22390 | .expect("update written"); |
| 22391 | assert_eq!( |
| 22392 | updated.get_kind().as_str(), |
| 22393 | "study", |
| 22394 | "the concurrent kind change was reverted" |
| 22395 | ); |
| 22396 | |
| 22397 | // The rename landed and the kind change stayed. |
| 22398 | let res = send( |
| 22399 | &app, |
| 22400 | "GET", |
| 22401 | &format!("/courses/{course}"), |
| 22402 | Some(&owner), |
| 22403 | None, |
| 22404 | ) |
| 22405 | .await; |
| 22406 | assert_eq!(res.body["title"], "renamed"); |
| 22407 | assert_eq!(res.body["kind"], "study"); |
| 22408 | } |
| 22409 | |
| 22410 | /// The mirror image: staffing writes only the junction row. `assign_teacher` |
| 22411 | /// reads the actor and the target user before writing, so an instance PATCH can |
| 22412 | /// land in between — and a whole-row save would revert it. `unassign_teacher` |
| 22413 | /// gets the same field-scoped treatment. |
| 22414 | #[tokio::test] |
| 22415 | async fn staffing_an_instance_does_not_clobber_a_concurrent_edit() { |
| 22416 | use hezarfen_backend::domain::class_course::ClassCourseId; |
| 22417 | use hezarfen_backend::service::class_course; |
| 22418 | |
| 22419 | let (app, db) = app_and_db().await; |
| 22420 | let owner = login_as(&app, &db, "cstaff_o", "teacher").await; |
| 22421 | let helper = login_as(&app, &db, "cstaff_h", "teacher").await; |
| 22422 | let boss = login_as(&app, &db, "cstaff_m", "manager").await; |
| 22423 | let helper_id = me_id(&app, &helper).await; |
| 22424 | let boss_id = me_id(&app, &boss).await; |
| 22425 | let t = taught_under(&app, &boss, &owner, "cstaff_c").await; |
| 22426 | |
| 22427 | // The staffing's read, then the policy write lands mid-window. |
| 22428 | let stale = class_course::read(&db, &ClassCourseId::from_key(&t.instance)) |
| 22429 | .await |
| 22430 | .unwrap() |
| 22431 | .expect("instance exists"); |
| 22432 | let res = send( |
| 22433 | &app, |
| 22434 | "PATCH", |
| 22435 | &format!("/instances/{}", t.instance), |
| 22436 | Some(&owner), |
| 22437 | Some(json!({ "ders_saati": 9 })), |
| 22438 | ) |
| 22439 | .await; |
| 22440 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 22441 | |
| 22442 | class_course::assign_teacher( |
| 22443 | &db, |
| 22444 | stale.get_id(), |
| 22445 | &UserId::from_key(&helper_id), |
| 22446 | &UserId::from_key(&boss_id), |
| 22447 | ) |
| 22448 | .await |
| 22449 | .expect("assignment written"); |
| 22450 | |
| 22451 | // The policy write survives and the teacher is assigned. |
| 22452 | let res = send( |
| 22453 | &app, |
| 22454 | "GET", |
| 22455 | &format!("/instances/{}", t.instance), |
| 22456 | Some(&owner), |
| 22457 | None, |
| 22458 | ) |
| 22459 | .await; |
| 22460 | assert_eq!(res.body["ders_saati"], 9); |
| 22461 | assert_eq!(res.body["teachers"][0]["username"], "cstaff_h"); |
| 22462 | |
| 22463 | // Unassigning from a read taken before another policy write is just as safe. |
| 22464 | let stale = class_course::read(&db, &ClassCourseId::from_key(&t.instance)) |
| 22465 | .await |
| 22466 | .unwrap() |
| 22467 | .expect("instance exists"); |
| 22468 | let res = send( |
| 22469 | &app, |
| 22470 | "PATCH", |
| 22471 | &format!("/instances/{}", t.instance), |
| 22472 | Some(&owner), |
| 22473 | Some(json!({ "counts_toward_karne": false })), |
| 22474 | ) |
| 22475 | .await; |
| 22476 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 22477 | let removed = |
| 22478 | class_course::unassign_teacher(&db, stale.get_id(), &UserId::from_key(&helper_id)) |
| 22479 | .await |
| 22480 | .expect("unassignment written"); |
| 22481 | assert!(removed, "the teacher was assigned"); |
| 22482 | |
| 22483 | let res = send( |
| 22484 | &app, |
| 22485 | "GET", |
| 22486 | &format!("/instances/{}", t.instance), |
| 22487 | Some(&owner), |
| 22488 | None, |
| 22489 | ) |
| 22490 | .await; |
| 22491 | assert_eq!(res.body["counts_toward_karne"], false); |
| 22492 | assert_eq!(res.body["teachers"].as_array().unwrap().len(), 0); |
| 22493 | } |
| 22494 | |
| 22495 | // --- schedule-window list filters ---------------------------------------- |
| 22496 | |
| 22497 | /// Titles of a list envelope, in response order. |
| 22498 | fn titles(body: &serde_json::Value) -> Vec<String> { |
| 22499 | common::items(body) |
| 22500 | .iter() |
| 22501 | .map(|item| item["title"].as_str().unwrap().to_string()) |
| 22502 | .collect() |
| 22503 | } |
| 22504 | |
| 22505 | #[tokio::test] |
| 22506 | async fn events_schedule_window_filters_and_orders() { |
| 22507 | let (app, db) = app_and_db().await; |
| 22508 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 22509 | let now = Timestamp::now().as_millis(); |
| 22510 | |
| 22511 | // Four events, created oldest-id first: one with no schedule at all, one |
| 22512 | // already running (inside the 60s backdating grace), one starting later |
| 22513 | // with no end, and one that only carries an end. |
| 22514 | for body in [ |
| 22515 | json!({ "title": "no-schedule", "description": "" }), |
| 22516 | json!({ "title": "running", "starts_at": now - 30_000, "ends_at": now + 600_000 }), |
| 22517 | json!({ "title": "later", "starts_at": now + 900_000 }), |
| 22518 | json!({ "title": "ending", "ends_at": now + 300_000 }), |
| 22519 | ] { |
| 22520 | let res = send(&app, "POST", "/events", Some(&ali), Some(body)).await; |
| 22521 | assert_eq!(res.status, StatusCode::CREATED); |
| 22522 | } |
| 22523 | |
| 22524 | // No window params: unchanged behaviour — every row, newest-created first. |
| 22525 | let all = send(&app, "GET", "/events", Some(&ali), None).await; |
| 22526 | assert_eq!(common::total(&all.body), 4); |
| 22527 | assert_eq!( |
| 22528 | titles(&all.body), |
| 22529 | ["ending", "later", "running", "no-schedule"] |
| 22530 | ); |
| 22531 | |
| 22532 | // ends_after: keeps unfinished rows (running on ends_at, later on the |
| 22533 | // starts_at fallback), drops the schedule-less one, ascending by schedule. |
| 22534 | let res = send( |
| 22535 | &app, |
| 22536 | "GET", |
| 22537 | &format!("/events?ends_after={now}"), |
| 22538 | Some(&ali), |
| 22539 | None, |
| 22540 | ) |
| 22541 | .await; |
| 22542 | assert_eq!(common::total(&res.body), 3); |
| 22543 | assert_eq!(titles(&res.body), ["running", "ending", "later"]); |
| 22544 | |
| 22545 | // Past the running event's end: only the pure-end row and the fallback row. |
| 22546 | let res = send( |
| 22547 | &app, |
| 22548 | "GET", |
| 22549 | &format!("/events?ends_after={}", now + 700_000), |
| 22550 | Some(&ali), |
| 22551 | None, |
| 22552 | ) |
| 22553 | .await; |
| 22554 | assert_eq!(titles(&res.body), ["later"]); |
| 22555 | |
| 22556 | // starts_after excludes the already-started row and every start-less row. |
| 22557 | let res = send( |
| 22558 | &app, |
| 22559 | "GET", |
| 22560 | &format!("/events?starts_after={now}"), |
| 22561 | Some(&ali), |
| 22562 | None, |
| 22563 | ) |
| 22564 | .await; |
| 22565 | assert_eq!(common::total(&res.body), 1); |
| 22566 | assert_eq!(titles(&res.body), ["later"]); |
| 22567 | |
| 22568 | // total is the filtered, pre-pagination count; the page is the soonest. |
| 22569 | let res = send( |
| 22570 | &app, |
| 22571 | "GET", |
| 22572 | &format!("/events?ends_after={now}&limit=1"), |
| 22573 | Some(&ali), |
| 22574 | None, |
| 22575 | ) |
| 22576 | .await; |
| 22577 | assert_eq!(common::total(&res.body), 3); |
| 22578 | assert_eq!(titles(&res.body), ["running"]); |
| 22579 | |
| 22580 | // Invalid values are a 400 naming the field. |
| 22581 | for query in ["starts_after=-1", "ends_after=-1", "ends_after=soon"] { |
| 22582 | let res = send(&app, "GET", &format!("/events?{query}"), Some(&ali), None).await; |
| 22583 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{query}"); |
| 22584 | } |
| 22585 | } |
| 22586 | |
| 22587 | #[tokio::test] |
| 22588 | async fn exams_schedule_window_applies_after_visibility_and_drafts() { |
| 22589 | let (app, db) = app_and_db().await; |
| 22590 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 22591 | let ayse = login_as(&app, &db, "ayse", "student").await; |
| 22592 | let now = Timestamp::now().as_millis(); |
| 22593 | |
| 22594 | let mudur = login_as(&app, &db, "win_m", "manager").await; |
| 22595 | let math = taught_under(&app, &mudur, &ali, "math").await; |
| 22596 | let other = taught_under(&app, &mudur, &ali, "hidden").await; |
| 22597 | // The student's visibility is their şube: being on the section's roster is |
| 22598 | // what puts them in the instance it teaches. |
| 22599 | let ayse_id = me_id(&app, &ayse).await; |
| 22600 | add_member(&app, &mudur, &math.class, &ayse_id).await; |
| 22601 | |
| 22602 | // Windowed exams in the student's instance, plus a draft, an open-mode exam |
| 22603 | // (no window at all), and one in an instance they cannot see. |
| 22604 | for (instance, body) in [ |
| 22605 | ( |
| 22606 | &math.instance, |
| 22607 | json!({ "term": &math.term, "title": "soon", "kind": "yazili", |
| 22608 | "mode": "sync", |
| 22609 | "starts_at": now + 600_000, "ends_at": now + 900_000 }), |
| 22610 | ), |
| 22611 | ( |
| 22612 | &math.instance, |
| 22613 | json!({ "term": &math.term, "title": "late", "kind": "yazili", |
| 22614 | "mode": "sync", |
| 22615 | "starts_at": now + 1_800_000, "ends_at": now + 2_400_000 }), |
| 22616 | ), |
| 22617 | ( |
| 22618 | &math.instance, |
| 22619 | json!({ "term": &math.term, "title": "draft", "kind": "yazili", |
| 22620 | "mode": "sync", "draft": true, |
| 22621 | "starts_at": now + 60_000, "ends_at": now + 120_000 }), |
| 22622 | ), |
| 22623 | ( |
| 22624 | &math.instance, |
| 22625 | json!({ "term": &math.term, "title": "open", "kind": "yazili", |
| 22626 | "mode": "open" }), |
| 22627 | ), |
| 22628 | ( |
| 22629 | &other.instance, |
| 22630 | json!({ "term": &other.term, "title": "unseen", "kind": "yazili", |
| 22631 | "mode": "sync", |
| 22632 | "starts_at": now + 90_000, "ends_at": now + 150_000 }), |
| 22633 | ), |
| 22634 | ] { |
| 22635 | let res = create_exam_with(&app, &ali, instance, body).await; |
| 22636 | assert_eq!(res.status, StatusCode::CREATED, "{:?}", res.body); |
| 22637 | } |
| 22638 | |
| 22639 | // Unfiltered: the student sees their course's non-draft exams only. |
| 22640 | let all = send(&app, "GET", "/exams", Some(&ayse), None).await; |
| 22641 | assert_eq!(common::total(&all.body), 3); |
| 22642 | assert_eq!(titles(&all.body), ["open", "late", "soon"]); |
| 22643 | |
| 22644 | // Windowed: the draft and the other course stay invisible (the window runs |
| 22645 | // after visibility), the window-less open exam drops out, soonest first. |
| 22646 | let res = send( |
| 22647 | &app, |
| 22648 | "GET", |
| 22649 | &format!("/exams?ends_after={now}"), |
| 22650 | Some(&ayse), |
| 22651 | None, |
| 22652 | ) |
| 22653 | .await; |
| 22654 | assert_eq!(common::total(&res.body), 2); |
| 22655 | assert_eq!(titles(&res.body), ["soon", "late"]); |
| 22656 | |
| 22657 | // The teacher's own draft is windowed like any other exam of theirs. |
| 22658 | let res = send( |
| 22659 | &app, |
| 22660 | "GET", |
| 22661 | &format!("/exams?starts_after={now}&limit=2"), |
| 22662 | Some(&ali), |
| 22663 | None, |
| 22664 | ) |
| 22665 | .await; |
| 22666 | assert_eq!(common::total(&res.body), 4); |
| 22667 | assert_eq!(titles(&res.body), ["draft", "unseen"]); |
| 22668 | |
| 22669 | let res = send(&app, "GET", "/exams?starts_after=-1", Some(&ayse), None).await; |
| 22670 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 22671 | } |
| 22672 | |
| 22673 | // --- meals: menus and dishes --------------------------------------------- |
| 22674 | |
| 22675 | /// The whole published side, end to end: publish, list, patch the cap, add and |
| 22676 | /// edit and drop a dish, and the unique day+slot rule. |
| 22677 | #[tokio::test] |
| 22678 | async fn menus_and_dishes_round_trip() { |
| 22679 | let (app, db) = app_and_db().await; |
| 22680 | let mgr = login_as(&app, &db, "meal_mgr", "manager").await; |
| 22681 | |
| 22682 | let res = send( |
| 22683 | &app, |
| 22684 | "POST", |
| 22685 | "/meals/menus", |
| 22686 | Some(&mgr), |
| 22687 | Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 120 })), |
| 22688 | ) |
| 22689 | .await; |
| 22690 | assert_eq!(res.status, StatusCode::CREATED); |
| 22691 | let menu = id_of(&res.body); |
| 22692 | assert_eq!(res.body["slot"], "lunch"); |
| 22693 | assert_eq!(res.body["capacity"], 120); |
| 22694 | assert_eq!(res.body["created_by"]["username"], "meal_mgr"); |
| 22695 | |
| 22696 | // A second menu for the same day and slot is the UNIQUE rule, as a 409 — |
| 22697 | // never a 500 out of the index. |
| 22698 | let res = send( |
| 22699 | &app, |
| 22700 | "POST", |
| 22701 | "/meals/menus", |
| 22702 | Some(&mgr), |
| 22703 | Some(json!({ "date": "2099-09-14", "slot": "lunch" })), |
| 22704 | ) |
| 22705 | .await; |
| 22706 | assert_eq!(res.status, StatusCode::CONFLICT); |
| 22707 | |
| 22708 | // Same day, another slot is a different meal and lands fine. |
| 22709 | let res = send( |
| 22710 | &app, |
| 22711 | "POST", |
| 22712 | "/meals/menus", |
| 22713 | Some(&mgr), |
| 22714 | Some(json!({ "date": "2099-09-14", "slot": "breakfast" })), |
| 22715 | ) |
| 22716 | .await; |
| 22717 | assert_eq!(res.status, StatusCode::CREATED); |
| 22718 | |
| 22719 | // Dishes: money is minor units, tags come from the school's list. |
| 22720 | let res = send( |
| 22721 | &app, |
| 22722 | "POST", |
| 22723 | &format!("/meals/menus/{menu}/dishes"), |
| 22724 | Some(&mgr), |
| 22725 | Some(json!({ |
| 22726 | "name": "Mercimek çorbası", |
| 22727 | "description": " ", |
| 22728 | "price_minor": 4550, |
| 22729 | "tags": ["vegetarian", "vegetarian"], |
| 22730 | })), |
| 22731 | ) |
| 22732 | .await; |
| 22733 | assert_eq!(res.status, StatusCode::CREATED); |
| 22734 | let dish = id_of(&res.body); |
| 22735 | assert_eq!(res.body["price_minor"], 4550); |
| 22736 | // A whitespace-only description is the absence of one, and repeated tags |
| 22737 | // collapse. |
| 22738 | assert_eq!(res.body["description"], json!(null)); |
| 22739 | assert_eq!(res.body["tags"], json!(["vegetarian"])); |
| 22740 | |
| 22741 | let res = send( |
| 22742 | &app, |
| 22743 | "PATCH", |
| 22744 | &format!("/meals/dishes/{dish}"), |
| 22745 | Some(&mgr), |
| 22746 | Some(json!({ "price_minor": 5000, "description": "günlük" })), |
| 22747 | ) |
| 22748 | .await; |
| 22749 | assert_eq!(res.status, StatusCode::OK); |
| 22750 | assert_eq!(res.body["price_minor"], 5000); |
| 22751 | assert_eq!(res.body["description"], "günlük"); |
| 22752 | assert_eq!(res.body["name"], "Mercimek çorbası"); |
| 22753 | |
| 22754 | // The menu read carries its dishes, and `null` clears the cap. |
| 22755 | let res = send( |
| 22756 | &app, |
| 22757 | "PATCH", |
| 22758 | &format!("/meals/menus/{menu}"), |
| 22759 | Some(&mgr), |
| 22760 | Some(json!({ "capacity": null })), |
| 22761 | ) |
| 22762 | .await; |
| 22763 | assert_eq!(res.status, StatusCode::OK); |
| 22764 | assert_eq!(res.body["capacity"], json!(null)); |
| 22765 | assert_eq!(res.body["dishes"].as_array().expect("dishes").len(), 1); |
| 22766 | |
| 22767 | // Any authenticated user reads; the range filter is inclusive. |
| 22768 | let student = login(&app, "meal_student").await; |
| 22769 | let res = send( |
| 22770 | &app, |
| 22771 | "GET", |
| 22772 | "/meals/menus?from=2099-09-14&to=2099-09-14", |
| 22773 | Some(&student), |
| 22774 | None, |
| 22775 | ) |
| 22776 | .await; |
| 22777 | assert_eq!(res.status, StatusCode::OK); |
| 22778 | assert_eq!(common::total(&res.body), 2); |
| 22779 | let res = send( |
| 22780 | &app, |
| 22781 | "GET", |
| 22782 | "/meals/menus?from=2099-09-15", |
| 22783 | Some(&student), |
| 22784 | None, |
| 22785 | ) |
| 22786 | .await; |
| 22787 | assert_eq!(common::total(&res.body), 0); |
| 22788 | |
| 22789 | let res = send( |
| 22790 | &app, |
| 22791 | "DELETE", |
| 22792 | &format!("/meals/dishes/{dish}"), |
| 22793 | Some(&mgr), |
| 22794 | None, |
| 22795 | ) |
| 22796 | .await; |
| 22797 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 22798 | let res = send( |
| 22799 | &app, |
| 22800 | "GET", |
| 22801 | &format!("/meals/menus/{menu}"), |
| 22802 | Some(&mgr), |
| 22803 | None, |
| 22804 | ) |
| 22805 | .await; |
| 22806 | assert_eq!(res.body["dishes"], json!([])); |
| 22807 | |
| 22808 | let res = send( |
| 22809 | &app, |
| 22810 | "DELETE", |
| 22811 | &format!("/meals/menus/{menu}"), |
| 22812 | Some(&mgr), |
| 22813 | None, |
| 22814 | ) |
| 22815 | .await; |
| 22816 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 22817 | let res = send( |
| 22818 | &app, |
| 22819 | "GET", |
| 22820 | &format!("/meals/menus/{menu}"), |
| 22821 | Some(&mgr), |
| 22822 | None, |
| 22823 | ) |
| 22824 | .await; |
| 22825 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 22826 | } |
| 22827 | |
| 22828 | /// Publishing is manager+, and both school-editable lists are enforced: a slot |
| 22829 | /// nobody serves and a tag nobody defined are 400s, not stored strings. |
| 22830 | #[tokio::test] |
| 22831 | async fn menu_writes_are_manager_only_and_validate_against_settings() { |
| 22832 | let (app, db) = app_and_db().await; |
| 22833 | let mgr = login_as(&app, &db, "meal_mgr2", "manager").await; |
| 22834 | let teacher = login_as(&app, &db, "meal_teacher", "teacher").await; |
| 22835 | |
| 22836 | let body = json!({ "date": "2099-09-15", "slot": "lunch" }); |
| 22837 | let res = send( |
| 22838 | &app, |
| 22839 | "POST", |
| 22840 | "/meals/menus", |
| 22841 | Some(&teacher), |
| 22842 | Some(body.clone()), |
| 22843 | ) |
| 22844 | .await; |
| 22845 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 22846 | |
| 22847 | // A slot outside the school's `meal_slots` never reaches the column. |
| 22848 | let res = send( |
| 22849 | &app, |
| 22850 | "POST", |
| 22851 | "/meals/menus", |
| 22852 | Some(&mgr), |
| 22853 | Some(json!({ "date": "2099-09-15", "slot": "brunch" })), |
| 22854 | ) |
| 22855 | .await; |
| 22856 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 22857 | |
| 22858 | // Neither does a malformed day. |
| 22859 | let res = send( |
| 22860 | &app, |
| 22861 | "POST", |
| 22862 | "/meals/menus", |
| 22863 | Some(&mgr), |
| 22864 | Some(json!({ "date": "2026-9-15", "slot": "lunch" })), |
| 22865 | ) |
| 22866 | .await; |
| 22867 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 22868 | |
| 22869 | let res = send(&app, "POST", "/meals/menus", Some(&mgr), Some(body)).await; |
| 22870 | assert_eq!(res.status, StatusCode::CREATED); |
| 22871 | let menu = id_of(&res.body); |
| 22872 | |
| 22873 | let res = send( |
| 22874 | &app, |
| 22875 | "POST", |
| 22876 | &format!("/meals/menus/{menu}/dishes"), |
| 22877 | Some(&teacher), |
| 22878 | Some(json!({ "name": "Pilav", "price_minor": 1000 })), |
| 22879 | ) |
| 22880 | .await; |
| 22881 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 22882 | |
| 22883 | // A tag outside the school's `dietary_tags` is a 400, on create... |
| 22884 | let res = send( |
| 22885 | &app, |
| 22886 | "POST", |
| 22887 | &format!("/meals/menus/{menu}/dishes"), |
| 22888 | Some(&mgr), |
| 22889 | Some(json!({ "name": "Pilav", "price_minor": 1000, "tags": ["halal"] })), |
| 22890 | ) |
| 22891 | .await; |
| 22892 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 22893 | |
| 22894 | // ...and on patch, and negative money never lands either. |
| 22895 | let res = send( |
| 22896 | &app, |
| 22897 | "POST", |
| 22898 | &format!("/meals/menus/{menu}/dishes"), |
| 22899 | Some(&mgr), |
| 22900 | Some(json!({ "name": "Pilav", "price_minor": 1000 })), |
| 22901 | ) |
| 22902 | .await; |
| 22903 | assert_eq!(res.status, StatusCode::CREATED); |
| 22904 | let dish = id_of(&res.body); |
| 22905 | let res = send( |
| 22906 | &app, |
| 22907 | "PATCH", |
| 22908 | &format!("/meals/dishes/{dish}"), |
| 22909 | Some(&mgr), |
| 22910 | Some(json!({ "tags": ["halal"] })), |
| 22911 | ) |
| 22912 | .await; |
| 22913 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 22914 | let res = send( |
| 22915 | &app, |
| 22916 | "PATCH", |
| 22917 | &format!("/meals/dishes/{dish}"), |
| 22918 | Some(&mgr), |
| 22919 | Some(json!({ "price_minor": -1 })), |
| 22920 | ) |
| 22921 | .await; |
| 22922 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 22923 | } |
| 22924 | |
| 22925 | // --- meals: bookings ------------------------------------------------------ |
| 22926 | |
| 22927 | /// A seat, end to end: book, see it on both listings, cancel it (the row stays, |
| 22928 | /// flipped), re-book the same seat, and the menu-delete guard in between. |
| 22929 | #[tokio::test] |
| 22930 | async fn meal_bookings_round_trip() { |
| 22931 | let (app, db) = app_and_db().await; |
| 22932 | let mgr = login_as(&app, &db, "booking_mgr", "manager").await; |
| 22933 | let ali = login(&app, "booking_ali").await; |
| 22934 | |
| 22935 | let res = send( |
| 22936 | &app, |
| 22937 | "POST", |
| 22938 | "/meals/menus", |
| 22939 | Some(&mgr), |
| 22940 | Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 2 })), |
| 22941 | ) |
| 22942 | .await; |
| 22943 | let menu = id_of(&res.body); |
| 22944 | |
| 22945 | let res = send( |
| 22946 | &app, |
| 22947 | "POST", |
| 22948 | &format!("/meals/menus/{menu}/bookings"), |
| 22949 | Some(&ali), |
| 22950 | Some(json!({})), |
| 22951 | ) |
| 22952 | .await; |
| 22953 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 22954 | let booking = id_of(&res.body); |
| 22955 | assert_eq!(res.body["status"], "booked"); |
| 22956 | assert_eq!(res.body["student"]["username"], "booking_ali"); |
| 22957 | assert_eq!(res.body["booked_by"]["username"], "booking_ali"); |
| 22958 | assert_eq!(res.body["cancelled_at"], json!(null)); |
| 22959 | |
| 22960 | // Booking twice is the same seat, not a second one — the composite id. |
| 22961 | let res = send( |
| 22962 | &app, |
| 22963 | "POST", |
| 22964 | &format!("/meals/menus/{menu}/bookings"), |
| 22965 | Some(&ali), |
| 22966 | Some(json!({})), |
| 22967 | ) |
| 22968 | .await; |
| 22969 | assert_eq!(res.status, StatusCode::CREATED); |
| 22970 | assert_eq!(id_of(&res.body), booking); |
| 22971 | |
| 22972 | let res = send(&app, "GET", "/meals/bookings/me", Some(&ali), None).await; |
| 22973 | assert_eq!(res.status, StatusCode::OK); |
| 22974 | assert_eq!(common::total(&res.body), 1); |
| 22975 | assert_eq!(res.body["items"][0]["id"], json!(booking)); |
| 22976 | |
| 22977 | // The kitchen's list is manager+; nobody else's `/me` shows the seat. |
| 22978 | let res = send( |
| 22979 | &app, |
| 22980 | "GET", |
| 22981 | &format!("/meals/menus/{menu}/bookings"), |
| 22982 | Some(&mgr), |
| 22983 | None, |
| 22984 | ) |
| 22985 | .await; |
| 22986 | assert_eq!(common::total(&res.body), 1); |
| 22987 | let res = send( |
| 22988 | &app, |
| 22989 | "GET", |
| 22990 | &format!("/meals/menus/{menu}/bookings"), |
| 22991 | Some(&ali), |
| 22992 | None, |
| 22993 | ) |
| 22994 | .await; |
| 22995 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 22996 | let res = send(&app, "GET", "/meals/bookings/me", Some(&mgr), None).await; |
| 22997 | assert_eq!(common::total(&res.body), 0); |
| 22998 | |
| 22999 | // A menu somebody still holds a seat on cannot be unpublished. |
| 23000 | let res = send( |
| 23001 | &app, |
| 23002 | "DELETE", |
| 23003 | &format!("/meals/menus/{menu}"), |
| 23004 | Some(&mgr), |
| 23005 | None, |
| 23006 | ) |
| 23007 | .await; |
| 23008 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 23009 | |
| 23010 | // Cancelling flips the row, it never deletes it. |
| 23011 | let res = send( |
| 23012 | &app, |
| 23013 | "DELETE", |
| 23014 | &format!("/meals/bookings/{booking}"), |
| 23015 | Some(&ali), |
| 23016 | None, |
| 23017 | ) |
| 23018 | .await; |
| 23019 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23020 | assert_eq!(res.body["status"], "cancelled"); |
| 23021 | let stamp = res.body["cancelled_at"].as_i64().expect("stamped"); |
| 23022 | assert!(stamp > 0); |
| 23023 | // Cancelling again is idempotent — a `200` with the row as it stands, so a |
| 23024 | // cancel interrupted before its refund can be recovered by repeating it. |
| 23025 | // The stamp is not re-written: the seat was freed once. |
| 23026 | let res = send( |
| 23027 | &app, |
| 23028 | "DELETE", |
| 23029 | &format!("/meals/bookings/{booking}"), |
| 23030 | Some(&ali), |
| 23031 | None, |
| 23032 | ) |
| 23033 | .await; |
| 23034 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23035 | assert_eq!(res.body["status"], "cancelled"); |
| 23036 | assert_eq!(res.body["cancelled_at"], stamp); |
| 23037 | let res = send( |
| 23038 | &app, |
| 23039 | "GET", |
| 23040 | &format!("/meals/menus/{menu}/bookings"), |
| 23041 | Some(&mgr), |
| 23042 | None, |
| 23043 | ) |
| 23044 | .await; |
| 23045 | assert_eq!(common::total(&res.body), 1, "the cancelled row survives"); |
| 23046 | |
| 23047 | // Re-booking is the same row flipped back — one seat, never two. |
| 23048 | let res = send( |
| 23049 | &app, |
| 23050 | "POST", |
| 23051 | &format!("/meals/menus/{menu}/bookings"), |
| 23052 | Some(&ali), |
| 23053 | Some(json!({})), |
| 23054 | ) |
| 23055 | .await; |
| 23056 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 23057 | assert_eq!(id_of(&res.body), booking); |
| 23058 | assert_eq!(res.body["status"], "booked"); |
| 23059 | assert_eq!(res.body["cancelled_at"], json!(null)); |
| 23060 | let res = send( |
| 23061 | &app, |
| 23062 | "GET", |
| 23063 | &format!("/meals/menus/{menu}/bookings"), |
| 23064 | Some(&mgr), |
| 23065 | None, |
| 23066 | ) |
| 23067 | .await; |
| 23068 | assert_eq!(common::total(&res.body), 1); |
| 23069 | |
| 23070 | // Cancelled, the menu is free to go. |
| 23071 | send( |
| 23072 | &app, |
| 23073 | "DELETE", |
| 23074 | &format!("/meals/bookings/{booking}"), |
| 23075 | Some(&ali), |
| 23076 | None, |
| 23077 | ) |
| 23078 | .await; |
| 23079 | let res = send( |
| 23080 | &app, |
| 23081 | "DELETE", |
| 23082 | &format!("/meals/menus/{menu}"), |
| 23083 | Some(&mgr), |
| 23084 | None, |
| 23085 | ) |
| 23086 | .await; |
| 23087 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 23088 | } |
| 23089 | |
| 23090 | /// The cap refuses the seat that would overflow it, and a cancel genuinely |
| 23091 | /// gives that seat back. |
| 23092 | #[tokio::test] |
| 23093 | async fn meal_booking_capacity_caps_and_a_cancel_frees_a_seat() { |
| 23094 | let (app, db) = app_and_db().await; |
| 23095 | let mgr = login_as(&app, &db, "cap_mgr", "manager").await; |
| 23096 | let res = send( |
| 23097 | &app, |
| 23098 | "POST", |
| 23099 | "/meals/menus", |
| 23100 | Some(&mgr), |
| 23101 | Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 2 })), |
| 23102 | ) |
| 23103 | .await; |
| 23104 | let menu = id_of(&res.body); |
| 23105 | |
| 23106 | let students: Vec<String> = { |
| 23107 | let mut cookies = Vec::new(); |
| 23108 | for i in 0..3 { |
| 23109 | cookies.push(login(&app, &format!("cap_student{i}")).await); |
| 23110 | } |
| 23111 | cookies |
| 23112 | }; |
| 23113 | let book = |who: String| { |
| 23114 | let app = app.clone(); |
| 23115 | let menu = menu.clone(); |
| 23116 | async move { |
| 23117 | send( |
| 23118 | &app, |
| 23119 | "POST", |
| 23120 | &format!("/meals/menus/{menu}/bookings"), |
| 23121 | Some(&who), |
| 23122 | Some(json!({})), |
| 23123 | ) |
| 23124 | .await |
| 23125 | } |
| 23126 | }; |
| 23127 | |
| 23128 | let first = book(students[0].clone()).await; |
| 23129 | assert_eq!(first.status, StatusCode::CREATED); |
| 23130 | assert_eq!(book(students[1].clone()).await.status, StatusCode::CREATED); |
| 23131 | assert_eq!(book(students[2].clone()).await.status, StatusCode::CONFLICT); |
| 23132 | |
| 23133 | // Cancelling frees the seat — a cancelled row must not count. |
| 23134 | let booking = id_of(&first.body); |
| 23135 | send( |
| 23136 | &app, |
| 23137 | "DELETE", |
| 23138 | &format!("/meals/bookings/{booking}"), |
| 23139 | Some(&students[0]), |
| 23140 | None, |
| 23141 | ) |
| 23142 | .await; |
| 23143 | assert_eq!(book(students[2].clone()).await.status, StatusCode::CREATED); |
| 23144 | // …and the freed seat is gone again, so the first student cannot return. |
| 23145 | assert_eq!(book(students[0].clone()).await.status, StatusCode::CONFLICT); |
| 23146 | } |
| 23147 | |
| 23148 | /// The cap is a conditional claim the store enforces: under a stampede it |
| 23149 | /// must still admit exactly `capacity` seats, and the |
| 23150 | /// losers must get a 409 rather than a 500. Mirrors |
| 23151 | /// `concurrent_duplicate_registrations_conflict_not_500`. |
| 23152 | #[tokio::test] |
| 23153 | async fn concurrent_meal_bookings_never_exceed_the_capacity() { |
| 23154 | let (app, db) = app_and_db().await; |
| 23155 | let mgr = login_as(&app, &db, "race_mgr", "manager").await; |
| 23156 | let res = send( |
| 23157 | &app, |
| 23158 | "POST", |
| 23159 | "/meals/menus", |
| 23160 | Some(&mgr), |
| 23161 | Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 3 })), |
| 23162 | ) |
| 23163 | .await; |
| 23164 | let menu = id_of(&res.body); |
| 23165 | |
| 23166 | let mut students = Vec::new(); |
| 23167 | for i in 0..24 { |
| 23168 | students.push(login(&app, &format!("race_student{i}")).await); |
| 23169 | } |
| 23170 | |
| 23171 | let mut handles = Vec::new(); |
| 23172 | for cookie in students { |
| 23173 | let app = app.clone(); |
| 23174 | let menu = menu.clone(); |
| 23175 | handles.push(tokio::spawn(async move { |
| 23176 | send( |
| 23177 | &app, |
| 23178 | "POST", |
| 23179 | &format!("/meals/menus/{menu}/bookings"), |
| 23180 | Some(&cookie), |
| 23181 | Some(json!({})), |
| 23182 | ) |
| 23183 | .await |
| 23184 | .status |
| 23185 | })); |
| 23186 | } |
| 23187 | |
| 23188 | let mut booked = 0; |
| 23189 | for h in handles { |
| 23190 | let status = h.await.unwrap(); |
| 23191 | assert!( |
| 23192 | status == StatusCode::CREATED || status == StatusCode::CONFLICT, |
| 23193 | "a lost race must be a 409, never a 500: {status}" |
| 23194 | ); |
| 23195 | booked += i32::from(status == StatusCode::CREATED); |
| 23196 | } |
| 23197 | assert_eq!(booked, 3, "exactly the capacity was admitted"); |
| 23198 | |
| 23199 | let res = send( |
| 23200 | &app, |
| 23201 | "GET", |
| 23202 | &format!("/meals/menus/{menu}/bookings"), |
| 23203 | Some(&mgr), |
| 23204 | None, |
| 23205 | ) |
| 23206 | .await; |
| 23207 | assert_eq!(common::total(&res.body), 3, "and only three rows exist"); |
| 23208 | |
| 23209 | // The rows are downstream of the counter, so assert the counter itself: |
| 23210 | // it is what every booking's `WHERE` compares, and a drift here would open |
| 23211 | // the cap on the next booking however tidy the listing looks. |
| 23212 | let counted: i64 = sqlx::query_scalar("SELECT seats_booked FROM menu WHERE id = $1") |
| 23213 | .bind(&menu) |
| 23214 | .fetch_one(&db) |
| 23215 | .await |
| 23216 | .expect("counter read"); |
| 23217 | assert_eq!( |
| 23218 | counted, 3, |
| 23219 | "the stored seat counter must agree with the seats handed out" |
| 23220 | ); |
| 23221 | } |
| 23222 | |
| 23223 | /// Publishing the same day+slot twice at once must be one menu and one 409 — |
| 23224 | /// never two rows and never a 500. The day and slot *are* the record id, so the |
| 23225 | /// racers collide on a single record inside the database rather than on a |
| 23226 | /// check-then-write pair, which is the only form no interleaving can defeat. |
| 23227 | #[tokio::test] |
| 23228 | async fn concurrent_duplicate_menu_publishes_conflict_not_500() { |
| 23229 | let (app, db) = app_and_db().await; |
| 23230 | let mgr = login_as(&app, &db, "publish_race_mgr", "manager").await; |
| 23231 | |
| 23232 | let mut handles = Vec::new(); |
| 23233 | for _ in 0..8 { |
| 23234 | let app = app.clone(); |
| 23235 | let mgr = mgr.clone(); |
| 23236 | handles.push(tokio::spawn(async move { |
| 23237 | send( |
| 23238 | &app, |
| 23239 | "POST", |
| 23240 | "/meals/menus", |
| 23241 | Some(&mgr), |
| 23242 | Some(json!({ "date": "2099-09-14", "slot": "lunch" })), |
| 23243 | ) |
| 23244 | .await |
| 23245 | .status |
| 23246 | })); |
| 23247 | } |
| 23248 | let mut published = 0; |
| 23249 | for h in handles { |
| 23250 | let status = h.await.unwrap(); |
| 23251 | assert!( |
| 23252 | status == StatusCode::CREATED || status == StatusCode::CONFLICT, |
| 23253 | "a lost publish must be a 409, never a 500: {status}" |
| 23254 | ); |
| 23255 | published += i32::from(status == StatusCode::CREATED); |
| 23256 | } |
| 23257 | assert_eq!(published, 1, "exactly one publish won"); |
| 23258 | |
| 23259 | let res = send(&app, "GET", "/meals/menus", Some(&mgr), None).await; |
| 23260 | assert_eq!(common::total(&res.body), 1, "and exactly one menu exists"); |
| 23261 | } |
| 23262 | |
| 23263 | /// Two appends of one ledger id must both succeed: the id is the store's |
| 23264 | /// idempotence key, so the loser reads back the winner's line instead of |
| 23265 | /// surfacing the duplicate-key error as a 500. Driven at the domain level |
| 23266 | /// because that is the collision, not HTTP. |
| 23267 | #[tokio::test] |
| 23268 | async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() { |
| 23269 | use hezarfen_backend::db::meal_ledger; |
| 23270 | use hezarfen_backend::domain::meal_booking::MealBookingId; |
| 23271 | use hezarfen_backend::service::meal_ledger as ledger_service; |
| 23272 | |
| 23273 | let (app, db) = app_and_db().await; |
| 23274 | let mgr = login_as(&app, &db, "ledger_race_mgr", "manager").await; |
| 23275 | let ali = login(&app, "ledger_race_ali").await; |
| 23276 | |
| 23277 | let res = send( |
| 23278 | &app, |
| 23279 | "POST", |
| 23280 | "/meals/menus", |
| 23281 | Some(&mgr), |
| 23282 | Some(json!({ "date": "2099-09-15", "slot": "lunch" })), |
| 23283 | ) |
| 23284 | .await; |
| 23285 | let menu = id_of(&res.body); |
| 23286 | let res = send( |
| 23287 | &app, |
| 23288 | "POST", |
| 23289 | &format!("/meals/menus/{menu}/dishes"), |
| 23290 | Some(&mgr), |
| 23291 | Some(json!({ "name": "Pilav", "price_minor": 1000 })), |
| 23292 | ) |
| 23293 | .await; |
| 23294 | assert_eq!(res.status, StatusCode::CREATED); |
| 23295 | |
| 23296 | // The seat charges 1000; its reversal line does not exist yet, so both |
| 23297 | // racers below derive the same unwritten id. |
| 23298 | let res = send( |
| 23299 | &app, |
| 23300 | "POST", |
| 23301 | &format!("/meals/menus/{menu}/bookings"), |
| 23302 | Some(&ali), |
| 23303 | Some(json!({})), |
| 23304 | ) |
| 23305 | .await; |
| 23306 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 23307 | let booking = hezarfen_backend::service::meal_booking::read( |
| 23308 | &db, |
| 23309 | &MealBookingId::from_key(&id_of(&res.body)), |
| 23310 | ) |
| 23311 | .await |
| 23312 | .expect("read the booking") |
| 23313 | .expect("the booking exists"); |
| 23314 | let student = *booking.get_student(); |
| 23315 | assert_eq!( |
| 23316 | meal_ledger::balance_of(&db, &student).await.unwrap(), |
| 23317 | -1000, |
| 23318 | "the seat was charged once" |
| 23319 | ); |
| 23320 | |
| 23321 | let (first, second) = tokio::join!( |
| 23322 | ledger_service::reverse_booking(&db, &booking, &student), |
| 23323 | ledger_service::reverse_booking(&db, &booking, &student), |
| 23324 | ); |
| 23325 | assert!(first.is_ok(), "the winner appended: {first:?}"); |
| 23326 | assert!( |
| 23327 | second.is_ok(), |
| 23328 | "the loser must read back the winner's line, not fail: {second:?}" |
| 23329 | ); |
| 23330 | |
| 23331 | let (lines, _) = meal_ledger::list_for_student(&db, &student, None, 0) |
| 23332 | .await |
| 23333 | .unwrap(); |
| 23334 | assert_eq!(lines.len(), 2, "one charge and exactly one reversal"); |
| 23335 | assert_eq!( |
| 23336 | meal_ledger::balance_of(&db, &student).await.unwrap(), |
| 23337 | 0, |
| 23338 | "the money moved back exactly once" |
| 23339 | ); |
| 23340 | } |
| 23341 | |
| 23342 | /// One knob closes both ends: past the school's `meal_cancel_cutoff_minutes` |
| 23343 | /// neither a new booking nor a cancellation lands. |
| 23344 | #[tokio::test] |
| 23345 | async fn meal_cutoff_closes_booking_and_cancelling_alike() { |
| 23346 | let (app, db) = app_and_db().await; |
| 23347 | let mgr = login_as(&app, &db, "cutoff_mgr", "manager").await; |
| 23348 | let ali = login(&app, "cutoff_ali").await; |
| 23349 | |
| 23350 | // No cutoff configured yet, so today's meal books at any hour — the day |
| 23351 | // being over is the *other* refusal, and today's is not over. |
| 23352 | let today = hezarfen_backend::domain::timestamp::Timestamp::today_utc() |
| 23353 | .format("%Y-%m-%d") |
| 23354 | .to_string(); |
| 23355 | let res = send( |
| 23356 | &app, |
| 23357 | "POST", |
| 23358 | "/meals/menus", |
| 23359 | Some(&mgr), |
| 23360 | Some(json!({ "date": today, "slot": "lunch" })), |
| 23361 | ) |
| 23362 | .await; |
| 23363 | let menu = id_of(&res.body); |
| 23364 | let res = send( |
| 23365 | &app, |
| 23366 | "POST", |
| 23367 | &format!("/meals/menus/{menu}/bookings"), |
| 23368 | Some(&ali), |
| 23369 | Some(json!({})), |
| 23370 | ) |
| 23371 | .await; |
| 23372 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 23373 | let booking = id_of(&res.body); |
| 23374 | |
| 23375 | // The serving hour goes with the knob: a slot without one has no instant |
| 23376 | // for the deadline to count back from, so the cutoff binds none of its |
| 23377 | // menus (see `meal_cutoff_counts_back_from_the_slots_serving_time`). Lunch |
| 23378 | // is served at 00:00 UTC, so today's deadline passed an hour before the day |
| 23379 | // began — whatever hour this test runs at. |
| 23380 | let res = send( |
| 23381 | &app, |
| 23382 | "PATCH", |
| 23383 | "/settings", |
| 23384 | Some(&mgr), |
| 23385 | Some(json!({ |
| 23386 | "meal_cancel_cutoff_minutes": 60, |
| 23387 | "meal_slots": [{ "name": "lunch", "serving_minute": 0 }], |
| 23388 | })), |
| 23389 | ) |
| 23390 | .await; |
| 23391 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23392 | |
| 23393 | // Both ends now refuse: the meal is settled. |
| 23394 | let res = send( |
| 23395 | &app, |
| 23396 | "DELETE", |
| 23397 | &format!("/meals/bookings/{booking}"), |
| 23398 | Some(&ali), |
| 23399 | None, |
| 23400 | ) |
| 23401 | .await; |
| 23402 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 23403 | let veli = login(&app, "cutoff_veli").await; |
| 23404 | let res = send( |
| 23405 | &app, |
| 23406 | "POST", |
| 23407 | &format!("/meals/menus/{menu}/bookings"), |
| 23408 | Some(&veli), |
| 23409 | Some(json!({})), |
| 23410 | ) |
| 23411 | .await; |
| 23412 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 23413 | |
| 23414 | // A meal far enough ahead is untouched by the same cutoff. |
| 23415 | let res = send( |
| 23416 | &app, |
| 23417 | "POST", |
| 23418 | "/meals/menus", |
| 23419 | Some(&mgr), |
| 23420 | Some(json!({ "date": "2099-01-06", "slot": "lunch" })), |
| 23421 | ) |
| 23422 | .await; |
| 23423 | let later = id_of(&res.body); |
| 23424 | let res = send( |
| 23425 | &app, |
| 23426 | "POST", |
| 23427 | &format!("/meals/menus/{later}/bookings"), |
| 23428 | Some(&ali), |
| 23429 | Some(json!({})), |
| 23430 | ) |
| 23431 | .await; |
| 23432 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 23433 | } |
| 23434 | |
| 23435 | /// The cutoff counts back from the slot's **serving time**, not from midnight. |
| 23436 | /// The discriminating case: a menu on tomorrow's date whose lunch is served at |
| 23437 | /// 23:59 UTC, with a cutoff wide enough that *midnight* of that date is already |
| 23438 | /// inside it. Under the old midnight rule the seat is shut; measured from the |
| 23439 | /// serving time it is open for another ~24 hours. Then, with no serving time on |
| 23440 | /// the slot, the very same menu closes at **nothing at all**: there is no |
| 23441 | /// instant left to count the deadline back from, and counting from midnight — |
| 23442 | /// as this did — shut every same-day menu of a school that had set the cutoff |
| 23443 | /// knob without serving hours, which is how all three slots ship. |
| 23444 | #[tokio::test] |
| 23445 | async fn meal_cutoff_counts_back_from_the_slots_serving_time() { |
| 23446 | let (app, db) = app_and_db().await; |
| 23447 | let mgr = login_as(&app, &db, "serve_mgr", "manager").await; |
| 23448 | let ali = login(&app, "serve_ali").await; |
| 23449 | |
| 23450 | // Tomorrow UTC, so midnight of the menu's date is 0–1440 minutes ahead. |
| 23451 | let now = Timestamp::now().as_millis(); |
| 23452 | let tomorrow = Timestamp::today_utc() + chrono::Days::new(1); |
| 23453 | let midnight = tomorrow |
| 23454 | .and_hms_opt(0, 0, 0) |
| 23455 | .unwrap() |
| 23456 | .and_utc() |
| 23457 | .timestamp_millis(); |
| 23458 | // Five minutes wider than the gap to midnight: the midnight deadline is |
| 23459 | // now in the past, while the 23:59 serving deadline is ~24 hours out. |
| 23460 | let cutoff = (midnight - now).div_euclid(60_000) + 5; |
| 23461 | let res = send( |
| 23462 | &app, |
| 23463 | "PATCH", |
| 23464 | "/settings", |
| 23465 | Some(&mgr), |
| 23466 | Some(json!({ |
| 23467 | "meal_slots": [{ "name": "lunch", "serving_minute": 1439 }], |
| 23468 | "meal_cancel_cutoff_minutes": cutoff, |
| 23469 | })), |
| 23470 | ) |
| 23471 | .await; |
| 23472 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23473 | |
| 23474 | let res = send( |
| 23475 | &app, |
| 23476 | "POST", |
| 23477 | "/meals/menus", |
| 23478 | Some(&mgr), |
| 23479 | Some(json!({ "date": tomorrow.to_string(), "slot": "lunch" })), |
| 23480 | ) |
| 23481 | .await; |
| 23482 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 23483 | let menu = id_of(&res.body); |
| 23484 | |
| 23485 | let res = send( |
| 23486 | &app, |
| 23487 | "POST", |
| 23488 | &format!("/meals/menus/{menu}/bookings"), |
| 23489 | Some(&ali), |
| 23490 | Some(json!({})), |
| 23491 | ) |
| 23492 | .await; |
| 23493 | assert_eq!( |
| 23494 | res.status, |
| 23495 | StatusCode::CREATED, |
| 23496 | "measured from 23:59 the seat is still open; the midnight rule would \ |
| 23497 | have refused it: {}", |
| 23498 | res.body |
| 23499 | ); |
| 23500 | let booking = id_of(&res.body); |
| 23501 | |
| 23502 | // Drop the serving time from the same slot: there is now no instant to |
| 23503 | // count the deadline back from, so this menu closes at nothing — it does |
| 23504 | // *not* snap back to midnight, which used to shut the canteen of every |
| 23505 | // school that set the cutoff without setting hours. The slot list is read |
| 23506 | // live, so the menu published under it moves with the edit. |
| 23507 | let res = send( |
| 23508 | &app, |
| 23509 | "PATCH", |
| 23510 | "/settings", |
| 23511 | Some(&mgr), |
| 23512 | Some(json!({ "meal_slots": [{ "name": "lunch" }] })), |
| 23513 | ) |
| 23514 | .await; |
| 23515 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23516 | assert_eq!( |
| 23517 | res.body["meal_slots"], |
| 23518 | json!([{ "name": "lunch", "serving_minute": null }]), |
| 23519 | "{}", |
| 23520 | res.body |
| 23521 | ); |
| 23522 | |
| 23523 | let veli = login(&app, "serve_veli").await; |
| 23524 | let res = send( |
| 23525 | &app, |
| 23526 | "POST", |
| 23527 | &format!("/meals/menus/{menu}/bookings"), |
| 23528 | Some(&veli), |
| 23529 | Some(json!({})), |
| 23530 | ) |
| 23531 | .await; |
| 23532 | assert_eq!( |
| 23533 | res.status, |
| 23534 | StatusCode::CREATED, |
| 23535 | "an unset serving hour is an unenforced cutoff: {}", |
| 23536 | res.body |
| 23537 | ); |
| 23538 | // …and the student holding a seat can still give it back themselves, |
| 23539 | // which the midnight fallback took away from them. |
| 23540 | let res = send( |
| 23541 | &app, |
| 23542 | "DELETE", |
| 23543 | &format!("/meals/bookings/{booking}"), |
| 23544 | Some(&ali), |
| 23545 | None, |
| 23546 | ) |
| 23547 | .await; |
| 23548 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23549 | |
| 23550 | // Serving lunch at midnight instead makes the same cutoff bite: the |
| 23551 | // deadline is that instant minus the cutoff, which is already past. |
| 23552 | let res = send( |
| 23553 | &app, |
| 23554 | "PATCH", |
| 23555 | "/settings", |
| 23556 | Some(&mgr), |
| 23557 | Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 0 }] })), |
| 23558 | ) |
| 23559 | .await; |
| 23560 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23561 | let res = send( |
| 23562 | &app, |
| 23563 | "POST", |
| 23564 | &format!("/meals/menus/{menu}/bookings"), |
| 23565 | Some(&ali), |
| 23566 | Some(json!({})), |
| 23567 | ) |
| 23568 | .await; |
| 23569 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 23570 | } |
| 23571 | |
| 23572 | /// Who may take a seat: the student it is for, or a parent holding a link to |
| 23573 | /// them. Nobody else — a teacher does not order lunch for a child. |
| 23574 | #[tokio::test] |
| 23575 | async fn meal_bookings_are_student_or_linked_parent_only() { |
| 23576 | let (app, db) = app_and_db().await; |
| 23577 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 23578 | let mgr = login_as(&app, &db, "kin_mgr", "manager").await; |
| 23579 | let teacher = login_as(&app, &db, "kin_teacher", "teacher").await; |
| 23580 | let mom = login_as(&app, &db, "kin_mom", "parent").await; |
| 23581 | let mom_id = me_id(&app, &mom).await; |
| 23582 | let ali = login(&app, "kin_ali").await; |
| 23583 | let ali_id = me_id(&app, &ali).await; |
| 23584 | let veli = login(&app, "kin_veli").await; |
| 23585 | let veli_id = me_id(&app, &veli).await; |
| 23586 | |
| 23587 | let res = send( |
| 23588 | &app, |
| 23589 | "POST", |
| 23590 | &format!("/users/{mom_id}/students"), |
| 23591 | Some(&admin), |
| 23592 | Some(json!({ "user_id": ali_id })), |
| 23593 | ) |
| 23594 | .await; |
| 23595 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23596 | |
| 23597 | let res = send( |
| 23598 | &app, |
| 23599 | "POST", |
| 23600 | "/meals/menus", |
| 23601 | Some(&mgr), |
| 23602 | Some(json!({ "date": "2099-09-14", "slot": "lunch" })), |
| 23603 | ) |
| 23604 | .await; |
| 23605 | let menu = id_of(&res.body); |
| 23606 | let path = format!("/meals/menus/{menu}/bookings"); |
| 23607 | |
| 23608 | // The parent books for their own child. |
| 23609 | let res = send( |
| 23610 | &app, |
| 23611 | "POST", |
| 23612 | &path, |
| 23613 | Some(&mom), |
| 23614 | Some(json!({ "student_id": ali_id })), |
| 23615 | ) |
| 23616 | .await; |
| 23617 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 23618 | assert_eq!(res.body["student"]["username"], "kin_ali"); |
| 23619 | assert_eq!(res.body["booked_by"]["username"], "kin_mom"); |
| 23620 | let booking = id_of(&res.body); |
| 23621 | // …and sees it on their own list, though the seat is not theirs. |
| 23622 | let res = send(&app, "GET", "/meals/bookings/me", Some(&mom), None).await; |
| 23623 | assert_eq!(common::total(&res.body), 1); |
| 23624 | |
| 23625 | // Never for someone else's child, and never without naming one. |
| 23626 | let res = send( |
| 23627 | &app, |
| 23628 | "POST", |
| 23629 | &path, |
| 23630 | Some(&mom), |
| 23631 | Some(json!({ "student_id": veli_id })), |
| 23632 | ) |
| 23633 | .await; |
| 23634 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 23635 | let res = send(&app, "POST", &path, Some(&mom), Some(json!({}))).await; |
| 23636 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 23637 | |
| 23638 | // Staff do not order for children through this route. |
| 23639 | let res = send( |
| 23640 | &app, |
| 23641 | "POST", |
| 23642 | &path, |
| 23643 | Some(&teacher), |
| 23644 | Some(json!({ "student_id": ali_id })), |
| 23645 | ) |
| 23646 | .await; |
| 23647 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 23648 | let res = send( |
| 23649 | &app, |
| 23650 | "POST", |
| 23651 | &path, |
| 23652 | Some(&mgr), |
| 23653 | Some(json!({ "student_id": ali_id })), |
| 23654 | ) |
| 23655 | .await; |
| 23656 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 23657 | |
| 23658 | // A student books only for themselves, and cancels only their own. |
| 23659 | let res = send( |
| 23660 | &app, |
| 23661 | "POST", |
| 23662 | &path, |
| 23663 | Some(&veli), |
| 23664 | Some(json!({ "student_id": ali_id })), |
| 23665 | ) |
| 23666 | .await; |
| 23667 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 23668 | let res = send( |
| 23669 | &app, |
| 23670 | "DELETE", |
| 23671 | &format!("/meals/bookings/{booking}"), |
| 23672 | Some(&veli), |
| 23673 | None, |
| 23674 | ) |
| 23675 | .await; |
| 23676 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 23677 | |
| 23678 | // The linked parent may give the seat back. |
| 23679 | let res = send( |
| 23680 | &app, |
| 23681 | "DELETE", |
| 23682 | &format!("/meals/bookings/{booking}"), |
| 23683 | Some(&mom), |
| 23684 | None, |
| 23685 | ) |
| 23686 | .await; |
| 23687 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23688 | assert_eq!(res.body["status"], "cancelled"); |
| 23689 | } |
| 23690 | |
| 23691 | // --- meals: the ledger ---------------------------------------------------- |
| 23692 | |
| 23693 | /// The money, end to end: booking charges the menu's price *snapshot*, editing |
| 23694 | /// a dish afterwards never moves that charge, cancelling appends a reversal |
| 23695 | /// (leaving the charge standing — the append-only proof), and re-booking bills |
| 23696 | /// the new price. |
| 23697 | #[tokio::test] |
| 23698 | async fn meal_booking_charges_a_price_snapshot_and_a_cancel_reverses_it() { |
| 23699 | let (app, db) = app_and_db().await; |
| 23700 | let mgr = login_as(&app, &db, "money_mgr", "manager").await; |
| 23701 | let ali = login(&app, "money_ali").await; |
| 23702 | let ali_id = me_id(&app, &ali).await; |
| 23703 | |
| 23704 | let res = send( |
| 23705 | &app, |
| 23706 | "POST", |
| 23707 | "/meals/menus", |
| 23708 | Some(&mgr), |
| 23709 | Some(json!({ "date": "2099-09-14", "slot": "lunch" })), |
| 23710 | ) |
| 23711 | .await; |
| 23712 | let menu = id_of(&res.body); |
| 23713 | let res = send( |
| 23714 | &app, |
| 23715 | "POST", |
| 23716 | &format!("/meals/menus/{menu}/dishes"), |
| 23717 | Some(&mgr), |
| 23718 | Some(json!({ "name": "Çorba", "price_minor": 4_500 })), |
| 23719 | ) |
| 23720 | .await; |
| 23721 | let dish = id_of(&res.body); |
| 23722 | send( |
| 23723 | &app, |
| 23724 | "POST", |
| 23725 | &format!("/meals/menus/{menu}/dishes"), |
| 23726 | Some(&mgr), |
| 23727 | Some(json!({ "name": "Pilav", "price_minor": 2_000 })), |
| 23728 | ) |
| 23729 | .await; |
| 23730 | |
| 23731 | // A fresh student owes nothing. |
| 23732 | let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; |
| 23733 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23734 | assert_eq!(res.body["balance_minor"], 0); |
| 23735 | |
| 23736 | // Booking charges the sum of the dishes — negative means "owes". |
| 23737 | let res = send( |
| 23738 | &app, |
| 23739 | "POST", |
| 23740 | &format!("/meals/menus/{menu}/bookings"), |
| 23741 | Some(&ali), |
| 23742 | Some(json!({})), |
| 23743 | ) |
| 23744 | .await; |
| 23745 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 23746 | let booking = id_of(&res.body); |
| 23747 | let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; |
| 23748 | assert_eq!(res.body["balance_minor"], -6_500); |
| 23749 | |
| 23750 | // Booking again is the same seat, so it must not bill twice. |
| 23751 | send( |
| 23752 | &app, |
| 23753 | "POST", |
| 23754 | &format!("/meals/menus/{menu}/bookings"), |
| 23755 | Some(&ali), |
| 23756 | Some(json!({})), |
| 23757 | ) |
| 23758 | .await; |
| 23759 | let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; |
| 23760 | assert_eq!(res.body["balance_minor"], -6_500, "one seat, one charge"); |
| 23761 | |
| 23762 | // A price edit is not retroactive: what the student owes is what the menu |
| 23763 | // cost the day they booked. |
| 23764 | let res = send( |
| 23765 | &app, |
| 23766 | "PATCH", |
| 23767 | &format!("/meals/dishes/{dish}"), |
| 23768 | Some(&mgr), |
| 23769 | Some(json!({ "price_minor": 9_900 })), |
| 23770 | ) |
| 23771 | .await; |
| 23772 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23773 | let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; |
| 23774 | assert_eq!(res.body["balance_minor"], -6_500, "the snapshot is frozen"); |
| 23775 | |
| 23776 | // Cancelling appends a reversal; the charge row stays right where it was. |
| 23777 | let res = send( |
| 23778 | &app, |
| 23779 | "DELETE", |
| 23780 | &format!("/meals/bookings/{booking}"), |
| 23781 | Some(&ali), |
| 23782 | None, |
| 23783 | ) |
| 23784 | .await; |
| 23785 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23786 | let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; |
| 23787 | assert_eq!(res.body["balance_minor"], 0); |
| 23788 | |
| 23789 | let res = send( |
| 23790 | &app, |
| 23791 | "GET", |
| 23792 | &format!("/meals/ledger/{ali_id}"), |
| 23793 | Some(&mgr), |
| 23794 | None, |
| 23795 | ) |
| 23796 | .await; |
| 23797 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23798 | assert_eq!(common::total(&res.body), 2, "both lines survive the cancel"); |
| 23799 | let lines = res.body["items"].as_array().unwrap().clone(); |
| 23800 | // Newest first: the reversal, then the charge it points at. |
| 23801 | assert_eq!(lines[0]["kind"], "reversal"); |
| 23802 | assert_eq!(lines[0]["amount_minor"], 6_500); |
| 23803 | assert_eq!(lines[1]["kind"], "charge"); |
| 23804 | assert_eq!(lines[1]["amount_minor"], 6_500); |
| 23805 | assert_eq!(lines[1]["source"], json!(booking)); |
| 23806 | assert_eq!(lines[0]["source"], lines[1]["id"]); |
| 23807 | |
| 23808 | // Re-booking is a fresh charge, at the *new* price. |
| 23809 | let res = send( |
| 23810 | &app, |
| 23811 | "POST", |
| 23812 | &format!("/meals/menus/{menu}/bookings"), |
| 23813 | Some(&ali), |
| 23814 | Some(json!({})), |
| 23815 | ) |
| 23816 | .await; |
| 23817 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 23818 | let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; |
| 23819 | assert_eq!(res.body["balance_minor"], -11_900); |
| 23820 | let res = send( |
| 23821 | &app, |
| 23822 | "GET", |
| 23823 | &format!("/meals/ledger/{ali_id}"), |
| 23824 | Some(&mgr), |
| 23825 | None, |
| 23826 | ) |
| 23827 | .await; |
| 23828 | assert_eq!(common::total(&res.body), 3); |
| 23829 | } |
| 23830 | |
| 23831 | /// Recording cash is admin-only — a manager runs the kitchen, not the till. |
| 23832 | #[tokio::test] |
| 23833 | async fn meal_credits_are_admin_only_and_raise_the_balance() { |
| 23834 | let (app, db) = app_and_db().await; |
| 23835 | let admin = login_as(&app, &db, "till_admin", "admin").await; |
| 23836 | let mgr = login_as(&app, &db, "till_mgr", "manager").await; |
| 23837 | let ali = login(&app, "till_ali").await; |
| 23838 | let ali_id = me_id(&app, &ali).await; |
| 23839 | |
| 23840 | let body = json!({ "student_id": ali_id, "amount_minor": 25_000, "method": "cash" }); |
| 23841 | let res = send( |
| 23842 | &app, |
| 23843 | "POST", |
| 23844 | "/meals/credits", |
| 23845 | Some(&mgr), |
| 23846 | Some(body.clone()), |
| 23847 | ) |
| 23848 | .await; |
| 23849 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 23850 | let res = send( |
| 23851 | &app, |
| 23852 | "POST", |
| 23853 | "/meals/credits", |
| 23854 | Some(&ali), |
| 23855 | Some(body.clone()), |
| 23856 | ) |
| 23857 | .await; |
| 23858 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 23859 | |
| 23860 | let res = send(&app, "POST", "/meals/credits", Some(&admin), Some(body)).await; |
| 23861 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 23862 | assert_eq!(res.body["kind"], "credit"); |
| 23863 | assert_eq!(res.body["amount_minor"], 25_000); |
| 23864 | assert_eq!(res.body["method"], "cash"); |
| 23865 | assert_eq!(res.body["note"], json!(null)); |
| 23866 | assert_eq!(res.body["source"], json!(null)); |
| 23867 | assert_eq!(res.body["recorded_by"]["username"], "till_admin"); |
| 23868 | |
| 23869 | let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; |
| 23870 | assert_eq!(res.body["balance_minor"], 25_000); |
| 23871 | |
| 23872 | // The amount is bounded and positive; the target must be a student. |
| 23873 | for bad in [ |
| 23874 | json!({ "student_id": ali_id, "amount_minor": 0 }), |
| 23875 | json!({ "student_id": ali_id, "amount_minor": -100 }), |
| 23876 | json!({ "student_id": ali_id, "amount_minor": 10_000_001 }), |
| 23877 | ] { |
| 23878 | let res = send(&app, "POST", "/meals/credits", Some(&admin), Some(bad)).await; |
| 23879 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 23880 | } |
| 23881 | let mgr_id = me_id(&app, &mgr).await; |
| 23882 | let res = send( |
| 23883 | &app, |
| 23884 | "POST", |
| 23885 | "/meals/credits", |
| 23886 | Some(&admin), |
| 23887 | Some(json!({ "student_id": mgr_id, "amount_minor": 100 })), |
| 23888 | ) |
| 23889 | .await; |
| 23890 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 23891 | // …and the failed writes left the balance exactly where it was. |
| 23892 | let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; |
| 23893 | assert_eq!(res.body["balance_minor"], 25_000); |
| 23894 | } |
| 23895 | |
| 23896 | /// Whose money a caller may read: their own, their linked child's, or — as |
| 23897 | /// manager+ — anyone's. Never another family's, and never a teacher's business. |
| 23898 | #[tokio::test] |
| 23899 | async fn meal_balance_reads_are_manager_only_outside_the_family() { |
| 23900 | let (app, db) = app_and_db().await; |
| 23901 | let admin = login_as(&app, &db, "wallet_boss", "admin").await; |
| 23902 | let teacher = login_as(&app, &db, "wallet_teacher", "teacher").await; |
| 23903 | let mom = login_as(&app, &db, "wallet_mom", "parent").await; |
| 23904 | let mom_id = me_id(&app, &mom).await; |
| 23905 | let ali = login(&app, "wallet_ali").await; |
| 23906 | let ali_id = me_id(&app, &ali).await; |
| 23907 | let veli = login(&app, "wallet_veli").await; |
| 23908 | let veli_id = me_id(&app, &veli).await; |
| 23909 | |
| 23910 | let res = send( |
| 23911 | &app, |
| 23912 | "POST", |
| 23913 | &format!("/users/{mom_id}/students"), |
| 23914 | Some(&admin), |
| 23915 | Some(json!({ "user_id": ali_id })), |
| 23916 | ) |
| 23917 | .await; |
| 23918 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23919 | |
| 23920 | // The linked parent reads their child's balance and statement. |
| 23921 | let res = send( |
| 23922 | &app, |
| 23923 | "GET", |
| 23924 | &format!("/meals/balance/{ali_id}"), |
| 23925 | Some(&mom), |
| 23926 | None, |
| 23927 | ) |
| 23928 | .await; |
| 23929 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23930 | assert_eq!(res.body["student"]["username"], "wallet_ali"); |
| 23931 | let res = send( |
| 23932 | &app, |
| 23933 | "GET", |
| 23934 | &format!("/meals/ledger/{ali_id}"), |
| 23935 | Some(&mom), |
| 23936 | None, |
| 23937 | ) |
| 23938 | .await; |
| 23939 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23940 | |
| 23941 | // Someone else's child is a 403, on both routes. |
| 23942 | for path in [ |
| 23943 | format!("/meals/balance/{veli_id}"), |
| 23944 | format!("/meals/ledger/{veli_id}"), |
| 23945 | ] { |
| 23946 | let res = send(&app, "GET", &path, Some(&mom), None).await; |
| 23947 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 23948 | } |
| 23949 | |
| 23950 | // A student reads their own money, never a classmate's. |
| 23951 | let res = send( |
| 23952 | &app, |
| 23953 | "GET", |
| 23954 | &format!("/meals/balance/{ali_id}"), |
| 23955 | Some(&ali), |
| 23956 | None, |
| 23957 | ) |
| 23958 | .await; |
| 23959 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23960 | let res = send( |
| 23961 | &app, |
| 23962 | "GET", |
| 23963 | &format!("/meals/balance/{ali_id}"), |
| 23964 | Some(&veli), |
| 23965 | None, |
| 23966 | ) |
| 23967 | .await; |
| 23968 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 23969 | |
| 23970 | // A teacher does not, however: what a family owes the canteen is money, |
| 23971 | // and money is manager+ here exactly as it is on /payments. |
| 23972 | let res = send( |
| 23973 | &app, |
| 23974 | "GET", |
| 23975 | &format!("/meals/balance/{ali_id}"), |
| 23976 | Some(&teacher), |
| 23977 | None, |
| 23978 | ) |
| 23979 | .await; |
| 23980 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 23981 | |
| 23982 | // Manager+ reads any student's. |
| 23983 | let res = send( |
| 23984 | &app, |
| 23985 | "GET", |
| 23986 | &format!("/meals/balance/{ali_id}"), |
| 23987 | Some(&admin), |
| 23988 | None, |
| 23989 | ) |
| 23990 | .await; |
| 23991 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 23992 | } |
| 23993 | |
| 23994 | // --- meals: attendance ---------------------------------------------------- |
| 23995 | |
| 23996 | /// Marking who ate is reporting, never billing: a booked no-show still owes the |
| 23997 | /// full price, and a walk-in served without a booking owes nothing. Also covers |
| 23998 | /// the composite id (re-marking flips the row) and the teacher+ gate. |
| 23999 | #[tokio::test] |
| 24000 | async fn meal_attendance_never_moves_money() { |
| 24001 | let (app, db) = app_and_db().await; |
| 24002 | let mgr = login_as(&app, &db, "ate_mgr", "manager").await; |
| 24003 | let teacher = login_as(&app, &db, "ate_teacher", "teacher").await; |
| 24004 | let ali = login(&app, "ate_ali").await; |
| 24005 | let ali_id = me_id(&app, &ali).await; |
| 24006 | let veli = login(&app, "ate_veli").await; |
| 24007 | let veli_id = me_id(&app, &veli).await; |
| 24008 | |
| 24009 | let res = send( |
| 24010 | &app, |
| 24011 | "POST", |
| 24012 | "/meals/menus", |
| 24013 | Some(&mgr), |
| 24014 | Some(json!({ "date": "2099-09-14", "slot": "lunch" })), |
| 24015 | ) |
| 24016 | .await; |
| 24017 | let menu = id_of(&res.body); |
| 24018 | send( |
| 24019 | &app, |
| 24020 | "POST", |
| 24021 | &format!("/meals/menus/{menu}/dishes"), |
| 24022 | Some(&mgr), |
| 24023 | Some(json!({ "name": "Çorba", "price_minor": 4_500 })), |
| 24024 | ) |
| 24025 | .await; |
| 24026 | |
| 24027 | // Ali books (and is charged); Veli never books. |
| 24028 | let res = send( |
| 24029 | &app, |
| 24030 | "POST", |
| 24031 | &format!("/meals/menus/{menu}/bookings"), |
| 24032 | Some(&ali), |
| 24033 | Some(json!({})), |
| 24034 | ) |
| 24035 | .await; |
| 24036 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24037 | let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; |
| 24038 | assert_eq!(res.body["balance_minor"], -4_500); |
| 24039 | |
| 24040 | let path = format!("/meals/menus/{menu}/attendance"); |
| 24041 | |
| 24042 | // Served shows up on the menu's list. |
| 24043 | let res = send( |
| 24044 | &app, |
| 24045 | "POST", |
| 24046 | &path, |
| 24047 | Some(&teacher), |
| 24048 | Some(json!({ "student_id": ali_id, "status": "served" })), |
| 24049 | ) |
| 24050 | .await; |
| 24051 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24052 | let mark = id_of(&res.body); |
| 24053 | assert_eq!(res.body["status"], "served"); |
| 24054 | assert_eq!(res.body["student"]["username"], "ate_ali"); |
| 24055 | assert_eq!(res.body["marked_by"]["username"], "ate_teacher"); |
| 24056 | assert_eq!(res.body["menu_id"], json!(menu)); |
| 24057 | let res = send(&app, "GET", &path, Some(&teacher), None).await; |
| 24058 | assert_eq!(common::total(&res.body), 1); |
| 24059 | assert_eq!(res.body["items"][0]["id"], json!(mark)); |
| 24060 | |
| 24061 | // Re-marking the same student flips the row — one row per (menu, student). |
| 24062 | let res = send( |
| 24063 | &app, |
| 24064 | "POST", |
| 24065 | &path, |
| 24066 | Some(&teacher), |
| 24067 | Some(json!({ "student_id": ali_id, "status": "missed" })), |
| 24068 | ) |
| 24069 | .await; |
| 24070 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24071 | assert_eq!(id_of(&res.body), mark); |
| 24072 | assert_eq!(res.body["status"], "missed"); |
| 24073 | let res = send(&app, "GET", &path, Some(&teacher), None).await; |
| 24074 | assert_eq!( |
| 24075 | common::total(&res.body), |
| 24076 | 1, |
| 24077 | "the mark was flipped, not doubled" |
| 24078 | ); |
| 24079 | |
| 24080 | // THE BILLING-ISOLATION PROOF: the no-show still owes the whole price, and |
| 24081 | // his statement grew no reversal line. The kitchen bought the food. |
| 24082 | let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; |
| 24083 | assert_eq!( |
| 24084 | res.body["balance_minor"], -4_500, |
| 24085 | "attendance must never move money" |
| 24086 | ); |
| 24087 | let res = send( |
| 24088 | &app, |
| 24089 | "GET", |
| 24090 | &format!("/meals/ledger/{ali_id}"), |
| 24091 | Some(&mgr), |
| 24092 | None, |
| 24093 | ) |
| 24094 | .await; |
| 24095 | assert_eq!(common::total(&res.body), 1, "only the booking's charge"); |
| 24096 | assert_eq!(res.body["items"][0]["kind"], "charge"); |
| 24097 | |
| 24098 | // A walk-in with no booking is recordable — and still not charged. |
| 24099 | let res = send( |
| 24100 | &app, |
| 24101 | "POST", |
| 24102 | &path, |
| 24103 | Some(&teacher), |
| 24104 | Some(json!({ "student_id": veli_id, "status": "served" })), |
| 24105 | ) |
| 24106 | .await; |
| 24107 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24108 | let res = send(&app, "GET", "/meals/balance/me", Some(&veli), None).await; |
| 24109 | assert_eq!(res.body["balance_minor"], 0, "a walk-in is never billed"); |
| 24110 | |
| 24111 | // Students never mark, not even themselves, and never read the list. |
| 24112 | let res = send( |
| 24113 | &app, |
| 24114 | "POST", |
| 24115 | &path, |
| 24116 | Some(&ali), |
| 24117 | Some(json!({ "student_id": ali_id, "status": "served" })), |
| 24118 | ) |
| 24119 | .await; |
| 24120 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 24121 | let res = send(&app, "GET", &path, Some(&ali), None).await; |
| 24122 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 24123 | |
| 24124 | // Bad inputs: a roll-call status is not a canteen status, and the menu and |
| 24125 | // the student both have to exist. |
| 24126 | let res = send( |
| 24127 | &app, |
| 24128 | "POST", |
| 24129 | &path, |
| 24130 | Some(&teacher), |
| 24131 | Some(json!({ "student_id": ali_id, "status": "excused" })), |
| 24132 | ) |
| 24133 | .await; |
| 24134 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 24135 | let res = send( |
| 24136 | &app, |
| 24137 | "POST", |
| 24138 | &path, |
| 24139 | Some(&teacher), |
| 24140 | Some(json!({ "student_id": "nobody", "status": "served" })), |
| 24141 | ) |
| 24142 | .await; |
| 24143 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 24144 | let res = send( |
| 24145 | &app, |
| 24146 | "POST", |
| 24147 | "/meals/menus/missing/attendance", |
| 24148 | Some(&teacher), |
| 24149 | Some(json!({ "student_id": ali_id, "status": "served" })), |
| 24150 | ) |
| 24151 | .await; |
| 24152 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 24153 | } |
| 24154 | |
| 24155 | /// Deleting a menu takes its marks with it. The menu id is deterministic on |
| 24156 | /// `(date, slot)`, so republishing the same meal mints the *same* record id: a |
| 24157 | /// mark left behind by the deleted menu would come back as a mark on the new |
| 24158 | /// one — the kitchen would read "served" for a student who never came, and the |
| 24159 | /// student's own report would cite a menu that no longer exists. |
| 24160 | #[tokio::test] |
| 24161 | async fn deleting_a_menu_takes_its_attendance_with_it() { |
| 24162 | let (app, db) = app_and_db().await; |
| 24163 | let mgr = login_as(&app, &db, "ghost_mgr", "manager").await; |
| 24164 | let teacher = login_as(&app, &db, "ghost_teacher", "teacher").await; |
| 24165 | let ali = login(&app, "ghost_ali").await; |
| 24166 | let ali_id = me_id(&app, &ali).await; |
| 24167 | |
| 24168 | let publish = json!({ "date": "2099-10-05", "slot": "lunch" }); |
| 24169 | let res = send( |
| 24170 | &app, |
| 24171 | "POST", |
| 24172 | "/meals/menus", |
| 24173 | Some(&mgr), |
| 24174 | Some(publish.clone()), |
| 24175 | ) |
| 24176 | .await; |
| 24177 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24178 | let menu = id_of(&res.body); |
| 24179 | |
| 24180 | let res = send( |
| 24181 | &app, |
| 24182 | "POST", |
| 24183 | &format!("/meals/menus/{menu}/attendance"), |
| 24184 | Some(&teacher), |
| 24185 | Some(json!({ "student_id": ali_id, "status": "served" })), |
| 24186 | ) |
| 24187 | .await; |
| 24188 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24189 | |
| 24190 | // No seat was ever taken, so the counter guard lets the delete through. |
| 24191 | let res = send( |
| 24192 | &app, |
| 24193 | "DELETE", |
| 24194 | &format!("/meals/menus/{menu}"), |
| 24195 | Some(&mgr), |
| 24196 | None, |
| 24197 | ) |
| 24198 | .await; |
| 24199 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 24200 | |
| 24201 | // The student's own report must not cite a menu that is gone. |
| 24202 | let res = send( |
| 24203 | &app, |
| 24204 | "GET", |
| 24205 | &format!("/meals/attendance/{ali_id}"), |
| 24206 | Some(&teacher), |
| 24207 | None, |
| 24208 | ) |
| 24209 | .await; |
| 24210 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24211 | assert_eq!( |
| 24212 | common::total(&res.body), |
| 24213 | 0, |
| 24214 | "the mark outlived the menu it was taken on" |
| 24215 | ); |
| 24216 | |
| 24217 | // Republishing the same day and slot lands on the same record id. |
| 24218 | let res = send(&app, "POST", "/meals/menus", Some(&mgr), Some(publish)).await; |
| 24219 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24220 | let again = id_of(&res.body); |
| 24221 | assert_eq!(again, menu, "the id is deterministic on (date, slot)"); |
| 24222 | |
| 24223 | let res = send( |
| 24224 | &app, |
| 24225 | "GET", |
| 24226 | &format!("/meals/menus/{menu}/attendance"), |
| 24227 | Some(&teacher), |
| 24228 | None, |
| 24229 | ) |
| 24230 | .await; |
| 24231 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24232 | assert_eq!( |
| 24233 | common::total(&res.body), |
| 24234 | 0, |
| 24235 | "the deleted menu's mark came back on the republished one" |
| 24236 | ); |
| 24237 | } |
| 24238 | |
| 24239 | /// The per-student report: a lexical `?from=&to=` window over the menu's day, |
| 24240 | /// readable by teacher+ or a linked parent and by nobody else. |
| 24241 | #[tokio::test] |
| 24242 | async fn meal_attendance_report_is_ranged_and_gated() { |
| 24243 | let (app, db) = app_and_db().await; |
| 24244 | let admin = login_as(&app, &db, "ate_boss", "admin").await; |
| 24245 | let mgr = login_as(&app, &db, "range_mgr", "manager").await; |
| 24246 | let teacher = login_as(&app, &db, "range_teacher", "teacher").await; |
| 24247 | let mom = login_as(&app, &db, "range_mom", "parent").await; |
| 24248 | let mom_id = me_id(&app, &mom).await; |
| 24249 | let ali = login(&app, "range_ali").await; |
| 24250 | let ali_id = me_id(&app, &ali).await; |
| 24251 | let veli = login(&app, "range_veli").await; |
| 24252 | let veli_id = me_id(&app, &veli).await; |
| 24253 | |
| 24254 | let res = send( |
| 24255 | &app, |
| 24256 | "POST", |
| 24257 | &format!("/users/{mom_id}/students"), |
| 24258 | Some(&admin), |
| 24259 | Some(json!({ "user_id": ali_id })), |
| 24260 | ) |
| 24261 | .await; |
| 24262 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24263 | |
| 24264 | // Three days, one mark each for Ali. |
| 24265 | for date in ["2099-09-01", "2099-09-15", "2099-09-30"] { |
| 24266 | let res = send( |
| 24267 | &app, |
| 24268 | "POST", |
| 24269 | "/meals/menus", |
| 24270 | Some(&mgr), |
| 24271 | Some(json!({ "date": date, "slot": "lunch" })), |
| 24272 | ) |
| 24273 | .await; |
| 24274 | let menu = id_of(&res.body); |
| 24275 | let res = send( |
| 24276 | &app, |
| 24277 | "POST", |
| 24278 | &format!("/meals/menus/{menu}/attendance"), |
| 24279 | Some(&teacher), |
| 24280 | Some(json!({ "student_id": ali_id, "status": "served" })), |
| 24281 | ) |
| 24282 | .await; |
| 24283 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24284 | } |
| 24285 | |
| 24286 | // Unbounded, then each bound, then both — the window is the menu's day. |
| 24287 | for (query, expected) in [ |
| 24288 | ("", 3), |
| 24289 | ("?from=2099-09-15", 2), |
| 24290 | ("?to=2099-09-15", 2), |
| 24291 | ("?from=2099-09-10&to=2099-09-20", 1), |
| 24292 | ("?from=2099-10-01", 0), |
| 24293 | ] { |
| 24294 | let res = send( |
| 24295 | &app, |
| 24296 | "GET", |
| 24297 | &format!("/meals/attendance/{ali_id}{query}"), |
| 24298 | Some(&teacher), |
| 24299 | None, |
| 24300 | ) |
| 24301 | .await; |
| 24302 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24303 | assert_eq!(common::total(&res.body), expected, "range {query}"); |
| 24304 | } |
| 24305 | |
| 24306 | // A malformed bound is a 400, never a silently ignored filter. |
| 24307 | let res = send( |
| 24308 | &app, |
| 24309 | "GET", |
| 24310 | &format!("/meals/attendance/{ali_id}?from=2026-9-1"), |
| 24311 | Some(&teacher), |
| 24312 | None, |
| 24313 | ) |
| 24314 | .await; |
| 24315 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 24316 | |
| 24317 | // The linked parent reads her child's report; another child's is a 403, |
| 24318 | // and a classmate never reads it at all. |
| 24319 | let res = send( |
| 24320 | &app, |
| 24321 | "GET", |
| 24322 | &format!("/meals/attendance/{ali_id}"), |
| 24323 | Some(&mom), |
| 24324 | None, |
| 24325 | ) |
| 24326 | .await; |
| 24327 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24328 | assert_eq!(common::total(&res.body), 3); |
| 24329 | let res = send( |
| 24330 | &app, |
| 24331 | "GET", |
| 24332 | &format!("/meals/attendance/{veli_id}"), |
| 24333 | Some(&mom), |
| 24334 | None, |
| 24335 | ) |
| 24336 | .await; |
| 24337 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 24338 | let res = send( |
| 24339 | &app, |
| 24340 | "GET", |
| 24341 | &format!("/meals/attendance/{ali_id}"), |
| 24342 | Some(&veli), |
| 24343 | None, |
| 24344 | ) |
| 24345 | .await; |
| 24346 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 24347 | } |
| 24348 | |
| 24349 | /// The dietary profile and the `conflicts` it produces on a menu read: the |
| 24350 | /// school writes it, everyone in the reading gate sees it, and the overlap is |
| 24351 | /// computed against the *caller's* own tags. |
| 24352 | #[tokio::test] |
| 24353 | async fn dietary_profile_drives_menu_conflicts() { |
| 24354 | let (app, db) = app_and_db().await; |
| 24355 | let admin = login_as(&app, &db, "diet_boss", "admin").await; |
| 24356 | let mgr = login_as(&app, &db, "diet_mgr", "manager").await; |
| 24357 | let teacher = login_as(&app, &db, "diet_teacher", "teacher").await; |
| 24358 | let mom = login_as(&app, &db, "diet_mom", "parent").await; |
| 24359 | let mom_id = me_id(&app, &mom).await; |
| 24360 | let other_mom = login_as(&app, &db, "diet_aunt", "parent").await; |
| 24361 | let ali = login(&app, "diet_ali").await; |
| 24362 | let ali_id = me_id(&app, &ali).await; |
| 24363 | let veli = login(&app, "diet_veli").await; |
| 24364 | let veli_id = me_id(&app, &veli).await; |
| 24365 | |
| 24366 | let res = send( |
| 24367 | &app, |
| 24368 | "POST", |
| 24369 | &format!("/users/{mom_id}/students"), |
| 24370 | Some(&admin), |
| 24371 | Some(json!({ "user_id": ali_id })), |
| 24372 | ) |
| 24373 | .await; |
| 24374 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24375 | |
| 24376 | // No profile yet: empty, never a 404. |
| 24377 | let res = send(&app, "GET", "/meals/profiles/me", Some(&ali), None).await; |
| 24378 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24379 | assert_eq!(res.body["tags"], json!([])); |
| 24380 | assert_eq!(res.body["note"], json!(null)); |
| 24381 | assert_eq!(res.body["updated_at"], json!(null)); |
| 24382 | |
| 24383 | // A student does not write their own allergen list, and neither does a |
| 24384 | // teacher — this is a manager+ safety record. |
| 24385 | for actor in [&ali, &teacher] { |
| 24386 | let res = send( |
| 24387 | &app, |
| 24388 | "PATCH", |
| 24389 | &format!("/meals/profiles/{ali_id}"), |
| 24390 | Some(actor), |
| 24391 | Some(json!({ "tags": ["nut_allergy"] })), |
| 24392 | ) |
| 24393 | .await; |
| 24394 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 24395 | } |
| 24396 | |
| 24397 | // A tag outside the school's list is a 400, never a stored string. |
| 24398 | let res = send( |
| 24399 | &app, |
| 24400 | "PATCH", |
| 24401 | &format!("/meals/profiles/{ali_id}"), |
| 24402 | Some(&mgr), |
| 24403 | Some(json!({ "tags": ["halal"] })), |
| 24404 | ) |
| 24405 | .await; |
| 24406 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 24407 | |
| 24408 | let res = send( |
| 24409 | &app, |
| 24410 | "PATCH", |
| 24411 | &format!("/meals/profiles/{ali_id}"), |
| 24412 | Some(&mgr), |
| 24413 | Some(json!({ "tags": ["nut_allergy", "nut_allergy"], "note": " EpiPen " })), |
| 24414 | ) |
| 24415 | .await; |
| 24416 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24417 | assert_eq!(res.body["tags"], json!(["nut_allergy"])); |
| 24418 | assert_eq!(res.body["note"], "EpiPen"); |
| 24419 | assert_eq!(res.body["updated_by"]["username"], "diet_mgr"); |
| 24420 | |
| 24421 | // The student reads it back at `/me`; a second PATCH edits the same row. |
| 24422 | let res = send(&app, "GET", "/meals/profiles/me", Some(&ali), None).await; |
| 24423 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24424 | assert_eq!(res.body["tags"], json!(["nut_allergy"])); |
| 24425 | assert_eq!(res.body["student"]["username"], "diet_ali"); |
| 24426 | |
| 24427 | let res = send( |
| 24428 | &app, |
| 24429 | "PATCH", |
| 24430 | &format!("/meals/profiles/{ali_id}"), |
| 24431 | Some(&mgr), |
| 24432 | Some(json!({ "note": null })), |
| 24433 | ) |
| 24434 | .await; |
| 24435 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24436 | assert_eq!(res.body["note"], json!(null)); |
| 24437 | assert_eq!(res.body["tags"], json!(["nut_allergy"]), "tags kept"); |
| 24438 | |
| 24439 | // The linked parent reads her child's; an unlinked one does not. |
| 24440 | let res = send( |
| 24441 | &app, |
| 24442 | "GET", |
| 24443 | &format!("/meals/profiles/{ali_id}"), |
| 24444 | Some(&mom), |
| 24445 | None, |
| 24446 | ) |
| 24447 | .await; |
| 24448 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24449 | assert_eq!(res.body["tags"], json!(["nut_allergy"])); |
| 24450 | let res = send( |
| 24451 | &app, |
| 24452 | "GET", |
| 24453 | &format!("/meals/profiles/{ali_id}"), |
| 24454 | Some(&other_mom), |
| 24455 | None, |
| 24456 | ) |
| 24457 | .await; |
| 24458 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 24459 | |
| 24460 | // A profile is a student's thing — a teacher never carries one. |
| 24461 | let teacher_id = me_id(&app, &teacher).await; |
| 24462 | let res = send( |
| 24463 | &app, |
| 24464 | "PATCH", |
| 24465 | &format!("/meals/profiles/{teacher_id}"), |
| 24466 | Some(&mgr), |
| 24467 | Some(json!({ "tags": ["vegan"] })), |
| 24468 | ) |
| 24469 | .await; |
| 24470 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 24471 | |
| 24472 | // One menu, two dishes: one Ali must avoid, one he must not. |
| 24473 | let res = send( |
| 24474 | &app, |
| 24475 | "POST", |
| 24476 | "/meals/menus", |
| 24477 | Some(&mgr), |
| 24478 | Some(json!({ "date": "2099-10-05", "slot": "lunch" })), |
| 24479 | ) |
| 24480 | .await; |
| 24481 | let menu = id_of(&res.body); |
| 24482 | for (name, tags) in [ |
| 24483 | ("Fıstıklı baklava", json!(["nut_allergy", "vegetarian"])), |
| 24484 | ("Pilav", json!(["vegan"])), |
| 24485 | ] { |
| 24486 | let res = send( |
| 24487 | &app, |
| 24488 | "POST", |
| 24489 | &format!("/meals/menus/{menu}/dishes"), |
| 24490 | Some(&mgr), |
| 24491 | Some(json!({ "name": name, "price_minor": 1000, "tags": tags })), |
| 24492 | ) |
| 24493 | .await; |
| 24494 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24495 | } |
| 24496 | |
| 24497 | // Ali sees his own conflict on the one dish, and nothing on the other. |
| 24498 | for path in [format!("/meals/menus/{menu}"), "/meals/menus".to_string()] { |
| 24499 | let res = send(&app, "GET", &path, Some(&ali), None).await; |
| 24500 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24501 | let menu_body = if path == "/meals/menus" { |
| 24502 | res.body["items"][0].clone() |
| 24503 | } else { |
| 24504 | res.body.clone() |
| 24505 | }; |
| 24506 | assert_eq!( |
| 24507 | menu_body["dishes"][0]["conflicts"], |
| 24508 | json!(["nut_allergy"]), |
| 24509 | "{path}: the tag Ali holds, and only it" |
| 24510 | ); |
| 24511 | assert_eq!(menu_body["dishes"][1]["conflicts"], json!([]), "{path}"); |
| 24512 | } |
| 24513 | |
| 24514 | // A student with no profile, and a manager (who never has one), both read |
| 24515 | // empty conflicts — that is correct, not a bug. |
| 24516 | for actor in [&veli, &mgr] { |
| 24517 | let res = send( |
| 24518 | &app, |
| 24519 | "GET", |
| 24520 | &format!("/meals/menus/{menu}"), |
| 24521 | Some(actor), |
| 24522 | None, |
| 24523 | ) |
| 24524 | .await; |
| 24525 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24526 | assert_eq!(res.body["dishes"][0]["conflicts"], json!([])); |
| 24527 | assert_eq!(res.body["dishes"][1]["conflicts"], json!([])); |
| 24528 | } |
| 24529 | |
| 24530 | // Cleanup 1: a student reads their OWN meal-attendance history, like they |
| 24531 | // already read their own balance and statement. |
| 24532 | let res = send( |
| 24533 | &app, |
| 24534 | "POST", |
| 24535 | &format!("/meals/menus/{menu}/attendance"), |
| 24536 | Some(&teacher), |
| 24537 | Some(json!({ "student_id": veli_id, "status": "served" })), |
| 24538 | ) |
| 24539 | .await; |
| 24540 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24541 | let res = send( |
| 24542 | &app, |
| 24543 | "GET", |
| 24544 | &format!("/meals/attendance/{veli_id}"), |
| 24545 | Some(&veli), |
| 24546 | None, |
| 24547 | ) |
| 24548 | .await; |
| 24549 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24550 | assert_eq!(common::total(&res.body), 1); |
| 24551 | } |
| 24552 | |
| 24553 | // --- meals: money under concurrency and stale grants ---------------------- |
| 24554 | |
| 24555 | /// Publish a lunch menu carrying one dish at `price`; returns (menu id, |
| 24556 | /// student cookie). Every money-race test below needs the same three rows. |
| 24557 | async fn priced_menu(tag: &str, price: i64) -> (axum::Router, String, String) { |
| 24558 | let (app, db) = app_and_db().await; |
| 24559 | let mgr = login_as(&app, &db, &format!("{tag}_mgr"), "manager").await; |
| 24560 | let stu = login(&app, &format!("{tag}_stu")).await; |
| 24561 | let res = send( |
| 24562 | &app, |
| 24563 | "POST", |
| 24564 | "/meals/menus", |
| 24565 | Some(&mgr), |
| 24566 | Some(json!({ "date": "2099-09-14", "slot": "lunch" })), |
| 24567 | ) |
| 24568 | .await; |
| 24569 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24570 | let menu = id_of(&res.body); |
| 24571 | let res = send( |
| 24572 | &app, |
| 24573 | "POST", |
| 24574 | &format!("/meals/menus/{menu}/dishes"), |
| 24575 | Some(&mgr), |
| 24576 | Some(json!({ "name": "Pilav", "price_minor": price })), |
| 24577 | ) |
| 24578 | .await; |
| 24579 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24580 | (app, menu, stu) |
| 24581 | } |
| 24582 | |
| 24583 | /// The sequential "booking twice bills once" test cannot see this: idempotence |
| 24584 | /// that rests on a "is there already a charge?" scan is no idempotence at all, |
| 24585 | /// since eight simultaneous POSTs of one seat all read "not yet" and all |
| 24586 | /// append. One seat must mean one charge, so the ledger line is keyed by |
| 24587 | /// (booking, attempt) and written under the same lock as the seat. |
| 24588 | #[tokio::test(flavor = "multi_thread", worker_threads = 8)] |
| 24589 | async fn concurrent_bookings_of_one_seat_bill_it_once() { |
| 24590 | let (app, menu, stu) = priced_menu("race", 5_000).await; |
| 24591 | |
| 24592 | let mut tasks = Vec::new(); |
| 24593 | for _ in 0..8 { |
| 24594 | let app = app.clone(); |
| 24595 | let stu = stu.clone(); |
| 24596 | let menu = menu.clone(); |
| 24597 | tasks.push(tokio::spawn(async move { |
| 24598 | send( |
| 24599 | &app, |
| 24600 | "POST", |
| 24601 | &format!("/meals/menus/{menu}/bookings"), |
| 24602 | Some(&stu), |
| 24603 | Some(json!({})), |
| 24604 | ) |
| 24605 | .await |
| 24606 | })); |
| 24607 | } |
| 24608 | for task in tasks { |
| 24609 | let res = task.await.unwrap(); |
| 24610 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24611 | } |
| 24612 | |
| 24613 | let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await; |
| 24614 | assert_eq!(common::total(&res.body), 1, "one seat: {}", res.body); |
| 24615 | let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; |
| 24616 | assert_eq!( |
| 24617 | res.body["balance_minor"], -5_000, |
| 24618 | "one seat, one charge: {}", |
| 24619 | res.body |
| 24620 | ); |
| 24621 | } |
| 24622 | |
| 24623 | /// The same stampede on a menu with exactly one seat. Every racer is the *same* |
| 24624 | /// student, so between them they owe one seat — but each claims before it can |
| 24625 | /// know another already placed the row, and the losers' claims are refused as |
| 24626 | /// "full". Answering that with a 409 would refuse a student the booking that |
| 24627 | /// just succeeded on their behalf, so a refused claim looks for this very seat |
| 24628 | /// before it blames the cap. |
| 24629 | #[tokio::test(flavor = "multi_thread", worker_threads = 8)] |
| 24630 | async fn concurrent_bookings_of_one_seat_never_refuse_their_own_winner() { |
| 24631 | let (app, db) = app_and_db().await; |
| 24632 | let mgr = login_as(&app, &db, "tight_mgr", "manager").await; |
| 24633 | let stu = login(&app, "tight_stu").await; |
| 24634 | let res = send( |
| 24635 | &app, |
| 24636 | "POST", |
| 24637 | "/meals/menus", |
| 24638 | Some(&mgr), |
| 24639 | Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 1 })), |
| 24640 | ) |
| 24641 | .await; |
| 24642 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24643 | let menu = id_of(&res.body); |
| 24644 | |
| 24645 | let mut tasks = Vec::new(); |
| 24646 | for _ in 0..8 { |
| 24647 | let (app, stu, menu) = (app.clone(), stu.clone(), menu.clone()); |
| 24648 | tasks.push(tokio::spawn(async move { |
| 24649 | send( |
| 24650 | &app, |
| 24651 | "POST", |
| 24652 | &format!("/meals/menus/{menu}/bookings"), |
| 24653 | Some(&stu), |
| 24654 | Some(json!({})), |
| 24655 | ) |
| 24656 | .await |
| 24657 | })); |
| 24658 | } |
| 24659 | for task in tasks { |
| 24660 | let res = task.await.unwrap(); |
| 24661 | assert_eq!( |
| 24662 | res.status, |
| 24663 | StatusCode::CREATED, |
| 24664 | "one student, one seat, no refusal: {}", |
| 24665 | res.body |
| 24666 | ); |
| 24667 | } |
| 24668 | |
| 24669 | let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await; |
| 24670 | assert_eq!(common::total(&res.body), 1, "one seat: {}", res.body); |
| 24671 | let counted: i64 = sqlx::query_scalar("SELECT seats_booked FROM menu WHERE id = $1") |
| 24672 | .bind(&menu) |
| 24673 | .fetch_one(&db) |
| 24674 | .await |
| 24675 | .expect("counter read"); |
| 24676 | assert_eq!( |
| 24677 | counted, 1, |
| 24678 | "and the seat it cost is the one seat the menu has" |
| 24679 | ); |
| 24680 | } |
| 24681 | |
| 24682 | /// A repeat POST racing the cancel. A cancel that reverses whatever charge it |
| 24683 | /// can find, off a booking row read before the lock, can flip the seat to |
| 24684 | /// `cancelled` while the charge of a newer attempt stands — the student owes |
| 24685 | /// for a seat they do not hold. Keying the reversal to the attempt, and |
| 24686 | /// re-reading the row inside the lock, is what closes it. |
| 24687 | #[tokio::test(flavor = "multi_thread", worker_threads = 8)] |
| 24688 | async fn a_cancelled_seat_never_keeps_its_charge() { |
| 24689 | let (app, menu, stu) = priced_menu("race2", 3_000).await; |
| 24690 | let res = send( |
| 24691 | &app, |
| 24692 | "POST", |
| 24693 | &format!("/meals/menus/{menu}/bookings"), |
| 24694 | Some(&stu), |
| 24695 | Some(json!({})), |
| 24696 | ) |
| 24697 | .await; |
| 24698 | let booking = id_of(&res.body); |
| 24699 | |
| 24700 | for round in 0..20 { |
| 24701 | let book = { |
| 24702 | let (app, stu, menu) = (app.clone(), stu.clone(), menu.clone()); |
| 24703 | tokio::spawn(async move { |
| 24704 | send( |
| 24705 | &app, |
| 24706 | "POST", |
| 24707 | &format!("/meals/menus/{menu}/bookings"), |
| 24708 | Some(&stu), |
| 24709 | Some(json!({})), |
| 24710 | ) |
| 24711 | .await |
| 24712 | }) |
| 24713 | }; |
| 24714 | let cancel = { |
| 24715 | let (app, stu, booking) = (app.clone(), stu.clone(), booking.clone()); |
| 24716 | tokio::spawn(async move { |
| 24717 | send( |
| 24718 | &app, |
| 24719 | "DELETE", |
| 24720 | &format!("/meals/bookings/{booking}"), |
| 24721 | Some(&stu), |
| 24722 | None, |
| 24723 | ) |
| 24724 | .await |
| 24725 | }) |
| 24726 | }; |
| 24727 | book.await.unwrap(); |
| 24728 | cancel.await.unwrap(); |
| 24729 | // Settle the seat into `cancelled`, then the money must be back. |
| 24730 | send( |
| 24731 | &app, |
| 24732 | "DELETE", |
| 24733 | &format!("/meals/bookings/{booking}"), |
| 24734 | Some(&stu), |
| 24735 | None, |
| 24736 | ) |
| 24737 | .await; |
| 24738 | let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await; |
| 24739 | assert_eq!( |
| 24740 | common::items(&res.body)[0]["status"], |
| 24741 | "cancelled", |
| 24742 | "round {round}: {}", |
| 24743 | res.body |
| 24744 | ); |
| 24745 | let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; |
| 24746 | assert_eq!( |
| 24747 | res.body["balance_minor"], 0, |
| 24748 | "round {round}: a cancelled seat still owes: {}", |
| 24749 | res.body |
| 24750 | ); |
| 24751 | } |
| 24752 | } |
| 24753 | |
| 24754 | /// "Was free" is a recorded fact, not the absence of a charge. A seat taken |
| 24755 | /// off a dishless menu writes no ledger line; if that were all the code knew, |
| 24756 | /// a dish added afterwards would make the next POST of the *same held seat* |
| 24757 | /// look unbilled and charge it — a price the student never agreed to. |
| 24758 | #[tokio::test] |
| 24759 | async fn a_repeat_post_never_bills_a_seat_that_was_free_when_taken() { |
| 24760 | let (app, db) = app_and_db().await; |
| 24761 | let mgr = login_as(&app, &db, "free_mgr", "manager").await; |
| 24762 | let stu = login(&app, "free_stu").await; |
| 24763 | let res = send( |
| 24764 | &app, |
| 24765 | "POST", |
| 24766 | "/meals/menus", |
| 24767 | Some(&mgr), |
| 24768 | Some(json!({ "date": "2099-09-14", "slot": "lunch" })), |
| 24769 | ) |
| 24770 | .await; |
| 24771 | let menu = id_of(&res.body); |
| 24772 | |
| 24773 | // The seat is taken while the menu carries no dishes at all. |
| 24774 | let res = send( |
| 24775 | &app, |
| 24776 | "POST", |
| 24777 | &format!("/meals/menus/{menu}/bookings"), |
| 24778 | Some(&stu), |
| 24779 | Some(json!({})), |
| 24780 | ) |
| 24781 | .await; |
| 24782 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24783 | let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; |
| 24784 | assert_eq!(res.body["balance_minor"], 0, "a free menu bills nothing"); |
| 24785 | |
| 24786 | // The kitchen prices the menu afterwards. |
| 24787 | let res = send( |
| 24788 | &app, |
| 24789 | "POST", |
| 24790 | &format!("/meals/menus/{menu}/dishes"), |
| 24791 | Some(&mgr), |
| 24792 | Some(json!({ "name": "Pilav", "price_minor": 9_000 })), |
| 24793 | ) |
| 24794 | .await; |
| 24795 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24796 | |
| 24797 | // A refresh re-POSTs the seat the student already holds. |
| 24798 | let res = send( |
| 24799 | &app, |
| 24800 | "POST", |
| 24801 | &format!("/meals/menus/{menu}/bookings"), |
| 24802 | Some(&stu), |
| 24803 | Some(json!({})), |
| 24804 | ) |
| 24805 | .await; |
| 24806 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24807 | let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; |
| 24808 | assert_eq!( |
| 24809 | res.body["balance_minor"], 0, |
| 24810 | "a repeat POST on a held seat moves no money: {}", |
| 24811 | res.body |
| 24812 | ); |
| 24813 | |
| 24814 | // Cancelling and taking the seat again *is* a fresh attempt, at the price |
| 24815 | // the menu carries now — that is the same rule, not an exception to it. |
| 24816 | let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await; |
| 24817 | let booking = common::items(&res.body)[0]["id"] |
| 24818 | .as_str() |
| 24819 | .unwrap() |
| 24820 | .to_string(); |
| 24821 | send( |
| 24822 | &app, |
| 24823 | "DELETE", |
| 24824 | &format!("/meals/bookings/{booking}"), |
| 24825 | Some(&stu), |
| 24826 | None, |
| 24827 | ) |
| 24828 | .await; |
| 24829 | send( |
| 24830 | &app, |
| 24831 | "POST", |
| 24832 | &format!("/meals/menus/{menu}/bookings"), |
| 24833 | Some(&stu), |
| 24834 | Some(json!({})), |
| 24835 | ) |
| 24836 | .await; |
| 24837 | let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; |
| 24838 | assert_eq!(res.body["balance_minor"], -9_000, "{}", res.body); |
| 24839 | } |
| 24840 | |
| 24841 | /// A revoked parent link must go inert everywhere, `booked_by` included: the |
| 24842 | /// seats a parent paid for stay visible while the link lives, and vanish with |
| 24843 | /// it. The leak this catches was a *live* one — the unlinked parent kept |
| 24844 | /// watching the child's row, seeing a cancellation made after the unlink. |
| 24845 | #[tokio::test] |
| 24846 | async fn an_unlinked_parent_loses_the_live_view_of_a_childs_bookings() { |
| 24847 | let (app, db) = app_and_db().await; |
| 24848 | let admin = login_as(&app, &db, "lv_boss", "admin").await; |
| 24849 | let mgr = login_as(&app, &db, "lv_mgr", "manager").await; |
| 24850 | let mom = login_as(&app, &db, "lv_mom", "parent").await; |
| 24851 | let mom_id = me_id(&app, &mom).await; |
| 24852 | let kid = login(&app, "lv_kid").await; |
| 24853 | let kid_id = me_id(&app, &kid).await; |
| 24854 | let res = send( |
| 24855 | &app, |
| 24856 | "POST", |
| 24857 | &format!("/users/{mom_id}/students"), |
| 24858 | Some(&admin), |
| 24859 | Some(json!({ "user_id": kid_id })), |
| 24860 | ) |
| 24861 | .await; |
| 24862 | assert!(res.status.is_success(), "link: {}", res.body); |
| 24863 | let res = send( |
| 24864 | &app, |
| 24865 | "POST", |
| 24866 | "/meals/menus", |
| 24867 | Some(&mgr), |
| 24868 | Some(json!({ "date": "2027-08-01", "slot": "lunch" })), |
| 24869 | ) |
| 24870 | .await; |
| 24871 | let menu = id_of(&res.body); |
| 24872 | let res = send( |
| 24873 | &app, |
| 24874 | "POST", |
| 24875 | &format!("/meals/menus/{menu}/bookings"), |
| 24876 | Some(&mom), |
| 24877 | Some(json!({ "student_id": kid_id })), |
| 24878 | ) |
| 24879 | .await; |
| 24880 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24881 | let booking = id_of(&res.body); |
| 24882 | |
| 24883 | // While the link lives, mom sees the seat she booked. |
| 24884 | let res = send(&app, "GET", "/meals/bookings/me", Some(&mom), None).await; |
| 24885 | assert_eq!(common::total(&res.body), 1, "{}", res.body); |
| 24886 | |
| 24887 | let res = send( |
| 24888 | &app, |
| 24889 | "DELETE", |
| 24890 | &format!("/users/{mom_id}/students/{kid_id}"), |
| 24891 | Some(&admin), |
| 24892 | None, |
| 24893 | ) |
| 24894 | .await; |
| 24895 | assert!(res.status.is_success(), "unlink: {}", res.body); |
| 24896 | |
| 24897 | // The kid cancels *after* the link is gone — mom must not see that. |
| 24898 | let res = send( |
| 24899 | &app, |
| 24900 | "DELETE", |
| 24901 | &format!("/meals/bookings/{booking}"), |
| 24902 | Some(&kid), |
| 24903 | None, |
| 24904 | ) |
| 24905 | .await; |
| 24906 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24907 | let res = send(&app, "GET", "/meals/bookings/me", Some(&mom), None).await; |
| 24908 | assert_eq!( |
| 24909 | common::total(&res.body), |
| 24910 | 0, |
| 24911 | "an unlinked parent still reads the child's seat: {}", |
| 24912 | res.body |
| 24913 | ); |
| 24914 | // The child's own view is untouched. |
| 24915 | let res = send(&app, "GET", "/meals/bookings/me", Some(&kid), None).await; |
| 24916 | assert_eq!(common::total(&res.body), 1, "{}", res.body); |
| 24917 | } |
| 24918 | |
| 24919 | /// A cancel is two writes — the status flip, then the reversal — and axum drops |
| 24920 | /// the handler future when the client goes away (tab closed, proxy timeout). A |
| 24921 | /// drop landing between them freed the seat and left the charge standing, and |
| 24922 | /// while an already-cancelled row was a `409` **no route on the API could ever |
| 24923 | /// append the missing reversal**: the student stayed billed for a meal they had |
| 24924 | /// given back, and re-booking billed them a second time. So the cancel is |
| 24925 | /// idempotent — repeating it replays the reversal, keyed by (seat, attempt), so |
| 24926 | /// it heals the gap exactly once. |
| 24927 | #[tokio::test] |
| 24928 | async fn a_cancel_cut_short_mid_flight_is_healed_by_repeating_it() { |
| 24929 | let (app, menu, stu) = priced_menu("cutshort", 3_000).await; |
| 24930 | let res = send( |
| 24931 | &app, |
| 24932 | "POST", |
| 24933 | &format!("/meals/menus/{menu}/bookings"), |
| 24934 | Some(&stu), |
| 24935 | Some(json!({})), |
| 24936 | ) |
| 24937 | .await; |
| 24938 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24939 | let booking = id_of(&res.body); |
| 24940 | let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; |
| 24941 | assert_eq!(res.body["balance_minor"], -3_000, "{}", res.body); |
| 24942 | |
| 24943 | // The DELETE, polled just far enough to flip the row, then dropped. |
| 24944 | let req = Request::builder() |
| 24945 | .method("DELETE") |
| 24946 | .uri(format!("/meals/bookings/{booking}")) |
| 24947 | .header("cookie", &stu) |
| 24948 | .body(Body::empty()) |
| 24949 | .unwrap(); |
| 24950 | let mut fut = Box::pin(app.clone().oneshot(req)); |
| 24951 | for _ in 0..7 { |
| 24952 | assert!( |
| 24953 | futures_util::poll!(fut.as_mut()).is_pending(), |
| 24954 | "the cancel finished before it could be interrupted" |
| 24955 | ); |
| 24956 | tokio::task::yield_now().await; |
| 24957 | } |
| 24958 | drop(fut); |
| 24959 | |
| 24960 | // Repeating the cancel is the documented recovery: a `200`, not a `409`. |
| 24961 | let res = send( |
| 24962 | &app, |
| 24963 | "DELETE", |
| 24964 | &format!("/meals/bookings/{booking}"), |
| 24965 | Some(&stu), |
| 24966 | None, |
| 24967 | ) |
| 24968 | .await; |
| 24969 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24970 | assert_eq!(res.body["status"], "cancelled", "{}", res.body); |
| 24971 | let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; |
| 24972 | assert_eq!( |
| 24973 | res.body["balance_minor"], 0, |
| 24974 | "still billed for a cancelled seat: {}", |
| 24975 | res.body |
| 24976 | ); |
| 24977 | |
| 24978 | // And a third cancel refunds nothing extra — the reversal is keyed, not |
| 24979 | // counted — while a re-book is one fresh charge, not a doubled one. |
| 24980 | let res = send( |
| 24981 | &app, |
| 24982 | "DELETE", |
| 24983 | &format!("/meals/bookings/{booking}"), |
| 24984 | Some(&stu), |
| 24985 | None, |
| 24986 | ) |
| 24987 | .await; |
| 24988 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 24989 | let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; |
| 24990 | assert_eq!(res.body["balance_minor"], 0, "{}", res.body); |
| 24991 | let res = send( |
| 24992 | &app, |
| 24993 | "POST", |
| 24994 | &format!("/meals/menus/{menu}/bookings"), |
| 24995 | Some(&stu), |
| 24996 | Some(json!({})), |
| 24997 | ) |
| 24998 | .await; |
| 24999 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 25000 | let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; |
| 25001 | assert_eq!( |
| 25002 | res.body["balance_minor"], -3_000, |
| 25003 | "one meal, one charge: {}", |
| 25004 | res.body |
| 25005 | ); |
| 25006 | } |
| 25007 | |
| 25008 | /// A dish must never outlive its menu — the two orderings that decide it, with |
| 25009 | /// no race in either: adding to a menu that is already gone is a `404` that |
| 25010 | /// writes nothing, and deleting a menu takes the dishes on it with it. |
| 25011 | /// |
| 25012 | /// This deliberately does **not** race the two requests. It used to (40 rounds, |
| 25013 | /// two spawned tasks), and that assertion could not be honest here: the |
| 25014 | /// production guard is a store-detected conflict — both transactions write |
| 25015 | /// `menu:<id>`'s revision, so one is refused — and the old embedded engine |
| 25016 | /// did not conflict-check concurrent writes to one record at all. |
| 25017 | /// It committed **both** and answered `Ok` to each, orphaning 4 of 3600 and 13 |
| 25018 | /// of 6000 rounds, which surfaced as a whole-suite failure a few percent of |
| 25019 | /// runs. The same code orphaned 0 of 9600 rounds against a real server. So the |
| 25020 | /// concurrent claim lives where the store can testify about it — |
| 25021 | /// `db::menu::tests::a_child_written_inside_a_delete_never_outlives_the_menu`, |
| 25022 | /// `#[ignore]`d and run against a real server — and what stays here is the |
| 25023 | /// logic, pinned deterministically. |
| 25024 | #[tokio::test] |
| 25025 | async fn a_dish_never_lands_on_a_deleted_menu() { |
| 25026 | let (app, db) = app_and_db().await; |
| 25027 | let mgr = login_as(&app, &db, "orphan_mgr", "manager").await; |
| 25028 | let dishes_on = async |menu: &str| -> i64 { |
| 25029 | sqlx::query_scalar("SELECT count(*) FROM menu_dish WHERE menu = $1") |
| 25030 | .bind(menu) |
| 25031 | .fetch_one(&db) |
| 25032 | .await |
| 25033 | .unwrap() |
| 25034 | }; |
| 25035 | let publish = async |date: &str| -> String { |
| 25036 | let res = send( |
| 25037 | &app, |
| 25038 | "POST", |
| 25039 | "/meals/menus", |
| 25040 | Some(&mgr), |
| 25041 | Some(json!({ "date": date, "slot": "lunch" })), |
| 25042 | ) |
| 25043 | .await; |
| 25044 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 25045 | id_of(&res.body) |
| 25046 | }; |
| 25047 | let add_dish = async |menu: &str| -> common::Res { |
| 25048 | send( |
| 25049 | &app, |
| 25050 | "POST", |
| 25051 | &format!("/meals/menus/{menu}/dishes"), |
| 25052 | Some(&mgr), |
| 25053 | Some(json!({ "name": "Pilav", "price_minor": 1 })), |
| 25054 | ) |
| 25055 | .await |
| 25056 | }; |
| 25057 | |
| 25058 | // Gone first: the add is refused, and refusing must write nothing. |
| 25059 | let menu = publish("2027-10-01").await; |
| 25060 | let res = send( |
| 25061 | &app, |
| 25062 | "DELETE", |
| 25063 | &format!("/meals/menus/{menu}"), |
| 25064 | Some(&mgr), |
| 25065 | None, |
| 25066 | ) |
| 25067 | .await; |
| 25068 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 25069 | let res = add_dish(&menu).await; |
| 25070 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 25071 | assert_eq!( |
| 25072 | dishes_on(&menu).await, |
| 25073 | 0, |
| 25074 | "a refused add left a dish behind" |
| 25075 | ); |
| 25076 | |
| 25077 | // Dish first: the delete's cascade takes it. Menu ids are deterministic on |
| 25078 | // (date, slot), so a survivor would come back as a dish on the next menu |
| 25079 | // published for that meal — priced by the old one. |
| 25080 | let menu = publish("2027-10-01").await; |
| 25081 | let res = add_dish(&menu).await; |
| 25082 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 25083 | assert_eq!(dishes_on(&menu).await, 1); |
| 25084 | let res = send( |
| 25085 | &app, |
| 25086 | "DELETE", |
| 25087 | &format!("/meals/menus/{menu}"), |
| 25088 | Some(&mgr), |
| 25089 | None, |
| 25090 | ) |
| 25091 | .await; |
| 25092 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 25093 | assert_eq!( |
| 25094 | dishes_on(&menu).await, |
| 25095 | 0, |
| 25096 | "the delete's cascade left a dish on a menu that is gone" |
| 25097 | ); |
| 25098 | } |
| 25099 | |
| 25100 | // --- school payments ----------------------------------------------------- |
| 25101 | |
| 25102 | /// Create a fee plan as `cookie` (asserts 201); returns its id. Installments |
| 25103 | /// are `(amount_minor, due_at)` pairs, billed in the order given. |
| 25104 | async fn create_plan( |
| 25105 | app: &axum::Router, |
| 25106 | cookie: &str, |
| 25107 | name: &str, |
| 25108 | installments: &[(i64, i64)], |
| 25109 | ) -> String { |
| 25110 | let body = json!({ |
| 25111 | "name": name, |
| 25112 | "installments": installments |
| 25113 | .iter() |
| 25114 | .map(|(amount, due)| json!({ "amount_minor": amount, "due_at": due })) |
| 25115 | .collect::<Vec<_>>(), |
| 25116 | }); |
| 25117 | let res = send(app, "POST", "/payments/plans", Some(cookie), Some(body)).await; |
| 25118 | assert_eq!( |
| 25119 | res.status, |
| 25120 | StatusCode::CREATED, |
| 25121 | "create plan {name}: {}", |
| 25122 | res.body |
| 25123 | ); |
| 25124 | id_of(&res.body) |
| 25125 | } |
| 25126 | |
| 25127 | /// Place `students` on `plan` (no assertion — the per-student outcomes are |
| 25128 | /// what most of these tests are about). |
| 25129 | async fn assign_plan( |
| 25130 | app: &axum::Router, |
| 25131 | cookie: &str, |
| 25132 | plan: &str, |
| 25133 | students: &[&str], |
| 25134 | ) -> common::Res { |
| 25135 | send( |
| 25136 | app, |
| 25137 | "POST", |
| 25138 | &format!("/payments/plans/{plan}/assignments"), |
| 25139 | Some(cookie), |
| 25140 | Some(json!({ "student_ids": students })), |
| 25141 | ) |
| 25142 | .await |
| 25143 | } |
| 25144 | |
| 25145 | /// One student's ledger lines, newest first (asserts 200). |
| 25146 | async fn ledger_of(app: &axum::Router, cookie: &str, student: &str) -> Vec<serde_json::Value> { |
| 25147 | let res = send( |
| 25148 | app, |
| 25149 | "GET", |
| 25150 | &format!("/payments/ledger/{student}"), |
| 25151 | Some(cookie), |
| 25152 | None, |
| 25153 | ) |
| 25154 | .await; |
| 25155 | assert_eq!( |
| 25156 | res.status, |
| 25157 | StatusCode::OK, |
| 25158 | "ledger of {student}: {}", |
| 25159 | res.body |
| 25160 | ); |
| 25161 | common::items(&res.body).clone() |
| 25162 | } |
| 25163 | |
| 25164 | /// The id of the student's `charge` line worth exactly `amount_minor`. |
| 25165 | async fn charge_worth(app: &axum::Router, cookie: &str, student: &str, amount: i64) -> String { |
| 25166 | let lines = ledger_of(app, cookie, student).await; |
| 25167 | let line = lines |
| 25168 | .iter() |
| 25169 | .find(|line| line["kind"] == "charge" && line["amount_minor"] == amount) |
| 25170 | .unwrap_or_else(|| panic!("no charge worth {amount} in {lines:?}")); |
| 25171 | id_of(line) |
| 25172 | } |
| 25173 | |
| 25174 | /// Record money in against `charge` (no assertion). |
| 25175 | async fn pay(app: &axum::Router, cookie: &str, charge: &str, amount: i64) -> common::Res { |
| 25176 | send( |
| 25177 | app, |
| 25178 | "POST", |
| 25179 | "/payments/credits", |
| 25180 | Some(cookie), |
| 25181 | Some(json!({ "charge_id": charge, "amount_minor": amount })), |
| 25182 | ) |
| 25183 | .await |
| 25184 | } |
| 25185 | |
| 25186 | /// Hand money back against `credit` (no assertion). |
| 25187 | async fn refund(app: &axum::Router, cookie: &str, credit: &str, amount: i64) -> common::Res { |
| 25188 | send( |
| 25189 | app, |
| 25190 | "POST", |
| 25191 | "/payments/refunds", |
| 25192 | Some(cookie), |
| 25193 | Some(json!({ "credit_id": credit, "amount_minor": amount })), |
| 25194 | ) |
| 25195 | .await |
| 25196 | } |
| 25197 | |
| 25198 | /// Record money in against `charge`, carrying a client idempotence key. |
| 25199 | async fn pay_keyed( |
| 25200 | app: &axum::Router, |
| 25201 | cookie: &str, |
| 25202 | charge: &str, |
| 25203 | amount: i64, |
| 25204 | key: &str, |
| 25205 | ) -> common::Res { |
| 25206 | send( |
| 25207 | app, |
| 25208 | "POST", |
| 25209 | "/payments/credits", |
| 25210 | Some(cookie), |
| 25211 | Some(json!({ "charge_id": charge, "amount_minor": amount, "request_key": key })), |
| 25212 | ) |
| 25213 | .await |
| 25214 | } |
| 25215 | |
| 25216 | /// Hand money back against `credit`, carrying a client idempotence key. |
| 25217 | async fn refund_keyed( |
| 25218 | app: &axum::Router, |
| 25219 | cookie: &str, |
| 25220 | credit: &str, |
| 25221 | amount: i64, |
| 25222 | key: &str, |
| 25223 | ) -> common::Res { |
| 25224 | send( |
| 25225 | app, |
| 25226 | "POST", |
| 25227 | "/payments/refunds", |
| 25228 | Some(cookie), |
| 25229 | Some(json!({ "credit_id": credit, "amount_minor": amount, "request_key": key })), |
| 25230 | ) |
| 25231 | .await |
| 25232 | } |
| 25233 | |
| 25234 | /// Undo `line` (no assertion). |
| 25235 | async fn reverse(app: &axum::Router, cookie: &str, line: &str) -> common::Res { |
| 25236 | send( |
| 25237 | app, |
| 25238 | "POST", |
| 25239 | "/payments/reversals", |
| 25240 | Some(cookie), |
| 25241 | Some(json!({ "line_id": line })), |
| 25242 | ) |
| 25243 | .await |
| 25244 | } |
| 25245 | |
| 25246 | /// Row count of `table`, straight from the database — a response is never |
| 25247 | /// proof that a line landed; stored state is. |
| 25248 | async fn pay_row_count(db: &hezarfen_backend::database::Database, table: &str) -> i64 { |
| 25249 | sqlx::query_scalar::<sqlx::Postgres, i64>(sqlx::AssertSqlSafe(format!( |
| 25250 | "SELECT count(*) FROM {table}" |
| 25251 | ))) |
| 25252 | .fetch_one(db) |
| 25253 | .await |
| 25254 | .unwrap() |
| 25255 | } |
| 25256 | |
| 25257 | /// A manager, a student, and a plan the student is on — the starting point of |
| 25258 | /// every money test below. Returns `(manager cookie, student id, plan id)`. |
| 25259 | async fn billed_student( |
| 25260 | app: &axum::Router, |
| 25261 | db: &hezarfen_backend::database::Database, |
| 25262 | installments: &[(i64, i64)], |
| 25263 | ) -> (String, String, String) { |
| 25264 | let mgr = login_as(app, db, "bursar", "manager").await; |
| 25265 | let student = login(app, "ali").await; |
| 25266 | let student_id = me_id(app, &student).await; |
| 25267 | let plan = create_plan(app, &mgr, "Yearly", installments).await; |
| 25268 | let res = assign_plan(app, &mgr, &plan, &[&student_id]).await; |
| 25269 | assert_eq!(res.status, StatusCode::OK, "assign: {}", res.body); |
| 25270 | (mgr, student_id, plan) |
| 25271 | } |
| 25272 | |
| 25273 | #[tokio::test] |
| 25274 | async fn fee_plans_are_manager_written_and_freeze_once_assigned() { |
| 25275 | let (app, db) = app_and_db().await; |
| 25276 | let mgr = login_as(&app, &db, "bursar", "manager").await; |
| 25277 | |
| 25278 | let plan = create_plan(&app, &mgr, "Yearly", &[(10_000, 1_000), (20_000, 2_000)]).await; |
| 25279 | let res = send( |
| 25280 | &app, |
| 25281 | "GET", |
| 25282 | &format!("/payments/plans/{plan}"), |
| 25283 | Some(&mgr), |
| 25284 | None, |
| 25285 | ) |
| 25286 | .await; |
| 25287 | assert_eq!(res.status, StatusCode::OK); |
| 25288 | assert_eq!(res.body["name"], "Yearly"); |
| 25289 | assert_eq!(res.body["installments"].as_array().unwrap().len(), 2); |
| 25290 | assert_eq!(res.body["installments"][1]["amount_minor"], 20_000); |
| 25291 | |
| 25292 | // Editing and deleting are both free while nobody is on the plan. |
| 25293 | let res = send( |
| 25294 | &app, |
| 25295 | "PATCH", |
| 25296 | &format!("/payments/plans/{plan}"), |
| 25297 | Some(&mgr), |
| 25298 | Some(json!({ "name": "Yearly (revised)" })), |
| 25299 | ) |
| 25300 | .await; |
| 25301 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 25302 | assert_eq!(res.body["name"], "Yearly (revised)"); |
| 25303 | |
| 25304 | let doomed = create_plan(&app, &mgr, "Scrapped", &[(500, 1_000)]).await; |
| 25305 | let res = send( |
| 25306 | &app, |
| 25307 | "DELETE", |
| 25308 | &format!("/payments/plans/{doomed}"), |
| 25309 | Some(&mgr), |
| 25310 | None, |
| 25311 | ) |
| 25312 | .await; |
| 25313 | assert_eq!( |
| 25314 | res.status, |
| 25315 | StatusCode::NO_CONTENT, |
| 25316 | "delete before assignment" |
| 25317 | ); |
| 25318 | |
| 25319 | // One assignment freezes both: the charges are frozen copies, so an edit |
| 25320 | // would only make the plan and the money disagree. |
| 25321 | let student = login(&app, "ali").await; |
| 25322 | let student_id = me_id(&app, &student).await; |
| 25323 | let res = assign_plan(&app, &mgr, &plan, &[&student_id]).await; |
| 25324 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 25325 | |
| 25326 | let res = send( |
| 25327 | &app, |
| 25328 | "PATCH", |
| 25329 | &format!("/payments/plans/{plan}"), |
| 25330 | Some(&mgr), |
| 25331 | Some(json!({ "name": "Too late" })), |
| 25332 | ) |
| 25333 | .await; |
| 25334 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 25335 | let res = send( |
| 25336 | &app, |
| 25337 | "DELETE", |
| 25338 | &format!("/payments/plans/{plan}"), |
| 25339 | Some(&mgr), |
| 25340 | None, |
| 25341 | ) |
| 25342 | .await; |
| 25343 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 25344 | // The refused edit changed nothing. |
| 25345 | let res = send( |
| 25346 | &app, |
| 25347 | "GET", |
| 25348 | &format!("/payments/plans/{plan}"), |
| 25349 | Some(&mgr), |
| 25350 | None, |
| 25351 | ) |
| 25352 | .await; |
| 25353 | assert_eq!(res.body["name"], "Yearly (revised)"); |
| 25354 | } |
| 25355 | |
| 25356 | #[tokio::test] |
| 25357 | async fn assigning_bills_every_installment_and_replays_without_billing_twice() { |
| 25358 | let (app, db) = app_and_db().await; |
| 25359 | let mgr = login_as(&app, &db, "bursar", "manager").await; |
| 25360 | let ali = login(&app, "ali").await; |
| 25361 | let ali_id = me_id(&app, &ali).await; |
| 25362 | let veli = login(&app, "veli").await; |
| 25363 | let veli_id = me_id(&app, &veli).await; |
| 25364 | |
| 25365 | let plan = create_plan( |
| 25366 | &app, |
| 25367 | &mgr, |
| 25368 | "Yearly", |
| 25369 | &[(10_000, 1_000), (20_000, 2_000), (30_000, 3_000)], |
| 25370 | ) |
| 25371 | .await; |
| 25372 | let res = assign_plan(&app, &mgr, &plan, &[&ali_id, &veli_id]).await; |
| 25373 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 25374 | let outcomes = res.body.as_array().expect("one outcome per student"); |
| 25375 | assert_eq!(outcomes.len(), 2); |
| 25376 | assert!(outcomes.iter().all(|o| o["status"] == "assigned")); |
| 25377 | |
| 25378 | // 2 students × 3 installments, counted in the database — a 200 is not |
| 25379 | // evidence that six lines landed. |
| 25380 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 6); |
| 25381 | assert_eq!(pay_row_count(&db, "fee_plan_assignment").await, 2); |
| 25382 | |
| 25383 | // The same call again: reported as a replay, and it bills nothing. |
| 25384 | let res = assign_plan(&app, &mgr, &plan, &[&ali_id, &veli_id]).await; |
| 25385 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 25386 | assert!( |
| 25387 | res.body |
| 25388 | .as_array() |
| 25389 | .unwrap() |
| 25390 | .iter() |
| 25391 | .all(|o| o["status"] == "already_assigned"), |
| 25392 | "{}", |
| 25393 | res.body |
| 25394 | ); |
| 25395 | assert_eq!( |
| 25396 | pay_row_count(&db, "payment_ledger").await, |
| 25397 | 6, |
| 25398 | "a replayed assignment must not append a second set of charges" |
| 25399 | ); |
| 25400 | assert_eq!(pay_row_count(&db, "fee_plan_assignment").await, 2); |
| 25401 | } |
| 25402 | |
| 25403 | #[tokio::test] |
| 25404 | async fn partial_payments_accumulate_up_to_the_charge_and_no_further() { |
| 25405 | let (app, db) = app_and_db().await; |
| 25406 | let (mgr, student_id, _) = billed_student(&app, &db, &[(100, 1_000)]).await; |
| 25407 | let charge = charge_worth(&app, &mgr, &student_id, 100).await; |
| 25408 | |
| 25409 | assert_eq!( |
| 25410 | pay(&app, &mgr, &charge, 40).await.status, |
| 25411 | StatusCode::CREATED |
| 25412 | ); |
| 25413 | assert_eq!( |
| 25414 | pay(&app, &mgr, &charge, 60).await.status, |
| 25415 | StatusCode::CREATED |
| 25416 | ); |
| 25417 | let res = pay(&app, &mgr, &charge, 1).await; |
| 25418 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 25419 | |
| 25420 | // The refused payment left no line behind: 1 charge + 2 credits. |
| 25421 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 3); |
| 25422 | let res = send( |
| 25423 | &app, |
| 25424 | "GET", |
| 25425 | &format!("/payments/balance/{student_id}"), |
| 25426 | Some(&mgr), |
| 25427 | None, |
| 25428 | ) |
| 25429 | .await; |
| 25430 | assert_eq!(res.body["balance_minor"], 0, "paid in full"); |
| 25431 | } |
| 25432 | |
| 25433 | #[tokio::test] |
| 25434 | async fn a_refund_frees_the_room_it_took_and_a_reversal_takes_it_back() { |
| 25435 | let (app, db) = app_and_db().await; |
| 25436 | let (mgr, student_id, _) = billed_student(&app, &db, &[(100, 1_000)]).await; |
| 25437 | let charge = charge_worth(&app, &mgr, &student_id, 100).await; |
| 25438 | |
| 25439 | let credit = pay(&app, &mgr, &charge, 100).await; |
| 25440 | assert_eq!(credit.status, StatusCode::CREATED); |
| 25441 | let credit_id = id_of(&credit.body); |
| 25442 | |
| 25443 | let refunded = refund(&app, &mgr, &credit_id, 100).await; |
| 25444 | assert_eq!(refunded.status, StatusCode::CREATED, "{}", refunded.body); |
| 25445 | let refund_id = id_of(&refunded.body); |
| 25446 | |
| 25447 | // Money handed back is money owed again, so the charge is payable again. |
| 25448 | let again = pay(&app, &mgr, &charge, 100).await; |
| 25449 | assert_eq!( |
| 25450 | again.status, |
| 25451 | StatusCode::CREATED, |
| 25452 | "a refunded charge must be payable again: {}", |
| 25453 | again.body |
| 25454 | ); |
| 25455 | |
| 25456 | // Undoing the refund says the money never left — the room it freed is |
| 25457 | // taken back, and a further payment is over-paying. |
| 25458 | assert_eq!( |
| 25459 | reverse(&app, &mgr, &refund_id).await.status, |
| 25460 | StatusCode::CREATED |
| 25461 | ); |
| 25462 | let res = pay(&app, &mgr, &charge, 1).await; |
| 25463 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 25464 | } |
| 25465 | |
| 25466 | #[tokio::test] |
| 25467 | async fn reversal_undoes_a_charge_once_and_refuses_a_payment() { |
| 25468 | let (app, db) = app_and_db().await; |
| 25469 | let (mgr, student_id, _) = billed_student(&app, &db, &[(100, 1_000)]).await; |
| 25470 | let charge = charge_worth(&app, &mgr, &student_id, 100).await; |
| 25471 | |
| 25472 | let first = reverse(&app, &mgr, &charge).await; |
| 25473 | assert_eq!(first.status, StatusCode::CREATED, "{}", first.body); |
| 25474 | // Keyed `<line>_r`, so a retry reverses the same line rather than again. |
| 25475 | let replay = reverse(&app, &mgr, &charge).await; |
| 25476 | assert_eq!(replay.status, StatusCode::CREATED, "{}", replay.body); |
| 25477 | assert_eq!(id_of(&replay.body), id_of(&first.body)); |
| 25478 | assert_eq!( |
| 25479 | pay_row_count(&db, "payment_ledger").await, |
| 25480 | 2, |
| 25481 | "a replayed reversal must not append a second line" |
| 25482 | ); |
| 25483 | |
| 25484 | // A reversed charge is no longer owed, so it takes no money — and the |
| 25485 | // refusal must say *reversed*. The reversal folds in at `+amount` exactly |
| 25486 | // as a payment does, so the cap alone cannot tell the two apart, and |
| 25487 | // "already paid in full" would send a bursar hunting for money that never |
| 25488 | // arrived against a charge nobody ever paid a kuruş on. |
| 25489 | let res = pay(&app, &mgr, &charge, 1).await; |
| 25490 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 25491 | let message = res.body["error"].as_str().unwrap_or_default(); |
| 25492 | assert!( |
| 25493 | message.contains("reversed"), |
| 25494 | "the refusal must name the reversal, not a payment: {message}" |
| 25495 | ); |
| 25496 | assert!( |
| 25497 | !message.contains("paid in full"), |
| 25498 | "no money ever arrived on this charge: {message}" |
| 25499 | ); |
| 25500 | assert_eq!( |
| 25501 | pay_row_count(&db, "payment_ledger").await, |
| 25502 | 2, |
| 25503 | "the refused payment must not have landed" |
| 25504 | ); |
| 25505 | |
| 25506 | // A mistaken payment is corrected with a refund, never a reversal. |
| 25507 | let (mgr2, other_id, _) = { |
| 25508 | let student = login(&app, "veli").await; |
| 25509 | let other_id = me_id(&app, &student).await; |
| 25510 | let plan = create_plan(&app, &mgr, "Second", &[(100, 1_000)]).await; |
| 25511 | assign_plan(&app, &mgr, &plan, &[&other_id]).await; |
| 25512 | (mgr.clone(), other_id, plan) |
| 25513 | }; |
| 25514 | let other_charge = charge_worth(&app, &mgr2, &other_id, 100).await; |
| 25515 | let credit = pay(&app, &mgr2, &other_charge, 100).await; |
| 25516 | let credit_id = id_of(&credit.body); |
| 25517 | let res = reverse(&app, &mgr2, &credit_id).await; |
| 25518 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 25519 | |
| 25520 | let refunded = refund(&app, &mgr2, &credit_id, 100).await; |
| 25521 | assert_eq!(refunded.status, StatusCode::CREATED); |
| 25522 | let res = reverse(&app, &mgr2, &id_of(&refunded.body)).await; |
| 25523 | assert_eq!( |
| 25524 | res.status, |
| 25525 | StatusCode::CREATED, |
| 25526 | "a refund may be reversed: {}", |
| 25527 | res.body |
| 25528 | ); |
| 25529 | } |
| 25530 | |
| 25531 | #[tokio::test] |
| 25532 | async fn the_statement_reports_overdue_and_its_rollup_matches_the_balance() { |
| 25533 | let (app, db) = app_and_db().await; |
| 25534 | let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000; |
| 25535 | // One installment already past due, one not. |
| 25536 | let (mgr, student_id, _) = billed_student(&app, &db, &[(100, 1_000), (200, future)]).await; |
| 25537 | |
| 25538 | let statement = |cookie: String, who: String| { |
| 25539 | let app = app.clone(); |
| 25540 | async move { |
| 25541 | let res = send( |
| 25542 | &app, |
| 25543 | "GET", |
| 25544 | &format!("/payments/statement/{who}"), |
| 25545 | Some(&cookie), |
| 25546 | None, |
| 25547 | ) |
| 25548 | .await; |
| 25549 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 25550 | res.body |
| 25551 | } |
| 25552 | }; |
| 25553 | |
| 25554 | let body = statement(mgr.clone(), student_id.clone()).await; |
| 25555 | let row = |body: &serde_json::Value, amount: i64| { |
| 25556 | body["entries"]["items"] |
| 25557 | .as_array() |
| 25558 | .unwrap() |
| 25559 | .iter() |
| 25560 | .find(|entry| entry["amount_minor"] == amount) |
| 25561 | .unwrap_or_else(|| panic!("no statement row worth {amount}")) |
| 25562 | .clone() |
| 25563 | }; |
| 25564 | let overdue = row(&body, 100); |
| 25565 | assert_eq!(overdue["plan_name"], "Yearly"); |
| 25566 | assert_eq!(overdue["outstanding_minor"], 100); |
| 25567 | assert_eq!( |
| 25568 | overdue["overdue"], true, |
| 25569 | "unpaid and its due date has passed" |
| 25570 | ); |
| 25571 | assert_eq!(row(&body, 200)["overdue"], false, "not due yet"); |
| 25572 | assert_eq!(body["balance_minor"], -300); |
| 25573 | |
| 25574 | // Pay the overdue one off, then hand a quarter of it back. |
| 25575 | let charge = charge_worth(&app, &mgr, &student_id, 100).await; |
| 25576 | let credit = pay(&app, &mgr, &charge, 100).await; |
| 25577 | let body = statement(mgr.clone(), student_id.clone()).await; |
| 25578 | let settled = row(&body, 100); |
| 25579 | assert_eq!(settled["credited_minor"], 100); |
| 25580 | assert_eq!(settled["outstanding_minor"], 0); |
| 25581 | assert_eq!(settled["overdue"], false, "settled, however late it was"); |
| 25582 | |
| 25583 | assert_eq!( |
| 25584 | refund(&app, &mgr, &id_of(&credit.body), 25).await.status, |
| 25585 | StatusCode::CREATED |
| 25586 | ); |
| 25587 | let body = statement(mgr.clone(), student_id.clone()).await; |
| 25588 | let clawed_back = row(&body, 100); |
| 25589 | assert_eq!(clawed_back["credited_minor"], 100); |
| 25590 | assert_eq!(clawed_back["refunded_minor"], 25); |
| 25591 | // 100 billed - 100 paid + 25 handed back, and owed again means overdue again. |
| 25592 | assert_eq!(clawed_back["outstanding_minor"], 25); |
| 25593 | assert_eq!(clawed_back["overdue"], true); |
| 25594 | assert_eq!(body["balance_minor"], -225); |
| 25595 | |
| 25596 | // The student's own statement is the same document, and the balance |
| 25597 | // endpoint agrees with the fold behind it. |
| 25598 | let student = send( |
| 25599 | &app, |
| 25600 | "POST", |
| 25601 | "/auth/login", |
| 25602 | None, |
| 25603 | Some(json!({ "username": "ali", "password": "secret1" })), |
| 25604 | ) |
| 25605 | .await |
| 25606 | .cookie |
| 25607 | .unwrap(); |
| 25608 | let own = send(&app, "GET", "/payments/statement/me", Some(&student), None).await; |
| 25609 | assert_eq!(own.status, StatusCode::OK); |
| 25610 | assert_eq!(own.body["balance_minor"], -225); |
| 25611 | assert_eq!(own.body["entries"]["items"].as_array().unwrap().len(), 2); |
| 25612 | let own = send(&app, "GET", "/payments/balance/me", Some(&student), None).await; |
| 25613 | assert_eq!(own.body["balance_minor"], -225); |
| 25614 | } |
| 25615 | |
| 25616 | #[tokio::test] |
| 25617 | async fn payment_reads_are_self_parent_or_manager_and_writes_are_manager_only() { |
| 25618 | let (app, db) = app_and_db().await; |
| 25619 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 25620 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 25621 | let parent = login_as(&app, &db, "mom", "parent").await; |
| 25622 | let parent_id = me_id(&app, &parent).await; |
| 25623 | let ali = login(&app, "ali").await; |
| 25624 | let ali_id = me_id(&app, &ali).await; |
| 25625 | let veli = login(&app, "veli").await; |
| 25626 | let veli_id = me_id(&app, &veli).await; |
| 25627 | |
| 25628 | // Mom is tied to Ali only. |
| 25629 | let res = send( |
| 25630 | &app, |
| 25631 | "POST", |
| 25632 | &format!("/users/{parent_id}/students"), |
| 25633 | Some(&admin), |
| 25634 | Some(json!({ "user_id": ali_id })), |
| 25635 | ) |
| 25636 | .await; |
| 25637 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 25638 | |
| 25639 | let plan = create_plan(&app, &admin, "Yearly", &[(100, 1_000)]).await; |
| 25640 | assert_eq!( |
| 25641 | assign_plan(&app, &admin, &plan, &[&ali_id, &veli_id]) |
| 25642 | .await |
| 25643 | .status, |
| 25644 | StatusCode::OK |
| 25645 | ); |
| 25646 | let charge = charge_worth(&app, &admin, &ali_id, 100).await; |
| 25647 | |
| 25648 | let reads = |who: &str| { |
| 25649 | [ |
| 25650 | format!("/payments/ledger/{who}"), |
| 25651 | format!("/payments/statement/{who}"), |
| 25652 | format!("/payments/balance/{who}"), |
| 25653 | ] |
| 25654 | }; |
| 25655 | for uri in reads(&ali_id) { |
| 25656 | // Own record, always. |
| 25657 | assert_eq!( |
| 25658 | send(&app, "GET", &uri, Some(&ali), None).await.status, |
| 25659 | StatusCode::OK, |
| 25660 | "{uri} as the student themselves" |
| 25661 | ); |
| 25662 | // A live parent link, and manager+. |
| 25663 | assert_eq!( |
| 25664 | send(&app, "GET", &uri, Some(&parent), None).await.status, |
| 25665 | StatusCode::OK, |
| 25666 | "{uri} as the linked parent" |
| 25667 | ); |
| 25668 | assert_eq!( |
| 25669 | send(&app, "GET", &uri, Some(&admin), None).await.status, |
| 25670 | StatusCode::OK, |
| 25671 | "{uri} as an admin" |
| 25672 | ); |
| 25673 | // Not a teacher: what a family owes the school is not classroom |
| 25674 | // information, so this is narrower than every other per-student report. |
| 25675 | assert_eq!( |
| 25676 | send(&app, "GET", &uri, Some(&teacher), None).await.status, |
| 25677 | StatusCode::FORBIDDEN, |
| 25678 | "{uri} as a teacher" |
| 25679 | ); |
| 25680 | } |
| 25681 | for uri in reads(&veli_id) { |
| 25682 | // Another student's record: not the student, not the unlinked parent. |
| 25683 | assert_eq!( |
| 25684 | send(&app, "GET", &uri, Some(&ali), None).await.status, |
| 25685 | StatusCode::FORBIDDEN, |
| 25686 | "{uri} as another student" |
| 25687 | ); |
| 25688 | assert_eq!( |
| 25689 | send(&app, "GET", &uri, Some(&parent), None).await.status, |
| 25690 | StatusCode::FORBIDDEN, |
| 25691 | "{uri} as a parent with no link to them" |
| 25692 | ); |
| 25693 | } |
| 25694 | |
| 25695 | // Writes — and the plan routes, which are money administration end to end. |
| 25696 | for cookie in [&ali, &parent, &teacher] { |
| 25697 | assert_eq!( |
| 25698 | send(&app, "GET", "/payments/plans", Some(cookie), None) |
| 25699 | .await |
| 25700 | .status, |
| 25701 | StatusCode::FORBIDDEN |
| 25702 | ); |
| 25703 | assert_eq!( |
| 25704 | send( |
| 25705 | &app, |
| 25706 | "POST", |
| 25707 | "/payments/plans", |
| 25708 | Some(cookie), |
| 25709 | Some( |
| 25710 | json!({ "name": "Mine", "installments": [{ "amount_minor": 1, "due_at": 0 }] }) |
| 25711 | ), |
| 25712 | ) |
| 25713 | .await |
| 25714 | .status, |
| 25715 | StatusCode::FORBIDDEN |
| 25716 | ); |
| 25717 | assert_eq!( |
| 25718 | assign_plan(&app, cookie, &plan, &[&ali_id]).await.status, |
| 25719 | StatusCode::FORBIDDEN |
| 25720 | ); |
| 25721 | assert_eq!( |
| 25722 | pay(&app, cookie, &charge, 1).await.status, |
| 25723 | StatusCode::FORBIDDEN |
| 25724 | ); |
| 25725 | assert_eq!( |
| 25726 | refund(&app, cookie, &charge, 1).await.status, |
| 25727 | StatusCode::FORBIDDEN |
| 25728 | ); |
| 25729 | assert_eq!( |
| 25730 | reverse(&app, cookie, &charge).await.status, |
| 25731 | StatusCode::FORBIDDEN |
| 25732 | ); |
| 25733 | } |
| 25734 | // Nothing above landed: one charge per student, and no other line. |
| 25735 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 2); |
| 25736 | } |
| 25737 | |
| 25738 | /// A client retry after a network timeout must not charge a family twice. The |
| 25739 | /// key is what makes the retry the *same* line, so the interesting case is a |
| 25740 | /// payment that filled its charge exactly: the cap, consulted first, would |
| 25741 | /// refuse precisely the payment that landed. |
| 25742 | #[tokio::test] |
| 25743 | async fn a_replayed_request_key_returns_the_same_payment_instead_of_a_second_one() { |
| 25744 | let (app, db) = app_and_db().await; |
| 25745 | let (mgr, student_id, _) = |
| 25746 | billed_student(&app, &db, &[(100, 1_000), (60, 2_000), (30, 3_000)]).await; |
| 25747 | let charge = |amount| { |
| 25748 | let app = app.clone(); |
| 25749 | let mgr = mgr.clone(); |
| 25750 | let student_id = student_id.clone(); |
| 25751 | async move { charge_worth(&app, &mgr, &student_id, amount).await } |
| 25752 | }; |
| 25753 | let full = charge(100).await; |
| 25754 | |
| 25755 | // This payment fills the charge to the penny. |
| 25756 | let first = pay_keyed(&app, &mgr, &full, 100, "receipt-114").await; |
| 25757 | assert_eq!(first.status, StatusCode::CREATED, "{}", first.body); |
| 25758 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 4); |
| 25759 | |
| 25760 | let replay = pay_keyed(&app, &mgr, &full, 100, "receipt-114").await; |
| 25761 | assert_eq!( |
| 25762 | replay.status, |
| 25763 | StatusCode::CREATED, |
| 25764 | "a replay of a cap-filling payment must return the line, not a 409: {}", |
| 25765 | replay.body |
| 25766 | ); |
| 25767 | assert_eq!(id_of(&replay.body), id_of(&first.body)); |
| 25768 | assert_eq!( |
| 25769 | pay_row_count(&db, "payment_ledger").await, |
| 25770 | 4, |
| 25771 | "the replay must not append a second credit" |
| 25772 | ); |
| 25773 | |
| 25774 | // The same key for different money is a client bug, not a replay. |
| 25775 | let mismatch = pay_keyed(&app, &mgr, &full, 50, "receipt-114").await; |
| 25776 | assert_eq!(mismatch.status, StatusCode::CONFLICT, "{}", mismatch.body); |
| 25777 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 4); |
| 25778 | |
| 25779 | // Two different keys are two payments, and the cap still applies to them. |
| 25780 | let sixty = charge(60).await; |
| 25781 | let a = pay_keyed(&app, &mgr, &sixty, 30, "a").await; |
| 25782 | let b = pay_keyed(&app, &mgr, &sixty, 30, "b").await; |
| 25783 | assert_eq!(a.status, StatusCode::CREATED); |
| 25784 | assert_eq!(b.status, StatusCode::CREATED, "{}", b.body); |
| 25785 | assert_ne!(id_of(&a.body), id_of(&b.body)); |
| 25786 | assert_eq!( |
| 25787 | pay_keyed(&app, &mgr, &sixty, 1, "c").await.status, |
| 25788 | StatusCode::CONFLICT, |
| 25789 | "a fresh key does not buy room the charge does not have" |
| 25790 | ); |
| 25791 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 6); |
| 25792 | |
| 25793 | // No key: the old semantics stay exactly as they were — two identical |
| 25794 | // posts are two payments, because a desk taking the same amount twice is. |
| 25795 | let thirty = charge(30).await; |
| 25796 | let one = pay(&app, &mgr, &thirty, 10).await; |
| 25797 | let two = pay(&app, &mgr, &thirty, 10).await; |
| 25798 | assert_eq!(one.status, StatusCode::CREATED); |
| 25799 | assert_eq!(two.status, StatusCode::CREATED); |
| 25800 | assert_ne!(id_of(&one.body), id_of(&two.body)); |
| 25801 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 8); |
| 25802 | } |
| 25803 | |
| 25804 | #[tokio::test] |
| 25805 | async fn a_replayed_request_key_returns_the_same_refund_instead_of_a_second_one() { |
| 25806 | let (app, db) = app_and_db().await; |
| 25807 | let (mgr, student_id, _) = billed_student(&app, &db, &[(100, 1_000)]).await; |
| 25808 | let charge = charge_worth(&app, &mgr, &student_id, 100).await; |
| 25809 | let credit = pay(&app, &mgr, &charge, 100).await; |
| 25810 | let credit_id = id_of(&credit.body); |
| 25811 | |
| 25812 | let first = refund_keyed(&app, &mgr, &credit_id, 100, "back-1").await; |
| 25813 | assert_eq!(first.status, StatusCode::CREATED, "{}", first.body); |
| 25814 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 3); |
| 25815 | |
| 25816 | // The refund used the credit up, so the cap would refuse a second one — |
| 25817 | // the replay must still answer with the line that exists. |
| 25818 | let replay = refund_keyed(&app, &mgr, &credit_id, 100, "back-1").await; |
| 25819 | assert_eq!(replay.status, StatusCode::CREATED, "{}", replay.body); |
| 25820 | assert_eq!(id_of(&replay.body), id_of(&first.body)); |
| 25821 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 3); |
| 25822 | |
| 25823 | let mismatch = refund_keyed(&app, &mgr, &credit_id, 25, "back-1").await; |
| 25824 | assert_eq!(mismatch.status, StatusCode::CONFLICT, "{}", mismatch.body); |
| 25825 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 3); |
| 25826 | |
| 25827 | // The balance is what it was after the single refund: money out once. |
| 25828 | let res = send( |
| 25829 | &app, |
| 25830 | "GET", |
| 25831 | &format!("/payments/balance/{student_id}"), |
| 25832 | Some(&mgr), |
| 25833 | None, |
| 25834 | ) |
| 25835 | .await; |
| 25836 | assert_eq!(res.body["balance_minor"], -100); |
| 25837 | } |
| 25838 | |
| 25839 | /// The statement pages its per-charge rows — but the money it reports is folded |
| 25840 | /// from every line, so `balance_minor` must not move between pages. |
| 25841 | #[tokio::test] |
| 25842 | async fn the_statement_pages_its_rows_without_moving_the_balance() { |
| 25843 | let (app, db) = app_and_db().await; |
| 25844 | let (mgr, student_id, _) = |
| 25845 | billed_student(&app, &db, &[(100, 1_000), (60, 2_000), (30, 3_000)]).await; |
| 25846 | let statement = |query: &str| { |
| 25847 | let app = app.clone(); |
| 25848 | let uri = format!("/payments/statement/{student_id}{query}"); |
| 25849 | let mgr = mgr.clone(); |
| 25850 | async move { |
| 25851 | let res = send(&app, "GET", &uri, Some(&mgr), None).await; |
| 25852 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 25853 | res.body |
| 25854 | } |
| 25855 | }; |
| 25856 | |
| 25857 | let all = statement("").await; |
| 25858 | assert_eq!(all["entries"]["items"].as_array().unwrap().len(), 3); |
| 25859 | assert_eq!(all["entries"]["total"], 3); |
| 25860 | assert_eq!(all["balance_minor"], -190); |
| 25861 | |
| 25862 | let head = statement("?limit=2&offset=0").await; |
| 25863 | assert_eq!(head["entries"]["items"].as_array().unwrap().len(), 2); |
| 25864 | assert_eq!(head["entries"]["total"], 3); |
| 25865 | assert_eq!(head["entries"]["limit"], 2); |
| 25866 | assert_eq!(head["entries"]["offset"], 0); |
| 25867 | assert_eq!(head["balance_minor"], -190); |
| 25868 | |
| 25869 | let tail = statement("?limit=2&offset=2").await; |
| 25870 | assert_eq!( |
| 25871 | tail["entries"]["items"].as_array().unwrap().len(), |
| 25872 | 1, |
| 25873 | "the tail returns the remainder" |
| 25874 | ); |
| 25875 | assert_eq!(tail["balance_minor"], -190, "every page folds every line"); |
| 25876 | // The window is a slice of one order, so the pages do not overlap. |
| 25877 | let page_ids = |body: &serde_json::Value| { |
| 25878 | body["entries"]["items"] |
| 25879 | .as_array() |
| 25880 | .unwrap() |
| 25881 | .iter() |
| 25882 | .map(|entry| entry["charge_id"].as_str().unwrap().to_string()) |
| 25883 | .collect::<Vec<_>>() |
| 25884 | }; |
| 25885 | let mut seen = page_ids(&head); |
| 25886 | seen.extend(page_ids(&tail)); |
| 25887 | seen.sort(); |
| 25888 | seen.dedup(); |
| 25889 | assert_eq!(seen.len(), 3, "two pages, three distinct charges"); |
| 25890 | |
| 25891 | let res = send( |
| 25892 | &app, |
| 25893 | "GET", |
| 25894 | &format!("/payments/statement/{student_id}?limit=0"), |
| 25895 | Some(&mgr), |
| 25896 | None, |
| 25897 | ) |
| 25898 | .await; |
| 25899 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 25900 | } |
| 25901 | |
| 25902 | #[tokio::test] |
| 25903 | async fn payment_lists_page_through_the_envelope() { |
| 25904 | let (app, db) = app_and_db().await; |
| 25905 | let mgr = login_as(&app, &db, "bursar", "manager").await; |
| 25906 | for n in 0..3 { |
| 25907 | create_plan(&app, &mgr, &format!("Plan {n}"), &[(100, 1_000)]).await; |
| 25908 | } |
| 25909 | let plan = create_plan(&app, &mgr, "Shared", &[(100, 1_000), (200, 2_000)]).await; |
| 25910 | let mut students = Vec::new(); |
| 25911 | for name in ["ali", "veli", "ayse"] { |
| 25912 | let cookie = login(&app, name).await; |
| 25913 | students.push(me_id(&app, &cookie).await); |
| 25914 | } |
| 25915 | let ids: Vec<&str> = students.iter().map(String::as_str).collect(); |
| 25916 | assert_eq!( |
| 25917 | assign_plan(&app, &mgr, &plan, &ids).await.status, |
| 25918 | StatusCode::OK |
| 25919 | ); |
| 25920 | |
| 25921 | let res = send( |
| 25922 | &app, |
| 25923 | "GET", |
| 25924 | "/payments/plans?limit=2&offset=0", |
| 25925 | Some(&mgr), |
| 25926 | None, |
| 25927 | ) |
| 25928 | .await; |
| 25929 | assert_eq!(common::total(&res.body), 4); |
| 25930 | assert_eq!(common::items(&res.body).len(), 2); |
| 25931 | assert_eq!(res.body["limit"], 2); |
| 25932 | assert_eq!(res.body["offset"], 0); |
| 25933 | |
| 25934 | let res = send( |
| 25935 | &app, |
| 25936 | "GET", |
| 25937 | &format!("/payments/plans/{plan}/assignments?limit=2&offset=2"), |
| 25938 | Some(&mgr), |
| 25939 | None, |
| 25940 | ) |
| 25941 | .await; |
| 25942 | assert_eq!(common::total(&res.body), 3); |
| 25943 | assert_eq!( |
| 25944 | common::items(&res.body).len(), |
| 25945 | 1, |
| 25946 | "tail returns the remainder" |
| 25947 | ); |
| 25948 | |
| 25949 | let student = &students[0]; |
| 25950 | let res = send( |
| 25951 | &app, |
| 25952 | "GET", |
| 25953 | &format!("/payments/ledger/{student}?limit=1&offset=0"), |
| 25954 | Some(&mgr), |
| 25955 | None, |
| 25956 | ) |
| 25957 | .await; |
| 25958 | assert_eq!(common::total(&res.body), 2, "both installments were billed"); |
| 25959 | assert_eq!(common::items(&res.body).len(), 1); |
| 25960 | // Unpaged is still the whole list. |
| 25961 | assert_eq!(ledger_of(&app, &mgr, student).await.len(), 2); |
| 25962 | } |
| 25963 | |
| 25964 | #[tokio::test] |
| 25965 | async fn assignment_rejects_a_non_student_without_billing_anyone() { |
| 25966 | let (app, db) = app_and_db().await; |
| 25967 | let mgr = login_as(&app, &db, "bursar", "manager").await; |
| 25968 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 25969 | let teacher_id = me_id(&app, &teacher).await; |
| 25970 | let ali = login(&app, "ali").await; |
| 25971 | let ali_id = me_id(&app, &ali).await; |
| 25972 | |
| 25973 | let plan = create_plan(&app, &mgr, "Yearly", &[(100, 1_000)]).await; |
| 25974 | let res = assign_plan(&app, &mgr, &plan, &[&teacher_id, &ali_id]).await; |
| 25975 | assert_eq!( |
| 25976 | res.status, |
| 25977 | StatusCode::OK, |
| 25978 | "one bad id never loses the batch" |
| 25979 | ); |
| 25980 | let outcomes = res.body.as_array().unwrap(); |
| 25981 | assert_eq!(outcomes[0]["student_id"], teacher_id.as_str()); |
| 25982 | assert_eq!(outcomes[0]["status"], "rejected"); |
| 25983 | assert_eq!(outcomes[0]["reason"], "no such student"); |
| 25984 | assert_eq!(outcomes[1]["status"], "assigned"); |
| 25985 | |
| 25986 | // Only the student was billed, and only the student was placed. |
| 25987 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 1); |
| 25988 | assert_eq!(pay_row_count(&db, "fee_plan_assignment").await, 1); |
| 25989 | assert!(ledger_of(&app, &mgr, &teacher_id).await.is_empty()); |
| 25990 | } |
| 25991 | |
| 25992 | #[tokio::test] |
| 25993 | async fn bulk_assignment_is_capped_at_two_hundred_students() { |
| 25994 | let (app, db) = app_and_db().await; |
| 25995 | let mgr = login_as(&app, &db, "bursar", "manager").await; |
| 25996 | let plan = create_plan(&app, &mgr, "Yearly", &[(100, 1_000)]).await; |
| 25997 | |
| 25998 | let too_many: Vec<String> = (0..MAX_FEE_PLAN_ASSIGN_STUDENTS + 1) |
| 25999 | .map(|n| format!("nobody{n}")) |
| 26000 | .collect(); |
| 26001 | let ids: Vec<&str> = too_many.iter().map(String::as_str).collect(); |
| 26002 | let res = assign_plan(&app, &mgr, &plan, &ids).await; |
| 26003 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 26004 | // Refused whole, not partly: nothing was written before the count check. |
| 26005 | assert_eq!(pay_row_count(&db, "fee_plan_assignment").await, 0); |
| 26006 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 0); |
| 26007 | } |
| 26008 | |
| 26009 | // --- whiteboards --------------------------------------------------------- |
| 26010 | |
| 26011 | /// Open a board (asserts 201); returns its id. |
| 26012 | async fn create_board( |
| 26013 | app: &axum::Router, |
| 26014 | cookie: &str, |
| 26015 | title: &str, |
| 26016 | participants: &[&str], |
| 26017 | ) -> String { |
| 26018 | let res = send( |
| 26019 | app, |
| 26020 | "POST", |
| 26021 | "/boards", |
| 26022 | Some(cookie), |
| 26023 | Some(json!({ "title": title, "participants": participants })), |
| 26024 | ) |
| 26025 | .await; |
| 26026 | assert_eq!( |
| 26027 | res.status, |
| 26028 | StatusCode::CREATED, |
| 26029 | "create board: {}", |
| 26030 | res.body |
| 26031 | ); |
| 26032 | id_of(&res.body) |
| 26033 | } |
| 26034 | |
| 26035 | /// Draw one mark straight through the domain. Drawing is a WebSocket surface |
| 26036 | /// (`tests/e2e.rs` owns the room), but every REST read below needs marks on the |
| 26037 | /// board first, and the two caps below need one refused at a boundary no HTTP |
| 26038 | /// route can reach. |
| 26039 | async fn draw( |
| 26040 | db: &Database, |
| 26041 | board: &str, |
| 26042 | author: &str, |
| 26043 | epoch: i64, |
| 26044 | payload: &str, |
| 26045 | ) -> Result<BoardStroke, hezarfen_backend::error::AppError> { |
| 26046 | hezarfen_backend::db::board_stroke::append( |
| 26047 | db, |
| 26048 | &BoardId::from_key(board), |
| 26049 | &UserId::from_key(author), |
| 26050 | payload, |
| 26051 | epoch, |
| 26052 | ) |
| 26053 | .await |
| 26054 | } |
| 26055 | |
| 26056 | /// The board row as the store holds it — never the response body, which cannot |
| 26057 | /// prove a counter moved (src/domain/cap.rs:44-49). |
| 26058 | async fn stored_board(db: &Database, board: &str) -> Option<Board> { |
| 26059 | hezarfen_backend::db::board::read(db, &BoardId::from_key(board)) |
| 26060 | .await |
| 26061 | .unwrap() |
| 26062 | } |
| 26063 | |
| 26064 | /// Every stroke row of a board, oldest first, straight out of the table. |
| 26065 | async fn stroke_rows(db: &Database, board: &str) -> Vec<BoardStroke> { |
| 26066 | sqlx::query_as::<_, BoardStroke>("SELECT * FROM board_stroke WHERE board = $1 ORDER BY id") |
| 26067 | .bind(Uuid::parse_str(board).expect("board id")) |
| 26068 | .fetch_all(db) |
| 26069 | .await |
| 26070 | .unwrap() |
| 26071 | } |
| 26072 | |
| 26073 | /// The stored `[epoch_stroke_count, total_stroke_count]` pair. |
| 26074 | async fn stored_counters(db: &Database, board: &str) -> Vec<i64> { |
| 26075 | let (epoch_stroke_count, total_stroke_count) = |
| 26076 | sqlx::query_as("SELECT epoch_stroke_count, total_stroke_count FROM board WHERE id = $1") |
| 26077 | .bind(Uuid::parse_str(board).expect("board id")) |
| 26078 | .fetch_one(db) |
| 26079 | .await |
| 26080 | .unwrap(); |
| 26081 | vec![epoch_stroke_count, total_stroke_count] |
| 26082 | } |
| 26083 | |
| 26084 | async fn set_counters(db: &Database, board: &str, epoch: i64, total: i64) { |
| 26085 | sqlx::query("UPDATE board SET epoch_stroke_count = $2, total_stroke_count = $3 WHERE id = $1") |
| 26086 | .bind(Uuid::parse_str(board).expect("board id")) |
| 26087 | .bind(epoch) |
| 26088 | .bind(total) |
| 26089 | .execute(db) |
| 26090 | .await |
| 26091 | .unwrap(); |
| 26092 | } |
| 26093 | |
| 26094 | /// The creator's stored `board_count` — the authority on how many boards they |
| 26095 | /// hold, so the per-creator cap is asserted here and not off a 409. |
| 26096 | async fn stored_board_count(db: &Database, user: &str) -> i64 { |
| 26097 | sqlx::query_scalar("SELECT board_count FROM app_user WHERE id = $1") |
| 26098 | .bind(Uuid::parse_str(user).expect("user id")) |
| 26099 | .fetch_one(db) |
| 26100 | .await |
| 26101 | .unwrap() |
| 26102 | } |
| 26103 | |
| 26104 | /// Every id-scoped board route, with a body where the route needs one. The |
| 26105 | /// `PATCH` arms are split because they carry different rights: `title` is every |
| 26106 | /// participant's, `participants` and `locked` are the creator's alone. |
| 26107 | fn board_routes(id: &str) -> Vec<(&'static str, String, Option<serde_json::Value>)> { |
| 26108 | vec![ |
| 26109 | ("GET", format!("/boards/{id}"), None), |
| 26110 | ("GET", format!("/boards/{id}/strokes"), None), |
| 26111 | ("GET", format!("/boards/{id}/history"), None), |
| 26112 | ("GET", format!("/boards/{id}/epochs"), None), |
| 26113 | ( |
| 26114 | "PATCH", |
| 26115 | format!("/boards/{id}"), |
| 26116 | Some(json!({"title": "x"})), |
| 26117 | ), |
| 26118 | ( |
| 26119 | "PATCH", |
| 26120 | format!("/boards/{id}"), |
| 26121 | Some(json!({"participants": []})), |
| 26122 | ), |
| 26123 | ( |
| 26124 | "PATCH", |
| 26125 | format!("/boards/{id}"), |
| 26126 | Some(json!({"locked": true})), |
| 26127 | ), |
| 26128 | ("POST", format!("/boards/{id}/clear"), None), |
| 26129 | ("POST", format!("/boards/{id}/close"), None), |
| 26130 | ("DELETE", format!("/boards/{id}"), None), |
| 26131 | ] |
| 26132 | } |
| 26133 | |
| 26134 | /// A board that exists must be indistinguishable from one that does not, on |
| 26135 | /// every single route — a 403 anywhere here would tell an outsider the school |
| 26136 | /// holds a board with that id, and the id list is guessable from nothing else. |
| 26137 | #[tokio::test] |
| 26138 | async fn every_board_route_is_a_404_for_an_outsider() { |
| 26139 | let (app, db) = app_and_db().await; |
| 26140 | let ali = login(&app, "ali").await; |
| 26141 | let veli = login(&app, "veli").await; |
| 26142 | let zeynep = login(&app, "zeynep").await; |
| 26143 | let veli_id = me_id(&app, &veli).await; |
| 26144 | let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await; |
| 26145 | draw(&db, &board, &me_id(&app, &ali).await, 0, "{\"p\":[1,2]}") |
| 26146 | .await |
| 26147 | .unwrap(); |
| 26148 | |
| 26149 | // The real board and an id that was never minted answer identically. |
| 26150 | let ghost = board_routes("nosuchboard"); |
| 26151 | for (n, (method, uri, body)) in board_routes(&board).into_iter().enumerate() { |
| 26152 | let res = send(&app, method, &uri, Some(&zeynep), body).await; |
| 26153 | assert_eq!( |
| 26154 | res.status, |
| 26155 | StatusCode::NOT_FOUND, |
| 26156 | "{method} {uri} must 404 for an outsider, got {}", |
| 26157 | res.body |
| 26158 | ); |
| 26159 | let (gm, gu, gb) = ghost[n].clone(); |
| 26160 | let gone = send(&app, gm, &gu, Some(&zeynep), gb).await; |
| 26161 | assert_eq!( |
| 26162 | res.status, gone.status, |
| 26163 | "{method} {uri} must answer exactly like a board that does not exist" |
| 26164 | ); |
| 26165 | assert_eq!(res.body, gone.body, "{method} {uri} bodies must match too"); |
| 26166 | } |
| 26167 | |
| 26168 | // The list route leaks nothing either, and none of the refusals above |
| 26169 | // touched the row: still open, still one stroke, still the same roster. |
| 26170 | let res = send(&app, "GET", "/boards", Some(&zeynep), None).await; |
| 26171 | assert_eq!(res.status, StatusCode::OK); |
| 26172 | assert_eq!(common::total(&res.body), 0, "an outsider lists no boards"); |
| 26173 | let stored = stored_board(&db, &board).await.expect("board survived"); |
| 26174 | assert_eq!(stored.get_title().as_str(), "Geometri"); |
| 26175 | assert_eq!(stored.get_epoch(), 0); |
| 26176 | assert!(!stored.is_locked()); |
| 26177 | assert!(stored.get_closed_at().is_none()); |
| 26178 | assert_eq!(stored.get_participants().len(), 1); |
| 26179 | assert_eq!(stroke_rows(&db, &board).await.len(), 1); |
| 26180 | |
| 26181 | // Opening a board is nobody's privilege — the outsider gets their own. |
| 26182 | let mine = create_board(&app, &zeynep, "Kendi tahtam", &[]).await; |
| 26183 | assert_ne!(mine, board); |
| 26184 | } |
| 26185 | |
| 26186 | /// The `parent` role has no whiteboard at all. Three cuts in one test, because |
| 26187 | /// they only work together: a parent cannot open a board, cannot be *named* on |
| 26188 | /// one, and — the stale-row case, forced here by writing a parent straight into |
| 26189 | /// a roster — still gets the outsider's `404` rather than a `403` that would |
| 26190 | /// confirm the board is there. |
| 26191 | #[tokio::test] |
| 26192 | async fn a_parent_gets_no_whiteboard_at_all() { |
| 26193 | let (app, db) = app_and_db().await; |
| 26194 | let ali = login(&app, "ali").await; |
| 26195 | let anne = login_as(&app, &db, "anne", "parent").await; |
| 26196 | let anne_id = me_id(&app, &anne).await; |
| 26197 | |
| 26198 | // 1. A parent cannot open one. A 403, not a 404: no board exists to hide. |
| 26199 | let res = send( |
| 26200 | &app, |
| 26201 | "POST", |
| 26202 | "/boards", |
| 26203 | Some(&anne), |
| 26204 | Some(json!({ "title": "Gizli", "participants": [] })), |
| 26205 | ) |
| 26206 | .await; |
| 26207 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 26208 | // And nothing was written on the way to that refusal. |
| 26209 | assert_eq!(stored_board_count(&db, &anne_id).await, 0); |
| 26210 | |
| 26211 | // 2. A parent cannot be named on one either — refused whole, so the board |
| 26212 | // is not created half-invited. |
| 26213 | let res = send( |
| 26214 | &app, |
| 26215 | "POST", |
| 26216 | "/boards", |
| 26217 | Some(&ali), |
| 26218 | Some(json!({ "title": "Geometri", "participants": [&anne_id] })), |
| 26219 | ) |
| 26220 | .await; |
| 26221 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 26222 | assert_eq!(stored_board_count(&db, &me_id(&app, &ali).await).await, 0); |
| 26223 | |
| 26224 | // The same refusal on the way in through PATCH, on a board that does exist. |
| 26225 | let board = create_board(&app, &ali, "Geometri", &[]).await; |
| 26226 | let res = send( |
| 26227 | &app, |
| 26228 | "PATCH", |
| 26229 | &format!("/boards/{board}"), |
| 26230 | Some(&ali), |
| 26231 | Some(json!({ "participants": [&anne_id] })), |
| 26232 | ) |
| 26233 | .await; |
| 26234 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 26235 | assert!( |
| 26236 | stored_board(&db, &board) |
| 26237 | .await |
| 26238 | .unwrap() |
| 26239 | .get_participants() |
| 26240 | .is_empty(), |
| 26241 | "a refused roster change must leave the old roster" |
| 26242 | ); |
| 26243 | |
| 26244 | // 3. The stale row: a parent already on a roster, written before this rule. |
| 26245 | // Every id-scoped route must still answer exactly like a board that was |
| 26246 | // never minted — a 403 anywhere here leaks the board's existence. |
| 26247 | let board_uuid = Uuid::parse_str(&board).expect("board id"); |
| 26248 | sqlx::query("DELETE FROM board_participant WHERE board = $1") |
| 26249 | .bind(board_uuid) |
| 26250 | .execute(&db) |
| 26251 | .await |
| 26252 | .unwrap(); |
| 26253 | sqlx::query( |
| 26254 | "INSERT INTO board_participant (board, participant) |
| 26255 | SELECT $1, t.x FROM unnest($2::uuid[]) AS t(x)", |
| 26256 | ) |
| 26257 | .bind(board_uuid) |
| 26258 | .bind(vec![Uuid::parse_str(&anne_id).expect("user id")]) |
| 26259 | .execute(&db) |
| 26260 | .await |
| 26261 | .unwrap(); |
| 26262 | let ghost = board_routes("nosuchboard"); |
| 26263 | for (n, (method, uri, body)) in board_routes(&board).into_iter().enumerate() { |
| 26264 | let res = send(&app, method, &uri, Some(&anne), body).await; |
| 26265 | assert_eq!( |
| 26266 | res.status, |
| 26267 | StatusCode::NOT_FOUND, |
| 26268 | "{method} {uri} must 404 for a parent, got {}", |
| 26269 | res.body |
| 26270 | ); |
| 26271 | let (gm, gu, gb) = ghost[n].clone(); |
| 26272 | let gone = send(&app, gm, &gu, Some(&anne), gb).await; |
| 26273 | assert_eq!(res.status, gone.status, "{method} {uri}"); |
| 26274 | assert_eq!(res.body, gone.body, "{method} {uri} bodies must match too"); |
| 26275 | } |
| 26276 | // The list route is barred outright — nothing to hide, so a 403 is honest. |
| 26277 | let res = send(&app, "GET", "/boards", Some(&anne), None).await; |
| 26278 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 26279 | // None of it disturbed the board. |
| 26280 | assert!(stored_board(&db, &board).await.is_some()); |
| 26281 | } |
| 26282 | |
| 26283 | /// The read-modify-write half of the same defect. A roster the creator was just |
| 26284 | /// served carries a participant who has since stopped qualifying, and echoing |
| 26285 | /// it back used to be a `400` — the invite list frozen by a value the server |
| 26286 | /// itself handed over. It is dropped now, silently. What must NOT be dropped is |
| 26287 | /// a *newly named* unqualified id: that split is the whole of the fix, and |
| 26288 | /// backwards it would let any caller seed a roster with anyone. |
| 26289 | #[tokio::test] |
| 26290 | async fn a_creator_can_patch_back_a_roster_holding_a_participant_who_no_longer_qualifies() { |
| 26291 | let (app, db) = app_and_db().await; |
| 26292 | let ali = login(&app, "ali").await; |
| 26293 | let veli = login(&app, "veli").await; |
| 26294 | let veli_id = me_id(&app, &veli).await; |
| 26295 | let anne = login_as(&app, &db, "anne", "parent").await; |
| 26296 | let anne_id = me_id(&app, &anne).await; |
| 26297 | |
| 26298 | let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await; |
| 26299 | // Demoted straight in the store: `set_role` would sweep the roster, and the |
| 26300 | // stale row is exactly the shape a volume written before that sweep holds. |
| 26301 | common::set_role(&db, "veli", "parent").await; |
| 26302 | // What the client sees, and sends straight back. |
| 26303 | let read = send(&app, "GET", &format!("/boards/{board}"), Some(&ali), None).await; |
| 26304 | assert_eq!(read.status, StatusCode::OK, "{}", read.body); |
| 26305 | let roster = read.body["participants"].clone(); |
| 26306 | assert_eq!( |
| 26307 | roster, |
| 26308 | json!([&veli_id]), |
| 26309 | "the stale id is served, not hidden" |
| 26310 | ); |
| 26311 | |
| 26312 | let res = send( |
| 26313 | &app, |
| 26314 | "PATCH", |
| 26315 | &format!("/boards/{board}"), |
| 26316 | Some(&ali), |
| 26317 | Some(json!({ "participants": roster })), |
| 26318 | ) |
| 26319 | .await; |
| 26320 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 26321 | assert_eq!(res.body["participants"], json!([]), "{}", res.body); |
| 26322 | assert!( |
| 26323 | stored_board(&db, &board) |
| 26324 | .await |
| 26325 | .unwrap() |
| 26326 | .get_participants() |
| 26327 | .is_empty(), |
| 26328 | "the drop is stored, not just rendered" |
| 26329 | ); |
| 26330 | |
| 26331 | // The other half: a fresh unqualified id still fails the whole call, and |
| 26332 | // both flavours of it — a parent, and an id no user answers to. |
| 26333 | for id in [anne_id.as_str(), "nosuchuser"] { |
| 26334 | let res = send( |
| 26335 | &app, |
| 26336 | "PATCH", |
| 26337 | &format!("/boards/{board}"), |
| 26338 | Some(&ali), |
| 26339 | Some(json!({ "participants": [id] })), |
| 26340 | ) |
| 26341 | .await; |
| 26342 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{id}: {}", res.body); |
| 26343 | } |
| 26344 | assert!( |
| 26345 | stored_board(&db, &board) |
| 26346 | .await |
| 26347 | .unwrap() |
| 26348 | .get_participants() |
| 26349 | .is_empty() |
| 26350 | ); |
| 26351 | } |
| 26352 | |
| 26353 | /// The roster is spelled `participants` on the way in, out and through `PATCH`. |
| 26354 | /// It used to be `participant_ids` on `POST` alone, and with serde ignoring the |
| 26355 | /// unknown key a client that posted back a board it had just read got a `201` |
| 26356 | /// for a board it was silently alone on. A misspelled roster must now be |
| 26357 | /// refused, not dropped — the assert is the *stored* row, because the response |
| 26358 | /// echoing an empty list is exactly what the old bug looked like. |
| 26359 | #[tokio::test] |
| 26360 | async fn a_misspelled_roster_is_refused_instead_of_silently_dropped() { |
| 26361 | let (app, db) = common::app_and_db().await; |
| 26362 | let ali = login(&app, "ali").await; |
| 26363 | let ali_id = me_id(&app, &ali).await; |
| 26364 | let veli = login(&app, "veli").await; |
| 26365 | let veli_id = me_id(&app, &veli).await; |
| 26366 | |
| 26367 | let res = send( |
| 26368 | &app, |
| 26369 | "POST", |
| 26370 | "/boards", |
| 26371 | Some(&ali), |
| 26372 | Some(json!({ "title": "Geometri", "participant_ids": [&veli_id] })), |
| 26373 | ) |
| 26374 | .await; |
| 26375 | assert_eq!( |
| 26376 | res.status, |
| 26377 | StatusCode::UNPROCESSABLE_ENTITY, |
| 26378 | "the old spelling must not open a board: {}", |
| 26379 | res.body |
| 26380 | ); |
| 26381 | // Refused whole: no solo board, and no seat spent on one. |
| 26382 | assert_eq!(stored_board_count(&db, &ali_id).await, 0); |
| 26383 | |
| 26384 | let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await; |
| 26385 | let stored = stored_board(&db, &board).await.unwrap(); |
| 26386 | assert_eq!( |
| 26387 | stored |
| 26388 | .get_participants() |
| 26389 | .iter() |
| 26390 | .map(|user| user.key().to_string()) |
| 26391 | .collect::<Vec<_>>(), |
| 26392 | vec![veli_id], |
| 26393 | "the roster must reach the row, not just the response" |
| 26394 | ); |
| 26395 | } |
| 26396 | |
| 26397 | /// The other half of the two-tier line: a participant sees the board and may |
| 26398 | /// re-title it, but the four commands and the roster/lock arms of `PATCH` are |
| 26399 | /// the creator's alone — a 403, because hiding a board they are already |
| 26400 | /// rendering would be a lie their client cannot act on. |
| 26401 | #[tokio::test] |
| 26402 | async fn a_participant_reads_and_retitles_but_cannot_command() { |
| 26403 | let (app, db) = app_and_db().await; |
| 26404 | let ali = login(&app, "ali").await; |
| 26405 | let veli = login(&app, "veli").await; |
| 26406 | let ali_id = me_id(&app, &ali).await; |
| 26407 | let veli_id = me_id(&app, &veli).await; |
| 26408 | let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await; |
| 26409 | draw(&db, &board, &veli_id, 0, "{\"p\":[1,2]}") |
| 26410 | .await |
| 26411 | .unwrap(); |
| 26412 | |
| 26413 | // Every read, and the title arm: the participant's. |
| 26414 | for uri in [ |
| 26415 | format!("/boards/{board}"), |
| 26416 | format!("/boards/{board}/strokes"), |
| 26417 | format!("/boards/{board}/history"), |
| 26418 | format!("/boards/{board}/epochs"), |
| 26419 | "/boards".to_string(), |
| 26420 | ] { |
| 26421 | let res = send(&app, "GET", &uri, Some(&veli), None).await; |
| 26422 | assert_eq!(res.status, StatusCode::OK, "GET {uri}: {}", res.body); |
| 26423 | } |
| 26424 | let res = send(&app, "GET", "/boards", Some(&veli), None).await; |
| 26425 | assert_eq!(common::total(&res.body), 1, "an invitee lists the board"); |
| 26426 | |
| 26427 | let res = send( |
| 26428 | &app, |
| 26429 | "PATCH", |
| 26430 | &format!("/boards/{board}"), |
| 26431 | Some(&veli), |
| 26432 | Some(json!({ "title": "Cebir" })), |
| 26433 | ) |
| 26434 | .await; |
| 26435 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 26436 | assert_eq!( |
| 26437 | stored_board(&db, &board) |
| 26438 | .await |
| 26439 | .unwrap() |
| 26440 | .get_title() |
| 26441 | .as_str(), |
| 26442 | "Cebir", |
| 26443 | "the re-title really landed" |
| 26444 | ); |
| 26445 | |
| 26446 | // The creator's four commands, and the two creator-only PATCH arms. |
| 26447 | for (method, uri, body) in [ |
| 26448 | ( |
| 26449 | "PATCH", |
| 26450 | format!("/boards/{board}"), |
| 26451 | Some(json!({"participants": []})), |
| 26452 | ), |
| 26453 | ( |
| 26454 | "PATCH", |
| 26455 | format!("/boards/{board}"), |
| 26456 | Some(json!({"locked": true})), |
| 26457 | ), |
| 26458 | ("POST", format!("/boards/{board}/clear"), None), |
| 26459 | ("POST", format!("/boards/{board}/close"), None), |
| 26460 | ("DELETE", format!("/boards/{board}"), None), |
| 26461 | ] { |
| 26462 | let res = send(&app, method, &uri, Some(&veli), body).await; |
| 26463 | assert_eq!( |
| 26464 | res.status, |
| 26465 | StatusCode::FORBIDDEN, |
| 26466 | "{method} {uri} must 403 for a non-creator participant, got {}", |
| 26467 | res.body |
| 26468 | ); |
| 26469 | } |
| 26470 | |
| 26471 | // Not one of those refusals wrote anything. |
| 26472 | let stored = stored_board(&db, &board).await.expect("board survived"); |
| 26473 | assert_eq!(stored.get_participants().len(), 1, "roster untouched"); |
| 26474 | assert!(!stored.is_locked(), "lock untouched"); |
| 26475 | assert_eq!(stored.get_epoch(), 0, "no clear landed"); |
| 26476 | assert!(stored.get_closed_at().is_none(), "not closed"); |
| 26477 | assert_eq!(stroke_rows(&db, &board).await.len(), 1, "stroke kept"); |
| 26478 | assert_eq!(stored.get_creator().key(), ali_id); |
| 26479 | |
| 26480 | // And the creator's own PATCH arms do work — the 403s above are about the |
| 26481 | // caller, not a route that refuses everyone. |
| 26482 | let res = send( |
| 26483 | &app, |
| 26484 | "PATCH", |
| 26485 | &format!("/boards/{board}"), |
| 26486 | Some(&ali), |
| 26487 | Some(json!({ "locked": true })), |
| 26488 | ) |
| 26489 | .await; |
| 26490 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 26491 | assert!(stored_board(&db, &board).await.unwrap().is_locked()); |
| 26492 | } |
| 26493 | |
| 26494 | /// The user's core requirement, over HTTP: a clear empties the live canvas and |
| 26495 | /// destroys nothing. If `/history` ever shrinks here, the feature is wrong. |
| 26496 | #[tokio::test] |
| 26497 | async fn a_clear_empties_the_canvas_and_keeps_the_history() { |
| 26498 | let (app, db) = app_and_db().await; |
| 26499 | let ali = login(&app, "ali").await; |
| 26500 | let ali_id = me_id(&app, &ali).await; |
| 26501 | let board = create_board(&app, &ali, "Geometri", &[]).await; |
| 26502 | for n in 0..3 { |
| 26503 | draw(&db, &board, &ali_id, 0, &format!("{{\"p\":[{n}]}}")) |
| 26504 | .await |
| 26505 | .unwrap(); |
| 26506 | } |
| 26507 | let before: Vec<String> = stroke_rows(&db, &board) |
| 26508 | .await |
| 26509 | .iter() |
| 26510 | .map(|row| row.get_id().key().to_string()) |
| 26511 | .collect(); |
| 26512 | assert_eq!(before.len(), 3); |
| 26513 | |
| 26514 | let res = send( |
| 26515 | &app, |
| 26516 | "GET", |
| 26517 | &format!("/boards/{board}/strokes"), |
| 26518 | Some(&ali), |
| 26519 | None, |
| 26520 | ) |
| 26521 | .await; |
| 26522 | assert_eq!(common::total(&res.body), 3, "the live canvas has 3 marks"); |
| 26523 | |
| 26524 | let res = send( |
| 26525 | &app, |
| 26526 | "POST", |
| 26527 | &format!("/boards/{board}/clear"), |
| 26528 | Some(&ali), |
| 26529 | None, |
| 26530 | ) |
| 26531 | .await; |
| 26532 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 26533 | assert_eq!(res.body["kind"], "clear"); |
| 26534 | assert_eq!( |
| 26535 | res.body["epoch"], 0, |
| 26536 | "the marker carries the epoch it closed" |
| 26537 | ); |
| 26538 | assert_eq!(res.body["count"], 3); |
| 26539 | assert!(res.body["payload"].is_null()); |
| 26540 | |
| 26541 | // The canvas is blank... |
| 26542 | let res = send( |
| 26543 | &app, |
| 26544 | "GET", |
| 26545 | &format!("/boards/{board}/strokes"), |
| 26546 | Some(&ali), |
| 26547 | None, |
| 26548 | ) |
| 26549 | .await; |
| 26550 | assert_eq!(common::total(&res.body), 0, "the canvas is empty"); |
| 26551 | assert!(common::items(&res.body).is_empty()); |
| 26552 | |
| 26553 | // ...and the history is not. 3 strokes + the marker. |
| 26554 | let res = send( |
| 26555 | &app, |
| 26556 | "GET", |
| 26557 | &format!("/boards/{board}/history"), |
| 26558 | Some(&ali), |
| 26559 | None, |
| 26560 | ) |
| 26561 | .await; |
| 26562 | assert_eq!(common::total(&res.body), 4); |
| 26563 | let kept: Vec<&str> = common::items(&res.body) |
| 26564 | .iter() |
| 26565 | .map(|row| row["id"].as_str().unwrap()) |
| 26566 | .collect(); |
| 26567 | for id in &before { |
| 26568 | assert!(kept.contains(&id.as_str()), "a clear lost stroke {id}"); |
| 26569 | } |
| 26570 | |
| 26571 | // Asserted at the table too, not just through the reader that a bug could |
| 26572 | // share with the writer. |
| 26573 | let rows = stroke_rows(&db, &board).await; |
| 26574 | assert_eq!(rows.len(), 4, "nothing was deleted"); |
| 26575 | let stored: Vec<String> = rows.iter().map(|r| r.get_id().key().to_string()).collect(); |
| 26576 | for id in &before { |
| 26577 | assert!(stored.contains(id), "stroke {id} is gone from the table"); |
| 26578 | } |
| 26579 | |
| 26580 | // Drawing resumes on the new epoch, and the old one is still readable |
| 26581 | // whole through `?epoch=`. |
| 26582 | let board_row = stored_board(&db, &board).await.unwrap(); |
| 26583 | assert_eq!(board_row.get_epoch(), 1); |
| 26584 | draw(&db, &board, &ali_id, 1, "{\"p\":[9]}").await.unwrap(); |
| 26585 | let res = send( |
| 26586 | &app, |
| 26587 | "GET", |
| 26588 | &format!("/boards/{board}/strokes"), |
| 26589 | Some(&ali), |
| 26590 | None, |
| 26591 | ) |
| 26592 | .await; |
| 26593 | assert_eq!(common::total(&res.body), 1, "the new canvas has one mark"); |
| 26594 | let res = send( |
| 26595 | &app, |
| 26596 | "GET", |
| 26597 | &format!("/boards/{board}/history?epoch=0"), |
| 26598 | Some(&ali), |
| 26599 | None, |
| 26600 | ) |
| 26601 | .await; |
| 26602 | assert_eq!(common::total(&res.body), 4, "epoch 0 replays in full"); |
| 26603 | let res = send( |
| 26604 | &app, |
| 26605 | "GET", |
| 26606 | &format!("/boards/{board}/history"), |
| 26607 | Some(&ali), |
| 26608 | None, |
| 26609 | ) |
| 26610 | .await; |
| 26611 | assert_eq!(common::total(&res.body), 5, "the whole session is one log"); |
| 26612 | } |
| 26613 | |
| 26614 | /// The epoch index: one entry per clear, each carrying the final stroke count |
| 26615 | /// of the epoch it closed — which must equal the rows actually on the table for |
| 26616 | /// that epoch, or "replay session 2" replays the wrong thing. |
| 26617 | #[tokio::test] |
| 26618 | async fn the_epoch_index_counts_each_epoch_it_closed() { |
| 26619 | let (app, db) = app_and_db().await; |
| 26620 | let ali = login(&app, "ali").await; |
| 26621 | let ali_id = me_id(&app, &ali).await; |
| 26622 | let board = create_board(&app, &ali, "Geometri", &[]).await; |
| 26623 | |
| 26624 | // Epoch 0 gets 2 marks, epoch 1 gets 3, then epoch 2 is left open. |
| 26625 | for (epoch, marks) in [(0, 2), (1, 3)] { |
| 26626 | for n in 0..marks { |
| 26627 | draw(&db, &board, &ali_id, epoch, &format!("{{\"p\":[{n}]}}")) |
| 26628 | .await |
| 26629 | .unwrap(); |
| 26630 | } |
| 26631 | let res = send( |
| 26632 | &app, |
| 26633 | "POST", |
| 26634 | &format!("/boards/{board}/clear"), |
| 26635 | Some(&ali), |
| 26636 | None, |
| 26637 | ) |
| 26638 | .await; |
| 26639 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 26640 | } |
| 26641 | draw(&db, &board, &ali_id, 2, "{\"p\":[7]}").await.unwrap(); |
| 26642 | |
| 26643 | let res = send( |
| 26644 | &app, |
| 26645 | "GET", |
| 26646 | &format!("/boards/{board}/epochs"), |
| 26647 | Some(&ali), |
| 26648 | None, |
| 26649 | ) |
| 26650 | .await; |
| 26651 | assert_eq!(res.status, StatusCode::OK); |
| 26652 | assert_eq!(common::total(&res.body), 2, "one marker per clear, no more"); |
| 26653 | let markers = common::items(&res.body); |
| 26654 | assert_eq!(markers[0]["epoch"], 0); |
| 26655 | assert_eq!(markers[0]["count"], 2); |
| 26656 | assert_eq!(markers[1]["epoch"], 1); |
| 26657 | assert_eq!(markers[1]["count"], 3); |
| 26658 | for marker in markers { |
| 26659 | assert_eq!(marker["kind"], "clear"); |
| 26660 | assert_eq!(marker["author"], ali_id.as_str()); |
| 26661 | } |
| 26662 | |
| 26663 | // Each `count` against the rows really stored under that epoch. |
| 26664 | let rows = stroke_rows(&db, &board).await; |
| 26665 | for marker in markers { |
| 26666 | let epoch = marker["epoch"].as_i64().unwrap(); |
| 26667 | let drawn = rows |
| 26668 | .iter() |
| 26669 | .filter(|row| row.get_epoch() == epoch && !row.is_clear()) |
| 26670 | .count() as i64; |
| 26671 | assert_eq!( |
| 26672 | marker["count"].as_i64().unwrap(), |
| 26673 | drawn, |
| 26674 | "marker for epoch {epoch} miscounts its strokes" |
| 26675 | ); |
| 26676 | } |
| 26677 | // The open epoch is deliberately absent — the markers *are* the index. |
| 26678 | assert_eq!(stored_board(&db, &board).await.unwrap().get_epoch(), 2); |
| 26679 | } |
| 26680 | |
| 26681 | /// A full live canvas is a *recoverable* refusal: the board stays open and a |
| 26682 | /// clear hands the whole cap back. |
| 26683 | #[tokio::test] |
| 26684 | async fn a_full_canvas_is_refused_until_the_creator_clears_it() { |
| 26685 | let (app, db) = app_and_db().await; |
| 26686 | let ali = login(&app, "ali").await; |
| 26687 | let ali_id = me_id(&app, &ali).await; |
| 26688 | let board = create_board(&app, &ali, "Geometri", &[]).await; |
| 26689 | set_counters(&db, &board, MAX_EPOCH_STROKES, MAX_EPOCH_STROKES).await; |
| 26690 | |
| 26691 | let refused = draw(&db, &board, &ali_id, 0, "{\"p\":[1]}").await; |
| 26692 | assert!(refused.is_err(), "a full canvas must refuse the append"); |
| 26693 | assert!(stroke_rows(&db, &board).await.is_empty(), "nothing written"); |
| 26694 | let stored = stored_board(&db, &board).await.unwrap(); |
| 26695 | assert!( |
| 26696 | stored.get_closed_at().is_none(), |
| 26697 | "a full canvas must NOT close the board — it is recoverable" |
| 26698 | ); |
| 26699 | assert_eq!( |
| 26700 | stored_counters(&db, &board).await, |
| 26701 | vec![MAX_EPOCH_STROKES, MAX_EPOCH_STROKES], |
| 26702 | "the refusal claimed nothing" |
| 26703 | ); |
| 26704 | |
| 26705 | // The creator clears, and drawing resumes against a fresh cap. |
| 26706 | let res = send( |
| 26707 | &app, |
| 26708 | "POST", |
| 26709 | &format!("/boards/{board}/clear"), |
| 26710 | Some(&ali), |
| 26711 | None, |
| 26712 | ) |
| 26713 | .await; |
| 26714 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 26715 | assert_eq!(res.body["count"], MAX_EPOCH_STROKES); |
| 26716 | assert!( |
| 26717 | draw(&db, &board, &ali_id, 1, "{\"p\":[1]}").await.is_ok(), |
| 26718 | "a clear must un-refuse the board" |
| 26719 | ); |
| 26720 | assert_eq!( |
| 26721 | stored_counters(&db, &board).await, |
| 26722 | vec![1, MAX_EPOCH_STROKES + 2], |
| 26723 | "the epoch counter reset; the lifetime counter kept the clear marker \ |
| 26724 | it minted and the new stroke" |
| 26725 | ); |
| 26726 | let res = send( |
| 26727 | &app, |
| 26728 | "GET", |
| 26729 | &format!("/boards/{board}/strokes"), |
| 26730 | Some(&ali), |
| 26731 | None, |
| 26732 | ) |
| 26733 | .await; |
| 26734 | assert_eq!(common::total(&res.body), 1, "the new mark is on the canvas"); |
| 26735 | } |
| 26736 | |
| 26737 | /// The lifetime cap is the permanent one: it stamps `closed_at`, and a closed |
| 26738 | /// board still serves every read it ever served. |
| 26739 | #[tokio::test] |
| 26740 | async fn the_lifetime_cap_closes_the_board_and_it_stays_readable() { |
| 26741 | let (app, db) = app_and_db().await; |
| 26742 | let ali = login(&app, "ali").await; |
| 26743 | let ali_id = me_id(&app, &ali).await; |
| 26744 | let board = create_board(&app, &ali, "Geometri", &[]).await; |
| 26745 | draw(&db, &board, &ali_id, 0, "{\"p\":[1]}").await.unwrap(); |
| 26746 | let res = send( |
| 26747 | &app, |
| 26748 | "POST", |
| 26749 | &format!("/boards/{board}/clear"), |
| 26750 | Some(&ali), |
| 26751 | None, |
| 26752 | ) |
| 26753 | .await; |
| 26754 | assert_eq!(res.status, StatusCode::CREATED); |
| 26755 | set_counters(&db, &board, 0, MAX_BOARD_STROKES).await; |
| 26756 | |
| 26757 | assert!( |
| 26758 | draw(&db, &board, &ali_id, 1, "{\"p\":[2]}").await.is_err(), |
| 26759 | "the lifetime cap must refuse the append" |
| 26760 | ); |
| 26761 | let stamp = stored_board(&db, &board) |
| 26762 | .await |
| 26763 | .unwrap() |
| 26764 | .get_closed_at() |
| 26765 | .expect("the lifetime cap stamps closed_at"); |
| 26766 | assert_eq!(stroke_rows(&db, &board).await.len(), 2, "nothing written"); |
| 26767 | |
| 26768 | // Permanently read-only: no more strokes, and no more clears either. |
| 26769 | tokio::time::sleep(std::time::Duration::from_millis(2)).await; |
| 26770 | assert!(draw(&db, &board, &ali_id, 1, "{\"p\":[3]}").await.is_err()); |
| 26771 | assert_eq!( |
| 26772 | stored_board(&db, &board).await.unwrap().get_closed_at(), |
| 26773 | Some(stamp), |
| 26774 | "a second refusal must not re-stamp closed_at" |
| 26775 | ); |
| 26776 | let res = send( |
| 26777 | &app, |
| 26778 | "POST", |
| 26779 | &format!("/boards/{board}/clear"), |
| 26780 | Some(&ali), |
| 26781 | None, |
| 26782 | ) |
| 26783 | .await; |
| 26784 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 26785 | |
| 26786 | // Still fully readable — that is the whole point of closing rather than |
| 26787 | // deleting. |
| 26788 | let res = send(&app, "GET", &format!("/boards/{board}"), Some(&ali), None).await; |
| 26789 | assert_eq!(res.status, StatusCode::OK); |
| 26790 | assert_eq!(res.body["closed_at"], stamp.as_millis()); |
| 26791 | let res = send( |
| 26792 | &app, |
| 26793 | "GET", |
| 26794 | &format!("/boards/{board}/history"), |
| 26795 | Some(&ali), |
| 26796 | None, |
| 26797 | ) |
| 26798 | .await; |
| 26799 | assert_eq!(common::total(&res.body), 2, "the whole log is still served"); |
| 26800 | let res = send( |
| 26801 | &app, |
| 26802 | "GET", |
| 26803 | &format!("/boards/{board}/epochs"), |
| 26804 | Some(&ali), |
| 26805 | None, |
| 26806 | ) |
| 26807 | .await; |
| 26808 | assert_eq!(common::total(&res.body), 1); |
| 26809 | let res = send( |
| 26810 | &app, |
| 26811 | "GET", |
| 26812 | &format!("/boards/{board}/strokes"), |
| 26813 | Some(&ali), |
| 26814 | None, |
| 26815 | ) |
| 26816 | .await; |
| 26817 | assert_eq!(res.status, StatusCode::OK); |
| 26818 | let res = send(&app, "GET", "/boards", Some(&ali), None).await; |
| 26819 | assert_eq!( |
| 26820 | common::total(&res.body), |
| 26821 | 1, |
| 26822 | "a closed board is still listed" |
| 26823 | ); |
| 26824 | } |
| 26825 | |
| 26826 | /// Demoting a board's **creator** to `parent` closes the room, and closes it |
| 26827 | /// through the ordinary role route. Without that the board is commandable by |
| 26828 | /// nobody: the ex-creator is 404'd off their own board (the whiteboard is shut |
| 26829 | /// to parents), clear/lock/close/delete are creator-only for everyone else, and |
| 26830 | /// no route lists a board the caller is not on — so not even an admin can find |
| 26831 | /// the id, while the participants keep drawing on it. Closed and not deleted: |
| 26832 | /// every read the board ever served, it still serves. |
| 26833 | #[tokio::test] |
| 26834 | async fn demoting_a_board_s_creator_closes_the_room_and_keeps_it_readable() { |
| 26835 | let (app, db) = app_and_db().await; |
| 26836 | let admin = login_as(&app, &db, "yonetici", "admin").await; |
| 26837 | let ali = login(&app, "ali").await; |
| 26838 | let ali_id = me_id(&app, &ali).await; |
| 26839 | let veli = login(&app, "veli").await; |
| 26840 | let veli_id = me_id(&app, &veli).await; |
| 26841 | let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await; |
| 26842 | draw(&db, &board, &veli_id, 0, "{\"p\":[1]}").await.unwrap(); |
| 26843 | |
| 26844 | let res = send( |
| 26845 | &app, |
| 26846 | "PATCH", |
| 26847 | &format!("/users/{ali_id}/role"), |
| 26848 | Some(&admin), |
| 26849 | Some(json!({ "role": "parent" })), |
| 26850 | ) |
| 26851 | .await; |
| 26852 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 26853 | |
| 26854 | let stamp = stored_board(&db, &board) |
| 26855 | .await |
| 26856 | .unwrap() |
| 26857 | .get_closed_at() |
| 26858 | .expect("the demotion must close the room its creator can no longer command"); |
| 26859 | // The seat stays taken: the row it counts still exists. |
| 26860 | assert_eq!(stored_board_count(&db, &ali_id).await, 1); |
| 26861 | |
| 26862 | // The participant still reads everything, and their marks are still there. |
| 26863 | let res = send(&app, "GET", &format!("/boards/{board}"), Some(&veli), None).await; |
| 26864 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 26865 | assert_eq!(res.body["closed_at"], stamp.as_millis()); |
| 26866 | let res = send( |
| 26867 | &app, |
| 26868 | "GET", |
| 26869 | &format!("/boards/{board}/history"), |
| 26870 | Some(&veli), |
| 26871 | None, |
| 26872 | ) |
| 26873 | .await; |
| 26874 | assert_eq!(common::total(&res.body), 1, "the whole log is still served"); |
| 26875 | assert_eq!(stroke_rows(&db, &board).await.len(), 1); |
| 26876 | let res = send(&app, "GET", "/boards", Some(&veli), None).await; |
| 26877 | assert_eq!(common::total(&res.body), 1, "and it is still listed"); |
| 26878 | |
| 26879 | // But every write answers the terminal refusal, not the recoverable one. |
| 26880 | let refused = draw(&db, &board, &veli_id, 0, "{\"p\":[2]}").await; |
| 26881 | assert!( |
| 26882 | matches!( |
| 26883 | refused, |
| 26884 | Err(hezarfen_backend::error::AppError::Conflict( |
| 26885 | hezarfen_backend::domain::board_stroke::BOARD_CLOSED |
| 26886 | )) |
| 26887 | ), |
| 26888 | "a closed board must refuse a stroke as closed, got {refused:?}" |
| 26889 | ); |
| 26890 | assert_eq!(stroke_rows(&db, &board).await.len(), 1, "nothing written"); |
| 26891 | |
| 26892 | // The ex-creator is out of their own room, which is the shape that made |
| 26893 | // this uncommandable in the first place. |
| 26894 | let res = send(&app, "GET", &format!("/boards/{board}"), Some(&ali), None).await; |
| 26895 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 26896 | } |
| 26897 | |
| 26898 | /// The per-creator cap, asserted on the stored counter — and a delete really |
| 26899 | /// hands the seat back, or a busy teacher's limit ratchets shut forever. |
| 26900 | #[tokio::test] |
| 26901 | async fn the_per_creator_cap_refuses_and_a_delete_frees_a_seat() { |
| 26902 | let (app, db) = app_and_db().await; |
| 26903 | let ali = login(&app, "ali").await; |
| 26904 | let ali_id = me_id(&app, &ali).await; |
| 26905 | let board = create_board(&app, &ali, "Geometri", &[]).await; |
| 26906 | assert_eq!(stored_board_count(&db, &ali_id).await, 1); |
| 26907 | |
| 26908 | // Age the counter to full rather than open 200 boards. |
| 26909 | sqlx::query("UPDATE app_user SET board_count = $1 WHERE id = $2") |
| 26910 | .bind(MAX_BOARDS_PER_CREATOR) |
| 26911 | .bind(Uuid::parse_str(&ali_id).expect("user id")) |
| 26912 | .execute(&db) |
| 26913 | .await |
| 26914 | .unwrap(); |
| 26915 | |
| 26916 | let res = send( |
| 26917 | &app, |
| 26918 | "POST", |
| 26919 | "/boards", |
| 26920 | Some(&ali), |
| 26921 | Some(json!({ "title": "Bir tane daha" })), |
| 26922 | ) |
| 26923 | .await; |
| 26924 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 26925 | assert_eq!( |
| 26926 | stored_board_count(&db, &ali_id).await, |
| 26927 | MAX_BOARDS_PER_CREATOR, |
| 26928 | "the refusal must not have claimed a seat" |
| 26929 | ); |
| 26930 | let boards: i64 = sqlx::query_scalar("SELECT count(*) FROM board") |
| 26931 | .fetch_one(&db) |
| 26932 | .await |
| 26933 | .unwrap(); |
| 26934 | assert_eq!(boards, 1, "no row was written by the refused create"); |
| 26935 | |
| 26936 | // Deleting frees exactly one seat, and the next create takes it. |
| 26937 | let res = send( |
| 26938 | &app, |
| 26939 | "DELETE", |
| 26940 | &format!("/boards/{board}"), |
| 26941 | Some(&ali), |
| 26942 | None, |
| 26943 | ) |
| 26944 | .await; |
| 26945 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 26946 | assert_eq!( |
| 26947 | stored_board_count(&db, &ali_id).await, |
| 26948 | MAX_BOARDS_PER_CREATOR - 1, |
| 26949 | "the delete handed the seat back" |
| 26950 | ); |
| 26951 | let next = create_board(&app, &ali, "Bir tane daha", &[]).await; |
| 26952 | assert_eq!( |
| 26953 | stored_board_count(&db, &ali_id).await, |
| 26954 | MAX_BOARDS_PER_CREATOR |
| 26955 | ); |
| 26956 | assert!(stored_board(&db, &next).await.is_some()); |
| 26957 | // And the deleted board is gone for its own creator too. |
| 26958 | let res = send(&app, "GET", &format!("/boards/{board}"), Some(&ali), None).await; |
| 26959 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 26960 | } |
| 26961 | |
| 26962 | /// The id-ordering hazard, over HTTP: a burst of marks all lands inside one |
| 26963 | /// or two milliseconds, and an id scheme without within-millisecond |
| 26964 | /// monotonicity would sort those rows at random. The canvas is a drawing, so |
| 26965 | /// an order that shuffles is a drawing that redraws wrong. |
| 26966 | #[tokio::test] |
| 26967 | async fn a_burst_of_strokes_comes_back_in_mint_order() { |
| 26968 | let (app, db) = app_and_db().await; |
| 26969 | let ali = login(&app, "ali").await; |
| 26970 | let ali_id = me_id(&app, &ali).await; |
| 26971 | let board = create_board(&app, &ali, "Geometri", &[]).await; |
| 26972 | |
| 26973 | let mut minted = Vec::new(); |
| 26974 | for n in 0..60 { |
| 26975 | minted.push( |
| 26976 | draw(&db, &board, &ali_id, 0, &format!("{{\"p\":[{n}]}}")) |
| 26977 | .await |
| 26978 | .unwrap() |
| 26979 | .get_id() |
| 26980 | .key() |
| 26981 | .to_string(), |
| 26982 | ); |
| 26983 | } |
| 26984 | // Whether *those* 60 shared a millisecond depends on how loaded the |
| 26985 | // machine is, so the same-millisecond half of the hazard is pinned with no |
| 26986 | // database in the way: a tight mint loop that certainly does share one, and |
| 26987 | // `ORDER BY id` on a string key is a plain string sort — so mint order must |
| 26988 | // already BE sorted order. `Ulid::new()` fails this within a few ids. |
| 26989 | let ids: Vec<String> = (0..500) |
| 26990 | .map(|_| BoardStrokeId::generate().key().to_string()) |
| 26991 | .collect(); |
| 26992 | let mut sorted = ids.clone(); |
| 26993 | sorted.sort(); |
| 26994 | assert_eq!( |
| 26995 | sorted, ids, |
| 26996 | "ids minted in one millisecond must sort in mint order" |
| 26997 | ); |
| 26998 | |
| 26999 | let res = send( |
| 27000 | &app, |
| 27001 | "GET", |
| 27002 | &format!("/boards/{board}/strokes"), |
| 27003 | Some(&ali), |
| 27004 | None, |
| 27005 | ) |
| 27006 | .await; |
| 27007 | let served: Vec<&str> = common::items(&res.body) |
| 27008 | .iter() |
| 27009 | .map(|row| row["id"].as_str().unwrap()) |
| 27010 | .collect(); |
| 27011 | assert_eq!(served, minted, "/strokes must replay in mint order"); |
| 27012 | let res = send( |
| 27013 | &app, |
| 27014 | "GET", |
| 27015 | &format!("/boards/{board}/history"), |
| 27016 | Some(&ali), |
| 27017 | None, |
| 27018 | ) |
| 27019 | .await; |
| 27020 | let served: Vec<&str> = common::items(&res.body) |
| 27021 | .iter() |
| 27022 | .map(|row| row["id"].as_str().unwrap()) |
| 27023 | .collect(); |
| 27024 | assert_eq!(served, minted, "/history must replay in mint order too"); |
| 27025 | // And the payloads ride along in that same order. |
| 27026 | let payloads: Vec<String> = common::items(&res.body) |
| 27027 | .iter() |
| 27028 | .map(|row| row["payload"].as_str().unwrap().to_string()) |
| 27029 | .collect(); |
| 27030 | assert_eq!(payloads[0], "{\"p\":[0]}"); |
| 27031 | assert_eq!(payloads[59], "{\"p\":[59]}"); |
| 27032 | } |
| 27033 | |
| 27034 | // --- class sections (şube) -------------------------------------------------- |
| 27035 | |
| 27036 | /// The class routes' own gates, end to end: who may write, who may not, and |
| 27037 | /// that the writes really are enrollments. The pump itself is proven in the |
| 27038 | /// domain unit tests — what only the router can prove is that the two axes are |
| 27039 | /// gated differently (roster = manager+, attach = *that course's* manager) and |
| 27040 | /// that a class is enrollment in bulk rather than a parallel roster. |
| 27041 | #[tokio::test] |
| 27042 | async fn a_class_pumps_enrollments_and_guards_each_axis_separately() { |
| 27043 | let (app, db) = app_and_db().await; |
| 27044 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 27045 | let teacher = login_as(&app, &db, "tch", "teacher").await; |
| 27046 | let other = login_as(&app, &db, "other", "teacher").await; |
| 27047 | let student = login_as(&app, &db, "stu", "student").await; |
| 27048 | let student_id = me_id(&app, &student).await; |
| 27049 | let teacher_id = me_id(&app, &teacher).await; |
| 27050 | let course = create_course(&app, &teacher, "algebra").await; |
| 27051 | |
| 27052 | // Creating a class is the office's call — a teacher may read, not write. |
| 27053 | let res = send( |
| 27054 | &app, |
| 27055 | "POST", |
| 27056 | "/classes", |
| 27057 | Some(&teacher), |
| 27058 | Some(json!({"name": "9-A", "grade_level": 9})), |
| 27059 | ) |
| 27060 | .await; |
| 27061 | assert_eq!( |
| 27062 | res.status, |
| 27063 | StatusCode::FORBIDDEN, |
| 27064 | "class create is manager+" |
| 27065 | ); |
| 27066 | let res = send( |
| 27067 | &app, |
| 27068 | "POST", |
| 27069 | "/classes", |
| 27070 | Some(&manager), |
| 27071 | Some(json!({"name": "9-A", "grade_level": 9})), |
| 27072 | ) |
| 27073 | .await; |
| 27074 | assert_eq!(res.status, StatusCode::CREATED); |
| 27075 | assert_eq!( |
| 27076 | res.body["class"]["grade_level"], 9, |
| 27077 | "the class carries the rung it was created at" |
| 27078 | ); |
| 27079 | let class = id_of(&res.body["class"]); |
| 27080 | assert_eq!( |
| 27081 | send(&app, "GET", "/classes", Some(&teacher), None) |
| 27082 | .await |
| 27083 | .status, |
| 27084 | StatusCode::OK, |
| 27085 | "teachers read the class list" |
| 27086 | ); |
| 27087 | |
| 27088 | // Only students go in a roster, and only real users. |
| 27089 | for (body, who) in [ |
| 27090 | (json!({"user_id": "nobody"}), "an unknown user"), |
| 27091 | (json!({"user_id": teacher_id}), "a teacher"), |
| 27092 | ] { |
| 27093 | let res = send( |
| 27094 | &app, |
| 27095 | "POST", |
| 27096 | &format!("/classes/{class}/members"), |
| 27097 | Some(&manager), |
| 27098 | Some(body), |
| 27099 | ) |
| 27100 | .await; |
| 27101 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{who} is a 400"); |
| 27102 | } |
| 27103 | let res = send( |
| 27104 | &app, |
| 27105 | "POST", |
| 27106 | &format!("/classes/{class}/members"), |
| 27107 | Some(&manager), |
| 27108 | Some(json!({ "user_id": student_id })), |
| 27109 | ) |
| 27110 | .await; |
| 27111 | assert_eq!(res.status, StatusCode::CREATED); |
| 27112 | |
| 27113 | // Attaching writes the course's roster, so it takes the course's own bar — |
| 27114 | // a teacher who does not manage it is refused even though they are teacher+. |
| 27115 | let attach = json!({ "course_id": course }); |
| 27116 | let res = send( |
| 27117 | &app, |
| 27118 | "POST", |
| 27119 | &format!("/classes/{class}/instances"), |
| 27120 | Some(&other), |
| 27121 | Some(attach.clone()), |
| 27122 | ) |
| 27123 | .await; |
| 27124 | assert_eq!( |
| 27125 | res.status, |
| 27126 | StatusCode::FORBIDDEN, |
| 27127 | "attach needs course rights" |
| 27128 | ); |
| 27129 | let res = send( |
| 27130 | &app, |
| 27131 | "POST", |
| 27132 | &format!("/classes/{class}/instances"), |
| 27133 | Some(&teacher), |
| 27134 | Some(attach.clone()), |
| 27135 | ) |
| 27136 | .await; |
| 27137 | assert_eq!(res.status, StatusCode::CREATED); |
| 27138 | let instance = id_of(&res.body); |
| 27139 | let res = send( |
| 27140 | &app, |
| 27141 | "POST", |
| 27142 | &format!("/classes/{class}/instances"), |
| 27143 | Some(&teacher), |
| 27144 | Some(attach), |
| 27145 | ) |
| 27146 | .await; |
| 27147 | assert_eq!(res.status, StatusCode::CONFLICT, "a second attach is a 409"); |
| 27148 | |
| 27149 | // The attach minted the instance, and it is what the seats are on now: the |
| 27150 | // membership is a real enrollment, so it shows up on the pair's roster. |
| 27151 | // (The pairing is the office's — a teacher attached to nothing here holds |
| 27152 | // no rights over the instance itself.) |
| 27153 | let res = send( |
| 27154 | &app, |
| 27155 | "GET", |
| 27156 | &format!("/instances/{instance}/enrollments"), |
| 27157 | Some(&manager), |
| 27158 | None, |
| 27159 | ) |
| 27160 | .await; |
| 27161 | assert_eq!( |
| 27162 | common::total(&res.body), |
| 27163 | 1, |
| 27164 | "the class must have enrolled its member" |
| 27165 | ); |
| 27166 | assert_eq!(common::items(&res.body)[0]["user"]["id"], student_id); |
| 27167 | |
| 27168 | // A class carrying either is undeletable until both ends are cleared. |
| 27169 | let res = send( |
| 27170 | &app, |
| 27171 | "DELETE", |
| 27172 | &format!("/classes/{class}"), |
| 27173 | Some(&manager), |
| 27174 | None, |
| 27175 | ) |
| 27176 | .await; |
| 27177 | assert_eq!(res.status, StatusCode::CONFLICT); |
| 27178 | assert_eq!( |
| 27179 | send( |
| 27180 | &app, |
| 27181 | "DELETE", |
| 27182 | &format!("/classes/{class}/instances/{instance}"), |
| 27183 | Some(&manager), |
| 27184 | None, |
| 27185 | ) |
| 27186 | .await |
| 27187 | .status, |
| 27188 | StatusCode::NO_CONTENT |
| 27189 | ); |
| 27190 | assert_eq!( |
| 27191 | send( |
| 27192 | &app, |
| 27193 | "DELETE", |
| 27194 | &format!("/classes/{class}/members/{student_id}"), |
| 27195 | Some(&manager), |
| 27196 | None, |
| 27197 | ) |
| 27198 | .await |
| 27199 | .status, |
| 27200 | StatusCode::NO_CONTENT |
| 27201 | ); |
| 27202 | let res = send( |
| 27203 | &app, |
| 27204 | "DELETE", |
| 27205 | &format!("/classes/{class}"), |
| 27206 | Some(&manager), |
| 27207 | None, |
| 27208 | ) |
| 27209 | .await; |
| 27210 | assert_eq!( |
| 27211 | res.status, |
| 27212 | StatusCode::NO_CONTENT, |
| 27213 | "empty on both axes, it goes" |
| 27214 | ); |
| 27215 | // And the pumped enrollment left with the detach: the instance is gone from |
| 27216 | // the catalog's own count, and the student who is still on the class roster |
| 27217 | // has no instance left to sit. |
| 27218 | let res = send( |
| 27219 | &app, |
| 27220 | "GET", |
| 27221 | &format!("/courses/{course}"), |
| 27222 | Some(&teacher), |
| 27223 | None, |
| 27224 | ) |
| 27225 | .await; |
| 27226 | assert_eq!( |
| 27227 | res.body["class_course_count"], 0, |
| 27228 | "the detached instance is not the catalog's any more: {}", |
| 27229 | res.body |
| 27230 | ); |
| 27231 | let res = send(&app, "GET", "/instances/me", Some(&student), None).await; |
| 27232 | assert_eq!( |
| 27233 | common::total(&res.body), |
| 27234 | 0, |
| 27235 | "a seat on a detached instance left with it" |
| 27236 | ); |
| 27237 | assert_eq!( |
| 27238 | send( |
| 27239 | &app, |
| 27240 | "GET", |
| 27241 | &format!("/classes/{class}"), |
| 27242 | Some(&teacher), |
| 27243 | None |
| 27244 | ) |
| 27245 | .await |
| 27246 | .status, |
| 27247 | StatusCode::NOT_FOUND |
| 27248 | ); |
| 27249 | } |
| 27250 | |
| 27251 | /// Who may look at a class, and the one write a manager holds without teaching |
| 27252 | /// anything. Every `/classes` read is teacher+, so the student on the roster — |
| 27253 | /// and the parent watching them — is refused their own row; and attaching takes |
| 27254 | /// management of the course, which a manager has over every course in the |
| 27255 | /// school whether or not they run it. |
| 27256 | #[tokio::test] |
| 27257 | async fn class_reads_are_staff_only_and_a_manager_manages_every_course() { |
| 27258 | let (app, db) = app_and_db().await; |
| 27259 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 27260 | let teacher = login_as(&app, &db, "tch", "teacher").await; |
| 27261 | let parent = login_as(&app, &db, "anne", "parent").await; |
| 27262 | let student = login(&app, "stu").await; |
| 27263 | let student_id = me_id(&app, &student).await; |
| 27264 | let course = create_course(&app, &teacher, "algebra").await; |
| 27265 | |
| 27266 | let res = send( |
| 27267 | &app, |
| 27268 | "POST", |
| 27269 | "/classes", |
| 27270 | Some(&manager), |
| 27271 | Some(json!({ "name": "9-A", "grade_level": 9 })), |
| 27272 | ) |
| 27273 | .await; |
| 27274 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 27275 | let class = id_of(&res.body["class"]); |
| 27276 | // The student really is on this roster, so the 403s below are the gate |
| 27277 | // talking and not an empty database. |
| 27278 | let res = send( |
| 27279 | &app, |
| 27280 | "POST", |
| 27281 | &format!("/classes/{class}/members"), |
| 27282 | Some(&manager), |
| 27283 | Some(json!({ "user_id": student_id })), |
| 27284 | ) |
| 27285 | .await; |
| 27286 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 27287 | |
| 27288 | for (who, cookie) in [("a student", &student), ("a parent", &parent)] { |
| 27289 | for uri in [ |
| 27290 | "/classes".to_string(), |
| 27291 | format!("/classes/{class}"), |
| 27292 | format!("/classes/{class}/members"), |
| 27293 | format!("/classes/{class}/instances"), |
| 27294 | ] { |
| 27295 | let res = send(&app, "GET", &uri, Some(cookie), None).await; |
| 27296 | assert_eq!(res.status, StatusCode::FORBIDDEN, "GET {uri} for {who}"); |
| 27297 | } |
| 27298 | // …and neither of them writes, on either axis. |
| 27299 | let res = send( |
| 27300 | &app, |
| 27301 | "POST", |
| 27302 | &format!("/classes/{class}/members"), |
| 27303 | Some(cookie), |
| 27304 | Some(json!({ "user_id": student_id })), |
| 27305 | ) |
| 27306 | .await; |
| 27307 | assert_eq!(res.status, StatusCode::FORBIDDEN, "member add for {who}"); |
| 27308 | let res = send( |
| 27309 | &app, |
| 27310 | "POST", |
| 27311 | &format!("/classes/{class}/instances"), |
| 27312 | Some(cookie), |
| 27313 | Some(json!({ "course_id": course })), |
| 27314 | ) |
| 27315 | .await; |
| 27316 | assert_eq!(res.status, StatusCode::FORBIDDEN, "attach for {who}"); |
| 27317 | } |
| 27318 | |
| 27319 | // The manager neither created this course nor teaches it, and still |
| 27320 | // attaches it: the bar is management of the course, not authorship of it. |
| 27321 | let res = send( |
| 27322 | &app, |
| 27323 | "POST", |
| 27324 | &format!("/classes/{class}/instances"), |
| 27325 | Some(&manager), |
| 27326 | Some(json!({ "course_id": course })), |
| 27327 | ) |
| 27328 | .await; |
| 27329 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 27330 | let instance = id_of(&res.body); |
| 27331 | // Stored, not merely answered: the instance is on the class and the roster |
| 27332 | // moved with it. |
| 27333 | let res = send( |
| 27334 | &app, |
| 27335 | "GET", |
| 27336 | &format!("/classes/{class}/instances"), |
| 27337 | Some(&teacher), |
| 27338 | None, |
| 27339 | ) |
| 27340 | .await; |
| 27341 | assert_eq!(common::total(&res.body), 1); |
| 27342 | assert_eq!(common::items(&res.body)[0]["course"], course); |
| 27343 | let res = send( |
| 27344 | &app, |
| 27345 | "GET", |
| 27346 | &format!("/instances/{instance}/enrollments"), |
| 27347 | Some(&manager), |
| 27348 | None, |
| 27349 | ) |
| 27350 | .await; |
| 27351 | assert_eq!(common::total(&res.body), 1, "{}", res.body); |
| 27352 | } |
| 27353 | |
| 27354 | /// A student promoted out of studenthood leaves their class as well as their |
| 27355 | /// rosters. Two sweeps run on that path and each owns exactly half the state — |
| 27356 | /// the memberships and the class counter, the enrollment rows and the course |
| 27357 | /// counter — so both halves are asserted stored, and then the class is deleted, |
| 27358 | /// which only a *released* member counter permits. |
| 27359 | #[tokio::test] |
| 27360 | async fn a_demotion_sweeps_the_class_membership_and_what_it_pumped() { |
| 27361 | let (app, db) = app_and_db().await; |
| 27362 | let admin = login_as(&app, &db, "boss", "admin").await; |
| 27363 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 27364 | let teacher = login_as(&app, &db, "tch", "teacher").await; |
| 27365 | let student = login(&app, "veli").await; |
| 27366 | let student_id = me_id(&app, &student).await; |
| 27367 | let course = create_course(&app, &teacher, "algebra").await; |
| 27368 | |
| 27369 | let res = send( |
| 27370 | &app, |
| 27371 | "POST", |
| 27372 | "/classes", |
| 27373 | Some(&manager), |
| 27374 | Some(json!({ "name": "9-A", "grade_level": 9 })), |
| 27375 | ) |
| 27376 | .await; |
| 27377 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 27378 | let class = id_of(&res.body["class"]); |
| 27379 | let res = send( |
| 27380 | &app, |
| 27381 | "POST", |
| 27382 | &format!("/classes/{class}/instances"), |
| 27383 | Some(&teacher), |
| 27384 | Some(json!({ "course_id": course })), |
| 27385 | ) |
| 27386 | .await; |
| 27387 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 27388 | let instance = id_of(&res.body); |
| 27389 | let res = send( |
| 27390 | &app, |
| 27391 | "POST", |
| 27392 | &format!("/classes/{class}/members"), |
| 27393 | Some(&manager), |
| 27394 | Some(json!({ "user_id": student_id })), |
| 27395 | ) |
| 27396 | .await; |
| 27397 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 27398 | let res = send( |
| 27399 | &app, |
| 27400 | "GET", |
| 27401 | &format!("/instances/{instance}/enrollments"), |
| 27402 | Some(&manager), |
| 27403 | None, |
| 27404 | ) |
| 27405 | .await; |
| 27406 | assert_eq!(common::total(&res.body), 1, "the class seated them first"); |
| 27407 | |
| 27408 | // Out of studenthood, through the endpoint an admin actually uses. |
| 27409 | let res = send( |
| 27410 | &app, |
| 27411 | "PATCH", |
| 27412 | &format!("/users/{student_id}/role"), |
| 27413 | Some(&admin), |
| 27414 | Some(json!({ "role": "teacher" })), |
| 27415 | ) |
| 27416 | .await; |
| 27417 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 27418 | |
| 27419 | let res = send( |
| 27420 | &app, |
| 27421 | "GET", |
| 27422 | &format!("/classes/{class}/members"), |
| 27423 | Some(&teacher), |
| 27424 | None, |
| 27425 | ) |
| 27426 | .await; |
| 27427 | assert_eq!(common::total(&res.body), 0, "the roster let them go"); |
| 27428 | let res = send( |
| 27429 | &app, |
| 27430 | "GET", |
| 27431 | &format!("/instances/{instance}/enrollments"), |
| 27432 | Some(&manager), |
| 27433 | None, |
| 27434 | ) |
| 27435 | .await; |
| 27436 | assert_eq!(common::total(&res.body), 0, "and so did the instance"); |
| 27437 | |
| 27438 | // Both tables and both counters, read off the store itself. |
| 27439 | let count = |sql: &'static str| { |
| 27440 | let db = &db; |
| 27441 | async move { |
| 27442 | sqlx::query_scalar::<_, i64>(sql) |
| 27443 | .fetch_one(db) |
| 27444 | .await |
| 27445 | .expect("read the swept state") |
| 27446 | } |
| 27447 | }; |
| 27448 | // A leave is a *stint*: the row stays, the live stint does not — and the |
| 27449 | // counter counts live stints, which is what the class's guard reads. |
| 27450 | assert_eq!( |
| 27451 | count("SELECT count(*) FROM class_member WHERE left_at IS NULL").await, |
| 27452 | 0, |
| 27453 | "no live stint may outlive the demotion" |
| 27454 | ); |
| 27455 | assert_eq!( |
| 27456 | count("SELECT count(*) FROM class_member").await, |
| 27457 | 1, |
| 27458 | "…while the history row the section keeps is still there" |
| 27459 | ); |
| 27460 | assert_eq!( |
| 27461 | count("SELECT count(*) FROM enrollment").await, |
| 27462 | 0, |
| 27463 | "the pumped enrollment is deleted too" |
| 27464 | ); |
| 27465 | let class_members: i64 = sqlx::query_scalar("SELECT class_member_count FROM class_group") |
| 27466 | .fetch_one(&db) |
| 27467 | .await |
| 27468 | .expect("read the swept state"); |
| 27469 | assert_eq!(class_members, 0, "the class counter came back"); |
| 27470 | let enrolled: i64 = |
| 27471 | sqlx::query_scalar("SELECT enrollment_count FROM class_course WHERE id = $1") |
| 27472 | .bind(uuid::Uuid::parse_str(&instance).unwrap()) |
| 27473 | .fetch_one(&db) |
| 27474 | .await |
| 27475 | .expect("read the swept state"); |
| 27476 | assert_eq!(enrolled, 0, "the instance counter came back"); |
| 27477 | |
| 27478 | // The bite: a membership left behind (or a counter never released) makes |
| 27479 | // the class undeletable forever. |
| 27480 | assert_eq!( |
| 27481 | send( |
| 27482 | &app, |
| 27483 | "DELETE", |
| 27484 | &format!("/classes/{class}/instances/{instance}"), |
| 27485 | Some(&teacher), |
| 27486 | None, |
| 27487 | ) |
| 27488 | .await |
| 27489 | .status, |
| 27490 | StatusCode::NO_CONTENT |
| 27491 | ); |
| 27492 | let res = send( |
| 27493 | &app, |
| 27494 | "DELETE", |
| 27495 | &format!("/classes/{class}"), |
| 27496 | Some(&manager), |
| 27497 | None, |
| 27498 | ) |
| 27499 | .await; |
| 27500 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 27501 | } |
| 27502 | |
| 27503 | /// A class files itself under an **academic year** — the same calendar a course |
| 27504 | /// no longer carries — so the year's delete guard has to count classes too: |
| 27505 | /// otherwise deleting the calendar entry would leave the class pointing at |
| 27506 | /// nothing. (It was the dönem's guard until the class became the academic |
| 27507 | /// anchor; the guard moved up with it.) |
| 27508 | #[tokio::test] |
| 27509 | async fn a_year_a_class_points_at_refuses_to_delete() { |
| 27510 | let (app, db) = app_and_db().await; |
| 27511 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 27512 | |
| 27513 | let res = send( |
| 27514 | &app, |
| 27515 | "POST", |
| 27516 | "/academic-years", |
| 27517 | Some(&manager), |
| 27518 | Some(json!({ |
| 27519 | "name": "2025-2026", |
| 27520 | "starts_at": 1_600_000_000_000_i64, |
| 27521 | "ends_at": 1_610_000_000_000_i64, |
| 27522 | })), |
| 27523 | ) |
| 27524 | .await; |
| 27525 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 27526 | let year = id_of(&res.body); |
| 27527 | let res = send( |
| 27528 | &app, |
| 27529 | "POST", |
| 27530 | "/classes", |
| 27531 | Some(&manager), |
| 27532 | Some(json!({ "name": "9-A", "grade_level": 9, "year": year })), |
| 27533 | ) |
| 27534 | .await; |
| 27535 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 27536 | assert_eq!(res.body["class"]["year"].as_str(), Some(year.as_str())); |
| 27537 | let class = id_of(&res.body["class"]); |
| 27538 | |
| 27539 | let res = send( |
| 27540 | &app, |
| 27541 | "DELETE", |
| 27542 | &format!("/academic-years/{year}"), |
| 27543 | Some(&manager), |
| 27544 | None, |
| 27545 | ) |
| 27546 | .await; |
| 27547 | assert_eq!( |
| 27548 | res.status, |
| 27549 | StatusCode::CONFLICT, |
| 27550 | "a class still points at it: {}", |
| 27551 | res.body |
| 27552 | ); |
| 27553 | |
| 27554 | // Unlinking gives the reference back — an explicit `null` on the named |
| 27555 | // field, because a `{}` body short-circuits before any guard runs. |
| 27556 | let res = send( |
| 27557 | &app, |
| 27558 | "PATCH", |
| 27559 | &format!("/classes/{class}"), |
| 27560 | Some(&manager), |
| 27561 | Some(json!({ "year": null })), |
| 27562 | ) |
| 27563 | .await; |
| 27564 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 27565 | assert!(res.body["year"].is_null()); |
| 27566 | let res = send( |
| 27567 | &app, |
| 27568 | "DELETE", |
| 27569 | &format!("/academic-years/{year}"), |
| 27570 | Some(&manager), |
| 27571 | None, |
| 27572 | ) |
| 27573 | .await; |
| 27574 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 27575 | // And the class outlives the year it was filed under. |
| 27576 | assert_eq!( |
| 27577 | send( |
| 27578 | &app, |
| 27579 | "GET", |
| 27580 | &format!("/classes/{class}"), |
| 27581 | Some(&manager), |
| 27582 | None |
| 27583 | ) |
| 27584 | .await |
| 27585 | .status, |
| 27586 | StatusCode::OK |
| 27587 | ); |
| 27588 | } |
| 27589 | |
| 27590 | /// All-or-nothing where a client can see it: a class already standing above |
| 27591 | /// `MAX_CLASS_MEMBERS` takes *no* new instance, because attaching one writes an |
| 27592 | /// enrollment per member in a single transaction. The 409 names the axis it is |
| 27593 | /// over, and — the half only stored state can show — nothing is left behind: |
| 27594 | /// no instance, no enrollment, no counter ticked. |
| 27595 | /// |
| 27596 | /// This is the same all-or-nothing subject the file used to pin on a course's |
| 27597 | /// `capacity` (a class of two with one free seat took neither); capacity is gone |
| 27598 | /// from the model, so the ceiling that still bounds the write is the one the |
| 27599 | /// class itself carries. The counter is seeded rather than filled by |
| 27600 | /// `MAX_CLASS_MEMBERS` real adds: it *is* what the attach reads. |
| 27601 | #[tokio::test] |
| 27602 | async fn an_attach_that_cannot_seat_the_whole_class_seats_none_of_it() { |
| 27603 | let (app, db) = app_and_db().await; |
| 27604 | let manager = login_as(&app, &db, "mgr", "manager").await; |
| 27605 | let teacher = login_as(&app, &db, "tch", "teacher").await; |
| 27606 | let ali = login(&app, "ali").await; |
| 27607 | let veli = login(&app, "veli").await; |
| 27608 | let ali_id = me_id(&app, &ali).await; |
| 27609 | let veli_id = me_id(&app, &veli).await; |
| 27610 | |
| 27611 | let course = create_course(&app, &teacher, "small").await; |
| 27612 | let res = send( |
| 27613 | &app, |
| 27614 | "POST", |
| 27615 | "/classes", |
| 27616 | Some(&manager), |
| 27617 | Some(json!({ "name": "9-A", "grade_level": 9 })), |
| 27618 | ) |
| 27619 | .await; |
| 27620 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 27621 | let class = id_of(&res.body["class"]); |
| 27622 | for student in [&ali_id, &veli_id] { |
| 27623 | let res = send( |
| 27624 | &app, |
| 27625 | "POST", |
| 27626 | &format!("/classes/{class}/members"), |
| 27627 | Some(&manager), |
| 27628 | Some(json!({ "user_id": student })), |
| 27629 | ) |
| 27630 | .await; |
| 27631 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 27632 | } |
| 27633 | |
| 27634 | // A volume that grew past the ceiling (the shape a real school's section |
| 27635 | // arrives in): the attach of two seats must refuse *before* the loop runs. |
| 27636 | let seed = |count: i64| { |
| 27637 | let db = &db; |
| 27638 | let class = uuid::Uuid::parse_str(&class).unwrap(); |
| 27639 | async move { |
| 27640 | sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2") |
| 27641 | .bind(count) |
| 27642 | .bind(class) |
| 27643 | .execute(db) |
| 27644 | .await |
| 27645 | .expect("seed the roster counter") |
| 27646 | } |
| 27647 | }; |
| 27648 | seed(MAX_CLASS_MEMBERS + 1).await; |
| 27649 | |
| 27650 | let res = send( |
| 27651 | &app, |
| 27652 | "POST", |
| 27653 | &format!("/classes/{class}/instances"), |
| 27654 | Some(&teacher), |
| 27655 | Some(json!({ "course_id": course })), |
| 27656 | ) |
| 27657 | .await; |
| 27658 | assert_eq!( |
| 27659 | res.status, |
| 27660 | StatusCode::CONFLICT, |
| 27661 | "a section over its ceiling attaches nothing: {}", |
| 27662 | res.body |
| 27663 | ); |
| 27664 | assert_eq!(res.body["code"], "class_roster_too_large", "{}", res.body); |
| 27665 | |
| 27666 | // Nothing on any of the three ends: no instance, no enrollment, no tick. |
| 27667 | let res = send( |
| 27668 | &app, |
| 27669 | "GET", |
| 27670 | &format!("/classes/{class}/instances"), |
| 27671 | Some(&teacher), |
| 27672 | None, |
| 27673 | ) |
| 27674 | .await; |
| 27675 | assert_eq!(common::total(&res.body), 0, "no instance was minted"); |
| 27676 | let enrolled: i64 = sqlx::query_scalar("SELECT count(*) FROM enrollment") |
| 27677 | .fetch_one(&db) |
| 27678 | .await |
| 27679 | .expect("read the stored roster"); |
| 27680 | assert_eq!( |
| 27681 | enrolled, 0, |
| 27682 | "and no seat was written on the way to the refusal" |
| 27683 | ); |
| 27684 | let counted: i64 = |
| 27685 | sqlx::query_scalar("SELECT class_course_count FROM class_group WHERE id = $1") |
| 27686 | .bind(uuid::Uuid::parse_str(&class).unwrap()) |
| 27687 | .fetch_one(&db) |
| 27688 | .await |
| 27689 | .expect("read the class counter"); |
| 27690 | assert_eq!(counted, 0, "nor ticked the axis it was refused on"); |
| 27691 | |
| 27692 | // Back under the ceiling, the very same attach goes through — and it seats |
| 27693 | // the whole roster, which is the other half of all-or-nothing. |
| 27694 | seed(2).await; |
| 27695 | let res = send( |
| 27696 | &app, |
| 27697 | "POST", |
| 27698 | &format!("/classes/{class}/instances"), |
| 27699 | Some(&teacher), |
| 27700 | Some(json!({ "course_id": course })), |
| 27701 | ) |
| 27702 | .await; |
| 27703 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 27704 | let instance = id_of(&res.body); |
| 27705 | let res = send( |
| 27706 | &app, |
| 27707 | "GET", |
| 27708 | &format!("/instances/{instance}/enrollments"), |
| 27709 | Some(&manager), |
| 27710 | None, |
| 27711 | ) |
| 27712 | .await; |
| 27713 | assert_eq!(common::total(&res.body), 2, "both members, in one go"); |
| 27714 | } |
| 27715 | |
| 27716 | // --- course notes: authz matrix over HTTP ----------------------------------- |
| 27717 | |
| 27718 | /// Create a course note as `cookie` on `course` (asserts 201); returns its id. |
| 27719 | async fn create_course_note(app: &axum::Router, cookie: &str, course: &str, title: &str) -> String { |
| 27720 | let res = send( |
| 27721 | app, |
| 27722 | "POST", |
| 27723 | "/course-notes", |
| 27724 | Some(cookie), |
| 27725 | Some(json!({ "course": course, "title": title, "content": "body" })), |
| 27726 | ) |
| 27727 | .await; |
| 27728 | assert_eq!( |
| 27729 | res.status, |
| 27730 | StatusCode::CREATED, |
| 27731 | "create course note: {}", |
| 27732 | res.body |
| 27733 | ); |
| 27734 | id_of(&res.body) |
| 27735 | } |
| 27736 | |
| 27737 | /// (a) the course's *creator* writes a note+file on it, while a teacher merely |
| 27738 | /// assigned to an instance of that course is refused the same write — the |
| 27739 | /// assignment gives them the instance, never the catalog row; an enrolled |
| 27740 | /// student reads it end to end — list, get, file list, download — with |
| 27741 | /// byte-identical bytes and the right `Content-Disposition`. |
| 27742 | /// (d) the creator manages what it wrote (update + delete). |
| 27743 | #[tokio::test] |
| 27744 | async fn course_note_creator_writes_assigned_teacher_refused_and_enrolled_student_reads() { |
| 27745 | let (app, db) = app_and_db().await; |
| 27746 | let manager = login_as(&app, &db, "boss", "manager").await; |
| 27747 | let creator = login_as(&app, &db, "creator_teacher", "teacher").await; |
| 27748 | let assigned = login_as(&app, &db, "assigned_teacher", "teacher").await; |
| 27749 | let student = login_as(&app, &db, "stu", "student").await; |
| 27750 | |
| 27751 | let t = taught_under(&app, &manager, &creator, "algebra").await; |
| 27752 | let course = t.course; |
| 27753 | let assigned_id = me_id(&app, &assigned).await; |
| 27754 | let res = send( |
| 27755 | &app, |
| 27756 | "POST", |
| 27757 | &format!("/instances/{}/teachers", t.instance), |
| 27758 | Some(&manager), |
| 27759 | Some(json!({ "user_id": assigned_id })), |
| 27760 | ) |
| 27761 | .await; |
| 27762 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 27763 | |
| 27764 | // The assignment is real, and still does not reach the catalog row: the |
| 27765 | // course note is the creator's (or a manager's) to write. |
| 27766 | let res = send( |
| 27767 | &app, |
| 27768 | "POST", |
| 27769 | "/course-notes", |
| 27770 | Some(&assigned), |
| 27771 | Some(json!({ "course": course, "title": "not mine", "content": "body" })), |
| 27772 | ) |
| 27773 | .await; |
| 27774 | assert_eq!( |
| 27775 | res.status, |
| 27776 | StatusCode::FORBIDDEN, |
| 27777 | "an instance's teacher keeps no catalog rights: {}", |
| 27778 | res.body |
| 27779 | ); |
| 27780 | |
| 27781 | let student_id = me_id(&app, &student).await; |
| 27782 | enroll(&app, &creator, &t.instance, &student_id).await; |
| 27783 | |
| 27784 | // (a) the creator writes note + file. |
| 27785 | let note = create_course_note(&app, &creator, &course, "recap").await; |
| 27786 | let bytes = b"%PDF-1.4 fake"; |
| 27787 | let up = |
| 27788 | upload_course_note_file(&app, &creator, ¬e, "recap.pdf", "application/pdf", bytes).await; |
| 27789 | assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); |
| 27790 | let file_id = id_of(&up.body); |
| 27791 | |
| 27792 | // Enrolled student reads: list, get, file list, download. |
| 27793 | let list = send( |
| 27794 | &app, |
| 27795 | "GET", |
| 27796 | &format!("/course-notes?course={course}"), |
| 27797 | Some(&student), |
| 27798 | None, |
| 27799 | ) |
| 27800 | .await; |
| 27801 | assert_eq!(list.status, StatusCode::OK); |
| 27802 | assert_eq!(common::total(&list.body), 1); |
| 27803 | |
| 27804 | let get = send( |
| 27805 | &app, |
| 27806 | "GET", |
| 27807 | &format!("/course-notes/{note}"), |
| 27808 | Some(&student), |
| 27809 | None, |
| 27810 | ) |
| 27811 | .await; |
| 27812 | assert_eq!(get.status, StatusCode::OK); |
| 27813 | assert_eq!(get.body["title"], "recap"); |
| 27814 | |
| 27815 | let files = send( |
| 27816 | &app, |
| 27817 | "GET", |
| 27818 | &format!("/course-notes/{note}/files"), |
| 27819 | Some(&student), |
| 27820 | None, |
| 27821 | ) |
| 27822 | .await; |
| 27823 | assert_eq!(files.status, StatusCode::OK); |
| 27824 | assert_eq!(common::total(&files.body), 1); |
| 27825 | |
| 27826 | let (status, headers, body) = common::send_raw( |
| 27827 | &app, |
| 27828 | "GET", |
| 27829 | &format!("/course-notes/{note}/files/{file_id}"), |
| 27830 | Some(&student), |
| 27831 | None, |
| 27832 | Vec::new(), |
| 27833 | ) |
| 27834 | .await; |
| 27835 | assert_eq!(status, StatusCode::OK); |
| 27836 | assert_eq!(body, bytes); |
| 27837 | assert_eq!(headers["content-type"], "application/pdf"); |
| 27838 | assert_eq!( |
| 27839 | headers["content-disposition"], |
| 27840 | "attachment; filename=\"recap.pdf\"; filename*=UTF-8''recap.pdf" |
| 27841 | ); |
| 27842 | |
| 27843 | // (d) the creator manages its own note as well: update then delete. |
| 27844 | let upd = send( |
| 27845 | &app, |
| 27846 | "PATCH", |
| 27847 | &format!("/course-notes/{note}"), |
| 27848 | Some(&creator), |
| 27849 | Some(json!({ "title": "recap v2" })), |
| 27850 | ) |
| 27851 | .await; |
| 27852 | assert_eq!(upd.status, StatusCode::OK, "{}", upd.body); |
| 27853 | assert_eq!(upd.body["title"], "recap v2"); |
| 27854 | |
| 27855 | let del = send( |
| 27856 | &app, |
| 27857 | "DELETE", |
| 27858 | &format!("/course-notes/{note}"), |
| 27859 | Some(&creator), |
| 27860 | None, |
| 27861 | ) |
| 27862 | .await; |
| 27863 | assert_eq!(del.status, StatusCode::NO_CONTENT); |
| 27864 | } |
| 27865 | |
| 27866 | /// (b) everyone without a seat at the table is turned away: a teacher with no |
| 27867 | /// relation to the course (403 on write), an unenrolled student (403 on |
| 27868 | /// read), a parent (403 on read), and an unauthenticated caller (401). |
| 27869 | #[tokio::test] |
| 27870 | async fn course_note_denies_unrelated_teacher_student_parent_and_anon() { |
| 27871 | let (app, db) = app_and_db().await; |
| 27872 | let creator = login_as(&app, &db, "owner_teacher", "teacher").await; |
| 27873 | let other_teacher = login_as(&app, &db, "other_teacher", "teacher").await; |
| 27874 | let other_student = login_as(&app, &db, "other_student", "student").await; |
| 27875 | let parent = login_as(&app, &db, "mom", "parent").await; |
| 27876 | |
| 27877 | let course = create_course(&app, &creator, "geometry").await; |
| 27878 | let note = create_course_note(&app, &creator, &course, "notes").await; |
| 27879 | |
| 27880 | // Non-responsible teacher: write paths all 403. |
| 27881 | let create_res = send( |
| 27882 | &app, |
| 27883 | "POST", |
| 27884 | "/course-notes", |
| 27885 | Some(&other_teacher), |
| 27886 | Some(json!({ "course": course, "title": "x", "content": "y" })), |
| 27887 | ) |
| 27888 | .await; |
| 27889 | assert_eq!( |
| 27890 | create_res.status, |
| 27891 | StatusCode::FORBIDDEN, |
| 27892 | "{}", |
| 27893 | create_res.body |
| 27894 | ); |
| 27895 | |
| 27896 | let upload_res = |
| 27897 | upload_course_note_file(&app, &other_teacher, ¬e, "a.txt", "text/plain", b"x").await; |
| 27898 | assert_eq!( |
| 27899 | upload_res.status, |
| 27900 | StatusCode::FORBIDDEN, |
| 27901 | "{}", |
| 27902 | upload_res.body |
| 27903 | ); |
| 27904 | |
| 27905 | let delete_res = send( |
| 27906 | &app, |
| 27907 | "DELETE", |
| 27908 | &format!("/course-notes/{note}"), |
| 27909 | Some(&other_teacher), |
| 27910 | None, |
| 27911 | ) |
| 27912 | .await; |
| 27913 | assert_eq!( |
| 27914 | delete_res.status, |
| 27915 | StatusCode::FORBIDDEN, |
| 27916 | "{}", |
| 27917 | delete_res.body |
| 27918 | ); |
| 27919 | |
| 27920 | // Unenrolled student: read paths 403. |
| 27921 | assert_eq!( |
| 27922 | send( |
| 27923 | &app, |
| 27924 | "GET", |
| 27925 | &format!("/course-notes?course={course}"), |
| 27926 | Some(&other_student), |
| 27927 | None, |
| 27928 | ) |
| 27929 | .await |
| 27930 | .status, |
| 27931 | StatusCode::FORBIDDEN |
| 27932 | ); |
| 27933 | |
| 27934 | // Parent: read paths 403 too. |
| 27935 | assert_eq!( |
| 27936 | send( |
| 27937 | &app, |
| 27938 | "GET", |
| 27939 | &format!("/course-notes/{note}"), |
| 27940 | Some(&parent), |
| 27941 | None, |
| 27942 | ) |
| 27943 | .await |
| 27944 | .status, |
| 27945 | StatusCode::FORBIDDEN |
| 27946 | ); |
| 27947 | |
| 27948 | // Unauthenticated: 401. |
| 27949 | assert_eq!( |
| 27950 | send(&app, "GET", &format!("/course-notes/{note}"), None, None) |
| 27951 | .await |
| 27952 | .status, |
| 27953 | StatusCode::UNAUTHORIZED |
| 27954 | ); |
| 27955 | assert_eq!( |
| 27956 | send( |
| 27957 | &app, |
| 27958 | "POST", |
| 27959 | "/course-notes", |
| 27960 | None, |
| 27961 | Some(json!({ "course": course, "title": "x" })), |
| 27962 | ) |
| 27963 | .await |
| 27964 | .status, |
| 27965 | StatusCode::UNAUTHORIZED |
| 27966 | ); |
| 27967 | } |
| 27968 | |
| 27969 | /// (c) a manager creates and deletes a note on a course they neither created |
| 27970 | /// nor are assigned to. |
| 27971 | #[tokio::test] |
| 27972 | async fn course_note_manager_manages_any_course() { |
| 27973 | let (app, db) = app_and_db().await; |
| 27974 | let manager = login_as(&app, &db, "boss2", "manager").await; |
| 27975 | let creator = login_as(&app, &db, "creator3", "teacher").await; |
| 27976 | let course = create_course(&app, &creator, "chem").await; |
| 27977 | |
| 27978 | let note = create_course_note(&app, &manager, &course, "manager note").await; |
| 27979 | let del = send( |
| 27980 | &app, |
| 27981 | "DELETE", |
| 27982 | &format!("/course-notes/{note}"), |
| 27983 | Some(&manager), |
| 27984 | None, |
| 27985 | ) |
| 27986 | .await; |
| 27987 | assert_eq!(del.status, StatusCode::NO_CONTENT); |
| 27988 | } |
| 27989 | |
| 27990 | /// (e) the file cap (409 past `MAX_COURSE_NOTE_FILES`) and the school's byte |
| 27991 | /// cap (413 over, 201 at) both apply to course-note files. |
| 27992 | #[tokio::test] |
| 27993 | async fn course_note_file_cap_and_size_limit() { |
| 27994 | let (app, db) = app_and_db().await; |
| 27995 | let manager = login_as(&app, &db, "boss3", "manager").await; |
| 27996 | let creator = login_as(&app, &db, "creator4", "teacher").await; |
| 27997 | let course = create_course(&app, &creator, "bio").await; |
| 27998 | let note = create_course_note(&app, &creator, &course, "capped").await; |
| 27999 | |
| 28000 | for i in 0..MAX_COURSE_NOTE_FILES { |
| 28001 | let res = upload_course_note_file( |
| 28002 | &app, |
| 28003 | &creator, |
| 28004 | ¬e, |
| 28005 | &format!("f{i}.txt"), |
| 28006 | "text/plain", |
| 28007 | b"x", |
| 28008 | ) |
| 28009 | .await; |
| 28010 | assert_eq!(res.status, StatusCode::CREATED, "file {i}: {}", res.body); |
| 28011 | } |
| 28012 | let over = upload_course_note_file( |
| 28013 | &app, |
| 28014 | &creator, |
| 28015 | ¬e, |
| 28016 | "one_too_many.txt", |
| 28017 | "text/plain", |
| 28018 | b"x", |
| 28019 | ) |
| 28020 | .await; |
| 28021 | assert_eq!(over.status, StatusCode::CONFLICT, "{}", over.body); |
| 28022 | |
| 28023 | // Lower the school's byte cap and check the size wall. |
| 28024 | let res = send( |
| 28025 | &app, |
| 28026 | "PATCH", |
| 28027 | "/settings", |
| 28028 | Some(&manager), |
| 28029 | Some(json!({ "max_file_bytes": 1024 })), |
| 28030 | ) |
| 28031 | .await; |
| 28032 | assert_eq!(res.status, StatusCode::OK); |
| 28033 | let note2 = create_course_note(&app, &creator, &course, "sized").await; |
| 28034 | let big = |
| 28035 | upload_course_note_file(&app, &creator, ¬e2, "big.bin", "", &vec![7u8; 1025]).await; |
| 28036 | assert_eq!(big.status, StatusCode::PAYLOAD_TOO_LARGE, "{}", big.body); |
| 28037 | let fits = |
| 28038 | upload_course_note_file(&app, &creator, ¬e2, "fits.bin", "", &vec![7u8; 1024]).await; |
| 28039 | assert_eq!(fits.status, StatusCode::CREATED, "{}", fits.body); |
| 28040 | } |
| 28041 | |
| 28042 | /// (f) deleting the course cascades its notes: a note that existed a moment |
| 28043 | /// ago 404s once its course is gone. |
| 28044 | #[tokio::test] |
| 28045 | async fn course_note_cascades_on_course_delete() { |
| 28046 | let (app, db) = app_and_db().await; |
| 28047 | let manager = login_as(&app, &db, "boss4", "manager").await; |
| 28048 | let creator = login_as(&app, &db, "creator5", "teacher").await; |
| 28049 | let course = create_course(&app, &creator, "temp").await; |
| 28050 | let note = create_course_note(&app, &creator, &course, "will vanish").await; |
| 28051 | |
| 28052 | let del = send( |
| 28053 | &app, |
| 28054 | "DELETE", |
| 28055 | &format!("/courses/{course}"), |
| 28056 | Some(&creator), |
| 28057 | None, |
| 28058 | ) |
| 28059 | .await; |
| 28060 | assert_eq!(del.status, StatusCode::NO_CONTENT, "{}", del.body); |
| 28061 | |
| 28062 | let get = send( |
| 28063 | &app, |
| 28064 | "GET", |
| 28065 | &format!("/course-notes/{note}"), |
| 28066 | Some(&manager), |
| 28067 | None, |
| 28068 | ) |
| 28069 | .await; |
| 28070 | assert_eq!(get.status, StatusCode::NOT_FOUND, "{}", get.body); |
| 28071 | } |
| 28072 | |
| 28073 | /// (g) a creator demoted teacher -> student mid-session loses every |
| 28074 | /// course-note write path and the read path too, on the note they made |
| 28075 | /// while still a teacher. |
| 28076 | #[tokio::test] |
| 28077 | async fn course_note_demoted_creator_loses_writes_and_reads() { |
| 28078 | let (app, db) = app_and_db().await; |
| 28079 | let admin = login_as(&app, &db, "probe_admin", "admin").await; |
| 28080 | let creator = login_as(&app, &db, "probe_creator", "teacher").await; |
| 28081 | let creator_id = me_id(&app, &creator).await; |
| 28082 | let course = create_course(&app, &creator, "algebra2").await; |
| 28083 | let note = create_course_note(&app, &creator, &course, "before").await; |
| 28084 | |
| 28085 | let r = send( |
| 28086 | &app, |
| 28087 | "PATCH", |
| 28088 | &format!("/users/{creator_id}/role"), |
| 28089 | Some(&admin), |
| 28090 | Some(json!({ "role": "student" })), |
| 28091 | ) |
| 28092 | .await; |
| 28093 | assert_eq!(r.status, StatusCode::OK, "{}", r.body); |
| 28094 | |
| 28095 | for (m, u, b) in [ |
| 28096 | ( |
| 28097 | "POST", |
| 28098 | "/course-notes".to_string(), |
| 28099 | Some(json!({ "course": course, "title": "x" })), |
| 28100 | ), |
| 28101 | ( |
| 28102 | "PATCH", |
| 28103 | format!("/course-notes/{note}"), |
| 28104 | Some(json!({ "title": "y" })), |
| 28105 | ), |
| 28106 | ("DELETE", format!("/course-notes/{note}"), None), |
| 28107 | ] { |
| 28108 | let res = send(&app, m, &u, Some(&creator), b).await; |
| 28109 | assert_eq!( |
| 28110 | res.status, |
| 28111 | StatusCode::FORBIDDEN, |
| 28112 | "{m} {u} -> {} {}", |
| 28113 | res.status, |
| 28114 | res.body |
| 28115 | ); |
| 28116 | } |
| 28117 | let up = upload_course_note_file(&app, &creator, ¬e, "a.txt", "text/plain", b"x").await; |
| 28118 | assert_eq!( |
| 28119 | up.status, |
| 28120 | StatusCode::FORBIDDEN, |
| 28121 | "upload -> {} {}", |
| 28122 | up.status, |
| 28123 | up.body |
| 28124 | ); |
| 28125 | let read = send( |
| 28126 | &app, |
| 28127 | "GET", |
| 28128 | &format!("/course-notes/{note}"), |
| 28129 | Some(&creator), |
| 28130 | None, |
| 28131 | ) |
| 28132 | .await; |
| 28133 | assert_eq!( |
| 28134 | read.status, |
| 28135 | StatusCode::FORBIDDEN, |
| 28136 | "read -> {} {}", |
| 28137 | read.status, |
| 28138 | read.body |
| 28139 | ); |
| 28140 | } |
| 28141 | |
| 28142 | /// (h) a note id doesn't unlock a file that belongs to another note: mounting |
| 28143 | /// course A's file id under course B's note id 404s (note-scoped lookup |
| 28144 | /// fails before authz), straight cross-course access 403s, and course A's |
| 28145 | /// file survives every one of these attempts. |
| 28146 | #[tokio::test] |
| 28147 | async fn course_note_cross_course_file_is_not_reachable() { |
| 28148 | let (app, db) = app_and_db().await; |
| 28149 | let manager = login_as(&app, &db, "probe_mgr", "manager").await; |
| 28150 | let t_a = login_as(&app, &db, "probe_ta", "teacher").await; |
| 28151 | let t_b = login_as(&app, &db, "probe_tb", "teacher").await; |
| 28152 | let outsider = login_as(&app, &db, "probe_out", "student").await; |
| 28153 | |
| 28154 | let course_a = create_course(&app, &t_a, "probeA").await; |
| 28155 | let course_b = create_course(&app, &t_b, "probeB").await; |
| 28156 | let note_a = create_course_note(&app, &t_a, &course_a, "na").await; |
| 28157 | let note_b = create_course_note(&app, &t_b, &course_b, "nb").await; |
| 28158 | let up = upload_course_note_file(&app, &t_a, ¬e_a, "secret.txt", "text/plain", b"top").await; |
| 28159 | assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); |
| 28160 | let file_a = id_of(&up.body); |
| 28161 | |
| 28162 | // teacher B mounts A's file id under his own note id (manager can view both, so |
| 28163 | // the only wall left is the note-scoping in read_for). |
| 28164 | for who in [&t_b, &manager] { |
| 28165 | let res = send( |
| 28166 | &app, |
| 28167 | "GET", |
| 28168 | &format!("/course-notes/{note_b}/files/{file_a}"), |
| 28169 | Some(who), |
| 28170 | None, |
| 28171 | ) |
| 28172 | .await; |
| 28173 | assert_eq!( |
| 28174 | res.status, |
| 28175 | StatusCode::NOT_FOUND, |
| 28176 | "cross-note -> {} {}", |
| 28177 | res.status, |
| 28178 | res.body |
| 28179 | ); |
| 28180 | } |
| 28181 | // teacher B and an unenrolled student straight at A's own note. |
| 28182 | for who in [&t_b, &outsider] { |
| 28183 | let res = send( |
| 28184 | &app, |
| 28185 | "GET", |
| 28186 | &format!("/course-notes/{note_a}/files/{file_a}"), |
| 28187 | Some(who), |
| 28188 | None, |
| 28189 | ) |
| 28190 | .await; |
| 28191 | assert_eq!( |
| 28192 | res.status, |
| 28193 | StatusCode::FORBIDDEN, |
| 28194 | "idor -> {} {}", |
| 28195 | res.status, |
| 28196 | res.body |
| 28197 | ); |
| 28198 | let res = send( |
| 28199 | &app, |
| 28200 | "GET", |
| 28201 | &format!("/course-notes/{note_a}/files"), |
| 28202 | Some(who), |
| 28203 | None, |
| 28204 | ) |
| 28205 | .await; |
| 28206 | assert_eq!( |
| 28207 | res.status, |
| 28208 | StatusCode::FORBIDDEN, |
| 28209 | "list -> {} {}", |
| 28210 | res.status, |
| 28211 | res.body |
| 28212 | ); |
| 28213 | } |
| 28214 | // teacher B may not patch/delete A's note or A's file. |
| 28215 | let res = send( |
| 28216 | &app, |
| 28217 | "PATCH", |
| 28218 | &format!("/course-notes/{note_a}"), |
| 28219 | Some(&t_b), |
| 28220 | Some(json!({ "title": "pwn" })), |
| 28221 | ) |
| 28222 | .await; |
| 28223 | assert_eq!( |
| 28224 | res.status, |
| 28225 | StatusCode::FORBIDDEN, |
| 28226 | "patch -> {} {}", |
| 28227 | res.status, |
| 28228 | res.body |
| 28229 | ); |
| 28230 | let res = send( |
| 28231 | &app, |
| 28232 | "DELETE", |
| 28233 | &format!("/course-notes/{note_a}/files/{file_a}"), |
| 28234 | Some(&t_b), |
| 28235 | None, |
| 28236 | ) |
| 28237 | .await; |
| 28238 | assert_eq!( |
| 28239 | res.status, |
| 28240 | StatusCode::FORBIDDEN, |
| 28241 | "del file -> {} {}", |
| 28242 | res.status, |
| 28243 | res.body |
| 28244 | ); |
| 28245 | // and the manager deleting through the wrong note is a 404, not a silent hit. |
| 28246 | let res = send( |
| 28247 | &app, |
| 28248 | "DELETE", |
| 28249 | &format!("/course-notes/{note_b}/files/{file_a}"), |
| 28250 | Some(&manager), |
| 28251 | None, |
| 28252 | ) |
| 28253 | .await; |
| 28254 | assert_eq!( |
| 28255 | res.status, |
| 28256 | StatusCode::NOT_FOUND, |
| 28257 | "cross del -> {} {}", |
| 28258 | res.status, |
| 28259 | res.body |
| 28260 | ); |
| 28261 | // A's file survives all of it. |
| 28262 | let res = send( |
| 28263 | &app, |
| 28264 | "GET", |
| 28265 | &format!("/course-notes/{note_a}/files"), |
| 28266 | Some(&t_a), |
| 28267 | None, |
| 28268 | ) |
| 28269 | .await; |
| 28270 | assert_eq!(common::total(&res.body), 1, "{}", res.body); |
| 28271 | } |
| 28272 | |
| 28273 | /// (i) the per-note file cap refuses without stranding a blob on disk, and |
| 28274 | /// deleting the course unlinks every blob it cascaded through. `integration` |
| 28275 | /// shares one process-wide files dir across every test in the binary (many |
| 28276 | /// running concurrently), so this checks the ten known blob paths by their |
| 28277 | /// own id rather than a directory-wide count, which would race. |
| 28278 | #[tokio::test] |
| 28279 | async fn course_note_cap_refusal_and_course_delete_leave_no_orphan_blobs() { |
| 28280 | let (app, db) = app_and_db().await; |
| 28281 | let creator = login_as(&app, &db, "probe_blob", "teacher").await; |
| 28282 | let course = create_course(&app, &creator, "blobs").await; |
| 28283 | let note = create_course_note(&app, &creator, &course, "n").await; |
| 28284 | |
| 28285 | let mut blob_paths = Vec::new(); |
| 28286 | for i in 0..10 { |
| 28287 | let r = upload_course_note_file( |
| 28288 | &app, |
| 28289 | &creator, |
| 28290 | ¬e, |
| 28291 | &format!("f{i}.txt"), |
| 28292 | "text/plain", |
| 28293 | b"x", |
| 28294 | ) |
| 28295 | .await; |
| 28296 | assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); |
| 28297 | blob_paths.push(common::blob_dir().join(id_of(&r.body))); |
| 28298 | } |
| 28299 | for p in &blob_paths { |
| 28300 | assert!(p.exists(), "blob missing after upload: {p:?}"); |
| 28301 | } |
| 28302 | let over = upload_course_note_file(&app, &creator, ¬e, "over.txt", "text/plain", b"x").await; |
| 28303 | assert_eq!(over.status, StatusCode::CONFLICT, "{}", over.body); |
| 28304 | for p in &blob_paths { |
| 28305 | assert!(p.exists(), "cap refusal disturbed an existing blob: {p:?}"); |
| 28306 | } |
| 28307 | |
| 28308 | let del = send( |
| 28309 | &app, |
| 28310 | "DELETE", |
| 28311 | &format!("/courses/{course}"), |
| 28312 | Some(&creator), |
| 28313 | None, |
| 28314 | ) |
| 28315 | .await; |
| 28316 | assert_eq!(del.status, StatusCode::NO_CONTENT, "{}", del.body); |
| 28317 | for p in &blob_paths { |
| 28318 | assert!(!p.exists(), "course delete left an orphan blob: {p:?}"); |
| 28319 | } |
| 28320 | let g = send( |
| 28321 | &app, |
| 28322 | "GET", |
| 28323 | &format!("/course-notes/{note}"), |
| 28324 | Some(&creator), |
| 28325 | None, |
| 28326 | ) |
| 28327 | .await; |
| 28328 | assert_eq!(g.status, StatusCode::NOT_FOUND, "{}", g.body); |
| 28329 | } |
| 28330 | |
| 28331 | /// The stored AI outputs of a course note over HTTP: readable by anyone who |
| 28332 | /// can view the course, deletable only by whoever can manage it, and scoped |
| 28333 | /// to the note in the path (an output of a sibling note is a 404, not a |
| 28334 | /// cross-note delete). No AI service runs in tests, so the rows are inserted |
| 28335 | /// through the domain directly. |
| 28336 | #[tokio::test] |
| 28337 | async fn course_note_rag_outputs_read_and_delete() { |
| 28338 | let (app, db) = app_and_db().await; |
| 28339 | let creator = login_as(&app, &db, "rag_teacher", "teacher").await; |
| 28340 | let outsider = login_as(&app, &db, "rag_other_teacher", "teacher").await; |
| 28341 | let student = login_as(&app, &db, "rag_student", "student").await; |
| 28342 | let stranger = login_as(&app, &db, "rag_stranger", "student").await; |
| 28343 | |
| 28344 | let mudur = login_as(&app, &db, "rag_mgr", "manager").await; |
| 28345 | let t = taught_under(&app, &mudur, &creator, "chemistry").await; |
| 28346 | let course = t.course; |
| 28347 | let student_id = me_id(&app, &student).await; |
| 28348 | enroll(&app, &creator, &t.instance, &student_id).await; |
| 28349 | |
| 28350 | let note = create_course_note(&app, &creator, &course, "indexed").await; |
| 28351 | let sibling = create_course_note(&app, &creator, &course, "also indexed").await; |
| 28352 | let up = |
| 28353 | upload_course_note_file(&app, &creator, ¬e, "src.pdf", "application/pdf", b"x").await; |
| 28354 | assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); |
| 28355 | let file_id = id_of(&up.body); |
| 28356 | |
| 28357 | let output = hezarfen_backend::db::rag_output::create( |
| 28358 | &db, |
| 28359 | &CourseNoteId::from_key(¬e), |
| 28360 | &CourseId::from_key(&course), |
| 28361 | vec![CourseNoteFileId::from_key(&file_id)], |
| 28362 | json!({ "summary": "acids and bases" }), |
| 28363 | ) |
| 28364 | .await |
| 28365 | .unwrap(); |
| 28366 | let output_id = output.get_id().key().to_string(); |
| 28367 | let sibling_output = hezarfen_backend::db::rag_output::create( |
| 28368 | &db, |
| 28369 | &CourseNoteId::from_key(&sibling), |
| 28370 | &CourseId::from_key(&course), |
| 28371 | Vec::new(), |
| 28372 | json!({ "summary": "other" }), |
| 28373 | ) |
| 28374 | .await |
| 28375 | .unwrap(); |
| 28376 | let sibling_output_id = sibling_output.get_id().key().to_string(); |
| 28377 | |
| 28378 | // (1) an enrolled student reads the output, sources and payload included. |
| 28379 | let list = send( |
| 28380 | &app, |
| 28381 | "GET", |
| 28382 | &format!("/course-notes/{note}/rag"), |
| 28383 | Some(&student), |
| 28384 | None, |
| 28385 | ) |
| 28386 | .await; |
| 28387 | assert_eq!(list.status, StatusCode::OK, "{}", list.body); |
| 28388 | assert_eq!(common::total(&list.body), 1, "{}", list.body); |
| 28389 | let item = &list.body["items"][0]; |
| 28390 | assert_eq!(item["id"], output_id); |
| 28391 | assert_eq!(item["course_note"], note); |
| 28392 | assert_eq!(item["course"], course); |
| 28393 | assert_eq!(item["sources"][0], file_id); |
| 28394 | assert_eq!(item["payload"]["summary"], "acids and bases"); |
| 28395 | assert!(item["generated_at"].as_i64().unwrap() > 0, "{}", list.body); |
| 28396 | |
| 28397 | // (2) a student with no seat in the course gets the same refusal the note |
| 28398 | // itself gives them: 403, not a 404. |
| 28399 | for path in [ |
| 28400 | format!("/course-notes/{note}"), |
| 28401 | format!("/course-notes/{note}/rag"), |
| 28402 | ] { |
| 28403 | let res = send(&app, "GET", &path, Some(&stranger), None).await; |
| 28404 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{path}: {}", res.body); |
| 28405 | } |
| 28406 | |
| 28407 | // (3) reading is not deleting. |
| 28408 | let res = send( |
| 28409 | &app, |
| 28410 | "DELETE", |
| 28411 | &format!("/course-notes/{note}/rag/{output_id}"), |
| 28412 | Some(&student), |
| 28413 | None, |
| 28414 | ) |
| 28415 | .await; |
| 28416 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 28417 | |
| 28418 | // (5) a teacher who does not manage this course cannot either. |
| 28419 | let res = send( |
| 28420 | &app, |
| 28421 | "DELETE", |
| 28422 | &format!("/course-notes/{note}/rag/{output_id}"), |
| 28423 | Some(&outsider), |
| 28424 | None, |
| 28425 | ) |
| 28426 | .await; |
| 28427 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 28428 | |
| 28429 | // (6) a sibling note's output is not reachable under this note. |
| 28430 | let res = send( |
| 28431 | &app, |
| 28432 | "DELETE", |
| 28433 | &format!("/course-notes/{note}/rag/{sibling_output_id}"), |
| 28434 | Some(&creator), |
| 28435 | None, |
| 28436 | ) |
| 28437 | .await; |
| 28438 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 28439 | assert!( |
| 28440 | hezarfen_backend::db::rag_output::read(&db, sibling_output.get_id()) |
| 28441 | .await |
| 28442 | .unwrap() |
| 28443 | .is_some() |
| 28444 | ); |
| 28445 | |
| 28446 | // (4) the managing teacher deletes, and the note's page empties. |
| 28447 | let res = send( |
| 28448 | &app, |
| 28449 | "DELETE", |
| 28450 | &format!("/course-notes/{note}/rag/{output_id}"), |
| 28451 | Some(&creator), |
| 28452 | None, |
| 28453 | ) |
| 28454 | .await; |
| 28455 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 28456 | let list = send( |
| 28457 | &app, |
| 28458 | "GET", |
| 28459 | &format!("/course-notes/{note}/rag"), |
| 28460 | Some(&student), |
| 28461 | None, |
| 28462 | ) |
| 28463 | .await; |
| 28464 | assert_eq!(common::total(&list.body), 0, "{}", list.body); |
| 28465 | } |
| 28466 | |
| 28467 | /// The manual reindex door is a note write like any other: teacher+, and |
| 28468 | /// management rights over the parent course. A foreign teacher, a student, and |
| 28469 | /// an unknown note are all refused — and none of them writes a row. |
| 28470 | #[tokio::test] |
| 28471 | async fn course_note_rag_reindex_denies_foreign_teacher_student_and_unknown_note() { |
| 28472 | let (app, db) = app_and_db().await; |
| 28473 | let creator = login_as(&app, &db, "reindex_teacher", "teacher").await; |
| 28474 | let outsider = login_as(&app, &db, "reindex_other_teacher", "teacher").await; |
| 28475 | let student = login_as(&app, &db, "reindex_student", "student").await; |
| 28476 | |
| 28477 | let course = create_course(&app, &creator, "reindex").await; |
| 28478 | let note = create_course_note(&app, &creator, &course, "to reindex").await; |
| 28479 | let uri = format!("/course-notes/{note}/rag/reindex"); |
| 28480 | |
| 28481 | // A teacher who does not manage the course: 403, like every other write. |
| 28482 | let res = send(&app, "POST", &uri, Some(&outsider), None).await; |
| 28483 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 28484 | |
| 28485 | // A student fails the teacher+ wall before any rights check. |
| 28486 | let res = send(&app, "POST", &uri, Some(&student), None).await; |
| 28487 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 28488 | |
| 28489 | // An unknown note is a 404, never a silent 202. |
| 28490 | let res = send( |
| 28491 | &app, |
| 28492 | "POST", |
| 28493 | "/course-notes/01NOTANOTE/rag/reindex", |
| 28494 | Some(&creator), |
| 28495 | None, |
| 28496 | ) |
| 28497 | .await; |
| 28498 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 28499 | |
| 28500 | let (rows, total) = |
| 28501 | hezarfen_backend::db::rag_output::list_for(&db, &CourseNoteId::from_key(¬e), None, 0) |
| 28502 | .await |
| 28503 | .unwrap(); |
| 28504 | assert!(rows.is_empty() && total == 0, "a refusal wrote a row"); |
| 28505 | } |
| 28506 | |
| 28507 | /// With no AI service connected the door answers `503` and dispatches nothing: |
| 28508 | /// a `202` here would promise a reindex nothing could ever run. |
| 28509 | #[tokio::test] |
| 28510 | async fn course_note_rag_reindex_reports_503_and_writes_nothing_without_a_service() { |
| 28511 | // `app_and_db` wires no AI bridge in — the same "no service connected" |
| 28512 | // state a school is in before its AI features are provisioned. |
| 28513 | let (app, db) = app_and_db().await; |
| 28514 | let creator = login_as(&app, &db, "reindex_off_teacher", "teacher").await; |
| 28515 | let course = create_course(&app, &creator, "reindex_off").await; |
| 28516 | let note = create_course_note(&app, &creator, &course, "unindexed").await; |
| 28517 | |
| 28518 | let res = send( |
| 28519 | &app, |
| 28520 | "POST", |
| 28521 | &format!("/course-notes/{note}/rag/reindex"), |
| 28522 | Some(&creator), |
| 28523 | None, |
| 28524 | ) |
| 28525 | .await; |
| 28526 | assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); |
| 28527 | assert!( |
| 28528 | res.body["error"].as_str().is_some_and(|e| !e.is_empty()), |
| 28529 | "{}", |
| 28530 | res.body |
| 28531 | ); |
| 28532 | |
| 28533 | let (rows, total) = |
| 28534 | hezarfen_backend::db::rag_output::list_for(&db, &CourseNoteId::from_key(¬e), None, 0) |
| 28535 | .await |
| 28536 | .unwrap(); |
| 28537 | assert!( |
| 28538 | rows.is_empty() && total == 0, |
| 28539 | "reindex dispatched while no service was connected" |
| 28540 | ); |
| 28541 | } |
| 28542 | |
| 28543 | // ========================================================================= |
| 28544 | // Multi-school isolation probes (REFUTE lane B). Two schools, same usernames. |
| 28545 | // ========================================================================= |
| 28546 | |
| 28547 | use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolStatus, SchoolId, Tenants}; |
| 28548 | |
| 28549 | /// Demo (school A) plus a second school "beta" (school B), and the registry. |
| 28550 | async fn two_schools() -> ( |
| 28551 | axum::Router, |
| 28552 | hezarfen_backend::database::Database, |
| 28553 | hezarfen_backend::database::Database, |
| 28554 | Tenants, |
| 28555 | ) { |
| 28556 | let (app, db_a, tenants) = common::app_and_tenants().await; |
| 28557 | let slug_b = SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).expect("beta id"); |
| 28558 | let db_b = tenants |
| 28559 | .create( |
| 28560 | slug_b, |
| 28561 | "Beta Koleji", |
| 28562 | ModuleSet::all(), |
| 28563 | ) |
| 28564 | .await |
| 28565 | .expect("school B"); |
| 28566 | (app, db_a, db_b, tenants) |
| 28567 | } |
| 28568 | |
| 28569 | /// The second school for [`common::deployment_with`], which creates the named |
| 28570 | /// schools itself — the demo school comes with the deployment it boots, so |
| 28571 | /// only `beta` is named here. |
| 28572 | const TWO_SCHOOLS: &[(&str, &str)] = &[("beta", "Beta Koleji")]; |
| 28573 | |
| 28574 | /// One school's handle out of the registry. |
| 28575 | async fn school_db(tenants: &Tenants, slug: &str) -> hezarfen_backend::database::Database { |
| 28576 | tenants |
| 28577 | .get(&common::school_id(slug)) |
| 28578 | .await |
| 28579 | .unwrap_or_else(|err| panic!("the {slug} handle: {err}")) |
| 28580 | } |
| 28581 | |
| 28582 | /// Every list surface that takes no path parameter — the sweep target. |
| 28583 | const LIST_ROUTES: [&str; 19] = [ |
| 28584 | "/users", |
| 28585 | "/notes", |
| 28586 | "/messages", |
| 28587 | "/events", |
| 28588 | "/appointments", |
| 28589 | "/appointments/slots", |
| 28590 | "/courses", |
| 28591 | "/courses/me", |
| 28592 | "/classes", |
| 28593 | "/exams", |
| 28594 | "/meals/menus", |
| 28595 | "/payments/plans", |
| 28596 | "/work/me", |
| 28597 | "/pomodoro/me", |
| 28598 | "/questions", |
| 28599 | "/bank-questions", |
| 28600 | "/terms", |
| 28601 | "/boards", |
| 28602 | "/chatbot/threads", |
| 28603 | ]; |
| 28604 | |
| 28605 | /// Fill school B with one row of as many kinds as a single admin can mint. |
| 28606 | async fn seed_school_b(app: &axum::Router, cookie: &str) -> serde_json::Value { |
| 28607 | let course = create_course(app, cookie, "B Course").await; |
| 28608 | let subject = create_subject(app, cookie, &course, "B Subject").await; |
| 28609 | // The exam keys on the instance an instance-teaching şube carries, so the |
| 28610 | // calendar, the şube (which must sit in a year to take an exam) and that |
| 28611 | // pair come first. |
| 28612 | let year = ensure_year(app, cookie).await; |
| 28613 | let term = create_term(app, cookie, &year, "1. Dönem").await; |
| 28614 | let note = send( |
| 28615 | app, |
| 28616 | "POST", |
| 28617 | "/notes", |
| 28618 | Some(cookie), |
| 28619 | Some(json!({ "title": "b-note", "content": "secret of B" })), |
| 28620 | ) |
| 28621 | .await; |
| 28622 | assert_eq!(note.status, StatusCode::CREATED, "{}", note.body); |
| 28623 | let event = send( |
| 28624 | app, |
| 28625 | "POST", |
| 28626 | "/events", |
| 28627 | Some(cookie), |
| 28628 | Some(json!({ "title": "b-event", "description": "B only" })), |
| 28629 | ) |
| 28630 | .await; |
| 28631 | assert_eq!(event.status, StatusCode::CREATED, "{}", event.body); |
| 28632 | let class_id = create_class(app, cookie, "9-B", json!({ "year": year })).await; |
| 28633 | let instance_id = attach_instance(app, cookie, &class_id, &course).await; |
| 28634 | let exam = create_exam(app, cookie, &instance_id, &term, "B Exam", "yazili").await; |
| 28635 | let board = send( |
| 28636 | app, |
| 28637 | "POST", |
| 28638 | "/boards", |
| 28639 | Some(cookie), |
| 28640 | Some(json!({ "title": "b-board", "participants": [] })), |
| 28641 | ) |
| 28642 | .await; |
| 28643 | assert_eq!(board.status, StatusCode::CREATED, "{}", board.body); |
| 28644 | let course_note = send( |
| 28645 | app, |
| 28646 | "POST", |
| 28647 | "/course-notes", |
| 28648 | Some(cookie), |
| 28649 | Some(json!({ "course": course, "title": "b-cnote", "content": "body" })), |
| 28650 | ) |
| 28651 | .await; |
| 28652 | assert_eq!( |
| 28653 | course_note.status, |
| 28654 | StatusCode::CREATED, |
| 28655 | "{}", |
| 28656 | course_note.body |
| 28657 | ); |
| 28658 | let bank = send( |
| 28659 | app, |
| 28660 | "POST", |
| 28661 | "/bank-questions", |
| 28662 | Some(cookie), |
| 28663 | Some( |
| 28664 | json!({ "subject_id": subject, "text": "B?", "kind": "choice", "points": 10, |
| 28665 | "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], |
| 28666 | "correct": "c1" }), |
| 28667 | ), |
| 28668 | ) |
| 28669 | .await; |
| 28670 | assert_eq!(bank.status, StatusCode::CREATED, "{}", bank.body); |
| 28671 | let thread = send( |
| 28672 | app, |
| 28673 | "POST", |
| 28674 | "/chatbot/threads", |
| 28675 | Some(cookie), |
| 28676 | Some(json!({})), |
| 28677 | ) |
| 28678 | .await; |
| 28679 | assert_eq!(thread.status, StatusCode::CREATED, "{}", thread.body); |
| 28680 | |
| 28681 | let idf = |what: &str, v: &serde_json::Value| -> String { |
| 28682 | v["id"] |
| 28683 | .as_str() |
| 28684 | .unwrap_or_else(|| panic!("{what} response has no id: {v}")) |
| 28685 | .to_string() |
| 28686 | }; |
| 28687 | json!({ |
| 28688 | "course": course, |
| 28689 | "subject": subject, |
| 28690 | "exam": exam, |
| 28691 | "note": idf("note", ¬e.body), |
| 28692 | "event": idf("event", &event.body), |
| 28693 | "class": class_id, |
| 28694 | "instance": instance_id, |
| 28695 | "board": idf("board", &board.body), |
| 28696 | "course_note": idf("course_note", &course_note.body), |
| 28697 | "bank": idf("bank", &bank.body), |
| 28698 | "thread": idf("thread", &thread.body), |
| 28699 | }) |
| 28700 | } |
| 28701 | |
| 28702 | /// Invariant 1, read side: with A's cookie every list surface answers with A's |
| 28703 | /// own rows only — the totals do not move when B fills up. |
| 28704 | #[tokio::test] |
| 28705 | async fn probe_cross_school_lists_show_only_own_rows() { |
| 28706 | let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 28707 | probe_cross_school_lists_show_only_own_rows_on(&app, &tenants).await; |
| 28708 | } |
| 28709 | |
| 28710 | /// [`probe_cross_school_lists_show_only_own_rows`] against a second, |
| 28711 | /// independent deployment — the probe body is shared, the deployment is not. |
| 28712 | #[tokio::test] |
| 28713 | async fn remote_probe_cross_school_lists_show_only_own_rows() { |
| 28714 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 28715 | probe_cross_school_lists_show_only_own_rows_on(&d.app, &d.tenants).await; |
| 28716 | } |
| 28717 | |
| 28718 | async fn probe_cross_school_lists_show_only_own_rows_on(app: &axum::Router, tenants: &Tenants) { |
| 28719 | let db_a = school_db(tenants, DEMO_SCHOOL_ID).await; |
| 28720 | let db_b = school_db(tenants, "beta").await; |
| 28721 | let a = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ada", "admin").await; |
| 28722 | let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 28723 | |
| 28724 | let mut before = Vec::new(); |
| 28725 | for route in LIST_ROUTES { |
| 28726 | let res = send(app, "GET", route, Some(&a), None).await; |
| 28727 | assert_eq!(res.status, StatusCode::OK, "GET {route} as A: {}", res.body); |
| 28728 | before.push(common::total(&res.body)); |
| 28729 | } |
| 28730 | |
| 28731 | let ids = seed_school_b(app, &b).await; |
| 28732 | |
| 28733 | for (i, route) in LIST_ROUTES.iter().enumerate() { |
| 28734 | let res = send(app, "GET", route, Some(&a), None).await; |
| 28735 | assert_eq!(res.status, StatusCode::OK, "GET {route} as A: {}", res.body); |
| 28736 | assert_eq!( |
| 28737 | common::total(&res.body), |
| 28738 | before[i], |
| 28739 | "GET {route} under A's cookie moved after B created rows: {}", |
| 28740 | res.body |
| 28741 | ); |
| 28742 | let dump = res.body.to_string(); |
| 28743 | for key in [ |
| 28744 | "secret of B", |
| 28745 | "b-note", |
| 28746 | "b-event", |
| 28747 | "9-B", |
| 28748 | "b-board", |
| 28749 | "B Course", |
| 28750 | ] { |
| 28751 | assert!(!dump.contains(key), "GET {route} leaked B's {key}: {dump}"); |
| 28752 | } |
| 28753 | } |
| 28754 | // and B still sees its own. |
| 28755 | let res = send(app, "GET", "/notes", Some(&b), None).await; |
| 28756 | assert_eq!(common::total(&res.body), 1, "{}", res.body); |
| 28757 | assert!(ids["note"].is_string()); |
| 28758 | } |
| 28759 | |
| 28760 | /// Invariant 1, id side: a record minted in B is a 404 under A's cookie on |
| 28761 | /// every verb — never a 200, never a 500. |
| 28762 | #[tokio::test] |
| 28763 | async fn probe_cross_school_ids_are_not_found_under_the_other_cookie() { |
| 28764 | let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 28765 | probe_cross_school_ids_are_not_found_under_the_other_cookie_on(&app, &tenants).await; |
| 28766 | } |
| 28767 | |
| 28768 | /// [`probe_cross_school_ids_are_not_found_under_the_other_cookie`] against a |
| 28769 | /// second, independent deployment — the probe body is shared, the deployment is not. |
| 28770 | #[tokio::test] |
| 28771 | async fn remote_probe_cross_school_ids_are_not_found_under_the_other_cookie() { |
| 28772 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 28773 | probe_cross_school_ids_are_not_found_under_the_other_cookie_on(&d.app, &d.tenants).await; |
| 28774 | } |
| 28775 | |
| 28776 | async fn probe_cross_school_ids_are_not_found_under_the_other_cookie_on( |
| 28777 | app: &axum::Router, |
| 28778 | tenants: &Tenants, |
| 28779 | ) { |
| 28780 | let db_a = school_db(tenants, DEMO_SCHOOL_ID).await; |
| 28781 | let db_b = school_db(tenants, "beta").await; |
| 28782 | let a = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ada", "admin").await; |
| 28783 | let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 28784 | let ids = seed_school_b(app, &b).await; |
| 28785 | let s = |k: &str| ids[k].as_str().unwrap().to_string(); |
| 28786 | |
| 28787 | let targets: Vec<(String, serde_json::Value)> = vec![ |
| 28788 | (format!("/notes/{}", s("note")), json!({ "title": "x" })), |
| 28789 | (format!("/events/{}", s("event")), json!({ "title": "x" })), |
| 28790 | (format!("/courses/{}", s("course")), json!({ "title": "x" })), |
| 28791 | (format!("/exams/{}", s("exam")), json!({ "title": "x" })), |
| 28792 | ( |
| 28793 | format!("/subjects/{}", s("subject")), |
| 28794 | json!({ "name": "x" }), |
| 28795 | ), |
| 28796 | (format!("/classes/{}", s("class")), json!({ "name": "x" })), |
| 28797 | (format!("/boards/{}", s("board")), json!({ "title": "x" })), |
| 28798 | ( |
| 28799 | format!("/course-notes/{}", s("course_note")), |
| 28800 | json!({ "title": "x" }), |
| 28801 | ), |
| 28802 | ( |
| 28803 | format!("/bank-questions/{}", s("bank")), |
| 28804 | json!({ "text": "x" }), |
| 28805 | ), |
| 28806 | ]; |
| 28807 | |
| 28808 | for (uri, patch) in targets { |
| 28809 | for (method, body) in [ |
| 28810 | ("GET", None), |
| 28811 | ("PATCH", Some(patch.clone())), |
| 28812 | ("DELETE", None), |
| 28813 | ] { |
| 28814 | let res = send(app, method, &uri, Some(&a), body).await; |
| 28815 | assert_ne!( |
| 28816 | res.status, |
| 28817 | StatusCode::OK, |
| 28818 | "{method} {uri} under A returned 200 for a row that lives in B: {}", |
| 28819 | res.body |
| 28820 | ); |
| 28821 | assert_ne!( |
| 28822 | res.status, |
| 28823 | StatusCode::NO_CONTENT, |
| 28824 | "{method} {uri} under A deleted/updated a row that lives in B" |
| 28825 | ); |
| 28826 | assert!( |
| 28827 | !res.status.is_server_error(), |
| 28828 | "{method} {uri} under A: {} {}", |
| 28829 | res.status, |
| 28830 | res.body |
| 28831 | ); |
| 28832 | } |
| 28833 | } |
| 28834 | |
| 28835 | // The one list surface that takes its scope from a query parameter: B's |
| 28836 | // course id under A's cookie must not open B's notes. |
| 28837 | let res = send( |
| 28838 | app, |
| 28839 | "GET", |
| 28840 | &format!("/course-notes?course={}", s("course")), |
| 28841 | Some(&a), |
| 28842 | None, |
| 28843 | ) |
| 28844 | .await; |
| 28845 | assert_ne!( |
| 28846 | res.status, |
| 28847 | StatusCode::OK, |
| 28848 | "GET /course-notes?course=<B course> under A's cookie: {}", |
| 28849 | res.body |
| 28850 | ); |
| 28851 | assert!(!res.status.is_server_error(), "{} {}", res.status, res.body); |
| 28852 | |
| 28853 | // B's rows survived every one of A's attempts. |
| 28854 | for (uri, _) in [ |
| 28855 | (format!("/notes/{}", s("note")), ()), |
| 28856 | (format!("/courses/{}", s("course")), ()), |
| 28857 | (format!("/boards/{}", s("board")), ()), |
| 28858 | ] { |
| 28859 | let res = send(app, "GET", &uri, Some(&b), None).await; |
| 28860 | assert_eq!( |
| 28861 | res.status, |
| 28862 | StatusCode::OK, |
| 28863 | "B still owns {uri}: {}", |
| 28864 | res.body |
| 28865 | ); |
| 28866 | } |
| 28867 | } |
| 28868 | |
| 28869 | /// Invariant 1, body side: an id from B carried in a request *body* under A's |
| 28870 | /// cookie must be refused, never silently linked. |
| 28871 | #[tokio::test] |
| 28872 | async fn probe_cross_school_ids_in_bodies_are_refused() { |
| 28873 | let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 28874 | probe_cross_school_ids_in_bodies_are_refused_on(&app, &tenants).await; |
| 28875 | } |
| 28876 | |
| 28877 | /// [`probe_cross_school_ids_in_bodies_are_refused`] against a second, |
| 28878 | /// independent deployment — the probe body is shared, the deployment is not. |
| 28879 | #[tokio::test] |
| 28880 | async fn remote_probe_cross_school_ids_in_bodies_are_refused() { |
| 28881 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 28882 | probe_cross_school_ids_in_bodies_are_refused_on(&d.app, &d.tenants).await; |
| 28883 | } |
| 28884 | |
| 28885 | async fn probe_cross_school_ids_in_bodies_are_refused_on(app: &axum::Router, tenants: &Tenants) { |
| 28886 | let db_a = school_db(tenants, DEMO_SCHOOL_ID).await; |
| 28887 | let db_b = school_db(tenants, "beta").await; |
| 28888 | let a_admin = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ada", "admin").await; |
| 28889 | let a_student = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ali", "student").await; |
| 28890 | let a_parent = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "veli", "parent").await; |
| 28891 | let b_admin = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 28892 | common::login_as_school(app, &db_b, "beta", "bstudent", "student").await; |
| 28893 | |
| 28894 | let b_user = { |
| 28895 | let res = send(app, "GET", "/users", Some(&b_admin), None).await; |
| 28896 | assert_eq!(res.status, StatusCode::OK); |
| 28897 | id_of(&common::items(&res.body)[0]) |
| 28898 | }; |
| 28899 | let a_parent_id = common::me_id(app, &a_parent).await; |
| 28900 | let a_course = create_course(app, &a_admin, "A Course").await; |
| 28901 | let a_board = { |
| 28902 | let res = send( |
| 28903 | app, |
| 28904 | "POST", |
| 28905 | "/boards", |
| 28906 | Some(&a_admin), |
| 28907 | Some(json!({ "title": "a-board", "participants": [] })), |
| 28908 | ) |
| 28909 | .await; |
| 28910 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 28911 | id_of(&res.body) |
| 28912 | }; |
| 28913 | |
| 28914 | let cases: Vec<(&str, String, &str, serde_json::Value)> = vec![ |
| 28915 | ( |
| 28916 | "message to a B recipient", |
| 28917 | "/messages".into(), |
| 28918 | &a_student, |
| 28919 | json!({ "recipient_id": b_user, "subject": "hi", "body": "cross" }), |
| 28920 | ), |
| 28921 | ( |
| 28922 | "enroll a B user into an A course", |
| 28923 | format!("/courses/{a_course}/enrollments"), |
| 28924 | &a_admin, |
| 28925 | json!({ "user_id": b_user }), |
| 28926 | ), |
| 28927 | ( |
| 28928 | "assign a B user as an A course teacher", |
| 28929 | format!("/courses/{a_course}/teachers"), |
| 28930 | &a_admin, |
| 28931 | json!({ "user_id": b_user }), |
| 28932 | ), |
| 28933 | ( |
| 28934 | "link a B student to an A parent", |
| 28935 | format!("/users/{a_parent_id}/students"), |
| 28936 | &a_admin, |
| 28937 | json!({ "user_id": b_user }), |
| 28938 | ), |
| 28939 | ( |
| 28940 | "invite a B user onto an A board", |
| 28941 | format!("/boards/{a_board}/invite"), |
| 28942 | &a_admin, |
| 28943 | json!({ "participants": [b_user] }), |
| 28944 | ), |
| 28945 | ( |
| 28946 | "create an A board with a B participant", |
| 28947 | "/boards".into(), |
| 28948 | &a_admin, |
| 28949 | json!({ "title": "x", "participants": [b_user] }), |
| 28950 | ), |
| 28951 | ]; |
| 28952 | |
| 28953 | for (what, uri, cookie, body) in cases { |
| 28954 | let res = send(app, "POST", &uri, Some(cookie), Some(body)).await; |
| 28955 | assert!( |
| 28956 | res.status.is_client_error(), |
| 28957 | "{what}: POST {uri} answered {} (expected a 4xx refusal): {}", |
| 28958 | res.status, |
| 28959 | res.body |
| 28960 | ); |
| 28961 | assert!( |
| 28962 | !res.body.to_string().contains(&b_user), |
| 28963 | "{what}: POST {uri} echoed B's user id back: {}", |
| 28964 | res.body |
| 28965 | ); |
| 28966 | } |
| 28967 | } |
| 28968 | |
| 28969 | /// Invariant 2: a suspended school is refused everywhere, and a resume brings |
| 28970 | /// the *same* cookie back to life. |
| 28971 | #[tokio::test] |
| 28972 | async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it() { |
| 28973 | let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 28974 | probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it_on(&app, &tenants) |
| 28975 | .await; |
| 28976 | } |
| 28977 | |
| 28978 | /// [`probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it`] |
| 28979 | /// against a second, independent deployment — shared body, own deployment. |
| 28980 | #[tokio::test] |
| 28981 | async fn remote_probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it() { |
| 28982 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 28983 | probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it_on(&d.app, &d.tenants) |
| 28984 | .await; |
| 28985 | } |
| 28986 | |
| 28987 | async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it_on( |
| 28988 | app: &axum::Router, |
| 28989 | tenants: &Tenants, |
| 28990 | ) { |
| 28991 | let db_b = school_db(tenants, "beta").await; |
| 28992 | let slug_b = SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap(); |
| 28993 | let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 28994 | |
| 28995 | // Alive first. |
| 28996 | let res = send(app, "GET", "/auth/me", Some(&b), None).await; |
| 28997 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 28998 | |
| 28999 | tenants |
| 29000 | .set_status(&slug_b, SchoolStatus::Suspended) |
| 29001 | .await |
| 29002 | .expect("suspend"); |
| 29003 | |
| 29004 | // The already-issued cookie, on the very next request. |
| 29005 | for route in ["/auth/me", "/users", "/notes", "/courses", "/settings"] { |
| 29006 | let res = send(app, "GET", route, Some(&b), None).await; |
| 29007 | assert_eq!( |
| 29008 | res.status, |
| 29009 | StatusCode::FORBIDDEN, |
| 29010 | "GET {route} with a suspended school's live cookie: {} {}", |
| 29011 | res.status, |
| 29012 | res.body |
| 29013 | ); |
| 29014 | } |
| 29015 | // A write too. |
| 29016 | let res = send( |
| 29017 | app, |
| 29018 | "POST", |
| 29019 | "/notes", |
| 29020 | Some(&b), |
| 29021 | Some(json!({ "title": "t", "content": "c" })), |
| 29022 | ) |
| 29023 | .await; |
| 29024 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 29025 | |
| 29026 | // Login is no exception. |
| 29027 | let res = send( |
| 29028 | app, |
| 29029 | "POST", |
| 29030 | "/auth/login", |
| 29031 | None, |
| 29032 | Some(json!({ "username": "boran", "password": "secret1" })), |
| 29033 | ) |
| 29034 | .await; |
| 29035 | assert_eq!( |
| 29036 | res.status, |
| 29037 | StatusCode::FORBIDDEN, |
| 29038 | "login into a suspended school: {}", |
| 29039 | res.body |
| 29040 | ); |
| 29041 | |
| 29042 | // Register into it is refused too. |
| 29043 | let res = send( |
| 29044 | app, |
| 29045 | "POST", |
| 29046 | "/auth/register", |
| 29047 | None, |
| 29048 | Some(json!({ "school": common::school_wire("beta"), "username": "newcomer", "password": "secret1" })), |
| 29049 | ) |
| 29050 | .await; |
| 29051 | assert_eq!( |
| 29052 | res.status, |
| 29053 | StatusCode::FORBIDDEN, |
| 29054 | "register into a suspended school: {}", |
| 29055 | res.body |
| 29056 | ); |
| 29057 | |
| 29058 | // Resume: the same cookie works again — the session rows were not deleted. |
| 29059 | tenants |
| 29060 | .set_status(&slug_b, SchoolStatus::Active) |
| 29061 | .await |
| 29062 | .expect("resume"); |
| 29063 | let res = send(app, "GET", "/auth/me", Some(&b), None).await; |
| 29064 | assert_eq!( |
| 29065 | res.status, |
| 29066 | StatusCode::OK, |
| 29067 | "the same cookie after a resume: {}", |
| 29068 | res.body |
| 29069 | ); |
| 29070 | assert_eq!(res.body["username"], "boran"); |
| 29071 | } |
| 29072 | |
| 29073 | /// Invariant 3: no cookie is usable as another kind of cookie. The last case — |
| 29074 | /// a real token from school A presented under school B's prefix — is the one |
| 29075 | /// that would be a full takeover. |
| 29076 | #[tokio::test] |
| 29077 | async fn probe_cookie_confusion_is_impossible_both_ways() { |
| 29078 | let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 29079 | probe_cookie_confusion_is_impossible_both_ways_on(&app, &tenants).await; |
| 29080 | } |
| 29081 | |
| 29082 | /// [`probe_cookie_confusion_is_impossible_both_ways`] against a second, |
| 29083 | /// independent deployment — the probe body is shared, the deployment is not. |
| 29084 | #[tokio::test] |
| 29085 | async fn remote_probe_cookie_confusion_is_impossible_both_ways() { |
| 29086 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 29087 | probe_cookie_confusion_is_impossible_both_ways_on(&d.app, &d.tenants).await; |
| 29088 | } |
| 29089 | |
| 29090 | async fn probe_cookie_confusion_is_impossible_both_ways_on(app: &axum::Router, tenants: &Tenants) { |
| 29091 | let db_a = school_db(tenants, DEMO_SCHOOL_ID).await; |
| 29092 | let db_b = school_db(tenants, "beta").await; |
| 29093 | let a = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ada", "admin").await; |
| 29094 | let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 29095 | let token_a = common::cookie_token(&a).to_string(); |
| 29096 | |
| 29097 | hezarfen_backend::service::builder::ensure( |
| 29098 | tenants.control(), |
| 29099 | Username::try_new("operator").unwrap(), |
| 29100 | Password::try_new("secret1").unwrap(), |
| 29101 | ) |
| 29102 | .await |
| 29103 | .expect("seed the builder"); |
| 29104 | let res = send( |
| 29105 | app, |
| 29106 | "POST", |
| 29107 | "/builder/login", |
| 29108 | None, |
| 29109 | Some(json!({ "username": "operator", "password": "secret1" })), |
| 29110 | ) |
| 29111 | .await; |
| 29112 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 29113 | let builder_cookie = res.cookie.expect("builder cookie"); |
| 29114 | let builder_token = common::cookie_token(&builder_cookie).to_string(); |
| 29115 | |
| 29116 | // (1) builder cookie on a school surface. |
| 29117 | for route in ["/auth/me", "/users", "/notes"] { |
| 29118 | let res = send(app, "GET", route, Some(&builder_cookie), None).await; |
| 29119 | assert_eq!( |
| 29120 | res.status, |
| 29121 | StatusCode::UNAUTHORIZED, |
| 29122 | "builder cookie on GET {route}: {} {}", |
| 29123 | res.status, |
| 29124 | res.body |
| 29125 | ); |
| 29126 | } |
| 29127 | // (2) school cookie on the builder surface. |
| 29128 | for cookie in [&a, &b] { |
| 29129 | for route in ["/builder/me", "/schools"] { |
| 29130 | let res = send(app, "GET", route, Some(cookie), None).await; |
| 29131 | assert_eq!( |
| 29132 | res.status, |
| 29133 | StatusCode::UNAUTHORIZED, |
| 29134 | "school cookie on GET {route}: {} {}", |
| 29135 | res.status, |
| 29136 | res.body |
| 29137 | ); |
| 29138 | } |
| 29139 | } |
| 29140 | // (3) bare token, no dot. |
| 29141 | for raw in [ |
| 29142 | format!("session={token_a}"), |
| 29143 | format!("session={builder_token}"), |
| 29144 | "session=.".to_string(), |
| 29145 | format!("session=.{token_a}"), |
| 29146 | format!("session={token_a}."), |
| 29147 | ] { |
| 29148 | for route in ["/auth/me", "/builder/me"] { |
| 29149 | let res = send(app, "GET", route, Some(&raw), None).await; |
| 29150 | assert_eq!( |
| 29151 | res.status, |
| 29152 | StatusCode::UNAUTHORIZED, |
| 29153 | "{raw} on GET {route}: {} {}", |
| 29154 | res.status, |
| 29155 | res.body |
| 29156 | ); |
| 29157 | } |
| 29158 | } |
| 29159 | // (4) a builder token wearing a school prefix. |
| 29160 | for raw in [ |
| 29161 | format!("session={DEMO_SCHOOL_ID}.{builder_token}"), |
| 29162 | format!("session={}.{}", hezarfen_backend::tenant::BETA_SCHOOL_ID, builder_token), |
| 29163 | ] { |
| 29164 | let res = send(app, "GET", "/auth/me", Some(&raw), None).await; |
| 29165 | assert_eq!( |
| 29166 | res.status, |
| 29167 | StatusCode::UNAUTHORIZED, |
| 29168 | "{raw} on /auth/me: {} {}", |
| 29169 | res.status, |
| 29170 | res.body |
| 29171 | ); |
| 29172 | } |
| 29173 | // (5) THE one: A's live token under B's prefix, and B's under A's. |
| 29174 | let token_b = common::cookie_token(&b).to_string(); |
| 29175 | for (raw, whose) in [ |
| 29176 | (format!("session={}.{token_a}", hezarfen_backend::tenant::BETA_SCHOOL_ID), "A's token under B"), |
| 29177 | (format!("session={DEMO_SCHOOL_ID}.{token_b}"), "B's token under A"), |
| 29178 | ] { |
| 29179 | for route in ["/auth/me", "/users", "/notes", "/settings"] { |
| 29180 | let res = send(app, "GET", route, Some(&raw), None).await; |
| 29181 | assert_eq!( |
| 29182 | res.status, |
| 29183 | StatusCode::UNAUTHORIZED, |
| 29184 | "{whose} on GET {route}: {} {}", |
| 29185 | res.status, |
| 29186 | res.body |
| 29187 | ); |
| 29188 | } |
| 29189 | } |
| 29190 | // (6) a school cookie naming a school that does not exist. |
| 29191 | let res = send( |
| 29192 | app, |
| 29193 | "GET", |
| 29194 | "/auth/me", |
| 29195 | Some(&format!("session=nosuchschool.{token_a}")), |
| 29196 | None, |
| 29197 | ) |
| 29198 | .await; |
| 29199 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); |
| 29200 | } |
| 29201 | |
| 29202 | /// Invariant 4: `POST /auth/register` names its school, registers into that one |
| 29203 | /// only, and an unknown school is indistinguishable from a bad credential. |
| 29204 | #[tokio::test] |
| 29205 | async fn probe_register_is_scoped_to_the_named_school() { |
| 29206 | let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 29207 | probe_register_is_scoped_to_the_named_school_on(&app, &tenants).await; |
| 29208 | } |
| 29209 | |
| 29210 | /// [`probe_register_is_scoped_to_the_named_school`] against a second, |
| 29211 | /// independent deployment — the probe body is shared, the deployment is not. |
| 29212 | #[tokio::test] |
| 29213 | async fn remote_probe_register_is_scoped_to_the_named_school() { |
| 29214 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 29215 | probe_register_is_scoped_to_the_named_school_on(&d.app, &d.tenants).await; |
| 29216 | } |
| 29217 | |
| 29218 | async fn probe_register_is_scoped_to_the_named_school_on(app: &axum::Router, tenants: &Tenants) { |
| 29219 | let db_a = school_db(tenants, DEMO_SCHOOL_ID).await; |
| 29220 | let db_b = school_db(tenants, "beta").await; |
| 29221 | |
| 29222 | // Missing `school` is a 4xx, not a silent default. |
| 29223 | let res = send( |
| 29224 | app, |
| 29225 | "POST", |
| 29226 | "/auth/register", |
| 29227 | None, |
| 29228 | Some(json!({ "username": "noschool", "password": "secret1" })), |
| 29229 | ) |
| 29230 | .await; |
| 29231 | assert!( |
| 29232 | res.status.is_client_error(), |
| 29233 | "register with no school: {} {}", |
| 29234 | res.status, |
| 29235 | res.body |
| 29236 | ); |
| 29237 | |
| 29238 | // The same username in both schools, independently. |
| 29239 | for (slug, db) in [(DEMO_SCHOOL_ID, &db_a), ("beta", &db_b)] { |
| 29240 | let res = send( |
| 29241 | app, |
| 29242 | "POST", |
| 29243 | "/auth/register", |
| 29244 | None, |
| 29245 | Some(json!({ "school": common::school_wire(slug), "username": "ayse", "password": "secret1" })), |
| 29246 | ) |
| 29247 | .await; |
| 29248 | assert_eq!( |
| 29249 | res.status, |
| 29250 | StatusCode::CREATED, |
| 29251 | "register into {slug}: {}", |
| 29252 | res.body |
| 29253 | ); |
| 29254 | let found: i64 = |
| 29255 | sqlx::query_scalar("SELECT count(*) FROM app_user WHERE username = 'ayse'") |
| 29256 | .fetch_one(db) |
| 29257 | .await |
| 29258 | .unwrap(); |
| 29259 | assert_eq!(found, 1, "exactly one 'ayse' in {slug}"); |
| 29260 | } |
| 29261 | |
| 29262 | // The login body names no school, so the customer list is not probeable |
| 29263 | // there at all. The parity that remains is unknown-username vs bad |
| 29264 | // password: same 401, same body, same argon2 bill. |
| 29265 | let unknown_user = send( |
| 29266 | app, |
| 29267 | "POST", |
| 29268 | "/auth/login", |
| 29269 | None, |
| 29270 | Some(json!({ "username": "nobody-here", "password": "secret1" })), |
| 29271 | ) |
| 29272 | .await; |
| 29273 | let bad_pass = send( |
| 29274 | app, |
| 29275 | "POST", |
| 29276 | "/auth/login", |
| 29277 | None, |
| 29278 | Some(json!({ "username": "ayse", "password": "wrongpw1" })), |
| 29279 | ) |
| 29280 | .await; |
| 29281 | assert_eq!( |
| 29282 | unknown_user.status, |
| 29283 | StatusCode::UNAUTHORIZED, |
| 29284 | "{}", |
| 29285 | unknown_user.body |
| 29286 | ); |
| 29287 | assert_eq!(unknown_user.status, bad_pass.status, "status differs"); |
| 29288 | assert_eq!( |
| 29289 | unknown_user.body, bad_pass.body, |
| 29290 | "an unknown username answers differently from a bad password: {} vs {}", |
| 29291 | unknown_user.body, bad_pass.body |
| 29292 | ); |
| 29293 | |
| 29294 | // Register against an unknown school: same treatment. |
| 29295 | let reg_unknown = send( |
| 29296 | app, |
| 29297 | "POST", |
| 29298 | "/auth/register", |
| 29299 | None, |
| 29300 | Some(json!({ "school": "not-a-school", "username": "zeynep", "password": "secret1" })), |
| 29301 | ) |
| 29302 | .await; |
| 29303 | assert_eq!( |
| 29304 | reg_unknown.status, |
| 29305 | StatusCode::UNAUTHORIZED, |
| 29306 | "register into an unknown school: {} {}", |
| 29307 | reg_unknown.status, |
| 29308 | reg_unknown.body |
| 29309 | ); |
| 29310 | } |
| 29311 | |
| 29312 | /// Invariant 5: an upload under A lands under `FILES_PATH/A/` and is a 404 |
| 29313 | /// under B's cookie even with the exact ids. |
| 29314 | #[tokio::test] |
| 29315 | async fn probe_uploaded_files_are_school_scoped() { |
| 29316 | let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 29317 | probe_uploaded_files_are_school_scoped_on(&app, &tenants, common::files_dir().as_path()).await; |
| 29318 | } |
| 29319 | |
| 29320 | /// [`probe_uploaded_files_are_school_scoped`] against a second, independent |
| 29321 | /// deployment — the probe body is shared, the deployment is not. |
| 29322 | #[tokio::test] |
| 29323 | async fn remote_probe_uploaded_files_are_school_scoped() { |
| 29324 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 29325 | probe_uploaded_files_are_school_scoped_on(&d.app, &d.tenants, &d.files).await; |
| 29326 | } |
| 29327 | |
| 29328 | async fn probe_uploaded_files_are_school_scoped_on( |
| 29329 | app: &axum::Router, |
| 29330 | tenants: &Tenants, |
| 29331 | files: &std::path::Path, |
| 29332 | ) { |
| 29333 | let db_a = school_db(tenants, DEMO_SCHOOL_ID).await; |
| 29334 | let db_b = school_db(tenants, "beta").await; |
| 29335 | let a = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ali", "student").await; |
| 29336 | let b = common::login_as_school(app, &db_b, "beta", "ali", "student").await; |
| 29337 | |
| 29338 | let note = send( |
| 29339 | app, |
| 29340 | "POST", |
| 29341 | "/notes", |
| 29342 | Some(&a), |
| 29343 | Some(json!({ "title": "n", "content": "c" })), |
| 29344 | ) |
| 29345 | .await; |
| 29346 | assert_eq!(note.status, StatusCode::CREATED, "{}", note.body); |
| 29347 | let note_id = id_of(¬e.body); |
| 29348 | |
| 29349 | let up = common::upload_file(app, &a, ¬e_id, "a.txt", "text/plain", b"A-ONLY-BYTES").await; |
| 29350 | assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); |
| 29351 | let file_id = id_of(&up.body); |
| 29352 | |
| 29353 | // It landed under the school's own directory, and nowhere else. |
| 29354 | let a_dir = files.join(DEMO_SCHOOL_ID); |
| 29355 | let b_dir = files.join(common::school_wire("beta")); |
| 29356 | let count = |dir: &std::path::Path| { |
| 29357 | std::fs::read_dir(dir) |
| 29358 | .map(|it| it.count()) |
| 29359 | .unwrap_or_default() |
| 29360 | }; |
| 29361 | assert!(count(&a_dir) >= 1, "A's blob directory {a_dir:?} is empty"); |
| 29362 | assert_eq!( |
| 29363 | count(&b_dir), |
| 29364 | 0, |
| 29365 | "B's blob directory {b_dir:?} is not empty" |
| 29366 | ); |
| 29367 | |
| 29368 | // A reads it back. |
| 29369 | let uri = format!("/notes/{note_id}/files/{file_id}"); |
| 29370 | let (status, _, bytes) = common::send_raw(app, "GET", &uri, Some(&a), None, Vec::new()).await; |
| 29371 | assert_eq!(status, StatusCode::OK, "A reads its own file"); |
| 29372 | assert_eq!(bytes, b"A-ONLY-BYTES"); |
| 29373 | |
| 29374 | // B, with the exact ids, gets nothing — and no 500. |
| 29375 | let (status, _, bytes) = common::send_raw(app, "GET", &uri, Some(&b), None, Vec::new()).await; |
| 29376 | assert_eq!( |
| 29377 | status, |
| 29378 | StatusCode::NOT_FOUND, |
| 29379 | "B read A's file: {}", |
| 29380 | String::from_utf8_lossy(&bytes) |
| 29381 | ); |
| 29382 | assert!(!bytes.windows(12).any(|w| w == b"A-ONLY-BYTES")); |
| 29383 | |
| 29384 | let (status, _, _) = common::send_raw(app, "DELETE", &uri, Some(&b), None, Vec::new()).await; |
| 29385 | assert_eq!(status, StatusCode::NOT_FOUND, "B deleted A's file"); |
| 29386 | let (status, _, _) = common::send_raw(app, "GET", &uri, Some(&a), None, Vec::new()).await; |
| 29387 | assert_eq!(status, StatusCode::OK, "A's file survived B's DELETE"); |
| 29388 | } |
| 29389 | |
| 29390 | /// Invariant 1, the leak that would be invisible from the API: no school row |
| 29391 | /// may land in the **control** database, and the search + settings surfaces |
| 29392 | /// (which are not paged lists) stay inside the caller's school. |
| 29393 | #[tokio::test] |
| 29394 | async fn probe_school_rows_never_reach_the_control_database() { |
| 29395 | let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 29396 | probe_school_rows_never_reach_the_control_database_on(&app, &tenants).await; |
| 29397 | } |
| 29398 | |
| 29399 | /// [`probe_school_rows_never_reach_the_control_database`] against a second, |
| 29400 | /// independent deployment — the probe body is shared, the deployment is not. |
| 29401 | #[tokio::test] |
| 29402 | async fn remote_probe_school_rows_never_reach_the_control_database() { |
| 29403 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 29404 | probe_school_rows_never_reach_the_control_database_on(&d.app, &d.tenants).await; |
| 29405 | } |
| 29406 | |
| 29407 | async fn probe_school_rows_never_reach_the_control_database_on( |
| 29408 | app: &axum::Router, |
| 29409 | tenants: &Tenants, |
| 29410 | ) { |
| 29411 | let db_a = school_db(tenants, DEMO_SCHOOL_ID).await; |
| 29412 | let db_b = school_db(tenants, "beta").await; |
| 29413 | let a = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ada", "admin").await; |
| 29414 | let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 29415 | common::login_as_school(app, &db_b, "beta", "bstudent", "student").await; |
| 29416 | let ids = seed_school_b(app, &b).await; |
| 29417 | assert!(ids["course"].is_string()); |
| 29418 | |
| 29419 | // Nothing a school writes may appear in the control database. |
| 29420 | let control = tenants.control(); |
| 29421 | for table in [ |
| 29422 | "app_user", |
| 29423 | "user_session", |
| 29424 | "note", |
| 29425 | "course", |
| 29426 | "event", |
| 29427 | "message", |
| 29428 | "class_group", |
| 29429 | "board", |
| 29430 | "course_note", |
| 29431 | "bank_question", |
| 29432 | "chatbot_thread", |
| 29433 | "exam", |
| 29434 | ] { |
| 29435 | let tables: i64 = sqlx::query_scalar( |
| 29436 | "SELECT count(*) FROM information_schema.tables \ |
| 29437 | WHERE table_schema = 'public' AND table_name = $1", |
| 29438 | ) |
| 29439 | .bind(table) |
| 29440 | .fetch_one(control) |
| 29441 | .await |
| 29442 | .expect("control query"); |
| 29443 | assert_eq!( |
| 29444 | tables, 0, |
| 29445 | "the control database holds a school table `{table}`" |
| 29446 | ); |
| 29447 | } |
| 29448 | // And the control database does hold the two schools. |
| 29449 | let schools: Vec<String> = sqlx::query_scalar("SELECT name FROM school ORDER BY name") |
| 29450 | .fetch_all(control) |
| 29451 | .await |
| 29452 | .unwrap(); |
| 29453 | assert_eq!(schools, vec!["Beta Koleji".to_string(), "Demo School".to_string()]); |
| 29454 | |
| 29455 | // User search never crosses the wall. Compare the returned names, not the |
| 29456 | // raw body: a substring match over the serialized JSON also hits the hex of |
| 29457 | // a UUIDv7 id — "ada" rides inside `01a0adad-…`, whose ms-timestamp prefix |
| 29458 | // spells it for a slice of every wall-clock window — so the negative |
| 29459 | // assertion flipped with the clock instead of with the search. |
| 29460 | for (cookie, forbidden) in [(&a, "boran"), (&b, "ada")] { |
| 29461 | for q in ["b", "a", "boran", "ada", "bstudent"] { |
| 29462 | let res = send( |
| 29463 | app, |
| 29464 | "GET", |
| 29465 | &format!("/users/search?q={q}"), |
| 29466 | Some(cookie), |
| 29467 | None, |
| 29468 | ) |
| 29469 | .await; |
| 29470 | assert_eq!(res.status, StatusCode::OK, "search {q}: {}", res.body); |
| 29471 | let named = res.body["items"] |
| 29472 | .as_array() |
| 29473 | .expect("search items") |
| 29474 | .iter() |
| 29475 | .any(|item| item["username"] == forbidden || item["display_name"] == forbidden); |
| 29476 | assert!( |
| 29477 | !named, |
| 29478 | "GET /users/search?q={q} returned the other school's `{forbidden}`: {}", |
| 29479 | res.body |
| 29480 | ); |
| 29481 | } |
| 29482 | } |
| 29483 | |
| 29484 | // Settings are the school's own: moving A's leaves B's alone. |
| 29485 | let before = send(app, "GET", "/settings", Some(&b), None).await; |
| 29486 | assert_eq!(before.status, StatusCode::OK, "{}", before.body); |
| 29487 | let patched = send( |
| 29488 | app, |
| 29489 | "PATCH", |
| 29490 | "/settings", |
| 29491 | Some(&a), |
| 29492 | Some(json!({ "max_file_bytes": 4096 })), |
| 29493 | ) |
| 29494 | .await; |
| 29495 | assert_eq!(patched.status, StatusCode::OK, "{}", patched.body); |
| 29496 | assert_eq!(patched.body["max_file_bytes"], 4096); |
| 29497 | let after = send(app, "GET", "/settings", Some(&b), None).await; |
| 29498 | assert_eq!( |
| 29499 | after.body, before.body, |
| 29500 | "A's settings PATCH moved B's settings" |
| 29501 | ); |
| 29502 | |
| 29503 | // A cookie prefix that is not a well-formed slug is a 401, never a lookup. |
| 29504 | for prefix in ["DEMO", "Demo", "de mo", "de/mo", "..", "demo%2e", "control"] { |
| 29505 | let raw = format!("session={prefix}.{}", common::cookie_token(&a)); |
| 29506 | let res = send(app, "GET", "/auth/me", Some(&raw), None).await; |
| 29507 | assert_eq!( |
| 29508 | res.status, |
| 29509 | StatusCode::UNAUTHORIZED, |
| 29510 | "prefix `{prefix}`: {} {}", |
| 29511 | res.status, |
| 29512 | res.body |
| 29513 | ); |
| 29514 | } |
| 29515 | } |
| 29516 | |
| 29517 | /// Invariant 1 on the path production actually uses: every school is its own |
| 29518 | /// *database on one server*, and isolation rests on the server, not on the |
| 29519 | /// handle — a school's rows are simply not visible from another school's |
| 29520 | /// database. |
| 29521 | /// |
| 29522 | /// The two slugs are the ones that are not bare identifiers: `ata-koleji` parses |
| 29523 | /// as a subtraction unquoted, `2024school` as a duration. |
| 29524 | #[tokio::test] |
| 29525 | async fn remote_probe_remote_mode_keeps_two_schools_apart() { |
| 29526 | let d = common::deployment_with(&[("ata-koleji", "Ata"), ("2024school", "2024")]).await; |
| 29527 | let (app, tenants) = (&d.app, &d.tenants); |
| 29528 | let slug_a = SchoolId::try_parse("019732e3-7b00-7000-8000-00000000a7a1").unwrap(); |
| 29529 | let slug_b = SchoolId::try_parse("019732e3-7b00-7000-8000-000000002024").unwrap(); |
| 29530 | |
| 29531 | // Same username in both schools is one person with two memberships. |
| 29532 | // Login into the second school therefore returns a person cookie; bind |
| 29533 | // each membership so the rest of the test holds two school sessions. |
| 29534 | let mut cookies = Vec::new(); |
| 29535 | for slug in [&slug_a, &slug_b] { |
| 29536 | let creds = json!({ "school": slug.as_str(), "username": "ada", "password": "secret1" }); |
| 29537 | let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await; |
| 29538 | assert_eq!( |
| 29539 | reg.status, |
| 29540 | StatusCode::CREATED, |
| 29541 | "register in {slug}: {}", |
| 29542 | reg.body |
| 29543 | ); |
| 29544 | let db = tenants.get(slug).await.unwrap(); |
| 29545 | common::set_role(&db, "ada", "admin").await; |
| 29546 | let res = send(app, "POST", "/auth/login", None, Some(creds)).await; |
| 29547 | assert_eq!(res.status, StatusCode::OK, "login in {slug}: {}", res.body); |
| 29548 | let cookie = if res.body["schools"].is_array() { |
| 29549 | let selected = send( |
| 29550 | app, |
| 29551 | "POST", |
| 29552 | "/auth/school", |
| 29553 | res.cookie.as_deref(), |
| 29554 | Some(json!({ "school": slug.as_str() })), |
| 29555 | ) |
| 29556 | .await; |
| 29557 | assert_eq!( |
| 29558 | selected.status, |
| 29559 | StatusCode::OK, |
| 29560 | "select {slug}: {}", |
| 29561 | selected.body |
| 29562 | ); |
| 29563 | selected.cookie.expect("school cookie") |
| 29564 | } else { |
| 29565 | res.cookie.expect("cookie") |
| 29566 | }; |
| 29567 | cookies.push(cookie); |
| 29568 | } |
| 29569 | let (a, b) = (cookies[0].clone(), cookies[1].clone()); |
| 29570 | |
| 29571 | // B fills up; A must not see a single row of it. |
| 29572 | let ids = seed_school_b(app, &b).await; |
| 29573 | for route in LIST_ROUTES { |
| 29574 | let res = send(app, "GET", route, Some(&a), None).await; |
| 29575 | assert_eq!(res.status, StatusCode::OK, "GET {route} as A: {}", res.body); |
| 29576 | let dump = res.body.to_string(); |
| 29577 | for key in [ |
| 29578 | "secret of B", |
| 29579 | "b-note", |
| 29580 | "b-event", |
| 29581 | "9-B", |
| 29582 | "b-board", |
| 29583 | "B Course", |
| 29584 | ] { |
| 29585 | assert!(!dump.contains(key), "GET {route} leaked B's {key}: {dump}"); |
| 29586 | } |
| 29587 | } |
| 29588 | // Each school sees exactly its own user, and only one. |
| 29589 | for cookie in [&a, &b] { |
| 29590 | let res = send(app, "GET", "/users", Some(cookie), None).await; |
| 29591 | assert_eq!(common::total(&res.body), 1, "{}", res.body); |
| 29592 | } |
| 29593 | // A row minted in B is a 404 under A on every verb. |
| 29594 | for key in ["note", "course", "board", "event", "class"] { |
| 29595 | let id = ids[key].as_str().unwrap(); |
| 29596 | let uri = match key { |
| 29597 | "note" => format!("/notes/{id}"), |
| 29598 | "course" => format!("/courses/{id}"), |
| 29599 | "board" => format!("/boards/{id}"), |
| 29600 | "event" => format!("/events/{id}"), |
| 29601 | _ => format!("/classes/{id}"), |
| 29602 | }; |
| 29603 | for method in ["GET", "DELETE"] { |
| 29604 | let res = send(app, method, &uri, Some(&a), None).await; |
| 29605 | assert_ne!( |
| 29606 | res.status, |
| 29607 | StatusCode::OK, |
| 29608 | "{method} {uri} as A: {}", |
| 29609 | res.body |
| 29610 | ); |
| 29611 | assert_ne!(res.status, StatusCode::NO_CONTENT, "{method} {uri} as A"); |
| 29612 | assert!( |
| 29613 | !res.status.is_server_error(), |
| 29614 | "{method} {uri}: {} {}", |
| 29615 | res.status, |
| 29616 | res.body |
| 29617 | ); |
| 29618 | } |
| 29619 | let res = send(app, "GET", &uri, Some(&b), None).await; |
| 29620 | assert_eq!( |
| 29621 | res.status, |
| 29622 | StatusCode::OK, |
| 29623 | "B still owns {uri}: {}", |
| 29624 | res.body |
| 29625 | ); |
| 29626 | } |
| 29627 | |
| 29628 | // A's token under B's prefix stays a 401 on a real server too. |
| 29629 | let raw = format!("session={}.{}", slug_b, common::cookie_token(&a)); |
| 29630 | let res = send(app, "GET", "/auth/me", Some(&raw), None).await; |
| 29631 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); |
| 29632 | } |
| 29633 | |
| 29634 | // ------------------------------------------------------------------------- |
| 29635 | // Database-per-school invariants: a school is its own database on the server, |
| 29636 | // so its rows are unreachable from any other school's handle. |
| 29637 | // ------------------------------------------------------------------------- |
| 29638 | |
| 29639 | /// The server's database list, off the control handle: the control database |
| 29640 | /// itself plus every school database, named `{control}_school_{uuid hex}` — |
| 29641 | /// the school's uuid, never its slug. |
| 29642 | async fn namespace_databases(tenants: &Tenants) -> Vec<String> { |
| 29643 | let control = tenants.control(); |
| 29644 | let control_db: String = sqlx::query_scalar("SELECT current_database()") |
| 29645 | .fetch_one(control) |
| 29646 | .await |
| 29647 | .expect("current database"); |
| 29648 | let mut names: Vec<String> = sqlx::query_scalar( |
| 29649 | "SELECT datname FROM pg_database \ |
| 29650 | WHERE datname = $1 OR datname LIKE $2", |
| 29651 | ) |
| 29652 | .bind(&control_db) |
| 29653 | .bind(format!("{control_db}\\_school\\_%")) |
| 29654 | .fetch_all(control) |
| 29655 | .await |
| 29656 | .expect("database list"); |
| 29657 | names.sort(); |
| 29658 | names |
| 29659 | } |
| 29660 | |
| 29661 | /// A school database's name, read off the registry: the control database's |
| 29662 | /// name plus the school's uuid in lowercase hex, no dashes. Postgres |
| 29663 | /// truncates identifiers at 63 bytes (NAMEDATALEN - 1), and a test control |
| 29664 | /// database's `heztest_` prefix runs the name one character past that — the |
| 29665 | /// server creates and dials the truncated name on both sides, so the |
| 29666 | /// expectation truncates with it. |
| 29667 | async fn school_db_by_slug(control_db: &str, school: &str, control: &sqlx::PgPool) -> String { |
| 29668 | let id = Uuid::parse_str(school).expect("school id is a uuid"); |
| 29669 | let id: Uuid = sqlx::query_scalar("SELECT id FROM school WHERE id = $1") |
| 29670 | .bind(id) |
| 29671 | .fetch_one(control) |
| 29672 | .await |
| 29673 | .expect("school id"); |
| 29674 | let name = format!("{control_db}_school_{}", id.simple()); |
| 29675 | name.chars().take(63).collect() |
| 29676 | } |
| 29677 | |
| 29678 | /// A school **is** a database, so the server must hold exactly the created |
| 29679 | /// schools plus the control database — and `DELETE /schools/{slug}` must drop |
| 29680 | /// the database, not merely delete the registry row. |
| 29681 | #[tokio::test] |
| 29682 | async fn remote_probe_a_school_is_a_database_and_delete_removes_it() { |
| 29683 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 29684 | let control_db: String = sqlx::query_scalar("SELECT current_database()") |
| 29685 | .fetch_one(d.tenants.control()) |
| 29686 | .await |
| 29687 | .expect("control name"); |
| 29688 | let demo_db = school_db_by_slug(&control_db, DEMO_SCHOOL_ID, d.tenants.control()).await; |
| 29689 | let beta_db = school_db_by_slug(&control_db, common::school_wire("beta"), d.tenants.control()).await; |
| 29690 | let mut expected = vec![control_db.clone(), demo_db.clone(), beta_db]; |
| 29691 | expected.sort(); |
| 29692 | assert_eq!( |
| 29693 | namespace_databases(&d.tenants).await, |
| 29694 | expected, |
| 29695 | "the server holds exactly the two schools and the control database" |
| 29696 | ); |
| 29697 | |
| 29698 | hezarfen_backend::service::builder::ensure( |
| 29699 | d.tenants.control(), |
| 29700 | Username::try_new("operator").unwrap(), |
| 29701 | Password::try_new("secret1").unwrap(), |
| 29702 | ) |
| 29703 | .await |
| 29704 | .expect("seed the builder"); |
| 29705 | let res = send( |
| 29706 | &d.app, |
| 29707 | "POST", |
| 29708 | "/builder/login", |
| 29709 | None, |
| 29710 | Some(json!({ "username": "operator", "password": "secret1" })), |
| 29711 | ) |
| 29712 | .await; |
| 29713 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 29714 | let builder = res.cookie.expect("builder cookie"); |
| 29715 | |
| 29716 | let res = send(&d.app, "DELETE", &format!("/schools/{}", common::school_wire("beta")), Some(&builder), None).await; |
| 29717 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 29718 | let mut expected = vec![control_db.clone(), demo_db]; |
| 29719 | expected.sort(); |
| 29720 | assert_eq!( |
| 29721 | namespace_databases(&d.tenants).await, |
| 29722 | expected, |
| 29723 | "DELETE /schools/beta dropped beta's database" |
| 29724 | ); |
| 29725 | } |
| 29726 | |
| 29727 | /// Raw SQL on a school's own handle sees that school's rows and no others — |
| 29728 | /// isolation by database, checked under the API rather than through it. |
| 29729 | #[tokio::test] |
| 29730 | async fn remote_probe_raw_sql_on_a_school_handle_counts_only_its_own_rows() { |
| 29731 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 29732 | // Different counts, so a leak cannot hide behind equal numbers. |
| 29733 | for (slug, users) in [ |
| 29734 | (DEMO_SCHOOL_ID, ["ada", "ali", "ayse"].as_slice()), |
| 29735 | ("beta", &["boran"]), |
| 29736 | ] { |
| 29737 | for username in users { |
| 29738 | let res = send( |
| 29739 | &d.app, |
| 29740 | "POST", |
| 29741 | "/auth/register", |
| 29742 | None, |
| 29743 | Some(json!({ "school": common::school_wire(slug), "username": username, "password": "secret1" })), |
| 29744 | ) |
| 29745 | .await; |
| 29746 | assert_eq!( |
| 29747 | res.status, |
| 29748 | StatusCode::CREATED, |
| 29749 | "{slug}/{username}: {}", |
| 29750 | res.body |
| 29751 | ); |
| 29752 | } |
| 29753 | } |
| 29754 | |
| 29755 | let count = async |db: &hezarfen_backend::database::Database| -> i64 { |
| 29756 | sqlx::query_scalar("SELECT count(*) FROM app_user") |
| 29757 | .fetch_one(db) |
| 29758 | .await |
| 29759 | .expect("count query") |
| 29760 | }; |
| 29761 | let db_a = school_db(&d.tenants, DEMO_SCHOOL_ID).await; |
| 29762 | let db_b = school_db(&d.tenants, "beta").await; |
| 29763 | assert_eq!(count(&db_a).await, 3, "demo's own users"); |
| 29764 | assert_eq!(count(&db_b).await, 1, "beta's own users"); |
| 29765 | } |
| 29766 | |
| 29767 | /// The same uuid *string* is well-formed everywhere, but the row it names |
| 29768 | /// exists only in the database that minted it: selecting it on the other |
| 29769 | /// school's handle must find nothing. |
| 29770 | #[tokio::test] |
| 29771 | async fn remote_probe_a_record_id_minted_in_one_school_is_absent_in_the_other() { |
| 29772 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 29773 | let res = send( |
| 29774 | &d.app, |
| 29775 | "POST", |
| 29776 | "/auth/register", |
| 29777 | None, |
| 29778 | Some(json!({ "school": DEMO_SCHOOL_ID, "username": "ada", "password": "secret1" })), |
| 29779 | ) |
| 29780 | .await; |
| 29781 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 29782 | |
| 29783 | let db_a = school_db(&d.tenants, DEMO_SCHOOL_ID).await; |
| 29784 | let db_b = school_db(&d.tenants, "beta").await; |
| 29785 | let id: Uuid = sqlx::query_scalar("SELECT id FROM app_user LIMIT 1") |
| 29786 | .fetch_one(&db_a) |
| 29787 | .await |
| 29788 | .expect("A's user id"); |
| 29789 | |
| 29790 | let mine: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user WHERE id = $1") |
| 29791 | .bind(id) |
| 29792 | .fetch_one(&db_a) |
| 29793 | .await |
| 29794 | .expect("select in A"); |
| 29795 | assert_eq!(mine, 1, "{id} is A's own row"); |
| 29796 | let theirs: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user WHERE id = $1") |
| 29797 | .bind(id) |
| 29798 | .fetch_one(&db_b) |
| 29799 | .await |
| 29800 | .expect("select in B"); |
| 29801 | assert_eq!( |
| 29802 | theirs, 0, |
| 29803 | "{id} — minted in demo — resolved on beta's handle" |
| 29804 | ); |
| 29805 | } |
| 29806 | |
| 29807 | /// Suspension evicts the cached pool; a resume must therefore dial fresh and |
| 29808 | /// find the school's rows exactly as they were. |
| 29809 | #[tokio::test] |
| 29810 | async fn remote_probe_a_suspended_school_reconnects_with_its_rows_intact() { |
| 29811 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 29812 | let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap(); |
| 29813 | let db = school_db(&d.tenants, DEMO_SCHOOL_ID).await; |
| 29814 | let cookie = common::login_as_school(&d.app, &db, DEMO_SCHOOL_ID, "ada", "admin").await; |
| 29815 | let note = send( |
| 29816 | &d.app, |
| 29817 | "POST", |
| 29818 | "/notes", |
| 29819 | Some(&cookie), |
| 29820 | Some(json!({ "title": "before", "content": "kept" })), |
| 29821 | ) |
| 29822 | .await; |
| 29823 | assert_eq!(note.status, StatusCode::CREATED, "{}", note.body); |
| 29824 | let note_id = id_of(¬e.body); |
| 29825 | |
| 29826 | d.tenants |
| 29827 | .set_status(&slug, SchoolStatus::Suspended) |
| 29828 | .await |
| 29829 | .expect("suspend"); |
| 29830 | let res = send(&d.app, "GET", "/auth/me", Some(&cookie), None).await; |
| 29831 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 29832 | d.tenants |
| 29833 | .set_status(&slug, SchoolStatus::Active) |
| 29834 | .await |
| 29835 | .expect("resume"); |
| 29836 | |
| 29837 | // A fresh connection (the old one was evicted) onto the same database. |
| 29838 | let reconnected = school_db(&d.tenants, DEMO_SCHOOL_ID).await; |
| 29839 | let titles: Vec<String> = sqlx::query_scalar("SELECT title FROM note") |
| 29840 | .fetch_all(&reconnected) |
| 29841 | .await |
| 29842 | .expect("notes after the resume"); |
| 29843 | assert_eq!(titles, vec!["before".to_string()], "the rows survived"); |
| 29844 | let res = send( |
| 29845 | &d.app, |
| 29846 | "GET", |
| 29847 | &format!("/notes/{note_id}"), |
| 29848 | Some(&cookie), |
| 29849 | None, |
| 29850 | ) |
| 29851 | .await; |
| 29852 | assert_eq!( |
| 29853 | res.status, |
| 29854 | StatusCode::OK, |
| 29855 | "the same cookie and the same note after a resume: {}", |
| 29856 | res.body |
| 29857 | ); |
| 29858 | } |
| 29859 | |
| 29860 | // --- module entitlements ------------------------------------------------- |
| 29861 | // |
| 29862 | // Foundation-level only: one nest proves the gate, one child route proves the |
| 29863 | // `/courses` exceptions, and the two WebSocket nests prove an upgrade is |
| 29864 | // refused like any other GET. The full per-module sweep is a later lane. |
| 29865 | |
| 29866 | use hezarfen_backend::module::Module; |
| 29867 | |
| 29868 | /// Turning a module off refuses **its** nest and nothing else — with the same |
| 29869 | /// cookie, and with the URL space untouched (an unmatched path inside the |
| 29870 | /// disabled nest is still a `404`, which is what `route_layer` buys). |
| 29871 | #[tokio::test] |
| 29872 | async fn a_disabled_module_refuses_its_nest_and_leaves_the_rest_alone() { |
| 29873 | let (app, db, tenants) = common::app_and_tenants().await; |
| 29874 | let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap(); |
| 29875 | let cookie = login_as(&app, &db, "ada", "admin").await; |
| 29876 | |
| 29877 | let res = send(&app, "GET", "/meals/menus", Some(&cookie), None).await; |
| 29878 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 29879 | |
| 29880 | let mut without_meals = ModuleSet::all(); |
| 29881 | without_meals.remove(Module::Meals); |
| 29882 | tenants |
| 29883 | .set_modules(&slug, &without_meals) |
| 29884 | .await |
| 29885 | .expect("take the meals module back"); |
| 29886 | |
| 29887 | let res = send(&app, "GET", "/meals/menus", Some(&cookie), None).await; |
| 29888 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 29889 | assert_eq!( |
| 29890 | res.body, |
| 29891 | json!({ "error": "module disabled", "module": "meals" }), |
| 29892 | "the refusal body is contract" |
| 29893 | ); |
| 29894 | |
| 29895 | for route in ["/auth/me", "/limits", "/settings"] { |
| 29896 | let res = send(&app, "GET", route, Some(&cookie), None).await; |
| 29897 | assert_eq!(res.status, StatusCode::OK, "{route}: {}", res.body); |
| 29898 | } |
| 29899 | |
| 29900 | let res = send(&app, "GET", "/meals/does-not-exist", Some(&cookie), None).await; |
| 29901 | assert_eq!( |
| 29902 | res.status, |
| 29903 | StatusCode::NOT_FOUND, |
| 29904 | "a disabled module must not swallow the 404: {}", |
| 29905 | res.body |
| 29906 | ); |
| 29907 | |
| 29908 | tenants |
| 29909 | .set_modules(&slug, &ModuleSet::all()) |
| 29910 | .await |
| 29911 | .expect("sell it back"); |
| 29912 | let res = send(&app, "GET", "/meals/menus", Some(&cookie), None).await; |
| 29913 | assert_eq!( |
| 29914 | res.status, |
| 29915 | StatusCode::OK, |
| 29916 | "the very same cookie after re-enabling: {}", |
| 29917 | res.body |
| 29918 | ); |
| 29919 | } |
| 29920 | |
| 29921 | /// The four route pairs mounted under `/courses` that belong to another |
| 29922 | /// module answer for *that* module: exams off refuses |
| 29923 | /// `POST /courses/{id}/exams` while the course itself stays reachable. |
| 29924 | /// Every module except `module` and everything that (transitively) needs it — |
| 29925 | /// the only shape the registry accepts now that `set_modules` validates the |
| 29926 | /// dependency graph itself. |
| 29927 | fn all_without(module: Module) -> ModuleSet { |
| 29928 | let mut set = ModuleSet::all(); |
| 29929 | let mut pending = vec![module]; |
| 29930 | while let Some(next) = pending.pop() { |
| 29931 | if set.contains(next) { |
| 29932 | set.remove(next); |
| 29933 | pending.extend(next.dependents()); |
| 29934 | } |
| 29935 | } |
| 29936 | set |
| 29937 | } |
| 29938 | |
| 29939 | #[tokio::test] |
| 29940 | async fn a_course_child_route_is_gated_by_its_own_module() { |
| 29941 | let (app, db, tenants) = common::app_and_tenants().await; |
| 29942 | let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap(); |
| 29943 | let cookie = login_as(&app, &db, "ada", "admin").await; |
| 29944 | let course = create_course(&app, &cookie, "Fizik").await; |
| 29945 | |
| 29946 | tenants |
| 29947 | .set_modules(&slug, &all_without(Module::Exams)) |
| 29948 | .await |
| 29949 | .unwrap(); |
| 29950 | |
| 29951 | // An empty body, and an id nothing minted: the gate must answer before the |
| 29952 | // payload is parsed and before any row is looked up, so which id the path |
| 29953 | // names is immaterial — the exams nest lives under `/instances` since the |
| 29954 | // class became the academic anchor. |
| 29955 | let res = send( |
| 29956 | &app, |
| 29957 | "POST", |
| 29958 | &format!("/instances/{course}/exams"), |
| 29959 | Some(&cookie), |
| 29960 | Some(json!({})), |
| 29961 | ) |
| 29962 | .await; |
| 29963 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 29964 | assert_eq!(res.body["module"], "exams"); |
| 29965 | |
| 29966 | let res = send( |
| 29967 | &app, |
| 29968 | "GET", |
| 29969 | &format!("/courses/{course}"), |
| 29970 | Some(&cookie), |
| 29971 | None, |
| 29972 | ) |
| 29973 | .await; |
| 29974 | assert_eq!( |
| 29975 | res.status, |
| 29976 | StatusCode::OK, |
| 29977 | "courses itself is still enabled: {}", |
| 29978 | res.body |
| 29979 | ); |
| 29980 | } |
| 29981 | |
| 29982 | /// A WebSocket upgrade is a `GET` inside its nest, so it is gated by |
| 29983 | /// construction — proven for both rooms rather than assumed. |
| 29984 | #[tokio::test] |
| 29985 | async fn a_disabled_module_refuses_its_websocket_upgrade() { |
| 29986 | let (app, db, tenants) = common::app_and_tenants().await; |
| 29987 | let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap(); |
| 29988 | let cookie = login_as(&app, &db, "ada", "admin").await; |
| 29989 | |
| 29990 | let mut without = all_without(Module::Exams); |
| 29991 | without.remove(Module::Boards); |
| 29992 | tenants.set_modules(&slug, &without).await.unwrap(); |
| 29993 | |
| 29994 | for (route, module) in [("/boards/x/ws", "boards"), ("/exams/x/attempt/ws", "exams")] { |
| 29995 | let res = send(&app, "GET", route, Some(&cookie), None).await; |
| 29996 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{route}: {}", res.body); |
| 29997 | assert_eq!(res.body["module"], module, "{route}"); |
| 29998 | } |
| 29999 | } |
| 30000 | |
| 30001 | // --- module entitlements: the full sweep --------------------------------- |
| 30002 | // |
| 30003 | // The foundation tests above prove the mechanism on one nest; these prove it |
| 30004 | // holds for *every* module, driven through the vendor's own surface, plus the |
| 30005 | // coverage test that fails when a future nest is mounted ungated. |
| 30006 | |
| 30007 | use hezarfen_backend::service::builder; |
| 30008 | |
| 30009 | const SWEEP_BUILDER_USER: &str = "operator"; |
| 30010 | const SWEEP_BUILDER_PASS: &str = "secret1"; |
| 30011 | |
| 30012 | /// A deployment with a builder account, so the sweep can sell and take back |
| 30013 | /// modules by the same path production does (mirrors `tests/builder_api.rs`). |
| 30014 | async fn sweep_deployment() -> (axum::Router, hezarfen_backend::database::Database, Tenants) { |
| 30015 | let (app, db, tenants) = common::app_and_tenants().await; |
| 30016 | builder::ensure( |
| 30017 | tenants.control(), |
| 30018 | Username::try_new(SWEEP_BUILDER_USER).unwrap(), |
| 30019 | Password::try_new(SWEEP_BUILDER_PASS).unwrap(), |
| 30020 | ) |
| 30021 | .await |
| 30022 | .expect("seed the builder"); |
| 30023 | (app, db, tenants) |
| 30024 | } |
| 30025 | |
| 30026 | async fn sweep_builder_login(app: &axum::Router) -> String { |
| 30027 | let res = send( |
| 30028 | app, |
| 30029 | "POST", |
| 30030 | "/builder/login", |
| 30031 | None, |
| 30032 | Some(json!({ "username": SWEEP_BUILDER_USER, "password": SWEEP_BUILDER_PASS })), |
| 30033 | ) |
| 30034 | .await; |
| 30035 | assert_eq!(res.status, StatusCode::OK, "builder login: {}", res.body); |
| 30036 | res.cookie.expect("builder cookie") |
| 30037 | } |
| 30038 | |
| 30039 | fn is_module_disabled(res: &common::Res) -> bool { |
| 30040 | res.status == StatusCode::FORBIDDEN && res.body["error"] == "module disabled" |
| 30041 | } |
| 30042 | |
| 30043 | /// One route per module that exists and lives in that module's nest — the |
| 30044 | /// probe the sweep drives. GET list routes wherever the nest has one; the |
| 30045 | /// status when the module is *on* is irrelevant (a `{id}` route may 400 or |
| 30046 | /// 404), only "not the module refusal" is. |
| 30047 | const MODULE_ROUTES: [(Module, &str, &str); 21] = [ |
| 30048 | (Module::Chatbot, "GET", "/chatbot/threads"), |
| 30049 | (Module::Notes, "GET", "/notes"), |
| 30050 | (Module::Messages, "GET", "/messages"), |
| 30051 | (Module::Events, "GET", "/events"), |
| 30052 | (Module::Appointments, "GET", "/appointments/slots"), |
| 30053 | (Module::Courses, "GET", "/courses"), |
| 30054 | (Module::CourseNotes, "GET", "/course-notes"), |
| 30055 | (Module::Classes, "GET", "/classes"), |
| 30056 | // No list route of its own: sessions are listed under a course. |
| 30057 | (Module::Sessions, "GET", "/sessions/nope"), |
| 30058 | (Module::Exams, "GET", "/exams"), |
| 30059 | (Module::Marks, "GET", "/marks/me"), |
| 30060 | (Module::Meals, "GET", "/meals/menus"), |
| 30061 | (Module::Payments, "GET", "/payments/plans"), |
| 30062 | (Module::Work, "GET", "/work/me"), |
| 30063 | (Module::Pomodoro, "GET", "/pomodoro/me"), |
| 30064 | (Module::Questions, "GET", "/questions"), |
| 30065 | (Module::BankQuestions, "GET", "/bank-questions"), |
| 30066 | (Module::Attendance, "GET", "/attendance/me"), |
| 30067 | // Same as sessions: a subject is reached by id or through its course. |
| 30068 | (Module::Subjects, "GET", "/subjects/nope"), |
| 30069 | (Module::Homework, "GET", "/homework"), |
| 30070 | (Module::Boards, "GET", "/boards"), |
| 30071 | ]; |
| 30072 | |
| 30073 | /// Every one of the 21 modules, one at a time: on → not refused, taken back → |
| 30074 | /// `403 {"error":"module disabled","module":"<name>"}` on the *same* school |
| 30075 | /// cookie, sold back → not refused again. |
| 30076 | #[tokio::test] |
| 30077 | async fn every_module_gates_its_own_nest_when_the_builder_takes_it_back() { |
| 30078 | let (app, db, tenants) = sweep_deployment().await; |
| 30079 | let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap(); |
| 30080 | let cookie = login_as(&app, &db, "ada", "admin").await; |
| 30081 | let builder = sweep_builder_login(&app).await; |
| 30082 | |
| 30083 | for (module, method, path) in MODULE_ROUTES { |
| 30084 | let res = send(&app, method, path, Some(&cookie), None).await; |
| 30085 | assert!( |
| 30086 | !is_module_disabled(&res), |
| 30087 | "{module} is enabled, so {method} {path} must not be the module refusal: {} {}", |
| 30088 | res.status, |
| 30089 | res.body |
| 30090 | ); |
| 30091 | |
| 30092 | let one = format!("/schools/{DEMO_SCHOOL_ID}/modules/{module}"); |
| 30093 | if module.dependents().is_empty() { |
| 30094 | let res = send(&app, "DELETE", &one, Some(&builder), None).await; |
| 30095 | assert_eq!( |
| 30096 | res.status, |
| 30097 | StatusCode::OK, |
| 30098 | "take back {module}: {}", |
| 30099 | res.body |
| 30100 | ); |
| 30101 | } else { |
| 30102 | // The five modules something else structurally needs. This sweep |
| 30103 | // leaves every *other* module on, so the builder API rightly |
| 30104 | // refuses (`409 "<m> is required by …"`) — asserted here rather |
| 30105 | // than worked around, then the entitlement is written through the |
| 30106 | // registry call the API itself ends in. |
| 30107 | let res = send(&app, "DELETE", &one, Some(&builder), None).await; |
| 30108 | assert_eq!( |
| 30109 | res.status, |
| 30110 | StatusCode::CONFLICT, |
| 30111 | "{module} has dependents {:?}, so the API must refuse: {}", |
| 30112 | module.dependents(), |
| 30113 | res.body |
| 30114 | ); |
| 30115 | tenants |
| 30116 | .set_modules(&slug, &all_without(module)) |
| 30117 | .await |
| 30118 | .unwrap(); |
| 30119 | } |
| 30120 | |
| 30121 | let res = send(&app, method, path, Some(&cookie), None).await; |
| 30122 | assert_eq!( |
| 30123 | res.status, |
| 30124 | StatusCode::FORBIDDEN, |
| 30125 | "{method} {path}: {}", |
| 30126 | res.body |
| 30127 | ); |
| 30128 | assert_eq!( |
| 30129 | res.body, |
| 30130 | json!({ "error": "module disabled", "module": module.as_str() }), |
| 30131 | "the refusal body is contract, for {module}" |
| 30132 | ); |
| 30133 | |
| 30134 | // Sold back through the API in every case: enabling never conflicts. |
| 30135 | let res = send(&app, "POST", &one, Some(&builder), None).await; |
| 30136 | assert_eq!( |
| 30137 | res.status, |
| 30138 | StatusCode::OK, |
| 30139 | "sell {module} back: {}", |
| 30140 | res.body |
| 30141 | ); |
| 30142 | // `all_without` also took the module's dependents away; restore them |
| 30143 | // so the next module in the sweep starts from a fully sold school. |
| 30144 | if !module.dependents().is_empty() { |
| 30145 | tenants.set_modules(&slug, &ModuleSet::all()).await.unwrap(); |
| 30146 | } |
| 30147 | let res = send(&app, method, path, Some(&cookie), None).await; |
| 30148 | assert!( |
| 30149 | !is_module_disabled(&res), |
| 30150 | "{module} is back on: {} {}", |
| 30151 | res.status, |
| 30152 | res.body |
| 30153 | ); |
| 30154 | } |
| 30155 | } |
| 30156 | |
| 30157 | /// Every foreign-module route pair the two anchors carry, not just the one the |
| 30158 | /// foundation test drives: each answers for its *own* module while `courses` |
| 30159 | /// stays on. The exam, session and homework pairs hang off `/instances` — the |
| 30160 | /// class×course anchor, gated by the course module out here and by their own |
| 30161 | /// module inside — while the subject pair still hangs off the catalog row. |
| 30162 | #[tokio::test] |
| 30163 | async fn every_course_child_route_names_its_own_module() { |
| 30164 | let (app, db, tenants) = common::app_and_tenants().await; |
| 30165 | let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap(); |
| 30166 | let cookie = login_as(&app, &db, "ada", "admin").await; |
| 30167 | let course = create_course(&app, &cookie, "Fizik").await; |
| 30168 | let class = create_class(&app, &cookie, "9-F", json!({})).await; |
| 30169 | let instance = attach_instance(&app, &cookie, &class, &course).await; |
| 30170 | |
| 30171 | for (module, path) in [ |
| 30172 | (Module::Exams, format!("/instances/{instance}/exams")), |
| 30173 | (Module::Sessions, format!("/instances/{instance}/sessions")), |
| 30174 | (Module::Homework, format!("/instances/{instance}/homework")), |
| 30175 | (Module::Subjects, format!("/courses/{course}/subjects")), |
| 30176 | ] { |
| 30177 | // The three foreign pairs are needed by another module (marks, |
| 30178 | // attendance, exams), so the builder API would `409` here — the set is |
| 30179 | // written directly, uniformly, since the API's own refusal is proven |
| 30180 | // above. |
| 30181 | tenants |
| 30182 | .set_modules(&slug, &all_without(module)) |
| 30183 | .await |
| 30184 | .unwrap(); |
| 30185 | |
| 30186 | let res = send(&app, "GET", &path, Some(&cookie), None).await; |
| 30187 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{path}: {}", res.body); |
| 30188 | assert_eq!( |
| 30189 | res.body, |
| 30190 | json!({ "error": "module disabled", "module": module.as_str() }), |
| 30191 | "{path} answers for its own module" |
| 30192 | ); |
| 30193 | |
| 30194 | let res = send( |
| 30195 | &app, |
| 30196 | "GET", |
| 30197 | &format!("/courses/{course}"), |
| 30198 | Some(&cookie), |
| 30199 | None, |
| 30200 | ) |
| 30201 | .await; |
| 30202 | assert_eq!( |
| 30203 | res.status, |
| 30204 | StatusCode::OK, |
| 30205 | "courses stays on while {module} is off: {}", |
| 30206 | res.body |
| 30207 | ); |
| 30208 | |
| 30209 | tenants.set_modules(&slug, &ModuleSet::all()).await.unwrap(); |
| 30210 | } |
| 30211 | } |
| 30212 | |
| 30213 | /// A school that bought nothing is still a school: it logs in, reads itself, |
| 30214 | /// and can be told what it has — none of that lives behind a module. |
| 30215 | #[tokio::test] |
| 30216 | async fn a_school_with_no_modules_can_still_use_the_core_routes() { |
| 30217 | let (app, _db, tenants) = sweep_deployment().await; |
| 30218 | let builder = sweep_builder_login(&app).await; |
| 30219 | |
| 30220 | let res = send( |
| 30221 | &app, |
| 30222 | "POST", |
| 30223 | "/schools", |
| 30224 | Some(&builder), |
| 30225 | Some(json!({ |
| 30226 | "name": "bare school", |
| 30227 | "admin_username": "admin", |
| 30228 | "admin_password": "secret1", |
| 30229 | "modules": [], |
| 30230 | })), |
| 30231 | ) |
| 30232 | .await; |
| 30233 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 30234 | assert_eq!(res.body["modules"], json!([])); |
| 30235 | |
| 30236 | let bare_id: Uuid = sqlx::query_scalar("SELECT id FROM school WHERE name = 'bare school'") |
| 30237 | .fetch_one(tenants.control()) |
| 30238 | .await |
| 30239 | .expect("bare school"); |
| 30240 | let res = send( |
| 30241 | &app, |
| 30242 | "POST", |
| 30243 | "/auth/login", |
| 30244 | None, |
| 30245 | Some(json!({ "username": "admin", "password": "secret1" })), |
| 30246 | ) |
| 30247 | .await; |
| 30248 | assert_eq!( |
| 30249 | res.status, |
| 30250 | StatusCode::OK, |
| 30251 | "a bare school still logs in: {}", |
| 30252 | res.body |
| 30253 | ); |
| 30254 | let cookie = if res.body["schools"].is_array() { |
| 30255 | let selected = send( |
| 30256 | &app, |
| 30257 | "POST", |
| 30258 | "/auth/school", |
| 30259 | res.cookie.as_deref(), |
| 30260 | Some(json!({ "school": bare_id.to_string() })), |
| 30261 | ) |
| 30262 | .await; |
| 30263 | assert_eq!(selected.status, StatusCode::OK, "{}", selected.body); |
| 30264 | selected.cookie.expect("session cookie") |
| 30265 | } else { |
| 30266 | res.cookie.expect("session cookie") |
| 30267 | }; |
| 30268 | |
| 30269 | for route in [ |
| 30270 | "/auth/me", |
| 30271 | "/limits", |
| 30272 | "/settings", |
| 30273 | "/terms", |
| 30274 | "/users/me/profile", |
| 30275 | ] { |
| 30276 | let res = send(&app, "GET", route, Some(&cookie), None).await; |
| 30277 | assert_eq!(res.status, StatusCode::OK, "{route}: {}", res.body); |
| 30278 | } |
| 30279 | |
| 30280 | let res = send(&app, "GET", "/modules", Some(&cookie), None).await; |
| 30281 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30282 | assert_eq!(res.body, json!({ "enabled": [] })); |
| 30283 | } |
| 30284 | |
| 30285 | // --- module entitlements: coverage --------------------------------------- |
| 30286 | |
| 30287 | /// Route prefixes that are deliberately ungated, each with the reason it is — |
| 30288 | /// a nest here is one no school can be sold or refused. |
| 30289 | const CORE_PREFIXES: [(&str, &str); 15] = [ |
| 30290 | ("/", "the health mirror at the root"), |
| 30291 | ("/health", "liveness, read before any school is resolved"), |
| 30292 | ("/time", "the server clock, a deploy constant"), |
| 30293 | ("/limits", "deploy-time constants, needed to draw any form"), |
| 30294 | ( |
| 30295 | "/modules", |
| 30296 | "the entitlement lookup itself; gating it is circular", |
| 30297 | ), |
| 30298 | ("/ai", "the AI bridge's own surface, not a school's nest"), |
| 30299 | ( |
| 30300 | "/auth", |
| 30301 | "the door: a school must log in before anything is refused", |
| 30302 | ), |
| 30303 | ( |
| 30304 | "/users", |
| 30305 | "identity and profiles, part of being a school at all", |
| 30306 | ), |
| 30307 | ("/settings", "the school's own settings"), |
| 30308 | ( |
| 30309 | "/terms", |
| 30310 | "the academic calendar every other module hangs off", |
| 30311 | ), |
| 30312 | ( |
| 30313 | "/holidays", |
| 30314 | "the school-wide non-teaching calendar the schedule bounds itself with", |
| 30315 | ), |
| 30316 | ( |
| 30317 | "/academic-years", |
| 30318 | "the calendar above the dönemler — every şube sits in one", |
| 30319 | ), |
| 30320 | ( |
| 30321 | "/builder", |
| 30322 | "the vendor principal, which is not a school user", |
| 30323 | ), |
| 30324 | ("/schools", "the vendor's registry surface, same principal"), |
| 30325 | ( |
| 30326 | "/school", |
| 30327 | "the caller's own school identity, not a sold module", |
| 30328 | ), |
| 30329 | ]; |
| 30330 | |
| 30331 | /// Every module's nest prefix. Written down rather than derived: the point is |
| 30332 | /// to catch a nest that was mounted without a gate, and a derived list would |
| 30333 | /// be derived from the same code it is checking. |
| 30334 | /// |
| 30335 | /// A module may own more than one prefix: `courses` also answers under |
| 30336 | /// `/instances` (the instance anchor), and `chatbot` — the whole `ai` package — |
| 30337 | /// also answers under `/rag`, `/insights` and `/podcast`. |
| 30338 | const MODULE_PREFIXES: [(Module, &str); 26] = [ |
| 30339 | (Module::Chatbot, "/chatbot"), |
| 30340 | (Module::Chatbot, "/rag"), |
| 30341 | (Module::Chatbot, "/insights"), |
| 30342 | (Module::Chatbot, "/podcast"), |
| 30343 | (Module::Notes, "/notes"), |
| 30344 | (Module::Messages, "/messages"), |
| 30345 | (Module::Events, "/events"), |
| 30346 | (Module::Appointments, "/appointments"), |
| 30347 | (Module::Courses, "/courses"), |
| 30348 | (Module::Courses, "/instances"), |
| 30349 | (Module::Courses, "/offerings"), |
| 30350 | (Module::CourseNotes, "/course-notes"), |
| 30351 | (Module::Classes, "/classes"), |
| 30352 | (Module::Sessions, "/sessions"), |
| 30353 | (Module::Exams, "/exams"), |
| 30354 | (Module::Marks, "/marks"), |
| 30355 | (Module::Meals, "/meals"), |
| 30356 | (Module::Payments, "/payments"), |
| 30357 | (Module::Work, "/work"), |
| 30358 | (Module::Pomodoro, "/pomodoro"), |
| 30359 | (Module::Questions, "/questions"), |
| 30360 | (Module::BankQuestions, "/bank-questions"), |
| 30361 | (Module::Attendance, "/attendance"), |
| 30362 | (Module::Subjects, "/subjects"), |
| 30363 | (Module::Homework, "/homework"), |
| 30364 | (Module::Boards, "/boards"), |
| 30365 | ]; |
| 30366 | |
| 30367 | /// `path` is inside `prefix` — segment-wise, so `/course-notes` is not inside |
| 30368 | /// `/courses` and `/` is only ever itself. |
| 30369 | fn under(path: &str, prefix: &str) -> bool { |
| 30370 | if prefix == "/" { |
| 30371 | return path == "/"; |
| 30372 | } |
| 30373 | path == prefix || path.starts_with(&format!("{prefix}/")) |
| 30374 | } |
| 30375 | |
| 30376 | /// The published surface is exactly: the ungated core, plus the gated module |
| 30377 | /// nests (one per module, and one more — `/instances`, the instance anchor that |
| 30378 | /// carries the course gate). A nest added to `build_router` without a gate |
| 30379 | /// matches neither list and fails here by name — which is the only way an |
| 30380 | /// ungated nest is ever noticed, since nothing else in the suite knows a new |
| 30381 | /// route exists. |
| 30382 | /// |
| 30383 | /// corner-cut: it reads the OpenAPI document, so it sees only routes mounted |
| 30384 | /// with `.routes(routes!(…))` — a bare `.route()` is invisible to it. Every |
| 30385 | /// nest in `build_router` is documented today, so the ceiling is an |
| 30386 | /// undocumented route — which is already against this repo's convention. |
| 30387 | #[tokio::test] |
| 30388 | async fn every_published_route_is_either_core_or_inside_a_gated_module_nest() { |
| 30389 | let app = mem_app().await; |
| 30390 | let spec = send(&app, "GET", "/api-docs/openapi.json", None, None).await; |
| 30391 | assert_eq!(spec.status, StatusCode::OK); |
| 30392 | let paths = spec.body["paths"].as_object().expect("the spec has paths"); |
| 30393 | assert!( |
| 30394 | paths.len() > 100, |
| 30395 | "the whole spec, not a stub: {}", |
| 30396 | paths.len() |
| 30397 | ); |
| 30398 | |
| 30399 | let mut ungated = Vec::new(); |
| 30400 | for path in paths.keys() { |
| 30401 | let core: Vec<&str> = CORE_PREFIXES |
| 30402 | .iter() |
| 30403 | .filter(|(prefix, _)| under(path, prefix)) |
| 30404 | .map(|(prefix, _)| *prefix) |
| 30405 | .collect(); |
| 30406 | let gated: Vec<&str> = MODULE_PREFIXES |
| 30407 | .iter() |
| 30408 | .filter(|(_, prefix)| under(path, prefix)) |
| 30409 | .map(|(_, prefix)| *prefix) |
| 30410 | .collect(); |
| 30411 | match core.len() + gated.len() { |
| 30412 | 1 => {} |
| 30413 | 0 => ungated.push(format!( |
| 30414 | "{path}: in no core prefix and no gated module nest — mount it under a module (and gate it), or add it to CORE_PREFIXES with its reason" |
| 30415 | )), |
| 30416 | _ => ungated.push(format!("{path}: ambiguous, matches {core:?} and {gated:?}")), |
| 30417 | } |
| 30418 | } |
| 30419 | assert!( |
| 30420 | ungated.is_empty(), |
| 30421 | "ungated routes:\n{}", |
| 30422 | ungated.join("\n") |
| 30423 | ); |
| 30424 | } |
| 30425 | |
| 30426 | /// The catalog a client draws the switchboard from lists every module the |
| 30427 | /// server can refuse — a module missing here is one nobody can buy. |
| 30428 | #[tokio::test] |
| 30429 | async fn the_catalog_lists_every_module() { |
| 30430 | let app = mem_app().await; |
| 30431 | let res = send(&app, "GET", "/modules/catalog", None, None).await; |
| 30432 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30433 | let listed: Vec<&str> = res.body["modules"] |
| 30434 | .as_array() |
| 30435 | .expect("modules") |
| 30436 | .iter() |
| 30437 | .map(|m| m["module"].as_str().expect("name")) |
| 30438 | .collect(); |
| 30439 | assert_eq!(listed.len(), Module::ALL.len()); |
| 30440 | for module in Module::ALL { |
| 30441 | assert!( |
| 30442 | listed.contains(&module.as_str()), |
| 30443 | "{module} is not for sale" |
| 30444 | ); |
| 30445 | } |
| 30446 | } |
| 30447 | |
| 30448 | // --- person-scoped login --------------------------------------------------- |
| 30449 | |
| 30450 | /// A person registered at exactly one school is entered straight into it: the |
| 30451 | /// login body carries no school, the reply names the person, and the session |
| 30452 | /// cookie is that school's. |
| 30453 | #[tokio::test] |
| 30454 | async fn login_without_school_enters_a_single_school_person() { |
| 30455 | let (app, _db) = app_and_db().await; |
| 30456 | let reg = send( |
| 30457 | &app, |
| 30458 | "POST", |
| 30459 | "/auth/register", |
| 30460 | None, |
| 30461 | Some(json!({ "school": DEMO_SCHOOL_ID, "username": "personada", "password": "secret1" })), |
| 30462 | ) |
| 30463 | .await; |
| 30464 | assert_eq!(reg.status, StatusCode::CREATED, "{}", reg.body); |
| 30465 | |
| 30466 | let res = send( |
| 30467 | &app, |
| 30468 | "POST", |
| 30469 | "/auth/login", |
| 30470 | None, |
| 30471 | Some(json!({ "username": "personada", "password": "secret1" })), |
| 30472 | ) |
| 30473 | .await; |
| 30474 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30475 | assert!(res.body["id"].is_string(), "the person's id: {}", res.body); |
| 30476 | assert_eq!(res.body["username"], "personada"); |
| 30477 | let cookie = res.cookie.expect("school cookie"); |
| 30478 | assert!(cookie.starts_with(&format!("session={DEMO_SCHOOL_ID}.")), "cookie: {cookie}"); |
| 30479 | |
| 30480 | let res = send(&app, "GET", "/auth/me", Some(&cookie), None).await; |
| 30481 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30482 | } |
| 30483 | |
| 30484 | /// A person registered at two schools is entered nowhere by login: the reply |
| 30485 | /// lists both schools and the cookie is a person cookie that has chosen |
| 30486 | /// nothing yet; `POST /auth/school` then binds it to one school. |
| 30487 | #[tokio::test] |
| 30488 | async fn a_multischool_person_selects_a_school() { |
| 30489 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 30490 | let app = &d.app; |
| 30491 | for school in [DEMO_SCHOOL_ID, "beta"] { |
| 30492 | let reg = send( |
| 30493 | app, |
| 30494 | "POST", |
| 30495 | "/auth/register", |
| 30496 | None, |
| 30497 | Some(json!({ "school": common::school_wire(school), "username": "personada", "password": "secret1" })), |
| 30498 | ) |
| 30499 | .await; |
| 30500 | assert_eq!( |
| 30501 | reg.status, |
| 30502 | StatusCode::CREATED, |
| 30503 | "register into {school}: {}", |
| 30504 | reg.body |
| 30505 | ); |
| 30506 | } |
| 30507 | |
| 30508 | let res = send( |
| 30509 | app, |
| 30510 | "POST", |
| 30511 | "/auth/login", |
| 30512 | None, |
| 30513 | Some(json!({ "username": "personada", "password": "secret1" })), |
| 30514 | ) |
| 30515 | .await; |
| 30516 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30517 | assert_eq!(res.body["username"], "personada"); |
| 30518 | let mut ids: Vec<&str> = res.body["schools"] |
| 30519 | .as_array() |
| 30520 | .expect("schools list") |
| 30521 | .iter() |
| 30522 | .map(|s| s["id"].as_str().expect("school id")) |
| 30523 | .collect(); |
| 30524 | ids.sort_unstable(); |
| 30525 | let mut expected = [DEMO_SCHOOL_ID, hezarfen_backend::tenant::BETA_SCHOOL_ID]; |
| 30526 | expected.sort_unstable(); |
| 30527 | assert_eq!(ids, expected); |
| 30528 | assert!( |
| 30529 | res.body.get("id").is_none(), |
| 30530 | "no school chosen yet: {}", |
| 30531 | res.body |
| 30532 | ); |
| 30533 | let person = res.cookie.expect("person cookie"); |
| 30534 | assert!(person.starts_with("session=person."), "cookie: {person}"); |
| 30535 | |
| 30536 | // A person cookie alone is not a session: `/auth/me` refuses it. |
| 30537 | let res = send(app, "GET", "/auth/me", Some(&person), None).await; |
| 30538 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); |
| 30539 | |
| 30540 | let res = send( |
| 30541 | app, |
| 30542 | "POST", |
| 30543 | "/auth/school", |
| 30544 | Some(&person), |
| 30545 | Some(json!({ "school": DEMO_SCHOOL_ID })), |
| 30546 | ) |
| 30547 | .await; |
| 30548 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30549 | assert!(res.body["id"].is_string(), "the person's id: {}", res.body); |
| 30550 | let cookie = res.cookie.expect("school cookie"); |
| 30551 | assert!(cookie.starts_with(&format!("session={DEMO_SCHOOL_ID}.")), "cookie: {cookie}"); |
| 30552 | let res = send(app, "GET", "/auth/me", Some(&cookie), None).await; |
| 30553 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30554 | } |
| 30555 | |
| 30556 | /// `POST /auth/school` is member-only and cookie-strict: a slug the person is |
| 30557 | /// not registered under, a missing cookie, and an already-bound school cookie |
| 30558 | /// all refuse. |
| 30559 | #[tokio::test] |
| 30560 | async fn school_selection_refuses_non_members_and_wrong_cookies() { |
| 30561 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 30562 | let app = &d.app; |
| 30563 | for school in [DEMO_SCHOOL_ID, "beta"] { |
| 30564 | let reg = send( |
| 30565 | app, |
| 30566 | "POST", |
| 30567 | "/auth/register", |
| 30568 | None, |
| 30569 | Some(json!({ "school": common::school_wire(school), "username": "personada", "password": "secret1" })), |
| 30570 | ) |
| 30571 | .await; |
| 30572 | assert_eq!( |
| 30573 | reg.status, |
| 30574 | StatusCode::CREATED, |
| 30575 | "register into {school}: {}", |
| 30576 | reg.body |
| 30577 | ); |
| 30578 | } |
| 30579 | let res = send( |
| 30580 | app, |
| 30581 | "POST", |
| 30582 | "/auth/login", |
| 30583 | None, |
| 30584 | Some(json!({ "username": "personada", "password": "secret1" })), |
| 30585 | ) |
| 30586 | .await; |
| 30587 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30588 | let person = res.cookie.expect("person cookie"); |
| 30589 | |
| 30590 | // Not a member of the requested school. |
| 30591 | let res = send( |
| 30592 | app, |
| 30593 | "POST", |
| 30594 | "/auth/school", |
| 30595 | Some(&person), |
| 30596 | Some(json!({ "school": "ghost-slug" })), |
| 30597 | ) |
| 30598 | .await; |
| 30599 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); |
| 30600 | |
| 30601 | // No cookie at all. |
| 30602 | let res = send( |
| 30603 | app, |
| 30604 | "POST", |
| 30605 | "/auth/school", |
| 30606 | None, |
| 30607 | Some(json!({ "school": DEMO_SCHOOL_ID })), |
| 30608 | ) |
| 30609 | .await; |
| 30610 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); |
| 30611 | |
| 30612 | // Selecting a school for real... |
| 30613 | let res = send( |
| 30614 | app, |
| 30615 | "POST", |
| 30616 | "/auth/school", |
| 30617 | Some(&person), |
| 30618 | Some(json!({ "school": DEMO_SCHOOL_ID })), |
| 30619 | ) |
| 30620 | .await; |
| 30621 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30622 | let school_cookie = res.cookie.expect("school cookie"); |
| 30623 | |
| 30624 | // ...and asking again with the school cookie: refused. |
| 30625 | let res = send( |
| 30626 | app, |
| 30627 | "POST", |
| 30628 | "/auth/school", |
| 30629 | Some(&school_cookie), |
| 30630 | Some(json!({ "school": DEMO_SCHOOL_ID })), |
| 30631 | ) |
| 30632 | .await; |
| 30633 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); |
| 30634 | } |
| 30635 | |
| 30636 | /// The old client shape — a leftover `"school"` field in the login body — is |
| 30637 | /// ignored, not refused: serde drops fields the login no longer knows. |
| 30638 | #[tokio::test] |
| 30639 | async fn login_ignores_a_leftover_school_field() { |
| 30640 | let (app, _db) = app_and_db().await; |
| 30641 | let reg = send( |
| 30642 | &app, |
| 30643 | "POST", |
| 30644 | "/auth/register", |
| 30645 | None, |
| 30646 | Some(json!({ "school": DEMO_SCHOOL_ID, "username": "personada", "password": "secret1" })), |
| 30647 | ) |
| 30648 | .await; |
| 30649 | assert_eq!(reg.status, StatusCode::CREATED, "{}", reg.body); |
| 30650 | |
| 30651 | let res = send( |
| 30652 | &app, |
| 30653 | "POST", |
| 30654 | "/auth/login", |
| 30655 | None, |
| 30656 | Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "personada", "password": "secret1" })), |
| 30657 | ) |
| 30658 | .await; |
| 30659 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30660 | } |
| 30661 | |
| 30662 | // --- insights: ZEKA's own tables, read back --------------------------------- |
| 30663 | |
| 30664 | /// Seed one student's ZEKA rows the way the service writes them (the backend |
| 30665 | /// never composes one, only reads): a nightly summary, one attention item, a |
| 30666 | /// live card addressed to the homeroom teacher, a dismissed card and an |
| 30667 | /// expired card addressed to the student, one displayable segment row and one |
| 30668 | /// below the display floor. |
| 30669 | async fn seed_insight_rows( |
| 30670 | db: &hezarfen_backend::database::Database, |
| 30671 | course: &str, |
| 30672 | student: &str, |
| 30673 | teacher: &str, |
| 30674 | ) { |
| 30675 | let student_uuid = Uuid::parse_str(student).expect("student id"); |
| 30676 | let teacher_uuid = Uuid::parse_str(teacher).expect("teacher id"); |
| 30677 | let course_uuid = Uuid::parse_str(course).expect("course id"); |
| 30678 | let now = Timestamp::now().as_millis(); |
| 30679 | |
| 30680 | sqlx::query( |
| 30681 | "INSERT INTO zeka_student_summary |
| 30682 | (student, marks, attendance, submission, study, confidence, computed_at, retain_until) |
| 30683 | VALUES ($1, '{\"courses\":{\"matematik\":{\"average\":72}}}'::jsonb, NULL, NULL, NULL, |
| 30684 | 'stable', $2, $3)", |
| 30685 | ) |
| 30686 | .bind(student_uuid) |
| 30687 | .bind(now) |
| 30688 | .bind(now + 400 * 86_400_000) |
| 30689 | .execute(db) |
| 30690 | .await |
| 30691 | .unwrap(); |
| 30692 | |
| 30693 | sqlx::query( |
| 30694 | "INSERT INTO zeka_attention_item |
| 30695 | (student, trigger, course, fact, window_from, window_to, evidence, ord) |
| 30696 | VALUES ($1, 'attendance', NULL, 'son 30 gunun 4 dersi kacirildi', $2, $3, |
| 30697 | '{\"absent_days\":4}'::jsonb, 1)", |
| 30698 | ) |
| 30699 | .bind(student_uuid) |
| 30700 | .bind(now - 30 * 86_400_000) |
| 30701 | .bind(now) |
| 30702 | .execute(db) |
| 30703 | .await |
| 30704 | .unwrap(); |
| 30705 | |
| 30706 | let live_card = Uuid::now_v7(); |
| 30707 | sqlx::query( |
| 30708 | "INSERT INTO zeka_recommendation |
| 30709 | (id, audience, product, rule_id, rule_version, scope, about, audience_role, |
| 30710 | course, evidence, confidence, created_at, expires_at, retain_until, |
| 30711 | dismissed_at, dismissed_by, dismiss_reason) |
| 30712 | VALUES ($1, $2, 'T4', 'T4.attendance', 1, NULL, $3, 'teacher', $4, |
| 30713 | '{\"absent_days\":4,\"limitation\":\"yalniz ders yoklamasi\"}'::jsonb, |
| 30714 | 'stable', $5, $6, $7, NULL, NULL, NULL)", |
| 30715 | ) |
| 30716 | .bind(live_card) |
| 30717 | .bind(teacher_uuid) |
| 30718 | .bind(student_uuid) |
| 30719 | .bind(course_uuid) |
| 30720 | .bind(now) |
| 30721 | .bind(now + 86_400_000) |
| 30722 | .bind(now + 90 * 86_400_000) |
| 30723 | .execute(db) |
| 30724 | .await |
| 30725 | .unwrap(); |
| 30726 | |
| 30727 | // Dismissed: the application's own audit trail — a card closed by its |
| 30728 | // audience must never be shown again. |
| 30729 | sqlx::query( |
| 30730 | "INSERT INTO zeka_recommendation |
| 30731 | (id, audience, product, rule_id, rule_version, scope, about, audience_role, |
| 30732 | course, evidence, confidence, created_at, expires_at, retain_until, |
| 30733 | dismissed_at, dismissed_by, dismiss_reason) |
| 30734 | VALUES ($1, $2, 'O3', 'O3.pattern', 1, NULL, NULL, 'student', NULL, |
| 30735 | '{\"n_stints\":7,\"limitation\":\"tek donem\"}'::jsonb, |
| 30736 | 'stable', $3, $4, $5, $3, $2, 'bu dogru degil')", |
| 30737 | ) |
| 30738 | .bind(Uuid::now_v7()) |
| 30739 | .bind(student_uuid) |
| 30740 | .bind(now) |
| 30741 | .bind(now + 86_400_000) |
| 30742 | .bind(now + 90 * 86_400_000) |
| 30743 | .execute(db) |
| 30744 | .await |
| 30745 | .unwrap(); |
| 30746 | |
| 30747 | // Expired: past its `expires_at`, so it is shown to nobody. |
| 30748 | sqlx::query( |
| 30749 | "INSERT INTO zeka_recommendation |
| 30750 | (id, audience, product, rule_id, rule_version, scope, about, audience_role, |
| 30751 | course, evidence, confidence, created_at, expires_at, retain_until, |
| 30752 | dismissed_at, dismissed_by, dismiss_reason) |
| 30753 | VALUES ($1, $2, 'O1', 'O1.review_band', 1, NULL, NULL, 'student', NULL, |
| 30754 | '{\"band\":\"review\",\"limitation\":\"n=3\"}'::jsonb, |
| 30755 | 'exploratory', $3, $4, $5, NULL, NULL, NULL)", |
| 30756 | ) |
| 30757 | .bind(Uuid::now_v7()) |
| 30758 | .bind(student_uuid) |
| 30759 | .bind(now - 10 * 86_400_000) |
| 30760 | .bind(now - 86_400_000) |
| 30761 | .bind(now + 90 * 86_400_000) |
| 30762 | .execute(db) |
| 30763 | .await |
| 30764 | .unwrap(); |
| 30765 | |
| 30766 | sqlx::query( |
| 30767 | "INSERT INTO zeka_student_segment_profile |
| 30768 | (student, dimension, label, n_answers, n_correct, accuracy, |
| 30769 | overall_n_answers, overall_accuracy, contrast, confidence, |
| 30770 | computed_at, retain_until) |
| 30771 | VALUES ($1, 'bilissel_talep', 'analiz', 120, 48, 0.40, 240, 0.55, -0.15, |
| 30772 | 'stable', $2, $3)", |
| 30773 | ) |
| 30774 | .bind(student_uuid) |
| 30775 | .bind(now) |
| 30776 | .bind(now + 400 * 86_400_000) |
| 30777 | .execute(db) |
| 30778 | .await |
| 30779 | .unwrap(); |
| 30780 | |
| 30781 | // Below the display floor (n < 30): it stays in the database and off every |
| 30782 | // screen, so a reader must not see this label. |
| 30783 | sqlx::query( |
| 30784 | "INSERT INTO zeka_student_segment_profile |
| 30785 | (student, dimension, label, n_answers, n_correct, accuracy, |
| 30786 | overall_n_answers, overall_accuracy, contrast, confidence, |
| 30787 | computed_at, retain_until) |
| 30788 | VALUES ($1, 'okuma_yuku', 'yuksek', 12, 9, 0.75, 240, 0.55, 0.20, |
| 30789 | 'none', $2, $3)", |
| 30790 | ) |
| 30791 | .bind(student_uuid) |
| 30792 | .bind(now) |
| 30793 | .bind(now + 400 * 86_400_000) |
| 30794 | .execute(db) |
| 30795 | .await |
| 30796 | .unwrap(); |
| 30797 | } |
| 30798 | |
| 30799 | /// The insight read is gated twice: role first (a student is refused outright), |
| 30800 | /// then reach (a teacher is `404`ed for a student they do not teach) — while |
| 30801 | /// the homeroom teacher of the student's own şube reads it whole, and the |
| 30802 | /// reader's own filters (dismissed/expired cards, noise segments, the |
| 30803 | /// attention list's audience) all hold. |
| 30804 | #[tokio::test] |
| 30805 | async fn insight_reads_are_gated_to_the_students_the_caller_reaches() { |
| 30806 | let (app, db) = app_and_db().await; |
| 30807 | let staff = login_as(&app, &db, "mudur", "manager").await; |
| 30808 | |
| 30809 | let homeroom = login_as(&app, &db, "ayse", "teacher").await; |
| 30810 | let taught = taught_under(&app, &staff, &homeroom, "matematik").await; |
| 30811 | |
| 30812 | let ali = login(&app, "ali").await; |
| 30813 | let ali_id = me_id(&app, &ali).await; |
| 30814 | add_member(&app, &staff, &taught.class, &ali_id).await; |
| 30815 | |
| 30816 | // A teacher the student shares no instance with — the refusal arm. |
| 30817 | let stranger = login_as(&app, &db, "bora", "teacher").await; |
| 30818 | let veli = login(&app, "veli").await; |
| 30819 | let veli_id = me_id(&app, &veli).await; |
| 30820 | add_member(&app, &staff, &taught.class, &veli_id).await; |
| 30821 | |
| 30822 | let teacher_uuid = me_id(&app, &homeroom).await; |
| 30823 | seed_insight_rows(&db, &taught.course, &ali_id, &teacher_uuid).await; |
| 30824 | |
| 30825 | // The homeroom teacher runs the instance the student sits in: the whole |
| 30826 | // card, with the filters applied. |
| 30827 | let res = send( |
| 30828 | &app, |
| 30829 | "GET", |
| 30830 | &format!("/insights/students/{ali_id}"), |
| 30831 | Some(&homeroom), |
| 30832 | None, |
| 30833 | ) |
| 30834 | .await; |
| 30835 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30836 | assert_eq!(res.body["user_id"], ali_id); |
| 30837 | assert_eq!(res.body["summary"]["confidence"], "stable"); |
| 30838 | assert_eq!( |
| 30839 | res.body["summary"]["marks"]["courses"]["matematik"]["average"], |
| 30840 | 72 |
| 30841 | ); |
| 30842 | assert_eq!( |
| 30843 | res.body["attention"].as_array().expect("attention").len(), |
| 30844 | 1 |
| 30845 | ); |
| 30846 | assert_eq!(res.body["attention"][0]["trigger"], "attendance"); |
| 30847 | let cards = res.body["cards"].as_array().expect("cards"); |
| 30848 | assert_eq!( |
| 30849 | cards.len(), |
| 30850 | 1, |
| 30851 | "dismissed and expired cards are filtered out" |
| 30852 | ); |
| 30853 | assert_eq!(cards[0]["rule_id"], "T4.attendance"); |
| 30854 | assert_eq!(cards[0]["about"], ali_id); |
| 30855 | assert_eq!(cards[0]["course"], taught.course); |
| 30856 | assert_eq!(cards[0]["evidence"]["limitation"], "yalniz ders yoklamasi"); |
| 30857 | let segments = res.body["segments"].as_array().expect("segments"); |
| 30858 | assert_eq!(segments.len(), 1, "a confidence:none row is not shown"); |
| 30859 | assert_eq!(segments[0]["label"], "analiz"); |
| 30860 | assert_eq!(segments[0]["contrast"], -0.15); |
| 30861 | |
| 30862 | // The same student's own view: the summary and the profile, and the two |
| 30863 | // things the contract keeps off a student's screen — the attention list |
| 30864 | // about themselves, and any card not addressed to them (their live card |
| 30865 | // belongs to the teacher, and their own two are dismissed/expired). |
| 30866 | let res = send(&app, "GET", "/insights/me", Some(&ali), None).await; |
| 30867 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30868 | assert_eq!(res.body["summary"]["confidence"], "stable"); |
| 30869 | assert_eq!( |
| 30870 | res.body["attention"].as_array().expect("attention").len(), |
| 30871 | 0 |
| 30872 | ); |
| 30873 | assert_eq!(res.body["cards"].as_array().expect("cards").len(), 0); |
| 30874 | assert_eq!(res.body["segments"].as_array().expect("segments").len(), 1); |
| 30875 | |
| 30876 | // A teacher who does not run any instance the student sits in reads the |
| 30877 | // same 404 a missing id reads — and the row above proves it is a refusal, |
| 30878 | // not an absence. |
| 30879 | let res = send( |
| 30880 | &app, |
| 30881 | "GET", |
| 30882 | &format!("/insights/students/{ali_id}"), |
| 30883 | Some(&stranger), |
| 30884 | None, |
| 30885 | ) |
| 30886 | .await; |
| 30887 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 30888 | |
| 30889 | // A fellow student is refused at the role gate, the same posture |
| 30890 | // `/marks/{user}` takes. |
| 30891 | let res = send( |
| 30892 | &app, |
| 30893 | "GET", |
| 30894 | &format!("/insights/students/{ali_id}"), |
| 30895 | Some(&veli), |
| 30896 | None, |
| 30897 | ) |
| 30898 | .await; |
| 30899 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 30900 | |
| 30901 | // The reach check has no existence oracle either: an id no user holds |
| 30902 | // reads exactly like the unreachable one. |
| 30903 | let res = send( |
| 30904 | &app, |
| 30905 | "GET", |
| 30906 | &format!("/insights/students/{}", Uuid::now_v7()), |
| 30907 | Some(&stranger), |
| 30908 | None, |
| 30909 | ) |
| 30910 | .await; |
| 30911 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 30912 | } |
| 30913 | |
| 30914 | /// The run ledger is the management view: manager+ reads it whole — with the |
| 30915 | /// two child tables joined back in their writer's order — and a teacher is |
| 30916 | /// refused outright (a pending-student list is a list of people). |
| 30917 | #[tokio::test] |
| 30918 | async fn the_insight_run_ledger_is_manager_only() { |
| 30919 | let (app, db) = app_and_db().await; |
| 30920 | let staff = login_as(&app, &db, "mudur", "manager").await; |
| 30921 | let teacher = login_as(&app, &db, "ayse", "teacher").await; |
| 30922 | let ali = login(&app, "ali").await; |
| 30923 | let ali_id = me_id(&app, &ali).await; |
| 30924 | |
| 30925 | let now = Timestamp::now().as_millis(); |
| 30926 | sqlx::query( |
| 30927 | "INSERT INTO zeka_run |
| 30928 | (run_day, started_at, finished_at, status, duration_ms, |
| 30929 | students_total, students_ok, students_failed, students_skipped, |
| 30930 | rows_written, budget_exceeded, budget_ms, retain_until) |
| 30931 | VALUES ('2026-09-16', $1, $2, 'partial', 61000, 12, 10, 1, 1, 44, true, 60000, $3)", |
| 30932 | ) |
| 30933 | .bind(now - 61_000) |
| 30934 | .bind(now) |
| 30935 | .bind(now + 90 * 86_400_000) |
| 30936 | .execute(&db) |
| 30937 | .await |
| 30938 | .unwrap(); |
| 30939 | sqlx::query("INSERT INTO zeka_run_pending (run, student, ord) VALUES ('2026-09-16', $1, 1)") |
| 30940 | .bind(Uuid::parse_str(&ali_id).expect("student id")) |
| 30941 | .execute(&db) |
| 30942 | .await |
| 30943 | .unwrap(); |
| 30944 | sqlx::query( |
| 30945 | "INSERT INTO zeka_run_failed_module (run, module, ord) |
| 30946 | VALUES ('2026-09-16', 'study', 1), ('2026-09-16', 'attendance', 2)", |
| 30947 | ) |
| 30948 | .execute(&db) |
| 30949 | .await |
| 30950 | .unwrap(); |
| 30951 | |
| 30952 | let res = send(&app, "GET", "/insights/runs", Some(&staff), None).await; |
| 30953 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30954 | assert_eq!(res.body["total"], 1); |
| 30955 | let run = &res.body["items"][0]; |
| 30956 | assert_eq!(run["run_day"], "2026-09-16"); |
| 30957 | assert_eq!(run["status"], "partial"); |
| 30958 | assert_eq!(run["budget_exceeded"], true); |
| 30959 | assert_eq!(run["pending_students"], json!([ali_id])); |
| 30960 | assert_eq!(run["failed_modules"], json!(["study", "attendance"])); |
| 30961 | |
| 30962 | let res = send(&app, "GET", "/insights/runs", Some(&teacher), None).await; |
| 30963 | assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); |
| 30964 | } |
| 30965 | |
| 30966 | // --- course template: the six template/instance children are wired -------- |
| 30967 | |
| 30968 | /// The six foreign-module route pairs wave 2 mounted — subject selection, |
| 30969 | /// exam weights and the weekly plan under both `/offerings` and |
| 30970 | /// `/instances` — all answer through the built router with one manager |
| 30971 | /// session. A missed merge or a double prefix would 404 here; the module |
| 30972 | /// gates stay out of the way because the school runs every module. |
| 30973 | #[tokio::test] |
| 30974 | async fn offering_and_instance_template_children_answer_through_the_router() { |
| 30975 | let (app, db) = app_and_db().await; |
| 30976 | let mudur = login_as(&app, &db, "mudur_template", "manager").await; |
| 30977 | |
| 30978 | // One class-delivered ders attached to one şube: the attach auto-mints |
| 30979 | // the grade-level offering the section inherits from, and the instance |
| 30980 | // read names it. |
| 30981 | let t = taught(&app, &mudur, "resim").await; |
| 30982 | let read = send( |
| 30983 | &app, |
| 30984 | "GET", |
| 30985 | &format!("/instances/{}", t.instance), |
| 30986 | Some(&mudur), |
| 30987 | None, |
| 30988 | ) |
| 30989 | .await; |
| 30990 | assert_eq!(read.status, StatusCode::OK, "{}", read.body); |
| 30991 | let offering = read.body["offering"] |
| 30992 | .as_str() |
| 30993 | .expect("instance carries its offering") |
| 30994 | .to_string(); |
| 30995 | |
| 30996 | // The catalog POST itself: a second grade level of the same ders is a |
| 30997 | // fresh template — 201, not a 404 from a double-prefixed mount. |
| 30998 | let created = send( |
| 30999 | &app, |
| 31000 | "POST", |
| 31001 | "/offerings", |
| 31002 | Some(&mudur), |
| 31003 | Some(json!({ "course": t.course, "grade_level": 0 })), |
| 31004 | ) |
| 31005 | .await; |
| 31006 | assert_eq!(created.status, StatusCode::CREATED, "{}", created.body); |
| 31007 | |
| 31008 | for (path, why) in [ |
| 31009 | ( |
| 31010 | format!("/offerings/{offering}/subjects"), |
| 31011 | "offering subjects", |
| 31012 | ), |
| 31013 | ( |
| 31014 | format!("/offerings/{offering}/exam-weights"), |
| 31015 | "offering exam weights", |
| 31016 | ), |
| 31017 | ( |
| 31018 | format!("/offerings/{offering}/weekly-plan"), |
| 31019 | "offering weekly plan", |
| 31020 | ), |
| 31021 | ( |
| 31022 | format!("/instances/{}/subjects", t.instance), |
| 31023 | "instance subjects", |
| 31024 | ), |
| 31025 | ( |
| 31026 | format!("/instances/{}/exam-weights", t.instance), |
| 31027 | "instance exam weights", |
| 31028 | ), |
| 31029 | ( |
| 31030 | format!("/instances/{}/weekly-plan", t.instance), |
| 31031 | "instance weekly plan", |
| 31032 | ), |
| 31033 | ] { |
| 31034 | let res = send(&app, "GET", &path, Some(&mudur), None).await; |
| 31035 | assert_eq!(res.status, StatusCode::OK, "{why}: {}", res.body); |
| 31036 | } |
| 31037 | } |
| 31038 | |
| 31039 | // --- course template: the user's per-class scenario, end to end ------------- |
| 31040 | |
| 31041 | /// The user's scenario (2026-09-23): a 9th-grade and a 12th-grade section both |
| 31042 | /// teach Biology — same catalog course, two instances — and each resolves to |
| 31043 | /// the template of its own grade, with per-class overrides deviating exactly |
| 31044 | /// one axis at a time (override-or-inherit, never merge). Driven over the HTTP |
| 31045 | /// surface only: |
| 31046 | /// |
| 31047 | /// (a) both instances share the course id but resolve to different offerings; |
| 31048 | /// (b) the grade-9 offering's template (title suffix, description, hours, a |
| 31049 | /// topic, a weight, a slot) shows on the grade-9 instance and nowhere on |
| 31050 | /// grade 12; |
| 31051 | /// (c) a `ders_saati` override on one instance deviates exactly that axis; |
| 31052 | /// (d) an own-but-empty subject set beats the offering's set; |
| 31053 | /// (e) the reset doors restore inheritance (a scalar, and the set axes); |
| 31054 | /// (f) a topic of the grade-9 template tags a question there and is refused |
| 31055 | /// in the grade-12 instance; |
| 31056 | /// (g) the marks and karne reports show each section its own resolved title. |
| 31057 | #[tokio::test] |
| 31058 | async fn course_template_resolution_is_per_class_end_to_end() { |
| 31059 | let (app, db) = app_and_db().await; |
| 31060 | let staff = login_as(&app, &db, "mudur_scenario", "manager").await; |
| 31061 | |
| 31062 | // One ders, two topics, two şubeler at different rungs of the ladder. |
| 31063 | let course = create_course(&app, &staff, "Biyoloji").await; |
| 31064 | let s1 = create_subject(&app, &staff, &course, "Hücre").await; |
| 31065 | let s2 = create_subject(&app, &staff, &course, "Genetik").await; |
| 31066 | let year = ensure_year(&app, &staff).await; |
| 31067 | let term = create_term(&app, &staff, &year, "1. Dönem").await; |
| 31068 | let class_a = create_class( |
| 31069 | &app, |
| 31070 | &staff, |
| 31071 | "9-A", |
| 31072 | json!({ "year": year, "grade_level": 9 }), |
| 31073 | ) |
| 31074 | .await; |
| 31075 | let class_b = create_class( |
| 31076 | &app, |
| 31077 | &staff, |
| 31078 | "12-B", |
| 31079 | json!({ "year": year, "grade_level": 12 }), |
| 31080 | ) |
| 31081 | .await; |
| 31082 | let inst_a = attach_instance(&app, &staff, &class_a, &course).await; |
| 31083 | let inst_b = attach_instance(&app, &staff, &class_b, &course).await; |
| 31084 | let read_instance = |uri: String| { |
| 31085 | let app = app.clone(); |
| 31086 | let staff = staff.clone(); |
| 31087 | async move { send(&app, "GET", &uri, Some(&staff), None).await } |
| 31088 | }; |
| 31089 | |
| 31090 | // (a) Same ders, two instances — and each teaches from its own grade's |
| 31091 | // template: shared course id, distinct offering ids, both scalars still |
| 31092 | // inheriting the catalog/constant floor. |
| 31093 | let a = read_instance(format!("/instances/{inst_a}")).await; |
| 31094 | let b = read_instance(format!("/instances/{inst_b}")).await; |
| 31095 | assert_eq!(a.status, StatusCode::OK, "{}", a.body); |
| 31096 | assert_eq!(b.status, StatusCode::OK, "{}", b.body); |
| 31097 | assert_eq!(a.body["course"], course, "(a) same catalog course"); |
| 31098 | assert_eq!(b.body["course"], course, "(a) same catalog course"); |
| 31099 | let offering_a = a.body["offering"].as_str().expect("(a) offering id"); |
| 31100 | let offering_b = b.body["offering"].as_str().expect("(a) offering id"); |
| 31101 | assert_ne!(offering_a, offering_b, "(a) each grade has its own template"); |
| 31102 | assert_eq!(a.body["title"], "Biyoloji", "(a) pre-template title inherits"); |
| 31103 | assert_eq!(a.body["title_overridden"], false); |
| 31104 | assert_eq!(b.body["ders_saati"], 1, "(a) the constant floor, not a value"); |
| 31105 | assert_eq!(b.body["ders_saati_overridden"], false); |
| 31106 | |
| 31107 | // (b) Fill the grade-9 template; the grade-12 one stays empty. |
| 31108 | let patched = send( |
| 31109 | &app, |
| 31110 | "PATCH", |
| 31111 | &format!("/offerings/{offering_a}"), |
| 31112 | Some(&staff), |
| 31113 | Some(json!({ |
| 31114 | "title": "Biyoloji (9. sınıf)", |
| 31115 | "description": "9. sınıf müfredatı", |
| 31116 | "default_ders_saati": 4 |
| 31117 | })), |
| 31118 | ) |
| 31119 | .await; |
| 31120 | assert_eq!(patched.status, StatusCode::OK, "{}", patched.body); |
| 31121 | for (offering, subject) in [(offering_a, &s1), (offering_b, &s2)] { |
| 31122 | let res = send( |
| 31123 | &app, |
| 31124 | "POST", |
| 31125 | &format!("/offerings/{offering}/subjects"), |
| 31126 | Some(&staff), |
| 31127 | Some(json!({ "subject": subject })), |
| 31128 | ) |
| 31129 | .await; |
| 31130 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 31131 | } |
| 31132 | let weighted = send( |
| 31133 | &app, |
| 31134 | "PATCH", |
| 31135 | &format!("/offerings/{offering_a}/exam-weights"), |
| 31136 | Some(&staff), |
| 31137 | Some(json!({ "kind": "yazili", "weight": 3 })), |
| 31138 | ) |
| 31139 | .await; |
| 31140 | assert_eq!(weighted.status, StatusCode::OK, "{}", weighted.body); |
| 31141 | let slotted = send( |
| 31142 | &app, |
| 31143 | "POST", |
| 31144 | &format!("/offerings/{offering_a}/weekly-plan"), |
| 31145 | Some(&staff), |
| 31146 | Some(json!({ "weekday": 1, "starts_at": 540, "ends_at": 570 })), |
| 31147 | ) |
| 31148 | .await; |
| 31149 | assert_eq!(slotted.status, StatusCode::CREATED, "{}", slotted.body); |
| 31150 | |
| 31151 | let a = read_instance(format!("/instances/{inst_a}")).await; |
| 31152 | assert_eq!(a.body["title"], "Biyoloji (9. sınıf)", "(b) grade-9 title"); |
| 31153 | assert_eq!(a.body["title_overridden"], false, "(b) inherited, not owned"); |
| 31154 | assert_eq!(a.body["description"], "9. sınıf müfredatı"); |
| 31155 | assert_eq!(a.body["ders_saati"], 4, "(b) the grade-9 default"); |
| 31156 | assert_eq!(a.body["subjects_inherited"], true); |
| 31157 | assert_eq!(a.body["subjects"][0]["id"], s1, "(b) the grade-9 syllabus"); |
| 31158 | let a_weights = a.body["exam_weights"] |
| 31159 | .as_array() |
| 31160 | .expect("(b) resolved weight map"); |
| 31161 | let a_yazili = a_weights |
| 31162 | .iter() |
| 31163 | .find(|w| w["kind"] == "yazili") |
| 31164 | .expect("(b) settings kinds are always mapped"); |
| 31165 | assert_eq!(a_yazili["weight"], 3, "(b) the template's weight"); |
| 31166 | assert_eq!(a.body["weekly_plan"][0]["weekday"], 1, "(b) template week"); |
| 31167 | |
| 31168 | let b = read_instance(format!("/instances/{inst_b}")).await; |
| 31169 | assert_eq!(b.body["title"], "Biyoloji", "(b) grade 12 stays on the catalog"); |
| 31170 | assert_eq!(b.body["ders_saati"], 1, "(b) the empty template inherits all"); |
| 31171 | assert_eq!(b.body["subjects"][0]["id"], s2, "(b) grade 12's own template"); |
| 31172 | assert!( |
| 31173 | !b.body["subjects"] |
| 31174 | .as_array() |
| 31175 | .expect("(b) subjects array") |
| 31176 | .iter() |
| 31177 | .any(|s| s["id"] == s1), |
| 31178 | "(b) no bleed of the grade-9 topic into grade 12" |
| 31179 | ); |
| 31180 | let b_weights = b.body["exam_weights"] |
| 31181 | .as_array() |
| 31182 | .expect("(b) resolved weight map"); |
| 31183 | let b_yazili = b_weights |
| 31184 | .iter() |
| 31185 | .find(|w| w["kind"] == "yazili") |
| 31186 | .expect("(b) settings kinds are always mapped"); |
| 31187 | assert_eq!(b_yazili["weight"], 1, "(b) grade 12 keeps the settings weight"); |
| 31188 | assert_eq!( |
| 31189 | b.body["weekly_plan"] |
| 31190 | .as_array() |
| 31191 | .expect("(b) weekly plan array") |
| 31192 | .len(), |
| 31193 | 0, |
| 31194 | "(b) the empty grade-12 template week" |
| 31195 | ); |
| 31196 | |
| 31197 | // (c) Override exactly one axis on the grade-9 section: its hours move, |
| 31198 | // everything else keeps flowing from the template, and grade 12 is |
| 31199 | // untouched. |
| 31200 | let patched = send( |
| 31201 | &app, |
| 31202 | "PATCH", |
| 31203 | &format!("/instances/{inst_a}"), |
| 31204 | Some(&staff), |
| 31205 | Some(json!({ "ders_saati": 6 })), |
| 31206 | ) |
| 31207 | .await; |
| 31208 | assert_eq!(patched.status, StatusCode::OK, "{}", patched.body); |
| 31209 | let a = read_instance(format!("/instances/{inst_a}")).await; |
| 31210 | assert_eq!(a.body["ders_saati"], 6, "(c) the override wins"); |
| 31211 | assert_eq!(a.body["ders_saati_overridden"], true, "(c) flagged as owned"); |
| 31212 | assert_eq!( |
| 31213 | a.body["title"], "Biyoloji (9. sınıf)", |
| 31214 | "(c) no merge: the title still inherits" |
| 31215 | ); |
| 31216 | assert_eq!(a.body["title_overridden"], false, "(c) still not owned"); |
| 31217 | assert_eq!( |
| 31218 | a.body["subjects_inherited"], true, |
| 31219 | "(c) the set axis is untouched" |
| 31220 | ); |
| 31221 | let b = read_instance(format!("/instances/{inst_b}")).await; |
| 31222 | assert_eq!(b.body["ders_saati"], 1, "(c) grade 12 unaffected"); |
| 31223 | |
| 31224 | // (f) Topic tagging while grade 9 still inherits: its template's topic is |
| 31225 | // accepted there, refused next door. |
| 31226 | let exam_a = create_exam(&app, &staff, &inst_a, &term, "A sınavı", "yazili").await; |
| 31227 | let exam_b = create_exam(&app, &staff, &inst_b, &term, "B sınavı", "yazili").await; |
| 31228 | let tagged = send( |
| 31229 | &app, |
| 31230 | "POST", |
| 31231 | &format!("/exams/{exam_a}/questions"), |
| 31232 | Some(&staff), |
| 31233 | Some(json!({ "subject_id": s1, "text": "Mitokondri?", "kind": "text", "points": 10 })), |
| 31234 | ) |
| 31235 | .await; |
| 31236 | assert_eq!(tagged.status, StatusCode::CREATED, "(f) {}", tagged.body); |
| 31237 | let refused = send( |
| 31238 | &app, |
| 31239 | "POST", |
| 31240 | &format!("/exams/{exam_b}/questions"), |
| 31241 | Some(&staff), |
| 31242 | Some(json!({ "subject_id": s1, "text": "Mitokondri?", "kind": "text", "points": 10 })), |
| 31243 | ) |
| 31244 | .await; |
| 31245 | assert_eq!(refused.status, StatusCode::BAD_REQUEST, "(f) {}", refused.body); |
| 31246 | let own = send( |
| 31247 | &app, |
| 31248 | "POST", |
| 31249 | &format!("/exams/{exam_b}/questions"), |
| 31250 | Some(&staff), |
| 31251 | Some(json!({ "subject_id": s2, "text": "DNA?", "kind": "text", "points": 10 })), |
| 31252 | ) |
| 31253 | .await; |
| 31254 | assert_eq!( |
| 31255 | own.status, |
| 31256 | StatusCode::CREATED, |
| 31257 | "(f) the refusal is syllabus scope, not course scope: {}", |
| 31258 | own.body |
| 31259 | ); |
| 31260 | |
| 31261 | // (d) An own set that is EMPTY wins: take a topic onto the section and |
| 31262 | // drop it — the flag stays "own", the resolved set is empty, and the |
| 31263 | // sibling still sees its own template's topic. |
| 31264 | let took = send( |
| 31265 | &app, |
| 31266 | "POST", |
| 31267 | &format!("/instances/{inst_a}/subjects"), |
| 31268 | Some(&staff), |
| 31269 | Some(json!({ "subject": s1 })), |
| 31270 | ) |
| 31271 | .await; |
| 31272 | assert_eq!(took.status, StatusCode::CREATED, "(d) {}", took.body); |
| 31273 | let dropped = send( |
| 31274 | &app, |
| 31275 | "DELETE", |
| 31276 | &format!("/instances/{inst_a}/subjects/{s1}"), |
| 31277 | Some(&staff), |
| 31278 | None, |
| 31279 | ) |
| 31280 | .await; |
| 31281 | assert_eq!(dropped.status, StatusCode::NO_CONTENT, "(d) {}", dropped.body); |
| 31282 | let a = read_instance(format!("/instances/{inst_a}")).await; |
| 31283 | assert_eq!(a.body["subjects_inherited"], false, "(d) the set is its own"); |
| 31284 | assert_eq!( |
| 31285 | a.body["subjects"] |
| 31286 | .as_array() |
| 31287 | .expect("(d) subjects array") |
| 31288 | .len(), |
| 31289 | 0, |
| 31290 | "(d) empty own set beats the template's" |
| 31291 | ); |
| 31292 | let b = read_instance(format!("/instances/{inst_b}")).await; |
| 31293 | assert_eq!( |
| 31294 | b.body["subjects"][0]["id"], s2, |
| 31295 | "(d) the sibling still inherits its template" |
| 31296 | ); |
| 31297 | |
| 31298 | // (e) The reset doors restore inheritance: the scalar goes back to the |
| 31299 | // offering's default, the weekly plan back to the template week, and the |
| 31300 | // subjects flag back to the template's set. |
| 31301 | let reset = send( |
| 31302 | &app, |
| 31303 | "POST", |
| 31304 | &format!("/instances/{inst_a}/reset"), |
| 31305 | Some(&staff), |
| 31306 | Some(json!({ "fields": ["ders_saati"] })), |
| 31307 | ) |
| 31308 | .await; |
| 31309 | assert_eq!(reset.status, StatusCode::OK, "(e) {}", reset.body); |
| 31310 | assert_eq!(reset.body["ders_saati"], 4, "(e) the offering default again"); |
| 31311 | assert_eq!(reset.body["ders_saati_overridden"], false, "(e) inheriting"); |
| 31312 | |
| 31313 | let own_slot = send( |
| 31314 | &app, |
| 31315 | "POST", |
| 31316 | &format!("/instances/{inst_a}/weekly-plan"), |
| 31317 | Some(&staff), |
| 31318 | Some(json!({ "weekday": 2, "starts_at": 600, "ends_at": 630 })), |
| 31319 | ) |
| 31320 | .await; |
| 31321 | assert_eq!(own_slot.status, StatusCode::CREATED, "(e) {}", own_slot.body); |
| 31322 | let a = read_instance(format!("/instances/{inst_a}")).await; |
| 31323 | assert_eq!(a.body["weekly_plan_inherited"], false, "(e) own week wins"); |
| 31324 | assert_eq!(a.body["weekly_plan"][0]["weekday"], 2); |
| 31325 | let plan_reset = send( |
| 31326 | &app, |
| 31327 | "DELETE", |
| 31328 | &format!("/instances/{inst_a}/weekly-plan"), |
| 31329 | Some(&staff), |
| 31330 | None, |
| 31331 | ) |
| 31332 | .await; |
| 31333 | assert_eq!(plan_reset.status, StatusCode::NO_CONTENT, "(e)"); |
| 31334 | let a = read_instance(format!("/instances/{inst_a}")).await; |
| 31335 | assert_eq!(a.body["weekly_plan_inherited"], true, "(e) inheriting again"); |
| 31336 | assert_eq!( |
| 31337 | a.body["weekly_plan"][0]["weekday"], 1, |
| 31338 | "(e) the template week again" |
| 31339 | ); |
| 31340 | |
| 31341 | let subjects_reset = send( |
| 31342 | &app, |
| 31343 | "POST", |
| 31344 | &format!("/instances/{inst_a}/reset"), |
| 31345 | Some(&staff), |
| 31346 | Some(json!({ "fields": ["subjects"] })), |
| 31347 | ) |
| 31348 | .await; |
| 31349 | assert_eq!(subjects_reset.status, StatusCode::OK, "(e)" |
Showing the first 1 MiB of this file. View raw.