1
//! Helpers that inject fetched Select options into an open form's fields,
2
//! and methods that fetch option lists from the server.
3

            
4
use cli_core::forms::{FormOption, parse_form_options};
5

            
6
use crate::app::App;
7
use crate::form::{Field, Form, FormKind};
8
use crate::modal::Modal;
9
use crate::route::{FormOptionsSource, RouteCtx};
10
use crate::widgets::{SelectOption, Widget};
11

            
12
/// The select options of fetched form options.
13
136
pub(super) fn select_options_of(options: Vec<FormOption>) -> Vec<SelectOption> {
14
136
    options
15
136
        .into_iter()
16
        .map(|option| SelectOption {
17
286
            id: option.id,
18
286
            label: option.label,
19
286
        })
20
        .collect()
21
136
}
22

            
23
pub(super) use crate::widgets::with_none;
24

            
25
/// Inject options into ALL Select fields (used for forms with multiple commodity Selects).
26
30
pub(super) fn inject_all_select_options(fields: &mut [Field], options: &[SelectOption]) {
27
30
    for field in fields {
28
66
        if let Widget::Select(ref mut sw) = field.widget {
29
56
            sw.set_options(options.to_vec());
30
10
        }
31
    }
32
30
}
33

            
34
/// Inject options into the Select field `key`, leaving the other Selects alone.
35
2
pub(super) fn inject_keyed_select_options(
36
2
    fields: &mut [Field],
37
2
    key: &str,
38
2
    options: &[SelectOption],
39
2
) {
40
10
    for field in fields.iter_mut().filter(|f| f.key == Some(key)) {
41
2
        if let Widget::Select(ref mut sw) = field.widget {
42
2
            sw.set_options_preserving_id(options.to_vec());
43
        }
44
    }
45
2
}
46

            
47
51
pub(super) fn inject_splits_account_options(
48
51
    fields: &mut [Field],
49
51
    options: Vec<SelectOption>,
50
51
    fills: Vec<FormOption>,
51
51
) {
52
51
    for field in fields {
53
204
        if let Widget::Splits(ref mut sw) = field.widget {
54
51
            sw.set_account_options(options);
55
51
            sw.set_account_fills(fills);
56
51
            return;
57
153
        }
58
    }
59
51
}
60

            
61
43
pub(super) fn inject_splits_commodity_options(fields: &mut [Field], options: Vec<SelectOption>) {
62
43
    for field in fields {
63
172
        if let Widget::Splits(ref mut sw) = field.widget {
64
43
            sw.set_commodity_options(options);
65
43
            return;
66
129
        }
67
    }
68
43
}
69

            
70
impl App {
71
    /// Issue a `form-options` fetch to populate the parent Select in the open
72
    /// account-create form.  Bumps `form_options_seq` so a stale reply is dropped.
73
26
    pub fn fetch_account_form_options(&mut self) {
74
26
        if self.console_eval.is_none() {
75
12
            return;
76
14
        }
77
14
        let seq = self.form_options_seq.advance();
78
14
        let _ = self.dispatch_app_eval(
79
14
            RouteCtx::FormOptions {
80
14
                seq,
81
14
                source: FormOptionsSource::FormAccounts,
82
14
            },
83
14
            r#"(form-options "accounts")"#.to_string(),
84
14
        );
85
26
    }
86

            
87
    /// Issue a `form-options` fetch for the commodity selects of the open report or convert form.
88
50
    pub fn fetch_commodity_form_options(&mut self) {
89
50
        if self.console_eval.is_none() {
90
5
            return;
91
45
        }
92
45
        let seq = self.form_options_seq.advance();
93
45
        let _ = self.dispatch_app_eval(
94
45
            RouteCtx::FormOptions {
95
45
                seq,
96
45
                source: FormOptionsSource::FormCommodities,
97
45
            },
98
45
            r#"(form-options "commodities")"#.to_string(),
99
45
        );
100
50
    }
101

            
102
    /// Issue `form-options` for accounts and commodities to populate the Selects
103
    /// in the open transaction form.  Both requests share the same seq.
104
41
    pub fn fetch_transaction_form_options(&mut self) {
105
41
        if self.console_eval.is_none() {
106
32
            return;
107
9
        }
108
9
        self.form_options_seq.advance();
109
9
        self.request_account_and_commodity_options();
110
41
    }
111

            
112
    /// Ask for both option lists under the current seq, so replies already in
113
    /// flight for the form beneath stay valid.
114
52
    pub fn request_account_and_commodity_options(&mut self) {
115
52
        if self.console_eval.is_none() {
116
43
            return;
117
9
        }
118
9
        let seq = self.form_options_seq.current();
119
9
        for (source, form) in [
120
9
            (
121
9
                FormOptionsSource::FormAccounts,
122
9
                r#"(form-options "accounts")"#,
123
9
            ),
124
9
            (
125
9
                FormOptionsSource::FormCommodities,
126
9
                r#"(form-options "commodities")"#,
127
9
            ),
128
9
        ] {
129
18
            let _ = self.dispatch_app_eval(RouteCtx::FormOptions { seq, source }, form.to_string());
130
        }
131
52
    }
132

            
133
108
    pub(super) fn deliver_form_options_reply(
134
108
        &mut self,
135
108
        wire: &str,
136
108
        seq: u64,
137
108
        source: FormOptionsSource,
138
108
    ) {
139
108
        if !self.form_options_seq.awaits(seq) {
140
2
            return;
141
106
        }
142
106
        match source {
143
57
            FormOptionsSource::FormAccounts => self.deliver_transaction_account_options(wire),
144
49
            FormOptionsSource::FormCommodities => self.deliver_transaction_commodity_options(wire),
145
        }
146
108
    }
147

            
148
    /// The `(none)` entry keeps an unchosen account empty instead of silently
149
    /// defaulting to the first option.
150
57
    pub(super) fn deliver_transaction_account_options(&mut self, wire: &str) {
151
57
        let fills = parse_form_options(wire);
152
57
        let accounts = select_options_of(fills.clone());
153
57
        if accounts.is_empty() {
154
1
            return;
155
56
        }
156
56
        if let Some(builder) = self.overlays.builder_mut() {
157
1
            builder.accounts.clone_from(&accounts);
158
55
        }
159
56
        self.refresh_row_picks();
160
56
        let options = with_none(accounts);
161
56
        if let Some(form) = self.account_select_form_mut() {
162
4
            fill(form, |form| {
163
4
                inject_all_select_options(&mut form.fields, &options)
164
4
            });
165
52
        } else if let Some(form) = self.transaction_form_mut() {
166
51
            fill(form, |form| {
167
51
                inject_splits_account_options(&mut form.fields, options, fills);
168
51
            });
169
1
        }
170
57
    }
171

            
172
    /// The open form, or the one awaiting its submit reply, when `accepts` its kind.
173
165
    pub(super) fn form_mut(&mut self, accepts: impl Fn(&Form) -> bool) -> Option<&mut Form> {
174
165
        self.overlays
175
165
            .form_mut()
176
5
            .or_else(|| self.pending_form.as_mut().map(|pending| &mut pending.form))
177
163
            .filter(|form| accepts(form))
178
165
    }
179

            
180
    /// The open transaction form, or the one awaiting its submit reply so a
181
    /// rejected submit comes back with populated selects.
182
100
    pub(super) fn transaction_form_mut(&mut self) -> Option<&mut Form> {
183
100
        self.form_mut(Form::is_transaction)
184
100
    }
185

            
186
    /// The open account-create or -edit form, or the one awaiting its
187
    /// submit reply.
188
56
    pub(super) fn account_select_form_mut(&mut self) -> Option<&mut Form> {
189
56
        self.form_mut(|form| {
190
56
            matches!(
191
56
                form.kind,
192
                FormKind::AccountCreate | FormKind::AccountEdit | FormKind::TransactionFilter
193
            )
194
56
        })
195
56
    }
196

            
197
    /// Gives an open builder row form the names that arrived after it opened.
198
104
    fn refresh_row_picks(&mut self) {
199
104
        let Some(Modal::Form(form)) = self.overlays.top() else {
200
4
            return;
201
        };
202
100
        let FormKind::FilterRow(shape) = form.kind else {
203
99
            return;
204
        };
205
1
        let Some(options) = self
206
1
            .overlays
207
1
            .builder_mut()
208
1
            .map(|builder| builder.options_for(shape).to_vec())
209
        else {
210
            return;
211
        };
212
1
        if let Some(Modal::Form(form)) = self.overlays.top_mut() {
213
1
            form.refresh_picks(&options);
214
        }
215
104
    }
216

            
217
    /// The report form, also beneath a filter builder, or the one awaiting its submit reply.
218
2
    fn report_form_mut(&mut self) -> Option<&mut Form> {
219
2
        let pending = self.pending_form.as_mut().map(|pending| &mut pending.form);
220
2
        self.overlays
221
2
            .report_form_mut()
222
2
            .or(pending)
223
2
            .filter(|form| matches!(form.kind, FormKind::Report(_)))
224
2
    }
225

            
226
49
    pub(super) fn deliver_transaction_commodity_options(&mut self, wire: &str) {
227
49
        let options = select_options(wire);
228
49
        if options.is_empty() {
229
1
            return;
230
48
        }
231
48
        if let Some(builder) = self.overlays.builder_mut() {
232
1
            builder.commodities.clone_from(&options);
233
47
        }
234
48
        self.refresh_row_picks();
235
48
        if let Some(form) = self.transaction_form_mut() {
236
43
            fill(form, |form| {
237
43
                inject_splits_commodity_options(&mut form.fields, options);
238
43
            });
239
5
        } else if let Some(form) = self.form_mut(|form| form.kind == FormKind::CommodityConvert) {
240
3
            fill(form, |form| {
241
3
                inject_all_select_options(&mut form.fields, &options)
242
3
            });
243
2
        } else if let Some(form) = self.report_form_mut() {
244
2
            fill(form, |form| {
245
2
                inject_keyed_select_options(&mut form.fields, "target", &with_none(options));
246
2
            });
247
        }
248
49
    }
249
}
250

            
251
/// Applies arriving options; an untouched form stays untouched.
252
103
fn fill(form: &mut Form, inject: impl FnOnce(&mut Form)) {
253
103
    let clean = !form.is_dirty();
254
103
    inject(form);
255
103
    if clean {
256
101
        form.rebaseline();
257
2
    }
258
103
}
259

            
260
/// The options of a `form-options` reply.
261
49
fn select_options(wire: &str) -> Vec<SelectOption> {
262
49
    select_options_of(parse_form_options(wire))
263
49
}