1
//! Transaction edit: the form opens from a `load-form` reply, keeps the
2
//! loaded text byte for byte, and submits it through the shared descriptor.
3

            
4
use forms::{FormValues, TRANSACTION_EDIT, write_payload};
5

            
6
use crate::app::App;
7
use crate::event::{Intent, apply};
8
use crate::form::{Form, FormKind};
9
use crate::modal::Modal;
10
use crate::route::{FormOptionsSource, Route, RouteCtx};
11
use crate::tabs::fetch::Fetch;
12
use crate::view::ViewId;
13
use crate::widgets::splits::{COL_TO, COL_VALUE};
14
use crate::widgets::{FocusedSubWidget, SplitsWidget, Widget};
15

            
16
pub(crate) const TX: &str = "11111111-0000-0000-0000-000000000001";
17
pub(super) const CASH: &str = "550e8400-e29b-41d4-a716-446655440011";
18
pub(super) const FOOD: &str = "550e8400-e29b-41d4-a716-446655440012";
19
pub(super) const BANK: &str = "550e8400-e29b-41d4-a716-446655440013";
20
pub(super) const USD: &str = "550e8400-e29b-41d4-a716-446655440010";
21
pub(super) const EUR: &str = "550e8400-e29b-41d4-a716-446655440014";
22

            
23
/// A `load-form` payload in descriptor order; the second row is cross-currency.
24
pub(crate) const PAYLOAD: &str = concat!(
25
    r#"(:id "11111111-0000-0000-0000-000000000001" :revision "rev-1" "#,
26
    r#":date "2024-06-01T12:34:56.123456Z" :note "a \"q\" back\\slash\nnext" :splits ("#,
27
    r#"(:key "r1" :from "550e8400-e29b-41d4-a716-446655440011" :to "550e8400-e29b-41d4-a716-446655440012" :from-commodity "550e8400-e29b-41d4-a716-446655440010" :to-commodity "550e8400-e29b-41d4-a716-446655440010" :value "10.00" :hidden "(:from-id \"h1\" :tags ((\"memo\" \"say \\\"hi\\\"\")))") "#,
28
    r#"(:key "r2" :from "550e8400-e29b-41d4-a716-446655440011" :to "550e8400-e29b-41d4-a716-446655440013" :from-commodity "550e8400-e29b-41d4-a716-446655440010" :to-commodity "550e8400-e29b-41d4-a716-446655440014" :value "5" :to-amount "4.50" :hidden "H2")) "#,
29
    r#":split-tags ((:row "r1" :name "category" :value "food") (:row "r2" :name "trip" :value "" :side "to")))"#
30
);
31

            
32
64
pub(crate) fn wire_of(text: &str) -> String {
33
64
    let escaped = text.replace('\\', "\\\\").replace('"', "\\\"");
34
64
    format!(r#"(:id 1 :value "{escaped}")"#)
35
64
}
36

            
37
150
pub(super) fn options_wire(items: &[(&str, &str)]) -> String {
38
150
    let items: Vec<String> = items
39
150
        .iter()
40
229
        .map(|(id, label)| format!(r#"(:id \"{id}\" :label \"{label}\")"#))
41
        .collect();
42
150
    format!(r#"(:id 2 :value "({})")"#, items.join(" "))
43
150
}
44

            
45
40
pub(super) fn deliver_options(app: &mut App, source: FormOptionsSource, wire: &str) {
46
40
    app.deliver_reply(
47
40
        Route {
48
40
            target: Some(app.window_of(ViewId::Accounts)),
49
40
            ctx: RouteCtx::FormOptions { seq: 1, source },
50
40
        },
51
40
        wire,
52
40
    );
53
40
}
54

            
55
12
pub(crate) fn open_edit_app() -> App {
56
12
    let mut app = crate::test_support::app();
57
12
    app.form_options_seq.advance();
58
12
    app.deliver_transaction_edit_reply(
59
12
        Some(app.window_of(crate::view::ViewId::Transactions)),
60
12
        &wire_of(PAYLOAD),
61
12
    );
62
12
    let accounts = options_wire(&[
63
12
        (CASH, "Assets:Cash"),
64
12
        (FOOD, "Expenses:Food"),
65
12
        (BANK, "Assets:Bank"),
66
12
    ]);
67
12
    deliver_options(&mut app, FormOptionsSource::FormAccounts, &accounts);
68
12
    let commodities = options_wire(&[(USD, "USD"), (EUR, "EUR")]);
69
12
    deliver_options(&mut app, FormOptionsSource::FormCommodities, &commodities);
70
12
    app
71
12
}
72

            
73
75
pub(crate) fn top_form(app: &App) -> &Form {
74
75
    match app.overlays.top() {
75
75
        Some(Modal::Form(form)) => form,
76
        other => panic!("expected a form, got {other:?}"),
77
    }
78
75
}
79

            
80
5
pub(crate) fn splits(form: &mut Form) -> &mut SplitsWidget {
81
5
    match &mut form.fields[3].widget {
82
5
        Widget::Splits(sw) => sw,
83
        other => panic!("field 2 must be Splits, got {other:?}"),
84
    }
85
5
}
86

            
87
11
pub(super) fn payload_of(values: &FormValues) -> String {
88
11
    write_payload(&TRANSACTION_EDIT, values)
89
11
}
90

            
91
3
fn pending_edit(app: &mut App) {
92
3
    let Some(Modal::Form(form)) = app.overlays.pop() else {
93
        panic!("edit form must be open");
94
    };
95
3
    app.lock_pending_form(5, form);
96
3
}
97

            
98
4
fn rejected(code: &str, message: &str, field: &str, detail_message: &str) -> String {
99
4
    let detail = format!(r#"((:FIELD "{field}" :MESSAGE "{detail_message}"))"#);
100
4
    format!(r#"(:id 5 :error (:code {code} :message "{message}" :detail {detail}))"#)
101
4
}
102

            
103
#[test]
104
1
fn the_reply_opens_a_form_holding_the_loaded_values_keys_and_hidden_data() {
105
1
    let mut app = crate::test_support::app();
106
1
    app.deliver_transaction_edit_reply(
107
1
        Some(app.window_of(crate::view::ViewId::Transactions)),
108
1
        &wire_of(PAYLOAD),
109
1
    );
110
1
    let form = top_form(&app);
111
1
    assert_eq!(form.kind, FormKind::TransactionEdit);
112
1
    assert_eq!(form.fields.len(), 4, "id and revision are not rendered");
113
1
    assert_eq!(form.fields[0].widget.value(), "2024-06-01T12:34:56.123456Z");
114
1
    assert_eq!(form.fields[1].widget.value(), "a \"q\" back\\slash\nnext");
115
1
    assert_eq!(
116
1
        form.hidden,
117
1
        [("id", TX.to_string()), ("revision", "rev-1".to_string())]
118
    );
119
1
    let Widget::Splits(sw) = &form.fields[3].widget else {
120
        panic!("field 2 must be Splits");
121
    };
122
1
    assert_eq!(sw.rows().len(), 2);
123
1
    assert_eq!(sw.rows()[1].text("key"), "r2");
124
1
    assert_eq!(sw.rows()[1].text("hidden"), "H2");
125
1
    assert_eq!(sw.rows()[1].text("to-amount"), "4.50");
126
1
}
127

            
128
#[test]
129
1
fn an_untouched_edit_submits_the_loaded_payload_byte_for_byte() {
130
1
    let app = open_edit_app();
131
1
    assert_eq!(payload_of(&top_form(&app).values()), PAYLOAD);
132
1
}
133

            
134
#[test]
135
1
fn a_cell_missing_from_the_options_is_still_submitted_as_loaded() {
136
1
    let mut app = open_edit_app();
137
1
    let renamed = options_wire(&[(CASH, "Assets:Wallet")]);
138
1
    deliver_options(&mut app, FormOptionsSource::FormAccounts, &renamed);
139
1
    let form = top_form(&app);
140
1
    assert_eq!(payload_of(&form.values()), PAYLOAD);
141
1
}
142

            
143
#[test]
144
1
fn changing_one_select_submits_the_chosen_uuid_for_that_cell_only() {
145
1
    let mut app = open_edit_app();
146
1
    let Some(Modal::Form(form)) = app.overlays.top_mut() else {
147
        panic!("edit form must be open");
148
    };
149
1
    let sw = splits(form);
150
1
    sw.focus_cell(0, "to");
151
1
    assert_eq!(sw.col_focus, COL_TO);
152
1
    let Some(FocusedSubWidget::Select(select)) = sw.focused_subwidget_mut() else {
153
        panic!("to must be a select");
154
    };
155
2
    while select.value() != BANK {
156
1
        select.next();
157
    }
158
1
    let expected = PAYLOAD.replacen(&format!("\"{FOOD}\""), &format!("\"{BANK}\""), 1);
159
1
    assert_eq!(payload_of(&top_form(&app).values()), expected);
160
1
}
161

            
162
#[test]
163
1
fn an_appended_row_has_no_key_or_hidden_and_loaded_rows_are_unchanged() {
164
1
    let mut app = open_edit_app();
165
1
    let Some(Modal::Form(form)) = app.overlays.top_mut() else {
166
        panic!("edit form must be open");
167
    };
168
1
    let sw = splits(form);
169
1
    sw.focus_cell(1, "value");
170
1
    sw.add_row();
171
1
    sw.col_focus = COL_VALUE;
172
1
    let Some(FocusedSubWidget::Amount(amount)) = sw.focused_subwidget_mut() else {
173
        panic!("value must be an amount");
174
    };
175
1
    "7".chars().for_each(|c| amount.insert_char(c));
176
1
    let values = top_form(&app).values();
177
1
    let rows = values.rows("splits").expect("rows");
178
1
    assert_eq!(rows.len(), 3);
179
1
    assert_eq!(rows[2].get("value").map(String::as_str), Some("7"));
180
1
    assert!(!rows[2].contains_key("key"));
181
1
    assert!(!rows[2].contains_key("hidden"));
182
1
    let untouched = open_edit_app();
183
1
    let loaded_rows = top_form(&untouched).values().rows("splits").expect("rows")[..2].to_vec();
184
1
    assert_eq!(rows[..2], loaded_rows);
185
1
}
186

            
187
#[test]
188
1
fn a_refusal_shows_its_reason_and_opens_no_form() {
189
1
    let mut app = crate::test_support::app();
190
1
    let refusal = r#"(:id 1 :error (:code args :message "this transaction has lot data"))"#;
191
1
    app.deliver_transaction_edit_reply(
192
1
        Some(app.window_of(crate::view::ViewId::Transactions)),
193
1
        refusal,
194
1
    );
195
1
    assert_eq!(
196
1
        app.status,
197
1
        "can't edit this transaction: this transaction has lot data"
198
    );
199
1
    assert!(app.overlays.is_empty());
200
1
}
201

            
202
#[test]
203
1
fn a_reply_that_is_not_a_payload_opens_no_form() {
204
1
    let mut app = crate::test_support::app();
205
1
    app.deliver_transaction_edit_reply(
206
1
        Some(app.window_of(crate::view::ViewId::Transactions)),
207
1
        "garbage",
208
1
    );
209
1
    assert!(app.status.starts_with("can't edit this transaction:"));
210
1
    assert!(app.overlays.is_empty());
211
1
}
212

            
213
#[test]
214
1
fn opening_without_a_console_says_so() {
215
1
    let mut app = crate::test_support::app();
216
1
    app.activate_window(app.window_of(crate::view::ViewId::Transactions));
217
1
    app.open_transaction_edit_async(TX);
218
1
    assert_eq!(app.status, "console not connected");
219
1
    assert!(app.overlays.is_empty());
220
1
}
221

            
222
#[test]
223
1
fn a_stale_edit_shows_the_reload_message_on_the_restored_form() {
224
1
    let mut app = open_edit_app();
225
1
    pending_edit(&mut app);
226
1
    let message = "the transaction changed since it was loaded; reload it";
227
1
    app.route_reply(
228
1
        5,
229
1
        &rejected("form-invalid", "1 field invalid", "revision", message),
230
1
    );
231
1
    let form = top_form(&app);
232
1
    assert_eq!(form.errors, [message]);
233
1
    assert!(
234
1
        app.status
235
1
            .ends_with("(close the form and open it again to reload)"),
236
        "{}",
237
        app.status
238
    );
239
1
    assert_eq!(form.focus, 0, "the hidden revision has nothing to focus");
240
1
    assert_eq!(payload_of(&form.values()), PAYLOAD, "the entry is kept");
241
1
}
242

            
243
#[test]
244
1
fn a_rejected_value_in_the_second_row_focuses_its_value_cell() {
245
1
    let mut app = open_edit_app();
246
1
    pending_edit(&mut app);
247
1
    let wire = rejected(
248
1
        "form-invalid",
249
1
        "1 field invalid",
250
1
        "splits.1.value",
251
1
        "is invalid",
252
1
    );
253
1
    app.route_reply(5, &wire);
254
1
    let form = top_form(&app);
255
1
    assert_eq!(form.errors, ["Row 2 \u{b7} Value: is invalid"]);
256
1
    assert_eq!(form.focus, 3);
257
1
    let Widget::Splits(sw) = &form.fields[3].widget else {
258
        panic!("field 2 must be Splits");
259
    };
260
1
    assert_eq!((sw.row_focus, sw.col_focus), (1, COL_VALUE));
261
1
}
262

            
263
#[test]
264
1
fn a_rejected_split_tag_opens_its_splits_list_on_the_cell_and_names_it() {
265
1
    let mut app = open_edit_app();
266
1
    pending_edit(&mut app);
267
1
    let wire = rejected(
268
1
        "form-invalid",
269
1
        "1 field invalid",
270
1
        "split-tags.1.value",
271
1
        "is required",
272
1
    );
273
1
    app.route_reply(5, &wire);
274
1
    let form = top_form(&app);
275
1
    assert_eq!(form.errors, ["Tag 2 \u{b7} Value: is required"]);
276
1
    assert_eq!(form.focus, 3);
277
1
    let Widget::Splits(sw) = &form.fields[3].widget else {
278
        panic!("field 3 must be Splits");
279
    };
280
1
    assert_eq!(sw.row_focus, 1);
281
1
    assert!(sw.tags_open());
282
1
    assert_eq!(sw.tags().and_then(|t| t.focused_key()), Some("value"));
283
1
}
284

            
285
/// Fronts the loaded Transactions window, the one an edit of its row acts on.
286
2
fn show_transactions(app: &mut App) {
287
2
    app.transactions_mut().state = Fetch::Loaded(Vec::new());
288
2
    app.switch_tab(ViewId::Transactions);
289
2
}
290

            
291
#[tokio::test]
292
1
async fn opening_dispatches_load_form_for_the_transaction() {
293
1
    let mut app = crate::test_support::app();
294
1
    let sent = app.attach_echo();
295
1
    show_transactions(&mut app);
296
1
    app.open_transaction_edit_async(TX);
297
1
    assert!(
298
1
        app.pending_routes
299
1
            .values()
300
1
            .any(|route| matches!(route.ctx, RouteCtx::TransactionEdit))
301
    );
302
1
    tokio::task::yield_now().await;
303
1
    app.drain_eval();
304
1
    let echoed = sent.frames().join("\n");
305
1
    assert!(
306
1
        echoed.contains(&format!(r#"(load-form "transaction-edit" "{TX}")"#)),
307
1
        "frame: {echoed}"
308
1
    );
309
1
}
310

            
311
#[tokio::test]
312
1
async fn submitting_dispatches_submit_form_with_the_edit_payload() {
313
1
    let mut app = open_edit_app();
314
1
    let sent = app.attach_echo();
315
1
    apply(&mut app, Intent::Submit);
316
1
    assert!(app.pending_form.is_some(), "the form waits for its reply");
317
1
    tokio::task::yield_now().await;
318
1
    app.drain_eval();
319
1
    let echoed = sent.frames().join("\n");
320
1
    assert!(
321
1
        echoed.contains(r#"(submit-form "transaction-edit" "(:id "#),
322
        "{echoed}"
323
    );
324
1
    assert!(
325
1
        echoed.contains(r#":revision \"rev-1\" :date \"2024-06-01T12:34:56.123456Z\""#),
326
        "{echoed}"
327
    );
328
1
    assert!(echoed.contains(r#":hidden \"H2\""#), "{echoed}");
329
1
}
330

            
331
#[test]
332
1
fn refreshed_options_keep_a_changed_select_and_the_untouched_loaded_cells() {
333
1
    let mut app = open_edit_app();
334
1
    let Some(Modal::Form(form)) = app.overlays.top_mut() else {
335
        panic!("edit form must be open");
336
    };
337
1
    let sw = splits(form);
338
1
    sw.focus_cell(0, "to");
339
1
    let Some(FocusedSubWidget::Select(select)) = sw.focused_subwidget_mut() else {
340
        panic!("to must be a select");
341
    };
342
2
    while select.value() != BANK {
343
1
        select.next();
344
    }
345
1
    let accounts = options_wire(&[
346
1
        (CASH, "Assets:Cash"),
347
1
        (FOOD, "Expenses:Food"),
348
1
        (BANK, "Assets:Bank"),
349
1
    ]);
350
1
    deliver_options(&mut app, FormOptionsSource::FormAccounts, &accounts);
351
1
    let expected = PAYLOAD.replacen(&format!("\"{FOOD}\""), &format!("\"{BANK}\""), 1);
352
1
    assert_eq!(payload_of(&top_form(&app).values()), expected);
353
1
}
354

            
355
#[test]
356
1
fn a_same_commodity_row_shows_no_conversion_arrow_after_binding() {
357
1
    let app = open_edit_app();
358
1
    let Widget::Splits(sw) = &top_form(&app).fields[3].widget else {
359
        panic!("field 2 must be Splits");
360
    };
361
1
    let grid = sw.grid(true, None, None);
362
1
    assert_eq!(crate::test_support::arrows(&grid, 0), 1);
363
1
    assert_eq!(crate::test_support::arrows(&grid, 1), 2);
364
1
}
365

            
366
#[tokio::test]
367
1
async fn a_second_open_while_loading_is_ignored() {
368
1
    let mut app = crate::test_support::app();
369
1
    app.attach_echo();
370
1
    show_transactions(&mut app);
371
1
    app.open_transaction_edit_async(TX);
372
1
    app.open_transaction_edit_async(TX);
373
1
    assert_eq!(app.pending_routes.len(), 1);
374
1
    assert_eq!(app.status, "the transaction is already loading");
375
1
}
376

            
377
#[test]
378
1
fn a_load_reply_over_another_dialog_is_dropped_with_a_status() {
379
1
    let mut app = crate::test_support::app();
380
1
    app.overlays.push(Modal::Form(Form::transaction_create()));
381
1
    app.deliver_transaction_edit_reply(
382
1
        Some(app.window_of(crate::view::ViewId::Transactions)),
383
1
        &wire_of(PAYLOAD),
384
1
    );
385
1
    assert_eq!(app.status, "edit dropped: another dialog is open");
386
1
    assert_eq!(top_form(&app).kind, FormKind::TransactionCreate);
387
1
}
388

            
389
#[test]
390
1
fn a_rejected_edit_keeps_the_split_tags() {
391
1
    let mut app = open_edit_app();
392
1
    let Some(Modal::Form(mut form)) = app.overlays.pop() else {
393
        panic!("edit form must be open");
394
    };
395
1
    let tag: forms::Row = [("row", "r2"), ("name", "trip")]
396
2
        .map(|(k, v)| (k.to_string(), v.to_string()))
397
        .into();
398
1
    splits(&mut form).load_tags(Some(std::slice::from_ref(&tag)));
399
1
    app.lock_pending_form(5, form);
400
1
    app.route_reply(
401
1
        5,
402
1
        &rejected("form-invalid", "1 field invalid", "note", "bad"),
403
1
    );
404
1
    assert_eq!(top_form(&app).values().rows("split-tags"), Some(&[tag][..]));
405
1
}
406

            
407
#[test]
408
1
fn picking_the_label_a_renamed_entity_gave_up_submits_that_entitys_uuid() {
409
1
    let mut app = crate::test_support::app();
410
1
    app.form_options_seq.advance();
411
1
    app.deliver_transaction_edit_reply(
412
1
        Some(app.window_of(crate::view::ViewId::Transactions)),
413
1
        &wire_of(PAYLOAD),
414
1
    );
415
1
    let renamed = options_wire(&[(CASH, "Assets:Wallet"), (BANK, "Cash ‹550e›")]);
416
1
    deliver_options(&mut app, FormOptionsSource::FormAccounts, &renamed);
417
1
    let Some(Modal::Form(form)) = app.overlays.top_mut() else {
418
        panic!("edit form must be open");
419
    };
420
1
    let sw = splits(form);
421
1
    sw.focus_cell(0, "from");
422
1
    let Some(FocusedSubWidget::Select(select)) = sw.focused_subwidget_mut() else {
423
        panic!("from must be a select");
424
    };
425
2
    while select.display() != "Cash ‹550e›" {
426
1
        select.next();
427
    }
428
1
    let expected = PAYLOAD.replacen(&format!("\"{CASH}\""), &format!("\"{BANK}\""), 1);
429
1
    assert_eq!(payload_of(&top_form(&app).values()), expected);
430
1
}
431

            
432
#[test]
433
1
fn an_empty_loaded_to_commodity_stays_empty_after_the_options_arrive() {
434
1
    let payload = PAYLOAD.replacen(&format!(":to-commodity \"{USD}\""), ":to-commodity \"\"", 1);
435
1
    let mut app = crate::test_support::app();
436
1
    app.form_options_seq.advance();
437
1
    app.deliver_transaction_edit_reply(
438
1
        Some(app.window_of(crate::view::ViewId::Transactions)),
439
1
        &wire_of(&payload),
440
1
    );
441
1
    let commodities = options_wire(&[(USD, "USD"), (EUR, "EUR")]);
442
1
    deliver_options(&mut app, FormOptionsSource::FormCommodities, &commodities);
443
1
    let form = top_form(&app);
444
1
    assert_eq!(
445
1
        payload_of(&form.values()),
446
1
        payload.replacen(" :to-commodity \"\"", "", 1)
447
    );
448
1
    let Widget::Splits(sw) = &form.fields[3].widget else {
449
        panic!("field 2 must be Splits");
450
    };
451
1
    assert_eq!(sw.rows()[0].to_commodity.display(), "same");
452
1
}