headless_lms_models/
material_references.rs

1use crate::prelude::*;
2use chrono::{DateTime, Utc};
3use sqlx::PgConnection;
4use uuid::Uuid;
5
6#[derive(Debug, Serialize, Deserialize, FromRow, PartialEq, Clone)]
7#[cfg_attr(feature = "ts_rs", derive(TS))]
8pub struct MaterialReference {
9    pub id: Uuid,
10    pub course_id: Uuid,
11    pub citation_key: String,
12    pub reference: String,
13    pub created_at: DateTime<Utc>,
14    pub updated_at: DateTime<Utc>,
15    pub deleted_at: Option<DateTime<Utc>>,
16}
17
18#[derive(Debug, Serialize, Deserialize, FromRow, PartialEq, Clone)]
19#[cfg_attr(feature = "ts_rs", derive(TS))]
20pub struct NewMaterialReference {
21    pub citation_key: String,
22    pub reference: String,
23}
24
25pub async fn insert_reference(
26    conn: &mut PgConnection,
27    course_id: Uuid,
28    new_ref: Vec<NewMaterialReference>,
29) -> ModelResult<()> {
30    let mut tx = conn.begin().await?;
31    let new_ref_iter = new_ref.iter();
32
33    for new_ref in new_ref_iter {
34        sqlx::query!(
35            "
36    INSERT INTO material_references(course_id, citation_key, reference)
37    VALUES ($1, $2, $3)
38    ",
39            course_id,
40            new_ref.citation_key,
41            new_ref.reference
42        )
43        .execute(&mut *tx)
44        .await?;
45    }
46    tx.commit().await?;
47
48    Ok(())
49}
50
51pub async fn get_reference_by_id(
52    conn: &mut PgConnection,
53    reference_id: Uuid,
54) -> ModelResult<MaterialReference> {
55    let res = sqlx::query_as!(
56        MaterialReference,
57        "
58SELECT *
59FROM material_references
60WHERE id = $1;
61    ",
62        reference_id
63    )
64    .fetch_one(conn)
65    .await?;
66    Ok(res)
67}
68
69pub async fn get_references_by_course_id(
70    conn: &mut PgConnection,
71    course_id: Uuid,
72) -> ModelResult<Vec<MaterialReference>> {
73    let res = sqlx::query_as!(
74        MaterialReference,
75        "
76SELECT *
77FROM material_references
78WHERE course_id = $1
79  AND deleted_at IS NULL;
80    ",
81        course_id
82    )
83    .fetch_all(conn)
84    .await?;
85    Ok(res)
86}
87
88pub async fn update_material_reference_by_id(
89    conn: &mut PgConnection,
90    material_reference_id: Uuid,
91    material_reference: NewMaterialReference,
92) -> ModelResult<()> {
93    sqlx::query!(
94        "
95UPDATE material_references
96SET reference = $1, citation_key = $2
97WHERE id = $3;
98",
99        material_reference.reference,
100        material_reference.citation_key,
101        material_reference_id
102    )
103    .execute(conn)
104    .await?;
105    Ok(())
106}
107
108pub async fn delete_reference(conn: &mut PgConnection, id: Uuid) -> ModelResult<()> {
109    sqlx::query!(
110        "
111UPDATE material_references
112SET deleted_at = now()
113WHERE material_references.id = $1;
114        ",
115        id
116    )
117    .execute(conn)
118    .await?;
119    Ok(())
120}