1
//! One from→to row of the splits editor.
2

            
3
use std::collections::BTreeSet;
4

            
5
use cli_core::forms::{FormOption, commodity_fill};
6
use forms::{Kind, LINK_CELL, Row, Source};
7

            
8
use super::{
9
    COL_FROM, COL_FROM_COMM, COL_TO, COL_TO_AMOUNT, COL_TO_COMM, COL_VALUE, columns, tag_fields,
10
};
11
use crate::widgets::{AmountWidget, RowsWidget, SelectOption, SelectWidget, WidgetKind, with_none};
12

            
13
/// One from→to split row with four account/commodity selects and two amount editors.
14
#[derive(Debug)]
15
pub struct SplitRow {
16
    pub from: SelectWidget,
17
    pub to: SelectWidget,
18
    pub from_commodity: SelectWidget,
19
    pub to_commodity: SelectWidget,
20
    pub value: AmountWidget,
21
    pub to_amount: AmountWidget,
22
    /// The tags of this split, linked to it by `key` on submit.
23
    pub(super) tags: RowsWidget,
24
    /// Loaded row identity and opaque server data; neither is shown or edited,
25
    /// both are submitted unchanged. Empty on appended rows.
26
    key: String,
27
    hidden: String,
28
    /// Loaded text of the from, to, from-commodity and to-commodity cells.
29
    loaded: [String; 4],
30
    /// The columns filled by a declared fill, not chosen by the user.
31
    auto: BTreeSet<usize>,
32
    /// A loaded row keeps every cell as stored: no fill touches it.
33
    from_load: bool,
34
}
35

            
36
impl SplitRow {
37
    /// Build a row whose Selects are pre-seeded from the cached option lists,
38
    /// so a row added after the options arrive is immediately completable.
39
713
    pub(super) fn new(accounts: &[SelectOption], commodities: &[SelectOption]) -> Self {
40
713
        let mut row = Self {
41
713
            from: SelectWidget::new(),
42
713
            to: SelectWidget::new(),
43
713
            from_commodity: SelectWidget::new(),
44
713
            to_commodity: SelectWidget::new(),
45
713
            value: AmountWidget::default(),
46
713
            to_amount: AmountWidget::default(),
47
713
            tags: RowsWidget::new(tag_fields()),
48
713
            key: String::new(),
49
713
            hidden: String::new(),
50
713
            loaded: Default::default(),
51
713
            auto: BTreeSet::new(),
52
713
            from_load: false,
53
713
        };
54
713
        row.from.set_options(accounts.to_vec());
55
713
        row.to.set_options(accounts.to_vec());
56
713
        row.from_commodity
57
713
            .set_options(with_none(commodities.to_vec()));
58
713
        row.to_commodity
59
713
            .set_options(with_empty_meaning(commodities));
60
713
        row
61
713
    }
62

            
63
    /// A row holding the loaded cells; each select starts as a single option
64
    /// whose id is the loaded text, until the option lists arrive.
65
138
    pub(super) fn loaded(row: &Row) -> Self {
66
1104
        let text = |key: &str| row.get(key).map_or("", String::as_str);
67
138
        let mut loaded = Self::new(&[], &[]);
68
138
        loaded.value = AmountWidget::with_value(text("value"));
69
138
        loaded.to_amount = AmountWidget::with_value(text("to-amount"));
70
138
        loaded.from_load = true;
71
138
        loaded.key = text("key").to_string();
72
138
        loaded.hidden = text("hidden").to_string();
73
138
        loaded.loaded =
74
552
            ["from", "to", "from-commodity", "to-commodity"].map(|k| text(k).to_string());
75
138
        let [from, to, from_commodity, to_commodity] = &loaded.loaded;
76
138
        loaded.from.set_options(seed(from));
77
138
        loaded.to.set_options(seed(to));
78
138
        loaded.from_commodity.set_options(seed(from_commodity));
79
138
        loaded.to_commodity.set_options(seed(to_commodity));
80
138
        loaded
81
138
    }
82

            
83
188
    pub(super) fn key(&self) -> &str {
84
188
        &self.key
85
188
    }
86

            
87
16
    pub(super) fn set_key(&mut self, key: String) {
88
16
        self.key = key;
89
16
    }
90

            
91
    /// The non-blank tags linked to this split's key.
92
860
    pub(super) fn tag_rows(&self) -> impl Iterator<Item = Row> + '_ {
93
860
        let rows = self.tags.rows().into_iter().filter(|tag| !tag.is_empty());
94
860
        rows.map(|mut tag| {
95
351
            tag.insert(LINK_CELL.to_string(), self.key.clone());
96
351
            tag
97
351
        })
98
860
    }
99

            
100
257
    pub(super) fn bind_accounts(&mut self, options: &[SelectOption]) {
101
257
        let [from, to, ..] = &self.loaded;
102
257
        self.from.set_options_preserving_id(bound(options, from));
103
257
        self.to.set_options_preserving_id(bound(options, to));
104
257
    }
105

            
106
228
    pub(super) fn bind_commodities(&mut self, options: &[SelectOption]) {
107
228
        let [.., from, to] = &self.loaded;
108
228
        self.from_commodity
109
228
            .set_options_preserving_id(bound(&with_none(options.to_vec()), from));
110
228
        self.to_commodity
111
228
            .set_options_preserving_id(bound(&with_empty_meaning(options), to));
112
228
    }
113

            
114
    /// What column `source` fills into its target: a commodity fills itself,
115
    /// an account its only commodity.
116
882
    fn fill_of(&self, source: usize, fills: &[FormOption]) -> Option<String> {
117
882
        let text = self.cell_text(source);
118
882
        match columns().nth(source).map(|field| field.kind) {
119
            Some(Kind::Select {
120
                source: Source::Commodities,
121
                ..
122
529
            }) => Some(text.to_string()).filter(|text| !text.is_empty()),
123
353
            _ => commodity_fill(fills, text),
124
        }
125
882
    }
126

            
127
    /// Refill column `target` after a change of column `source`, unless the
128
    /// user chose it: an auto-filled one follows the source, even back to unset.
129
1088
    pub(super) fn refill(&mut self, (source, target): (usize, usize), fills: &[FormOption]) {
130
1088
        if self.from_load {
131
206
            return;
132
882
        }
133
882
        let fill = self.fill_of(source, fills);
134
882
        let auto = self.auto.contains(&target);
135
882
        let Some(select) = self.select_mut(target) else {
136
            return;
137
        };
138
882
        if !auto && !select.value().is_empty() {
139
5
            return;
140
877
        }
141
877
        select.select_id(fill.as_deref().unwrap_or(""));
142
877
        match fill {
143
62
            Some(_) => self.auto.insert(target),
144
815
            None => self.auto.remove(&target),
145
        };
146
1088
    }
147

            
148
109
    pub(super) fn commodity_state(&mut self, target: usize) -> Option<(bool, String)> {
149
109
        let value = self.select_mut(target)?.value().to_string();
150
109
        Some((self.auto.contains(&target), value))
151
109
    }
152

            
153
23
    pub(super) fn restore_commodity(&mut self, target: usize, (auto, value): (bool, String)) {
154
23
        if let Some(select) = self.select_mut(target) {
155
23
            select.select_id(&value);
156
        }
157
23
        if auto {
158
7
            self.auto.insert(target);
159
        } else {
160
16
            self.auto.remove(&target);
161
        }
162
23
    }
163

            
164
331
    pub(super) fn picked(&mut self, col: usize) {
165
331
        self.auto.remove(&col);
166
331
    }
167

            
168
    /// WidgetKind for the given column index.
169
    #[must_use]
170
470
    pub fn col_kind(col: usize) -> WidgetKind {
171
470
        match columns().nth(col).map(|field| field.kind) {
172
239
            Some(Kind::Select { .. }) => WidgetKind::Select,
173
231
            _ => WidgetKind::Amount,
174
        }
175
470
    }
176

            
177
    /// Submit text of descriptor field `key`; `""` for unknown keys.
178
    #[must_use]
179
6864
    pub fn text(&self, key: &str) -> &str {
180
6864
        match key {
181
858
            "key" => &self.key,
182
854
            "hidden" => &self.hidden,
183
5152
            _ => columns()
184
18022
                .position(|field| field.key == key)
185
5152
                .map_or("", |col| self.cell_text(col)),
186
        }
187
6864
    }
188

            
189
6034
    fn cell_text(&self, col: usize) -> &str {
190
6034
        match col {
191
1209
            COL_FROM => self.from.value(),
192
852
            COL_TO => self.to.value(),
193
1401
            COL_FROM_COMM => self.from_commodity.value(),
194
867
            COL_TO_COMM => self.to_commodity.value(),
195
852
            COL_VALUE => self.value.value(),
196
853
            COL_TO_AMOUNT => self.to_amount.value(),
197
            _ => "",
198
        }
199
6034
    }
200

            
201
973
    pub(in crate::widgets) fn select(&self, col: usize) -> Option<&SelectWidget> {
202
973
        match col {
203
447
            COL_FROM => Some(&self.from),
204
137
            COL_TO => Some(&self.to),
205
27
            COL_FROM_COMM => Some(&self.from_commodity),
206
59
            COL_TO_COMM => Some(&self.to_commodity),
207
303
            _ => None,
208
        }
209
973
    }
210

            
211
1512
    pub(in crate::widgets) fn select_mut(&mut self, col: usize) -> Option<&mut SelectWidget> {
212
1512
        match col {
213
239
            COL_FROM => Some(&mut self.from),
214
190
            COL_TO => Some(&mut self.to),
215
452
            COL_FROM_COMM => Some(&mut self.from_commodity),
216
631
            COL_TO_COMM => Some(&mut self.to_commodity),
217
            _ => None,
218
        }
219
1512
    }
220

            
221
183
    pub(in crate::widgets) fn amount_mut(&mut self, col: usize) -> Option<&mut AmountWidget> {
222
183
        match col {
223
172
            COL_VALUE => Some(&mut self.value),
224
11
            COL_TO_AMOUNT => Some(&mut self.to_amount),
225
            _ => None,
226
        }
227
183
    }
228
}
229

            
230
/// An empty to-commodity means the from-commodity, so it leads the list and
231
/// a new row starts on it.
232
941
fn with_empty_meaning(commodities: &[SelectOption]) -> Vec<SelectOption> {
233
941
    let meaning = match columns().nth(COL_TO_COMM).map(|field| field.kind) {
234
        Some(Kind::Select {
235
            empty: Some(meaning),
236
            ..
237
941
        }) => meaning,
238
        _ => "",
239
    };
240
941
    let same = SelectOption {
241
941
        id: String::new(),
242
941
        label: meaning.to_string(),
243
941
    };
244
941
    std::iter::once(same)
245
941
        .chain(commodities.iter().cloned())
246
941
        .collect()
247
941
}
248

            
249
/// The label of a select whose option list has not arrived: a loaded id is
250
/// never shown.
251
pub(super) const PENDING_LABEL: &str = "…";
252

            
253
552
fn seed(cell: &str) -> Vec<SelectOption> {
254
552
    match cell {
255
222
        "" => Vec::new(),
256
330
        cell => vec![SelectOption {
257
330
            id: cell.to_string(),
258
330
            label: PENDING_LABEL.to_string(),
259
330
        }],
260
    }
261
552
}
262

            
263
/// `options` themselves when one has the id `cell`, so the loaded entity is
264
/// selected by its option. Else (an id missing from the list) led by a seed
265
/// option holding the loaded `cell` text, so an untouched select submits it
266
/// byte for byte.
267
970
fn bound(options: &[SelectOption], cell: &str) -> Vec<SelectOption> {
268
970
    if cell.is_empty() || options.iter().any(|option| option.id == cell) {
269
950
        return options.to_vec();
270
20
    }
271
20
    let seed = SelectOption {
272
20
        id: cell.to_string(),
273
20
        label: format!("{cell} (unchanged)"),
274
20
    };
275
20
    std::iter::once(seed)
276
20
        .chain(options.iter().cloned())
277
20
        .collect()
278
970
}