summaryrefslogtreecommitdiffstats
path: root/cli/src/main.rs
blob: 12325e2235016205118a3cc97d74c5fa37d8aa6f (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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use chrono::naive::NaiveDate;
use rust_decimal::Decimal;
use std::path::PathBuf;
use std::str::FromStr;
use structopt::clap::AppSettings;
use structopt::StructOpt;
use tabled::{Style, Table};

mod search;
mod store;
mod transaction;

use search::Search;
use store::Store;
use transaction::{Transaction, TransactionKind};

//TODO relative ("yesterday", "-2d", etc)
fn parse_date(s: &str) -> Result<NaiveDate, String> {
    NaiveDate::parse_from_str(s, "%Y-%m-%d").map_err(|e| e.to_string())
}

#[derive(Debug)]
#[derive(StructOpt)]
enum Command {
    Insert {
        kind: TransactionKind,
        #[structopt(long)]
        account: String,

        //TODO multiple
        #[structopt(long)]
        category: String,

        #[structopt(long, parse(try_from_str = Decimal::from_str))]
        amount: Decimal,

        description: String,
        #[structopt(long, parse(try_from_str = parse_date))]
        date: Option<NaiveDate>,
    },
    List {
        target: ListTarget,
    },
    #[structopt(setting = AppSettings::AllowLeadingHyphen)]
    Show {
        #[structopt(long, multiple = true, number_of_values = 1)]
        sort: Vec<SortTarget>,

        filters: Vec<String>,
    },
}

#[derive(Debug)]
#[derive(StructOpt)]
enum ListTarget {
    Categories,
}

impl std::str::FromStr for ListTarget {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "categories" => Ok(ListTarget::Categories),
            _ => Err(format!("Unknown listable: {:?}", s)),
        }
    }
}

#[derive(Debug)]
#[derive(StructOpt)]
enum SortTarget {
    Amount,
    Date,
}

impl std::str::FromStr for SortTarget {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "amount" => Ok(SortTarget::Amount),
            "date" => Ok(SortTarget::Date),
            _ => Err(format!("Unknown sort target: {:?}", s)),
        }
    }
}

#[derive(Debug)]
#[derive(StructOpt)]
struct Mn {
    #[structopt(subcommand)]
    command: Command,
}

fn main() {
    let mut store = Store::open(PathBuf::from("store")).unwrap();

    let args = Mn::from_args();
    eprintln!("{:?}", args);
    match args.command {
        Command::Insert {
            kind,
            account,
            category,
            amount,
            description,
            date,
        } => {
            let transaction = Transaction {
                kind,
                to: account,
                from: "Default".to_string(),
                category,
                amount,
                description,
                date: match date {
                    Some(date) => date,
                    None => chrono::offset::Local::today().naive_utc(),
                },
            };
            eprintln!("{:?}", transaction);
            println!("{}", transaction.id());
            store.push(transaction);
            store.write().unwrap();
        }
        Command::List {
            target: ListTarget::Categories
        } => {
            println!("{}", store.categories().join("\n"));
        }
        Command::Show {
            sort,
            filters,
        } => {
            let mut search = Search::new(store.transactions());
            if !filters.is_empty() {
                search = search.parse(filters.join(" "));
            }
            let mut transactions = search.get();
            if sort.is_empty() {
                transactions.sort_by_key(|t| t.date);
            } else {
                match &sort[0] {
                    SortTarget::Amount => transactions.sort_by_key(|t| t.amount),
                    SortTarget::Date => transactions.sort_by_key(|t| t.date),
                }
                for i in 1..sort.len() {
                    //TODO This won't work with 3+ sorts in case key 2 are equal across a key 1
                    //     border. We need to pass the earlier buckets for later sorts as well.
                    //     `Vec<range>`?
                    inner_sort_by(&mut transactions, sort_by_func(&sort[i-1]), sort_by_func(&sort[i]));
                }
            }
            println!("{}", Table::new(transactions).with(Style::psql()));
        }
    }
}

fn sort_by_func(sort: &SortTarget) -> impl FnMut(&&Transaction, &&Transaction) -> std::cmp::Ordering {
    match sort {
        SortTarget::Amount => |t1: &&Transaction, t2: &&Transaction| t1.amount.cmp(&t2.amount),
        SortTarget::Date => |t1: &&Transaction, t2: &&Transaction| t1.date.cmp(&t2.date),
    }
}

fn inner_sort_by<T, F>(v: &mut [T], mut outer_cmp: F, mut inner_cmp: F)
where
    F: FnMut(&T, &T) -> std::cmp::Ordering,
{
    // Early out
    if v.len() < 2 {
        return;
    }

    let mut lower = 0; // Lower bound of current equal range
    for i in 0..v.len() {
        if outer_cmp(&v[i], &v[lower]) != std::cmp::Ordering::Equal {
            let upper = i;
            if upper - lower > 1 {
                v[lower..upper].sort_by(&mut inner_cmp);
            }
            lower = i;
        }
    }
}