1
//! Account edit: the form opens from a `load-form` reply, takes the parent
2
//! options, and submits and settles through the shared descriptor.
3

            
4
use forms::{ACCOUNT_EDIT, FormValues, Row, write_payload};
5

            
6
use super::edit::{deliver_options, options_wire, top_form, wire_of};
7
use crate::app::App;
8
use crate::event::{Intent, apply};
9
use crate::form::{Form, FormKind};
10
use crate::modal::Modal;
11
use crate::route::{FormOptionsSource, Route, RouteCtx};
12
use crate::tabs::fetch::Fetch;
13
use crate::view::ViewId;
14
use crate::widgets::Widget;
15

            
16
const ACCOUNT: &str = "22222222-0000-0000-0000-000000000001";
17
const ROOT: &str = "550e8400-e29b-41d4-a716-446655440031";
18
const PARENT: &str = "550e8400-e29b-41d4-a716-446655440032";
19

            
20
19
fn row(cells: &[(&str, &str)]) -> Row {
21
19
    cells
22
19
        .iter()
23
37
        .map(|(key, text)| (key.to_string(), text.to_string()))
24
        .collect()
25
19
}
26

            
27
8
fn payload() -> String {
28
8
    let mut values = FormValues::default();
29
8
    values.set("id", ACCOUNT);
30
8
    values.set("revision", "rev-1");
31
8
    values.set("name", "Cash");
32
8
    values.set("parent", PARENT);
33
8
    values.set_rows("tags");
34
8
    values.push_row("tags", row(&[("name", "type"), ("value", "asset")]));
35
8
    values.push_row("tags", row(&[("name", "memo"), ("value", "daily")]));
36
8
    write_payload(&ACCOUNT_EDIT, &values)
37
8
}
38

            
39
8
fn open_app() -> App {
40
8
    let mut app = crate::test_support::app();
41
8
    app.form_options_seq.advance();
42
8
    app.deliver_account_edit_reply(
43
8
        Some(app.window_of(crate::view::ViewId::Accounts)),
44
8
        &wire_of(&payload()),
45
8
    );
46
8
    app
47
8
}
48

            
49
3
fn accounts() -> String {
50
3
    options_wire(&[
51
3
        (ROOT, "Assets"),
52
3
        (PARENT, "Assets:Bank"),
53
3
        (ACCOUNT, "Assets:Cash"),
54
3
    ])
55
3
}
56

            
57
4
fn pending_edit(app: &mut App) {
58
4
    let Some(Modal::Form(form)) = app.overlays.pop() else {
59
        panic!("edit form must be open");
60
    };
61
4
    app.lock_pending_form(5, form);
62
4
}
63

            
64
2
fn rejected(message: &str, field: &str) -> String {
65
2
    let detail = format!(r#"((:FIELD "{field}" :MESSAGE "{message}"))"#);
66
2
    format!(r#"(:id 5 :error (:code form-invalid :message "1 field invalid" :detail {detail}))"#)
67
2
}
68

            
69
4
fn tags(form: &Form) -> &crate::widgets::RowsWidget {
70
4
    match &form.fields[2].widget {
71
4
        Widget::Rows(rw) => rw,
72
        other => panic!("field 2 must be Rows, got {other:?}"),
73
    }
74
4
}
75

            
76
#[test]
77
1
fn the_reply_fills_name_tags_and_hidden_values() {
78
1
    let app = open_app();
79
1
    let form = top_form(&app);
80
1
    assert_eq!(form.kind, FormKind::AccountEdit);
81
1
    assert_eq!(form.fields.len(), 3, "id and revision are not rendered");
82
1
    assert_eq!(form.fields[0].widget.value(), "Cash");
83
1
    assert_eq!(
84
1
        form.hidden,
85
1
        [
86
1
            ("id", ACCOUNT.to_string()),
87
1
            ("revision", "rev-1".to_string())
88
1
        ]
89
    );
90
1
    assert_eq!(tags(form).values().map_or(0, |rows| rows.len()), 2);
91
1
    assert_eq!(
92
1
        form.values().rows("tags"),
93
1
        Some(
94
1
            &[
95
1
                row(&[("name", "type"), ("value", "asset")]),
96
1
                row(&[("name", "memo"), ("value", "daily")])
97
1
            ][..]
98
1
        )
99
    );
100
1
}
101

            
102
#[test]
103
1
fn the_parent_options_keep_the_loaded_parent_selected() {
104
1
    let mut app = open_app();
105
1
    deliver_options(&mut app, FormOptionsSource::FormAccounts, &accounts());
106
1
    let form = top_form(&app);
107
1
    let Widget::Select(select) = &form.fields[1].widget else {
108
        panic!("field 1 must be the parent select");
109
    };
110
1
    assert_eq!(select.options().len(), 4, "(none) and the three accounts");
111
1
    assert_eq!(select.value(), PARENT);
112
1
    assert_eq!(select.display(), "Assets:Bank");
113
1
}
114

            
115
#[test]
116
1
fn the_values_before_the_options_arrive_keep_the_loaded_parent() {
117
1
    let app = open_app();
118
1
    assert_eq!(top_form(&app).values().text("parent"), Some(PARENT));
119
1
}
120

            
121
#[test]
122
1
fn a_root_account_selects_none_after_the_options_arrive() {
123
1
    let mut app = crate::test_support::app();
124
1
    app.form_options_seq.advance();
125
1
    let mut values = FormValues::default();
126
1
    values.set("id", ACCOUNT);
127
1
    values.set("revision", "rev-1");
128
1
    values.set("name", "Assets");
129
1
    values.set("parent", "");
130
1
    app.deliver_account_edit_reply(
131
1
        Some(app.window_of(crate::view::ViewId::Accounts)),
132
1
        &wire_of(&write_payload(&ACCOUNT_EDIT, &values)),
133
1
    );
134
1
    deliver_options(&mut app, FormOptionsSource::FormAccounts, &accounts());
135
1
    assert_eq!(top_form(&app).values().text("parent"), Some(""));
136
1
}
137

            
138
#[tokio::test]
139
1
async fn opening_dispatches_load_form_for_the_account() {
140
1
    let mut app = crate::test_support::app();
141
1
    let sent = app.attach_echo();
142
1
    app.open_account_edit_async(ACCOUNT);
143
1
    assert!(
144
1
        app.pending_routes
145
1
            .values()
146
1
            .any(|route| matches!(route.ctx, RouteCtx::AccountEdit))
147
    );
148
1
    tokio::task::yield_now().await;
149
1
    app.drain_eval();
150
1
    let echoed = sent.frames().join("\n");
151
1
    assert!(
152
1
        echoed.contains(&format!(r#"(load-form "account-edit" "{ACCOUNT}")"#)),
153
1
        "frame: {echoed}"
154
1
    );
155
1
}
156

            
157
#[test]
158
1
fn opening_without_a_console_says_so() {
159
1
    let mut app = crate::test_support::app();
160
1
    app.open_account_edit_async(ACCOUNT);
161
1
    assert_eq!(app.status, "console not connected");
162
1
    assert!(app.overlays.is_empty());
163
1
}
164

            
165
#[test]
166
1
fn a_refused_load_shows_why() {
167
1
    let mut app = crate::test_support::app();
168
1
    app.deliver_account_edit_reply(
169
1
        Some(app.window_of(crate::view::ViewId::Accounts)),
170
1
        r#"(:id 1 :error (:code not-found :message "gone"))"#,
171
1
    );
172
1
    assert!(
173
1
        app.status.starts_with("can't edit this account"),
174
        "{}",
175
        app.status
176
    );
177
1
    assert!(app.overlays.is_empty());
178
1
}
179

            
180
#[tokio::test]
181
1
async fn an_edited_name_parent_and_tags_submit_in_the_payload() {
182
1
    let mut app = open_app();
183
1
    deliver_options(&mut app, FormOptionsSource::FormAccounts, &accounts());
184
1
    let Some(Modal::Form(form)) = app.overlays.top_mut() else {
185
        panic!("edit form must be open");
186
    };
187
1
    form.fields[0].widget.set_text("Wallet");
188
1
    let Widget::Select(select) = &mut form.fields[1].widget else {
189
        panic!("field 1 must be the parent select");
190
    };
191
1
    select.select_id(ROOT);
192
1
    let Widget::Rows(rw) = &mut form.fields[2].widget else {
193
        panic!("field 2 must be Rows");
194
    };
195
1
    rw.add_row();
196
1
    for c in "trip".chars() {
197
4
        if let Some(editor) = rw.focused_editor_mut() {
198
4
            editor.insert_char(c);
199
        }
200
    }
201
1
    let values = top_form(&app).values();
202
1
    assert_eq!(values.text("id"), Some(ACCOUNT));
203
1
    assert_eq!(values.text("revision"), Some("rev-1"));
204
1
    assert_eq!(values.text("name"), Some("Wallet"));
205
1
    assert_eq!(values.text("parent"), Some(ROOT));
206
1
    assert_eq!(values.rows("tags").map(<[Row]>::len), Some(3), "{values:?}");
207
1
    assert_eq!(
208
1
        values.rows("tags").and_then(|rows| rows.get(1)),
209
1
        Some(&row(&[("name", "trip")]))
210
    );
211

            
212
1
    let sent = app.attach_echo();
213
1
    apply(&mut app, Intent::Submit);
214
1
    assert!(app.pending_form.is_some(), "the form waits for its reply");
215
1
    tokio::task::yield_now().await;
216
1
    app.drain_eval();
217
1
    let echoed = sent.frames().join("\n");
218
1
    assert!(
219
1
        echoed.contains(r#"(submit-form "account-edit" "(:id "#),
220
        "{echoed}"
221
    );
222
1
    assert!(echoed.contains(r#":name \"Wallet\""#), "{echoed}");
223
1
}
224

            
225
#[test]
226
1
fn a_rejected_tag_name_marks_its_cell() {
227
1
    let mut app = open_app();
228
1
    pending_edit(&mut app);
229
1
    app.route_reply(5, &rejected("is reserved", "tags.1.name"));
230
1
    let form = top_form(&app);
231
1
    assert_eq!(form.errors, ["Row 2 \u{b7} Name: is reserved"]);
232
1
    assert_eq!(form.focus, 2);
233
1
    assert_eq!((tags(form).row_focus, tags(form).col_focus), (1, 0));
234
1
}
235

            
236
#[test]
237
1
fn a_stale_revision_shows_the_reload_status_and_keeps_the_form() {
238
1
    let mut app = open_app();
239
1
    pending_edit(&mut app);
240
1
    let message = "the account changed since it was loaded; reload it";
241
1
    app.route_reply(5, &rejected(message, "revision"));
242
1
    let form = top_form(&app);
243
1
    assert_eq!(form.errors, [message]);
244
1
    assert!(
245
1
        app.status
246
1
            .ends_with("(close the form and open it again to reload)"),
247
        "{}",
248
        app.status
249
    );
250
1
    assert_eq!(form.values().text("name"), Some("Cash"));
251
1
    assert_eq!(tags(form).values().map_or(0, |rows| rows.len()), 2);
252
1
}
253

            
254
#[test]
255
1
fn success_closes_the_form_and_refreshes_the_accounts() {
256
1
    let mut app = open_app();
257
1
    pending_edit(&mut app);
258
1
    app.pending_routes.insert(
259
1
        5,
260
1
        Route {
261
1
            target: Some(app.window_of(ViewId::Accounts)),
262
1
            ctx: RouteCtx::Mutation {
263
1
                refresh: ViewId::Accounts,
264
1
            },
265
1
        },
266
1
    );
267
1
    app.accounts_mut().state = Fetch::Loaded(Vec::new());
268
1
    app.route_reply(5, &format!(r#"(:id 5 :value "{ACCOUNT}")"#));
269
1
    assert!(app.overlays.is_empty());
270
1
    assert!(app.pending_form.is_none());
271
1
    assert_eq!(app.accounts().state, Fetch::Idle);
272
1
}
273

            
274
#[test]
275
1
fn a_settled_edit_shows_the_reply_notice() {
276
1
    let mut app = open_app();
277
1
    pending_edit(&mut app);
278
1
    app.pending_routes.insert(
279
1
        5,
280
1
        Route {
281
1
            target: Some(app.window_of(ViewId::Accounts)),
282
1
            ctx: RouteCtx::Mutation {
283
1
                refresh: ViewId::Accounts,
284
1
            },
285
1
        },
286
1
    );
287
1
    app.route_reply(
288
1
        5,
289
1
        &format!(r#"(:id 5 :value "{ACCOUNT}" :notices ("Another account named 'Cash' exists"))"#),
290
1
    );
291
1
    assert!(app.overlays.is_empty());
292
1
    assert_eq!(app.status, "Another account named 'Cash' exists");
293
1
}