1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
use chrono::Duration;

use crate::{courses::Course, prelude::*};
use headless_lms_utils::document_schema_processor::GutenbergBlock;

#[derive(Debug, Serialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct Exam {
    pub id: Uuid,
    pub name: String,
    pub instructions: serde_json::Value,
    // TODO: page_id is not in the exams table, prevents from using select * with query_as!
    pub page_id: Uuid,
    pub courses: Vec<Course>,
    pub starts_at: Option<DateTime<Utc>>,
    pub ends_at: Option<DateTime<Utc>>,
    pub time_minutes: i32,
    pub minimum_points_treshold: i32,
    pub language: String,
}

impl Exam {
    /// Whether or not the exam has already started at the specified timestamp. If no start date for
    /// exam is defined, returns the provided default instead.
    pub fn started_at_or(&self, timestamp: DateTime<Utc>, default: bool) -> bool {
        match self.starts_at {
            Some(starts_at) => starts_at <= timestamp,
            None => default,
        }
    }

    /// Whether or not the exam has already ended at the specified timestamp. If no end date for exam
    /// is defined, returns the provided default instead.
    pub fn ended_at_or(&self, timestamp: DateTime<Utc>, default: bool) -> bool {
        match self.ends_at {
            Some(ends_at) => ends_at < timestamp,
            None => default,
        }
    }
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct OrgExam {
    pub id: Uuid,
    pub name: String,
    pub instructions: serde_json::Value,
    pub starts_at: Option<DateTime<Utc>>,
    pub ends_at: Option<DateTime<Utc>>,
    pub time_minutes: i32,
    pub organization_id: Uuid,
    pub minimum_points_treshold: i32,
}

pub async fn get(conn: &mut PgConnection, id: Uuid) -> ModelResult<Exam> {
    let exam = sqlx::query!(
        "
SELECT exams.id,
  exams.name,
  exams.instructions,
  pages.id AS page_id,
  exams.starts_at,
  exams.ends_at,
  exams.time_minutes,
  exams.minimum_points_treshold,
  exams.language
FROM exams
  JOIN pages ON pages.exam_id = exams.id
WHERE exams.id = $1
",
        id
    )
    .fetch_one(&mut *conn)
    .await?;

    let courses = sqlx::query_as!(
        Course,
        "
SELECT id,
  slug,
  courses.created_at,
  courses.updated_at,
  courses.deleted_at,
  name,
  description,
  organization_id,
  language_code,
  copied_from,
  content_search_language::text,
  course_language_group_id,
  is_draft,
  is_test_mode,
  is_unlisted,
  base_module_completion_requires_n_submodule_completions
FROM courses
  JOIN course_exams ON courses.id = course_exams.course_id
WHERE course_exams.exam_id = $1
  AND courses.deleted_at IS NULL
  AND course_exams.deleted_at IS NULL
",
        id
    )
    .fetch_all(&mut *conn)
    .await?;

    Ok(Exam {
        id: exam.id,
        name: exam.name,
        instructions: exam.instructions,
        page_id: exam.page_id,
        starts_at: exam.starts_at,
        ends_at: exam.ends_at,
        time_minutes: exam.time_minutes,
        courses,
        minimum_points_treshold: exam.minimum_points_treshold,
        language: exam.language.unwrap_or("en-US".to_string()),
    })
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct CourseExam {
    pub id: Uuid,
    pub course_id: Uuid,
    pub course_name: String,
    pub name: String,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct NewExam {
    pub name: String,
    pub starts_at: Option<DateTime<Utc>>,
    pub ends_at: Option<DateTime<Utc>>,
    pub time_minutes: i32,
    pub organization_id: Uuid,
    pub minimum_points_treshold: i32,
}

#[derive(Debug, Serialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct ExamInstructions {
    pub id: Uuid,
    pub instructions: serde_json::Value,
}

#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct ExamInstructionsUpdate {
    pub instructions: serde_json::Value,
}

pub async fn insert(
    conn: &mut PgConnection,
    pkey_policy: PKeyPolicy<Uuid>,
    exam: &NewExam,
) -> ModelResult<Uuid> {
    let res = sqlx::query!(
        "
INSERT INTO exams (
    id,
    name,
    instructions,
    starts_at,
    ends_at,
    time_minutes,
    organization_id,
    minimum_points_treshold
  )
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id
        ",
        pkey_policy.into_uuid(),
        exam.name,
        serde_json::Value::Array(vec![]),
        exam.starts_at,
        exam.ends_at,
        exam.time_minutes,
        exam.organization_id,
        exam.minimum_points_treshold,
    )
    .fetch_one(conn)
    .await?;

    Ok(res.id)
}

pub async fn edit(conn: &mut PgConnection, id: Uuid, new_exam: NewExam) -> ModelResult<()> {
    sqlx::query!(
        "
UPDATE exams
SET name = COALESCE($2, name),
  starts_at = $3,
  ends_at = $4,
  time_minutes = $5,
  minimum_points_treshold = $6
WHERE id = $1
",
        id,
        new_exam.name,
        new_exam.starts_at,
        new_exam.ends_at,
        new_exam.time_minutes,
        new_exam.minimum_points_treshold,
    )
    .execute(conn)
    .await?;
    Ok(())
}

pub async fn get_exams_for_organization(
    conn: &mut PgConnection,
    organization: Uuid,
) -> ModelResult<Vec<OrgExam>> {
    let res = sqlx::query_as!(
        OrgExam,
        "
SELECT id,
  name,
  instructions,
  starts_at,
  ends_at,
  time_minutes,
  organization_id,
  minimum_points_treshold
FROM exams
WHERE exams.organization_id = $1
  AND exams.deleted_at IS NULL
",
        organization
    )
    .fetch_all(conn)
    .await?;
    Ok(res)
}

pub async fn get_organization_exam_with_exam_id(
    conn: &mut PgConnection,
    exam_id: Uuid,
) -> ModelResult<OrgExam> {
    let res = sqlx::query_as!(
        OrgExam,
        "
SELECT id,
  name,
  instructions,
  starts_at,
  ends_at,
  time_minutes,
  organization_id,
  minimum_points_treshold
FROM exams
WHERE exams.id = $1
  AND exams.deleted_at IS NULL
",
        exam_id
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

pub async fn get_course_exams_for_organization(
    conn: &mut PgConnection,
    organization: Uuid,
) -> ModelResult<Vec<CourseExam>> {
    let res = sqlx::query_as!(
        CourseExam,
        "
SELECT exams.id,
  courses.id as course_id,
  courses.name as course_name,
  exams.name
FROM exams
  JOIN course_exams ON course_exams.exam_id = exams.id
  JOIN courses ON courses.id = course_exams.course_id
WHERE exams.organization_id = $1
  AND exams.deleted_at IS NULL
  AND courses.deleted_at IS NULL
",
        organization
    )
    .fetch_all(conn)
    .await?;
    Ok(res)
}

pub async fn get_exams_for_course(
    conn: &mut PgConnection,
    course: Uuid,
) -> ModelResult<Vec<CourseExam>> {
    let res = sqlx::query_as!(
        CourseExam,
        "
SELECT exams.id,
  courses.id as course_id,
  courses.name as course_name,
  exams.name
FROM exams
  JOIN course_exams ON course_id = $1
  JOIN courses ON courses.id = $1
  AND exams.deleted_at IS NULL
  AND courses.deleted_at IS NULL
",
        course
    )
    .fetch_all(conn)
    .await?;
    Ok(res)
}

pub async fn enroll(
    conn: &mut PgConnection,
    exam_id: Uuid,
    user_id: Uuid,
    is_teacher_testing: bool,
) -> ModelResult<()> {
    sqlx::query!(
        "
INSERT INTO exam_enrollments (exam_id, user_id, is_teacher_testing)
VALUES ($1, $2, $3)
",
        exam_id,
        user_id,
        is_teacher_testing
    )
    .execute(conn)
    .await?;
    Ok(())
}

/// Checks whether a submission can be made for the given exam.
pub async fn verify_exam_submission_can_be_made(
    conn: &mut PgConnection,
    exam_id: Uuid,
    user_id: Uuid,
) -> ModelResult<bool> {
    let exam = get(conn, exam_id).await?;
    let enrollment = get_enrollment(conn, exam_id, user_id)
        .await?
        .ok_or_else(|| {
            ModelError::new(
                ModelErrorType::PreconditionFailed,
                "User has no enrollment for the exam".to_string(),
                None,
            )
        })?;
    let student_has_time =
        Utc::now() <= enrollment.started_at + Duration::minutes(exam.time_minutes.into());
    let exam_is_ongoing = exam.ends_at.map(|ea| Utc::now() < ea).unwrap_or_default();
    Ok(student_has_time && exam_is_ongoing)
}

#[derive(Debug, Serialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct ExamEnrollment {
    pub user_id: Uuid,
    pub exam_id: Uuid,
    pub started_at: DateTime<Utc>,
    pub is_teacher_testing: bool,
    pub show_exercise_answers: Option<bool>,
}

pub async fn get_enrollment(
    conn: &mut PgConnection,
    exam_id: Uuid,
    user_id: Uuid,
) -> ModelResult<Option<ExamEnrollment>> {
    let res = sqlx::query_as!(
        ExamEnrollment,
        "
SELECT user_id,
  exam_id,
  started_at,
  is_teacher_testing,
  show_exercise_answers
FROM exam_enrollments
WHERE exam_id = $1
  AND user_id = $2
  AND deleted_at IS NULL
",
        exam_id,
        user_id
    )
    .fetch_optional(conn)
    .await?;
    Ok(res)
}

pub async fn update_exam_start_time(
    conn: &mut PgConnection,
    exam_id: Uuid,
    user_id: Uuid,
    started_at: DateTime<Utc>,
) -> ModelResult<()> {
    sqlx::query!(
        "
UPDATE exam_enrollments
SET started_at = $3
WHERE exam_id = $1
  AND user_id = $2
  AND deleted_at IS NULL
",
        exam_id,
        user_id,
        started_at
    )
    .execute(conn)
    .await?;
    Ok(())
}

pub async fn update_show_exercise_answers(
    conn: &mut PgConnection,
    exam_id: Uuid,
    user_id: Uuid,
    show_exercise_answers: bool,
) -> ModelResult<()> {
    sqlx::query!(
        "
UPDATE exam_enrollments
SET show_exercise_answers = $3
WHERE exam_id = $1
  AND user_id = $2
  AND deleted_at IS NULL
",
        exam_id,
        user_id,
        show_exercise_answers
    )
    .execute(conn)
    .await?;
    Ok(())
}

pub async fn get_organization_id(conn: &mut PgConnection, exam_id: Uuid) -> ModelResult<Uuid> {
    let organization_id = sqlx::query!(
        "
SELECT organization_id
FROM exams
WHERE id = $1
",
        exam_id
    )
    .fetch_one(conn)
    .await?
    .organization_id;
    Ok(organization_id)
}

pub async fn get_exam_instructions_data(
    conn: &mut PgConnection,
    exam_id: Uuid,
) -> ModelResult<ExamInstructions> {
    let exam_instructions_data = sqlx::query_as!(
        ExamInstructions,
        "
SELECT id, instructions
FROM exams
WHERE id = $1;
",
        exam_id
    )
    .fetch_one(conn)
    .await?;
    Ok(exam_instructions_data)
}

pub async fn update_exam_instructions(
    conn: &mut PgConnection,
    exam_id: Uuid,
    instructions_update: ExamInstructionsUpdate,
) -> ModelResult<ExamInstructions> {
    let parsed_content: Vec<GutenbergBlock> =
        serde_json::from_value(instructions_update.instructions)?;
    let updated_data = sqlx::query_as!(
        ExamInstructions,
        "
    UPDATE exams
    SET instructions = $1
    WHERE id = $2
    RETURNING id,
        instructions
    ",
        serde_json::to_value(parsed_content)?,
        exam_id
    )
    .fetch_one(conn)
    .await?;

    Ok(updated_data)
}