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
use crate::prelude::*;

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct CodeGiveaway {
    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_id: Option<Uuid>,
    pub require_course_specific_consent_form_question_id: Option<Uuid>,
    pub enabled: bool,
    pub name: String,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct NewCodeGiveaway {
    pub course_id: Uuid,
    pub name: String,
    pub course_module_id: Option<Uuid>,
    pub require_course_specific_consent_form_question_id: Option<Uuid>,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
#[serde(tag = "tag")]
pub enum CodeGiveawayStatus {
    Disabled,
    NotEligible,
    Eligible { codes_left: bool },
    AlreadyGottenCode { given_code: String },
}

pub async fn insert(conn: &mut PgConnection, input: &NewCodeGiveaway) -> ModelResult<CodeGiveaway> {
    let res = sqlx::query_as!(
        CodeGiveaway,
        r#"
INSERT INTO code_giveaways (course_id, name, course_module_id, require_course_specific_consent_form_question_id)
VALUES ($1, $2, $3, $4)
RETURNING *
        "#,
        input.course_id,
        input.name,
        input.course_module_id,
        input.require_course_specific_consent_form_question_id
    )
    .fetch_one(&mut *conn)
    .await?;

    Ok(res)
}

pub async fn get_all_for_course(
    conn: &mut PgConnection,
    course_id: Uuid,
) -> ModelResult<Vec<CodeGiveaway>> {
    let res = sqlx::query_as!(
        CodeGiveaway,
        r#"
SELECT *
FROM code_giveaways
WHERE course_id = $1
  AND deleted_at IS NULL
"#,
        course_id
    )
    .fetch_all(&mut *conn)
    .await?;

    Ok(res)
}

pub async fn get_by_id(conn: &mut PgConnection, id: Uuid) -> ModelResult<CodeGiveaway> {
    let res = sqlx::query_as!(
        CodeGiveaway,
        r#"
SELECT *
FROM code_giveaways
WHERE id = $1
"#,
        id
    )
    .fetch_one(&mut *conn)
    .await?;

    Ok(res)
}

pub async fn set_enabled(
    conn: &mut PgConnection,
    id: Uuid,
    enabled: bool,
) -> ModelResult<CodeGiveaway> {
    let res = sqlx::query_as!(
        CodeGiveaway,
        r#"
UPDATE code_giveaways
SET enabled = $2
WHERE id = $1
RETURNING *
"#,
        id,
        enabled
    )
    .fetch_one(&mut *conn)
    .await?;

    Ok(res)
}

pub async fn get_code_giveaway_status(
    conn: &mut PgConnection,
    code_giveaway_id: Uuid,
    user_id: Uuid,
) -> ModelResult<CodeGiveawayStatus> {
    let code_giveaway = get_by_id(conn, code_giveaway_id).await?;
    if !code_giveaway.enabled {
        return Ok(CodeGiveawayStatus::Disabled);
    }

    if let Some(course_module_id) = code_giveaway.course_module_id {
        let course_module_completions =
            crate::course_module_completions::get_all_by_user_id_and_course_module_id(
                conn,
                user_id,
                course_module_id,
            )
            .await?;

        if !course_module_completions.iter().any(|c| c.passed) {
            return Ok(CodeGiveawayStatus::NotEligible);
        }
    } else {
        warn!(
            "Code giveaway {} does not have a course module requirement",
            code_giveaway_id
        );
        return Ok(CodeGiveawayStatus::Disabled);
    }
    if let Some(question_id) = code_giveaway.require_course_specific_consent_form_question_id {
        let research_form_answers =
            crate::research_forms::get_all_research_form_answers_with_user_course_and_question_id(
                conn,
                user_id,
                code_giveaway.course_id,
                question_id,
            )
            .await?;

        if !research_form_answers.iter().any(|a| a.research_consent) {
            return Ok(CodeGiveawayStatus::NotEligible);
        }
    }
    let already_given_code =
        crate::code_giveaway_codes::get_code_given_to_user(conn, code_giveaway_id, user_id).await?;

    if let Some(code) = already_given_code {
        return Ok(CodeGiveawayStatus::AlreadyGottenCode {
            given_code: code.code,
        });
    }

    let codes_left = crate::code_giveaway_codes::are_any_codes_left(conn, code_giveaway_id).await?;

    Ok(CodeGiveawayStatus::Eligible { codes_left })
}