Skip to main content

tui/app/
form_options.rs

1//! Helpers that inject fetched Select options into an open form's fields,
2//! and methods that fetch option lists from the server.
3
4use cli_core::forms::{FormOption, parse_form_options};
5
6use crate::app::App;
7use crate::form::{Field, Form, FormKind};
8use crate::modal::Modal;
9use crate::route::{FormOptionsSource, RouteCtx};
10use crate::widgets::{SelectOption, Widget};
11
12/// The select options of fetched form options.
13pub(super) fn select_options_of(options: Vec<FormOption>) -> Vec<SelectOption> {
14    options
15        .into_iter()
16        .map(|option| SelectOption {
17            id: option.id,
18            label: option.label,
19        })
20        .collect()
21}
22
23pub(super) use crate::widgets::with_none;
24
25/// Inject options into ALL Select fields (used for forms with multiple commodity Selects).
26pub(super) fn inject_all_select_options(fields: &mut [Field], options: &[SelectOption]) {
27    for field in fields {
28        if let Widget::Select(ref mut sw) = field.widget {
29            sw.set_options(options.to_vec());
30        }
31    }
32}
33
34/// Inject options into the Select field `key`, leaving the other Selects alone.
35pub(super) fn inject_keyed_select_options(
36    fields: &mut [Field],
37    key: &str,
38    options: &[SelectOption],
39) {
40    for field in fields.iter_mut().filter(|f| f.key == Some(key)) {
41        if let Widget::Select(ref mut sw) = field.widget {
42            sw.set_options_preserving_id(options.to_vec());
43        }
44    }
45}
46
47pub(super) fn inject_splits_account_options(
48    fields: &mut [Field],
49    options: Vec<SelectOption>,
50    fills: Vec<FormOption>,
51) {
52    for field in fields {
53        if let Widget::Splits(ref mut sw) = field.widget {
54            sw.set_account_options(options);
55            sw.set_account_fills(fills);
56            return;
57        }
58    }
59}
60
61pub(super) fn inject_splits_commodity_options(fields: &mut [Field], options: Vec<SelectOption>) {
62    for field in fields {
63        if let Widget::Splits(ref mut sw) = field.widget {
64            sw.set_commodity_options(options);
65            return;
66        }
67    }
68}
69
70impl 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    pub fn fetch_account_form_options(&mut self) {
74        if self.console_eval.is_none() {
75            return;
76        }
77        let seq = self.form_options_seq.advance();
78        let _ = self.dispatch_app_eval(
79            RouteCtx::FormOptions {
80                seq,
81                source: FormOptionsSource::FormAccounts,
82            },
83            r#"(form-options "accounts")"#.to_string(),
84        );
85    }
86
87    /// Issue a `form-options` fetch for the commodity selects of the open report or convert form.
88    pub fn fetch_commodity_form_options(&mut self) {
89        if self.console_eval.is_none() {
90            return;
91        }
92        let seq = self.form_options_seq.advance();
93        let _ = self.dispatch_app_eval(
94            RouteCtx::FormOptions {
95                seq,
96                source: FormOptionsSource::FormCommodities,
97            },
98            r#"(form-options "commodities")"#.to_string(),
99        );
100    }
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    pub fn fetch_transaction_form_options(&mut self) {
105        if self.console_eval.is_none() {
106            return;
107        }
108        self.form_options_seq.advance();
109        self.request_account_and_commodity_options();
110    }
111
112    /// Ask for both option lists under the current seq, so replies already in
113    /// flight for the form beneath stay valid.
114    pub fn request_account_and_commodity_options(&mut self) {
115        if self.console_eval.is_none() {
116            return;
117        }
118        let seq = self.form_options_seq.current();
119        for (source, form) in [
120            (
121                FormOptionsSource::FormAccounts,
122                r#"(form-options "accounts")"#,
123            ),
124            (
125                FormOptionsSource::FormCommodities,
126                r#"(form-options "commodities")"#,
127            ),
128        ] {
129            let _ = self.dispatch_app_eval(RouteCtx::FormOptions { seq, source }, form.to_string());
130        }
131    }
132
133    pub(super) fn deliver_form_options_reply(
134        &mut self,
135        wire: &str,
136        seq: u64,
137        source: FormOptionsSource,
138    ) {
139        if !self.form_options_seq.awaits(seq) {
140            return;
141        }
142        match source {
143            FormOptionsSource::FormAccounts => self.deliver_transaction_account_options(wire),
144            FormOptionsSource::FormCommodities => self.deliver_transaction_commodity_options(wire),
145        }
146    }
147
148    /// The `(none)` entry keeps an unchosen account empty instead of silently
149    /// defaulting to the first option.
150    pub(super) fn deliver_transaction_account_options(&mut self, wire: &str) {
151        let fills = parse_form_options(wire);
152        let accounts = select_options_of(fills.clone());
153        if accounts.is_empty() {
154            return;
155        }
156        if let Some(builder) = self.overlays.builder_mut() {
157            builder.accounts.clone_from(&accounts);
158        }
159        self.refresh_row_picks();
160        let options = with_none(accounts);
161        if let Some(form) = self.account_select_form_mut() {
162            fill(form, |form| {
163                inject_all_select_options(&mut form.fields, &options)
164            });
165        } else if let Some(form) = self.transaction_form_mut() {
166            fill(form, |form| {
167                inject_splits_account_options(&mut form.fields, options, fills);
168            });
169        }
170    }
171
172    /// The open form, or the one awaiting its submit reply, when `accepts` its kind.
173    pub(super) fn form_mut(&mut self, accepts: impl Fn(&Form) -> bool) -> Option<&mut Form> {
174        self.overlays
175            .form_mut()
176            .or_else(|| self.pending_form.as_mut().map(|pending| &mut pending.form))
177            .filter(|form| accepts(form))
178    }
179
180    /// The open transaction form, or the one awaiting its submit reply so a
181    /// rejected submit comes back with populated selects.
182    pub(super) fn transaction_form_mut(&mut self) -> Option<&mut Form> {
183        self.form_mut(Form::is_transaction)
184    }
185
186    /// The open account-create or -edit form, or the one awaiting its
187    /// submit reply.
188    pub(super) fn account_select_form_mut(&mut self) -> Option<&mut Form> {
189        self.form_mut(|form| {
190            matches!(
191                form.kind,
192                FormKind::AccountCreate | FormKind::AccountEdit | FormKind::TransactionFilter
193            )
194        })
195    }
196
197    /// Gives an open builder row form the names that arrived after it opened.
198    fn refresh_row_picks(&mut self) {
199        let Some(Modal::Form(form)) = self.overlays.top() else {
200            return;
201        };
202        let FormKind::FilterRow(shape) = form.kind else {
203            return;
204        };
205        let Some(options) = self
206            .overlays
207            .builder_mut()
208            .map(|builder| builder.options_for(shape).to_vec())
209        else {
210            return;
211        };
212        if let Some(Modal::Form(form)) = self.overlays.top_mut() {
213            form.refresh_picks(&options);
214        }
215    }
216
217    /// The report form, also beneath a filter builder, or the one awaiting its submit reply.
218    fn report_form_mut(&mut self) -> Option<&mut Form> {
219        let pending = self.pending_form.as_mut().map(|pending| &mut pending.form);
220        self.overlays
221            .report_form_mut()
222            .or(pending)
223            .filter(|form| matches!(form.kind, FormKind::Report(_)))
224    }
225
226    pub(super) fn deliver_transaction_commodity_options(&mut self, wire: &str) {
227        let options = select_options(wire);
228        if options.is_empty() {
229            return;
230        }
231        if let Some(builder) = self.overlays.builder_mut() {
232            builder.commodities.clone_from(&options);
233        }
234        self.refresh_row_picks();
235        if let Some(form) = self.transaction_form_mut() {
236            fill(form, |form| {
237                inject_splits_commodity_options(&mut form.fields, options);
238            });
239        } else if let Some(form) = self.form_mut(|form| form.kind == FormKind::CommodityConvert) {
240            fill(form, |form| {
241                inject_all_select_options(&mut form.fields, &options)
242            });
243        } else if let Some(form) = self.report_form_mut() {
244            fill(form, |form| {
245                inject_keyed_select_options(&mut form.fields, "target", &with_none(options));
246            });
247        }
248    }
249}
250
251/// Applies arriving options; an untouched form stays untouched.
252fn fill(form: &mut Form, inject: impl FnOnce(&mut Form)) {
253    let clean = !form.is_dirty();
254    inject(form);
255    if clean {
256        form.rebaseline();
257    }
258}
259
260/// The options of a `form-options` reply.
261fn select_options(wire: &str) -> Vec<SelectOption> {
262    select_options_of(parse_form_options(wire))
263}