1
use chrono::Utc;
2
use finance::split::Split;
3
use server::command::FinanceEntity;
4
use server::command::transaction::CreateTransaction;
5
use sqlx::PgPool;
6
use uuid::Uuid;
7

            
8
use super::load_form;
9
use super::test_edit::{
10
    Fx, condition, create, detail_text, fields, fx, replace_once, rows_of, with_rows,
11
};
12
use super::test_seed::submit_edit;
13
use crate::natives::transaction::run_logical::run_create_transaction_logical;
14

            
15
const POSTED: &str = "2026-10-27T12:00:00Z";
16

            
17
#[sqlx::test(migrator = "server::db::MIGRATOR")]
18
async fn load_reply_shape(pool: PgPool) -> anyhow::Result<()> {
19
    let _guard = server::db::install_test_pool(pool.clone());
20
    let fx = fx(&pool).await?;
21
    let (cash, food, usd, eur) = (fx.cash, fx.food, fx.usd, fx.eur);
22
    let created = run_create_transaction_logical(
23
        fx.user,
24
        Some(format!(
25
            "(:date \"{POSTED}\" :note \"hi\" :splits (\
26
             (:from \"{cash}\" :to \"{food}\" :from-commodity \"{usd}\" :to-commodity \"{eur}\" \
27
             :value 10 :to-amount 9/2 :tags ((:name \"memo\" :value \"m\" :description \"d\")))))"
28
        )),
29
    )
30
    .await?;
31

            
32
    let reply = load_form(fx.user, "transaction-edit", &created).await?;
33

            
34
    let hidden = format!(
35
        "(:from-id \\\"{cash}\\\" :to-id \\\"{food}\\\" :from-commodity-id \\\"{usd}\\\" \
36
         :to-commodity-id \\\"{eur}\\\" :value \\\"10\\\" \
37
         :to-amount \\\"9/2\\\" :price-date \\\"{POSTED}\\\")"
38
    );
39
    let revision = reply
40
        .split(" :revision \"")
41
        .nth(1)
42
1
        .and_then(|rest| rest.split('"').next())
43
        .unwrap_or_default();
44
    assert_eq!(revision.len(), 64);
45
    assert_eq!(
46
        reply,
47
        format!(
48
            "(:id \"{created}\" :revision \"{revision}\" :date \"{POSTED}\" :note \"hi\" :tags () :splits ((:key \"r1\" :from \"{cash}\" \
49
             :to \"{food}\" :from-commodity \"{usd}\" :to-commodity \"{eur}\" :value \"10.00\" \
50
             :to-amount \"4.50\" :hidden \"{hidden}\")) \
51
             :split-tags ((:row \"r1\" :name \"memo\" :value \"m\" :description \"d\")))"
52
        )
53
    );
54
    Ok(())
55
}
56

            
57
#[sqlx::test(migrator = "server::db::MIGRATOR")]
58
async fn untagged_row_still_carries_hidden_and_empty_note(pool: PgPool) -> anyhow::Result<()> {
59
    let _guard = server::db::install_test_pool(pool.clone());
60
    let fx = fx(&pool).await?;
61
    let payload = format!("(:date \"{POSTED}\" :splits ({}))", fx.row("1", ""));
62
    let id = super::test_seed::submit_create(fx.user, &payload).await?;
63
    let reply = load_form(fx.user, "transaction-edit", &id).await?;
64
    assert!(reply.contains(":note \"\""), "{reply}");
65
    assert!(reply.contains(":hidden \"(:from-id"), "{reply}");
66
    assert!(reply.ends_with(":split-tags ())"), "{reply}");
67
    assert!(!reply.contains(":price-date"), "{reply}");
68
    assert!(!reply.contains(":to-amount"), "{reply}");
69
    assert!(reply.contains(":to-commodity \"\" "), "{reply}");
70
    Ok(())
71
}
72

            
73
4
async fn expect_refusal(fx: &Fx, id: &str, needle: &str) -> anyhow::Result<()> {
74
4
    let err = load_form(fx.user, "transaction-edit", id)
75
4
        .await
76
4
        .expect_err("must be refused");
77
4
    let condition = condition(&err);
78
4
    assert_eq!(condition.code, "args");
79
4
    assert!(condition.message.contains(needle), "{}", condition.message);
80
4
    Ok(())
81
4
}
82

            
83
25
pub(super) fn leg(fx: &Fx, tx_id: Uuid, account_id: Uuid, value_num: i64) -> Split {
84
25
    Split {
85
25
        id: Uuid::new_v4(),
86
25
        tx_id,
87
25
        account_id,
88
25
        commodity_id: fx.usd,
89
25
        value_num,
90
25
        value_denom: 1,
91
25
        reconcile_state: None,
92
25
        reconcile_date: None,
93
25
        lot_id: None,
94
25
    }
95
25
}
96

            
97
10
pub(super) async fn raw_transaction(
98
10
    fx: &Fx,
99
10
    splits: impl FnOnce(Uuid) -> Vec<Split>,
100
10
) -> anyhow::Result<Uuid> {
101
10
    let tx_id = Uuid::new_v4();
102
10
    let splits = splits(tx_id)
103
10
        .into_iter()
104
10
        .map(FinanceEntity::Split)
105
10
        .collect();
106
10
    CreateTransaction::new()
107
10
        .user_id(fx.user)
108
10
        .id(tx_id)
109
10
        .post_date(Utc::now())
110
10
        .enter_date(Utc::now())
111
10
        .splits(splits)
112
10
        .run()
113
10
        .await?;
114
10
    Ok(tx_id)
115
10
}
116

            
117
#[sqlx::test(migrator = "server::db::MIGRATOR")]
118
async fn ambiguous_pairing_is_refused(pool: PgPool) -> anyhow::Result<()> {
119
    let _guard = server::db::install_test_pool(pool.clone());
120
    let fx = fx(&pool).await?;
121
1
    let tx = raw_transaction(&fx, |tx| {
122
1
        vec![
123
1
            leg(&fx, tx, fx.cash, -100),
124
1
            leg(&fx, tx, fx.food, 60),
125
1
            leg(&fx, tx, fx.food, 40),
126
        ]
127
1
    })
128
    .await?;
129
    expect_refusal(&fx, &tx.to_string(), "paired").await
130
}
131

            
132
#[sqlx::test(migrator = "server::db::MIGRATOR")]
133
async fn reconciliation_data_is_refused(pool: PgPool) -> anyhow::Result<()> {
134
    let _guard = server::db::install_test_pool(pool.clone());
135
    let fx = fx(&pool).await?;
136
1
    let tx = raw_transaction(&fx, |tx| {
137
1
        let mut reconciled = leg(&fx, tx, fx.cash, -100);
138
1
        reconciled.reconcile_state = Some(true);
139
1
        vec![reconciled, leg(&fx, tx, fx.food, 100)]
140
1
    })
141
    .await?;
142
    expect_refusal(&fx, &tx.to_string(), "reconciliation").await
143
}
144

            
145
4
async fn uncleared_transaction(fx: &Fx) -> anyhow::Result<Uuid> {
146
4
    raw_transaction(fx, |tx| {
147
4
        let mut uncleared = leg(fx, tx, fx.cash, -100);
148
4
        uncleared.reconcile_state = Some(false);
149
4
        vec![uncleared, leg(fx, tx, fx.food, 100)]
150
4
    })
151
4
    .await
152
4
}
153

            
154
4
async fn states(pool: &PgPool, tx: Uuid) -> anyhow::Result<Vec<Option<bool>>> {
155
    Ok(
156
4
        sqlx::query_scalar(
157
4
            "SELECT reconcile_state FROM splits WHERE tx_id = $1 ORDER BY value_num",
158
4
        )
159
4
        .bind(tx)
160
4
        .fetch_all(pool)
161
4
        .await?,
162
    )
163
4
}
164

            
165
#[sqlx::test(migrator = "server::db::MIGRATOR")]
166
async fn an_untouched_edit_keeps_a_known_uncleared_split(pool: PgPool) -> anyhow::Result<()> {
167
    let _guard = server::db::install_test_pool(pool.clone());
168
    let fx = fx(&pool).await?;
169
    let tx = uncleared_transaction(&fx).await?;
170
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
171
    assert!(
172
        payload.contains(":from-reconcile \\\"false\\\""),
173
        "{payload}"
174
    );
175
    submit_edit(fx.user, &payload).await?;
176
    assert_eq!(states(&pool, tx).await?, [Some(false), None]);
177
    Ok(())
178
}
179

            
180
#[sqlx::test(migrator = "server::db::MIGRATOR")]
181
async fn a_note_only_edit_keeps_a_known_uncleared_split(pool: PgPool) -> anyhow::Result<()> {
182
    let _guard = server::db::install_test_pool(pool.clone());
183
    let fx = fx(&pool).await?;
184
    let tx = uncleared_transaction(&fx).await?;
185
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
186
    let edited = replace_once(&payload, ":note \"\"", ":note \"changed\"");
187
    submit_edit(fx.user, &edited).await?;
188
    assert_eq!(states(&pool, tx).await?, [Some(false), None]);
189
    Ok(())
190
}
191

            
192
#[sqlx::test(migrator = "server::db::MIGRATOR")]
193
async fn a_changed_row_keeps_the_state_of_its_splits(pool: PgPool) -> anyhow::Result<()> {
194
    let _guard = server::db::install_test_pool(pool.clone());
195
    let fx = fx(&pool).await?;
196
    let tx = uncleared_transaction(&fx).await?;
197
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
198
    let edited = replace_once(&payload, ":value \"100.00\"", ":value \"90\"");
199
    submit_edit(fx.user, &edited).await?;
200
    assert_eq!(states(&pool, tx).await?, [Some(false), None]);
201
    Ok(())
202
}
203

            
204
#[sqlx::test(migrator = "server::db::MIGRATOR")]
205
async fn an_appended_row_has_an_unknown_state(pool: PgPool) -> anyhow::Result<()> {
206
    let _guard = server::db::install_test_pool(pool.clone());
207
    let fx = fx(&pool).await?;
208
    let tx = uncleared_transaction(&fx).await?;
209
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
210
    let mut rows = rows_of(&payload);
211
    rows.push(fx.row("5", ""));
212
    submit_edit(fx.user, &with_rows(&payload, &rows)).await?;
213
    assert_eq!(
214
        states(&pool, tx).await?,
215
        [Some(false), None, None, None],
216
        "only the loaded row's from split is known"
217
    );
218
    Ok(())
219
}
220

            
221
#[sqlx::test(migrator = "server::db::MIGRATOR")]
222
async fn mismatched_rate_is_refused(pool: PgPool) -> anyhow::Result<()> {
223
    let _guard = server::db::install_test_pool(pool.clone());
224
    let fx = fx(&pool).await?;
225
    let tx = create(&fx, POSTED, &[fx.fx_row("10")]).await?;
226
    sqlx::query("UPDATE prices SET value_num = value_num + 1")
227
        .execute(&pool)
228
        .await?;
229
    expect_refusal(&fx, &tx.to_string(), "exchange rate").await
230
}
231

            
232
#[sqlx::test(migrator = "server::db::MIGRATOR")]
233
async fn tag_line_break_is_refused(pool: PgPool) -> anyhow::Result<()> {
234
    let _guard = server::db::install_test_pool(pool.clone());
235
    let fx = fx(&pool).await?;
236
    let (cash, food, usd) = (fx.cash, fx.food, fx.usd);
237
    let id = run_create_transaction_logical(
238
        fx.user,
239
        Some(format!(
240
            "(:splits ((:from \"{cash}\" :to \"{food}\" :from-commodity \"{usd}\" \
241
             :to-commodity \"{usd}\" :value 1 :tags ((:name \"memo\" :value \"a\nb\")))))"
242
        )),
243
    )
244
    .await?;
245
    expect_refusal(&fx, &id, "line break").await
246
}
247

            
248
#[sqlx::test(migrator = "server::db::MIGRATOR")]
249
async fn reconciled_after_load_is_a_stale_revision(pool: PgPool) -> anyhow::Result<()> {
250
    let _guard = server::db::install_test_pool(pool.clone());
251
    let fx = fx(&pool).await?;
252
    let tx = create(&fx, POSTED, &[fx.row("10", "")]).await?;
253
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
254
    sqlx::query("UPDATE splits SET reconcile_state = TRUE")
255
        .execute(&pool)
256
        .await?;
257
    let err = submit_edit(fx.user, &payload)
258
        .await
259
        .expect_err("must be stale");
260
    let condition = condition(&err);
261
    assert_eq!(condition.code, "form-invalid");
262
    assert_eq!(fields(&detail_text(&condition)), ["revision"]);
263
    Ok(())
264
}
265

            
266
#[sqlx::test(migrator = "server::db::MIGRATOR")]
267
async fn unchanged_transaction_without_refusal_still_submits(pool: PgPool) -> anyhow::Result<()> {
268
    let _guard = server::db::install_test_pool(pool.clone());
269
    let fx = fx(&pool).await?;
270
    let tx = create(&fx, POSTED, &[fx.row("10", "")]).await?;
271
    let payload = load_form(fx.user, "transaction-edit", &tx.to_string()).await?;
272
    submit_edit(fx.user, &payload).await?;
273
    Ok(())
274
}
275

            
276
#[sqlx::test(migrator = "server::db::MIGRATOR")]
277
async fn unknown_id_is_not_found_and_bad_input_is_args(pool: PgPool) -> anyhow::Result<()> {
278
    let _guard = server::db::install_test_pool(pool.clone());
279
    let fx = fx(&pool).await?;
280
    for (name, id, code) in [
281
        ("transaction-edit", Uuid::new_v4().to_string(), "not-found"),
282
        ("transaction-edit", "nope".to_string(), "args"),
283
        (
284
            "transaction-create",
285
            Uuid::new_v4().to_string(),
286
            "not-found",
287
        ),
288
    ] {
289
        let err = load_form(fx.user, name, &id).await.expect_err(code);
290
        assert_eq!(condition(&err).code, code, "{name} {id}");
291
    }
292
    Ok(())
293
}