1
use server::command::transaction::{SetTransactionTag, UpdateTransaction};
2
use sqlx::PgPool;
3
use uuid::Uuid;
4

            
5
use super::test_edit::{
6
    Fx, condition, create, detail_text, fields, fx, post_date, price_dates, rename_symbol,
7
    replace_once, row, rows_of, set_price_date, split_accounts, split_commodities, with_rows,
8
    without_revision,
9
};
10
use super::test_seed::submit_edit;
11
use super::test_seed::{seed_account, seed_child_account, seed_commodity};
12
use super::{form_options, load_form};
13

            
14
const POSTED: &str = "2026-10-27T12:00:00Z";
15
const OLD_PRICE: &str = "2026-10-20T10:11:12.345678Z";
16

            
17
3
async fn dates_by_rate(pool: &PgPool) -> anyhow::Result<Vec<(i64, String)>> {
18
    let rows: Vec<(i64, chrono::DateTime<chrono::Utc>)> =
19
3
        sqlx::query_as("SELECT value_num, price_date FROM prices ORDER BY value_num")
20
3
            .fetch_all(pool)
21
3
            .await?;
22
3
    Ok(rows
23
3
        .into_iter()
24
6
        .map(|(rate, date)| (rate, date.to_rfc3339()))
25
        .collect())
26
3
}
27

            
28
#[sqlx::test(migrator = "server::db::MIGRATOR")]
29
async fn defaulted_to_commodity_never_drops_a_renamed_row(pool: PgPool) -> anyhow::Result<()> {
30
    let _guard = server::db::install_test_pool(pool.clone());
31
    let fx = fx(&pool).await?;
32
    let tx = create(&fx, POSTED, &[fx.fx_row("10")]).await?;
33
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
34
    rename_symbol(&pool, "USD", "DOLLAR").await?;
35

            
36
    let cleared = replace_once(&payload, &format!(":to-commodity \"{}\" ", fx.eur), "");
37
    let err = submit_edit(fx.user, &cleared)
38
        .await
39
        .expect_err("the row now has a to-amount without a second commodity");
40
    assert_eq!(condition(&err).code, "form-invalid");
41
    assert_eq!(split_commodities(&pool, tx).await?.len(), 2);
42

            
43
    let plain = replace_once(&cleared, ":to-amount \"9.00\" ", "");
44
    submit_edit(fx.user, &plain).await?;
45
    let commodities = split_commodities(&pool, tx).await?;
46
    assert_eq!(commodities, [fx.usd, fx.usd]);
47
    Ok(())
48
}
49

            
50
#[sqlx::test(migrator = "server::db::MIGRATOR")]
51
async fn value_spelling_keeps_the_price_date(pool: PgPool) -> anyhow::Result<()> {
52
    let _guard = server::db::install_test_pool(pool.clone());
53
    let fx = fx(&pool).await?;
54
    let tx = create(&fx, POSTED, &[fx.fx_row("10")]).await?;
55
    set_price_date(&pool, OLD_PRICE).await?;
56
    let before = price_dates(&pool).await?;
57
    for spelling in ["10", "20/2"] {
58
        let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
59
        let respelled = replace_once(
60
            &payload,
61
            ":value \"10.00\" :to-amount",
62
            &format!(":value \"{spelling}\" :to-amount"),
63
        );
64
        submit_edit(fx.user, &respelled).await?;
65
        assert_eq!(price_dates(&pool).await?, before, "{spelling}");
66
    }
67
    Ok(())
68
}
69

            
70
#[sqlx::test(migrator = "server::db::MIGRATOR")]
71
async fn reordered_fx_rows_keep_their_own_dates(pool: PgPool) -> anyhow::Result<()> {
72
    let _guard = server::db::install_test_pool(pool.clone());
73
    let fx = fx(&pool).await?;
74
    let rows = [
75
        fx.fx_row("10"),
76
        fx.row(
77
            "20",
78
            &format!(":to-commodity \"{}\" :to-amount \"15\"", fx.eur),
79
        ),
80
    ];
81
    let tx = create(&fx, POSTED, &rows).await?;
82
    sqlx::query("UPDATE prices SET price_date = '2026-10-01T00:00:00.5Z' WHERE value_num = 10")
83
        .execute(&pool)
84
        .await?;
85
    sqlx::query("UPDATE prices SET price_date = '2026-10-02T00:00:00.25Z' WHERE value_num = 4")
86
        .execute(&pool)
87
        .await?;
88
    let before = dates_by_rate(&pool).await?;
89
    assert_ne!(before[0].1, before[1].1);
90

            
91
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
92
    let mut rows = rows_of(&payload);
93
    rows.reverse();
94
    submit_edit(fx.user, &with_rows(&payload, &rows)).await?;
95
    assert_eq!(dates_by_rate(&pool).await?, before);
96
    Ok(())
97
}
98

            
99
#[sqlx::test(migrator = "server::db::MIGRATOR")]
100
async fn appended_fx_row_takes_the_post_date(pool: PgPool) -> anyhow::Result<()> {
101
    let _guard = server::db::install_test_pool(pool.clone());
102
    let fx = fx(&pool).await?;
103
    let tx = create(&fx, POSTED, &[fx.fx_row("10")]).await?;
104
    set_price_date(&pool, OLD_PRICE).await?;
105
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
106
    let mut rows = rows_of(&payload);
107
    rows.push(format!(
108
        "(:key \"\" :from \"{}\" :to \"{}\" :from-commodity \"{}\" :to-commodity \"{}\" \
109
         :value \"5\" :to-amount \"4\")",
110
        fx.cash, fx.food, fx.usd, fx.eur
111
    ));
112
    submit_edit(fx.user, &with_rows(&payload, &rows)).await?;
113

            
114
    let posted = post_date(&pool, tx).await?.to_rfc3339();
115
    let dates = dates_by_rate(&pool).await?;
116
    assert_eq!(dates.len(), 2);
117
    assert_eq!(dates[0], (5, posted));
118
    assert_eq!(dates[1].0, 10);
119
    assert!(dates[1].1.starts_with("2026-10-20T10:11:12.345678"));
120
    Ok(())
121
}
122

            
123
#[sqlx::test(migrator = "server::db::MIGRATOR")]
124
async fn renamed_commodity_keeps_its_identity(pool: PgPool) -> anyhow::Result<()> {
125
    let _guard = server::db::install_test_pool(pool.clone());
126
    let fx = fx(&pool).await?;
127
    let tx = create(&fx, POSTED, &[fx.row("10", "")]).await?;
128
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
129
    rename_symbol(&pool, "USD", "DOLLAR").await?;
130
    let impostor = seed_commodity(fx.user, "USD").await?;
131

            
132
    submit_edit(fx.user, &payload).await?;
133
    assert_eq!(split_commodities(&pool, tx).await?, [fx.usd, fx.usd]);
134
    assert_ne!(fx.usd, impostor);
135
    Ok(())
136
}
137

            
138
#[sqlx::test(migrator = "server::db::MIGRATOR")]
139
async fn a_changed_cell_moves_the_split(pool: PgPool) -> anyhow::Result<()> {
140
    let _guard = server::db::install_test_pool(pool.clone());
141
    let fx = fx(&pool).await?;
142
    let tx = create(&fx, POSTED, &[fx.row("10", "")]).await?;
143
    let other = seed_account(fx.user, "Other").await?;
144
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
145

            
146
    let moved = replace_once(
147
        &payload,
148
        &format!(":to \"{}\" ", fx.food),
149
        &format!(":to \"{other}\" "),
150
    );
151
    submit_edit(fx.user, &moved).await?;
152
    let accounts = split_accounts(&pool, tx).await?;
153
    assert!(accounts.contains(&other) && !accounts.contains(&fx.food));
154
    Ok(())
155
}
156

            
157
#[sqlx::test(migrator = "server::db::MIGRATOR")]
158
async fn transaction_tags_survive_an_edit(pool: PgPool) -> anyhow::Result<()> {
159
    let _guard = server::db::install_test_pool(pool.clone());
160
    let fx = fx(&pool).await?;
161
    let tx = create(&fx, POSTED, &[fx.row("10", "")]).await?;
162
    SetTransactionTag::new()
163
        .user_id(fx.user)
164
        .transaction_id(tx)
165
        .tag_name("project".to_string())
166
        .tag_value("x".to_string())
167
        .run()
168
        .await?;
169
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
170
    submit_edit(fx.user, &payload).await?;
171
    let tags: Vec<String> = sqlx::query_scalar(
172
        "SELECT t.tag_name || '=' || t.tag_value FROM transaction_tags tt \
173
         JOIN tags t ON t.id = tt.tag_id WHERE tt.tx_id = $1 AND t.tag_name <> 'note'",
174
    )
175
    .bind(tx)
176
    .fetch_all(&pool)
177
    .await?;
178
    assert_eq!(tags, ["project=x"]);
179
    Ok(())
180
}
181

            
182
#[sqlx::test(migrator = "server::db::MIGRATOR")]
183
async fn stale_load_is_refused_and_reload_accepted(pool: PgPool) -> anyhow::Result<()> {
184
    let _guard = server::db::install_test_pool(pool.clone());
185
    let fx = fx(&pool).await?;
186
    let tx = create(&fx, POSTED, &[fx.row("10", "")]).await?;
187
    let stale = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
188
    UpdateTransaction::new()
189
        .user_id(fx.user)
190
        .transaction_id(tx)
191
        .note("changed elsewhere".to_string())
192
        .run()
193
        .await?;
194

            
195
    let err = submit_edit(fx.user, &stale).await.expect_err("stale");
196
    let condition = condition(&err);
197
    assert_eq!(condition.code, "form-invalid");
198
    let detail = detail_text(&condition);
199
    assert_eq!(fields(&detail), ["revision"]);
200
    assert!(detail.contains("changed since it was loaded"), "{detail}");
201

            
202
    let fresh = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
203
    assert!(fresh.contains(":note \"changed elsewhere\""), "{fresh}");
204
    submit_edit(fx.user, &fresh).await?;
205
    Ok(())
206
}
207

            
208
#[sqlx::test(migrator = "server::db::MIGRATOR")]
209
async fn padded_name_gets_a_uuid_key_and_its_twin_stays_pickable(
210
    pool: PgPool,
211
) -> anyhow::Result<()> {
212
    let _guard = server::db::install_test_pool(pool.clone());
213
    let fx = fx(&pool).await?;
214
    let padded = seed_account(fx.user, "Padded").await?;
215
    sqlx::query("UPDATE tags SET tag_value = 'Cash ' WHERE tag_value = 'Padded'")
216
        .execute(&pool)
217
        .await?;
218
    let twin = fx.cash;
219
    let tx = create(
220
        &fx,
221
        POSTED,
222
        &[row(
223
            &padded.to_string(),
224
            &fx.food.to_string(),
225
            &fx.usd.to_string(),
226
            "10",
227
            "",
228
        )],
229
    )
230
    .await?;
231
    let options = form_options(fx.user, "accounts").await?;
232
    assert!(options.contains(&format!(
233
        ":id \"{padded}\" :label \"Cash \" :alias \"Cash \""
234
    )));
235
    assert!(options.contains(&format!(":id \"{twin}\" :label \"Cash\" :alias \"Cash\"")));
236

            
237
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
238
    assert!(
239
        payload.contains(&format!(":from \"{padded}\"")),
240
        "{payload}"
241
    );
242
    submit_edit(fx.user, &payload).await?;
243
    assert!(split_accounts(&pool, tx).await?.contains(&padded));
244

            
245
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
246
    let picked = replace_once(
247
        &payload,
248
        &format!(":from \"{padded}\""),
249
        &format!(":from \"{twin}\""),
250
    );
251
    submit_edit(fx.user, &picked).await?;
252
    let accounts = split_accounts(&pool, tx).await?;
253
    assert!(accounts.contains(&twin) && !accounts.contains(&padded));
254
    Ok(())
255
}
256

            
257
3
fn fx_row_from(fx: &Fx, from: Uuid, value: &str) -> String {
258
3
    row(
259
3
        &from.to_string(),
260
3
        &fx.food.to_string(),
261
3
        &fx.usd.to_string(),
262
3
        value,
263
3
        "",
264
3
    )
265
3
}
266

            
267
2
fn wallet_row(fx: &Fx, from: &str) -> String {
268
2
    format!(
269
2
        "(:key \"\" :from \"{from}\" :to \"{}\" :from-commodity \"{}\" :value \"2\")",
270
2
        fx.food, fx.usd
271
    )
272
2
}
273

            
274
#[sqlx::test(migrator = "server::db::MIGRATOR")]
275
async fn path_labels_are_refused_and_ambiguous_ones_key_by_uuid(
276
    pool: PgPool,
277
) -> anyhow::Result<()> {
278
    let _guard = server::db::install_test_pool(pool.clone());
279
    let fx = fx(&pool).await?;
280
    let assets = seed_account(fx.user, "Assets").await?;
281
    let nested = seed_child_account(fx.user, "Wallet", assets).await?;
282
    let tx = create(&fx, POSTED, &[fx.row("10", "")]).await?;
283
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
284
    let mut rows = rows_of(&payload);
285
    rows.push(wallet_row(&fx, &nested.to_string()));
286
    submit_edit(fx.user, &with_rows(&payload, &rows)).await?;
287
    assert!(split_accounts(&pool, tx).await?.contains(&nested));
288

            
289
    let twin = seed_account(fx.user, "Assets:Wallet").await?;
290
    let siblings = seed_child_account(fx.user, "Wallet", assets).await?;
291
    let options = form_options(fx.user, "accounts").await?;
292
    for id in [nested, twin, siblings] {
293
        assert!(options.contains(&format!("(:id \"{id}\"")), "{options}");
294
    }
295
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
296
    let mut rows = rows_of(&payload);
297
    rows.push(wallet_row(&fx, "Assets:Wallet"));
298
    let err = submit_edit(fx.user, &with_rows(&payload, &rows))
299
        .await
300
        .expect_err("a path is not an id");
301
    let detail = detail_text(&condition(&err));
302
    assert_eq!(fields(&detail), ["splits.2.from"]);
303
    Ok(())
304
}
305

            
306
#[sqlx::test(migrator = "server::db::MIGRATOR")]
307
async fn unfit_names_round_trip_by_id(pool: PgPool) -> anyhow::Result<()> {
308
    let _guard = server::db::install_test_pool(pool.clone());
309
    let fx = fx(&pool).await?;
310
    let pipe = seed_account(fx.user, "Expenses|Fx").await?;
311
    let newline = seed_account(fx.user, "Line\nBreak").await?;
312
    let cr = seed_account(fx.user, "A\rB").await?;
313
    let tx = create(
314
        &fx,
315
        POSTED,
316
        &[
317
            fx_row_from(&fx, pipe, "10"),
318
            fx_row_from(&fx, newline, "5"),
319
            fx_row_from(&fx, cr, "2"),
320
        ],
321
    )
322
    .await?;
323
    let options = form_options(fx.user, "accounts").await?;
324
    for id in [pipe, newline, cr] {
325
        assert!(!options.contains(&format!(":id \"{id}\" :label \"{id}\"")));
326
    }
327

            
328
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
329
    for id in [pipe, newline, cr] {
330
        assert!(payload.contains(&format!(":from \"{id}\"")), "{payload}");
331
    }
332
    assert!(!payload.contains("Expenses|Fx"), "{payload}");
333
    submit_edit(fx.user, &payload).await?;
334
    let again = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
335
    assert_eq!(without_revision(&payload), without_revision(&again));
336
    let accounts = split_accounts(&pool, tx).await?;
337
    assert!(accounts.contains(&pipe) && accounts.contains(&newline) && accounts.contains(&cr));
338
    Ok(())
339
}