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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
use crate::{
    exercise_task_gradings::{ExerciseTaskGrading, UserPointsUpdateStrategy},
    exercises::{ActivityProgress, GradingProgress},
    prelude::*,
};

#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct UserExerciseTaskState {
    pub exercise_task_id: Uuid,
    pub user_exercise_slide_state_id: Uuid,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub deleted_at: Option<DateTime<Utc>>,
    pub score_given: Option<f32>,
    pub grading_progress: GradingProgress,
}

pub async fn insert(
    conn: &mut PgConnection,
    exercise_task_id: Uuid,
    user_exercise_slide_state_id: Uuid,
    grading_progress: GradingProgress,
) -> ModelResult<()> {
    sqlx::query!(
        "
INSERT INTO user_exercise_task_states (
    exercise_task_id,
    user_exercise_slide_state_id,
    grading_progress
  )
VALUES ($1, $2, $3)
        ",
        exercise_task_id,
        user_exercise_slide_state_id,
        grading_progress as GradingProgress,
    )
    .execute(conn)
    .await?;
    Ok(())
}

/// Upserts user score from task grading results. The score can always increase
/// or decrease, since they represent only a part of the whole user submission.
pub async fn upsert_with_grading(
    conn: &mut PgConnection,
    user_exercise_slide_state_id: Uuid,
    exercise_task_grading: &ExerciseTaskGrading,
) -> ModelResult<UserExerciseTaskState> {
    upsert_with_grading_status(
        conn,
        exercise_task_grading.exercise_task_id,
        user_exercise_slide_state_id,
        exercise_task_grading.score_given,
        exercise_task_grading.grading_progress,
    )
    .await
}

async fn upsert_with_grading_status(
    conn: &mut PgConnection,
    exercise_task_id: Uuid,
    user_exercise_slide_state_id: Uuid,
    score_given: Option<f32>,
    grading_progress: GradingProgress,
) -> ModelResult<UserExerciseTaskState> {
    let res = sqlx::query_as!(
        UserExerciseTaskState,
        r#"
INSERT INTO user_exercise_task_states (
    exercise_task_id,
    user_exercise_slide_state_id,
    score_given,
    grading_progress
  )
VALUES ($1, $2, $3, $4) ON CONFLICT (exercise_task_id, user_exercise_slide_state_id) DO
UPDATE
SET deleted_at = NULL,
  score_given = $3,
  grading_progress = $4
RETURNING exercise_task_id,
  user_exercise_slide_state_id,
  created_at,
  updated_at,
  deleted_at,
  score_given,
  grading_progress as "grading_progress: _"
    "#,
        exercise_task_id,
        user_exercise_slide_state_id,
        score_given,
        grading_progress as GradingProgress,
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

pub async fn get(
    conn: &mut PgConnection,
    exercise_task_id: Uuid,
    user_exercise_state_id: Uuid,
) -> ModelResult<UserExerciseTaskState> {
    let res = sqlx::query_as!(
        UserExerciseTaskState,
        r#"
SELECT exercise_task_id,
  user_exercise_slide_state_id,
  created_at,
  updated_at,
  deleted_at,
  score_given,
  grading_progress as "grading_progress: _"
FROM user_exercise_task_states
WHERE exercise_task_id = $1
  AND user_exercise_slide_state_id = $2
  AND deleted_at IS NULL
        "#,
        exercise_task_id,
        user_exercise_state_id,
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

pub async fn get_grading_summary_by_user_exercise_slide_state_id(
    conn: &mut PgConnection,
    user_exercise_slide_state_id: Uuid,
) -> ModelResult<(Option<f32>, GradingProgress)> {
    let res = sqlx::query!(
        r#"
SELECT score_given,
  grading_progress AS "grading_progress: GradingProgress"
FROM user_exercise_task_states
WHERE user_exercise_slide_state_id = $1
  AND deleted_at IS NULL
        "#,
        user_exercise_slide_state_id
    )
    .fetch_all(conn)
    .await?;
    let total_score_given = res
        .iter()
        .filter_map(|x| x.score_given)
        .reduce(|acc, next| acc + next);
    let least_significant_grading_progress = res
        .iter()
        .map(|x| x.grading_progress)
        .min()
        .unwrap_or(GradingProgress::NotReady);
    Ok((total_score_given, least_significant_grading_progress))
}

pub async fn delete(
    conn: &mut PgConnection,
    exercise_task_id: Uuid,
    user_exercise_slide_state_id: Uuid,
) -> ModelResult<()> {
    sqlx::query!(
        "
UPDATE user_exercise_task_states
SET deleted_at = now()
WHERE exercise_task_id = $1
  AND user_exercise_slide_state_id = $2
  AND deleted_at IS NULL
    ",
        exercise_task_id,
        user_exercise_slide_state_id,
    )
    .execute(conn)
    .await?;
    Ok(())
}

/**
Returns a new state for the activity progress.

In the future this function will be extended to support peer reviews. When
there's a peer review associated with the exercise, the activity is not complete
before the user has given the peer reviews that they're required to give.
*/
pub fn figure_out_new_activity_progress(
    current_activity_progress: ActivityProgress,
) -> ActivityProgress {
    if current_activity_progress == ActivityProgress::Completed {
        return ActivityProgress::Completed;
    }

    // The case where activity is not completed when the user needs to give peer
    // reviews
    ActivityProgress::Completed
}

/**
Returns a new state for the grading progress.

The new grading progress is always the grading progress from the new grading
unless the current grading progress is already finished. If the current grading
progress is finished, we don't change it to anything else so that a new worse
submission won't take the user's progress away.

In the future this function will be extended to support peer reviews. When
there's a peer review associated with the exercise, it is part of the overall
grading progress.
*/
pub fn figure_out_new_grading_progress(
    current_grading_progress: Option<GradingProgress>,
    grading_grading_progress: GradingProgress,
) -> GradingProgress {
    match current_grading_progress {
        Some(GradingProgress::FullyGraded) => GradingProgress::FullyGraded,
        _ => grading_grading_progress,
    }
}

pub fn figure_out_new_score_given(
    current_score_given: Option<f32>,
    grading_score_given: Option<f32>,
    user_points_update_strategy: UserPointsUpdateStrategy,
) -> Option<f32> {
    let current_score_given = if let Some(current_score_given) = current_score_given {
        current_score_given
    } else {
        info!(
            "Current state has no score, using score from grading ({:?})",
            grading_score_given
        );
        return grading_score_given;
    };
    let grading_score_given = if let Some(grading_score_given) = grading_score_given {
        grading_score_given
    } else {
        info!(
            "Grading has no score, using score from current state ({:?})",
            current_score_given
        );
        return Some(current_score_given);
    };

    let new_score = match user_points_update_strategy {
        UserPointsUpdateStrategy::CanAddPointsButCannotRemovePoints => {
            if current_score_given >= grading_score_given {
                info!(
                    "Not updating score ({:?} >= {:?})",
                    current_score_given, grading_score_given
                );
                current_score_given
            } else {
                info!(
                    "Updating score from {:?} to {:?}",
                    current_score_given, grading_score_given
                );
                grading_score_given
            }
        }
        UserPointsUpdateStrategy::CanAddPointsAndCanRemovePoints => {
            info!(
                "Updating score from {:?} to {:?}",
                current_score_given, grading_score_given
            );
            grading_score_given
        }
    };
    Some(new_score)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helper::*;

    mod get_grading_summary_by_user_exercise_slide_state_id {
        use headless_lms_utils::numbers::f32_approx_eq;
        use serde_json::Value;

        use crate::{
            chapters::{self, NewChapter},
            exercise_slides,
            exercise_tasks::{self, NewExerciseTask},
            exercises,
            pages::{self, NewCoursePage},
            user_exercise_slide_states, user_exercise_states,
        };

        use super::*;

        #[tokio::test]
        async fn initial_values() {
            insert_data!(:tx);
            let (user_exercise_slide_state_id, task_1, task_2, task_3) =
                create_test_data(&mut tx).await.unwrap();
            insert(
                tx.as_mut(),
                task_1,
                user_exercise_slide_state_id,
                GradingProgress::NotReady,
            )
            .await
            .unwrap();
            insert(
                tx.as_mut(),
                task_2,
                user_exercise_slide_state_id,
                GradingProgress::NotReady,
            )
            .await
            .unwrap();
            insert(
                tx.as_mut(),
                task_3,
                user_exercise_slide_state_id,
                GradingProgress::NotReady,
            )
            .await
            .unwrap();

            let (score_given, grading_progress) =
                get_grading_summary_by_user_exercise_slide_state_id(
                    tx.as_mut(),
                    user_exercise_slide_state_id,
                )
                .await
                .unwrap();
            assert_eq!(score_given, None);
            assert_eq!(grading_progress, GradingProgress::NotReady);
        }

        #[tokio::test]
        async fn single_task() {
            insert_data!(:tx);
            let (user_exercise_slide_state_id, task_1, task_2, task_3) =
                create_test_data(&mut tx).await.unwrap();
            upsert_with_grading_status(
                tx.as_mut(),
                task_1,
                user_exercise_slide_state_id,
                None,
                GradingProgress::NotReady,
            )
            .await
            .unwrap();
            upsert_with_grading_status(
                tx.as_mut(),
                task_2,
                user_exercise_slide_state_id,
                None,
                GradingProgress::NotReady,
            )
            .await
            .unwrap();
            upsert_with_grading_status(
                tx.as_mut(),
                task_3,
                user_exercise_slide_state_id,
                Some(1.0),
                GradingProgress::FullyGraded,
            )
            .await
            .unwrap();

            let (score_given, grading_progress) =
                get_grading_summary_by_user_exercise_slide_state_id(
                    tx.as_mut(),
                    user_exercise_slide_state_id,
                )
                .await
                .unwrap();
            assert!(f32_approx_eq(score_given.unwrap(), 1.0));
            assert_eq!(grading_progress, GradingProgress::NotReady);
        }

        #[tokio::test]
        async fn all_tasks() {
            insert_data!(:tx);
            let (user_exercise_slide_state_id, task_1, task_2, task_3) =
                create_test_data(&mut tx).await.unwrap();
            upsert_with_grading_status(
                tx.as_mut(),
                task_1,
                user_exercise_slide_state_id,
                Some(1.0),
                GradingProgress::FullyGraded,
            )
            .await
            .unwrap();
            upsert_with_grading_status(
                tx.as_mut(),
                task_2,
                user_exercise_slide_state_id,
                Some(1.0),
                GradingProgress::FullyGraded,
            )
            .await
            .unwrap();
            upsert_with_grading_status(
                tx.as_mut(),
                task_3,
                user_exercise_slide_state_id,
                Some(1.0),
                GradingProgress::FullyGraded,
            )
            .await
            .unwrap();

            let (score_given, grading_progress) =
                get_grading_summary_by_user_exercise_slide_state_id(
                    tx.as_mut(),
                    user_exercise_slide_state_id,
                )
                .await
                .unwrap();
            assert!(f32_approx_eq(score_given.unwrap(), 3.0));
            assert_eq!(grading_progress, GradingProgress::FullyGraded);
        }

        async fn create_test_data(tx: &mut Tx<'_>) -> ModelResult<(Uuid, Uuid, Uuid, Uuid)> {
            insert_data!(tx: tx; :user, :org, :course, :instance, :course_module);
            let chapter_id = chapters::insert(
                tx.as_mut(),
                PKeyPolicy::Generate,
                &NewChapter {
                    name: "chapter".to_string(),
                    color: Some("#065853".to_string()),
                    course_id: course,
                    chapter_number: 1,
                    front_page_id: None,
                    opens_at: None,
                    deadline: None,
                    course_module_id: Some(course_module.id),
                },
            )
            .await?;

            let (page_id, _history) = pages::insert_course_page(
                tx.as_mut(),
                &NewCoursePage::new(course, 1, "/test", "test"),
                user,
            )
            .await?;
            let exercise_id = exercises::insert(
                tx.as_mut(),
                PKeyPolicy::Generate,
                course,
                "course",
                page_id,
                chapter_id,
                1,
            )
            .await?;
            let slide_id =
                exercise_slides::insert(tx.as_mut(), PKeyPolicy::Generate, exercise_id, 1).await?;
            let task_1 = exercise_tasks::insert(
                tx.as_mut(),
                PKeyPolicy::Generate,
                NewExerciseTask {
                    exercise_slide_id: slide_id,
                    exercise_type: "test-exercise".to_string(),
                    assignment: vec![],
                    public_spec: Some(Value::Null),
                    private_spec: Some(Value::Null),
                    model_solution_spec: Some(Value::Null),
                    order_number: 1,
                },
            )
            .await?;
            let task_2 = exercise_tasks::insert(
                tx.as_mut(),
                PKeyPolicy::Generate,
                NewExerciseTask {
                    exercise_slide_id: slide_id,
                    exercise_type: "test-exercise".to_string(),
                    assignment: vec![],
                    public_spec: Some(Value::Null),
                    private_spec: Some(Value::Null),
                    model_solution_spec: Some(Value::Null),
                    order_number: 2,
                },
            )
            .await?;
            let task_3 = exercise_tasks::insert(
                tx.as_mut(),
                PKeyPolicy::Generate,
                NewExerciseTask {
                    exercise_slide_id: slide_id,
                    exercise_type: "test-exercise".to_string(),
                    assignment: vec![],
                    public_spec: Some(Value::Null),
                    private_spec: Some(Value::Null),
                    model_solution_spec: Some(Value::Null),
                    order_number: 3,
                },
            )
            .await?;
            let user_exercise_state = user_exercise_states::get_or_create_user_exercise_state(
                tx.as_mut(),
                user,
                exercise_id,
                Some(instance.id),
                None,
            )
            .await?;
            user_exercise_states::upsert_selected_exercise_slide_id(
                tx.as_mut(),
                user,
                exercise_id,
                Some(instance.id),
                None,
                Some(slide_id),
            )
            .await?;
            let user_exercise_slide_state_id = user_exercise_slide_states::insert(
                tx.as_mut(),
                PKeyPolicy::Generate,
                user_exercise_state.id,
                slide_id,
            )
            .await?;
            Ok((user_exercise_slide_state_id, task_1, task_2, task_3))
        }
    }

    mod figure_out_new_activity_progress {
        use super::*;

        #[test]
        fn it_works() {
            assert_eq!(
                figure_out_new_activity_progress(ActivityProgress::Initialized),
                ActivityProgress::Completed
            );
        }
    }

    mod figure_out_new_grading_progress {
        use super::*;

        const ALL_GRADING_PROGRESSES: [GradingProgress; 5] = [
            GradingProgress::FullyGraded,
            GradingProgress::Pending,
            GradingProgress::PendingManual,
            GradingProgress::Failed,
            GradingProgress::NotReady,
        ];

        #[test]
        fn current_fully_graded_progress_always_retains() {
            let current_grading_progress = GradingProgress::FullyGraded;
            for grading_grading_progress in ALL_GRADING_PROGRESSES {
                let new_grading_progress = figure_out_new_grading_progress(
                    Some(current_grading_progress),
                    grading_grading_progress,
                );
                assert_eq!(new_grading_progress, current_grading_progress);
            }
        }

        #[test]
        fn uses_value_from_grading_if_not_completed() {
            for grading_grading_progress in ALL_GRADING_PROGRESSES {
                let current_grading_progresses = vec![
                    None,
                    Some(GradingProgress::Pending),
                    Some(GradingProgress::PendingManual),
                    Some(GradingProgress::Failed),
                    Some(GradingProgress::NotReady),
                ];
                for current_grading_progress in current_grading_progresses {
                    let new_grading_progress = figure_out_new_grading_progress(
                        current_grading_progress,
                        grading_grading_progress,
                    );
                    assert_eq!(new_grading_progress, grading_grading_progress);
                }
            }
        }
    }

    mod figure_out_new_score_given {
        use headless_lms_utils::numbers::{f32_approx_eq, f32_max};

        use super::*;

        #[test]
        fn strategy_can_add_points_and_can_remove_points_works() {
            let test_cases = vec![(1.1, 1.1), (1.1, 20.9), (20.9, 1.1)];
            for (current, new) in test_cases {
                let result = figure_out_new_score_given(
                    Some(current),
                    Some(new),
                    UserPointsUpdateStrategy::CanAddPointsAndCanRemovePoints,
                )
                .unwrap();
                assert!(f32_approx_eq(result, new));
            }
        }

        #[test]
        fn strategy_can_add_points_but_cannot_remove_points_works() {
            let test_cases = vec![(1.1, 1.1), (1.1, 20.9), (20.9, 1.1)];
            for (current, new) in test_cases {
                let result = figure_out_new_score_given(
                    Some(current),
                    Some(new),
                    UserPointsUpdateStrategy::CanAddPointsButCannotRemovePoints,
                )
                .unwrap();
                assert!(f32_approx_eq(result, f32_max(current, new)))
            }
        }

        #[test]
        fn it_handles_nones() {
            let user_points_update_strategies = vec![
                UserPointsUpdateStrategy::CanAddPointsAndCanRemovePoints,
                UserPointsUpdateStrategy::CanAddPointsButCannotRemovePoints,
            ];
            for update_strategy in user_points_update_strategies {
                assert_eq!(
                    figure_out_new_score_given(None, None, update_strategy),
                    None
                );
                assert!(f32_approx_eq(
                    figure_out_new_score_given(None, Some(1.1), update_strategy).unwrap(),
                    1.1
                ));
                assert!(f32_approx_eq(
                    figure_out_new_score_given(Some(1.1), None, update_strategy).unwrap(),
                    1.1
                ));
            }
        }
    }
}