Skip to main content

forms/filter/
check.rs

1//! The one answer to "can the builder write these rows as they stand".
2//!
3//! A filled-in row that no condition can be built from is a [`Fault`], never
4//! silently left out of the text: that would run a broader report than the one
5//! asked for. Only an empty builder (no rows at all) means no filter. A client
6//! whose form shows an untouched placeholder row leaves it out of the items it
7//! hands over; a blank row that does arrive here is a fault.
8
9use super::{Entity, Item, Logic};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Reason {
13    /// A nested group holds no row.
14    EmptyGroup,
15    /// An `in` row holds no id at all.
16    EmptyIn,
17    /// An id, or a member of an `in` list, is blank.
18    BlankId,
19    TagWithoutEntity,
20    TagWithoutName,
21    TagWithoutValues,
22    NotArity(usize),
23    /// A row with nothing filled in.
24    BlankRow,
25    /// Text was typed into an account picker but no account was picked.
26    NotPicked,
27    /// A single-id row holds several ids.
28    NotSingle,
29    /// The amount is not a number.
30    BadAmount,
31    /// A row no condition can be built from, for a reason not listed above.
32    Incomplete,
33}
34
35impl Reason {
36    #[must_use]
37    pub fn describe(self) -> String {
38        match self {
39            Self::EmptyGroup => "a group needs at least one row".to_owned(),
40            Self::EmptyIn => "an id list needs at least one id".to_owned(),
41            Self::BlankId => "an id list needs non-blank ids".to_owned(),
42            Self::TagWithoutEntity => "a tag row needs an entity".to_owned(),
43            Self::TagWithoutName => "a tag row needs a name".to_owned(),
44            Self::TagWithoutValues => "a tag row needs a value".to_owned(),
45            Self::NotArity(count) => format!("not takes exactly one condition, got {count}"),
46            Self::BlankRow => "row is blank".to_owned(),
47            Self::NotPicked => "pick one from the list".to_owned(),
48            Self::NotSingle => "this row takes exactly one id".to_owned(),
49            Self::BadAmount => "the amount is not a number: use 5, 1/3, 0.25 or 15%".to_owned(),
50            Self::Incomplete => "row is incomplete".to_owned(),
51        }
52    }
53}
54
55/// The first refusal and where it is: `path` holds the index of each row on
56/// the way down from the list that was checked, empty for the list itself.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct Fault {
59    pub path: Vec<usize>,
60    pub reason: Reason,
61}
62
63impl Fault {
64    fn at(reason: Reason) -> Self {
65        Self {
66            path: Vec::new(),
67            reason,
68        }
69    }
70
71    fn under(mut self, at: usize) -> Self {
72        self.path.insert(0, at);
73        self
74    }
75}
76
77fn tag(entities: &[Entity], name: &str, values: &[String]) -> Result<(), Reason> {
78    match (name.trim().is_empty(), values.is_empty()) {
79        (true, true) => Err(Reason::BlankRow),
80        (true, false) => Err(Reason::TagWithoutName),
81        (false, true) => Err(Reason::TagWithoutValues),
82        (false, false) if entities.is_empty() => Err(Reason::TagWithoutEntity),
83        (false, false) => Ok(()),
84    }
85}
86
87fn blank_id(id: &str) -> Result<(), Reason> {
88    if id.trim().is_empty() {
89        return Err(Reason::BlankRow);
90    }
91    Ok(())
92}
93
94fn id_list(ids: &[String]) -> Result<(), Reason> {
95    if ids.is_empty() {
96        return Err(Reason::EmptyIn);
97    }
98    if ids.iter().any(|id| id.trim().is_empty()) {
99        return Err(Reason::BlankId);
100    }
101    Ok(())
102}
103
104fn logic_arity(logic: Logic, count: usize) -> Result<(), Reason> {
105    match (logic, count) {
106        (Logic::Not, 1) => Ok(()),
107        (Logic::Not, count) => Err(Reason::NotArity(count)),
108        _ => Ok(()),
109    }
110}
111
112/// Checks one row or nested group.
113///
114/// # Errors
115/// The first `Fault`, the path counted from `item`.
116pub fn check_item(item: &Item) -> Result<(), Fault> {
117    match item {
118        Item::Group { items, .. } if items.is_empty() => Err(Fault::at(Reason::EmptyGroup)),
119        Item::Group { logic, items } => check(*logic, items),
120        leaf => leaf_reason(leaf).map_err(Fault::at),
121    }
122}
123
124fn leaf_reason(item: &Item) -> Result<(), Reason> {
125    match item {
126        Item::Tag {
127            entities,
128            name,
129            values,
130        } => tag(entities, name, values),
131        Item::Account { id: value, .. }
132        | Item::CounterpartyEq { id: value }
133        | Item::CommodityEq { id: value } => blank_id(value),
134        Item::AccountIn { ids: list }
135        | Item::CounterpartyIn { ids: list }
136        | Item::CommodityIn { ids: list } => id_list(list),
137        Item::Amount { .. } | Item::Group { .. } => Ok(()),
138    }
139}
140
141/// Checks the rows of the builder. No rows is no filter and is fine.
142///
143/// # Errors
144/// The first `Fault`, the children before the list they are in.
145pub fn check(logic: Logic, items: &[Item]) -> Result<(), Fault> {
146    for (at, item) in items.iter().enumerate() {
147        check_item(item).map_err(|fault| fault.under(at))?;
148    }
149    match items.len() {
150        0 => Ok(()),
151        count => logic_arity(logic, count).map_err(Fault::at),
152    }
153}
154
155#[cfg(test)]
156#[path = "check_tests.rs"]
157mod tests;