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
use crate::{
    exercise_task_gradings::{self, ExerciseTaskGrading, UserPointsUpdateStrategy},
    exercise_task_regrading_submissions, exercise_task_submissions,
    exercises::GradingProgress,
    prelude::*,
};

#[derive(Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct Regrading {
    pub id: Uuid,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub regrading_started_at: Option<DateTime<Utc>>,
    pub regrading_completed_at: Option<DateTime<Utc>>,
    pub total_grading_progress: GradingProgress,
    pub user_points_update_strategy: UserPointsUpdateStrategy,
    pub user_id: Option<Uuid>,
}

#[derive(Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct NewRegrading {
    user_points_update_strategy: UserPointsUpdateStrategy,
    ids: Vec<Uuid>,
    id_type: NewRegradingIdType,
}

#[derive(Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub enum NewRegradingIdType {
    ExerciseTaskSubmissionId,
    ExerciseId,
}

#[derive(Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct RegradingInfo {
    pub regrading: Regrading,
    pub submission_infos: Vec<RegradingSubmissionInfo>,
}

#[derive(Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct RegradingSubmissionInfo {
    pub exercise_task_submission_id: Uuid,
    pub grading_before_regrading: ExerciseTaskGrading,
    pub grading_after_regrading: Option<ExerciseTaskGrading>,
}

pub async fn insert(
    conn: &mut PgConnection,
    user_points_update_strategy: UserPointsUpdateStrategy,
) -> ModelResult<Uuid> {
    let res = sqlx::query!(
        "
INSERT INTO regradings (user_points_update_strategy)
VALUES ($1)
RETURNING id
        ",
        user_points_update_strategy as UserPointsUpdateStrategy
    )
    .fetch_one(conn)
    .await?;
    Ok(res.id)
}

/// Creates a new regrading for the exercise task submission ids supplied as arguments.
pub async fn insert_and_create_exercise_task_regradings(
    conn: &mut PgConnection,
    new_regrading: NewRegrading,
    user_id: Uuid,
) -> ModelResult<Uuid> {
    let mut tx = conn.begin().await?;
    info!("Creating a new regrading.");
    let res = sqlx::query!(
        "
INSERT INTO regradings (user_points_update_strategy, user_id)
VALUES ($1, $2)
RETURNING id
        ",
        new_regrading.user_points_update_strategy as UserPointsUpdateStrategy,
        user_id
    )
    .fetch_one(&mut *tx)
    .await?;

    let exercise_task_submission_ids = match new_regrading.id_type {
        NewRegradingIdType::ExerciseTaskSubmissionId => new_regrading.ids,
        NewRegradingIdType::ExerciseId => {
            let mut ids = Vec::new();
            for id in new_regrading.ids {
                let exercise = crate::exercises::get_by_id(&mut tx, id).await?;
                let submission_ids = if exercise.exam_id.is_some() {
                    // On exams only the last submission is considered.
                    // That's why we will only regrade those.
                    exercise_task_submissions::get_latest_submission_ids_by_exercise_id(
                        &mut tx,
                        exercise.id,
                    )
                    .await?
                } else {
                    exercise_task_submissions::get_ids_by_exercise_id(&mut tx, exercise.id).await?
                };
                ids.extend(submission_ids);
            }
            ids
        }
    };

    info!(
        "Adding {:?} exercise task submissions to the regrading.",
        exercise_task_submission_ids.len()
    );
    for id in &exercise_task_submission_ids {
        let exercise_task_submission = exercise_task_submissions::get_by_id(&mut tx, *id).await?;
        let grading_before_regrading_id = exercise_task_submission
            .exercise_task_grading_id
            .ok_or_else(|| {
                ModelError::new(
                    ModelErrorType::PreconditionFailed,
                    "One of the submissions to be regraded has not been graded yet.".to_string(),
                    None,
                )
            })?;
        let _etrs = exercise_task_regrading_submissions::insert(
            &mut tx,
            PKeyPolicy::Generate,
            res.id,
            *id,
            grading_before_regrading_id,
        )
        .await?;
    }
    tx.commit().await?;
    Ok(res.id)
}

pub async fn get_regrading_info_by_id(
    conn: &mut PgConnection,
    regrading_id: Uuid,
) -> ModelResult<RegradingInfo> {
    let regrading = get_by_id(&mut *conn, regrading_id).await?;
    let etrs =
        exercise_task_regrading_submissions::get_regrading_submissions(&mut *conn, regrading_id)
            .await?;
    let mut grading_id_to_grading =
        exercise_task_gradings::get_new_and_old_exercise_task_gradings_by_regrading_id(
            &mut *conn,
            regrading_id,
        )
        .await?;
    let submission_infos = etrs
        .iter()
        .map(|e| -> ModelResult<_> {
            Ok(RegradingSubmissionInfo {
                exercise_task_submission_id: e.exercise_task_submission_id,
                grading_before_regrading: grading_id_to_grading
                    .remove(&e.grading_before_regrading)
                    .ok_or_else(|| {
                        ModelError::new(
                            ModelErrorType::Generic,
                            "Grading before regrading not found".to_string(),
                            None,
                        )
                    })?,
                grading_after_regrading: e
                    .grading_after_regrading
                    .and_then(|gar| grading_id_to_grading.remove(&gar)),
            })
        })
        .collect::<ModelResult<Vec<_>>>()?;
    Ok(RegradingInfo {
        regrading,
        submission_infos,
    })
}

pub async fn get_all_paginated(
    conn: &mut PgConnection,
    pagination: Pagination,
) -> ModelResult<Vec<Regrading>> {
    let res = sqlx::query_as!(
        Regrading,
        r#"
SELECT id,
  created_at,
  updated_at,
  regrading_started_at,
  regrading_completed_at,
  total_grading_progress AS "total_grading_progress: _",
  user_points_update_strategy AS "user_points_update_strategy: _",
  user_id
FROM regradings
WHERE deleted_at IS NULL
ORDER BY regradings.created_at
LIMIT $1 OFFSET $2;
"#,
        pagination.limit(),
        pagination.offset()
    )
    .fetch_all(conn)
    .await?;
    Ok(res)
}

pub async fn get_all_count(conn: &mut PgConnection) -> ModelResult<i64> {
    let res = sqlx::query!(
        "
SELECT COUNT(*) as count
from regradings
WHERE deleted_at IS NULL;
"
    )
    .fetch_one(conn)
    .await?;
    Ok(res.count.unwrap_or(0))
}

pub async fn get_by_id(conn: &mut PgConnection, id: Uuid) -> ModelResult<Regrading> {
    let res = sqlx::query_as!(
        Regrading,
        r#"
SELECT id,
  regrading_started_at,
  regrading_completed_at,
  created_at,
  updated_at,
  total_grading_progress AS "total_grading_progress: _",
  user_points_update_strategy AS "user_points_update_strategy: _",
  user_id
FROM regradings
WHERE id = $1
"#,
        id
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

pub async fn get_uncompleted_regradings_and_mark_as_started(
    conn: &mut PgConnection,
) -> ModelResult<Vec<Uuid>> {
    let res = sqlx::query!(
        r#"
UPDATE regradings
SET regrading_started_at = CASE
    WHEN regrading_started_at IS NULL THEN now()
    ELSE regrading_started_at
  END
WHERE regrading_completed_at IS NULL
  AND deleted_at IS NULL
RETURNING id
"#
    )
    .fetch_all(&mut *conn)
    .await?
    .into_iter()
    .map(|r| r.id)
    .collect();

    Ok(res)
}

pub async fn set_total_grading_progress(
    conn: &mut PgConnection,
    regrading_id: Uuid,
    progress: GradingProgress,
) -> ModelResult<()> {
    sqlx::query!(
        "
UPDATE regradings
SET total_grading_progress = $1
WHERE id = $2
",
        progress as GradingProgress,
        regrading_id
    )
    .execute(conn)
    .await?;
    Ok(())
}

pub async fn complete_regrading(conn: &mut PgConnection, regrading_id: Uuid) -> ModelResult<()> {
    sqlx::query!(
        "
UPDATE regradings
SET regrading_completed_at = now(),
  total_grading_progress = 'fully-graded'
WHERE id = $1
",
        regrading_id
    )
    .execute(conn)
    .await?;
    Ok(())
}

pub async fn set_error_message(
    conn: &mut PgConnection,
    regrading_id: Uuid,
    error_message: &str,
) -> ModelResult<()> {
    sqlx::query!(
        "
UPDATE regradings
SET error_message = $1
WHERE id = $2
",
        error_message,
        regrading_id
    )
    .execute(conn)
    .await?;
    Ok(())
}