1
//! Fixtures of the `transaction-edit` tests.
2

            
3
use chrono::{DateTime, Utc};
4
use forms::escape_str;
5
use nomiscript::{Value, format_value};
6
use scripting::runtime::HostCondition;
7
use sqlx::PgPool;
8
use uuid::Uuid;
9

            
10
use super::test_seed::submit_create;
11
use super::test_seed::{seed_account, seed_commodity, seed_user};
12

            
13
pub(super) struct Fx {
14
    pub(super) user: Uuid,
15
    pub(super) usd: Uuid,
16
    pub(super) eur: Uuid,
17
    pub(super) cash: Uuid,
18
    pub(super) food: Uuid,
19
}
20

            
21
140
pub(super) async fn fx(pool: &PgPool) -> anyhow::Result<Fx> {
22
140
    let user = seed_user(pool).await?;
23
    Ok(Fx {
24
140
        user,
25
140
        usd: seed_commodity(user, "USD").await?,
26
140
        eur: seed_commodity(user, "EUR").await?,
27
140
        cash: seed_account(user, "Cash").await?,
28
140
        food: seed_account(user, "Food").await?,
29
    })
30
140
}
31

            
32
140
pub(super) fn row(from: &str, to: &str, commodity: &str, value: &str, extra: &str) -> String {
33
140
    let [from, to, commodity, value] = [from, to, commodity, value].map(escape_str);
34
140
    format!("(:from {from} :to {to} :from-commodity {commodity} :value {value} {extra})")
35
140
}
36

            
37
impl Fx {
38
    /// A `Cash` to `Food` row in `USD`.
39
127
    pub(super) fn row(&self, value: &str, extra: &str) -> String {
40
381
        let [cash, food, usd] = [self.cash, self.food, self.usd].map(|id| id.to_string());
41
127
        row(&cash, &food, &usd, value, extra)
42
127
    }
43

            
44
    /// The same row converted to `EUR` at an amount of 9.
45
11
    pub(super) fn fx_row(&self, value: &str) -> String {
46
11
        self.row(
47
11
            value,
48
11
            &format!(":to-commodity \"{}\" :to-amount \"9\"", self.eur),
49
11
        )
50
11
    }
51
}
52

            
53
53
pub(super) async fn create(fx: &Fx, date: &str, rows: &[String]) -> anyhow::Result<Uuid> {
54
53
    let payload = format!(
55
53
        "(:date \"{date}\" :note \"n\" :splits ({}))",
56
53
        rows.join(" ")
57
    );
58
53
    let id = submit_create(fx.user, &payload).await?;
59
53
    Ok(Uuid::parse_str(&id)?)
60
53
}
61

            
62
61
pub(super) fn condition(err: &wasmtime::Error) -> HostCondition {
63
61
    err.downcast_ref::<HostCondition>()
64
61
        .cloned()
65
61
        .expect("host condition")
66
61
}
67

            
68
66
pub(super) fn detail_text(condition: &HostCondition) -> String {
69
66
    condition
70
66
        .detail
71
66
        .clone()
72
65
        .map(|detail| format_value(&Value::from(detail)))
73
        .unwrap_or_default()
74
66
}
75

            
76
42
pub(super) fn fields(detail: &str) -> Vec<String> {
77
42
    detail
78
42
        .split("(:FIELD \"")
79
42
        .skip(1)
80
58
        .filter_map(|part| part.split('"').next().map(str::to_string))
81
        .collect()
82
42
}
83

            
84
33
pub(super) fn replace_once(text: &str, from: &str, to: &str) -> String {
85
33
    assert_eq!(text.matches(from).count(), 1, "{from} in {text}");
86
33
    text.replace(from, to)
87
33
}
88

            
89
8
pub(super) async fn price_dates(pool: &PgPool) -> anyhow::Result<Vec<DateTime<Utc>>> {
90
8
    Ok(sqlx::query_scalar("SELECT price_date FROM prices")
91
8
        .fetch_all(pool)
92
8
        .await?)
93
8
}
94

            
95
5
pub(super) async fn set_price_date(pool: &PgPool, date: &str) -> anyhow::Result<()> {
96
5
    sqlx::query("UPDATE prices SET price_date = $1::timestamptz")
97
5
        .bind(date)
98
5
        .execute(pool)
99
5
        .await?;
100
5
    Ok(())
101
5
}
102

            
103
3
pub(super) async fn post_date(pool: &PgPool, tx: Uuid) -> anyhow::Result<DateTime<Utc>> {
104
    Ok(
105
3
        sqlx::query_scalar("SELECT post_date FROM transactions WHERE id = $1")
106
3
            .bind(tx)
107
3
            .fetch_one(pool)
108
3
            .await?,
109
    )
110
3
}
111

            
112
14
pub(super) async fn split_accounts(pool: &PgPool, tx: Uuid) -> anyhow::Result<Vec<Uuid>> {
113
14
    Ok(sqlx::query_scalar(
114
14
        "SELECT account_id FROM splits WHERE tx_id = $1 ORDER BY value_num, account_id",
115
14
    )
116
14
    .bind(tx)
117
14
    .fetch_all(pool)
118
14
    .await?)
119
14
}
120

            
121
2
pub(super) async fn split_tag_pairs(pool: &PgPool, tx: Uuid) -> anyhow::Result<Vec<String>> {
122
2
    Ok(sqlx::query_scalar(
123
2
        "SELECT t.tag_name || '=' || t.tag_value FROM split_tags st \
124
2
         JOIN tags t ON t.id = st.tag_id JOIN splits s ON s.id = st.split_id \
125
2
         WHERE s.tx_id = $1 ORDER BY 1",
126
2
    )
127
2
    .bind(tx)
128
2
    .fetch_all(pool)
129
2
    .await?)
130
2
}
131

            
132
2
pub(super) async fn rename_symbol(pool: &PgPool, from: &str, to: &str) -> anyhow::Result<()> {
133
2
    sqlx::query("UPDATE tags SET tag_value = $2 WHERE tag_name = 'symbol' AND tag_value = $1")
134
2
        .bind(from)
135
2
        .bind(to)
136
2
        .execute(pool)
137
2
        .await?;
138
2
    Ok(())
139
2
}
140

            
141
3
pub(super) async fn split_commodities(pool: &PgPool, tx: Uuid) -> anyhow::Result<Vec<Uuid>> {
142
3
    Ok(sqlx::query_scalar(
143
3
        "SELECT commodity_id FROM splits WHERE tx_id = $1 ORDER BY value_num, commodity_id",
144
3
    )
145
3
    .bind(tx)
146
3
    .fetch_all(pool)
147
3
    .await?)
148
3
}
149

            
150
/// The loaded payload as its head, split rows text and split-tags tail.
151
14
fn parts(payload: &str) -> (&str, &str, &str) {
152
14
    let (head, rest) = payload.split_once(" :splits (").unwrap_or((payload, ""));
153
14
    let (rows, tail) = rest.rsplit_once(") :split-tags ").unwrap_or((rest, "()"));
154
14
    (head, rows, tail)
155
14
}
156

            
157
/// The loaded payload with its rows replaced by `rows` (each row text whole);
158
/// its split tags stay.
159
7
pub(super) fn with_rows(payload: &str, rows: &[String]) -> String {
160
7
    let (head, _, tail) = parts(payload);
161
7
    format!("{head} :splits ({}) :split-tags {tail}", rows.join(" "))
162
7
}
163

            
164
/// The row texts of a loaded payload.
165
7
pub(super) fn rows_of(payload: &str) -> Vec<String> {
166
7
    let (_, body, _) = parts(payload);
167
7
    body.split(" (:key ")
168
7
        .enumerate()
169
10
        .map(|(index, row)| match index {
170
7
            0 => row.to_string(),
171
3
            _ => format!("(:key {row}"),
172
10
        })
173
        .collect()
174
7
}
175

            
176
/// The payload without its `:revision`, for comparing loads across edits.
177
18
pub(super) fn without_revision(payload: &str) -> String {
178
18
    let start = payload.find(" :revision \"").unwrap_or_default();
179
18
    let tail = &payload[start + 12..];
180
18
    let end = tail.find('"').unwrap_or_default();
181
18
    format!("{}{}", &payload[..start], &tail[end + 1..])
182
18
}
183

            
184
/// A loaded payload as it was emitted before UUID cells: names in the cells
185
/// and labelled hidden data. The fixture's entities are `Cash`, `Food`,
186
/// `USD` and `EUR`.
187
2
pub(super) fn legacy_loaded(payload: &str, fx: &Fx) -> String {
188
2
    let names = [
189
2
        (fx.cash, "Cash"),
190
2
        (fx.food, "Food"),
191
2
        (fx.usd, "USD"),
192
2
        (fx.eur, "EUR"),
193
2
    ];
194
19
    let name_of = |id: Uuid| names.iter().find(|(known, _)| *known == id).map(|e| e.1);
195
8
    let hidden_id = |key: &str, text: &str| {
196
8
        let start = format!(":{key} \\\"");
197
8
        let at = text.find(&start)? + start.len();
198
8
        Uuid::parse_str(text.get(at..at + 36)?).ok()
199
8
    };
200
8
    let labels = ["from-id", "to-id", "from-commodity-id", "to-commodity-id"].map(|key| {
201
8
        hidden_id(key, payload)
202
8
            .and_then(name_of)
203
8
            .unwrap_or_default()
204
8
    });
205
2
    let mut text = payload.to_string();
206
2
    for (id, name) in names {
207
8
        text = text.replace(&format!(" \"{id}\" :"), &format!(" \"{name}\" :"));
208
    }
209
2
    let [from, to, from_commodity, to_commodity] = labels;
210
2
    replace_once(
211
2
        &text,
212
2
        " :value \\\"",
213
2
        &format!(
214
2
            " :from-label \\\"{from}\\\" :to-label \\\"{to}\\\" \
215
2
             :from-commodity-label \\\"{from_commodity}\\\" \
216
2
             :to-commodity-label \\\"{to_commodity}\\\" :value \\\""
217
2
        ),
218
2
    )
219
2
}