| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | use sqlx::PgConnection; |
| 7 | |
| 8 | use crate::database::{Database, tx_with_retry}; |
| 9 | use crate::domain::exam::ExamId; |
| 10 | use crate::domain::exam_answer::{AnswerText, ExamAnswer}; |
| 11 | use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId}; |
| 12 | use crate::domain::timestamp::Timestamp; |
| 13 | use crate::domain::user::UserId; |
| 14 | use crate::error::{AppError, ValidationError}; |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | pub async fn save( |
| 24 | db: &Database, |
| 25 | question: &ExamQuestion, |
| 26 | user: &UserId, |
| 27 | seq: i64, |
| 28 | selected: Option<String>, |
| 29 | text: Option<String>, |
| 30 | ) -> Result<ExamAnswer, AppError> { |
| 31 | let invalid = |field, reason| AppError::Validation(ValidationError::Invalid { field, reason }); |
| 32 | let (selected, text) = match question.get_kind().as_str() { |
| 33 | "choice" => { |
| 34 | if text.is_some() { |
| 35 | return Err(invalid( |
| 36 | "text", |
| 37 | "a choice question takes selected, not text", |
| 38 | )); |
| 39 | } |
| 40 | let Some(selected) = selected else { |
| 41 | return Err(invalid("selected", "required for a choice question")); |
| 42 | }; |
| 43 | |
| 44 | |
| 45 | let picked = question |
| 46 | .get_choices() |
| 47 | .unwrap_or_default() |
| 48 | .iter() |
| 49 | .find(|choice| choice.get_id().as_str() == selected) |
| 50 | .ok_or_else(|| invalid("selected", "must name one of the question's choices"))?; |
| 51 | (Some(picked.get_id().clone()), None) |
| 52 | } |
| 53 | _ => { |
| 54 | if selected.is_some() { |
| 55 | return Err(invalid( |
| 56 | "selected", |
| 57 | "a text question takes text, not selected", |
| 58 | )); |
| 59 | } |
| 60 | let Some(text) = text else { |
| 61 | return Err(invalid("text", "required for a text question")); |
| 62 | }; |
| 63 | (None, Some(AnswerText::try_new(&text)?)) |
| 64 | } |
| 65 | }; |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | let question = question.clone(); |
| 79 | let user = *user; |
| 80 | tx_with_retry(db, false, async move |conn| { |
| 81 | save_in(conn, &question, &user, seq, selected.clone(), text.clone()).await |
| 82 | }) |
| 83 | .await |
| 84 | } |
| 85 | |
| 86 | |
| 87 | |
| 88 | pub(crate) async fn save_in( |
| 89 | conn: &mut PgConnection, |
| 90 | question: &ExamQuestion, |
| 91 | user: &UserId, |
| 92 | seq: i64, |
| 93 | selected: Option<ChoiceId>, |
| 94 | text: Option<AnswerText>, |
| 95 | ) -> Result<ExamAnswer, AppError> { |
| 96 | let touched = sqlx::query!( |
| 97 | r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, |
| 98 | question.get_exam().uuid(), |
| 99 | ) |
| 100 | .fetch_optional(&mut *conn) |
| 101 | .await?; |
| 102 | if touched.is_none() { |
| 103 | return Err(AppError::NotFound); |
| 104 | } |
| 105 | let now = Timestamp::now(); |
| 106 | sqlx::query_as!( |
| 107 | ExamAnswer, |
| 108 | r#"INSERT INTO exam_answer (exam, question, app_user, selected, text, updated_at, seq) |
| 109 | VALUES ($1, $2, $3, $4, $5, $6, $7) |
| 110 | ON CONFLICT (question, app_user, seq) DO UPDATE |
| 111 | SET selected = EXCLUDED.selected, text = EXCLUDED.text, |
| 112 | updated_at = EXCLUDED.updated_at |
| 113 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 114 | app_user AS "user: UserId", seq, |
| 115 | selected AS "selected: ChoiceId", |
| 116 | text AS "text: AnswerText", |
| 117 | updated_at AS "updated_at: Timestamp""#, |
| 118 | question.get_exam().uuid(), |
| 119 | question.get_id().uuid(), |
| 120 | user.uuid(), |
| 121 | selected.as_ref().map(ChoiceId::as_str), |
| 122 | text.as_ref().map(AnswerText::as_str), |
| 123 | now.as_millis(), |
| 124 | seq, |
| 125 | ) |
| 126 | .fetch_one(&mut *conn) |
| 127 | .await |
| 128 | .map_err(AppError::from) |
| 129 | } |
| 130 | |
| 131 | |
| 132 | pub async fn read( |
| 133 | db: &Database, |
| 134 | question: &ExamQuestionId, |
| 135 | user: &UserId, |
| 136 | seq: i64, |
| 137 | ) -> Result<Option<ExamAnswer>, AppError> { |
| 138 | Ok(sqlx::query_as!( |
| 139 | ExamAnswer, |
| 140 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 141 | app_user AS "user: UserId", seq, |
| 142 | selected AS "selected: ChoiceId", |
| 143 | text AS "text: AnswerText", |
| 144 | updated_at AS "updated_at: Timestamp" |
| 145 | FROM exam_answer |
| 146 | WHERE question = $1 AND app_user = $2 AND seq = $3"#, |
| 147 | question.uuid(), |
| 148 | user.uuid(), |
| 149 | seq, |
| 150 | ) |
| 151 | .fetch_optional(db) |
| 152 | .await?) |
| 153 | } |
| 154 | |
| 155 | |
| 156 | pub async fn delete( |
| 157 | db: &Database, |
| 158 | question: &ExamQuestionId, |
| 159 | user: &UserId, |
| 160 | seq: i64, |
| 161 | ) -> Result<(), AppError> { |
| 162 | sqlx::query!( |
| 163 | r#"DELETE FROM exam_answer WHERE question = $1 AND app_user = $2 AND seq = $3"#, |
| 164 | question.uuid(), |
| 165 | user.uuid(), |
| 166 | seq, |
| 167 | ) |
| 168 | .execute(db) |
| 169 | .await?; |
| 170 | Ok(()) |
| 171 | } |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | pub async fn list_for_exam_user( |
| 177 | db: &Database, |
| 178 | exam: &ExamId, |
| 179 | user: &UserId, |
| 180 | seq: i64, |
| 181 | ) -> Result<Vec<ExamAnswer>, AppError> { |
| 182 | Ok(sqlx::query_as!( |
| 183 | ExamAnswer, |
| 184 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 185 | app_user AS "user: UserId", seq, |
| 186 | selected AS "selected: ChoiceId", |
| 187 | text AS "text: AnswerText", |
| 188 | updated_at AS "updated_at: Timestamp" |
| 189 | FROM exam_answer |
| 190 | WHERE exam = $1 AND app_user = $2 AND seq = $3 |
| 191 | ORDER BY question ASC"#, |
| 192 | exam.uuid(), |
| 193 | user.uuid(), |
| 194 | seq, |
| 195 | ) |
| 196 | .fetch_all(db) |
| 197 | .await?) |
| 198 | } |
| 199 | |
| 200 | |
| 201 | |
| 202 | pub async fn list_seqs_for_user( |
| 203 | db: &Database, |
| 204 | exam: &ExamId, |
| 205 | user: &UserId, |
| 206 | ) -> Result<Vec<i64>, AppError> { |
| 207 | let rows = sqlx::query!( |
| 208 | r#"SELECT DISTINCT seq FROM exam_answer |
| 209 | WHERE exam = $1 AND app_user = $2 ORDER BY seq ASC"#, |
| 210 | exam.uuid(), |
| 211 | user.uuid(), |
| 212 | ) |
| 213 | .fetch_all(db) |
| 214 | .await?; |
| 215 | Ok(rows.into_iter().map(|row| row.seq).collect()) |
| 216 | } |
| 217 | |
| 218 | |
| 219 | pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamAnswer>, AppError> { |
| 220 | Ok(sqlx::query_as!( |
| 221 | ExamAnswer, |
| 222 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 223 | app_user AS "user: UserId", seq, |
| 224 | selected AS "selected: ChoiceId", |
| 225 | text AS "text: AnswerText", |
| 226 | updated_at AS "updated_at: Timestamp" |
| 227 | FROM exam_answer WHERE exam = $1 ORDER BY question ASC"#, |
| 228 | exam.uuid(), |
| 229 | ) |
| 230 | .fetch_all(db) |
| 231 | .await?) |
| 232 | } |
| 233 | |
| 234 | |
| 235 | |
| 236 | pub async fn delete_for_exam_user( |
| 237 | db: &Database, |
| 238 | exam: &ExamId, |
| 239 | user: &UserId, |
| 240 | ) -> Result<(), AppError> { |
| 241 | sqlx::query!( |
| 242 | r#"DELETE FROM exam_answer WHERE exam = $1 AND app_user = $2"#, |
| 243 | exam.uuid(), |
| 244 | user.uuid(), |
| 245 | ) |
| 246 | .execute(db) |
| 247 | .await?; |
| 248 | Ok(()) |
| 249 | } |
| 250 | |
| 251 | #[cfg(test)] |
| 252 | mod tests { |
| 253 | use super::*; |
| 254 | use crate::domain::exam::ExamId; |
| 255 | use crate::domain::exam_question::{ChoiceId, ChoiceInput, QuestionKind, QuestionSpec}; |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | fn choice_question(exam: &ExamId, points: i64, correct: usize) -> ExamQuestion { |
| 261 | let labels = ["a", "b", "c"]; |
| 262 | let spec = QuestionSpec::try_new( |
| 263 | QuestionKind::try_new("choice").unwrap(), |
| 264 | Some( |
| 265 | labels |
| 266 | .iter() |
| 267 | .map(|l| ChoiceInput { |
| 268 | id: Some((*l).into()), |
| 269 | text: (*l).into(), |
| 270 | }) |
| 271 | .collect(), |
| 272 | ), |
| 273 | Some(labels[correct].into()), |
| 274 | &[], |
| 275 | ) |
| 276 | .unwrap(); |
| 277 | ExamQuestion::test_new(exam, "pick one", points, spec) |
| 278 | } |
| 279 | |
| 280 | |
| 281 | fn choice_id(question: &ExamQuestion, index: usize) -> ChoiceId { |
| 282 | question.get_choices().unwrap()[index].get_id().clone() |
| 283 | } |
| 284 | |
| 285 | fn student() -> UserId { |
| 286 | UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa") |
| 287 | } |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | #[tokio::test] |
| 297 | async fn a_save_puts_the_exams_mark_counter_back_exactly() { |
| 298 | use crate::domain::exam::{ |
| 299 | ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, |
| 300 | }; |
| 301 | let (db, _leases) = crate::database::init_test_db().await; |
| 302 | |
| 303 | |
| 304 | sqlx::query( |
| 305 | "INSERT INTO app_user (id, username, created_at) \ |
| 306 | VALUES ($1, 'aaaa-fixture', 0)", |
| 307 | ) |
| 308 | .bind(student().uuid()) |
| 309 | .execute(&db) |
| 310 | .await |
| 311 | .unwrap(); |
| 312 | let kinds = crate::domain::settings::Settings::defaults() |
| 313 | .get_exam_kinds() |
| 314 | .to_vec(); |
| 315 | |
| 316 | |
| 317 | let (instance, _course) = crate::db::course::a_test_instance(&db).await; |
| 318 | let term = crate::db::term::a_test_term(&db).await; |
| 319 | let exam = crate::db::exam::create( |
| 320 | &db, |
| 321 | &student(), |
| 322 | &instance, |
| 323 | &term, |
| 324 | ExamTitle::try_new("quiz").unwrap(), |
| 325 | ExamDescription::try_new("").unwrap(), |
| 326 | ExamKind::try_new("yazili", &kinds).unwrap(), |
| 327 | ExamSchedule::try_new(None, None, None, None).unwrap(), |
| 328 | ExamAttemptLimit::try_new(1).unwrap(), |
| 329 | true, |
| 330 | false, |
| 331 | false, |
| 332 | ) |
| 333 | .await |
| 334 | .unwrap(); |
| 335 | let stored = async |db: &Database| -> Option<i64> { |
| 336 | sqlx::query_scalar::<_, Option<i64>>("SELECT result_count FROM exam WHERE id = $1") |
| 337 | .bind(exam.get_id().uuid()) |
| 338 | .fetch_optional(db) |
| 339 | .await |
| 340 | .unwrap() |
| 341 | .flatten() |
| 342 | }; |
| 343 | |
| 344 | |
| 345 | let spec = QuestionSpec::try_new( |
| 346 | QuestionKind::try_new("choice").unwrap(), |
| 347 | Some( |
| 348 | ["a", "b", "c"] |
| 349 | .iter() |
| 350 | .map(|l| ChoiceInput { |
| 351 | id: Some((*l).into()), |
| 352 | text: (*l).into(), |
| 353 | }) |
| 354 | .collect(), |
| 355 | ), |
| 356 | Some("b".into()), |
| 357 | &[], |
| 358 | ) |
| 359 | .unwrap(); |
| 360 | let subject = crate::db::subject::create( |
| 361 | &db, |
| 362 | &crate::db::course::a_test_course(&db).await, |
| 363 | crate::domain::subject::SubjectName::try_new("sorular").unwrap(), |
| 364 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 365 | ) |
| 366 | .await |
| 367 | .unwrap(); |
| 368 | let question = crate::db::exam_question::create( |
| 369 | &db, |
| 370 | exam.get_id(), |
| 371 | *subject.get_id(), |
| 372 | crate::domain::exam_question::QuestionText::try_new("pick one").unwrap(), |
| 373 | crate::domain::exam_question::QuestionPoints::try_new(10).unwrap(), |
| 374 | spec, |
| 375 | ) |
| 376 | .await |
| 377 | .unwrap(); |
| 378 | let pick = choice_id(&question, 1).as_str().to_string(); |
| 379 | |
| 380 | |
| 381 | |
| 382 | assert_eq!(stored(&db).await, Some(0), "the fixture starts at zero"); |
| 383 | save(&db, &question, &student(), 1, Some(pick.clone()), None) |
| 384 | .await |
| 385 | .unwrap(); |
| 386 | assert_eq!( |
| 387 | stored(&db).await, |
| 388 | Some(0), |
| 389 | "the touch left the counter alone" |
| 390 | ); |
| 391 | |
| 392 | |
| 393 | sqlx::query("UPDATE exam SET result_count = 7 WHERE id = $1") |
| 394 | .bind(exam.get_id().uuid()) |
| 395 | .execute(&db) |
| 396 | .await |
| 397 | .unwrap(); |
| 398 | save(&db, &question, &student(), 2, Some(pick), None) |
| 399 | .await |
| 400 | .unwrap(); |
| 401 | assert_eq!(stored(&db).await, Some(7), "the touch moved a real count"); |
| 402 | |
| 403 | |
| 404 | let orphan = choice_question( |
| 405 | &ExamId::from_key("019732e3-7b00-7000-8000-00000000e0a0"), |
| 406 | 10, |
| 407 | 0, |
| 408 | ); |
| 409 | let pick = choice_id(&orphan, 0).as_str().to_string(); |
| 410 | let refused = save(&db, &orphan, &student(), 1, Some(pick), None).await; |
| 411 | assert!( |
| 412 | matches!(refused, Err(AppError::NotFound)), |
| 413 | "a save into a missing exam must 404, got {refused:?}" |
| 414 | ); |
| 415 | } |
| 416 | } |