headless_lms_server/domain/csv_export/
user_exericse_states_export.rs

1use anyhow::Result;
2use bytes::Bytes;
3
4use futures::TryStreamExt;
5use headless_lms_models::{course_instances, user_exercise_states};
6
7use async_trait::async_trait;
8
9use crate::domain::csv_export::CsvWriter;
10
11use sqlx::PgConnection;
12use std::io::Write;
13use tokio::sync::mpsc::UnboundedSender;
14
15use uuid::Uuid;
16
17use crate::prelude::*;
18
19use super::{
20    super::authorization::{AuthorizationToken, AuthorizedResponse},
21    CSVExportAdapter, CsvExportDataLoader,
22};
23
24pub struct UserExerciseStatesExportOperation {
25    pub course_id: Uuid,
26}
27
28#[async_trait]
29impl CsvExportDataLoader for UserExerciseStatesExportOperation {
30    async fn load_data(
31        &self,
32        sender: UnboundedSender<Result<AuthorizedResponse<Bytes>, ControllerError>>,
33        conn: &mut PgConnection,
34        token: AuthorizationToken,
35    ) -> anyhow::Result<CSVExportAdapter> {
36        export_user_exercise_states(
37            &mut *conn,
38            self.course_id,
39            CSVExportAdapter {
40                sender,
41                authorization_token: token,
42            },
43        )
44        .await
45    }
46}
47
48/// Writes user exercise states as csv into the writer
49pub async fn export_user_exercise_states<W>(
50    conn: &mut PgConnection,
51    course_id: Uuid,
52    writer: W,
53) -> Result<W>
54where
55    W: Write + Send + 'static,
56{
57    let course_instance_ids =
58        course_instances::get_course_instance_ids_with_course_id(conn, course_id).await?;
59
60    let headers = IntoIterator::into_iter([
61        "course_instance_id".to_string(),
62        "user_id".to_string(),
63        "exercise_id".to_string(),
64        "created_at".to_string(),
65        "updated_at".to_string(),
66        "activity_process".to_string(),
67        "grading_progress".to_string(),
68        "reviewing_stage".to_string(),
69        "score_given".to_string(),
70    ]);
71
72    let mut stream =
73        user_exercise_states::stream_user_exercise_states_for_course(conn, &course_instance_ids);
74
75    let writer = CsvWriter::new_with_initialized_headers(writer, headers).await?;
76    while let Some(next) = stream.try_next().await? {
77        let csv_row = vec![
78            next.course_instance_id.unwrap_or_default().to_string(),
79            next.user_id.to_string(),
80            next.exercise_id.to_string(),
81            next.created_at.to_rfc3339(),
82            next.updated_at.to_rfc3339(),
83            next.activity_progress.to_string(),
84            next.grading_progress.to_string(),
85            next.reviewing_stage.to_string(),
86            next.score_given.unwrap_or(0.0).to_string(),
87        ];
88        writer.write_record(csv_row);
89    }
90    let writer = writer.finish().await?;
91    Ok(writer)
92}