1
//! The lossless fixture through the TUI edit form: a no-op and a note-only
2
//! edit submit the loaded payload byte for byte, and the store is unchanged.
3

            
4
use cli_core::transaction::submit_call;
5
use forms::{FormValues, TRANSACTION_EDIT, escape_str, write_payload};
6
use nomiscript::Value;
7
use rpc::{ResponsePayload, ScriptCtx, Session};
8
use server::lossless::{
9
    EDITED_NOTE, NOTE, first_row_tag, kept_only, seed, snapshot, split_tag_facts, tag_facts,
10
    without_note,
11
};
12
use sqlx::PgPool;
13

            
14
use crate::app::App;
15
use crate::modal::Modal;
16
use crate::route::{FormOptionsSource, Route, RouteCtx};
17
use crate::view::ViewId;
18
use crate::widgets::splits::{COL_FROM, COL_FROM_COMM, COL_TO, COL_TO_COMM, COL_VALUE};
19
use crate::widgets::{FocusedSubWidget, SplitsWidget, Widget};
20

            
21
27
async fn reply(session: &mut Session, form: &str) -> String {
22
27
    session.handle_form(&format!("(:id 1 :form {form})")).await
23
27
}
24

            
25
13
fn value(wire: &str) -> anyhow::Result<String> {
26
13
    match rpc::parse_response(wire).map(|response| response.payload) {
27
13
        Ok(ResponsePayload::Value(Value::String(text))) => Ok(text),
28
        other => anyhow::bail!("expected a string value, got {other:?}"),
29
    }
30
13
}
31

            
32
/// The edit form opened from a real `load-form` reply with real options.
33
7
async fn open(session: &mut Session, id: &str) -> anyhow::Result<(App, String)> {
34
7
    let wire = reply(
35
7
        session,
36
7
        &format!("(load-form \"transaction-edit\" \"{id}\")"),
37
7
    )
38
7
    .await;
39
7
    let mut app = crate::test_support::app();
40
7
    app.form_options_seq.advance();
41
7
    app.deliver_transaction_edit_reply(
42
7
        Some(app.window_of(crate::view::ViewId::Transactions)),
43
7
        &wire,
44
7
    );
45
7
    for (target, source, form) in [
46
7
        (
47
7
            ViewId::Accounts,
48
7
            FormOptionsSource::FormAccounts,
49
7
            r#"(form-options "accounts")"#,
50
7
        ),
51
7
        (
52
7
            ViewId::Commodities,
53
7
            FormOptionsSource::FormCommodities,
54
7
            r#"(form-options "commodities")"#,
55
7
        ),
56
7
    ] {
57
14
        let ctx = RouteCtx::FormOptions { seq: 1, source };
58
14
        app.deliver_reply(
59
14
            Route {
60
14
                target: Some(app.window_of(target)),
61
14
                ctx,
62
14
            },
63
14
            &reply(session, form).await,
64
        );
65
    }
66
7
    Ok((app, value(&wire)?))
67
7
}
68

            
69
/// The values the open form submits, after `change` edits it.
70
6
fn submitted(
71
6
    mut app: App,
72
6
    change: impl FnOnce(&mut crate::form::Form),
73
6
) -> anyhow::Result<FormValues> {
74
6
    let Some(Modal::Form(mut form)) = app.overlays.pop() else {
75
        anyhow::bail!("the edit form is not open: {}", app.status);
76
    };
77
6
    change(&mut form);
78
6
    Ok(form.values())
79
6
}
80

            
81
8
fn widget_mut<'a>(form: &'a mut crate::form::Form, key: &str) -> Option<&'a mut Widget> {
82
8
    form.fields
83
8
        .iter_mut()
84
24
        .find(|field| field.key == Some(key))
85
8
        .map(|field| &mut field.widget)
86
8
}
87

            
88
6
async fn submit(session: &mut Session, values: &FormValues) -> anyhow::Result<()> {
89
6
    let wire = reply(session, &submit_call(&TRANSACTION_EDIT, values)).await;
90
6
    value(&wire).map(|_| ())
91
6
}
92

            
93
4
fn without_revision(text: &str) -> String {
94
4
    let (head, rest) = text.split_once(" :revision \"").unwrap_or((text, "\""));
95
4
    let tail = rest.split_once('"').map_or("", |(_, tail)| tail);
96
4
    format!("{head}{tail}")
97
4
}
98

            
99
/// The form leaves an empty cell out of its payload; the server reads it the same.
100
2
fn without_empty_to_commodity(text: &str) -> String {
101
2
    text.replace(" :to-commodity \"\"", "")
102
2
}
103

            
104
#[sqlx::test(migrator = "server::db::MIGRATOR")]
105
async fn noop_and_note_only_edits_are_lossless(pool: PgPool) -> anyhow::Result<()> {
106
    let _guard = server::db::install_test_pool(pool.clone());
107
    let fixture = seed(&pool).await?;
108
    let id = fixture.transaction.to_string();
109
    let mut session = Session::new(ScriptCtx::new(fixture.user))?;
110
    let stored = snapshot(&pool, fixture.transaction).await?;
111

            
112
    let (app, loaded) = open(&mut session, &id).await?;
113
    assert!(loaded.contains(":description \"client forms\""), "{loaded}");
114
    assert!(
115
        loaded.contains(":description \"split memo\\nsecond line\")"),
116
        "{loaded}"
117
    );
118
    let values = submitted(app, |_| ())?;
119
    assert_eq!(
120
        write_payload(&TRANSACTION_EDIT, &values),
121
        without_empty_to_commodity(&loaded)
122
    );
123
    submit(&mut session, &values).await?;
124
    assert_eq!(snapshot(&pool, fixture.transaction).await?, stored);
125

            
126
    let (app, reloaded) = open(&mut session, &id).await?;
127
    assert_eq!(without_revision(&reloaded), without_revision(&loaded));
128
1
    let values = submitted(app, |form| {
129
1
        if let Some(note) = widget_mut(form, "note") {
130
1
            note.set_text(EDITED_NOTE);
131
        }
132
1
    })?;
133
    let expected = reloaded.replace(&escape_str(NOTE), &escape_str(EDITED_NOTE));
134
    assert_eq!(
135
        write_payload(&TRANSACTION_EDIT, &values),
136
        without_empty_to_commodity(&expected)
137
    );
138
    submit(&mut session, &values).await?;
139
    let (_, after) = open(&mut session, &id).await?;
140
    assert_eq!(without_revision(&after), without_revision(&expected));
141
    let now = snapshot(&pool, fixture.transaction).await?;
142
    assert_eq!(without_note(&now), without_note(&stored));
143
    assert!(
144
        now.contains(&format!("tag note {EDITED_NOTE} -")),
145
        "{now:?}"
146
    );
147
    Ok(())
148
}
149

            
150
/// Pick the option matching `text` in the select at `col` of the focused row.
151
8
fn pick(sw: &mut SplitsWidget, col: usize, text: &str) {
152
8
    sw.col_focus = col;
153
8
    if let Some(FocusedSubWidget::Select(select)) = sw.focused_subwidget_mut() {
154
28
        text.chars().for_each(|c| select.filter_push(c));
155
8
        select.confirm();
156
    }
157
8
}
158

            
159
/// Drop row `r2` and append two rows from Cash to Food of 1 and 2 USD.
160
1
fn drop_r2_and_add_two(sw: &mut SplitsWidget) {
161
2
    if let Some(index) = sw.rows().iter().position(|row| row.text("key") == "r2") {
162
1
        sw.row_focus = index;
163
1
        sw.remove_row();
164
    }
165
1
    for value in ["1", "2"] {
166
2
        sw.row_focus = sw.rows().len() - 1;
167
2
        sw.add_row();
168
2
        pick(sw, COL_FROM, "Cash");
169
2
        pick(sw, COL_TO, "Food");
170
2
        pick(sw, COL_FROM_COMM, "USD");
171
2
        pick(sw, COL_TO_COMM, "USD");
172
2
        sw.col_focus = COL_VALUE;
173
2
        if let Some(FocusedSubWidget::Amount(amount)) = sw.focused_subwidget_mut() {
174
2
            value.chars().for_each(|c| amount.insert_char(c));
175
        }
176
    }
177
1
}
178

            
179
#[sqlx::test(migrator = "server::db::MIGRATOR")]
180
async fn two_new_keyless_rows_and_a_removed_row_keep_the_other_tags(
181
    pool: PgPool,
182
) -> anyhow::Result<()> {
183
    let _guard = server::db::install_test_pool(pool.clone());
184
    let fixture = seed(&pool).await?;
185
    let id = fixture.transaction.to_string();
186
    let mut session = Session::new(ScriptCtx::new(fixture.user))?;
187
    let (app, loaded) = open(&mut session, &id).await?;
188
    let name = first_row_tag(&loaded).ok_or_else(|| anyhow::anyhow!("no r1 tag"))?;
189
    let kept = split_tag_facts(&snapshot(&pool, fixture.transaction).await?, name);
190
1
    let values = submitted(app, |form| {
191
1
        if let Some(Widget::Splits(sw)) = widget_mut(form, "splits") {
192
1
            drop_r2_and_add_two(sw);
193
        }
194
1
    })?;
195
    assert_eq!(values.rows("splits").map(<[_]>::len), Some(3));
196
    submit(&mut session, &values).await?;
197
    let now = snapshot(&pool, fixture.transaction).await?;
198
    assert!(kept_only(&now, &kept), "{kept:?}: {now:?}");
199
    Ok(())
200
}
201

            
202
2
fn type_into_tags(form: &mut crate::form::Form, text: &str) {
203
2
    if let Some(Widget::Rows(rw)) = widget_mut(form, "tags")
204
2
        && let Some(editor) = rw.focused_editor_mut()
205
    {
206
5
        text.chars().for_each(|c| editor.insert_char(c));
207
    }
208
2
}
209

            
210
#[sqlx::test(migrator = "server::db::MIGRATOR")]
211
async fn a_tag_is_added_changed_and_cleared_through_the_session(
212
    pool: PgPool,
213
) -> anyhow::Result<()> {
214
    let _guard = server::db::install_test_pool(pool.clone());
215
    let fixture = seed(&pool).await?;
216
    let id = fixture.transaction.to_string();
217
    let mut session = Session::new(ScriptCtx::new(fixture.user))?;
218
    let before = tag_facts(&snapshot(&pool, fixture.transaction).await?);
219

            
220
    let (app, _) = open(&mut session, &id).await?;
221
1
    let values = submitted(app, |form| {
222
1
        if let Some(Widget::Rows(rw)) = widget_mut(form, "tags") {
223
1
            rw.add_row();
224
        }
225
1
        type_into_tags(form, "shop");
226
1
        if let Some(Widget::Rows(rw)) = widget_mut(form, "tags") {
227
1
            rw.advance_cell();
228
        }
229
1
        type_into_tags(form, "x");
230
1
    })?;
231
    submit(&mut session, &values).await?;
232
    let added = tag_facts(&snapshot(&pool, fixture.transaction).await?);
233
    assert_eq!(added.len(), before.len() + 1, "{added:?}");
234
    assert!(added.contains(&"tag shop x -".to_string()), "{added:?}");
235

            
236
    let (app, _) = open(&mut session, &id).await?;
237
1
    let values = submitted(app, |form| {
238
1
        if let Some(Widget::Rows(rw)) = widget_mut(form, "tags") {
239
4
            let shop = (0..rw.values().map_or(0, |rows| rows.len())).find(|&row| {
240
4
                rw.focus_cell(row, "name");
241
4
                rw.focused_editor_mut()
242
4
                    .is_some_and(|e| e.buffer() == "shop")
243
4
            });
244
1
            if let Some(row) = shop {
245
1
                rw.focus_cell(row, "description");
246
1
                if let Some(editor) = rw.focused_editor_mut() {
247
6
                    "bought".chars().for_each(|c| editor.insert_char(c));
248
                }
249
            }
250
        }
251
1
    })?;
252
    submit(&mut session, &values).await?;
253
    let changed = tag_facts(&snapshot(&pool, fixture.transaction).await?);
254
    assert!(
255
        changed.contains(&"tag shop x bought".to_string()),
256
        "{changed:?}"
257
    );
258

            
259
    let (app, _) = open(&mut session, &id).await?;
260
1
    let values = submitted(app, |form| {
261
1
        if let Some(Widget::Rows(rw)) = widget_mut(form, "tags") {
262
1
            let count = rw.values().map_or(0, |rows| rows.len());
263
6
            (0..count).for_each(|_| rw.remove_row());
264
        }
265
1
    })?;
266
    submit(&mut session, &values).await?;
267
    assert!(tag_facts(&snapshot(&pool, fixture.transaction).await?).is_empty());
268
    Ok(())
269
}