Skip to main content

forms/
filter.rs

1//! Report filter grammar: the operator names the server parser reads and the
2//! writer the visual builder emits them with.
3
4use crate::sexpr::escape_str;
5
6mod check;
7#[cfg(any(test, feature = "test-fixtures"))]
8pub mod fixtures;
9mod read;
10mod restore;
11
12pub use check::{Fault, Reason, check, check_item};
13pub use read::{Amount, Filter, NotAnAmount, ParseError};
14pub use restore::{Restored, restore};
15
16pub const AND: &str = "and";
17pub const OR: &str = "or";
18pub const NOT: &str = "not";
19pub const ACCOUNT_EQ: &str = "account=";
20pub const ACCOUNT_IN: &str = "account-in";
21pub const ACCOUNT_SUBTREE: &str = "account-subtree";
22pub const COUNTERPARTY_EQ: &str = "counterparty=";
23pub const COUNTERPARTY_IN: &str = "counterparty-in";
24pub const COMMODITY_EQ: &str = "commodity=";
25pub const COMMODITY_IN: &str = "commodity-in";
26pub const AMOUNT_GT: &str = "amount>";
27pub const AMOUNT_LT: &str = "amount<";
28pub const AMOUNT_EQ: &str = "amount=";
29pub const ACCOUNT_TAG_EQ: &str = "account-tag=";
30pub const TRANSACTION_TAG_EQ: &str = "transaction-tag=";
31pub const SPLIT_TAG_EQ: &str = "split-tag=";
32
33/// Written when the builder holds a condition it cannot express. It is not in
34/// the grammar, so the server refuses the request instead of running a broader
35/// report than the one asked for.
36pub const UNBUILDABLE: &str = "(unbuildable-filter)";
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Entity {
40    Account,
41    Transaction,
42    Split,
43}
44
45impl Entity {
46    pub const ALL: [Self; 3] = [Self::Transaction, Self::Split, Self::Account];
47
48    #[must_use]
49    pub fn parse(name: &str) -> Option<Self> {
50        Self::ALL.into_iter().find(|entity| entity.name() == name)
51    }
52
53    /// The name the builder's checkboxes and the tag routes use.
54    #[must_use]
55    pub fn name(self) -> &'static str {
56        match self {
57            Self::Account => "account",
58            Self::Transaction => "transaction",
59            Self::Split => "split",
60        }
61    }
62
63    fn operator(self) -> &'static str {
64        match self {
65            Self::Account => ACCOUNT_TAG_EQ,
66            Self::Transaction => TRANSACTION_TAG_EQ,
67            Self::Split => SPLIT_TAG_EQ,
68        }
69    }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Logic {
74    And,
75    Or,
76    Not,
77}
78
79impl Logic {
80    #[must_use]
81    pub fn parse(name: &str) -> Option<Self> {
82        match name {
83            AND => Some(Self::And),
84            OR => Some(Self::Or),
85            NOT => Some(Self::Not),
86            _ => None,
87        }
88    }
89
90    #[must_use]
91    pub fn operator(self) -> &'static str {
92        match self {
93            Self::And => AND,
94            Self::Or => OR,
95            Self::Not => NOT,
96        }
97    }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum Comparison {
102    Gt,
103    Lt,
104    Eq,
105}
106
107impl Comparison {
108    #[must_use]
109    pub fn operator(self) -> &'static str {
110        match self {
111            Self::Gt => AMOUNT_GT,
112            Self::Lt => AMOUNT_LT,
113            Self::Eq => AMOUNT_EQ,
114        }
115    }
116}
117
118/// One row or nested group of the visual builder.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub enum Item {
121    Tag {
122        entities: Vec<Entity>,
123        name: String,
124        values: Vec<String>,
125    },
126    Account {
127        id: String,
128        subtree: bool,
129    },
130    AccountIn {
131        ids: Vec<String>,
132    },
133    CounterpartyEq {
134        id: String,
135    },
136    CounterpartyIn {
137        ids: Vec<String>,
138    },
139    CommodityEq {
140        id: String,
141    },
142    CommodityIn {
143        ids: Vec<String>,
144    },
145    Amount {
146        comparison: Comparison,
147        value: Amount,
148    },
149    Group {
150        logic: Logic,
151        items: Vec<Item>,
152    },
153}
154
155fn call(operator: &str, args: &[String]) -> String {
156    format!("({operator} {})", args.join(" "))
157}
158
159fn any_of(mut parts: Vec<String>) -> String {
160    if parts.len() == 1 {
161        return parts.swap_remove(0);
162    }
163    call(OR, &parts)
164}
165
166fn tag_sexpr(entities: &[Entity], name: &str, values: &[String]) -> String {
167    let mut seen = Vec::new();
168    for entity in entities {
169        if !seen.contains(entity) {
170            seen.push(*entity);
171        }
172    }
173    let per_entity = seen
174        .into_iter()
175        .map(|entity| {
176            let leaves = values
177                .iter()
178                .map(|value| call(entity.operator(), &[escape_str(name), escape_str(value)]))
179                .collect();
180            any_of(leaves)
181        })
182        .collect();
183    any_of(per_entity)
184}
185
186fn id_sexpr(operator: &str, id: &str) -> String {
187    call(operator, &[escape_str(id.trim())])
188}
189
190fn ids_sexpr(operator: &str, ids: &[String]) -> String {
191    let args: Vec<String> = ids.iter().map(|id| escape_str(id.trim())).collect();
192    call(operator, &args)
193}
194
195fn amount_sexpr(comparison: Comparison, value: Amount) -> String {
196    let text = match value.denom() {
197        1 => value.numer().to_string(),
198        denom => format!("{}/{denom}", value.numer()),
199    };
200    call(comparison.operator(), &[text])
201}
202
203/// The text of a checked row or group.
204fn render(item: &Item) -> String {
205    match item {
206        Item::Tag {
207            entities,
208            name,
209            values,
210        } => tag_sexpr(entities, name, values),
211        Item::Account { id, subtree } => id_sexpr(
212            if *subtree {
213                ACCOUNT_SUBTREE
214            } else {
215                ACCOUNT_EQ
216            },
217            id,
218        ),
219        Item::AccountIn { ids } => ids_sexpr(ACCOUNT_IN, ids),
220        Item::CounterpartyEq { id } => id_sexpr(COUNTERPARTY_EQ, id),
221        Item::CounterpartyIn { ids } => ids_sexpr(COUNTERPARTY_IN, ids),
222        Item::CommodityEq { id } => id_sexpr(COMMODITY_EQ, id),
223        Item::CommodityIn { ids } => ids_sexpr(COMMODITY_IN, ids),
224        Item::Amount { comparison, value } => amount_sexpr(*comparison, *value),
225        Item::Group { logic, items } => render_group(*logic, items),
226    }
227}
228
229fn render_group(logic: Logic, items: &[Item]) -> String {
230    let mut parts: Vec<String> = items.iter().map(render).collect();
231    match (logic, parts.len()) {
232        (Logic::Not, _) => call(NOT, &parts),
233        (_, 1) => parts.swap_remove(0),
234        (logic, _) => call(logic.operator(), &parts),
235    }
236}
237
238/// The filter text for one builder row or group.
239///
240/// # Errors
241/// The `Fault` of a row or group no condition can be built from.
242pub fn item_sexpr(item: &Item) -> Result<String, Fault> {
243    check_item(item)?;
244    Ok(render(item))
245}
246
247/// The filter text for the rows of the builder; `None` for an empty builder,
248/// which means no filter. A single child stands for its group.
249///
250/// # Errors
251/// The `Fault` of the first row or group no condition can be built from.
252pub fn group_sexpr(logic: Logic, items: &[Item]) -> Result<Option<String>, Fault> {
253    check(logic, items)?;
254    Ok((!items.is_empty()).then(|| render_group(logic, items)))
255}
256
257#[cfg(test)]
258#[path = "filter_tests.rs"]
259mod tests;