1
//! `update-transaction` keeps the reconcile state, reconcile date and lot a
2
//! replacement split leaves out (plan 0016 H24).
3

            
4
use chrono::{DateTime, Utc};
5
use server::command::transaction::KeepStored;
6
use sqlx::PgPool;
7
use uuid::Uuid;
8

            
9
use super::parse::{parse_split_plist, parse_update_transaction_payload};
10
use super::run::run_update_transaction;
11
use super::run_logical::run_create_transaction_logical;
12
use super::tests_logical_update::{seed_account, seed_commodity, seed_user};
13

            
14
const KEEP_ALL: KeepStored = KeepStored {
15
    reconcile_state: true,
16
    reconcile_date: true,
17
    lot_id: true,
18
};
19

            
20
10
fn parsed(fields: &str) -> Result<(finance::split::Split, KeepStored), String> {
21
10
    let src = format!(
22
10
        "(:transaction-id \"{}\" :splits ((:account-id \"{a}\" :commodity-id \"{a}\" :value 1 {fields}) \
23
         (:account-id \"{a}\" :commodity-id \"{a}\" :value -1)))",
24
10
        Uuid::nil(),
25
10
        a = Uuid::nil()
26
    );
27
10
    let mut splits = parse_update_transaction_payload(&src)?
28
        .splits
29
6
        .ok_or("no splits")?;
30
6
    Ok(splits.remove(0))
31
10
}
32

            
33
#[test]
34
1
fn a_split_without_state_keys_keeps_every_stored_field() -> Result<(), String> {
35
1
    let (split, keep) = parsed("")?;
36
1
    assert_eq!(keep, KEEP_ALL);
37
1
    assert_eq!(
38
1
        (split.reconcile_state, split.reconcile_date, split.lot_id),
39
1
        (None, None, None)
40
    );
41
1
    Ok(())
42
1
}
43

            
44
#[test]
45
1
fn reconciled_takes_t_nil_and_unknown() -> Result<(), String> {
46
1
    for (token, state) in [("t", Some(true)), ("nil", Some(false)), (":unknown", None)] {
47
3
        let (split, keep) = parsed(&format!(":reconciled {token}"))?;
48
3
        assert_eq!(split.reconcile_state, state, "{token}");
49
3
        assert!(!keep.reconcile_state, "{token}");
50
3
        assert!(keep.reconcile_date && keep.lot_id, "{token}");
51
    }
52
1
    Ok(())
53
1
}
54

            
55
#[test]
56
1
fn a_given_date_and_lot_are_set_and_nil_clears_them() -> Result<(), String> {
57
1
    let lot = Uuid::new_v4();
58
1
    let (split, keep) = parsed(&format!(
59
1
        ":reconcile-date \"2026-01-02T03:04:05Z\" :lot-id \"{lot}\""
60
1
    ))?;
61
1
    let date: DateTime<Utc> = "2026-01-02T03:04:05Z".parse().map_err(|e| format!("{e}"))?;
62
1
    assert_eq!(
63
1
        (split.reconcile_date, split.lot_id),
64
1
        (Some(date), Some(lot))
65
    );
66
1
    assert!(!keep.reconcile_date && !keep.lot_id && keep.reconcile_state);
67
1
    let (split, keep) = parsed(":reconcile-date nil :lot-id nil")?;
68
1
    assert_eq!((split.reconcile_date, split.lot_id), (None, None));
69
1
    assert!(!keep.reconcile_date && !keep.lot_id);
70
1
    Ok(())
71
1
}
72

            
73
#[test]
74
1
fn malformed_state_values_name_the_split_and_key() {
75
1
    for (fields, expected) in [
76
1
        (
77
1
            ":reconciled 1",
78
1
            "split[0]: :reconciled must be t, nil or :unknown",
79
1
        ),
80
1
        (
81
1
            ":reconcile-date \"soon\"",
82
1
            "split[0]: invalid :reconcile-date 'soon'",
83
1
        ),
84
1
        (":lot-id \"x\"", "split[0]: invalid :lot-id 'x'"),
85
1
        (":lot-id 3", "split[0]: :lot-id must be a string or nil"),
86
1
    ] {
87
4
        let err = parsed(fields).map(|_| ()).unwrap_err();
88
4
        assert!(err.contains(expected), "{fields}: {err}");
89
    }
90
1
}
91

            
92
#[test]
93
1
fn a_create_split_ignores_what_it_would_keep() -> Result<(), String> {
94
1
    let program = nomiscript::Reader::parse(&format!(
95
1
        "(:account-id \"{a}\" :commodity-id \"{a}\" :value 1 :reconciled t)",
96
1
        a = Uuid::nil()
97
1
    ))
98
    .map_err(|e| format!("{e}"))?;
99
1
    let expr = program.exprs.into_iter().next().ok_or("empty")?;
100
1
    let (split, _) = parse_split_plist(expr, 0)?;
101
1
    assert_eq!(split.reconcile_state, Some(true));
102
1
    Ok(())
103
1
}
104

            
105
struct Reconciled {
106
    user: Uuid,
107
    tx: Uuid,
108
    commodity: Uuid,
109
    /// (id, value, account), the negative split first.
110
    splits: [(Uuid, i64, Uuid); 2],
111
    lot: Uuid,
112
    date: DateTime<Utc>,
113
}
114

            
115
/// A two-split transaction whose splits are reconciled, dated and in a lot.
116
6
async fn reconciled(pool: &PgPool) -> anyhow::Result<Reconciled> {
117
6
    let user = Uuid::new_v4();
118
6
    seed_user(pool, user).await?;
119
6
    let commodity = seed_commodity(user, "USD", "US Dollar").await?;
120
6
    let from = seed_account(user, "Assets").await?;
121
6
    let to = seed_account(user, "Expenses").await?;
122
6
    let create = format!(
123
6
        "(:splits ((:from \"{from}\" :to \"{to}\" :from-commodity \"{commodity}\" \
124
         :to-commodity \"{commodity}\" :value 5)))"
125
    );
126
6
    run_create_transaction_logical(user, Some(create))
127
6
        .await
128
        .map_err(|e| anyhow::anyhow!("{e}"))?;
129
6
    let lot = Uuid::new_v4();
130
6
    sqlx::query("INSERT INTO lots (id, account_id, is_closed) VALUES ($1, $2, 0)")
131
6
        .bind(lot)
132
6
        .bind(from)
133
6
        .execute(pool)
134
6
        .await?;
135
6
    let date: DateTime<Utc> = "2026-01-02T03:04:05Z".parse()?;
136
6
    sqlx::query("UPDATE splits SET reconcile_state = true, reconcile_date = $1, lot_id = $2")
137
6
        .bind(date)
138
6
        .bind(lot)
139
6
        .execute(pool)
140
6
        .await?;
141
    let rows: Vec<(Uuid, Uuid, i64, Uuid)> =
142
6
        sqlx::query_as("SELECT id, tx_id, value_num, account_id FROM splits ORDER BY value_num")
143
6
            .fetch_all(pool)
144
6
            .await?;
145
6
    let [(a, tx, a_value, a_account), (b, _, b_value, b_account)] = rows[..] else {
146
        anyhow::bail!("expected two splits: {rows:?}");
147
    };
148
6
    Ok(Reconciled {
149
6
        user,
150
6
        tx,
151
6
        commodity,
152
6
        splits: [(a, a_value, a_account), (b, b_value, b_account)],
153
6
        lot,
154
6
        date,
155
6
    })
156
6
}
157

            
158
/// A split's reconcile state, reconcile date and lot.
159
type Fields = (Option<bool>, Option<DateTime<Utc>>, Option<Uuid>);
160
type State = (Uuid, Option<bool>, Option<DateTime<Utc>>, Option<Uuid>);
161

            
162
5
async fn states(pool: &PgPool) -> anyhow::Result<Vec<State>> {
163
5
    Ok(sqlx::query_as(
164
5
        "SELECT id, reconcile_state, reconcile_date, lot_id FROM splits ORDER BY value_num",
165
5
    )
166
5
    .fetch_all(pool)
167
5
    .await?)
168
5
}
169

            
170
/// Replace the splits with these (id, value, account, extra keys).
171
5
async fn replace(f: &Reconciled, splits: &[(Uuid, i64, Uuid, &str)]) -> anyhow::Result<()> {
172
5
    let plists: String = splits
173
5
        .iter()
174
10
        .map(|(id, value, account, fields)| {
175
10
            format!(
176
10
                "(:id \"{id}\" :account-id \"{account}\" :commodity-id \"{}\" :value {value} {fields})",
177
10
                f.commodity
178
            )
179
10
        })
180
        .collect();
181
5
    let payload = format!("(:transaction-id \"{}\" :splits ({plists}))", f.tx);
182
5
    run_update_transaction(f.user, Some(payload))
183
5
        .await
184
        .map_err(|e| anyhow::anyhow!("{e}"))?;
185
5
    Ok(())
186
5
}
187

            
188
#[sqlx::test(migrator = "server::db::MIGRATOR")]
189
async fn a_replaced_reconciled_split_stays_reconciled_dated_and_in_its_lot(
190
    pool: PgPool,
191
) -> anyhow::Result<()> {
192
    let _guard = server::db::install_test_pool(pool.clone());
193
    let f = reconciled(&pool).await?;
194
    let [(a, a_value, a_account), (b, b_value, b_account)] = f.splits;
195

            
196
    replace(
197
        &f,
198
        &[(a, a_value, a_account, ""), (b, b_value, b_account, "")],
199
    )
200
    .await?;
201

            
202
    let kept = (Some(true), Some(f.date), Some(f.lot));
203
    assert_eq!(
204
        states(&pool).await?,
205
        [(a, kept.0, kept.1, kept.2), (b, kept.0, kept.1, kept.2)]
206
    );
207
    Ok(())
208
}
209

            
210
#[sqlx::test(migrator = "server::db::MIGRATOR")]
211
async fn given_state_keys_replace_the_stored_values(pool: PgPool) -> anyhow::Result<()> {
212
    let _guard = server::db::install_test_pool(pool.clone());
213
    let f = reconciled(&pool).await?;
214
    let [(a, a_value, a_account), (b, b_value, b_account)] = f.splits;
215

            
216
    replace(
217
        &f,
218
        &[
219
            (a, a_value, a_account, ":reconciled nil :reconcile-date nil"),
220
            (b, b_value, b_account, ":lot-id nil"),
221
        ],
222
    )
223
    .await?;
224

            
225
    assert_eq!(
226
        states(&pool).await?,
227
        [
228
            (a, Some(false), None, Some(f.lot)),
229
            (b, Some(true), Some(f.date), None)
230
        ]
231
    );
232
    Ok(())
233
}
234

            
235
#[sqlx::test(migrator = "server::db::MIGRATOR")]
236
async fn a_split_with_a_new_id_keeps_nothing(pool: PgPool) -> anyhow::Result<()> {
237
    let _guard = server::db::install_test_pool(pool.clone());
238
    let f = reconciled(&pool).await?;
239
    let [(a, a_value, a_account), (_, b_value, b_account)] = f.splits;
240
    let fresh = Uuid::new_v4();
241

            
242
    replace(
243
        &f,
244
        &[(a, a_value, a_account, ""), (fresh, b_value, b_account, "")],
245
    )
246
    .await?;
247

            
248
    assert_eq!(
249
        states(&pool).await?,
250
        [
251
            (a, Some(true), Some(f.date), Some(f.lot)),
252
            (fresh, None, None, None)
253
        ]
254
    );
255
    Ok(())
256
}
257

            
258
#[sqlx::test(migrator = "server::db::MIGRATOR")]
259
async fn a_split_moved_to_another_account_keeps_nothing(pool: PgPool) -> anyhow::Result<()> {
260
    let _guard = server::db::install_test_pool(pool.clone());
261
    let f = reconciled(&pool).await?;
262
    let [(a, a_value, a_account), (b, b_value, b_account)] = f.splits;
263

            
264
    replace(
265
        &f,
266
        &[(a, a_value, b_account, ""), (b, b_value, a_account, "")],
267
    )
268
    .await?;
269

            
270
    assert_eq!(
271
        states(&pool).await?,
272
        [(a, None, None, None), (b, None, None, None)]
273
    );
274
    Ok(())
275
}
276

            
277
#[sqlx::test(migrator = "server::db::MIGRATOR")]
278
async fn a_changed_amount_keeps_the_lot_but_not_the_reconciliation(
279
    pool: PgPool,
280
) -> anyhow::Result<()> {
281
    let _guard = server::db::install_test_pool(pool.clone());
282
    let f = reconciled(&pool).await?;
283
    let [(a, a_value, a_account), (b, b_value, b_account)] = f.splits;
284

            
285
    replace(
286
        &f,
287
        &[
288
            (a, a_value * 2, a_account, ""),
289
            (b, b_value * 2, b_account, ""),
290
        ],
291
    )
292
    .await?;
293

            
294
    assert_eq!(
295
        states(&pool).await?,
296
        [(a, None, None, Some(f.lot)), (b, None, None, Some(f.lot))]
297
    );
298
    Ok(())
299
}
300

            
301
#[sqlx::test(migrator = "server::db::MIGRATOR")]
302
async fn create_transaction_stores_given_split_state(pool: PgPool) -> anyhow::Result<()> {
303
    let _guard = server::db::install_test_pool(pool.clone());
304
    let f = reconciled(&pool).await?;
305
    let [(_, _, a_account), (_, _, b_account)] = f.splits;
306
    sqlx::query("DELETE FROM splits").execute(&pool).await?;
307
    let payload = format!(
308
        "(:post-date \"2026-03-01T00:00:00Z\" :splits (\
309
         (:account-id \"{a_account}\" :commodity-id \"{c}\" :value -3 :reconciled t \
310
          :reconcile-date \"2026-01-02T03:04:05Z\" :lot-id \"{lot}\") \
311
         (:account-id \"{b_account}\" :commodity-id \"{c}\" :value 3 :RECONCILED :unknown)))",
312
        c = f.commodity,
313
        lot = f.lot
314
    );
315

            
316
    super::run::run_create_transaction(f.user, Some(payload))
317
        .await
318
        .map_err(|e| anyhow::anyhow!("{e}"))?;
319

            
320
    let stored: Vec<Fields> = sqlx::query_as(
321
        "SELECT reconcile_state, reconcile_date, lot_id FROM splits ORDER BY value_num",
322
    )
323
    .fetch_all(&pool)
324
    .await?;
325
    assert_eq!(
326
        stored,
327
        [(Some(true), Some(f.date), Some(f.lot)), (None, None, None)]
328
    );
329
    Ok(())
330
}