headless_lms_models/library/
course_stats.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
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
use crate::library::TimeGranularity;
use crate::{prelude::*, roles::UserRole};
use std::collections::HashMap;

/// A generic result representing a count metric over a time period.
/// When the time period is not applicable (for overall totals), `period` will be `None`.
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct CountResult {
    /// The start of the time period (e.g., day, week, month) associated with this count.
    /// For overall totals, this will be `None`.
    pub period: Option<DateTime<Utc>>,
    /// The count (for example, the number of users).
    pub count: i64,
}

/// A generic result representing an average metric over a time period.
/// The average value (e.g. average time in seconds) may be absent if no data is available.
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct AverageMetric {
    /// The start of the time period (e.g., day, week, month) associated with this metric.
    pub period: Option<DateTime<Utc>>,
    /// The average value. For example, the average time (in seconds) from course start to first submission.
    pub average: Option<f64>,
}

/// Represents cohort activity metrics for both weekly and daily cohorts.
/// For daily cohorts, `offset` will be populated (and `activity_period` may be computed from it);
/// for weekly cohorts, `offset` will be `None` and `activity_period` indicates the week start.
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct CohortActivity {
    /// The start date of the cohort (either day or week).
    pub cohort_start: Option<DateTime<Utc>>,
    /// The activity period (for example, the start of the week or the computed activity day).
    pub activity_period: Option<DateTime<Utc>>,
    /// The day offset from the cohort start (only applicable for daily cohorts).
    pub offset: Option<i32>,
    /// The number of active users in this cohort for the given period.
    pub active_users: i64,
}

/// Gets user IDs to exclude from course statistics for a single course.
/// Excludes users with any role other than MaterialViewer in the course, its organization, or globally.
async fn get_user_ids_to_exclude_from_course_stats(
    conn: &mut PgConnection,
    course_id: Uuid,
) -> ModelResult<Vec<Uuid>> {
    let roles = crate::roles::get_course_related_roles(conn, course_id).await?;
    let user_ids: Vec<_> = roles
        .iter()
        .filter(|role| role.role != UserRole::MaterialViewer)
        .map(|role| role.user_id)
        .collect::<std::collections::HashSet<_>>()
        .into_iter()
        .collect();
    Ok(user_ids)
}

/// Gets user IDs to exclude from course language group statistics.
/// Uses a single query to get all roles and filters out MaterialViewer roles.
async fn get_user_ids_to_exclude_from_course_language_group_stats(
    conn: &mut PgConnection,
    course_language_group_id: Uuid,
) -> ModelResult<Vec<Uuid>> {
    let roles =
        crate::roles::get_course_language_group_related_roles(conn, course_language_group_id)
            .await?;
    let user_ids: Vec<_> = roles
        .iter()
        .filter(|role| role.role != UserRole::MaterialViewer)
        .map(|role| role.user_id)
        .collect::<std::collections::HashSet<_>>()
        .into_iter()
        .collect();
    Ok(user_ids)
}

/// Total unique users in the course settings table.
pub async fn get_total_users_started_course(
    conn: &mut PgConnection,
    course_id: Uuid,
) -> ModelResult<CountResult> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let res = sqlx::query_as!(
        CountResult,
        r#"
SELECT NULL::timestamptz AS "period",
       COUNT(DISTINCT user_id) AS "count!"
FROM user_course_settings
WHERE current_course_id = $1
  AND deleted_at IS NULL
  AND user_id != ALL($2);
        "#,
        course_id,
        &exclude_user_ids
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

/// Total unique users who have completed the course.
pub async fn get_total_users_completed_course(
    conn: &mut PgConnection,
    course_id: Uuid,
) -> ModelResult<CountResult> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let res = sqlx::query_as!(
        CountResult,
        r#"
SELECT NULL::timestamptz AS "period",
       COUNT(DISTINCT user_id) AS "count!"
FROM course_module_completions
WHERE course_id = $1
  AND deleted_at IS NULL
  AND user_id != ALL($2);
        "#,
        course_id,
        &exclude_user_ids
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

/// Total unique users who have returned at least one exercise.
pub async fn get_total_users_returned_at_least_one_exercise(
    conn: &mut PgConnection,
    course_id: Uuid,
) -> ModelResult<CountResult> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let res = sqlx::query_as!(
        CountResult,
        r#"
SELECT NULL::timestamptz AS "period",
  COUNT(DISTINCT user_id) AS "count!"
FROM exercise_slide_submissions
WHERE course_id = $1
  AND deleted_at IS NULL
  AND user_id != ALL($2);
      "#,
        course_id,
        &exclude_user_ids
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

/// Total unique users who have completed the course in all language versions
pub async fn get_total_users_completed_all_language_versions_of_a_course(
    conn: &mut PgConnection,
    course_language_group_id: Uuid,
) -> ModelResult<CountResult> {
    let exclude_user_ids =
        get_user_ids_to_exclude_from_course_language_group_stats(conn, course_language_group_id)
            .await?;

    let res = sqlx::query_as!(
        CountResult,
        r#"
SELECT NULL::timestamptz AS "period",
  COUNT(DISTINCT user_id) AS "count!"
FROM course_module_completions
WHERE course_id IN (
    SELECT id
    FROM courses
    WHERE course_language_group_id = $1
      AND deleted_at IS NULL
  )
  AND deleted_at IS NULL
  AND user_id != ALL($2);
    "#,
        course_language_group_id,
        &exclude_user_ids
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

/// Total unique users who have started the course in all language versions
pub async fn get_total_users_started_all_language_versions_of_a_course(
    conn: &mut PgConnection,
    course_language_group_id: Uuid,
) -> ModelResult<CountResult> {
    let exclude_user_ids =
        get_user_ids_to_exclude_from_course_language_group_stats(conn, course_language_group_id)
            .await?;

    let res = sqlx::query_as!(
        CountResult,
        r#"
SELECT NULL::timestamptz AS "period",
  COUNT(DISTINCT user_id) AS "count!"
FROM user_course_settings
WHERE current_course_id IN (
    SELECT id
    FROM courses
    WHERE course_language_group_id = $1
      AND deleted_at IS NULL
  )
  AND deleted_at IS NULL
  AND user_id != ALL($2);
    "#,
        course_language_group_id,
        &exclude_user_ids
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

/// Get unique users starting counts with specified time granularity.
///
/// The time_window parameter controls how far back to look:
/// - For Year granularity: number of years
/// - For Month granularity: number of months
/// - For Day granularity: number of days
pub async fn unique_users_starting_history(
    conn: &mut PgConnection,
    course_id: Uuid,
    granularity: TimeGranularity,
    time_window: u16,
) -> ModelResult<Vec<CountResult>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let (interval_unit, time_unit) = granularity.get_sql_units();

    let res = sqlx::query_as!(
        CountResult,
        r#"
SELECT DATE_TRUNC($5, created_at) AS "period",
  COUNT(DISTINCT user_id) AS "count!"
FROM user_course_settings
WHERE current_course_id = $1
  AND deleted_at IS NULL
  AND NOT user_id = ANY($2)
  AND created_at >= NOW() - ($3 || ' ' || $4)::INTERVAL
GROUP BY "period"
ORDER BY "period"
        "#,
        course_id,
        &exclude_user_ids,
        &time_window.to_string(),
        interval_unit,
        time_unit,
    )
    .fetch_all(conn)
    .await?;

    Ok(res)
}

/// Get first exercise submission counts with specified time granularity.
///
/// The time_window parameter controls how far back to look:
/// - For Year granularity: number of years
/// - For Month granularity: number of months
/// - For Day granularity: number of days
pub async fn first_exercise_submissions_history(
    conn: &mut PgConnection,
    course_id: Uuid,
    granularity: TimeGranularity,
    time_window: u16,
) -> ModelResult<Vec<CountResult>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let (interval_unit, time_unit) = granularity.get_sql_units();

    let res = sqlx::query_as!(
        CountResult,
        r#"
SELECT DATE_TRUNC($5, first_submission) AS "period",
  COUNT(user_id) AS "count!"
FROM (
    SELECT user_id,
      MIN(created_at) AS first_submission
    FROM exercise_slide_submissions
    WHERE course_id = $1
      AND deleted_at IS NULL
      AND NOT user_id = ANY($2)
      AND created_at >= NOW() - ($3 || ' ' || $4)::INTERVAL
    GROUP BY user_id
  ) AS first_submissions
GROUP BY "period"
ORDER BY "period"
        "#,
        course_id,
        &exclude_user_ids,
        &time_window.to_string(),
        interval_unit,
        time_unit,
    )
    .fetch_all(conn)
    .await?;

    Ok(res)
}

/// Get users returning exercises counts with specified time granularity.
///
/// The time_window parameter controls how far back to look:
/// - For Year granularity: number of years
/// - For Month granularity: number of months
/// - For Day granularity: number of days
pub async fn users_returning_exercises_history(
    conn: &mut PgConnection,
    course_id: Uuid,
    granularity: TimeGranularity,
    time_window: u16,
) -> ModelResult<Vec<CountResult>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let (interval_unit, time_unit) = granularity.get_sql_units();

    let res = sqlx::query_as!(
        CountResult,
        r#"
SELECT DATE_TRUNC($5, created_at) AS "period",
  COUNT(DISTINCT user_id) AS "count!"
FROM exercise_slide_submissions
WHERE course_id = $1
  AND deleted_at IS NULL
  AND NOT user_id = ANY($2)
  AND created_at >= NOW() - ($3 || ' ' || $4)::INTERVAL
GROUP BY "period"
ORDER BY "period"
        "#,
        course_id,
        &exclude_user_ids,
        &time_window.to_string(),
        interval_unit,
        time_unit,
    )
    .fetch_all(conn)
    .await?;

    Ok(res)
}

/// Get average time from course start to first exercise submission with specified time granularity.
///
/// The time_window parameter controls how far back to look:
/// - For Year granularity: number of years
/// - For Month granularity: number of months
/// - For Day granularity: number of days
///
/// Returns the average time in seconds.
pub async fn avg_time_to_first_submission_history(
    conn: &mut PgConnection,
    course_id: Uuid,
    granularity: TimeGranularity,
    time_window: u16,
) -> ModelResult<Vec<AverageMetric>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let (interval_unit, time_unit) = granularity.get_sql_units();

    let res = sqlx::query_as!(
        AverageMetric,
        r#"
SELECT DATE_TRUNC($5, user_start) AS "period",
  AVG(
    EXTRACT(
      EPOCH
      FROM (first_submission - user_start)
    )
  )::float8 AS "average"
FROM (
    SELECT u.user_id,
      MIN(u.created_at) AS user_start,
      MIN(e.created_at) AS first_submission
    FROM user_course_settings u
      JOIN exercise_slide_submissions e ON u.user_id = e.user_id
      AND e.course_id = $1
      AND e.deleted_at IS NULL
    WHERE u.current_course_id = $1
      AND u.deleted_at IS NULL
      AND NOT u.user_id = ANY($2)
      AND u.created_at >= NOW() - ($3 || ' ' || $4)::INTERVAL
    GROUP BY u.user_id
  ) AS timings
GROUP BY "period"
ORDER BY "period"
        "#,
        course_id,
        &exclude_user_ids,
        &time_window.to_string(),
        interval_unit,
        time_unit,
    )
    .fetch_all(conn)
    .await?;

    Ok(res)
}

/// Get cohort activity statistics with specified time granularity.
///
/// Parameters:
/// - history_window: How far back to look for cohorts
/// - tracking_window: How long to track activity after each cohort's start
///
/// For each granularity:
/// - Year: windows in years, tracking monthly activity
/// - Month: windows in months, tracking weekly activity
/// - Day: windows in days, tracking daily activity
///
/// Cohorts are defined by when users first submitted an exercise.
pub async fn get_cohort_activity_history(
    conn: &mut PgConnection,
    course_id: Uuid,
    granularity: TimeGranularity,
    history_window: u16,
    tracking_window: u16,
) -> ModelResult<Vec<CohortActivity>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let (interval_unit, time_unit) = granularity.get_sql_units();

    Ok(sqlx::query_as!(
        CohortActivity,
        r#"
WITH first_activity AS (
  SELECT user_id,
    MIN(DATE_TRUNC($6, created_at)) AS first_active_at
  FROM exercise_slide_submissions
  WHERE course_id = $1
    AND created_at >= NOW() - ($3 || ' ' || $4)::INTERVAL
    AND deleted_at IS NULL
    AND NOT user_id = ANY($2)
  GROUP BY user_id
),
cohort AS (
  SELECT user_id,
    first_active_at AS cohort_start
  FROM first_activity
)
SELECT c.cohort_start AS "cohort_start",
  DATE_TRUNC($6, s.created_at) AS "activity_period",
  CASE
    WHEN $6 = 'day' THEN EXTRACT(
      DAY
      FROM (DATE_TRUNC('day', s.created_at) - c.cohort_start)
    )::integer
    WHEN $6 = 'week' THEN EXTRACT(
      WEEK
      FROM (
          DATE_TRUNC('week', s.created_at) - c.cohort_start
        )
    )::integer
    WHEN $6 = 'month' THEN (
      EXTRACT(
        YEAR
        FROM s.created_at
      ) - EXTRACT(
        YEAR
        FROM c.cohort_start
      )
    )::integer * 12 + (
      EXTRACT(
        MONTH
        FROM s.created_at
      ) - EXTRACT(
        MONTH
        FROM c.cohort_start
      )
    )::integer
    ELSE NULL::integer
  END AS "offset",
  COUNT(DISTINCT s.user_id) AS "active_users!"
FROM cohort c
  JOIN exercise_slide_submissions s ON (
    c.user_id = s.user_id
    AND s.course_id = $1
  )
  AND s.created_at >= c.cohort_start
  AND s.created_at < c.cohort_start + ($5 || ' ' || $4)::INTERVAL
  AND s.deleted_at IS NULL
GROUP BY c.cohort_start,
  "activity_period",
  "offset"
ORDER BY c.cohort_start,
  "offset"
        "#,
        course_id,
        &exclude_user_ids,
        &history_window.to_string(),
        interval_unit,
        &tracking_window.to_string(),
        time_unit,
    )
    .fetch_all(conn)
    .await?)
}

/// Get course completion counts with specified time granularity.
///
/// The time_window parameter controls how far back to look:
/// - For Year granularity: number of years
/// - For Month granularity: number of months
/// - For Day granularity: number of days
pub async fn course_completions_history(
    conn: &mut PgConnection,
    course_id: Uuid,
    granularity: TimeGranularity,
    time_window: u16,
) -> ModelResult<Vec<CountResult>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let (interval_unit, time_unit) = granularity.get_sql_units();

    let res = sqlx::query_as!(
        CountResult,
        r#"
SELECT DATE_TRUNC($5, created_at) AS "period",
  COUNT(DISTINCT user_id) AS "count!"
FROM course_module_completions
WHERE course_id = $1
  AND prerequisite_modules_completed = TRUE
  AND needs_to_be_reviewed = FALSE
  AND passed = TRUE
  AND deleted_at IS NULL
  AND NOT user_id = ANY($2)
  AND created_at >= NOW() - ($3 || ' ' || $4)::INTERVAL
GROUP BY "period"
ORDER BY "period"
          "#,
        course_id,
        &exclude_user_ids,
        &time_window.to_string(),
        interval_unit,
        time_unit,
    )
    .fetch_all(conn)
    .await?;

    Ok(res)
}

/// Get completion counts for all language versions of a course with specified time granularity.
///
/// The time_window parameter controls how far back to look:
/// - For Year granularity: number of years
/// - For Month granularity: number of months
/// - For Day granularity: number of days
pub async fn course_completions_history_all_language_versions(
    conn: &mut PgConnection,
    course_language_group_id: Uuid,
    granularity: TimeGranularity,
    time_window: u16,
) -> ModelResult<Vec<CountResult>> {
    let exclude_user_ids =
        get_user_ids_to_exclude_from_course_language_group_stats(conn, course_language_group_id)
            .await?;
    let (interval_unit, time_unit) = granularity.get_sql_units();

    let res = sqlx::query_as!(
        CountResult,
        r#"
SELECT DATE_TRUNC($5, created_at) AS "period",
COUNT(DISTINCT user_id) AS "count!"
FROM course_module_completions
WHERE course_id IN (
    SELECT id
    FROM courses
    WHERE course_language_group_id = $1
      AND deleted_at IS NULL
  )
  AND prerequisite_modules_completed = TRUE
  AND needs_to_be_reviewed = FALSE
  AND passed = TRUE
  AND deleted_at IS NULL
  AND NOT user_id = ANY($2)
  AND created_at >= NOW() - ($3 || ' ' || $4)::INTERVAL
GROUP BY "period"
ORDER BY "period"
        "#,
        course_language_group_id,
        &exclude_user_ids,
        &time_window.to_string(),
        interval_unit,
        time_unit,
    )
    .fetch_all(conn)
    .await?;

    Ok(res)
}

/// Get unique users starting counts for all language versions with specified time granularity.
///
/// The time_window parameter controls how far back to look:
/// - For Year granularity: number of years
/// - For Month granularity: number of months
/// - For Day granularity: number of days
pub async fn unique_users_starting_history_all_language_versions(
    conn: &mut PgConnection,
    course_language_group_id: Uuid,
    granularity: TimeGranularity,
    time_window: u16,
) -> ModelResult<Vec<CountResult>> {
    let exclude_user_ids =
        get_user_ids_to_exclude_from_course_language_group_stats(conn, course_language_group_id)
            .await?;
    let (interval_unit, time_unit) = granularity.get_sql_units();

    let res = sqlx::query_as!(
        CountResult,
        r#"
SELECT DATE_TRUNC($5, created_at) AS "period",
  COUNT(DISTINCT user_id) AS "count!"
FROM user_course_settings
WHERE current_course_id IN (
    SELECT id
    FROM courses
    WHERE course_language_group_id = $1
      AND deleted_at IS NULL
  )
  AND deleted_at IS NULL
  AND NOT user_id = ANY($2)
  AND created_at >= NOW() - ($3 || ' ' || $4)::INTERVAL
GROUP BY "period"
ORDER BY "period"
        "#,
        course_language_group_id,
        &exclude_user_ids,
        &time_window.to_string(),
        interval_unit,
        time_unit,
    )
    .fetch_all(conn)
    .await?;

    Ok(res)
}

/// Total unique users in the course settings table, grouped by course instance.
///
/// Returns a HashMap where keys are course instance IDs and values are the total user counts
/// for that instance.
pub async fn get_total_users_started_course_by_instance(
    conn: &mut PgConnection,
    course_id: Uuid,
) -> ModelResult<HashMap<Uuid, CountResult>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let results = sqlx::query!(
        r#"
SELECT current_course_instance_id AS "instance_id!",
  NULL::timestamptz AS "period",
  COUNT(DISTINCT user_id) AS "count!"
FROM user_course_settings
WHERE current_course_id = $1
  AND deleted_at IS NULL
  AND user_id != ALL($2)
GROUP BY current_course_instance_id
        "#,
        course_id,
        &exclude_user_ids
    )
    .fetch_all(conn)
    .await?;

    let mut grouped_results = HashMap::new();
    for row in results {
        let count_result = CountResult {
            period: row.period,
            count: row.count,
        };
        grouped_results.insert(row.instance_id, count_result);
    }

    Ok(grouped_results)
}

/// Total unique users who have completed the course, grouped by course instance.
///
/// Returns a HashMap where keys are course instance IDs and values are the completion counts
/// for that instance.
pub async fn get_total_users_completed_course_by_instance(
    conn: &mut PgConnection,
    course_id: Uuid,
) -> ModelResult<HashMap<Uuid, CountResult>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let results = sqlx::query!(
        r#"
SELECT ucs.current_course_instance_id AS "instance_id!",
  NULL::timestamptz AS "period",
  COUNT(DISTINCT c.user_id) AS "count!"
FROM course_module_completions c
JOIN user_course_settings ucs ON c.user_id = ucs.user_id
  AND ucs.current_course_id = c.course_id
WHERE c.course_id = $1
  AND c.deleted_at IS NULL
  AND c.user_id != ALL($2)
GROUP BY ucs.current_course_instance_id
        "#,
        course_id,
        &exclude_user_ids
    )
    .fetch_all(conn)
    .await?;

    let mut grouped_results = HashMap::new();
    for row in results {
        let count_result = CountResult {
            period: row.period,
            count: row.count,
        };
        grouped_results.insert(row.instance_id, count_result);
    }

    Ok(grouped_results)
}

/// Total unique users who have returned at least one exercise, grouped by course instance.
///
/// Returns a HashMap where keys are course instance IDs and values are the submission counts
/// for that instance.
pub async fn get_total_users_returned_at_least_one_exercise_by_instance(
    conn: &mut PgConnection,
    course_id: Uuid,
) -> ModelResult<HashMap<Uuid, CountResult>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let results = sqlx::query!(
        r#"
SELECT ucs.current_course_instance_id AS "instance_id!",
  NULL::timestamptz AS "period",
  COUNT(DISTINCT ess.user_id) AS "count!"
FROM exercise_slide_submissions ess
JOIN user_course_settings ucs ON ess.user_id = ucs.user_id
  AND ucs.current_course_id = ess.course_id
WHERE ess.course_id = $1
  AND ess.deleted_at IS NULL
  AND ess.user_id != ALL($2)
GROUP BY ucs.current_course_instance_id
        "#,
        course_id,
        &exclude_user_ids
    )
    .fetch_all(conn)
    .await?;

    let mut grouped_results = HashMap::new();
    for row in results {
        let count_result = CountResult {
            period: row.period,
            count: row.count,
        };
        grouped_results.insert(row.instance_id, count_result);
    }

    Ok(grouped_results)
}

/// Get course completion counts with specified time granularity, grouped by course instance.
///
/// Returns a HashMap where keys are course instance IDs and values are vectors of completion counts
/// over time for that instance.
///
/// The time_window parameter controls how far back to look:
/// - For Year granularity: number of years
/// - For Month granularity: number of months
/// - For Day granularity: number of days
pub async fn course_completions_history_by_instance(
    conn: &mut PgConnection,
    course_id: Uuid,
    granularity: TimeGranularity,
    time_window: u16,
) -> ModelResult<HashMap<Uuid, Vec<CountResult>>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let (interval_unit, time_unit) = granularity.get_sql_units();

    // Get completions joined with user_course_settings to get instance information
    let results = sqlx::query!(
        r#"
WITH completions AS (
SELECT c.user_id,
  c.created_at,
  ucs.current_course_instance_id
FROM course_module_completions c
  JOIN user_course_settings ucs ON c.user_id = ucs.user_id
  AND ucs.current_course_id = c.course_id
WHERE c.course_id = $1
  AND c.prerequisite_modules_completed = TRUE
  AND c.needs_to_be_reviewed = FALSE
  AND c.passed = TRUE
  AND c.deleted_at IS NULL
  AND NOT c.user_id = ANY($2)
  AND c.created_at >= NOW() - ($3 || ' ' || $4)::INTERVAL
)
SELECT current_course_instance_id AS "instance_id!",
DATE_TRUNC($5, created_at) AS "period",
COUNT(DISTINCT user_id) AS "count!"
FROM completions
GROUP BY current_course_instance_id,
period
ORDER BY current_course_instance_id,
period "#,
        course_id,
        &exclude_user_ids,
        &time_window.to_string(),
        interval_unit,
        time_unit,
    )
    .fetch_all(conn)
    .await?;

    // Convert the flat results into a HashMap grouped by instance_id
    let mut grouped_results: HashMap<Uuid, Vec<CountResult>> = HashMap::new();

    for row in results {
        let count_result = CountResult {
            period: row.period,
            count: row.count,
        };

        grouped_results
            .entry(row.instance_id)
            .or_default()
            .push(count_result);
    }

    Ok(grouped_results)
}

/// Get unique users starting counts with specified time granularity, grouped by course instance.
///
/// Returns a HashMap where keys are course instance IDs and values are vectors of user counts
/// over time for that instance.
///
/// The time_window parameter controls how far back to look:
/// - For Year granularity: number of years
/// - For Month granularity: number of months
/// - For Day granularity: number of days
pub async fn unique_users_starting_history_by_instance(
    conn: &mut PgConnection,
    course_id: Uuid,
    granularity: TimeGranularity,
    time_window: u16,
) -> ModelResult<HashMap<Uuid, Vec<CountResult>>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let (interval_unit, time_unit) = granularity.get_sql_units();

    let results = sqlx::query!(
        r#"
SELECT current_course_instance_id AS "instance_id!",
DATE_TRUNC($5, created_at) AS "period",
COUNT(DISTINCT user_id) AS "count!"
FROM user_course_settings
WHERE current_course_id = $1
AND deleted_at IS NULL
AND NOT user_id = ANY($2)
AND created_at >= NOW() - ($3 || ' ' || $4)::INTERVAL
GROUP BY current_course_instance_id,
period
ORDER BY current_course_instance_id,
period
    "#,
        course_id,
        &exclude_user_ids,
        &time_window.to_string(),
        interval_unit,
        time_unit,
    )
    .fetch_all(conn)
    .await?;

    // Convert the flat results into a HashMap grouped by instance_id
    let mut grouped_results: HashMap<Uuid, Vec<CountResult>> = HashMap::new();

    for row in results {
        let count_result = CountResult {
            period: row.period,
            count: row.count,
        };

        grouped_results
            .entry(row.instance_id)
            .or_default()
            .push(count_result);
    }

    Ok(grouped_results)
}

/// Get first exercise submission counts with specified time granularity, grouped by course instance.
///
/// Returns a HashMap where keys are course instance IDs and values are vectors of submission counts
/// over time for that instance.
///
/// The time_window parameter controls how far back to look:
/// - For Year granularity: number of years
/// - For Month granularity: number of months
/// - For Day granularity: number of days
pub async fn first_exercise_submissions_history_by_instance(
    conn: &mut PgConnection,
    course_id: Uuid,
    granularity: TimeGranularity,
    time_window: u16,
) -> ModelResult<HashMap<Uuid, Vec<CountResult>>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let (interval_unit, time_unit) = granularity.get_sql_units();

    let results = sqlx::query!(
        r#"
WITH first_submissions AS (
SELECT user_id,
  MIN(created_at) AS first_submission
FROM exercise_slide_submissions
WHERE course_id = $1
  AND deleted_at IS NULL
  AND NOT user_id = ANY($2)
  AND created_at >= NOW() - ($3 || ' ' || $4)::INTERVAL
GROUP BY user_id
)
SELECT ucs.current_course_instance_id AS "instance_id!",
DATE_TRUNC($5, fs.first_submission) AS "period",
COUNT(fs.user_id) AS "count!"
FROM first_submissions fs
JOIN user_course_settings ucs ON fs.user_id = ucs.user_id
AND ucs.current_course_id = $1
GROUP BY ucs.current_course_instance_id,
period
ORDER BY ucs.current_course_instance_id,
period
    "#,
        course_id,
        &exclude_user_ids,
        &time_window.to_string(),
        interval_unit,
        time_unit,
    )
    .fetch_all(conn)
    .await?;

    // Convert the flat results into a HashMap grouped by instance_id
    let mut grouped_results: HashMap<Uuid, Vec<CountResult>> = HashMap::new();

    for row in results {
        let count_result = CountResult {
            period: row.period,
            count: row.count,
        };

        grouped_results
            .entry(row.instance_id)
            .or_default()
            .push(count_result);
    }

    Ok(grouped_results)
}

/// Get users returning exercises counts with specified time granularity, grouped by course instance.
///
/// Returns a HashMap where keys are course instance IDs and values are vectors of user counts
/// over time for that instance.
///
/// The time_window parameter controls how far back to look:
/// - For Year granularity: number of years
/// - For Month granularity: number of months
/// - For Day granularity: number of days
pub async fn users_returning_exercises_history_by_instance(
    conn: &mut PgConnection,
    course_id: Uuid,
    granularity: TimeGranularity,
    time_window: u16,
) -> ModelResult<HashMap<Uuid, Vec<CountResult>>> {
    let exclude_user_ids = get_user_ids_to_exclude_from_course_stats(conn, course_id).await?;
    let (interval_unit, time_unit) = granularity.get_sql_units();

    let results = sqlx::query!(
        r#"
SELECT ucs.current_course_instance_id AS "instance_id!",
DATE_TRUNC($5, ess.created_at) AS "period",
COUNT(DISTINCT ess.user_id) AS "count!"
FROM exercise_slide_submissions ess
JOIN user_course_settings ucs ON ess.user_id = ucs.user_id
AND ucs.current_course_id = ess.course_id
WHERE ess.course_id = $1
AND ess.deleted_at IS NULL
AND NOT ess.user_id = ANY($2)
AND ess.created_at >= NOW() - ($3 || ' ' || $4)::INTERVAL
GROUP BY ucs.current_course_instance_id,
period
ORDER BY ucs.current_course_instance_id,
period
    "#,
        course_id,
        &exclude_user_ids,
        &time_window.to_string(),
        interval_unit,
        time_unit,
    )
    .fetch_all(conn)
    .await?;

    // Convert the flat results into a HashMap grouped by instance_id
    let mut grouped_results: HashMap<Uuid, Vec<CountResult>> = HashMap::new();

    for row in results {
        let count_result = CountResult {
            period: row.period,
            count: row.count,
        };

        grouped_results
            .entry(row.instance_id)
            .or_default()
            .push(count_result);
    }

    Ok(grouped_results)
}