1
//! The report filter builder: the rows of the filter grammar, edited one
2
//! group at a time. Enter on a group or an `in` row steps into it, `back`
3
//! steps out; the whole tree is written back only by [`FilterBuilder::apply`].
4

            
5
use forms::FormValues;
6
use forms::filter::{Fault, Item, Logic, Restored, group_sexpr, restore};
7

            
8
use crate::form::RowShape;
9
use crate::widgets::SelectOption;
10
use describe::{describe, label, logic as logic_label};
11
use rows::{blank, id_of, item_of, picks_commodities, shape_of, values_of};
12

            
13
mod describe;
14
mod rows;
15

            
16
#[cfg(test)]
17
mod tests;
18

            
19
/// The rows or the ids of the group or `in` row being edited.
20
enum Level<'a> {
21
    Items(&'a [Item]),
22
    Ids(&'a [String]),
23
}
24

            
25
enum LevelMut<'a> {
26
    Items(&'a mut Vec<Item>),
27
    Ids(&'a mut Vec<String>),
28
}
29

            
30
126
fn level<'a>(items: &'a [Item], path: &[usize]) -> Option<Level<'a>> {
31
126
    let Some((&first, rest)) = path.split_first() else {
32
99
        return Some(Level::Items(items));
33
    };
34
27
    match items.get(first)? {
35
12
        Item::Group { items, .. } => level(items, rest),
36
        Item::AccountIn { ids } | Item::CounterpartyIn { ids } | Item::CommodityIn { ids } => {
37
15
            rest.is_empty().then_some(Level::Ids(ids))
38
        }
39
        _ => None,
40
    }
41
126
}
42

            
43
57
fn level_mut<'a>(items: &'a mut Vec<Item>, path: &[usize]) -> Option<LevelMut<'a>> {
44
57
    let Some((&first, rest)) = path.split_first() else {
45
39
        return Some(LevelMut::Items(items));
46
    };
47
18
    match items.get_mut(first)? {
48
8
        Item::Group { items, .. } => level_mut(items, rest),
49
        Item::AccountIn { ids } | Item::CounterpartyIn { ids } | Item::CommodityIn { ids } => {
50
10
            rest.is_empty().then_some(LevelMut::Ids(ids))
51
        }
52
        _ => None,
53
    }
54
57
}
55

            
56
/// What the builder shows: the heading, one line per row and the cursor.
57
#[derive(Debug, PartialEq, Eq)]
58
pub struct View {
59
    pub heading: String,
60
    pub rows: Vec<String>,
61
    pub selected: usize,
62
    pub notice: Option<String>,
63
}
64

            
65
/// A row form is open: where its values go.
66
#[derive(Debug, Clone)]
67
enum Pending {
68
    /// An id for the `in` row being edited.
69
    Id,
70
    /// A row of the kind of `template`, replacing the row `at` or appended.
71
    Row { at: Option<usize>, template: Item },
72
}
73

            
74
/// A row form to open: its shape and the values it starts with.
75
#[derive(Debug)]
76
pub struct Opened {
77
    pub shape: RowShape,
78
    pub values: FormValues,
79
}
80

            
81
#[derive(Debug)]
82
pub struct FilterBuilder {
83
    logic: Logic,
84
    items: Vec<Item>,
85
    original: (Logic, Vec<Item>),
86
    /// The filter text rows cannot show; the builder then edits nothing.
87
    opaque: Option<String>,
88
    path: Vec<usize>,
89
    selected: usize,
90
    pending: Option<Pending>,
91
    /// Why the last apply or edit was refused.
92
    pub error: Option<String>,
93
    pub accounts: Vec<SelectOption>,
94
    pub commodities: Vec<SelectOption>,
95
}
96

            
97
impl FilterBuilder {
98
    /// A builder holding the rows of the filter `text`.
99
    #[must_use]
100
105
    pub fn new(text: &str) -> Self {
101
105
        let (logic, items, opaque) = match restore(text) {
102
97
            Restored::Rows { logic, items } => (logic, items, None),
103
8
            Restored::Opaque => (Logic::And, Vec::new(), Some(text.to_string())),
104
        };
105
105
        Self {
106
105
            original: (logic, items.clone()),
107
105
            logic,
108
105
            items,
109
105
            opaque,
110
105
            path: Vec::new(),
111
105
            selected: 0,
112
105
            pending: None,
113
105
            error: None,
114
105
            accounts: Vec::new(),
115
105
            commodities: Vec::new(),
116
105
        }
117
105
    }
118

            
119
    #[must_use]
120
37
    pub fn is_dirty(&self) -> bool {
121
37
        self.original != (self.logic, self.items.clone())
122
37
    }
123

            
124
    #[must_use]
125
106
    pub fn is_opaque(&self) -> bool {
126
106
        self.opaque.is_some()
127
106
    }
128

            
129
22
    fn len(&self) -> usize {
130
22
        match level(&self.items, &self.path) {
131
18
            Some(Level::Items(items)) => items.len(),
132
4
            Some(Level::Ids(ids)) => ids.len(),
133
            None => 0,
134
        }
135
22
    }
136

            
137
9
    pub fn select_next(&mut self) {
138
9
        self.selected = (self.selected + 1).min(self.len().saturating_sub(1));
139
9
    }
140

            
141
2
    pub fn select_prev(&mut self) {
142
2
        self.selected = self.selected.saturating_sub(1);
143
2
    }
144

            
145
    /// The row under the cursor when this level holds rows.
146
    #[must_use]
147
24
    pub fn selected_item(&self) -> Option<&Item> {
148
24
        match level(&self.items, &self.path)? {
149
24
            Level::Items(items) => items.get(self.selected),
150
            Level::Ids(_) => None,
151
        }
152
24
    }
153

            
154
    /// Whether the level holds ids of an `in` row.
155
    #[must_use]
156
1
    pub fn in_ids(&self) -> bool {
157
1
        matches!(level(&self.items, &self.path), Some(Level::Ids(_)))
158
1
    }
159

            
160
    /// Steps into the group or `in` row under the cursor; `false` for any other row.
161
21
    pub fn enter(&mut self) -> bool {
162
21
        let steps = matches!(
163
21
            self.selected_item(),
164
            Some(
165
                Item::Group { .. }
166
                    | Item::AccountIn { .. }
167
                    | Item::CounterpartyIn { .. }
168
                    | Item::CommodityIn { .. }
169
            )
170
        );
171
21
        if steps {
172
17
            self.path.push(self.selected);
173
17
            self.selected = 0;
174
17
            self.error = None;
175
4
        }
176
21
        steps
177
21
    }
178

            
179
    /// Steps out to the enclosing level, the cursor on the row left.
180
18
    pub fn back(&mut self) -> bool {
181
18
        let Some(index) = self.path.pop() else {
182
1
            return false;
183
        };
184
17
        self.selected = index;
185
17
        self.error = None;
186
17
        true
187
18
    }
188

            
189
13
    pub fn delete(&mut self) {
190
13
        match level_mut(&mut self.items, &self.path) {
191
9
            Some(LevelMut::Items(items)) if self.selected < items.len() => {
192
9
                items.remove(self.selected);
193
            }
194
4
            Some(LevelMut::Ids(ids)) if self.selected < ids.len() => {
195
4
                ids.remove(self.selected);
196
            }
197
            _ => return,
198
        }
199
13
        self.error = None;
200
13
        self.selected = self.selected.min(self.len().saturating_sub(1));
201
13
    }
202

            
203
    /// And, or, not in turn for the group being edited.
204
6
    pub fn cycle_logic(&mut self) {
205
6
        let Some(logic) = self.logic_mut() else {
206
            return;
207
        };
208
6
        *logic = match *logic {
209
4
            Logic::And => Logic::Or,
210
2
            Logic::Or => Logic::Not,
211
            Logic::Not => Logic::And,
212
        };
213
6
        self.error = None;
214
6
    }
215

            
216
6
    fn logic_mut(&mut self) -> Option<&mut Logic> {
217
6
        let Some((&last, parent)) = self.path.split_last() else {
218
6
            return Some(&mut self.logic);
219
        };
220
        let Some(LevelMut::Items(items)) = level_mut(&mut self.items, parent) else {
221
            return None;
222
        };
223
        match items.get_mut(last)? {
224
            Item::Group { logic, .. } => Some(logic),
225
            _ => None,
226
        }
227
6
    }
228

            
229
    /// The form for adding an id to the `in` row being edited; `None` off an `in` row.
230
39
    pub fn begin_id(&mut self) -> Option<Opened> {
231
39
        let shape = match self.in_row()? {
232
4
            Item::AccountIn { .. } => RowShape::AccountId,
233
2
            Item::CounterpartyIn { .. } => RowShape::Counterparty,
234
2
            Item::CommodityIn { .. } => RowShape::Commodity,
235
3
            _ => return None,
236
        };
237
8
        self.pending = Some(Pending::Id);
238
8
        Some(Opened {
239
8
            shape,
240
8
            values: FormValues::default(),
241
8
        })
242
39
    }
243

            
244
    /// The form for the row under the cursor; `None` for a group or an `in` row.
245
3
    pub fn begin_edit(&mut self) -> Option<Opened> {
246
3
        let template = self.selected_item()?.clone();
247
3
        let shape = shape_of(&template)?;
248
3
        let values = values_of(&template);
249
3
        self.pending = Some(Pending::Row {
250
3
            at: Some(self.selected),
251
3
            template,
252
3
        });
253
3
        Some(Opened { shape, values })
254
3
    }
255

            
256
    /// Starts a new row of the named kind. Groups and `in` rows are added at
257
    /// once and stepped into; the others come back as a form to fill.
258
37
    pub fn begin_add(&mut self, kind: &str) -> Option<Opened> {
259
37
        let template = blank(kind)?;
260
36
        let Some(shape) = shape_of(&template) else {
261
7
            self.push(template);
262
7
            self.enter();
263
7
            return None;
264
        };
265
29
        let values = values_of(&template);
266
29
        self.pending = Some(Pending::Row { at: None, template });
267
29
        Some(Opened { shape, values })
268
37
    }
269

            
270
    /// Takes the values of the open row form.
271
    ///
272
    /// # Errors
273
    /// Why they are not a row; the form stays open and the same values may be retried.
274
37
    pub fn accept(&mut self, values: &FormValues) -> Result<(), String> {
275
37
        match self.pending.clone() {
276
            Some(Pending::Id) => {
277
8
                let id = id_of(values)?;
278
8
                if !self.has_id(&id) {
279
6
                    self.push_id(id);
280
2
                }
281
            }
282
            Some(Pending::Row { at, template }) => {
283
29
                let item = item_of(&template, values)?;
284
17
                match at {
285
1
                    Some(index) => self.replace(index, item),
286
16
                    None => self.push(item),
287
                }
288
            }
289
            None => return Err("no row is being edited".to_string()),
290
        }
291
25
        self.pending = None;
292
25
        Ok(())
293
37
    }
294

            
295
8
    fn has_id(&self, id: &str) -> bool {
296
8
        matches!(level(&self.items, &self.path), Some(Level::Ids(ids)) if ids.iter().any(|have| have == id))
297
8
    }
298

            
299
    /// The names a row form of this shape picks among.
300
    #[must_use]
301
36
    pub fn options_for(&self, shape: RowShape) -> &[SelectOption] {
302
36
        match picks_commodities(shape) {
303
5
            true => &self.commodities,
304
31
            false => &self.accounts,
305
        }
306
36
    }
307

            
308
    /// Adds `item` to the rows being edited and puts the cursor on it.
309
29
    fn push(&mut self, item: Item) {
310
29
        if let Some(LevelMut::Items(items)) = level_mut(&mut self.items, &self.path) {
311
29
            items.push(item);
312
29
            self.selected = items.len() - 1;
313
29
            self.error = None;
314
        }
315
29
    }
316

            
317
    /// Adds `id` to the `in` row being edited.
318
6
    fn push_id(&mut self, id: String) {
319
6
        if let Some(LevelMut::Ids(ids)) = level_mut(&mut self.items, &self.path) {
320
6
            ids.push(id);
321
6
            self.selected = ids.len() - 1;
322
6
            self.error = None;
323
        }
324
6
    }
325

            
326
    /// Replaces the row at `index` of the rows being edited.
327
1
    fn replace(&mut self, index: usize, item: Item) {
328
1
        if let Some(LevelMut::Items(items)) = level_mut(&mut self.items, &self.path)
329
1
            && let Some(row) = items.get_mut(index)
330
        {
331
1
            *row = item;
332
1
            self.error = None;
333
        }
334
1
    }
335

            
336
    /// The filter text of all rows. A row the writer would drop or widen is
337
    /// refused: the cursor goes to it and `error` says why.
338
64
    pub fn apply(&mut self) -> Option<String> {
339
64
        if self.is_opaque() {
340
2
            self.error = Some("the filter text is not shown as rows; nothing applied".into());
341
2
            return None;
342
62
        }
343
62
        match group_sexpr(self.logic, &self.items) {
344
57
            Ok(text) => Some(text.unwrap_or_default()),
345
            Err(fault) => {
346
5
                self.refuse(fault);
347
5
                None
348
            }
349
        }
350
64
    }
351

            
352
5
    fn refuse(&mut self, fault: Fault) {
353
5
        let (selected, parent) = match fault.path.split_last() {
354
4
            Some((&index, parent)) => (index, parent.to_vec()),
355
1
            None => (0, Vec::new()),
356
        };
357
5
        self.path = parent;
358
5
        self.selected = selected;
359
5
        self.error = Some(fault.reason.describe());
360
5
    }
361

            
362
44
    fn heading(&self) -> String {
363
44
        let mut crumbs = vec![logic_label(self.logic).to_string()];
364
44
        let mut items = self.items.as_slice();
365
44
        for &index in &self.path {
366
8
            match items.get(index) {
367
                Some(Item::Group {
368
                    logic,
369
                    items: inner,
370
                }) => {
371
6
                    crumbs.push(logic_label(*logic).to_string());
372
6
                    items = inner;
373
                }
374
2
                Some(row) => crumbs.push(describe(row, &self.accounts, &self.commodities)),
375
                None => break,
376
            }
377
        }
378
44
        crumbs.join(" > ")
379
44
    }
380

            
381
44
    fn rows(&self) -> Vec<String> {
382
44
        match level(&self.items, &self.path) {
383
42
            Some(Level::Items(items)) => items
384
42
                .iter()
385
55
                .map(|item| describe(item, &self.accounts, &self.commodities))
386
                .collect(),
387
4
            Some(Level::Ids(ids)) => ids.iter().map(|id| self.id_label(id)).collect(),
388
            None => Vec::new(),
389
        }
390
44
    }
391

            
392
    /// The name of an id of the `in` row being edited.
393
4
    fn id_label(&self, id: &str) -> String {
394
4
        let options = match self.in_row() {
395
            Some(Item::CommodityIn { .. }) => &self.commodities,
396
4
            _ => &self.accounts,
397
        };
398
4
        label(options, id)
399
4
    }
400

            
401
43
    fn in_row(&self) -> Option<&Item> {
402
43
        let (&last, parent) = self.path.split_last()?;
403
15
        match level(&self.items, parent)? {
404
15
            Level::Items(items) => items.get(last),
405
            Level::Ids(_) => None,
406
        }
407
43
    }
408

            
409
    #[must_use]
410
44
    pub fn view(&self) -> View {
411
        View {
412
44
            heading: self.heading(),
413
44
            rows: self.rows(),
414
44
            selected: self.selected,
415
44
            notice: self
416
44
                .opaque
417
44
                .as_ref()
418
3
                .map(|text| format!("cannot be shown as rows; the filter is left as is:\n{text}")),
419
        }
420
44
    }
421
}