1
//! The lossless fixture of the client form tests: one transaction holding
2
//! everything an edit could lose, and a snapshot of what is stored for it.
3

            
4
use std::collections::HashMap;
5

            
6
use chrono::{DateTime, Utc};
7
use finance::price::Price;
8
use finance::split::Split;
9
use finance::tag::Tag;
10
use num_rational::Rational64;
11
use sqlx::PgPool;
12
use sqlx::types::Uuid;
13

            
14
use crate::command::account::CreateAccount;
15
use crate::command::commodity::CreateCommodity;
16
use crate::command::transaction::CreateTransaction;
17
use crate::command::{CmdError, CmdResult, FinanceEntity};
18
use crate::logical::{LogicalSplit, lower_logical_transaction};
19

            
20
/// An exact instant with microseconds.
21
pub const POST_DATE: &str = "2026-10-27T09:15:42.123456Z";
22
/// The FX price date: distinct from the post date, with microseconds.
23
pub const PRICE_DATE: &str = "2026-10-20T08:30:15.654321Z";
24
pub const NOTE: &str = "first line\nsecond \"quoted\" back\\slash";
25
/// The note a note-only edit writes.
26
pub const EDITED_NOTE: &str = "edited\nnote";
27

            
28
pub struct Lossless {
29
    pub user: Uuid,
30
    pub transaction: Uuid,
31
}
32

            
33
29457
fn tag(name: &str, value: &str, description: Option<&str>) -> Tag {
34
29457
    Tag {
35
29457
        id: Uuid::new_v4(),
36
29457
        tag_name: name.to_string(),
37
29457
        tag_value: value.to_string(),
38
29457
        description: description.map(str::to_string),
39
29457
    }
40
29457
}
41

            
42
6546
fn instant(text: &str) -> Result<DateTime<Utc>, CmdError> {
43
6546
    DateTime::parse_from_rfc3339(text)
44
6546
        .map(|date| date.with_timezone(&Utc))
45
        .map_err(|err| CmdError::Args(err.to_string()))
46
6546
}
47

            
48
6559
pub(crate) async fn commodity(user: Uuid, symbol: &str) -> Result<Uuid, CmdError> {
49
6559
    let created = CreateCommodity::new()
50
6559
        .symbol(symbol.to_string())
51
6559
        .name(symbol.to_string())
52
6559
        .user_id(user)
53
6559
        .run()
54
6559
        .await?;
55
6559
    match created {
56
        Some(CmdResult::String(id)) => {
57
6559
            Uuid::parse_str(&id).map_err(|err| CmdError::Args(err.to_string()))
58
        }
59
        other => Err(CmdError::Args(format!("commodity: {other:?}"))),
60
    }
61
6559
}
62

            
63
6572
pub(crate) async fn account(user: Uuid, name: &str) -> Result<Uuid, CmdError> {
64
6572
    let created = CreateAccount::new()
65
6572
        .name(name.to_string())
66
6572
        .user_id(user)
67
6572
        .run()
68
6572
        .await?;
69
6572
    match created {
70
6572
        Some(CmdResult::Entity(FinanceEntity::Account(account))) => Ok(account.id),
71
        other => Err(CmdError::Args(format!("account: {other:?}"))),
72
    }
73
6572
}
74

            
75
/// An FX row (reconcile carried, distinct price date) and an exact
76
/// fraction row, from `Cash` to `Food`.
77
3273
fn rows(cash: Uuid, food: Uuid, usd: Uuid, eur: Uuid) -> [LogicalSplit; 2] {
78
3273
    [
79
3273
        LogicalSplit {
80
3273
            from: cash,
81
3273
            to: food,
82
3273
            from_commodity: usd,
83
3273
            to_commodity: eur,
84
3273
            value: Rational64::new(10, 1),
85
3273
            to_amount: Some(Rational64::new(9, 1)),
86
3273
            from_reconcile: Some(false),
87
3273
            to_reconcile: Some(false),
88
3273
        },
89
3273
        LogicalSplit {
90
3273
            from: cash,
91
3273
            to: food,
92
3273
            from_commodity: usd,
93
3273
            to_commodity: usd,
94
3273
            value: Rational64::new(1, 3),
95
3273
            to_amount: None,
96
3273
            from_reconcile: None,
97
3273
            to_reconcile: None,
98
3273
        },
99
3273
    ]
100
3273
}
101

            
102
13092
fn split_entity(split: &crate::logical::PhysicalSplit, tx_id: Uuid) -> FinanceEntity {
103
13092
    FinanceEntity::Split(Split {
104
13092
        id: split.id,
105
13092
        tx_id,
106
13092
        account_id: split.account_id,
107
13092
        commodity_id: split.commodity_id,
108
13092
        value_num: *split.value.numer(),
109
13092
        value_denom: *split.value.denom(),
110
13092
        reconcile_state: split.reconcile_state,
111
13092
        reconcile_date: None,
112
13092
        lot_id: None,
113
13092
    })
114
13092
}
115

            
116
3273
fn transaction_tags(carriage_returns: bool) -> HashMap<String, FinanceEntity> {
117
3273
    [
118
3273
        tag("trip", "japan", Some("spring \"trip\" \\ notes\nday two")),
119
3273
        tag("project", "nomisync", Some("client forms")),
120
3273
        tag("cleared", "yes", None),
121
3273
        tag("windows", "crlf", Some("dos\r\nline\rmac end")),
122
3273
        tag("blank", "empty", Some("")),
123
3273
    ]
124
3273
    .into_iter()
125
16365
    .filter(|tag| carriage_returns || tag.tag_name != "windows")
126
16185
    .map(|tag| (tag.tag_name.clone(), FinanceEntity::Tag(tag)))
127
    .collect()
128
3273
}
129

            
130
/// A user with the lossless transaction: transaction tags with and without
131
/// (multiline, CR and CRLF, or empty) descriptions, split tags, an FX price dated apart from the
132
/// exact post date, a fraction and a multiline note.
133
///
134
/// # Errors
135
/// Any failing seed command.
136
2903
pub async fn seed(pool: &PgPool) -> Result<Lossless, CmdError> {
137
2903
    let user = Uuid::new_v4();
138
2903
    sqlx::query_file!(
139
        "sql/insert/users/fixture.sql",
140
        user,
141
2903
        format!("u{user}"),
142
2903
        format!("{user}@test.com")
143
    )
144
2903
    .execute(pool)
145
2903
    .await?;
146
2903
    let transaction = seed_transaction(user).await?;
147
2903
    Ok(Lossless { user, transaction })
148
2903
}
149

            
150
/// The lossless transaction in the store of the existing `user`.
151
///
152
/// # Errors
153
/// Any failing seed command.
154
3093
pub async fn seed_transaction(user: Uuid) -> Result<Uuid, CmdError> {
155
3093
    seed_with(user, true).await
156
3093
}
157

            
158
/// [`seed_transaction`] without the carriage-return tag, for the web edit
159
/// page, which refuses carriage returns by design.
160
///
161
/// # Errors
162
/// Any failing seed command.
163
180
pub async fn seed_transaction_without_cr(user: Uuid) -> Result<Uuid, CmdError> {
164
180
    seed_with(user, false).await
165
180
}
166

            
167
3273
async fn seed_with(user: Uuid, carriage_returns: bool) -> Result<Uuid, CmdError> {
168
3273
    let (usd, eur) = (commodity(user, "USD").await?, commodity(user, "EUR").await?);
169
3273
    let (cash, food) = (account(user, "Cash").await?, account(user, "Food").await?);
170
3273
    let (splits, mut prices) = lower_logical_transaction(&rows(cash, food, usd, eur))?;
171
3273
    let price_date = instant(PRICE_DATE)?;
172
3273
    prices
173
3273
        .iter_mut()
174
3273
        .for_each(|price| price.date = Some(price_date));
175
3273
    let transaction = Uuid::new_v4();
176
3273
    let split_tags = splits
177
3273
        .iter()
178
3273
        .enumerate()
179
13092
        .map(|(index, split)| match index / 2 {
180
6546
            0 => (
181
6546
                split.id,
182
6546
                tag("memo", "m\\x", Some("split memo\nsecond line")),
183
6546
            ),
184
6546
            _ => (split.id, tag("category", "food", None)),
185
13092
        })
186
        .collect();
187
3273
    let prices = prices
188
3273
        .into_iter()
189
3273
        .map(|price| {
190
3273
            FinanceEntity::Price(Price {
191
3273
                id: Uuid::new_v4(),
192
3273
                date: price_date,
193
3273
                commodity_id: price.commodity_id,
194
3273
                currency_id: price.currency_id,
195
3273
                commodity_split: Some(price.commodity_split),
196
3273
                currency_split: Some(price.currency_split),
197
3273
                value_num: price.value_num,
198
3273
                value_denom: price.value_denom,
199
3273
            })
200
3273
        })
201
        .collect();
202
3273
    CreateTransaction::new()
203
3273
        .user_id(user)
204
3273
        .id(transaction)
205
3273
        .post_date(instant(POST_DATE)?)
206
3273
        .enter_date(Utc::now())
207
        .splits(
208
3273
            splits
209
3273
                .iter()
210
13092
                .map(|s| split_entity(s, transaction))
211
                .collect(),
212
        )
213
3273
        .prices(prices)
214
3273
        .note(NOTE.to_string())
215
3273
        .tags(transaction_tags(carriage_returns))
216
3273
        .split_tags(split_tags)
217
        .run()
218
3273
        .await?;
219
3273
    Ok(transaction)
220
3273
}
221

            
222
/// Everything stored for the transaction, one sorted line per fact, without
223
/// the split and price ids an edit regenerates.
224
///
225
/// # Errors
226
/// The query failing.
227
109
pub async fn snapshot<'e>(
228
109
    executor: impl sqlx::PgExecutor<'e>,
229
109
    transaction: Uuid,
230
109
) -> Result<Vec<String>, sqlx::Error> {
231
109
    let facts = sqlx::query_file_scalar!("sql/select/transactions/snapshot.sql", transaction)
232
109
        .fetch_all(executor)
233
109
        .await?;
234
109
    Ok(facts.into_iter().flatten().collect())
235
109
}
236

            
237
/// The snapshot without its note line.
238
#[must_use]
239
3060
pub fn without_note(snapshot: &[String]) -> Vec<String> {
240
3060
    snapshot
241
3060
        .iter()
242
45720
        .filter(|fact| !fact.starts_with("tag note "))
243
        .cloned()
244
        .collect()
245
3060
}
246

            
247
/// The name of the first split tag the loaded payload gives row `r1`.
248
#[must_use]
249
720
pub fn first_row_tag(loaded: &str) -> Option<&str> {
250
720
    let (_, rest) = loaded.split_once("(:row \"r1\" :name \"")?;
251
720
    rest.split('"').next()
252
720
}
253

            
254
2160
fn facts<'a>(snapshot: &'a [String], kind: &str) -> impl Iterator<Item = &'a String> {
255
2160
    let prefix = format!("{kind} ");
256
2160
    snapshot
257
2160
        .iter()
258
26460
        .filter(move |fact| fact.starts_with(&prefix))
259
2160
}
260

            
261
/// The split-tag facts of the snapshot whose tag is named `name`.
262
#[must_use]
263
1440
pub fn split_tag_facts(snapshot: &[String], name: &str) -> Vec<String> {
264
1440
    let name = format!(" {name} ");
265
1440
    facts(snapshot, "split-tag")
266
3600
        .filter(|fact| fact.contains(&name))
267
        .cloned()
268
        .collect()
269
1440
}
270

            
271
/// The sorted transaction-tag facts of the snapshot, the note fact excluded.
272
#[must_use]
273
1260
pub fn tag_facts(snapshot: &[String]) -> Vec<String> {
274
1260
    let mut facts: Vec<_> = without_note(snapshot)
275
1260
        .into_iter()
276
16020
        .filter(|fact| fact.starts_with("tag "))
277
        .collect();
278
1260
    facts.sort();
279
1260
    facts
280
1260
}
281

            
282
/// Whether the snapshot holds three rows and, as split tags, exactly the
283
/// non-empty `kept` facts: what an edit that drops row `r2` and adds two
284
/// untagged rows stores.
285
#[must_use]
286
360
pub fn kept_only(snapshot: &[String], kept: &[String]) -> bool {
287
360
    !kept.is_empty()
288
360
        && facts(snapshot, "split").count() == 6
289
360
        && facts(snapshot, "split-tag").eq(kept.iter())
290
360
}