🏦 link exam questions to their bank template, both ways
Browse files at this commitebbd8135ed8fb9bbd23a9d15479a9e591a4996a1Parent: 45d6fea- fix
- 🏦 link exam questions to their bank template, both ways
5 changed files +253 -9
- src/domain/bank_question.rs +12 -4
- src/domain/exam.rs +8 -3
- src/domain/exam_question.rs +28 -0
- src/web/exams.rs +22 -2
- tests/integration.rs +183 -0
src/domain/bank_question.rsmodified+12 -4
| @@ -217,11 +217,19 @@ impl BankQuestion { | |||
| 217 | /// Delete the template and cascade-remove its bank images, so none points | 217 | /// Delete the template and cascade-remove its bank images, so none points |
| 218 | /// at a missing template. Bank rows have no answers. The image *blobs* are | 218 | /// at a missing template. Bank rows have no answers. The image *blobs* are |
| 219 | /// the web layer's to remove — it collects their names before calling this. | 219 | /// the web layer's to remove — it collects their names before calling this. |
| 220 | + /// | ||
| 221 | + /// Exam questions saved from this template keep living: only their | ||
| 222 | + /// `source_bank` provenance link is cleared, field-scoped (never a whole-row | ||
| 223 | + /// save — the question isn't ours and may be edited concurrently), so the | ||
| 224 | + /// bank page can't read a link to a template that no longer exists. | ||
| 220 | pub async fn delete(self, db: &Database) -> Result<BankQuestion, AppError> { | 225 | pub async fn delete(self, db: &Database) -> Result<BankQuestion, AppError> { |
| 221 | - db.query("DELETE bank_question_image WHERE bank_question = $b;") | 226 | + db.query( |
| 222 | - .bind(("b", self.id.record())) | 227 | + "DELETE bank_question_image WHERE bank_question = $b; |
| 223 | - .await? | 228 | + UPDATE exam_question SET source_bank = NONE WHERE source_bank = $b;", |
| 224 | - .check()?; | 229 | + ) |
| 230 | + .bind(("b", self.id.record())) | ||
| 231 | + .await? | ||
| 232 | + .check()?; | ||
| 225 | let deleted: Option<BankQuestion> = db.delete(self.id.record()).await?; | 233 | let deleted: Option<BankQuestion> = db.delete(self.id.record()).await?; |
| 226 | deleted.ok_or(AppError::NotFound) | 234 | deleted.ok_or(AppError::NotFound) |
| 227 | } | 235 | } |
src/domain/exam.rsmodified+8 -3
| @@ -474,6 +474,10 @@ impl Exam { | |||
| 474 | /// so a failure can't leave an emptied-out exam shell behind. The image | 474 | /// so a failure can't leave an emptied-out exam shell behind. The image |
| 475 | /// *blobs* (question and answer) are the web layer's to remove — it collects | 475 | /// *blobs* (question and answer) are the web layer's to remove — it collects |
| 476 | /// their names before calling this. | 476 | /// their names before calling this. |
| 477 | + /// | ||
| 478 | + /// Bank templates saved out of this exam survive it — they are a separate, | ||
| 479 | + /// reusable library — so only their `source_exam` provenance link is cleared, | ||
| 480 | + /// in the same transaction, never left pointing at a dead exam. | ||
| 477 | pub async fn delete(self, db: &Database) -> Result<Exam, AppError> { | 481 | pub async fn delete(self, db: &Database) -> Result<Exam, AppError> { |
| 478 | let mut result = db | 482 | let mut result = db |
| 479 | .query( | 483 | .query( |
| @@ -484,15 +488,16 @@ impl Exam { | |||
| 484 | DELETE answer_image WHERE exam = $ex; | 488 | DELETE answer_image WHERE exam = $ex; |
| 485 | DELETE question_image WHERE exam = $ex; | 489 | DELETE question_image WHERE exam = $ex; |
| 486 | DELETE exam_question WHERE exam = $ex; | 490 | DELETE exam_question WHERE exam = $ex; |
| 491 | + UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex; | ||
| 487 | DELETE $ex RETURN BEFORE; | 492 | DELETE $ex RETURN BEFORE; |
| 488 | COMMIT TRANSACTION;", | 493 | COMMIT TRANSACTION;", |
| 489 | ) | 494 | ) |
| 490 | .bind(("ex", self.id.record())) | 495 | .bind(("ex", self.id.record())) |
| 491 | .await? | 496 | .await? |
| 492 | .check()?; | 497 | .check()?; |
| 493 | - // Statement slots count BEGIN and the child deletes: the exam's own | 498 | + // Statement slots count BEGIN, the child deletes and the bank |
| 494 | - // DELETE is slot 7. | 499 | + // provenance clear: the exam's own DELETE is slot 8. |
| 495 | - let deleted: Option<Exam> = result.take::<Vec<Exam>>(7)?.into_iter().next(); | 500 | + let deleted: Option<Exam> = result.take::<Vec<Exam>>(8)?.into_iter().next(); |
| 496 | deleted.ok_or(AppError::NotFound) | 501 | deleted.ok_or(AppError::NotFound) |
| 497 | } | 502 | } |
| 498 | } | 503 | } |
src/domain/exam_question.rsmodified+28 -0
| @@ -334,6 +334,34 @@ impl ExamQuestion { | |||
| 334 | updated.ok_or(AppError::NotFound) | 334 | updated.ok_or(AppError::NotFound) |
| 335 | } | 335 | } |
| 336 | 336 | ||
| 337 | + /// Point the question at the bank template it was just saved into | ||
| 338 | + /// (`POST …/questions/{qid}/to-bank`), the mirror of the `source_bank` | ||
| 339 | + /// [`Self::create_from_bank`] writes on the other direction. Overwrites any | ||
| 340 | + /// earlier link: repeat saves mint a new template and the newest one wins. | ||
| 341 | + /// | ||
| 342 | + /// Field-scoped write, unlike [`Self::update`]: the caller holds only | ||
| 343 | + /// `BANK_LOCK` (which guards the bank, not `exam_question`) and awaits a | ||
| 344 | + /// bank insert plus the whole blob-copy loop between reading this row and | ||
| 345 | + /// linking it, so a concurrent `PATCH` of the question is entirely possible | ||
| 346 | + /// in that window — a whole-row save would silently revert it. | ||
| 347 | + pub async fn link_source_bank( | ||
| 348 | + self, | ||
| 349 | + source: BankQuestionId, | ||
| 350 | + db: &Database, | ||
| 351 | + ) -> Result<ExamQuestion, AppError> { | ||
| 352 | + let mut result = db | ||
| 353 | + .query("UPDATE $id SET source_bank = $bank RETURN AFTER") | ||
| 354 | + .bind(("id", self.id.record())) | ||
| 355 | + .bind(("bank", source.record())) | ||
| 356 | + .await? | ||
| 357 | + .check()?; | ||
| 358 | + result | ||
| 359 | + .take::<Vec<ExamQuestion>>(0)? | ||
| 360 | + .into_iter() | ||
| 361 | + .next() | ||
| 362 | + .ok_or(AppError::NotFound) | ||
| 363 | + } | ||
| 364 | + | ||
| 337 | /// Delete the question and cascade-remove its answers and image rows, so | 365 | /// Delete the question and cascade-remove its answers and image rows, so |
| 338 | /// neither can point at a missing question. The image *blobs* are the web | 366 | /// neither can point at a missing question. The image *blobs* are the web |
| 339 | /// layer's to remove — it collects their names before calling this. | 367 | /// layer's to remove — it collects their names before calling this. |
src/web/exams.rsmodified+22 -2
| @@ -1863,8 +1863,10 @@ async fn question_from_bank( | |||
| 1863 | /// template. Requires teacher+ and management rights over the exam's course. | 1863 | /// template. Requires teacher+ and management rights over the exam's course. |
| 1864 | /// The caller becomes the template's owner; the question's subject rides along | 1864 | /// The caller becomes the template's owner; the question's subject rides along |
| 1865 | /// as origin metadata. A full copy — text, points, spec, illustration, and | 1865 | /// as origin metadata. A full copy — text, points, spec, illustration, and |
| 1866 | -/// option pictures — lands under a new bank id; the exam question is untouched. | 1866 | +/// option pictures — lands under a new bank id. Provenance rides both ways: the |
| 1867 | -/// The origin exam is recorded on the template as `source_exam`. | 1867 | +/// origin exam is recorded on the template as `source_exam`, and the exam |
| 1868 | +/// question's `source_bank` is pointed at the new template (a repeat save is | ||
| 1869 | +/// allowed and repoints it at the newest one). | ||
| 1868 | #[utoipa::path( | 1870 | #[utoipa::path( |
| 1869 | post, | 1871 | post, |
| 1870 | path = "/{id}/questions/{qid}/to-bank", | 1872 | path = "/{id}/questions/{qid}/to-bank", |
| @@ -1953,6 +1955,24 @@ async fn question_to_bank( | |||
| 1953 | } | 1955 | } |
| 1954 | } | 1956 | } |
| 1955 | } | 1957 | } |
| 1958 | + // Provenance back-link, so a client can tell this question was already | ||
| 1959 | + // banked: the question points at the template it was saved into, and a | ||
| 1960 | + // repeat save repoints it at the newest one (never blocked). Written only | ||
| 1961 | + // after the all-or-nothing copy above, so a rolled-back template can never | ||
| 1962 | + // leave a dangling link. A failure here is logged and swallowed rather than | ||
| 1963 | + // rolling the template back: the save is the user's actual work and a | ||
| 1964 | + // template silently vanishing over a metadata write is worse than a | ||
| 1965 | + // template with no back-link (the next save re-links it). | ||
| 1966 | + let question_key = question.get_id().key().to_string(); | ||
| 1967 | + if let Err(err) = question | ||
| 1968 | + .link_source_bank(template.get_id().clone(), &st.db) | ||
| 1969 | + .await | ||
| 1970 | + { | ||
| 1971 | + tracing::warn!( | ||
| 1972 | + "saved question {question_key} to the bank but could not link it back: {err}" | ||
| 1973 | + ); | ||
| 1974 | + } | ||
| 1975 | + | ||
| 1956 | let images = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; | 1976 | let images = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; |
| 1957 | Ok(( | 1977 | Ok(( |
| 1958 | StatusCode::CREATED, | 1978 | StatusCode::CREATED, |
tests/integration.rsmodified+183 -0
| @@ -17476,3 +17476,186 @@ async fn bank_provenance_both_directions() { | |||
| 17476 | let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; | 17476 | let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; |
| 17477 | assert!(res.body["source_exam"].is_null()); | 17477 | assert!(res.body["source_exam"].is_null()); |
| 17478 | } | 17478 | } |
| 17479 | + | ||
| 17480 | +/// Save-to-bank also links the *question* back at the template it produced, so | ||
| 17481 | +/// a client can tell it was already banked. A repeat save is allowed and | ||
| 17482 | +/// repoints the link at the newer template. | ||
| 17483 | +#[tokio::test] | ||
| 17484 | +async fn to_bank_links_the_question_at_the_new_template() { | ||
| 17485 | + let (app, db) = app_and_db().await; | ||
| 17486 | + let teacher = login_as(&app, &db, "bback_t", "teacher").await; | ||
| 17487 | + let course = create_course(&app, &teacher, "bback_c").await; | ||
| 17488 | + let subject = create_subject(&app, &teacher, &course, "bback_s").await; | ||
| 17489 | + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; | ||
| 17490 | + let qid = create_question( | ||
| 17491 | + &app, | ||
| 17492 | + &teacher, | ||
| 17493 | + &exam, | ||
| 17494 | + &subject, | ||
| 17495 | + json!({ "text": "plain", "kind": "text", "points": 5 }), | ||
| 17496 | + ) | ||
| 17497 | + .await; | ||
| 17498 | + | ||
| 17499 | + // Fresh question: no link yet. | ||
| 17500 | + let source_bank_of = |body: &serde_json::Value| -> serde_json::Value { | ||
| 17501 | + common::items(body) | ||
| 17502 | + .iter() | ||
| 17503 | + .find(|q| q["id"] == qid) | ||
| 17504 | + .expect("question in list")["source_bank"] | ||
| 17505 | + .clone() | ||
| 17506 | + }; | ||
| 17507 | + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; | ||
| 17508 | + assert!(source_bank_of(&res.body).is_null()); | ||
| 17509 | + | ||
| 17510 | + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; | ||
| 17511 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 17512 | + let first = id_of(&res.body); | ||
| 17513 | + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; | ||
| 17514 | + assert_eq!(source_bank_of(&res.body), json!(first)); | ||
| 17515 | + | ||
| 17516 | + // Second save: still 201, a distinct template, and the link follows it. | ||
| 17517 | + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; | ||
| 17518 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 17519 | + let second = id_of(&res.body); | ||
| 17520 | + assert_ne!(first, second); | ||
| 17521 | + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; | ||
| 17522 | + assert_eq!(source_bank_of(&res.body), json!(second)); | ||
| 17523 | +} | ||
| 17524 | + | ||
| 17525 | +/// The back-link is a field-scoped write. `question_to_bank` reads the question, | ||
| 17526 | +/// then awaits a bank insert and the whole blob-copy loop before linking, holding | ||
| 17527 | +/// no lock over `exam_question` — so a `PATCH` can land in that window. A | ||
| 17528 | +/// whole-row save from the stale struct would silently revert it. Driven at the | ||
| 17529 | +/// domain level: HTTP offers no way to interleave inside the handler. | ||
| 17530 | +#[tokio::test] | ||
| 17531 | +async fn linking_the_bank_source_does_not_clobber_a_concurrent_edit() { | ||
| 17532 | + use hezarfen_backend::domain::bank_question::BankQuestionId; | ||
| 17533 | + use hezarfen_backend::domain::exam_question::{ExamQuestion, ExamQuestionId}; | ||
| 17534 | + | ||
| 17535 | + let (app, db) = app_and_db().await; | ||
| 17536 | + let teacher = login_as(&app, &db, "bclob_t", "teacher").await; | ||
| 17537 | + let course = create_course(&app, &teacher, "bclob_c").await; | ||
| 17538 | + let subject = create_subject(&app, &teacher, &course, "bclob_s").await; | ||
| 17539 | + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; | ||
| 17540 | + let qid = create_question( | ||
| 17541 | + &app, | ||
| 17542 | + &teacher, | ||
| 17543 | + &exam, | ||
| 17544 | + &subject, | ||
| 17545 | + json!({ "text": "original", "kind": "text", "points": 5 }), | ||
| 17546 | + ) | ||
| 17547 | + .await; | ||
| 17548 | + let res = send( | ||
| 17549 | + &app, | ||
| 17550 | + "POST", | ||
| 17551 | + "/bank-questions", | ||
| 17552 | + Some(&teacher), | ||
| 17553 | + Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), | ||
| 17554 | + ) | ||
| 17555 | + .await; | ||
| 17556 | + let bid = id_of(&res.body); | ||
| 17557 | + | ||
| 17558 | + // The handler's read, then someone else's edit lands mid-window. | ||
| 17559 | + let stale = ExamQuestion::read(&ExamQuestionId::from_key(&qid), &db) | ||
| 17560 | + .await | ||
| 17561 | + .unwrap() | ||
| 17562 | + .expect("question exists"); | ||
| 17563 | + let res = send( | ||
| 17564 | + &app, | ||
| 17565 | + "PATCH", | ||
| 17566 | + &format!("/exams/{exam}/questions/{qid}"), | ||
| 17567 | + Some(&teacher), | ||
| 17568 | + Some(json!({ "text": "edited by someone else", "points": 9 })), | ||
| 17569 | + ) | ||
| 17570 | + .await; | ||
| 17571 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 17572 | + | ||
| 17573 | + stale | ||
| 17574 | + .link_source_bank(BankQuestionId::from_key(&bid), &db) | ||
| 17575 | + .await | ||
| 17576 | + .expect("link written"); | ||
| 17577 | + | ||
| 17578 | + // The edit survives and the link is set. | ||
| 17579 | + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; | ||
| 17580 | + let question = common::items(&res.body) | ||
| 17581 | + .iter() | ||
| 17582 | + .find(|q| q["id"] == qid) | ||
| 17583 | + .expect("question in list") | ||
| 17584 | + .clone(); | ||
| 17585 | + assert_eq!(question["text"], "edited by someone else"); | ||
| 17586 | + assert_eq!(question["points"], 9); | ||
| 17587 | + assert_eq!(question["source_bank"], bid); | ||
| 17588 | +} | ||
| 17589 | + | ||
| 17590 | +/// Deleting a bank template clears the provenance link on every exam question | ||
| 17591 | +/// saved from it, instead of leaving `source_bank` pointing at a dead row. | ||
| 17592 | +#[tokio::test] | ||
| 17593 | +async fn deleting_a_template_clears_the_questions_source_bank() { | ||
| 17594 | + let (app, db) = app_and_db().await; | ||
| 17595 | + let teacher = login_as(&app, &db, "bdang_t", "teacher").await; | ||
| 17596 | + let course = create_course(&app, &teacher, "bdang_c").await; | ||
| 17597 | + let subject = create_subject(&app, &teacher, &course, "bdang_s").await; | ||
| 17598 | + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; | ||
| 17599 | + let qid = create_question( | ||
| 17600 | + &app, | ||
| 17601 | + &teacher, | ||
| 17602 | + &exam, | ||
| 17603 | + &subject, | ||
| 17604 | + json!({ "text": "plain", "kind": "text", "points": 5 }), | ||
| 17605 | + ) | ||
| 17606 | + .await; | ||
| 17607 | + | ||
| 17608 | + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; | ||
| 17609 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 17610 | + let bid = id_of(&res.body); | ||
| 17611 | + | ||
| 17612 | + let source_bank_of = |body: &serde_json::Value| -> serde_json::Value { | ||
| 17613 | + common::items(body) | ||
| 17614 | + .iter() | ||
| 17615 | + .find(|q| q["id"] == qid) | ||
| 17616 | + .expect("question in list")["source_bank"] | ||
| 17617 | + .clone() | ||
| 17618 | + }; | ||
| 17619 | + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; | ||
| 17620 | + assert_eq!(source_bank_of(&res.body), json!(bid)); | ||
| 17621 | + | ||
| 17622 | + let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; | ||
| 17623 | + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | ||
| 17624 | + | ||
| 17625 | + // The question survives the template with no dangling link. | ||
| 17626 | + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; | ||
| 17627 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 17628 | + assert!(source_bank_of(&res.body).is_null(), "{}", res.body); | ||
| 17629 | +} | ||
| 17630 | + | ||
| 17631 | +/// The mirror: deleting the origin exam clears `source_exam` on the templates | ||
| 17632 | +/// saved out of it — the template is a reusable library row and outlives the | ||
| 17633 | +/// exam, but the bank page must not read a link to a dead exam. | ||
| 17634 | +#[tokio::test] | ||
| 17635 | +async fn deleting_an_exam_clears_the_templates_source_exam() { | ||
| 17636 | + let (app, db) = app_and_db().await; | ||
| 17637 | + let teacher = login_as(&app, &db, "edang_t", "teacher").await; | ||
| 17638 | + let course = create_course(&app, &teacher, "edang_c").await; | ||
| 17639 | + let subject = create_subject(&app, &teacher, &course, "edang_s").await; | ||
| 17640 | + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; | ||
| 17641 | + let qid = create_question( | ||
| 17642 | + &app, | ||
| 17643 | + &teacher, | ||
| 17644 | + &exam, | ||
| 17645 | + &subject, | ||
| 17646 | + json!({ "text": "plain", "kind": "text", "points": 5 }), | ||
| 17647 | + ) | ||
| 17648 | + .await; | ||
| 17649 | + | ||
| 17650 | + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; | ||
| 17651 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 17652 | + let bid = id_of(&res.body); | ||
| 17653 | + assert_eq!(res.body["source_exam"], exam); | ||
| 17654 | + | ||
| 17655 | + let res = send(&app, "DELETE", &format!("/exams/{exam}"), Some(&teacher), None).await; | ||
| 17656 | + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | ||
| 17657 | + | ||
| 17658 | + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; | ||
| 17659 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 17660 | + assert!(res.body["source_exam"].is_null(), "{}", res.body); | ||
| 17661 | +} | ||