1
use super::*;
2
use crate::command::transaction::CROSS_PRICE;
3
use crate::fleet::jobs::cross_price::fixture::{Rows, seed};
4

            
5
type PriceRow = (Uuid, i64, i64);
6

            
7
5
async fn user_with_rows(pool: &PgPool) -> anyhow::Result<(&'static User, Rows)> {
8
5
    let user = USER.get().unwrap();
9
5
    user.commit().await?;
10
5
    Ok((user, seed(pool).await?))
11
5
}
12

            
13
3
async fn split_ids(pool: &PgPool, tx: Uuid) -> anyhow::Result<Vec<Uuid>> {
14
    Ok(
15
3
        sqlx::query_scalar("SELECT id FROM splits WHERE tx_id = $1 ORDER BY id")
16
3
            .bind(tx)
17
3
            .fetch_all(pool)
18
3
            .await?,
19
    )
20
3
}
21

            
22
6
async fn prices_of(pool: &PgPool, tx: Uuid) -> anyhow::Result<Vec<PriceRow>> {
23
6
    Ok(sqlx::query_as(
24
6
        "SELECT p.id, p.value_num, p.value_denom FROM prices p \
25
6
         JOIN splits s ON s.id = p.commodity_split_id WHERE s.tx_id = $1 ORDER BY p.id",
26
6
    )
27
6
    .bind(tx)
28
6
    .fetch_all(pool)
29
6
    .await?)
30
6
}
31

            
32
4
fn price(id: Uuid, legs: &[Uuid], value_num: i64) -> FinanceEntity {
33
4
    FinanceEntity::Price(Price {
34
4
        id,
35
4
        commodity_id: Uuid::from_u128(1),
36
4
        currency_id: Uuid::from_u128(1),
37
4
        commodity_split: legs.first().copied(),
38
4
        currency_split: legs.get(1).copied(),
39
4
        date: Utc::now(),
40
4
        value_num,
41
4
        value_denom: 2,
42
4
    })
43
4
}
44

            
45
4
fn split(id: Uuid, tx: Uuid, value_num: i64) -> FinanceEntity {
46
4
    FinanceEntity::Split(Split {
47
4
        id,
48
4
        tx_id: tx,
49
4
        account_id: Uuid::from_u128(2),
50
4
        commodity_id: Uuid::from_u128(1),
51
4
        value_num,
52
4
        value_denom: 1,
53
4
        reconcile_state: None,
54
4
        reconcile_date: None,
55
4
        lot_id: None,
56
4
    })
57
4
}
58

            
59
3
async fn update_prices(
60
3
    user: &User,
61
3
    tx: Uuid,
62
3
    prices: Vec<FinanceEntity>,
63
3
) -> Result<Option<CmdResult>, CmdError> {
64
3
    UpdateTransaction::new()
65
3
        .user_id(user.id)
66
3
        .transaction_id(tx)
67
3
        .prices(prices)
68
3
        .run()
69
3
        .await
70
3
}
71

            
72
#[local_db_sqlx_test]
73
async fn a_prices_only_update_replaces_the_old_price(pool: PgPool) -> anyhow::Result<()> {
74
    let (user, rows) = user_with_rows(&pool).await?;
75
    let legs = split_ids(&pool, rows.tx_own).await?;
76
    let new_id = Uuid::new_v4();
77

            
78
    update_prices(user, rows.tx_own, vec![price(new_id, &legs, 3)]).await?;
79

            
80
    assert_eq!(prices_of(&pool, rows.tx_own).await?, vec![(new_id, 3, 2)]);
81
    let gone: i64 = sqlx::query_scalar("SELECT count(*) FROM prices WHERE id = $1")
82
        .bind(rows.own_price)
83
        .fetch_one(&pool)
84
        .await?;
85
    assert_eq!(gone, 0);
86
}
87

            
88
#[local_db_sqlx_test]
89
async fn a_resent_price_id_keeps_one_row_with_the_new_value(pool: PgPool) -> anyhow::Result<()> {
90
    let (user, rows) = user_with_rows(&pool).await?;
91
    let legs = split_ids(&pool, rows.tx_own).await?;
92

            
93
    update_prices(user, rows.tx_own, vec![price(rows.own_price, &legs, 7)]).await?;
94

            
95
    assert_eq!(
96
        prices_of(&pool, rows.tx_own).await?,
97
        vec![(rows.own_price, 7, 2)]
98
    );
99
}
100

            
101
#[local_db_sqlx_test]
102
async fn an_update_without_prices_keeps_them(pool: PgPool) -> anyhow::Result<()> {
103
    let (user, rows) = user_with_rows(&pool).await?;
104

            
105
    UpdateTransaction::new()
106
        .user_id(user.id)
107
        .transaction_id(rows.tx_own)
108
        .note("changed".to_string())
109
        .run()
110
        .await?;
111

            
112
    assert_eq!(
113
        prices_of(&pool, rows.tx_own).await?,
114
        vec![(rows.own_price, 1, 1)]
115
    );
116
}
117

            
118
#[local_db_sqlx_test]
119
async fn a_split_replacing_update_drops_or_replaces_the_prices(pool: PgPool) -> anyhow::Result<()> {
120
    let (user, rows) = user_with_rows(&pool).await?;
121
2
    let replace = |legs: [Uuid; 2]| {
122
2
        UpdateTransaction::new()
123
2
            .user_id(user.id)
124
2
            .transaction_id(rows.tx_own)
125
2
            .splits(vec![
126
2
                split(legs[0], rows.tx_own, -5),
127
2
                split(legs[1], rows.tx_own, 5),
128
2
            ])
129
2
    };
130

            
131
    replace([Uuid::new_v4(), Uuid::new_v4()]).run().await?;
132
    assert_eq!(prices_of(&pool, rows.tx_own).await?, vec![]);
133

            
134
    let legs = [Uuid::new_v4(), Uuid::new_v4()];
135
    let new_id = Uuid::new_v4();
136
    replace(legs)
137
        .prices(vec![price(new_id, &legs, 9)])
138
        .run()
139
        .await?;
140
    assert_eq!(prices_of(&pool, rows.tx_own).await?, vec![(new_id, 9, 2)]);
141
}
142

            
143
#[local_db_sqlx_test]
144
async fn a_prices_only_update_of_a_cross_price_transaction_is_refused(
145
    pool: PgPool,
146
) -> anyhow::Result<()> {
147
    let (user, rows) = user_with_rows(&pool).await?;
148
    let legs = split_ids(&pool, rows.tx_a).await?;
149

            
150
    let result = update_prices(user, rows.tx_a, vec![price(Uuid::new_v4(), &legs, 3)]).await;
151

            
152
    assert!(
153
        matches!(&result, Err(CmdError::Refused(message)) if message == CROSS_PRICE),
154
        "{result:?}"
155
    );
156
    assert_eq!(
157
        prices_of(&pool, rows.tx_a).await?,
158
        vec![(rows.cross_price, 1, 1)]
159
    );
160
}