headless_lms_server/domain/csv_export/
code_giveaway_codes.rs1use anyhow::Result;
2use bytes::Bytes;
3
4use futures::TryStreamExt;
5use headless_lms_models::code_giveaway_codes;
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 CodeGiveawayCodesExportOperation {
25 pub code_giveaway_id: Uuid,
26}
27
28#[async_trait]
29impl CsvExportDataLoader for CodeGiveawayCodesExportOperation {
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_code_giveaway_codes(
37 &mut *conn,
38 self.code_giveaway_id,
39 CSVExportAdapter {
40 sender,
41 authorization_token: token,
42 },
43 )
44 .await
45 }
46}
47
48pub async fn export_code_giveaway_codes<W>(
50 conn: &mut PgConnection,
51 code_giveaway_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 "code_giveaway_id".to_string(),
62 "code_given_to_user_id".to_string(),
63 "added_by_user_id".to_string(),
64 "code".to_string(),
65 ]);
66
67 let mut stream =
68 code_giveaway_codes::stream_given_code_giveaway_codes(conn, code_giveaway_id).await;
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.code_giveaway_id.to_string(),
77 next.code_given_to_user_id
78 .map(|o| o.to_string())
79 .unwrap_or("".to_string()),
80 next.added_by_user_id.to_string(),
81 next.code.to_string(),
82 ];
83 writer.write_record(csv_row);
84 }
85 let writer = writer.finish().await?;
86 Ok(writer)
87}