summaryrefslogtreecommitdiffstats
path: root/cli/src/transaction.rs
blob: 117edfbedf1207b0e5fd6a37706160c910dc3bbf (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
use chrono::naive::NaiveDate;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::convert::AsRef;
use std::fs;
use std::hash::{Hash, Hasher};
use std::path::Path;
use structopt::StructOpt;
use twox_hash::XxHash64;

pub(crate) type Account = String;
pub(crate) type Category = String;

#[derive(Debug)]
#[derive(Hash)]
#[derive(Deserialize, Serialize)]
#[derive(StructOpt)]
pub enum TransactionKind {
    Expense,
    Income,
    //TODO Transfer,
}

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

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "expense" => Ok(TransactionKind::Expense),
            "income" => Ok(TransactionKind::Income),
            _ => Err(format!("Unknown transaction kind: {:?}", s)),
        }
    }
}

#[derive(Debug)]
#[derive(Hash)]
#[derive(Deserialize, Serialize)]
pub struct Transaction {
    pub description: String,
    pub date: NaiveDate,
    pub category: Category,
    pub amount: Decimal,
    pub kind: TransactionKind,
    pub from: Account,
    pub to: Account,
}

impl Transaction {
    pub(crate) fn write<P: AsRef<Path>>(&self, p: &P) -> std::io::Result<()> {
        fs::write(p, serde_json::to_string_pretty(self).unwrap()) //TODO control pretty or not
    }

    //TODO Result
    pub(crate) fn open<P: AsRef<Path>>(p: &P) -> Option<Self> {
        fs::read_to_string(p).ok().as_ref().and_then(|s| serde_json::from_str(s).ok())
    }

    pub fn id(&self) -> u64 {
        let mut h = XxHash64::default();
        self.hash(&mut h);
        h.finish()
    }
}