summaryrefslogtreecommitdiffstats
path: root/cli/src/search.rs
blob: 993a924ca8919e2ed72900e263be2b8ebed047df (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
use chrono::{naive::NaiveDate, Duration};

use crate::transaction::{Category, Transaction};

pub struct Search<'t> {
    filtered: Vec<usize>,
    transactions: Vec<&'t Transaction>,
}

#[derive(Clone)]
pub enum DateIsh {
    Absolute(NaiveDate),
    Relative(Duration),
}

impl DateIsh {
    pub fn parse(s: &str) -> Self {
        DateIsh::Absolute(NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap())
    }

    pub fn get(self) -> NaiveDate {
        match self {
            DateIsh::Absolute(date) => date,
            DateIsh::Relative(offset) => chrono::offset::Local::today().naive_utc() + offset
        }
    }
}

pub enum Constraint {
    Category(Category),
    Before(DateIsh),
    After(DateIsh),
}

enum FilterType {
    Add(Constraint),
    Subtract(Constraint),
    Only(Constraint),
}

impl FilterType {
    fn apply<'s>(&self, mut search: Search<'s>) -> Search<'s> {
        match self {
            FilterType::Add(_) => {
                //TODO binary search and insert sorted
                for idx in search
                    .transactions
                    .iter()
                    .enumerate()
                    .filter(|(_, t)| self.satisfies(t))
                    .map(|(idx, _)| idx)
                {
                    search.filtered.push(idx);
                }
                search.filtered.sort();
                search.filtered.dedup();
            }
            FilterType::Subtract(_) => {
                search.filtered = search
                    .filtered
                    .iter()
                    .filter(|t| !self.satisfies(search.transactions[**t]))
                    .copied()
                    .collect();
            }
            FilterType::Only(_) => {
                search.filtered = search
                    .filtered
                    .iter()
                    .filter(|t| self.satisfies(search.transactions[**t]))
                    .copied()
                    .collect();
            }
        }
        search
    }

    fn satisfies(&self, transaction: &Transaction) -> bool {
        match self {
            // Category
            FilterType::Add(Constraint::Category(category))
                | FilterType::Subtract(Constraint::Category(category))
                | FilterType::Only(Constraint::Category(category))
                => &transaction.category == category,

            FilterType::Only(Constraint::Before(date))
                => transaction.date < date.clone().get(),

            FilterType::Only(Constraint::After(date))
                => transaction.date >= date.clone().get(),

            FilterType::Add(Constraint::Before(date))
                => transaction.date < date.clone().get(),

            FilterType::Add(Constraint::After(date))
                => transaction.date >= date.clone().get(),

            FilterType::Subtract(Constraint::Before(date))
                => transaction.date < date.clone().get(),

            FilterType::Subtract(Constraint::After(date))
                => transaction.date >= date.clone().get(),
        }
    }
}

impl<'t> Search<'t> {
    pub fn new(transactions: Vec<&'t Transaction>) -> Self {
        Self {
            filtered: std::iter::successors(Some(0_usize), |n| Some(n.checked_add(1).unwrap()))
                .take(transactions.len())
                .collect(),
            transactions,
        }
    }

    pub fn get(&self) -> Vec<&'t Transaction> {
        self
            .filtered
            .iter()
            .map(|idx| self.transactions[*idx])
            .collect()
    }

    pub fn parse(mut self, rules: String) -> Self {
        for rule in rules.split(' ') {
            let (filter_type, rule): (fn(Constraint) -> FilterType, &str) = match rule.chars().nth(0).unwrap() {
                '-' => (FilterType::Subtract, &rule[1..]),
                '+' => (FilterType::Add, &rule[1..]),
                _ => (FilterType::Only, &rule[..]),
            };

            //TODO lexing? can do a function for "spaces inside" instead

            // +category:a
            //TODO: category:"foo bar"

            //  before:2021-01-01  =>  + (* -> 2020-12-31) n-incl
            //  after:2021-01-01   =>  + (2021-01-01 -> *) incl
            // -before:2021-01-01  =>  - (2021-01-01 -> *) incl
            // -after:2021-01-01   =>  - (* -> 2021-12-31) n-incl

            //TODO:
            // today is 2021-01-01:
            //  before:-1d  =>  + (* -> 2020-12-31) n-incl
            //  after:-1d   =>  + (2021-01-01 -> *) incl
            // -before:-1d  =>  - (2021-01-01 -> *) incl
            // -after:-1d   =>  - (* -> 2020-12-31) n-incl

            let constraint = match rule.split_once(':').unwrap() {
                ("category", category) => Constraint::Category(category.to_string()),
                ("before", date_ish) => Constraint::Before(DateIsh::parse(date_ish)),
                ("after", date_ish) => Constraint::After(DateIsh::parse(date_ish)),
                _ => panic!(),
            };

            self = filter_type(constraint).apply(self);
        }
        self
    }
}