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
use futures::future::BoxFuture;
use url::Url;

use crate::{
    exercise_service_info::ExerciseServiceInfoApi,
    exercises::{self, Exercise},
    library::{self, peer_or_self_reviewing::CourseMaterialPeerOrSelfReviewData},
    peer_or_self_review_questions::{
        delete_peer_or_self_review_questions_by_peer_or_self_review_config_ids,
        upsert_multiple_peer_or_self_review_questions, CmsPeerOrSelfReviewQuestion,
    },
    prelude::*,
    user_exercise_states::{self, ReviewingStage},
};

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct PeerOrSelfReviewConfig {
    pub id: Uuid,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub deleted_at: Option<DateTime<Utc>>,
    pub course_id: Uuid,
    pub exercise_id: Option<Uuid>,
    pub peer_reviews_to_give: i32,
    pub peer_reviews_to_receive: i32,
    pub accepting_threshold: f32,
    pub processing_strategy: PeerReviewProcessingStrategy,
    pub manual_review_cutoff_in_days: i32,
    pub points_are_all_or_nothing: bool,
    pub review_instructions: Option<serde_json::Value>,
}

/// Like `PeerOrSelfReviewConfig` but only the fields it's fine to show to all users.
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct CourseMaterialPeerOrSelfReviewConfig {
    pub id: Uuid,
    pub course_id: Uuid,
    pub exercise_id: Option<Uuid>,
    pub peer_reviews_to_give: i32,
    pub peer_reviews_to_receive: i32,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct CmsPeerOrSelfReviewConfig {
    pub id: Uuid,
    pub course_id: Uuid,
    pub exercise_id: Option<Uuid>,
    pub peer_reviews_to_give: i32,
    pub peer_reviews_to_receive: i32,
    pub accepting_threshold: f32,
    pub processing_strategy: PeerReviewProcessingStrategy,
    pub points_are_all_or_nothing: bool,
    pub review_instructions: Option<serde_json::Value>,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct CmsPeerOrSelfReviewConfiguration {
    pub peer_or_self_review_config: CmsPeerOrSelfReviewConfig,
    pub peer_or_self_review_questions: Vec<CmsPeerOrSelfReviewQuestion>,
}

/**
Determines how we will treat the answer being peer reviewed once it has received enough reviews and the student has given enough peer reviews.

Some strategies compare the overall received peer review likert answer (1-5) average to peer_reviews.accepting threshold.
*/
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Copy, sqlx::Type)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
#[sqlx(
    type_name = "peer_review_processing_strategy",
    rename_all = "snake_case"
)]
pub enum PeerReviewProcessingStrategy {
    /// If the average of the peer review likert answers is greater than the threshold, the peer review is accepted, otherwise it is rejected.
    AutomaticallyGradeByAverage,
    /// If the average of the peer review likert answers is greater than the threshold, the peer review is accepted, otherwise it is sent to be manually reviewed by the teacher.
    AutomaticallyGradeOrManualReviewByAverage,
    /// All answers will be sent to be manually reviewed by the teacher once they have received and given enough peer reviews.
    ManualReviewEverything,
}

pub async fn insert(
    conn: &mut PgConnection,
    pkey_policy: PKeyPolicy<Uuid>,
    course_id: Uuid,
    exercise_id: Option<Uuid>,
) -> ModelResult<Uuid> {
    let res = sqlx::query!(
        "
INSERT INTO peer_or_self_review_configs (id, course_id, exercise_id)
VALUES ($1, $2, $3)
RETURNING id
        ",
        pkey_policy.into_uuid(),
        course_id,
        exercise_id,
    )
    .fetch_one(conn)
    .await?;
    Ok(res.id)
}

pub async fn upsert_with_id(
    conn: &mut PgConnection,
    pkey_policy: PKeyPolicy<Uuid>,
    cms_peer_review: &CmsPeerOrSelfReviewConfig,
) -> ModelResult<CmsPeerOrSelfReviewConfig> {
    let res = sqlx::query_as!(
        CmsPeerOrSelfReviewConfig,
        r#"
    INSERT INTO peer_or_self_review_configs (
    id,
    course_id,
    exercise_id,
    peer_reviews_to_give,
    peer_reviews_to_receive,
    accepting_threshold,
    processing_strategy,
    points_are_all_or_nothing,
    review_instructions
  )
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) ON CONFLICT (id) DO
UPDATE
SET course_id = excluded.course_id,
  exercise_id = excluded.exercise_id,
  peer_reviews_to_give = excluded.peer_reviews_to_give,
  peer_reviews_to_receive = excluded.peer_reviews_to_receive,
  accepting_threshold = excluded.accepting_threshold,
  processing_strategy = excluded.processing_strategy,
  points_are_all_or_nothing = excluded.points_are_all_or_nothing,
  review_instructions = excluded.review_instructions
RETURNING id,
  course_id,
  exercise_id,
  peer_reviews_to_give,
  peer_reviews_to_receive,
  accepting_threshold,
  processing_strategy AS "processing_strategy:_",
  points_are_all_or_nothing,
  review_instructions
"#,
        pkey_policy.into_uuid(),
        cms_peer_review.course_id,
        cms_peer_review.exercise_id,
        cms_peer_review.peer_reviews_to_give,
        cms_peer_review.peer_reviews_to_receive,
        cms_peer_review.accepting_threshold,
        cms_peer_review.processing_strategy as _,
        cms_peer_review.points_are_all_or_nothing,
        cms_peer_review.review_instructions,
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

pub async fn get_by_id(conn: &mut PgConnection, id: Uuid) -> ModelResult<PeerOrSelfReviewConfig> {
    let res = sqlx::query_as!(
        PeerOrSelfReviewConfig,
        r#"
SELECT id,
  created_at,
  updated_at,
  deleted_at,
  course_id,
  exercise_id,
  peer_reviews_to_give,
  peer_reviews_to_receive,
  accepting_threshold,
  processing_strategy AS "processing_strategy: _",
  manual_review_cutoff_in_days,
  points_are_all_or_nothing,
  review_instructions
FROM peer_or_self_review_configs
WHERE id = $1
  AND deleted_at IS NULL
        "#,
        id
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

/// Usually you want to use `get_by_exercise_or_course_id` instead of this one.
pub async fn get_by_exercise_id(
    conn: &mut PgConnection,
    exercise_id: Uuid,
) -> ModelResult<PeerOrSelfReviewConfig> {
    let res = sqlx::query_as!(
        PeerOrSelfReviewConfig,
        r#"
SELECT id,
    created_at,
    updated_at,
    deleted_at,
    course_id,
    exercise_id,
    peer_reviews_to_give,
    peer_reviews_to_receive,
    accepting_threshold,
    processing_strategy AS "processing_strategy: _",
    manual_review_cutoff_in_days,
    points_are_all_or_nothing,
    review_instructions
FROM peer_or_self_review_configs
WHERE exercise_id = $1
  AND deleted_at IS NULL
        "#,
        exercise_id
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

/// Returns the correct peer review config depending on `exercise.use_course_default_peer_or_self_review_config`.
pub async fn get_by_exercise_or_course_id(
    conn: &mut PgConnection,
    exercise: &Exercise,
    course_id: Uuid,
) -> ModelResult<PeerOrSelfReviewConfig> {
    if exercise.use_course_default_peer_or_self_review_config {
        get_default_for_course_by_course_id(conn, course_id).await
    } else {
        get_by_exercise_id(conn, exercise.id).await
    }
}

pub async fn get_default_for_course_by_course_id(
    conn: &mut PgConnection,
    course_id: Uuid,
) -> ModelResult<PeerOrSelfReviewConfig> {
    let res = sqlx::query_as!(
        PeerOrSelfReviewConfig,
        r#"
SELECT id,
  created_at,
  updated_at,
  deleted_at,
  course_id,
  exercise_id,
  peer_reviews_to_give,
  peer_reviews_to_receive,
  accepting_threshold,
  processing_strategy AS "processing_strategy: _",
  manual_review_cutoff_in_days,
  points_are_all_or_nothing,
  review_instructions
FROM peer_or_self_review_configs
WHERE course_id = $1
  AND exercise_id IS NULL
  AND deleted_at IS NULL;
        "#,
        course_id
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

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

pub async fn get_course_material_peer_or_self_review_data(
    conn: &mut PgConnection,
    user_id: Uuid,
    exercise_id: Uuid,
    fetch_service_info: impl Fn(Url) -> BoxFuture<'static, ModelResult<ExerciseServiceInfoApi>>,
) -> ModelResult<CourseMaterialPeerOrSelfReviewData> {
    let exercise = exercises::get_by_id(conn, exercise_id).await?;
    let (_current_exercise_slide, instance_or_exam_id) = exercises::get_or_select_exercise_slide(
        &mut *conn,
        Some(user_id),
        &exercise,
        &fetch_service_info,
    )
    .await?;

    let user_exercise_state = match instance_or_exam_id {
        Some(course_instance_or_exam_id) => {
            user_exercise_states::get_user_exercise_state_if_exists(
                conn,
                user_id,
                exercise.id,
                course_instance_or_exam_id,
            )
            .await?
        }
        _ => None,
    };

    match user_exercise_state {
        Some(ref user_exercise_state) => {
            if matches!(
                user_exercise_state.reviewing_stage,
                ReviewingStage::PeerReview | ReviewingStage::WaitingForPeerReviews
            ) {
                // Calling library inside a model function. Maybe should be refactored by moving
                // complicated logic to own library file?
                let res = library::peer_or_self_reviewing::try_to_select_exercise_slide_submission_for_peer_review(
                    conn,
                    &exercise,
                    user_exercise_state,
                    &fetch_service_info
                )
                .await?;
                Ok(res)
            } else if user_exercise_state.reviewing_stage == ReviewingStage::SelfReview {
                let res = library::peer_or_self_reviewing::select_own_submission_for_self_review(
                    conn,
                    &exercise,
                    user_exercise_state,
                    &fetch_service_info,
                )
                .await?;
                Ok(res)
            } else {
                Err(ModelError::new(
                    ModelErrorType::PreconditionFailed,
                    "You cannot peer review yet".to_string(),
                    None,
                ))
            }
        }
        None => Err(ModelError::new(
            ModelErrorType::InvalidRequest,
            "You haven't answered this exercise".to_string(),
            None,
        )),
    }
}

pub async fn get_peer_reviews_by_page_id(
    conn: &mut PgConnection,
    page_id: Uuid,
) -> ModelResult<Vec<CmsPeerOrSelfReviewConfig>> {
    let res = sqlx::query_as!(
        CmsPeerOrSelfReviewConfig,
        r#"
SELECT pr.id as id,
  pr.course_id as course_id,
  pr.exercise_id as exercise_id,
  pr.peer_reviews_to_give as peer_reviews_to_give,
  pr.peer_reviews_to_receive as peer_reviews_to_receive,
  pr.accepting_threshold as accepting_threshold,
  pr.processing_strategy AS "processing_strategy: _",
  points_are_all_or_nothing,
  pr.review_instructions
from pages p
  join exercises e on p.id = e.page_id
  join peer_or_self_review_configs pr on e.id = pr.exercise_id
where p.id = $1
  AND p.deleted_at IS NULL
  AND e.deleted_at IS NULL
  AND pr.deleted_at IS NULL;
    "#,
        page_id,
    )
    .fetch_all(conn)
    .await?;

    Ok(res)
}

pub async fn delete_peer_reviews_by_exrcise_ids(
    conn: &mut PgConnection,
    exercise_ids: &[Uuid],
) -> ModelResult<Vec<Uuid>> {
    let res = sqlx::query!(
        "
UPDATE peer_or_self_review_configs
SET deleted_at = now()
WHERE exercise_id = ANY ($1)
AND deleted_at IS NULL
RETURNING id;
    ",
        exercise_ids
    )
    .fetch_all(conn)
    .await?
    .into_iter()
    .map(|x| x.id)
    .collect();
    Ok(res)
}

pub async fn get_course_default_cms_peer_review(
    conn: &mut PgConnection,
    course_id: Uuid,
) -> ModelResult<CmsPeerOrSelfReviewConfig> {
    let res = sqlx::query_as!(
        CmsPeerOrSelfReviewConfig,
        r#"
SELECT id,
  course_id,
  exercise_id,
  peer_reviews_to_give,
  peer_reviews_to_receive,
  accepting_threshold,
  processing_strategy AS "processing_strategy: _",
  points_are_all_or_nothing,
  review_instructions
FROM peer_or_self_review_configs
WHERE course_id = $1
  AND exercise_id IS NULL
  AND deleted_at IS NULL;
"#,
        course_id
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

pub async fn get_cms_peer_review_by_id(
    conn: &mut PgConnection,
    peer_or_self_review_config_id: Uuid,
) -> ModelResult<CmsPeerOrSelfReviewConfig> {
    let res = sqlx::query_as!(
        CmsPeerOrSelfReviewConfig,
        r#"
SELECT id,
  course_id,
  exercise_id,
  peer_reviews_to_give,
  peer_reviews_to_receive,
  accepting_threshold,
  processing_strategy AS "processing_strategy:_",
  points_are_all_or_nothing,
  review_instructions
FROM peer_or_self_review_configs
WHERE id = $1;
    "#,
        peer_or_self_review_config_id
    )
    .fetch_one(conn)
    .await?;
    Ok(res)
}

pub async fn upsert_course_default_cms_peer_review_and_questions(
    conn: &mut PgConnection,
    peer_or_self_review_configuration: &CmsPeerOrSelfReviewConfiguration,
) -> ModelResult<CmsPeerOrSelfReviewConfiguration> {
    // Upsert peer review
    let peer_or_self_review_config = upsert_with_id(
        conn,
        PKeyPolicy::Fixed(
            peer_or_self_review_configuration
                .peer_or_self_review_config
                .id,
        ),
        &peer_or_self_review_configuration.peer_or_self_review_config,
    )
    .await?;

    // Upsert peer review questions
    let previous_peer_or_self_review_question_ids =
        delete_peer_or_self_review_questions_by_peer_or_self_review_config_ids(
            conn,
            &[peer_or_self_review_config.id],
        )
        .await?;
    let peer_or_self_review_questions = upsert_multiple_peer_or_self_review_questions(
        conn,
        &peer_or_self_review_configuration
            .peer_or_self_review_questions
            .iter()
            .map(|prq| {
                let id = if previous_peer_or_self_review_question_ids.contains(&prq.id) {
                    prq.id
                } else {
                    Uuid::new_v4()
                };
                CmsPeerOrSelfReviewQuestion { id, ..prq.clone() }
            })
            .collect::<Vec<_>>(),
    )
    .await?;

    Ok(CmsPeerOrSelfReviewConfiguration {
        peer_or_self_review_config,
        peer_or_self_review_questions,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helper::*;

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

        let peer_review_1 = insert(tx.as_mut(), PKeyPolicy::Generate, course, None).await;
        assert!(peer_review_1.is_err());
    }
}