1
//! Report filter grammar: the operator names the server parser reads and the
2
//! writer the visual builder emits them with.
3

            
4
use crate::sexpr::escape_str;
5

            
6
mod check;
7
#[cfg(any(test, feature = "test-fixtures"))]
8
pub mod fixtures;
9
mod read;
10
mod restore;
11

            
12
pub use check::{Fault, Reason, check, check_item};
13
pub use read::{Amount, Filter, NotAnAmount, ParseError};
14
pub use restore::{Restored, restore};
15

            
16
pub const AND: &str = "and";
17
pub const OR: &str = "or";
18
pub const NOT: &str = "not";
19
pub const ACCOUNT_EQ: &str = "account=";
20
pub const ACCOUNT_IN: &str = "account-in";
21
pub const ACCOUNT_SUBTREE: &str = "account-subtree";
22
pub const COUNTERPARTY_EQ: &str = "counterparty=";
23
pub const COUNTERPARTY_IN: &str = "counterparty-in";
24
pub const COMMODITY_EQ: &str = "commodity=";
25
pub const COMMODITY_IN: &str = "commodity-in";
26
pub const AMOUNT_GT: &str = "amount>";
27
pub const AMOUNT_LT: &str = "amount<";
28
pub const AMOUNT_EQ: &str = "amount=";
29
pub const ACCOUNT_TAG_EQ: &str = "account-tag=";
30
pub const TRANSACTION_TAG_EQ: &str = "transaction-tag=";
31
pub 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.
36
pub const UNBUILDABLE: &str = "(unbuildable-filter)";
37

            
38
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39
pub enum Entity {
40
    Account,
41
    Transaction,
42
    Split,
43
}
44

            
45
impl Entity {
46
    pub const ALL: [Self; 3] = [Self::Transaction, Self::Split, Self::Account];
47

            
48
    #[must_use]
49
3847
    pub fn parse(name: &str) -> Option<Self> {
50
7695
        Self::ALL.into_iter().find(|entity| entity.name() == name)
51
3847
    }
52

            
53
    /// The name the builder's checkboxes and the tag routes use.
54
    #[must_use]
55
10962
    pub fn name(self) -> &'static str {
56
10962
        match self {
57
1540
            Self::Account => "account",
58
5384
            Self::Transaction => "transaction",
59
4038
            Self::Split => "split",
60
        }
61
10962
    }
62

            
63
6581
    fn operator(self) -> &'static str {
64
6581
        match self {
65
1549
            Self::Account => ACCOUNT_TAG_EQ,
66
1735
            Self::Transaction => TRANSACTION_TAG_EQ,
67
3297
            Self::Split => SPLIT_TAG_EQ,
68
        }
69
6581
    }
70
}
71

            
72
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73
pub enum Logic {
74
    And,
75
    Or,
76
    Not,
77
}
78

            
79
impl Logic {
80
    #[must_use]
81
10183
    pub fn parse(name: &str) -> Option<Self> {
82
10183
        match name {
83
6530
            AND => Some(Self::And),
84
1538
            OR => Some(Self::Or),
85
1538
            NOT => Some(Self::Not),
86
577
            _ => None,
87
        }
88
10183
    }
89

            
90
    #[must_use]
91
16348
    pub fn operator(self) -> &'static str {
92
16348
        match self {
93
11725
            Self::And => AND,
94
3662
            Self::Or => OR,
95
961
            Self::Not => NOT,
96
        }
97
16348
    }
98
}
99

            
100
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101
pub enum Comparison {
102
    Gt,
103
    Lt,
104
    Eq,
105
}
106

            
107
impl Comparison {
108
    #[must_use]
109
8853
    pub fn operator(self) -> &'static str {
110
8853
        match self {
111
3847
            Self::Gt => AMOUNT_GT,
112
2887
            Self::Lt => AMOUNT_LT,
113
2119
            Self::Eq => AMOUNT_EQ,
114
        }
115
8853
    }
116
}
117

            
118
/// One row or nested group of the visual builder.
119
#[derive(Debug, Clone, PartialEq, Eq)]
120
pub 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

            
155
40120
fn call(operator: &str, args: &[String]) -> String {
156
40120
    format!("({operator} {})", args.join(" "))
157
40120
}
158

            
159
9869
fn any_of(mut parts: Vec<String>) -> String {
160
9869
    if parts.len() == 1 {
161
7739
        return parts.swap_remove(0);
162
2130
    }
163
2130
    call(OR, &parts)
164
9869
}
165

            
166
4451
fn tag_sexpr(entities: &[Entity], name: &str, values: &[String]) -> String {
167
4451
    let mut seen = Vec::new();
168
4451
    for entity in entities {
169
5420
        if !seen.contains(entity) {
170
5418
            seen.push(*entity);
171
2
        }
172
    }
173
4451
    let per_entity = seen
174
4451
        .into_iter()
175
5418
        .map(|entity| {
176
5418
            let leaves = values
177
5418
                .iter()
178
6581
                .map(|value| call(entity.operator(), &[escape_str(name), escape_str(value)]))
179
                .collect();
180
5418
            any_of(leaves)
181
5418
        })
182
        .collect();
183
4451
    any_of(per_entity)
184
4451
}
185

            
186
8489
fn id_sexpr(operator: &str, id: &str) -> String {
187
8489
    call(operator, &[escape_str(id.trim())])
188
8489
}
189

            
190
5968
fn ids_sexpr(operator: &str, ids: &[String]) -> String {
191
9049
    let args: Vec<String> = ids.iter().map(|id| escape_str(id.trim())).collect();
192
5968
    call(operator, &args)
193
5968
}
194

            
195
8850
fn amount_sexpr(comparison: Comparison, value: Amount) -> String {
196
8850
    let text = match value.denom() {
197
5386
        1 => value.numer().to_string(),
198
3464
        denom => format!("{}/{denom}", value.numer()),
199
    };
200
8850
    call(comparison.operator(), &[text])
201
8850
}
202

            
203
/// The text of a checked row or group.
204
32577
fn render(item: &Item) -> String {
205
32577
    match item {
206
        Item::Tag {
207
            entities,
208
            name,
209
            values,
210
4451
        } => tag_sexpr(entities, name, values),
211
5214
        Item::Account { id, subtree } => id_sexpr(
212
5214
            if *subtree {
213
1737
                ACCOUNT_SUBTREE
214
            } else {
215
3477
                ACCOUNT_EQ
216
            },
217
5214
            id,
218
        ),
219
2503
        Item::AccountIn { ids } => ids_sexpr(ACCOUNT_IN, ids),
220
1927
        Item::CounterpartyEq { id } => id_sexpr(COUNTERPARTY_EQ, id),
221
1540
        Item::CounterpartyIn { ids } => ids_sexpr(COUNTERPARTY_IN, ids),
222
1348
        Item::CommodityEq { id } => id_sexpr(COMMODITY_EQ, id),
223
1925
        Item::CommodityIn { ids } => ids_sexpr(COMMODITY_IN, ids),
224
8850
        Item::Amount { comparison, value } => amount_sexpr(*comparison, *value),
225
4819
        Item::Group { logic, items } => render_group(*logic, items),
226
    }
227
32577
}
228

            
229
26214
fn render_group(logic: Logic, items: &[Item]) -> String {
230
26214
    let mut parts: Vec<String> = items.iter().map(render).collect();
231
26214
    match (logic, parts.len()) {
232
2509
        (Logic::Not, _) => call(NOT, &parts),
233
18112
        (_, 1) => parts.swap_remove(0),
234
5593
        (logic, _) => call(logic.operator(), &parts),
235
    }
236
26214
}
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.
242
3
pub fn item_sexpr(item: &Item) -> Result<String, Fault> {
243
3
    check_item(item)?;
244
    Ok(render(item))
245
3
}
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.
252
25243
pub fn group_sexpr(logic: Logic, items: &[Item]) -> Result<Option<String>, Fault> {
253
25243
    check(logic, items)?;
254
21973
    Ok((!items.is_empty()).then(|| render_group(logic, items)))
255
25243
}
256

            
257
#[cfg(test)]
258
#[path = "filter_tests.rs"]
259
mod tests;