1
use crate::error::{FinanceError, PriceError};
2
use sqlx::types::Uuid;
3
use sqlx::types::chrono::{DateTime, Utc};
4
use sqlx::{Connection, query_file};
5
use supp_macro::Builder;
6

            
7
#[derive(Debug, sqlx::FromRow, Builder)]
8
#[builder(error_kind = "FinanceError")]
9
pub struct Price {
10
    pub id: Uuid,
11
    pub date: DateTime<Utc>,
12
    pub commodity_id: Uuid,
13
    pub currency_id: Uuid,
14
    pub commodity_split: Option<Uuid>,
15
    pub currency_split: Option<Uuid>,
16
    pub value_num: i64,
17
    pub value_denom: i64,
18
}
19

            
20
impl Price {
21
11747
    pub async fn commit<E>(&self, conn: &mut E) -> Result<(), FinanceError>
22
11747
    where
23
11747
        E: Connection<Database = sqlx::Postgres>,
24
11747
    {
25
11747
        let mut tr = conn.begin().await?;
26

            
27
11747
        query_file!(
28
            "sql/price_insert.sql",
29
            &self.id,
30
            &self.commodity_id,
31
            &self.currency_id,
32
11747
            match &self.commodity_split {
33
11746
                &Some(s) => Some(s),
34
1
                _ => None,
35
            },
36
11747
            match &self.currency_split {
37
11746
                &Some(s) => Some(s),
38
1
                _ => None,
39
            },
40
            &self.date,
41
            &self.value_num,
42
            &self.value_denom,
43
        )
44
11747
        .execute(&mut *tr)
45
11747
        .await?;
46
11747
        tr.commit().await?;
47

            
48
11747
        Ok(())
49
11747
    }
50
}
51

            
52
#[cfg(test)]
53
mod price_tests {
54
    use super::*;
55
    use crate::account::{Account, AccountBuilder};
56
    use crate::commodity::{Commodity, CommodityBuilder};
57
    use sqlx::PgPool;
58
    use sqlx::types::chrono::Local;
59
    use tokio::sync::OnceCell;
60

            
61
    /// Context for keeping environment intact
62
    static CONTEXT: OnceCell<()> = OnceCell::const_new();
63
    static COMMODITY_1: OnceCell<Commodity> = OnceCell::const_new();
64
    static COMMODITY_2: OnceCell<Commodity> = OnceCell::const_new();
65
    static ACCOUNT_1: OnceCell<Account> = OnceCell::const_new();
66
    static ACCOUNT_2: OnceCell<Account> = OnceCell::const_new();
67

            
68
2
    async fn setup(pool: &PgPool) {
69
2
        CONTEXT
70
2
            .get_or_init(|| async {
71
                #[cfg(feature = "testlog")]
72
2
                crate::test_logging::init();
73
4
            })
74
2
            .await;
75

            
76
2
        COMMODITY_1
77
4
            .get_or_init(|| async { CommodityBuilder::new().id(Uuid::new_v4()).build().unwrap() })
78
2
            .await;
79
2
        let mut conn = pool.acquire().await.unwrap();
80
2
        COMMODITY_1.get().unwrap().commit(&mut *conn).await.unwrap();
81

            
82
2
        COMMODITY_2
83
4
            .get_or_init(|| async { CommodityBuilder::new().id(Uuid::new_v4()).build().unwrap() })
84
2
            .await;
85
2
        let mut conn = pool.acquire().await.unwrap();
86
2
        COMMODITY_2.get().unwrap().commit(&mut *conn).await.unwrap();
87

            
88
2
        ACCOUNT_1
89
4
            .get_or_init(|| async { AccountBuilder::new().id(Uuid::new_v4()).build().unwrap() })
90
2
            .await;
91

            
92
2
        let mut conn = pool.acquire().await.unwrap();
93
2
        ACCOUNT_1.get().unwrap().commit(&mut *conn).await.unwrap();
94

            
95
2
        ACCOUNT_2
96
4
            .get_or_init(|| async { AccountBuilder::new().id(Uuid::new_v4()).build().unwrap() })
97
2
            .await;
98

            
99
2
        let mut conn = pool.acquire().await.unwrap();
100
2
        ACCOUNT_2.get().unwrap().commit(&mut *conn).await.unwrap();
101
2
    }
102

            
103
    #[sqlx::test(migrations = "../migrations")]
104
    async fn test_price_store(pool: PgPool) -> anyhow::Result<()> {
105
        setup(&pool).await;
106
        let price = Price {
107
            id: Uuid::new_v4(),
108
            date: Local::now().into(),
109
            commodity_id: COMMODITY_1.get().unwrap().id,
110
            currency_id: COMMODITY_2.get().unwrap().id,
111
            commodity_split: None,
112
            currency_split: None,
113
            value_num: 100,
114
            value_denom: 1,
115
        };
116

            
117
        let mut conn = pool.acquire().await?;
118
        price.commit(&mut *conn).await?;
119

            
120
        let mut conn = pool.acquire().await.unwrap();
121

            
122
        let result = sqlx::query!("SELECT id FROM prices WHERE value_num = 100")
123
            .fetch_one(&mut *conn)
124
            .await
125
            .unwrap();
126

            
127
        assert_eq!(price.id, result.id);
128

            
129
        Ok(())
130
    }
131

            
132
    #[sqlx::test(migrations = "../migrations")]
133
    async fn test_price_builder(pool: PgPool) -> anyhow::Result<()> {
134
        setup(&pool).await;
135

            
136
        let price = Price::builder()
137
            .id(Uuid::new_v4())
138
            .date(Local::now().into())
139
            .commodity_id(COMMODITY_1.get().unwrap().id)
140
            .currency_id(COMMODITY_2.get().unwrap().id)
141
            .value_num(100)
142
            .value_denom(1)
143
            .build()?;
144

            
145
        assert_eq!(price.value_num, 100);
146
        Ok(())
147
    }
148
}