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

impl fmt::Display for TransactionKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TransactionKind::Expense => write!(f, "expense"),
            TransactionKind::Income => write!(f, "income"),
        }
    }
}

#[derive(Debug)]
#[derive(Hash)]
#[derive(Deserialize, Serialize)]
#[derive(Tabled)]
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()
    }
}