headless_lms_server/controllers/course_material/
exams.rs

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
493
use chrono::{DateTime, Duration, Utc};
use headless_lms_models::{
    exercises::Exercise, user_exercise_states::CourseInstanceOrExamId, ModelError, ModelErrorType,
};
use models::{
    exams::{self, ExamEnrollment},
    exercises,
    pages::{self, Page},
    teacher_grading_decisions::{self, TeacherGradingDecision},
    user_exercise_states,
};

use crate::prelude::*;

/**
GET /api/v0/course-material/exams/:id/enrollment
*/
#[instrument(skip(pool))]
pub async fn enrollment(
    pool: web::Data<PgPool>,
    exam_id: web::Path<Uuid>,
    user: AuthUser,
) -> ControllerResult<web::Json<Option<ExamEnrollment>>> {
    let mut conn = pool.acquire().await?;
    let enrollment = exams::get_enrollment(&mut conn, *exam_id, user.id).await?;
    let token = authorize(&mut conn, Act::Teach, Some(user.id), Res::Exam(*exam_id)).await?;
    token.authorized_ok(web::Json(enrollment))
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct IsTeacherTesting {
    pub is_teacher_testing: bool,
}
/**
POST /api/v0/course-material/exams/:id/enroll
*/
#[instrument(skip(pool))]
pub async fn enroll(
    pool: web::Data<PgPool>,
    exam_id: web::Path<Uuid>,
    user: AuthUser,
    payload: web::Json<IsTeacherTesting>,
) -> ControllerResult<web::Json<()>> {
    let mut conn = pool.acquire().await?;
    let exam = exams::get(&mut conn, *exam_id).await?;

    // enroll if teacher is testing regardless of exams starting time
    if payload.is_teacher_testing {
        exams::enroll(&mut conn, *exam_id, user.id, payload.is_teacher_testing).await?;
        let token = authorize(&mut conn, Act::Edit, Some(user.id), Res::Exam(*exam_id)).await?;
        return token.authorized_ok(web::Json(()));
    }

    // check that the exam is not over
    let now = Utc::now();
    if exam.ended_at_or(now, false) {
        return Err(ControllerError::new(
            ControllerErrorType::Forbidden,
            "Exam is over".to_string(),
            None,
        ));
    }

    if exam.started_at_or(now, false) {
        // This check should probably be handled in the authorize function but I'm not sure of
        // the proper action type.
        let can_start =
            models::library::progressing::user_can_take_exam(&mut conn, *exam_id, user.id).await?;
        if !can_start {
            return Err(ControllerError::new(
                ControllerErrorType::Forbidden,
                "User is not allowed to enroll to the exam.".to_string(),
                None,
            ));
        }
        exams::enroll(&mut conn, *exam_id, user.id, payload.is_teacher_testing).await?;
        let token = skip_authorize();
        return token.authorized_ok(web::Json(()));
    }

    // no start time defined or it's still upcoming
    Err(ControllerError::new(
        ControllerErrorType::Forbidden,
        "Exam has not started yet".to_string(),
        None,
    ))
}

#[derive(Debug, Serialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct ExamData {
    pub id: Uuid,
    pub name: String,
    pub instructions: serde_json::Value,
    pub starts_at: DateTime<Utc>,
    pub ends_at: DateTime<Utc>,
    pub ended: bool,
    pub time_minutes: i32,
    pub enrollment_data: ExamEnrollmentData,
    pub language: String,
}

#[derive(Debug, Serialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
#[serde(tag = "tag")]
pub enum ExamEnrollmentData {
    /// The student has enrolled to the exam and started it.
    EnrolledAndStarted {
        page_id: Uuid,
        page: Box<Page>,
        enrollment: ExamEnrollment,
    },
    /// The student has not enrolled to the exam yet. However, the the exam is open.
    NotEnrolled { can_enroll: bool },
    /// The exam's start time is in the future, no one can enroll yet.
    NotYetStarted,
    /// The exam is still open but the student has run out of time.
    StudentTimeUp,
    // Exam is still open but student can view published grading results
    StudentCanViewGrading {
        gradings: Vec<(TeacherGradingDecision, Exercise)>,
        enrollment: ExamEnrollment,
    },
}

/**
GET /api/v0/course-material/exams/:id
*/
#[instrument(skip(pool))]
pub async fn fetch_exam_for_user(
    pool: web::Data<PgPool>,
    exam_id: web::Path<Uuid>,
    user: AuthUser,
) -> ControllerResult<web::Json<ExamData>> {
    let mut conn = pool.acquire().await?;
    let exam = exams::get(&mut conn, *exam_id).await?;

    let starts_at = if let Some(starts_at) = exam.starts_at {
        starts_at
    } else {
        return Err(ControllerError::new(
            ControllerErrorType::Forbidden,
            "Cannot fetch exam that has no start time".to_string(),
            None,
        ));
    };
    let ends_at = if let Some(ends_at) = exam.ends_at {
        ends_at
    } else {
        return Err(ControllerError::new(
            ControllerErrorType::Forbidden,
            "Cannot fetch exam that has no end time".to_string(),
            None,
        ));
    };

    let ended = ends_at < Utc::now();

    if starts_at > Utc::now() {
        // exam has not started yet
        let token = authorize(&mut conn, Act::View, Some(user.id), Res::Exam(*exam_id)).await?;
        return token.authorized_ok(web::Json(ExamData {
            id: exam.id,
            name: exam.name,
            instructions: exam.instructions,
            starts_at,
            ends_at,
            ended,
            time_minutes: exam.time_minutes,
            enrollment_data: ExamEnrollmentData::NotYetStarted,
            language: exam.language,
        }));
    }

    let enrollment = if let Some(enrollment) =
        exams::get_enrollment(&mut conn, *exam_id, user.id).await?
    {
        if exam.grade_manually {
            // Get the grading results, if the student has any
            let teachers_grading_decisions_list =
                teacher_grading_decisions::get_all_latest_grading_decisions_by_user_id_and_exam_id(
                    &mut conn, user.id, *exam_id,
                )
                .await?;
            let teacher_grading_decisions = teachers_grading_decisions_list.clone();

            let exam_exercises = exercises::get_exercises_by_exam_id(&mut conn, *exam_id).await?;

            let user_exercise_states =
                user_exercise_states::get_all_for_user_and_course_instance_or_exam(
                    &mut conn,
                    user.id,
                    CourseInstanceOrExamId::Exam(*exam_id),
                )
                .await?;

            let mut grading_decision_and_exercise_list: Vec<(TeacherGradingDecision, Exercise)> =
                Vec::new();

            // Check if student has any published grading results they can view at the exam page
            for grading_decision in teachers_grading_decisions_list.into_iter() {
                if let Some(hidden) = grading_decision.hidden {
                    if !hidden {
                        // Get the corresponding exercise for the grading result
                        for grading in teacher_grading_decisions.into_iter() {
                            let user_exercise_state = user_exercise_states
                                .iter()
                                .find(|state| state.id == grading.user_exercise_state_id)
                                .ok_or_else(|| {
                                    ModelError::new(
                                        ModelErrorType::Generic,
                                        "User_exercise_state not found",
                                        None,
                                    )
                                })?;

                            let exercise = exam_exercises
                                .iter()
                                .find(|exercise| exercise.id == user_exercise_state.exercise_id)
                                .ok_or_else(|| {
                                    ModelError::new(
                                        ModelErrorType::Generic,
                                        "Exercise not found",
                                        None,
                                    )
                                })?;

                            grading_decision_and_exercise_list.push((grading, exercise.clone()));
                        }

                        let token =
                            authorize(&mut conn, Act::View, Some(user.id), Res::Exam(*exam_id))
                                .await?;
                        return token.authorized_ok(web::Json(ExamData {
                            id: exam.id,
                            name: exam.name,
                            instructions: exam.instructions,
                            starts_at,
                            ends_at,
                            ended,
                            time_minutes: exam.time_minutes,
                            enrollment_data: ExamEnrollmentData::StudentCanViewGrading {
                                gradings: grading_decision_and_exercise_list,
                                enrollment,
                            },
                            language: exam.language,
                        }));
                    }
                }
            }
            // user has ended the exam
            if enrollment.ended_at.is_some() {
                let token: domain::authorization::AuthorizationToken =
                    authorize(&mut conn, Act::View, Some(user.id), Res::Exam(*exam_id)).await?;
                return token.authorized_ok(web::Json(ExamData {
                    id: exam.id,
                    name: exam.name,
                    instructions: exam.instructions,
                    starts_at,
                    ends_at,
                    ended,
                    time_minutes: exam.time_minutes,
                    enrollment_data: ExamEnrollmentData::StudentTimeUp,
                    language: exam.language,
                }));
            }
        }

        // user has started the exam
        if Utc::now() < ends_at
            && (Utc::now() > enrollment.started_at + Duration::minutes(exam.time_minutes.into())
                || enrollment.ended_at.is_some())
        {
            // exam is still open but the student's time has expired or student has ended their exam
            if enrollment.ended_at.is_none() {
                exams::update_exam_ended_at(&mut conn, *exam_id, user.id, Utc::now()).await?;
            }
            let token: domain::authorization::AuthorizationToken =
                authorize(&mut conn, Act::View, Some(user.id), Res::Exam(*exam_id)).await?;
            return token.authorized_ok(web::Json(ExamData {
                id: exam.id,
                name: exam.name,
                instructions: exam.instructions,
                starts_at,
                ends_at,
                ended,
                time_minutes: exam.time_minutes,
                enrollment_data: ExamEnrollmentData::StudentTimeUp,
                language: exam.language,
            }));
        }
        enrollment
    } else {
        // user has not started the exam
        let token = authorize(&mut conn, Act::View, Some(user.id), Res::Exam(*exam_id)).await?;
        let can_enroll =
            models::library::progressing::user_can_take_exam(&mut conn, *exam_id, user.id).await?;
        return token.authorized_ok(web::Json(ExamData {
            id: exam.id,
            name: exam.name,
            instructions: exam.instructions,
            starts_at,
            ends_at,
            ended,
            time_minutes: exam.time_minutes,
            enrollment_data: ExamEnrollmentData::NotEnrolled { can_enroll },
            language: exam.language,
        }));
    };

    let page = pages::get_page(&mut conn, exam.page_id).await?;

    let token = authorize(&mut conn, Act::View, Some(user.id), Res::Exam(*exam_id)).await?;
    token.authorized_ok(web::Json(ExamData {
        id: exam.id,
        name: exam.name,
        instructions: exam.instructions,
        starts_at,
        ends_at,
        ended,
        time_minutes: exam.time_minutes,
        enrollment_data: ExamEnrollmentData::EnrolledAndStarted {
            page_id: exam.page_id,
            page: Box::new(page),
            enrollment,
        },
        language: exam.language,
    }))
}

/**
GET /api/v0/course-material/exams/:id/fetch-exam-for-testing

Fetches an exam for testing.
*/
#[instrument(skip(pool))]
pub async fn fetch_exam_for_testing(
    pool: web::Data<PgPool>,
    exam_id: web::Path<Uuid>,
    user: AuthUser,
) -> ControllerResult<web::Json<ExamData>> {
    let mut conn = pool.acquire().await?;
    let exam = exams::get(&mut conn, *exam_id).await?;

    let starts_at = Utc::now();
    let ends_at = if let Some(ends_at) = exam.ends_at {
        ends_at
    } else {
        return Err(ControllerError::new(
            ControllerErrorType::Forbidden,
            "Cannot fetch exam that has no end time".to_string(),
            None,
        ));
    };
    let ended = ends_at < Utc::now();

    let enrollment = if let Some(enrollment) =
        exams::get_enrollment(&mut conn, *exam_id, user.id).await?
    {
        enrollment
    } else {
        // user has not started the exam
        let token = authorize(&mut conn, Act::Edit, Some(user.id), Res::Exam(*exam_id)).await?;
        let can_enroll =
            models::library::progressing::user_can_take_exam(&mut conn, *exam_id, user.id).await?;
        return token.authorized_ok(web::Json(ExamData {
            id: exam.id,
            name: exam.name,
            instructions: exam.instructions,
            starts_at,
            ends_at,
            ended,
            time_minutes: exam.time_minutes,
            enrollment_data: ExamEnrollmentData::NotEnrolled { can_enroll },
            language: exam.language,
        }));
    };

    let page = pages::get_page(&mut conn, exam.page_id).await?;

    let token = authorize(&mut conn, Act::Edit, Some(user.id), Res::Exam(*exam_id)).await?;
    token.authorized_ok(web::Json(ExamData {
        id: exam.id,
        name: exam.name,
        instructions: exam.instructions,
        starts_at,
        ends_at,
        ended,
        time_minutes: exam.time_minutes,
        enrollment_data: ExamEnrollmentData::EnrolledAndStarted {
            page_id: exam.page_id,
            page: Box::new(page),
            enrollment,
        },
        language: exam.language,
    }))
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct ShowExerciseAnswers {
    pub show_exercise_answers: bool,
}
/**
POST /api/v0/course-material/exams/:id/update-show-exercise-answers

Used for testing an exam, updates wheter exercise answers are shown.
*/
#[instrument(skip(pool))]
pub async fn update_show_exercise_answers(
    pool: web::Data<PgPool>,
    exam_id: web::Path<Uuid>,
    user: AuthUser,
    payload: web::Json<ShowExerciseAnswers>,
) -> ControllerResult<web::Json<()>> {
    let mut conn = pool.acquire().await?;
    let show_answers = payload.show_exercise_answers;
    exams::update_show_exercise_answers(&mut conn, *exam_id, user.id, show_answers).await?;
    let token = authorize(&mut conn, Act::Teach, Some(user.id), Res::Exam(*exam_id)).await?;
    token.authorized_ok(web::Json(()))
}

/**
POST /api/v0/course-material/exams/:id/reset-exam-progress

Used for testing an exam, resets exercise submissions and restarts the exam time.
*/
#[instrument(skip(pool))]
pub async fn reset_exam_progress(
    pool: web::Data<PgPool>,
    exam_id: web::Path<Uuid>,
    user: AuthUser,
) -> ControllerResult<web::Json<()>> {
    let mut conn = pool.acquire().await?;

    let started_at = Utc::now();
    exams::update_exam_start_time(&mut conn, *exam_id, user.id, started_at).await?;

    models::exercise_slide_submissions::delete_exercise_submissions_with_exam_id_and_user_id(
        &mut conn, *exam_id, user.id,
    )
    .await?;

    let token = authorize(&mut conn, Act::Teach, Some(user.id), Res::Exam(*exam_id)).await?;
    token.authorized_ok(web::Json(()))
}

/**
POST /api/v0/course-material/exams/:id/end-exam-time

Used for marking the students exam as ended in the exam enrollment
*/
#[instrument(skip(pool))]
pub async fn end_exam_time(
    pool: web::Data<PgPool>,
    exam_id: web::Path<Uuid>,
    user: AuthUser,
) -> ControllerResult<web::Json<()>> {
    let mut conn = pool.acquire().await?;

    let ended_at = Utc::now();
    models::exams::update_exam_ended_at(&mut conn, *exam_id, user.id, ended_at).await?;

    let token = authorize(&mut conn, Act::View, Some(user.id), Res::Exam(*exam_id)).await?;
    token.authorized_ok(web::Json(()))
}

/**
Add a route for each controller in this module.

The name starts with an underline in order to appear before other functions in the module documentation.

We add the routes by calling the route method instead of using the route annotations because this method preserves the function signatures for documentation.
*/
pub fn _add_routes(cfg: &mut ServiceConfig) {
    cfg.route("/{id}/enrollment", web::get().to(enrollment))
        .route("/{id}/enroll", web::post().to(enroll))
        .route("/{id}", web::get().to(fetch_exam_for_user))
        .route(
            "/testexam/{id}/fetch-exam-for-testing",
            web::get().to(fetch_exam_for_testing),
        )
        .route(
            "/testexam/{id}/update-show-exercise-answers",
            web::post().to(update_show_exercise_answers),
        )
        .route(
            "/testexam/{id}/reset-exam-progress",
            web::post().to(reset_exam_progress),
        )
        .route("/{id}/end-exam-time", web::post().to(end_exam_time));
}