Skip to main content

headless_lms_credit_registration/use_cases/
materialize.rs

1//! The `materialize` phase: the ledger rows for completions that became eligible, and for grades
2//! that improved on a registered one.
3
4use headless_lms_models::library::credit_registration::materialize::{
5    GRADE_IMPROVEMENT_LIMIT, MATERIALIZE_LIMIT, ensure_registration_rows_for_eligible_completions,
6    start_re_attempts_for_improved_grades,
7};
8use sqlx::{PgConnection, PgPool};
9
10use crate::error::CreditRegistrationResult;
11use crate::workflow::Counts;
12use headless_lms_models::credit_registrations::RegistrationScope;
13
14/// The ledger rows one materialize pass created.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct Materialized {
17    /// Rows for completions that became eligible.
18    pub created: i64,
19    /// New attempts for grades that improved on a registered one.
20    pub re_attempted: i64,
21}
22
23/// Both statements that create ledger rows, bounded apart from each other: the phase's body, and
24/// the admin "materialize now" button's, so the two cannot drift apart.
25pub async fn materialize_now(
26    conn: &mut PgConnection,
27    scope: &RegistrationScope,
28) -> CreditRegistrationResult<Materialized> {
29    let created =
30        ensure_registration_rows_for_eligible_completions(conn, scope, MATERIALIZE_LIMIT).await?;
31    let re_attempted =
32        start_re_attempts_for_improved_grades(conn, scope, GRADE_IMPROVEMENT_LIMIT).await?;
33    Ok(Materialized {
34        created,
35        re_attempted,
36    })
37}
38
39/// One pass in one phase, so the Workers tab's row-creation counter accounts for every row the
40/// pipeline invented.
41pub(crate) async fn run(
42    pool: &PgPool,
43    scope: &RegistrationScope,
44) -> CreditRegistrationResult<Counts> {
45    let mut conn = pool.acquire().await?;
46    let Materialized {
47        created,
48        re_attempted,
49    } = materialize_now(&mut conn, scope).await?;
50    if created > 0 || re_attempted > 0 {
51        debug!(
52            created,
53            re_attempted, "Materialized credit registration rows"
54        );
55    }
56    Ok(Counts::processed(created + re_attempted))
57}