| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | use std::collections::HashMap; |
| 9 | |
| 10 | use sqlx::types::Json; |
| 11 | |
| 12 | use crate::database::{Database, tx_with_retry}; |
| 13 | use crate::db::page::{PagedList, Param}; |
| 14 | use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; |
| 15 | use crate::domain::bank_question_image::BankQuestionImage; |
| 16 | use crate::domain::exam::ExamId; |
| 17 | use crate::domain::exam_question::{ |
| 18 | Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 19 | }; |
| 20 | use crate::domain::note_file::FileContentType; |
| 21 | use crate::domain::subject::SubjectId; |
| 22 | use crate::domain::text_fold::{search_fold, search_fold_sql}; |
| 23 | use crate::domain::timestamp::Timestamp; |
| 24 | use crate::domain::user::UserId; |
| 25 | use crate::error::AppError; |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | fn choices_as_value(choices: &[Choice]) -> serde_json::Value { |
| 31 | serde_json::to_value(choices).expect("Choice serialization cannot fail") |
| 32 | } |
| 33 | |
| 34 | pub async fn create( |
| 35 | db: &Database, |
| 36 | owner: UserId, |
| 37 | subject: SubjectId, |
| 38 | text: QuestionText, |
| 39 | points: QuestionPoints, |
| 40 | spec: QuestionSpec, |
| 41 | ) -> Result<BankQuestion, AppError> { |
| 42 | insert(db, owner, subject, text, points, spec, None).await |
| 43 | } |
| 44 | |
| 45 | |
| 46 | |
| 47 | pub async fn create_from_exam( |
| 48 | db: &Database, |
| 49 | owner: UserId, |
| 50 | subject: SubjectId, |
| 51 | text: QuestionText, |
| 52 | points: QuestionPoints, |
| 53 | spec: QuestionSpec, |
| 54 | source: ExamId, |
| 55 | ) -> Result<BankQuestion, AppError> { |
| 56 | insert(db, owner, subject, text, points, spec, Some(source)).await |
| 57 | } |
| 58 | |
| 59 | #[allow(clippy::too_many_arguments)] |
| 60 | async fn insert( |
| 61 | db: &Database, |
| 62 | owner: UserId, |
| 63 | subject: SubjectId, |
| 64 | text: QuestionText, |
| 65 | points: QuestionPoints, |
| 66 | spec: QuestionSpec, |
| 67 | source_exam: Option<ExamId>, |
| 68 | ) -> Result<BankQuestion, AppError> { |
| 69 | let question = BankQuestion::from_parts( |
| 70 | BankQuestionId::generate(), |
| 71 | owner, |
| 72 | |
| 73 | |
| 74 | Some(subject), |
| 75 | text, |
| 76 | points, |
| 77 | spec, |
| 78 | source_exam, |
| 79 | |
| 80 | BankVisibility::default(), |
| 81 | Timestamp::now(), |
| 82 | ); |
| 83 | let row = sqlx::query_as!( |
| 84 | BankQuestion, |
| 85 | r#"INSERT INTO bank_question |
| 86 | (id, owner, subject, text, kind, points, choices, correct, |
| 87 | source_exam, visibility, created_at) |
| 88 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) |
| 89 | RETURNING id AS "id: BankQuestionId", owner AS "owner: UserId", |
| 90 | subject AS "subject: SubjectId", text AS "text: QuestionText", |
| 91 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", |
| 92 | choices AS "choices: Json<Vec<Choice>>", |
| 93 | correct AS "correct: ChoiceId", |
| 94 | source_exam AS "source_exam: ExamId", |
| 95 | visibility AS "visibility: BankVisibility", |
| 96 | created_at AS "created_at: Timestamp""#, |
| 97 | question.id.uuid(), |
| 98 | question.owner.uuid(), |
| 99 | question.subject.as_ref().map(SubjectId::uuid), |
| 100 | question.text.as_str(), |
| 101 | question.kind.as_str(), |
| 102 | question.points.as_i64(), |
| 103 | question |
| 104 | .choices |
| 105 | .as_ref() |
| 106 | .map(|json| choices_as_value(&json.0)), |
| 107 | question.correct.as_ref().map(ChoiceId::as_str), |
| 108 | question.source_exam.as_ref().map(ExamId::uuid), |
| 109 | question.visibility.as_str(), |
| 110 | question.created_at.as_millis(), |
| 111 | ) |
| 112 | .fetch_one(db) |
| 113 | .await?; |
| 114 | Ok(row) |
| 115 | } |
| 116 | |
| 117 | pub async fn read(db: &Database, id: &BankQuestionId) -> Result<Option<BankQuestion>, AppError> { |
| 118 | let row = sqlx::query_as!( |
| 119 | BankQuestion, |
| 120 | r#"SELECT id AS "id: BankQuestionId", owner AS "owner: UserId", |
| 121 | subject AS "subject: SubjectId", text AS "text: QuestionText", |
| 122 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", |
| 123 | choices AS "choices: Json<Vec<Choice>>", |
| 124 | correct AS "correct: ChoiceId", |
| 125 | source_exam AS "source_exam: ExamId", |
| 126 | visibility AS "visibility: BankVisibility", |
| 127 | created_at AS "created_at: Timestamp" |
| 128 | FROM bank_question WHERE id = $1"#, |
| 129 | id.uuid() |
| 130 | ) |
| 131 | .fetch_optional(db) |
| 132 | .await?; |
| 133 | Ok(row) |
| 134 | } |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | |
| 145 | |
| 146 | |
| 147 | |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | #[allow(clippy::too_many_arguments)] |
| 165 | pub async fn list( |
| 166 | db: &Database, |
| 167 | visible_to: Option<&UserId>, |
| 168 | owner: Option<&UserId>, |
| 169 | subject: Option<&SubjectId>, |
| 170 | visibility: Option<&BankVisibility>, |
| 171 | q: Option<&str>, |
| 172 | limit: Option<i64>, |
| 173 | offset: i64, |
| 174 | ) -> Result<(Vec<BankQuestion>, i64), AppError> { |
| 175 | let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); |
| 176 | let mut clauses: Vec<String> = Vec::new(); |
| 177 | let mut binds: Vec<Param> = Vec::new(); |
| 178 | if let Some(viewer) = visible_to { |
| 179 | binds.push(Param::Uuid(viewer.uuid())); |
| 180 | clauses.push(format!( |
| 181 | "(visibility = 'school' OR owner = ${})", |
| 182 | binds.len() |
| 183 | )); |
| 184 | } |
| 185 | if let Some(visibility) = visibility { |
| 186 | binds.push(Param::Text(visibility.as_str().to_string())); |
| 187 | clauses.push(format!("visibility = ${}", binds.len())); |
| 188 | } |
| 189 | if let Some(owner) = owner { |
| 190 | binds.push(Param::Uuid(owner.uuid())); |
| 191 | clauses.push(format!("owner = ${}", binds.len())); |
| 192 | } |
| 193 | if let Some(subject) = subject { |
| 194 | binds.push(Param::Uuid(subject.uuid())); |
| 195 | clauses.push(format!("subject = ${}", binds.len())); |
| 196 | } |
| 197 | if let Some(needle) = needle { |
| 198 | binds.push(Param::Text(needle)); |
| 199 | clauses.push(format!( |
| 200 | "position(${} in {}) > 0", |
| 201 | binds.len(), |
| 202 | search_fold_sql("text") |
| 203 | )); |
| 204 | } |
| 205 | let from_where = if clauses.is_empty() { |
| 206 | "bank_question WHERE true".to_string() |
| 207 | } else { |
| 208 | format!("bank_question WHERE {}", clauses.join(" AND ")) |
| 209 | }; |
| 210 | |
| 211 | |
| 212 | let mut page = PagedList::new(from_where, "ORDER BY id DESC"); |
| 213 | for bind in binds { |
| 214 | page = page.bind(bind); |
| 215 | } |
| 216 | page.run(limit, offset, db).await |
| 217 | } |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | |
| 227 | |
| 228 | |
| 229 | pub async fn usage_counts( |
| 230 | db: &Database, |
| 231 | ids: &[&BankQuestionId], |
| 232 | ) -> Result<HashMap<String, i64>, AppError> { |
| 233 | if ids.is_empty() { |
| 234 | return Ok(HashMap::new()); |
| 235 | } |
| 236 | let ids: Vec<uuid::Uuid> = ids.iter().map(|id| id.uuid()).collect(); |
| 237 | let rows = sqlx::query!( |
| 238 | r#"SELECT from_bank AS "from_bank: BankQuestionId", count(*) AS n |
| 239 | FROM exam_question |
| 240 | WHERE from_bank = ANY($1) |
| 241 | GROUP BY from_bank"#, |
| 242 | &ids, |
| 243 | ) |
| 244 | .fetch_all(db) |
| 245 | .await?; |
| 246 | Ok(rows |
| 247 | .into_iter() |
| 248 | .filter_map(|row| { |
| 249 | let n = row.n.unwrap_or(0); |
| 250 | row.from_bank.map(|from_bank| (from_bank.key(), n)) |
| 251 | }) |
| 252 | .collect()) |
| 253 | } |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | pub async fn update_if_unchanged( |
| 271 | db: &Database, |
| 272 | expected: BankQuestion, |
| 273 | subject: Option<SubjectId>, |
| 274 | text: QuestionText, |
| 275 | points: QuestionPoints, |
| 276 | spec: QuestionSpec, |
| 277 | visibility: BankVisibility, |
| 278 | ) -> Result<Option<BankQuestion>, AppError> { |
| 279 | let (kind, choices, correct) = spec.into_parts(); |
| 280 | let choices = choices.map(Json); |
| 281 | let row = sqlx::query_as!( |
| 282 | BankQuestion, |
| 283 | r#"UPDATE bank_question SET |
| 284 | subject = $2, text = $3, points = $4, kind = $5, |
| 285 | choices = $6, correct = $7, visibility = $8 |
| 286 | WHERE id = $1 |
| 287 | AND subject IS NOT DISTINCT FROM $9 |
| 288 | AND text = $10 |
| 289 | AND points = $11 |
| 290 | AND kind = $12 |
| 291 | AND choices IS NOT DISTINCT FROM $13 |
| 292 | AND correct IS NOT DISTINCT FROM $14 |
| 293 | AND visibility = $15 |
| 294 | RETURNING id AS "id: BankQuestionId", owner AS "owner: UserId", |
| 295 | subject AS "subject: SubjectId", text AS "text: QuestionText", |
| 296 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", |
| 297 | choices AS "choices: Json<Vec<Choice>>", |
| 298 | correct AS "correct: ChoiceId", |
| 299 | source_exam AS "source_exam: ExamId", |
| 300 | visibility AS "visibility: BankVisibility", |
| 301 | created_at AS "created_at: Timestamp""#, |
| 302 | expected.id.uuid(), |
| 303 | subject.as_ref().map(SubjectId::uuid), |
| 304 | text.as_str(), |
| 305 | points.as_i64(), |
| 306 | kind.as_str(), |
| 307 | choices.as_ref().map(|json| choices_as_value(&json.0)), |
| 308 | correct.as_ref().map(ChoiceId::as_str), |
| 309 | visibility.as_str(), |
| 310 | expected.subject.as_ref().map(SubjectId::uuid), |
| 311 | expected.text.as_str(), |
| 312 | expected.points.as_i64(), |
| 313 | expected.kind.as_str(), |
| 314 | expected |
| 315 | .choices |
| 316 | .as_ref() |
| 317 | .map(|json| choices_as_value(&json.0)), |
| 318 | expected.correct.as_ref().map(ChoiceId::as_str), |
| 319 | expected.visibility.as_str(), |
| 320 | ) |
| 321 | .fetch_optional(db) |
| 322 | .await?; |
| 323 | Ok(row) |
| 324 | } |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | |
| 336 | |
| 337 | |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | pub async fn delete( |
| 343 | db: &Database, |
| 344 | target: BankQuestion, |
| 345 | ) -> Result<(BankQuestion, Vec<BankQuestionImage>), AppError> { |
| 346 | tx_with_retry(db, true, async move |tx| { |
| 347 | let id = target.id.clone(); |
| 348 | sqlx::query!( |
| 349 | "UPDATE exam_question SET from_bank = NULL WHERE from_bank = $1", |
| 350 | id.uuid() |
| 351 | ) |
| 352 | .execute(&mut *tx) |
| 353 | .await?; |
| 354 | sqlx::query!( |
| 355 | "UPDATE exam_question SET banked_as = NULL WHERE banked_as = $1", |
| 356 | id.uuid() |
| 357 | ) |
| 358 | .execute(&mut *tx) |
| 359 | .await?; |
| 360 | let images = sqlx::query_as!( |
| 361 | BankQuestionImage, |
| 362 | r#"DELETE FROM bank_question_image WHERE bank_question = $1 |
| 363 | RETURNING bank_question AS "bank_question: BankQuestionId", |
| 364 | slot AS "slot: ChoiceId", file, |
| 365 | content_type AS "content_type: FileContentType", size"#, |
| 366 | id.uuid() |
| 367 | ) |
| 368 | .fetch_all(&mut *tx) |
| 369 | .await?; |
| 370 | let question = sqlx::query_as!( |
| 371 | BankQuestion, |
| 372 | r#"DELETE FROM bank_question WHERE id = $1 |
| 373 | RETURNING id AS "id: BankQuestionId", owner AS "owner: UserId", |
| 374 | subject AS "subject: SubjectId", |
| 375 | text AS "text: QuestionText", kind AS "kind: QuestionKind", |
| 376 | points AS "points: QuestionPoints", |
| 377 | choices AS "choices: Json<Vec<Choice>>", |
| 378 | correct AS "correct: ChoiceId", |
| 379 | source_exam AS "source_exam: ExamId", |
| 380 | visibility AS "visibility: BankVisibility", |
| 381 | created_at AS "created_at: Timestamp""#, |
| 382 | id.uuid() |
| 383 | ) |
| 384 | .fetch_optional(&mut *tx) |
| 385 | .await? |
| 386 | .ok_or(AppError::NotFound)?; |
| 387 | Ok((question, images)) |
| 388 | }) |
| 389 | .await |
| 390 | } |
| 391 | |
| 392 | #[cfg(test)] |
| 393 | mod tests { |
| 394 | use super::*; |
| 395 | use crate::constant::{BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL}; |
| 396 | |
| 397 | |
| 398 | |
| 399 | async fn a_person(db: &Database, label: &str) -> UserId { |
| 400 | let user = UserId::generate(); |
| 401 | sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)") |
| 402 | .bind(user.uuid()) |
| 403 | .bind(format!("{label}-{}", &user.key()[30..])) |
| 404 | .execute(db) |
| 405 | .await |
| 406 | .unwrap(); |
| 407 | user |
| 408 | } |
| 409 | |
| 410 | |
| 411 | |
| 412 | async fn a_subject(db: &Database) -> SubjectId { |
| 413 | *crate::db::subject::create( |
| 414 | db, |
| 415 | &crate::db::course::a_test_course(db).await, |
| 416 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 417 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 418 | ) |
| 419 | .await |
| 420 | .unwrap() |
| 421 | .get_id() |
| 422 | } |
| 423 | |
| 424 | fn spec() -> QuestionSpec { |
| 425 | use crate::domain::exam_question::{ChoiceInput, QuestionKind}; |
| 426 | QuestionSpec::try_new( |
| 427 | QuestionKind::try_new("choice").unwrap(), |
| 428 | Some(vec![ |
| 429 | ChoiceInput { |
| 430 | id: Some("a".into()), |
| 431 | text: "yes".into(), |
| 432 | }, |
| 433 | ChoiceInput { |
| 434 | id: Some("b".into()), |
| 435 | text: "no".into(), |
| 436 | }, |
| 437 | ]), |
| 438 | Some("b".into()), |
| 439 | &[], |
| 440 | ) |
| 441 | .unwrap() |
| 442 | } |
| 443 | |
| 444 | |
| 445 | |
| 446 | |
| 447 | |
| 448 | |
| 449 | |
| 450 | #[tokio::test] |
| 451 | async fn a_row_without_the_field_decodes_private() { |
| 452 | let (db, _leases) = crate::database::init_test_db().await; |
| 453 | let owner = a_person(&db, "owner").await; |
| 454 | let id = BankQuestionId::generate(); |
| 455 | sqlx::query( |
| 456 | "INSERT INTO bank_question (id, owner, text, kind, points, created_at) \ |
| 457 | VALUES ($1, $2, 'q', 'multiple_choice', 1, 0)", |
| 458 | ) |
| 459 | .bind(id.uuid()) |
| 460 | .bind(owner.uuid()) |
| 461 | .execute(&db) |
| 462 | .await |
| 463 | .unwrap(); |
| 464 | |
| 465 | let old = read(&db, &id).await.unwrap().expect("the row is there"); |
| 466 | assert_eq!(old.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); |
| 467 | assert!(!old.get_visibility().is_school()); |
| 468 | } |
| 469 | |
| 470 | |
| 471 | |
| 472 | #[tokio::test] |
| 473 | async fn list_hides_private_templates_from_others() { |
| 474 | let (db, _leases) = crate::database::init_test_db().await; |
| 475 | let owner = a_person(&db, "owner").await; |
| 476 | let other = a_person(&db, "other").await; |
| 477 | let private = create( |
| 478 | &db, |
| 479 | owner, |
| 480 | a_subject(&db).await, |
| 481 | QuestionText::try_new("secret").unwrap(), |
| 482 | QuestionPoints::try_new(1).unwrap(), |
| 483 | spec(), |
| 484 | ) |
| 485 | .await |
| 486 | .unwrap(); |
| 487 | let published = create( |
| 488 | &db, |
| 489 | owner, |
| 490 | a_subject(&db).await, |
| 491 | QuestionText::try_new("shared").unwrap(), |
| 492 | QuestionPoints::try_new(1).unwrap(), |
| 493 | spec(), |
| 494 | ) |
| 495 | .await |
| 496 | .unwrap(); |
| 497 | let subject = published.get_subject().cloned(); |
| 498 | update_if_unchanged( |
| 499 | &db, |
| 500 | published, |
| 501 | subject, |
| 502 | QuestionText::try_new("shared").unwrap(), |
| 503 | QuestionPoints::try_new(1).unwrap(), |
| 504 | spec(), |
| 505 | BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), |
| 506 | ) |
| 507 | .await |
| 508 | .unwrap(); |
| 509 | |
| 510 | |
| 511 | let (items, total) = list(&db, Some(&other), None, None, None, None, None, 0) |
| 512 | .await |
| 513 | .unwrap(); |
| 514 | assert_eq!((items.len(), total), (1, 1)); |
| 515 | assert_eq!(items[0].get_text().as_str(), "shared"); |
| 516 | |
| 517 | let (items, total) = list(&db, Some(&owner), None, None, None, None, None, 0) |
| 518 | .await |
| 519 | .unwrap(); |
| 520 | assert_eq!((items.len(), total), (2, 2)); |
| 521 | let (items, total) = list(&db, None, None, None, None, None, None, 0) |
| 522 | .await |
| 523 | .unwrap(); |
| 524 | assert_eq!((items.len(), total), (2, 2)); |
| 525 | |
| 526 | let (items, total) = list(&db, Some(&other), Some(&owner), None, None, None, None, 0) |
| 527 | .await |
| 528 | .unwrap(); |
| 529 | assert_eq!((items.len(), total), (1, 1)); |
| 530 | assert_eq!(private.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); |
| 531 | } |
| 532 | |
| 533 | |
| 534 | |
| 535 | |
| 536 | |
| 537 | |
| 538 | |
| 539 | #[tokio::test] |
| 540 | async fn a_merge_built_on_a_stale_snapshot_is_refused() { |
| 541 | let (db, _leases) = crate::database::init_test_db().await; |
| 542 | let owner = a_person(&db, "owner").await; |
| 543 | let stale = create( |
| 544 | &db, |
| 545 | owner, |
| 546 | a_subject(&db).await, |
| 547 | QuestionText::try_new("first").unwrap(), |
| 548 | QuestionPoints::try_new(1).unwrap(), |
| 549 | spec(), |
| 550 | ) |
| 551 | .await |
| 552 | .unwrap(); |
| 553 | |
| 554 | let landed = update_if_unchanged( |
| 555 | &db, |
| 556 | stale.clone(), |
| 557 | None, |
| 558 | QuestionText::try_new("theirs").unwrap(), |
| 559 | QuestionPoints::try_new(2).unwrap(), |
| 560 | spec(), |
| 561 | BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(), |
| 562 | ) |
| 563 | .await |
| 564 | .unwrap(); |
| 565 | assert!(landed.is_some(), "the first write is on a fresh snapshot"); |
| 566 | |
| 567 | let refused = update_if_unchanged( |
| 568 | &db, |
| 569 | stale, |
| 570 | None, |
| 571 | QuestionText::try_new("mine").unwrap(), |
| 572 | QuestionPoints::try_new(3).unwrap(), |
| 573 | spec(), |
| 574 | BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(), |
| 575 | ) |
| 576 | .await |
| 577 | .unwrap(); |
| 578 | assert!(refused.is_none(), "a stale merge must not be written"); |
| 579 | let stored = read(&db, landed.unwrap().get_id()).await.unwrap().unwrap(); |
| 580 | assert_eq!(stored.get_text().as_str(), "theirs"); |
| 581 | assert_eq!(stored.get_points().as_i64(), 2); |
| 582 | } |
| 583 | |
| 584 | |
| 585 | |
| 586 | |
| 587 | #[tokio::test] |
| 588 | async fn visibility_filter_narrows_never_widens() { |
| 589 | let (db, _leases) = crate::database::init_test_db().await; |
| 590 | let owner = a_person(&db, "owner").await; |
| 591 | let other = a_person(&db, "other").await; |
| 592 | async fn mine(db: &Database, owner: &UserId, text: &str) -> Result<BankQuestion, AppError> { |
| 593 | create( |
| 594 | db, |
| 595 | *owner, |
| 596 | a_subject(db).await, |
| 597 | QuestionText::try_new(text).unwrap(), |
| 598 | QuestionPoints::try_new(1).unwrap(), |
| 599 | spec(), |
| 600 | ) |
| 601 | .await |
| 602 | } |
| 603 | mine(&db, &owner, "draft").await.unwrap(); |
| 604 | let published = mine(&db, &owner, "shared").await.unwrap(); |
| 605 | let subject = published.get_subject().cloned(); |
| 606 | update_if_unchanged( |
| 607 | &db, |
| 608 | published, |
| 609 | subject, |
| 610 | QuestionText::try_new("shared").unwrap(), |
| 611 | QuestionPoints::try_new(1).unwrap(), |
| 612 | spec(), |
| 613 | BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), |
| 614 | ) |
| 615 | .await |
| 616 | .unwrap(); |
| 617 | let private = BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(); |
| 618 | let school = BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(); |
| 619 | |
| 620 | |
| 621 | let (items, total) = list(&db, Some(&owner), None, None, Some(&private), None, None, 0) |
| 622 | .await |
| 623 | .unwrap(); |
| 624 | assert_eq!((items.len(), total), (1, 1)); |
| 625 | assert_eq!(items[0].get_text().as_str(), "draft"); |
| 626 | let (items, total) = list(&db, Some(&owner), None, None, Some(&school), None, None, 0) |
| 627 | .await |
| 628 | .unwrap(); |
| 629 | assert_eq!((items.len(), total), (1, 1)); |
| 630 | assert_eq!(items[0].get_text().as_str(), "shared"); |
| 631 | |
| 632 | let (items, total) = list(&db, Some(&other), None, None, Some(&private), None, None, 0) |
| 633 | .await |
| 634 | .unwrap(); |
| 635 | assert!(items.is_empty()); |
| 636 | assert_eq!(total, 0); |
| 637 | |
| 638 | let (items, total) = list(&db, Some(&other), None, None, Some(&school), None, None, 0) |
| 639 | .await |
| 640 | .unwrap(); |
| 641 | assert_eq!((items.len(), total), (1, 1)); |
| 642 | |
| 643 | let (items, total) = list( |
| 644 | &db, |
| 645 | Some(&owner), |
| 646 | Some(&owner), |
| 647 | None, |
| 648 | Some(&school), |
| 649 | Some("draft"), |
| 650 | None, |
| 651 | 0, |
| 652 | ) |
| 653 | .await |
| 654 | .unwrap(); |
| 655 | assert!(items.is_empty()); |
| 656 | assert_eq!(total, 0); |
| 657 | } |
| 658 | |
| 659 | |
| 660 | |
| 661 | |
| 662 | #[tokio::test] |
| 663 | async fn usage_counts_tallies_a_page_in_one_statement() { |
| 664 | |
| 665 | |
| 666 | |
| 667 | let (db, _leases) = crate::database::init_test_db().await; |
| 668 | let owner = a_person(&db, "owner").await; |
| 669 | async fn template( |
| 670 | db: &Database, |
| 671 | owner: &UserId, |
| 672 | text: &str, |
| 673 | ) -> Result<BankQuestion, AppError> { |
| 674 | create( |
| 675 | db, |
| 676 | *owner, |
| 677 | a_subject(db).await, |
| 678 | QuestionText::try_new(text).unwrap(), |
| 679 | QuestionPoints::try_new(1).unwrap(), |
| 680 | spec(), |
| 681 | ) |
| 682 | .await |
| 683 | } |
| 684 | let used_twice = template(&db, &owner, "twice").await.unwrap(); |
| 685 | let used_once = template(&db, &owner, "once").await.unwrap(); |
| 686 | let unused = template(&db, &owner, "never").await.unwrap(); |
| 687 | |
| 688 | |
| 689 | |
| 690 | |
| 691 | let exam = crate::db::exam::published_exam(&db).await.get_id().clone(); |
| 692 | let other_exam = crate::db::exam::published_exam(&db).await.get_id().clone(); |
| 693 | |
| 694 | |
| 695 | let subject = crate::db::subject::create( |
| 696 | &db, |
| 697 | &crate::db::course::a_test_course(&db).await, |
| 698 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 699 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 700 | ) |
| 701 | .await |
| 702 | .unwrap(); |
| 703 | async fn instantiate( |
| 704 | exam: &ExamId, |
| 705 | subject: &SubjectId, |
| 706 | source: &BankQuestion, |
| 707 | db: &Database, |
| 708 | ) { |
| 709 | crate::db::exam_question::create_from_bank( |
| 710 | db, |
| 711 | exam, |
| 712 | *subject, |
| 713 | source.get_text().clone(), |
| 714 | source.get_points(), |
| 715 | source.spec(), |
| 716 | source.get_id().clone(), |
| 717 | ) |
| 718 | .await |
| 719 | .unwrap(); |
| 720 | } |
| 721 | |
| 722 | instantiate(&exam, subject.get_id(), &used_twice, &db).await; |
| 723 | instantiate(&other_exam, subject.get_id(), &used_twice, &db).await; |
| 724 | instantiate(&exam, subject.get_id(), &used_once, &db).await; |
| 725 | |
| 726 | crate::db::exam_question::create( |
| 727 | &db, |
| 728 | &exam, |
| 729 | *subject.get_id(), |
| 730 | QuestionText::try_new("mine").unwrap(), |
| 731 | QuestionPoints::try_new(1).unwrap(), |
| 732 | spec(), |
| 733 | ) |
| 734 | .await |
| 735 | .unwrap(); |
| 736 | |
| 737 | let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()]; |
| 738 | let counts = usage_counts(&db, &ids).await.unwrap(); |
| 739 | assert_eq!(counts.get(&used_twice.get_id().key()).copied(), Some(2)); |
| 740 | assert_eq!(counts.get(&used_once.get_id().key()).copied(), Some(1)); |
| 741 | assert_eq!( |
| 742 | counts.get(&unused.get_id().key()), |
| 743 | None, |
| 744 | "unused stays absent" |
| 745 | ); |
| 746 | assert_eq!(counts.len(), 2); |
| 747 | |
| 748 | |
| 749 | let narrow = usage_counts(&db, &[used_once.get_id()]).await.unwrap(); |
| 750 | assert_eq!(narrow.len(), 1); |
| 751 | assert_eq!(narrow.get(&used_once.get_id().key()).copied(), Some(1)); |
| 752 | |
| 753 | assert!(usage_counts(&db, &[]).await.unwrap().is_empty()); |
| 754 | } |
| 755 | |
| 756 | #[tokio::test] |
| 757 | async fn list_is_school_wide() { |
| 758 | let (db, _leases) = crate::database::init_test_db().await; |
| 759 | for _ in 0..2 { |
| 760 | create( |
| 761 | &db, |
| 762 | a_person(&db, "owner").await, |
| 763 | a_subject(&db).await, |
| 764 | QuestionText::try_new("q").unwrap(), |
| 765 | QuestionPoints::try_new(1).unwrap(), |
| 766 | spec(), |
| 767 | ) |
| 768 | .await |
| 769 | .unwrap(); |
| 770 | } |
| 771 | |
| 772 | let (items, total) = list(&db, None, None, None, None, None, None, 0) |
| 773 | .await |
| 774 | .unwrap(); |
| 775 | assert_eq!(items.len(), 2); |
| 776 | assert_eq!(total, 2); |
| 777 | } |
| 778 | |
| 779 | |
| 780 | #[tokio::test] |
| 781 | async fn list_pages_newest_first_and_filters_text() { |
| 782 | let (db, _leases) = crate::database::init_test_db().await; |
| 783 | let owner = a_person(&db, "owner").await; |
| 784 | for i in 0..5 { |
| 785 | create( |
| 786 | &db, |
| 787 | owner, |
| 788 | a_subject(&db).await, |
| 789 | QuestionText::try_new(&format!("question {i}")).unwrap(), |
| 790 | QuestionPoints::try_new(1).unwrap(), |
| 791 | spec(), |
| 792 | ) |
| 793 | .await |
| 794 | .unwrap(); |
| 795 | } |
| 796 | let (page, total) = list(&db, None, None, None, None, None, Some(2), 0) |
| 797 | .await |
| 798 | .unwrap(); |
| 799 | assert_eq!(total, 5); |
| 800 | assert_eq!(page.len(), 2); |
| 801 | |
| 802 | assert_eq!(page[0].get_text().as_str(), "question 4"); |
| 803 | |
| 804 | let (tail, _) = list(&db, None, None, None, None, None, Some(2), 4) |
| 805 | .await |
| 806 | .unwrap(); |
| 807 | assert_eq!(tail[0].get_text().as_str(), "question 0"); |
| 808 | |
| 809 | let (hits, total) = list(&db, None, None, None, None, Some("QUESTION 3"), None, 0) |
| 810 | .await |
| 811 | .unwrap(); |
| 812 | assert_eq!((hits.len(), total), (1, 1)); |
| 813 | |
| 814 | let (none, total) = list( |
| 815 | &db, |
| 816 | None, |
| 817 | Some(&a_person(&db, "empty").await), |
| 818 | None, |
| 819 | None, |
| 820 | None, |
| 821 | None, |
| 822 | 0, |
| 823 | ) |
| 824 | .await |
| 825 | .unwrap(); |
| 826 | assert!(none.is_empty()); |
| 827 | assert_eq!(total, 0); |
| 828 | } |
| 829 | |
| 830 | |
| 831 | #[tokio::test] |
| 832 | async fn list_text_filter_folds_turkish_casing() { |
| 833 | let (db, _leases) = crate::database::init_test_db().await; |
| 834 | create( |
| 835 | &db, |
| 836 | a_person(&db, "owner").await, |
| 837 | a_subject(&db).await, |
| 838 | QuestionText::try_new("İSTANBUL kaç ilçeye ayrılır?").unwrap(), |
| 839 | QuestionPoints::try_new(1).unwrap(), |
| 840 | spec(), |
| 841 | ) |
| 842 | .await |
| 843 | .unwrap(); |
| 844 | for needle in [ |
| 845 | "istanbul", |
| 846 | "İSTANBUL", |
| 847 | "İstanbul", |
| 848 | "ıstanbul", |
| 849 | "ilçe", |
| 850 | "ILCE", |
| 851 | ] { |
| 852 | let (hits, total) = list(&db, None, None, None, None, Some(needle), None, 0) |
| 853 | .await |
| 854 | .unwrap(); |
| 855 | assert_eq!((hits.len(), total), (1, 1), "needle {needle} missed"); |
| 856 | } |
| 857 | let (miss, total) = list(&db, None, None, None, None, Some("ankara"), None, 0) |
| 858 | .await |
| 859 | .unwrap(); |
| 860 | assert!(miss.is_empty()); |
| 861 | assert_eq!(total, 0); |
| 862 | } |
| 863 | } |