headless_lms_server/domain/csv_export/
exercise_tasks_export.rs1use anyhow::Result;
2use bytes::Bytes;
3
4use futures::TryStreamExt;
5
6use async_trait::async_trait;
7use models::exercise_tasks;
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 CourseExerciseTasksExportOperation {
25 pub course_id: Uuid,
26}
27
28#[async_trait]
29impl CsvExportDataLoader for CourseExerciseTasksExportOperation {
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_course_exercise_tasks(
37 &mut *conn,
38 self.course_id,
39 CSVExportAdapter {
40 sender,
41 authorization_token: token,
42 },
43 )
44 .await
45 }
46}
47
48pub async fn export_course_exercise_tasks<W>(
50 conn: &mut PgConnection,
51 course_id: Uuid,
52 writer: W,
53) -> Result<W>
54where
55 W: Write + Send + 'static,
56{
57 let headers = IntoIterator::into_iter([
58 "id".to_string(),
59 "created_at".to_string(),
60 "updated_at".to_string(),
61 "exercise_type".to_string(),
62 "private_spec".to_string(),
63 "exercise_name".to_string(),
64 "course_module_id".to_string(),
65 "course_module_name".to_owned(),
66 ]);
67
68 let mut stream = exercise_tasks::stream_course_exercise_tasks(conn, course_id);
69
70 let writer = CsvWriter::new_with_initialized_headers(writer, headers).await?;
71 while let Some(next) = stream.try_next().await? {
72 let csv_row = vec![
73 next.id.to_string(),
74 next.created_at.to_rfc3339(),
75 next.updated_at.to_rfc3339(),
76 next.exercise_type.to_string(),
77 next.private_spec
78 .map(|o| o.to_string())
79 .unwrap_or_else(|| "".to_string()),
80 next.exercise_name.to_string(),
81 next.course_module_id.to_string(),
82 next.course_module_name
83 .map(|o| o.to_string())
84 .unwrap_or_else(|| "Default module".to_string()),
85 ];
86 writer.write_record(csv_row);
87 }
88 let writer = writer.finish().await?;
89 Ok(writer)
90}