headless_lms_models/
course_module_completion_registered_to_study_registries.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
use crate::{course_module_completions, prelude::*};
use rand::Rng;

#[derive(Clone, PartialEq, Deserialize, Serialize)]
pub struct CourseModuleCompletionRegisteredToStudyRegistry {
    pub id: Uuid,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub deleted_at: Option<DateTime<Utc>>,
    pub course_id: Uuid,
    pub course_module_completion_id: Uuid,
    pub course_module_id: Uuid,
    pub study_registry_registrar_id: Uuid,
    pub user_id: Uuid,
    pub real_student_number: String,
}

#[derive(Clone, PartialEq, Deserialize, Serialize)]
pub struct NewCourseModuleCompletionRegisteredToStudyRegistry {
    pub course_id: Uuid,
    pub course_module_completion_id: Uuid,
    pub course_module_id: Uuid,
    pub study_registry_registrar_id: Uuid,
    pub user_id: Uuid,
    pub real_student_number: String,
}

pub async fn insert(
    conn: &mut PgConnection,
    pkey_policy: PKeyPolicy<Uuid>,
    new_completion_registration: &NewCourseModuleCompletionRegisteredToStudyRegistry,
) -> ModelResult<Uuid> {
    let res = sqlx::query!(
        "
INSERT INTO course_module_completion_registered_to_study_registries (
    id,
    course_id,
    course_module_completion_id,
    course_module_id,
    study_registry_registrar_id,
    user_id,
    real_student_number
  )
VALUES (
    $1,
    $2,
    $3,
    $4,
    $5,
    $6,
    $7
  )
RETURNING id
        ",
        pkey_policy.into_uuid(),
        new_completion_registration.course_id,
        new_completion_registration.course_module_completion_id,
        new_completion_registration.course_module_id,
        new_completion_registration.study_registry_registrar_id,
        new_completion_registration.user_id,
        new_completion_registration.real_student_number,
    )
    .fetch_one(conn)
    .await?;
    Ok(res.id)
}

pub async fn insert_bulk(
    conn: &mut PgConnection,
    new_completion_registrations: Vec<NewCourseModuleCompletionRegisteredToStudyRegistry>,
) -> ModelResult<Vec<Uuid>> {
    if new_completion_registrations.is_empty() {
        return Ok(vec![]);
    }

    // Create separate vectors for each column
    let ids: Vec<Uuid> = (0..new_completion_registrations.len())
        .map(|_| Uuid::new_v4())
        .collect();
    let course_ids: Vec<Uuid> = new_completion_registrations
        .iter()
        .map(|r| r.course_id)
        .collect();
    let completion_ids: Vec<Uuid> = new_completion_registrations
        .iter()
        .map(|r| r.course_module_completion_id)
        .collect();
    let module_ids: Vec<Uuid> = new_completion_registrations
        .iter()
        .map(|r| r.course_module_id)
        .collect();
    let registrar_ids: Vec<Uuid> = new_completion_registrations
        .iter()
        .map(|r| r.study_registry_registrar_id)
        .collect();
    let user_ids: Vec<Uuid> = new_completion_registrations
        .iter()
        .map(|r| r.user_id)
        .collect();
    let student_numbers: Vec<String> = new_completion_registrations
        .iter()
        .map(|r| r.real_student_number.clone())
        .collect();

    let res = sqlx::query!(
        r#"
INSERT INTO course_module_completion_registered_to_study_registries (
    id,
    course_id,
    course_module_completion_id,
    course_module_id,
    study_registry_registrar_id,
    user_id,
    real_student_number
)
SELECT * FROM UNNEST(
    $1::uuid[],
    $2::uuid[],
    $3::uuid[],
    $4::uuid[],
    $5::uuid[],
    $6::uuid[],
    $7::text[]
)
RETURNING id
        "#,
        &ids[..],
        &course_ids[..],
        &completion_ids[..],
        &module_ids[..],
        &registrar_ids[..],
        &user_ids[..],
        &student_numbers[..],
    )
    .fetch_all(conn)
    .await?;

    Ok(res.into_iter().map(|r| r.id).collect())
}

#[derive(Clone, PartialEq, Eq, Deserialize, Serialize, Debug)]
/// An object representing that a completion has been registered to a study registry.
pub struct RegisteredCompletion {
    /// Id of the completion that was registered to the study registry.
    pub completion_id: Uuid,
    /// The student number the completion was registed to.
    pub student_number: String,
    /// The registration date that is visible in the study registry for the user.
    pub registration_date: DateTime<Utc>,
}

pub async fn mark_completions_as_registered_to_study_registry(
    conn: &mut PgConnection,
    completions: Vec<RegisteredCompletion>,
    study_registry_registrar_id: Uuid,
) -> ModelResult<()> {
    if completions.is_empty() {
        return Ok(());
    }

    let ids: Vec<Uuid> = completions.iter().map(|x| x.completion_id).collect();
    let completions_by_id = course_module_completions::get_by_ids_as_map(conn, &ids).await?;

    // Validate all completions exist before proceeding
    for completion in &completions {
        if !completions_by_id.contains_key(&completion.completion_id) {
            return Err(ModelError::new(
                ModelErrorType::PreconditionFailed,
                format!(
                    "Cannot find completion with id: {}. This completion does not exist in the database.",
                    completion.completion_id
                ),
                None,
            ));
        }
    }

    let new_registrations: Vec<NewCourseModuleCompletionRegisteredToStudyRegistry> = completions
        .into_iter()
        .map(|completion| {
            let module_completion = completions_by_id.get(&completion.completion_id).unwrap();
            NewCourseModuleCompletionRegisteredToStudyRegistry {
                course_id: module_completion.course_id,
                course_module_completion_id: completion.completion_id,
                course_module_id: module_completion.course_module_id,
                study_registry_registrar_id,
                user_id: module_completion.user_id,
                real_student_number: completion.student_number,
            }
        })
        .collect();

    let mut tx = conn.begin().await?;

    insert_bulk(&mut tx, new_registrations).await?;

    // We delete duplicates straight away, this way we can still see if the study registry keeps pushing the same completion multiple times
    // Using a random chance to optimize the performance of the operation
    let mut rng = rand::rng();
    let delete_all = rng.random_range(0..50) == 0; // 1 in 50 chance

    if delete_all {
        delete_all_duplicates(&mut tx).await?;
    } else {
        delete_duplicates_for_specific_completions(&mut tx, &ids).await?;
    }

    tx.commit().await?;

    Ok(())
}

pub async fn get_by_id(
    conn: &mut PgConnection,
    id: Uuid,
) -> ModelResult<CourseModuleCompletionRegisteredToStudyRegistry> {
    let res = sqlx::query_as!(
        CourseModuleCompletionRegisteredToStudyRegistry,
        "
SELECT *
FROM course_module_completion_registered_to_study_registries
WHERE id = $1
  AND deleted_at IS NULL
        ",
        id,
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

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

/// Get the number of students that have completed the course
pub async fn get_count_of_distinct_users_with_registrations_by_course_id(
    conn: &mut PgConnection,
    course_id: Uuid,
) -> ModelResult<i64> {
    let res = sqlx::query!(
        "
SELECT COUNT(DISTINCT user_id) as count
FROM course_module_completion_registered_to_study_registries
WHERE course_id = $1
  AND deleted_at IS NULL
",
        course_id,
    )
    .fetch_one(conn)
    .await?;
    Ok(res.count.unwrap_or(0))
}

pub async fn get_by_completion_id_and_registrar_id(
    conn: &mut PgConnection,
    completion_id: Uuid,
    study_registry_registrar_id: Uuid,
) -> ModelResult<Vec<CourseModuleCompletionRegisteredToStudyRegistry>> {
    let registrations = sqlx::query_as!(
        CourseModuleCompletionRegisteredToStudyRegistry,
        r#"
        SELECT *
        FROM course_module_completion_registered_to_study_registries
        WHERE course_module_completion_id = $1 AND study_registry_registrar_id = $2
        AND deleted_at IS NULL
        "#,
        completion_id,
        study_registry_registrar_id
    )
    .fetch_all(conn)
    .await?;

    Ok(registrations)
}

async fn delete_duplicates_for_specific_completions(
    conn: &mut PgConnection,
    completion_ids: &[Uuid],
) -> ModelResult<i64> {
    let res = sqlx::query!(
        r#"
WITH duplicate_rows AS (
  SELECT id,
    ROW_NUMBER() OVER (
      PARTITION BY course_module_completion_id
      ORDER BY created_at ASC -- Keep the oldest, delete the rest
    ) AS rn
  FROM course_module_completion_registered_to_study_registries
  WHERE deleted_at IS NULL
    AND course_module_completion_id = ANY($1)
)
UPDATE course_module_completion_registered_to_study_registries
SET deleted_at = NOW()
WHERE id IN (
    SELECT id
    FROM duplicate_rows
    WHERE rn > 1
  )
RETURNING id
        "#,
        completion_ids,
    )
    .fetch_all(conn)
    .await?;

    Ok(res.len() as i64)
}

async fn delete_all_duplicates(conn: &mut PgConnection) -> ModelResult<i64> {
    let res = sqlx::query!(
        r#"
WITH duplicate_rows AS (
  SELECT id,
    ROW_NUMBER() OVER (
      PARTITION BY course_module_completion_id
      ORDER BY created_at ASC -- Keep the oldest, delete the rest
    ) AS rn
  FROM course_module_completion_registered_to_study_registries
  WHERE deleted_at IS NULL
)
UPDATE course_module_completion_registered_to_study_registries
SET deleted_at = NOW()
WHERE id IN (
    SELECT id
    FROM duplicate_rows
    WHERE rn > 1
  )
RETURNING id
        "#
    )
    .fetch_all(conn)
    .await?;

    Ok(res.len() as i64)
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{course_module_completions::CourseModuleCompletionGranter, test_helper::*};

    #[tokio::test]
    async fn bulk_insert_works() {
        insert_data!(:tx, :user, :org, :course, :instance, :course_module);

        let registrar_id = crate::study_registry_registrars::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            "Test Registrar",
            "test_123131231231231231231231231231238971283718927389172893718923712893129837189273891278317892378193971289",
        )
        .await
        .unwrap();

        let new_completion_id = crate::course_module_completions::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            &crate::course_module_completions::NewCourseModuleCompletion {
                course_id: course,
                course_module_id: course_module.id,
                user_id: user,
                course_instance_id: instance.id,
                completion_date: Utc::now(),
                completion_registration_attempt_date: None,
                completion_language: "en-US".to_string(),
                eligible_for_ects: true,
                email: "test@example.com".to_string(),
                grade: Some(10),
                passed: true,
            },
            CourseModuleCompletionGranter::User(user),
        )
        .await
        .unwrap();

        let registrations = vec![
            NewCourseModuleCompletionRegisteredToStudyRegistry {
                course_id: course,
                course_module_completion_id: new_completion_id.id,
                course_module_id: course_module.id,
                study_registry_registrar_id: registrar_id,
                user_id: user,
                real_student_number: "12345".to_string(),
            },
            NewCourseModuleCompletionRegisteredToStudyRegistry {
                course_id: course,
                course_module_completion_id: new_completion_id.id,
                course_module_id: course_module.id,
                study_registry_registrar_id: registrar_id,
                user_id: user,
                real_student_number: "67890".to_string(),
            },
        ];

        let inserted_ids = insert_bulk(tx.as_mut(), registrations).await.unwrap();
        assert_eq!(inserted_ids.len(), 2);

        // Verify both records were inserted correctly
        for id in inserted_ids {
            let registration = get_by_id(tx.as_mut(), id).await.unwrap();
            assert_eq!(registration.course_id, course);
            assert_eq!(
                registration.course_module_completion_id,
                new_completion_id.id
            );
            assert_eq!(registration.course_module_id, course_module.id);
            assert_eq!(registration.study_registry_registrar_id, registrar_id);
            assert_eq!(registration.user_id, user);
        }
    }

    #[tokio::test]
    async fn bulk_insert_empty_vec_works() {
        insert_data!(:tx);

        let empty_vec = vec![];
        let result = insert_bulk(tx.as_mut(), empty_vec).await.unwrap();
        assert!(result.is_empty());
    }

    #[tokio::test]
    async fn insert_completions_works() {
        insert_data!(:tx, :user, :org, :course, :instance, :course_module);

        let registrar_id = crate::study_registry_registrars::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            "Test Registrar",
            "test_123131231231231231231231231231238971283718927389172893718923712893129837189273891278317892378193971289",
        )
        .await
        .unwrap();

        let completion = crate::course_module_completions::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            &crate::course_module_completions::NewCourseModuleCompletion {
                course_id: course,
                course_module_id: course_module.id,
                user_id: user,
                course_instance_id: instance.id,
                completion_date: Utc::now(),
                completion_registration_attempt_date: None,
                completion_language: "en-US".to_string(),
                eligible_for_ects: true,
                email: "test@example.com".to_string(),
                grade: Some(5),
                passed: true,
            },
            CourseModuleCompletionGranter::User(user),
        )
        .await
        .unwrap();

        let registered_completions = vec![RegisteredCompletion {
            completion_id: completion.id,
            student_number: "12345".to_string(),
            registration_date: Utc::now(),
        }];

        mark_completions_as_registered_to_study_registry(
            tx.as_mut(),
            registered_completions,
            registrar_id,
        )
        .await
        .unwrap();

        let registrations =
            get_by_completion_id_and_registrar_id(tx.as_mut(), completion.id, registrar_id)
                .await
                .unwrap();

        assert_eq!(registrations.len(), 1);
        assert_eq!(registrations[0].course_id, course);
        assert_eq!(registrations[0].course_module_id, course_module.id);
        assert_eq!(registrations[0].user_id, user);
        assert_eq!(registrations[0].real_student_number, "12345");
    }

    #[tokio::test]
    async fn insert_completions_with_invalid_completion_id_fails() {
        insert_data!(:tx);

        let registrar_id = crate::study_registry_registrars::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            "Test Registrar",
            "test_123131231231231231231231231231238971283718927389172893718923712893129837189273891278317892378193971289",
        )
        .await
        .unwrap();

        let invalid_uuid = Uuid::new_v4(); // This UUID doesn't correspond to any completion
        let registered_completions = vec![RegisteredCompletion {
            completion_id: invalid_uuid,
            student_number: "12345".to_string(),
            registration_date: Utc::now(),
        }];

        // Attempt to insert the completions should fail
        let result = mark_completions_as_registered_to_study_registry(
            tx.as_mut(),
            registered_completions,
            registrar_id,
        )
        .await;

        assert!(result.is_err());
        let error = result.unwrap_err();
        assert_eq!(*error.error_type(), ModelErrorType::PreconditionFailed);
        assert!(error.message().contains("Cannot find completion with id"));
        assert!(error.message().contains(&invalid_uuid.to_string()));
    }

    #[tokio::test]
    async fn delete_duplicate_registrations_works() {
        insert_data!(:tx, :user, :org, :course, :instance, :course_module);

        let registrar_id = crate::study_registry_registrars::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            "Test Registrar",
            "test_123131231231231231231231231231238971283718927389172893718923712893129837189273891278317892378193971289",
        )
        .await
        .unwrap();

        let completion = crate::course_module_completions::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            &crate::course_module_completions::NewCourseModuleCompletion {
                course_id: course,
                course_module_id: course_module.id,
                user_id: user,
                course_instance_id: instance.id,
                completion_date: Utc::now(),
                completion_registration_attempt_date: None,
                completion_language: "en-US".to_string(),
                eligible_for_ects: true,
                email: "test@example.com".to_string(),
                grade: Some(5),
                passed: true,
            },
            CourseModuleCompletionGranter::User(user),
        )
        .await
        .unwrap();

        // Create first registration
        let first_registration = NewCourseModuleCompletionRegisteredToStudyRegistry {
            course_id: course,
            course_module_completion_id: completion.id,
            course_module_id: course_module.id,
            study_registry_registrar_id: registrar_id,
            user_id: user,
            real_student_number: "12345".to_string(),
        };
        let first_id = insert(tx.as_mut(), PKeyPolicy::Generate, &first_registration)
            .await
            .unwrap();

        // Create additional registrations in a separate bulk insert so that we get a different created_at timestamp
        let later_registrations = vec![
            NewCourseModuleCompletionRegisteredToStudyRegistry {
                course_id: course,
                course_module_completion_id: completion.id,
                course_module_id: course_module.id,
                study_registry_registrar_id: registrar_id,
                user_id: user,
                real_student_number: "67890".to_string(),
            },
            NewCourseModuleCompletionRegisteredToStudyRegistry {
                course_id: course,
                course_module_completion_id: completion.id,
                course_module_id: course_module.id,
                study_registry_registrar_id: registrar_id,
                user_id: user,
                real_student_number: "54321".to_string(),
            },
        ];
        insert_bulk(tx.as_mut(), later_registrations).await.unwrap();

        let before_registrations =
            get_by_completion_id_and_registrar_id(tx.as_mut(), completion.id, registrar_id)
                .await
                .unwrap();
        assert_eq!(before_registrations.len(), 3);

        let deleted_count =
            delete_duplicates_for_specific_completions(tx.as_mut(), &[completion.id])
                .await
                .unwrap();
        assert_eq!(deleted_count, 2); // Should delete 2 out of 3 registrations

        let after_registrations =
            get_by_completion_id_and_registrar_id(tx.as_mut(), completion.id, registrar_id)
                .await
                .unwrap();
        assert_eq!(after_registrations.len(), 1);

        // The remaining registration should be the first one we created
        assert_eq!(after_registrations[0].id, first_id);
        assert_eq!(after_registrations[0].real_student_number, "12345");
    }

    #[tokio::test]
    async fn delete_duplicate_registrations_with_no_duplicates() {
        insert_data!(:tx, :user, :org, :course, :instance, :course_module);

        let registrar_id = crate::study_registry_registrars::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            "Test Registrar",
            "test_123131231231231231231231231231238971283718927389172893718923712893129837189273891278317892378193971289",
        )
        .await
        .unwrap();

        let completion1 = crate::course_module_completions::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            &crate::course_module_completions::NewCourseModuleCompletion {
                course_id: course,
                course_module_id: course_module.id,
                user_id: user,
                course_instance_id: instance.id,
                completion_date: Utc::now(),
                completion_registration_attempt_date: None,
                completion_language: "en-US".to_string(),
                eligible_for_ects: true,
                email: "test1@example.com".to_string(),
                grade: Some(5),
                passed: true,
            },
            CourseModuleCompletionGranter::User(user),
        )
        .await
        .unwrap();

        let completion2 = crate::course_module_completions::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            &crate::course_module_completions::NewCourseModuleCompletion {
                course_id: course,
                course_module_id: course_module.id,
                user_id: user,
                course_instance_id: instance.id,
                completion_date: Utc::now(),
                completion_registration_attempt_date: None,
                completion_language: "en-US".to_string(),
                eligible_for_ects: true,
                email: "test2@example.com".to_string(),
                grade: Some(4),
                passed: true,
            },
            CourseModuleCompletionGranter::User(user),
        )
        .await
        .unwrap();

        // Create one registration for each completion (no duplicates)
        let registrations = vec![
            NewCourseModuleCompletionRegisteredToStudyRegistry {
                course_id: course,
                course_module_completion_id: completion1.id,
                course_module_id: course_module.id,
                study_registry_registrar_id: registrar_id,
                user_id: user,
                real_student_number: "12345".to_string(),
            },
            NewCourseModuleCompletionRegisteredToStudyRegistry {
                course_id: course,
                course_module_completion_id: completion2.id,
                course_module_id: course_module.id,
                study_registry_registrar_id: registrar_id,
                user_id: user,
                real_student_number: "67890".to_string(),
            },
        ];
        insert_bulk(tx.as_mut(), registrations).await.unwrap();

        // Verify we have 1 registration for each completion
        let before_reg1 =
            get_by_completion_id_and_registrar_id(tx.as_mut(), completion1.id, registrar_id)
                .await
                .unwrap();
        let before_reg2 =
            get_by_completion_id_and_registrar_id(tx.as_mut(), completion2.id, registrar_id)
                .await
                .unwrap();
        assert_eq!(before_reg1.len(), 1);
        assert_eq!(before_reg2.len(), 1);

        // Delete duplicate registrations
        let deleted_count = delete_all_duplicates(tx.as_mut()).await.unwrap();
        assert_eq!(deleted_count, 0); // Should delete 0 registrations as there are no duplicates

        // Verify both registrations still exist
        let after_reg1 =
            get_by_completion_id_and_registrar_id(tx.as_mut(), completion1.id, registrar_id)
                .await
                .unwrap();
        let after_reg2 =
            get_by_completion_id_and_registrar_id(tx.as_mut(), completion2.id, registrar_id)
                .await
                .unwrap();
        assert_eq!(after_reg1.len(), 1);
        assert_eq!(after_reg2.len(), 1);
    }

    #[tokio::test]
    async fn delete_duplicate_registrations_filters_by_completion_id() {
        insert_data!(:tx, :user, :org, :course, :instance, :course_module);

        let registrar_id = crate::study_registry_registrars::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            "Test Registrar",
            "test_123131231231231231231231231231238971283718927389172893718923712893129837189273891278317892378193971289",
        )
        .await
        .unwrap();

        // Create two completions
        let completion1 = crate::course_module_completions::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            &crate::course_module_completions::NewCourseModuleCompletion {
                course_id: course,
                course_module_id: course_module.id,
                user_id: user,
                course_instance_id: instance.id,
                completion_date: Utc::now(),
                completion_registration_attempt_date: None,
                completion_language: "en-US".to_string(),
                eligible_for_ects: true,
                email: "test1@example.com".to_string(),
                grade: Some(5),
                passed: true,
            },
            CourseModuleCompletionGranter::User(user),
        )
        .await
        .unwrap();

        let completion2 = crate::course_module_completions::insert(
            tx.as_mut(),
            PKeyPolicy::Generate,
            &crate::course_module_completions::NewCourseModuleCompletion {
                course_id: course,
                course_module_id: course_module.id,
                user_id: user,
                course_instance_id: instance.id,
                completion_date: Utc::now(),
                completion_registration_attempt_date: None,
                completion_language: "en-US".to_string(),
                eligible_for_ects: true,
                email: "test2@example.com".to_string(),
                grade: Some(5),
                passed: true,
            },
            CourseModuleCompletionGranter::User(user),
        )
        .await
        .unwrap();

        // Create first registrations (these should be kept)
        let first_registrations = vec![
            NewCourseModuleCompletionRegisteredToStudyRegistry {
                course_id: course,
                course_module_completion_id: completion1.id,
                course_module_id: course_module.id,
                study_registry_registrar_id: registrar_id,
                user_id: user,
                real_student_number: "12345-1".to_string(),
            },
            NewCourseModuleCompletionRegisteredToStudyRegistry {
                course_id: course,
                course_module_completion_id: completion2.id,
                course_module_id: course_module.id,
                study_registry_registrar_id: registrar_id,
                user_id: user,
                real_student_number: "12345-2".to_string(),
            },
        ];
        insert_bulk(tx.as_mut(), first_registrations).await.unwrap();

        // Create second registrations (these should be deleted as duplicates)
        let second_registrations = vec![
            NewCourseModuleCompletionRegisteredToStudyRegistry {
                course_id: course,
                course_module_completion_id: completion1.id,
                course_module_id: course_module.id,
                study_registry_registrar_id: registrar_id,
                user_id: user,
                real_student_number: "67890-1".to_string(),
            },
            NewCourseModuleCompletionRegisteredToStudyRegistry {
                course_id: course,
                course_module_completion_id: completion2.id,
                course_module_id: course_module.id,
                study_registry_registrar_id: registrar_id,
                user_id: user,
                real_student_number: "67890-2".to_string(),
            },
        ];
        insert_bulk(tx.as_mut(), second_registrations)
            .await
            .unwrap();

        // Verify we have 2 registrations for each completion
        let before_reg1 =
            get_by_completion_id_and_registrar_id(tx.as_mut(), completion1.id, registrar_id)
                .await
                .unwrap();
        let before_reg2 =
            get_by_completion_id_and_registrar_id(tx.as_mut(), completion2.id, registrar_id)
                .await
                .unwrap();
        assert_eq!(before_reg1.len(), 2);
        assert_eq!(before_reg2.len(), 2);

        // Delete duplicate registrations only for completion1
        let deleted_count =
            delete_duplicates_for_specific_completions(tx.as_mut(), &[completion1.id])
                .await
                .unwrap();
        assert_eq!(deleted_count, 1); // Should delete 1 duplicate for completion1

        // Verify completion1 now has 1 registration and completion2 still has 2
        let after_reg1 =
            get_by_completion_id_and_registrar_id(tx.as_mut(), completion1.id, registrar_id)
                .await
                .unwrap();
        let after_reg2 =
            get_by_completion_id_and_registrar_id(tx.as_mut(), completion2.id, registrar_id)
                .await
                .unwrap();
        assert_eq!(after_reg1.len(), 1);
        assert_eq!(after_reg2.len(), 2);

        // The registration for completion1 should be the first one we created
        assert_eq!(after_reg1[0].real_student_number, "12345-1");
    }
}