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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
use std::collections::HashMap;

use futures::Stream;
use headless_lms_utils::numbers::option_f32_to_f32_two_decimals_with_none_as_zero;
use serde_json::Value;

use crate::{
    course_instances,
    course_modules::{self, CourseModule},
    courses,
    exercises::{ActivityProgress, Exercise, GradingProgress},
    prelude::*,
    user_course_settings,
};

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Copy, Type)]
#[sqlx(type_name = "reviewing_stage", rename_all = "snake_case")]
#[cfg_attr(feature = "ts_rs", derive(TS))]
/**
Tells what stage of reviewing the user is currently in. Used for for peer review, self review, and manual review. If an exercise does not involve reviewing, the value of this stage will always be `NotStarted`.
*/
pub enum ReviewingStage {
    /**
    In this stage the user submits answers to the exercise. If the exercise allows it, the user can answer the exercise multiple times. If the exercise is not in this stage, the user cannot answer the exercise. Most exercises will never leave this stage because other stages are reseverved for situations when we cannot give the user points just based on the automatic gradings.
    */
    NotStarted,
    /// In this stage the student is instructed to give peer reviews to other students.
    PeerReview,
    /// In this stage the student is instructed to review their own answer.
    SelfReview,
    /// In this stage the student has completed the neccessary peer and self reviews but is waiting for other students to peer review their answer before we can give points for this exercise.
    WaitingForPeerReviews,
    /**
    In this stage the student has completed everything they need to do, but before we can give points for this exercise, we need a manual grading from the teacher.

    Reasons for ending up in this stage may be one of these:

    1. The exercise is configured to require all answers to be reviewed by the teacher.
    2. The answer has received poor reviews from the peers, and the exercise has been configured so that the teacher has to double-check whether it is justified to not give full points to the student.
    */
    WaitingForManualGrading,
    /**
    In this stage the the reviews have been completed and the points have been awarded to the student. However, since the answer had to go though the review process, the student may no longer answer the exercise since because

    1. It is likely that we revealed the model solution to the student during the review process.
    2. In case of peer review, a new answer would have to be reviewed by other students again, and that would be unreasonable extra work for others.

    If the teacher for some reasoon feels bad for the student and wants to give them a new chance, the answers for this exercise should be reset, the reason should be recorded somewhere in the database, and the value of this column should be set to `NotStarted`. Deleting the whole user_exercise_state may also be wise. However, if we end up doing this for a teacher, we should make sure that the teacher realizes that they should not give an unfair advantage to anyone.
    */
    ReviewedAndLocked,
}

#[cfg_attr(feature = "ts_rs", derive(TS))]
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct UserExerciseState {
    pub id: Uuid,
    pub user_id: Uuid,
    pub exercise_id: Uuid,
    pub course_instance_id: Option<Uuid>,
    pub exam_id: Option<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 activity_progress: ActivityProgress,
    pub reviewing_stage: ReviewingStage,
    pub selected_exercise_slide_id: Option<Uuid>,
}

impl UserExerciseState {
    pub fn get_course_instance_id(&self) -> ModelResult<Uuid> {
        self.course_instance_id.ok_or_else(|| {
            ModelError::new(
                ModelErrorType::Generic,
                "Exercise is not part of a course instance.".to_string(),
                None,
            )
        })
    }

    pub fn get_selected_exercise_slide_id(&self) -> ModelResult<Uuid> {
        self.selected_exercise_slide_id.ok_or_else(|| {
            ModelError::new(
                ModelErrorType::Generic,
                "No exercise slide selected.".to_string(),
                None,
            )
        })
    }
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct UserExerciseStateUpdate {
    pub id: Uuid,
    pub score_given: Option<f32>,
    pub activity_progress: ActivityProgress,
    pub reviewing_stage: ReviewingStage,
    pub grading_progress: GradingProgress,
}

/// Either a course instance or exam id.
///
/// Exercises can either be part of courses or exams. Many user-related actions need to differentiate
/// between two, so `CourseInstanceOrExamId` helps when handling these separate scenarios.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Copy)]
pub enum CourseInstanceOrExamId {
    Instance(Uuid),
    Exam(Uuid),
}

impl CourseInstanceOrExamId {
    pub fn from_instance_and_exam_ids(
        course_instance_id: Option<Uuid>,
        exam_id: Option<Uuid>,
    ) -> ModelResult<Self> {
        match (course_instance_id, exam_id) {
            (None, None) => Err(ModelError::new(
                ModelErrorType::Generic,
                "Expected either course instance or exam id, but neither were provided.".into(),
                None,
            )),
            (Some(instance_id), None) => Ok(Self::Instance(instance_id)),
            (None, Some(exam_id)) => Ok(Self::Exam(exam_id)),
            (Some(_), Some(_)) => Err(ModelError::new(
                ModelErrorType::Generic,
                "Expected either course instance or exam id, but both were provided.".into(),
                None,
            )),
        }
    }

    pub fn to_instance_and_exam_ids(&self) -> (Option<Uuid>, Option<Uuid>) {
        match self {
            CourseInstanceOrExamId::Instance(instance_id) => (Some(*instance_id), None),
            CourseInstanceOrExamId::Exam(exam_id) => (None, Some(*exam_id)),
        }
    }
}

impl TryFrom<UserExerciseState> for CourseInstanceOrExamId {
    type Error = ModelError;

    fn try_from(user_exercise_state: UserExerciseState) -> Result<Self, Self::Error> {
        Self::from_instance_and_exam_ids(
            user_exercise_state.course_instance_id,
            user_exercise_state.exam_id,
        )
    }
}

#[derive(Debug, Serialize, Deserialize, FromRow, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct UserCourseInstanceProgress {
    pub course_module_id: Uuid,
    pub course_module_name: String,
    pub course_module_order_number: i32,
    pub score_given: f32,
    pub score_required: Option<i32>,
    pub score_maximum: Option<u32>,
    pub total_exercises: Option<u32>,
    pub attempted_exercises: Option<i32>,
    pub attempted_exercises_required: Option<i32>,
}

#[derive(Debug, Serialize, Deserialize, FromRow, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct UserCourseInstanceChapterExerciseProgress {
    pub exercise_id: Uuid,
    pub score_given: f32,
}

#[derive(Debug, Serialize, Deserialize, FromRow, PartialEq, Clone)]
pub struct DatabaseUserCourseInstanceChapterExerciseProgress {
    pub exercise_id: Uuid,
    pub score_given: Option<f32>,
}

#[derive(Debug, Serialize, Deserialize, FromRow, PartialEq, Clone)]
pub struct UserChapterMetrics {
    pub score_given: Option<f32>,
    pub attempted_exercises: Option<i64>,
}

#[derive(Debug, Serialize, Deserialize, FromRow, PartialEq, Clone)]
pub struct UserCourseInstanceMetrics {
    pub course_module_id: Uuid,
    pub score_given: Option<f32>,
    pub attempted_exercises: Option<i64>,
}

#[derive(Debug, Serialize, Deserialize, FromRow, PartialEq, Clone)]
pub struct CourseInstanceExerciseMetrics {
    course_module_id: Uuid,
    total_exercises: Option<i64>,
    score_maximum: Option<i64>,
}

#[derive(Debug, Serialize, Deserialize, FromRow, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct ExerciseUserCounts {
    exercise_name: String,
    exercise_order_number: i32,
    page_order_number: i32,
    chapter_number: i32,
    exercise_id: Uuid,
    #[cfg_attr(feature = "ts_rs", ts(type = "number"))]
    n_users_attempted: Option<i64>,
    #[cfg_attr(feature = "ts_rs", ts(type = "number"))]
    n_users_with_some_points: Option<i64>,
    #[cfg_attr(feature = "ts_rs", ts(type = "number"))]
    n_users_with_max_points: Option<i64>,
}

pub async fn get_course_instance_metrics(
    conn: &mut PgConnection,
    course_instance_id: Uuid,
) -> ModelResult<Vec<CourseInstanceExerciseMetrics>> {
    let res = sqlx::query_as!(
        CourseInstanceExerciseMetrics,
        r"
SELECT chapters.course_module_id,
  COUNT(exercises.id) AS total_exercises,
  SUM(exercises.score_maximum) AS score_maximum
FROM course_instances
  LEFT JOIN exercises ON (course_instances.course_id = exercises.course_id)
  LEFT JOIN chapters ON (exercises.chapter_id = chapters.id)
WHERE exercises.deleted_at IS NULL
  AND course_instances.id = $1
GROUP BY chapters.course_module_id
        ",
        course_instance_id
    )
    .fetch_all(conn)
    .await?;
    Ok(res)
}

pub async fn get_course_instance_metrics_indexed_by_module_id(
    conn: &mut PgConnection,
    course_instance_id: Uuid,
) -> ModelResult<HashMap<Uuid, CourseInstanceExerciseMetrics>> {
    let res = get_course_instance_metrics(conn, course_instance_id)
        .await?
        .into_iter()
        .map(|x| (x.course_module_id, x))
        .collect();
    Ok(res)
}

/// Gets course instance metrics for a single module.
pub async fn get_single_module_course_instance_metrics(
    conn: &mut PgConnection,
    course_instance_id: Uuid,
    course_module_id: Uuid,
    user_id: Uuid,
) -> ModelResult<UserCourseInstanceMetrics> {
    let res = sqlx::query!(
        "
SELECT COUNT(ues.exercise_id) AS attempted_exercises,
  COALESCE(SUM(ues.score_given), 0) AS score_given
FROM user_exercise_states AS ues
  LEFT JOIN exercises ON (ues.exercise_id = exercises.id)
  LEFT JOIN chapters ON (exercises.chapter_id = chapters.id)
WHERE chapters.course_module_id = $1
  AND ues.course_instance_id = $2
  AND ues.activity_progress IN ('completed', 'submitted')
  AND ues.user_id = $3
  AND ues.deleted_at IS NULL
        ",
        course_module_id,
        course_instance_id,
        user_id,
    )
    .map(|x| UserCourseInstanceMetrics {
        course_module_id,
        score_given: x.score_given,
        attempted_exercises: x.attempted_exercises,
    })
    .fetch_one(conn)
    .await?;
    Ok(res)
}

pub async fn get_user_course_instance_metrics(
    conn: &mut PgConnection,
    course_instance_id: Uuid,
    user_id: Uuid,
) -> ModelResult<Vec<UserCourseInstanceMetrics>> {
    let res = sqlx::query_as!(
        UserCourseInstanceMetrics,
        r"
SELECT chapters.course_module_id,
  COUNT(ues.exercise_id) AS attempted_exercises,
  COALESCE(SUM(ues.score_given), 0) AS score_given
FROM user_exercise_states AS ues
  LEFT JOIN exercises ON (ues.exercise_id = exercises.id)
  LEFT JOIN chapters ON (exercises.chapter_id = chapters.id)
WHERE ues.course_instance_id = $1
  AND ues.activity_progress IN ('completed', 'submitted')
  AND ues.user_id = $2
  AND ues.deleted_at IS NULL
GROUP BY chapters.course_module_id;
        ",
        course_instance_id,
        user_id,
    )
    .fetch_all(conn)
    .await?;
    Ok(res)
}

pub async fn get_user_course_instance_metrics_indexed_by_module_id(
    conn: &mut PgConnection,
    course_instance_id: Uuid,
    user_id: Uuid,
) -> ModelResult<HashMap<Uuid, UserCourseInstanceMetrics>> {
    let res = get_user_course_instance_metrics(conn, course_instance_id, user_id)
        .await?
        .into_iter()
        .map(|x| (x.course_module_id, x))
        .collect();
    Ok(res)
}

pub async fn get_user_course_instance_chapter_metrics(
    conn: &mut PgConnection,
    course_instance_id: Uuid,
    exercise_ids: &[Uuid],
    user_id: Uuid,
) -> ModelResult<UserChapterMetrics> {
    let res = sqlx::query_as!(
        UserChapterMetrics,
        r#"
SELECT COUNT(ues.exercise_id) AS attempted_exercises,
  COALESCE(SUM(ues.score_given), 0) AS score_given
FROM user_exercise_states AS ues
WHERE ues.exercise_id IN (
    SELECT UNNEST($1::uuid [])
  )
  AND ues.deleted_at IS NULL
  AND ues.activity_progress IN ('completed', 'submitted')
  AND ues.user_id = $2
  AND ues.course_instance_id = $3;
                "#,
        &exercise_ids,
        user_id,
        course_instance_id
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

pub async fn get_user_course_instance_progress(
    conn: &mut PgConnection,
    course_instance_id: Uuid,
    user_id: Uuid,
) -> ModelResult<Vec<UserCourseInstanceProgress>> {
    let course_metrics =
        get_course_instance_metrics_indexed_by_module_id(&mut *conn, course_instance_id).await?;
    let user_metrics =
        get_user_course_instance_metrics_indexed_by_module_id(conn, course_instance_id, user_id)
            .await?;
    let course_id = course_instances::get_course_instance(conn, course_instance_id)
        .await?
        .course_id;
    let course_name = courses::get_course(conn, course_id).await?.name;
    let course_modules = course_modules::get_by_course_id(conn, course_id).await?;
    merge_modules_with_metrics(course_modules, &course_metrics, &user_metrics, &course_name)
}

/// Gets the total amount of points that the user has received from an exam.
///
/// The caller should take into consideration that for an ongoing exam the result will be volatile.
pub async fn get_user_total_exam_points(
    conn: &mut PgConnection,
    user_id: Uuid,
    exam_id: Uuid,
) -> ModelResult<Option<f32>> {
    let res = sqlx::query!(
        r#"
SELECT SUM(score_given) AS "points"
FROM user_exercise_states
WHERE user_id = $2
  AND exam_id = $1
  AND deleted_at IS NULL
        "#,
        exam_id,
        user_id,
    )
    .map(|x| x.points)
    .fetch_one(conn)
    .await?;
    Ok(res)
}

fn merge_modules_with_metrics(
    course_modules: Vec<CourseModule>,
    course_metrics_by_course_module_id: &HashMap<Uuid, CourseInstanceExerciseMetrics>,
    user_metrics_by_course_module_id: &HashMap<Uuid, UserCourseInstanceMetrics>,
    default_course_module_name_placeholder: &str,
) -> ModelResult<Vec<UserCourseInstanceProgress>> {
    course_modules
        .into_iter()
        .map(|course_module| {
            let user_metrics = user_metrics_by_course_module_id.get(&course_module.id);
            let course_metrics = course_metrics_by_course_module_id.get(&course_module.id);
            let requirements = course_module.completion_policy.automatic();
            let progress = UserCourseInstanceProgress {
                course_module_id: course_module.id,
                // Only default course module doesn't have a name.
                course_module_name: course_module
                    .name
                    .unwrap_or_else(|| default_course_module_name_placeholder.to_string()),
                course_module_order_number: course_module.order_number,
                score_given: option_f32_to_f32_two_decimals_with_none_as_zero(
                    user_metrics.and_then(|x| x.score_given),
                ),
                score_required: requirements.and_then(|x| x.number_of_points_treshold),
                score_maximum: course_metrics
                    .and_then(|x| x.score_maximum)
                    .map(TryInto::try_into)
                    .transpose()?,
                total_exercises: course_metrics
                    .and_then(|x| x.total_exercises)
                    .map(TryInto::try_into)
                    .transpose()?,
                attempted_exercises: user_metrics
                    .and_then(|x| x.attempted_exercises)
                    .map(TryInto::try_into)
                    .transpose()?,
                attempted_exercises_required: requirements
                    .and_then(|x| x.number_of_exercises_attempted_treshold),
            };
            Ok(progress)
        })
        .collect::<ModelResult<_>>()
}

pub async fn get_user_course_instance_chapter_exercises_progress(
    conn: &mut PgConnection,
    course_instance_id: Uuid,
    exercise_ids: &[Uuid],
    user_id: Uuid,
) -> ModelResult<Vec<DatabaseUserCourseInstanceChapterExerciseProgress>> {
    let res = sqlx::query_as!(
        DatabaseUserCourseInstanceChapterExerciseProgress,
        r#"
SELECT COALESCE(ues.score_given, 0) AS score_given,
  ues.exercise_id AS exercise_id
FROM user_exercise_states AS ues
WHERE ues.deleted_at IS NULL
  AND ues.exercise_id IN (
    SELECT UNNEST($1::uuid [])
  )
  AND ues.course_instance_id = $2
  AND ues.user_id = $3;
        "#,
        exercise_ids,
        course_instance_id,
        user_id,
    )
    .fetch_all(conn)
    .await?;
    Ok(res)
}

pub async fn get_or_create_user_exercise_state(
    conn: &mut PgConnection,
    user_id: Uuid,
    exercise_id: Uuid,
    course_instance_id: Option<Uuid>,
    exam_id: Option<Uuid>,
) -> ModelResult<UserExerciseState> {
    let existing = sqlx::query_as!(
        UserExerciseState,
        r#"
SELECT id,
  user_id,
  exercise_id,
  course_instance_id,
  exam_id,
  created_at,
  updated_at,
  deleted_at,
  score_given,
  grading_progress AS "grading_progress: _",
  activity_progress AS "activity_progress: _",
  reviewing_stage AS "reviewing_stage: _",
  selected_exercise_slide_id
FROM user_exercise_states
WHERE user_id = $1
  AND exercise_id = $2
  AND (course_instance_id = $3 OR exam_id = $4)
  AND deleted_at IS NULL
"#,
        user_id,
        exercise_id,
        course_instance_id,
        exam_id
    )
    .fetch_optional(&mut *conn)
    .await?;

    let res = if let Some(existing) = existing {
        existing
    } else {
        sqlx::query_as!(
            UserExerciseState,
            r#"
    INSERT INTO user_exercise_states (user_id, exercise_id, course_instance_id, exam_id)
    VALUES ($1, $2, $3, $4)
    RETURNING id,
      user_id,
      exercise_id,
      course_instance_id,
      exam_id,
      created_at,
      updated_at,
      deleted_at,
      score_given,
      grading_progress as "grading_progress: _",
      activity_progress as "activity_progress: _",
      reviewing_stage AS "reviewing_stage: _",
      selected_exercise_slide_id
      "#,
            user_id,
            exercise_id,
            course_instance_id,
            exam_id
        )
        .fetch_one(&mut *conn)
        .await?
    };
    Ok(res)
}

pub async fn get_by_id(conn: &mut PgConnection, id: Uuid) -> ModelResult<UserExerciseState> {
    let res = sqlx::query_as!(
        UserExerciseState,
        r#"
SELECT id,
  user_id,
  exercise_id,
  course_instance_id,
  exam_id,
  created_at,
  updated_at,
  deleted_at,
  score_given,
  grading_progress AS "grading_progress: _",
  activity_progress AS "activity_progress: _",
  reviewing_stage AS "reviewing_stage: _",
  selected_exercise_slide_id
FROM user_exercise_states
WHERE id = $1
  AND deleted_at IS NULL
        "#,
        id,
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

pub async fn get_user_total_course_points(
    conn: &mut PgConnection,
    user_id: Uuid,
    course_instance_id: Uuid,
) -> ModelResult<Option<f32>> {
    let res = sqlx::query!(
        r#"
SELECT SUM(score_given) AS "total_points"
FROM user_exercise_states
WHERE user_id = $1
  AND course_instance_id = $2
  AND deleted_at IS NULL
  GROUP BY user_id
        "#,
        user_id,
        course_instance_id,
    )
    .map(|x| x.total_points)
    .fetch_one(conn)
    .await?;
    Ok(res)
}

pub async fn get_users_current_by_exercise(
    conn: &mut PgConnection,
    user_id: Uuid,
    exercise: &Exercise,
) -> ModelResult<UserExerciseState> {
    let course_or_exam_id = CourseOrExamId::from(exercise.course_id, exercise.exam_id)?;
    let course_instance_or_exam_id = match course_or_exam_id {
        CourseOrExamId::Course(course_id) => {
            user_course_settings::get_user_course_settings_by_course_id(conn, user_id, course_id)
                .await?
                .map(|settings| {
                    CourseInstanceOrExamId::Instance(settings.current_course_instance_id)
                })
                .ok_or_else(|| {
                    ModelError::new(
                        ModelErrorType::PreconditionFailed,
                        "Missing user course settings.".to_string(),
                        None,
                    )
                })
        }
        CourseOrExamId::Exam(exam_id) => Ok(CourseInstanceOrExamId::Exam(exam_id)),
    }?;
    let user_exercise_state =
        get_user_exercise_state_if_exists(conn, user_id, exercise.id, course_instance_or_exam_id)
            .await?
            .ok_or_else(|| {
                ModelError::new(
                    ModelErrorType::PreconditionFailed,
                    "Missing user exercise state.".to_string(),
                    None,
                )
            })?;
    Ok(user_exercise_state)
}

pub async fn get_user_exercise_state_if_exists(
    conn: &mut PgConnection,
    user_id: Uuid,
    exercise_id: Uuid,
    course_instance_or_exam_id: CourseInstanceOrExamId,
) -> ModelResult<Option<UserExerciseState>> {
    let (course_instance_id, exam_id) = course_instance_or_exam_id.to_instance_and_exam_ids();
    let res = sqlx::query_as!(
        UserExerciseState,
        r#"
SELECT id,
  user_id,
  exercise_id,
  course_instance_id,
  exam_id,
  created_at,
  updated_at,
  deleted_at,
  score_given,
  grading_progress AS "grading_progress: _",
  activity_progress AS "activity_progress: _",
  reviewing_stage AS "reviewing_stage: _",
  selected_exercise_slide_id
FROM user_exercise_states
WHERE user_id = $1
  AND exercise_id = $2
  AND (course_instance_id = $3 OR exam_id = $4)
  AND deleted_at IS NULL
      "#,
        user_id,
        exercise_id,
        course_instance_id,
        exam_id
    )
    .fetch_optional(conn)
    .await?;
    Ok(res)
}

pub async fn get_all_for_user_and_course_instance_or_exam(
    conn: &mut PgConnection,
    user_id: Uuid,
    course_instance_or_exam_id: CourseInstanceOrExamId,
) -> ModelResult<Vec<UserExerciseState>> {
    let (course_instance_id, exam_id) = course_instance_or_exam_id.to_instance_and_exam_ids();
    let res = sqlx::query_as!(
        UserExerciseState,
        r#"
SELECT id,
  user_id,
  exercise_id,
  course_instance_id,
  exam_id,
  created_at,
  updated_at,
  deleted_at,
  score_given,
  grading_progress AS "grading_progress: _",
  activity_progress AS "activity_progress: _",
  reviewing_stage AS "reviewing_stage: _",
  selected_exercise_slide_id
FROM user_exercise_states
WHERE user_id = $1
  AND (course_instance_id = $2 OR exam_id = $3)
  AND deleted_at IS NULL
      "#,
        user_id,
        course_instance_id,
        exam_id
    )
    .fetch_all(conn)
    .await?;
    Ok(res)
}

pub async fn upsert_selected_exercise_slide_id(
    conn: &mut PgConnection,
    user_id: Uuid,
    exercise_id: Uuid,
    course_instance_id: Option<Uuid>,
    exam_id: Option<Uuid>,
    selected_exercise_slide_id: Option<Uuid>,
) -> ModelResult<()> {
    let existing = sqlx::query!(
        "
SELECT
FROM user_exercise_states
WHERE user_id = $1
  AND exercise_id = $2
  AND (course_instance_id = $3 OR exam_id = $4)
  AND deleted_at IS NULL
",
        user_id,
        exercise_id,
        course_instance_id,
        exam_id
    )
    .fetch_optional(&mut *conn)
    .await?;
    if existing.is_some() {
        sqlx::query!(
            "
UPDATE user_exercise_states
SET selected_exercise_slide_id = $4
WHERE user_id = $1
  AND exercise_id = $2
  AND (course_instance_id = $3 OR exam_id = $5)
  AND deleted_at IS NULL
    ",
            user_id,
            exercise_id,
            course_instance_id,
            selected_exercise_slide_id,
            exam_id
        )
        .execute(&mut *conn)
        .await?;
    } else {
        sqlx::query!(
            "
    INSERT INTO user_exercise_states (
        user_id,
        exercise_id,
        course_instance_id,
        selected_exercise_slide_id,
        exam_id
      )
    VALUES ($1, $2, $3, $4, $5)
    ",
            user_id,
            exercise_id,
            course_instance_id,
            selected_exercise_slide_id,
            exam_id
        )
        .execute(&mut *conn)
        .await?;
    }
    Ok(())
}

/// TODO: should be moved to the user_exercise_state_updater as a private module so that this cannot be called outside of that module
pub async fn update(
    conn: &mut PgConnection,
    user_exercise_state_update: UserExerciseStateUpdate,
) -> ModelResult<UserExerciseState> {
    let res = sqlx::query_as!(
        UserExerciseState,
        r#"
UPDATE user_exercise_states
SET score_given = $1,
  activity_progress = $2,
  reviewing_stage = $3,
  grading_progress = $4
WHERE id = $5
  AND deleted_at IS NULL
RETURNING id,
  user_id,
  exercise_id,
  course_instance_id,
  exam_id,
  created_at,
  updated_at,
  deleted_at,
  score_given,
  grading_progress AS "grading_progress: _",
  activity_progress AS "activity_progress: _",
  reviewing_stage AS "reviewing_stage: _",
  selected_exercise_slide_id
        "#,
        user_exercise_state_update.score_given,
        user_exercise_state_update.activity_progress as ActivityProgress,
        user_exercise_state_update.reviewing_stage as ReviewingStage,
        user_exercise_state_update.grading_progress as GradingProgress,
        user_exercise_state_update.id,
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

pub async fn update_reviewing_stage(
    conn: &mut PgConnection,
    user_id: Uuid,
    course_instance_or_exam_id: CourseInstanceOrExamId,
    exercise_id: Uuid,
    new_reviewing_stage: ReviewingStage,
) -> ModelResult<UserExerciseState> {
    let (course_instance_id, exam_id) = course_instance_or_exam_id.to_instance_and_exam_ids();
    let res = sqlx::query_as!(
        UserExerciseState,
        r#"
UPDATE user_exercise_states
SET reviewing_stage = $5
WHERE user_id = $1
AND (course_instance_id = $2 OR exam_id = $3)
AND exercise_id = $4
RETURNING id,
  user_id,
  exercise_id,
  course_instance_id,
  exam_id,
  created_at,
  updated_at,
  deleted_at,
  score_given,
  grading_progress AS "grading_progress: _",
  activity_progress AS "activity_progress: _",
  reviewing_stage AS "reviewing_stage: _",
  selected_exercise_slide_id
        "#,
        user_id,
        course_instance_id,
        exam_id,
        exercise_id,
        new_reviewing_stage as ReviewingStage
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

/// TODO: should be removed
pub async fn update_exercise_progress(
    conn: &mut PgConnection,
    id: Uuid,
    reviewing_stage: ReviewingStage,
) -> ModelResult<UserExerciseState> {
    let res = sqlx::query_as!(
        UserExerciseState,
        r#"
UPDATE user_exercise_states
SET reviewing_stage = $1
WHERE id = $2
  AND deleted_at IS NULL
RETURNING id,
  user_id,
  exercise_id,
  course_instance_id,
  exam_id,
  created_at,
  updated_at,
  deleted_at,
  score_given,
  grading_progress AS "grading_progress: _",
  activity_progress AS "activity_progress: _",
  reviewing_stage AS "reviewing_stage: _",
  selected_exercise_slide_id
        "#,
        reviewing_stage as ReviewingStage,
        id
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

/// Convenience struct that combines user state to the exercise.
///
/// Many operations require information about both the user state and the exercise. However, because
/// exercises can either belong to a course or an exam, and each course instance will have their
/// own `UserExerciseState`, it can get difficult to track the proper context.
pub struct ExerciseWithUserState {
    exercise: Exercise,
    user_exercise_state: UserExerciseState,
    type_data: EwusCourseOrExam,
}

impl ExerciseWithUserState {
    pub fn new(exercise: Exercise, user_exercise_state: UserExerciseState) -> ModelResult<Self> {
        let state = EwusCourseOrExam::from_exercise_and_user_exercise_state(
            &exercise,
            &user_exercise_state,
        )?;
        Ok(Self {
            exercise,
            user_exercise_state,
            type_data: state,
        })
    }

    /// Provides a reference to the inner `Exercise`.
    pub fn exercise(&self) -> &Exercise {
        &self.exercise
    }

    /// Provides a reference to the inner `UserExerciseState`.
    pub fn user_exercise_state(&self) -> &UserExerciseState {
        &self.user_exercise_state
    }

    pub fn exercise_context(&self) -> &EwusCourseOrExam {
        &self.type_data
    }

    pub fn set_user_exercise_state(
        &mut self,
        user_exercise_state: UserExerciseState,
    ) -> ModelResult<()> {
        self.type_data = EwusCourseOrExam::from_exercise_and_user_exercise_state(
            &self.exercise,
            &user_exercise_state,
        )?;
        self.user_exercise_state = user_exercise_state;
        Ok(())
    }

    pub fn is_exam_exercise(&self) -> bool {
        match self.type_data {
            EwusCourseOrExam::Course(_) => false,
            EwusCourseOrExam::Exam(_) => true,
        }
    }
}

pub struct EwusCourse {
    pub course_id: Uuid,
    pub course_instance_id: Uuid,
}

pub struct EwusExam {
    pub exam_id: Uuid,
}

pub enum EwusContext<C, E> {
    Course(C),
    Exam(E),
}

pub enum EwusCourseOrExam {
    Course(EwusCourse),
    Exam(EwusExam),
}

impl EwusCourseOrExam {
    pub fn from_exercise_and_user_exercise_state(
        exercise: &Exercise,
        user_exercise_state: &UserExerciseState,
    ) -> ModelResult<Self> {
        if exercise.id == user_exercise_state.exercise_id {
            let course_id = exercise.course_id;
            let course_instance_id = user_exercise_state.course_instance_id;
            let exam_id = exercise.exam_id;
            match (course_id, course_instance_id, exam_id) {
                (None, None, Some(exam_id)) => Ok(Self::Exam(EwusExam { exam_id })),
                (Some(course_id), Some(course_instance_id), None) => Ok(Self::Course(EwusCourse {
                    course_id,
                    course_instance_id,
                })),
                _ => Err(ModelError::new(
                    ModelErrorType::Generic,
                    "Invalid initializer data.".to_string(),
                    None,
                )),
            }
        } else {
            Err(ModelError::new(
                ModelErrorType::Generic,
                "Exercise doesn't match the state.".to_string(),
                None,
            ))
        }
    }
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct CourseInstanceUserPoints {
    pub user_id: Uuid,
    pub points_for_each_chapter: Vec<CourseInstanceUserPointsInner>,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct CourseInstanceUserPointsInner {
    pub chapter_number: i32,
    pub points_for_chapter: f32,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct ExamUserPoints {
    pub user_id: Uuid,
    pub email: String,
    pub points_for_exercise: Vec<ExamUserPointsInner>,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct ExamUserPointsInner {
    pub exercise_id: Uuid,
    pub score_given: f32,
}

pub fn stream_course_instance_points(
    conn: &mut PgConnection,
    course_instance_id: Uuid,
) -> impl Stream<Item = sqlx::Result<CourseInstanceUserPoints>> + '_ {
    sqlx::query!(
        "
SELECT user_id,
  to_jsonb(array_agg(to_jsonb(uue) - 'email' - 'user_id')) AS points_for_each_chapter
FROM (
    SELECT ud.email,
      u.id AS user_id,
      c.chapter_number,
      COALESCE(SUM(ues.score_given), 0) AS points_for_chapter
    FROM user_exercise_states ues
      JOIN users u ON u.id = ues.user_id
      JOIN user_details ud ON ud.user_id = u.id
      JOIN exercises e ON e.id = ues.exercise_id
      JOIN chapters c on e.chapter_id = c.id
    WHERE ues.course_instance_id = $1
      AND ues.deleted_at IS NULL
      AND c.deleted_at IS NULL
      AND u.deleted_at IS NULL
      AND e.deleted_at IS NULL
    GROUP BY ud.email,
      u.id,
      c.chapter_number
  ) as uue
GROUP BY user_id

",
        course_instance_id
    )
    .try_map(|i| {
        let user_id = i.user_id;
        let points_for_each_chapter = i.points_for_each_chapter.unwrap_or(Value::Null);
        serde_json::from_value(points_for_each_chapter)
            .map(|points_for_each_chapter| CourseInstanceUserPoints {
                user_id,
                points_for_each_chapter,
            })
            .map_err(|e| sqlx::Error::Decode(Box::new(e)))
    })
    .fetch(conn)
}

pub fn stream_exam_points(
    conn: &mut PgConnection,
    exam_id: Uuid,
) -> impl Stream<Item = sqlx::Result<ExamUserPoints>> + '_ {
    sqlx::query!(
        "
SELECT user_id,
  email,
  to_jsonb(array_agg(to_jsonb(uue) - 'email' - 'user_id')) AS points_for_exercises
FROM (
    SELECT u.id AS user_id,
      ud.email,
      exercise_id,
      COALESCE(score_given, 0) as score_given
    FROM user_exercise_states ues
      JOIN users u ON u.id = ues.user_id
      JOIN user_details ud ON ud.user_id = u.id
      JOIN exercises e ON e.id = ues.exercise_id
    WHERE ues.exam_id = $1
      AND ues.deleted_at IS NULL
      AND u.deleted_at IS NULL
      AND e.deleted_at IS NULL
  ) as uue
GROUP BY user_id,
  email
",
        exam_id
    )
    .try_map(|i| {
        let user_id = i.user_id;
        let points_for_exercises = i.points_for_exercises.unwrap_or(Value::Null);
        serde_json::from_value(points_for_exercises)
            .map(|points_for_exercise| ExamUserPoints {
                user_id,
                points_for_exercise,
                email: i.email,
            })
            .map_err(|e| sqlx::Error::Decode(Box::new(e)))
    })
    .fetch(conn)
}

pub async fn get_course_users_counts_by_exercise(
    conn: &mut PgConnection,
    course_id: Uuid,
) -> ModelResult<Vec<ExerciseUserCounts>> {
    let res = sqlx::query_as!(
        ExerciseUserCounts,
        r#"
SELECT exercises.name as exercise_name,
  exercises.order_number as exercise_order_number,
  pages.order_number as page_order_number,
  chapters.chapter_number,
  stat_data.*
FROM (
    SELECT exercise_id,
      COUNT(DISTINCT user_id) FILTER (
        WHERE ues.activity_progress = 'completed'
      ) as n_users_attempted,
      COUNT(DISTINCT user_id) FILTER (
        WHERE ues.score_given IS NOT NULL
          and ues.score_given > 0
          AND ues.activity_progress = 'completed'
      ) as n_users_with_some_points,
      COUNT(DISTINCT user_id) FILTER (
        WHERE ues.score_given IS NOT NULL
          and ues.score_given >= exercises.score_maximum
          and ues.activity_progress = 'completed'
      ) as n_users_with_max_points
    FROM exercises
      JOIN user_exercise_states ues on exercises.id = ues.exercise_id
    WHERE exercises.course_id = $1
      AND exercises.deleted_at IS NULL
      AND ues.deleted_at IS NULL
    GROUP BY exercise_id
  ) as stat_data
  JOIN exercises ON stat_data.exercise_id = exercises.id
  JOIN pages on exercises.page_id = pages.id
  JOIN chapters on pages.chapter_id = chapters.id
WHERE exercises.deleted_at IS NULL
  AND pages.deleted_at IS NULL
  AND chapters.deleted_at IS NULL
          "#,
        course_id
    )
    .fetch_all(conn)
    .await?;
    Ok(res)
}

#[cfg(test)]
mod tests {
    use chrono::TimeZone;

    use super::*;
    use crate::test_helper::*;

    mod getting_single_module_course_instance_metrics {
        use super::*;

        #[tokio::test]
        async fn works_without_any_user_exercise_states() {
            insert_data!(:tx, :user, :org, :course, :instance, :course_module);
            let res = get_single_module_course_instance_metrics(
                tx.as_mut(),
                instance.id,
                course_module.id,
                user,
            )
            .await;
            assert!(res.is_ok())
        }
    }

    #[test]
    fn merges_course_modules_with_metrics() {
        let timestamp = Utc.with_ymd_and_hms(2022, 6, 22, 0, 0, 0).unwrap();
        let module_id = Uuid::parse_str("9e831ecc-9751-42f1-ae7e-9b2f06e523e8").unwrap();
        let course_modules = vec![CourseModule::new(
            module_id,
            Uuid::parse_str("3fa4bee6-7390-415e-968f-ecdc5f28330e").unwrap(),
        )
        .set_timestamps(timestamp, timestamp, None)
        .set_registration_info(None, Some(5.0), None, false)];
        let course_metrics_by_course_module_id = HashMap::from([(
            module_id,
            CourseInstanceExerciseMetrics {
                course_module_id: module_id,
                total_exercises: Some(4),
                score_maximum: Some(10),
            },
        )]);
        let user_metrics_by_course_module_id = HashMap::from([(
            module_id,
            UserCourseInstanceMetrics {
                course_module_id: module_id,
                score_given: Some(1.0),
                attempted_exercises: Some(3),
            },
        )]);
        let metrics = merge_modules_with_metrics(
            course_modules,
            &course_metrics_by_course_module_id,
            &user_metrics_by_course_module_id,
            "Default module",
        )
        .unwrap();
        assert_eq!(metrics.len(), 1);
        let metric = metrics.first().unwrap();
        assert_eq!(metric.attempted_exercises, Some(3));
        assert_eq!(&metric.course_module_name, "Default module");
        assert_eq!(metric.score_given, 1.0);
        assert_eq!(metric.score_maximum, Some(10));
        assert_eq!(metric.total_exercises, Some(4));
    }
}