summaryrefslogtreecommitdiff
path: root/src/web_frontend/balance.rs
blob: f05b69a0c3e0810cb1d315adb1b70011797db0a1 (plain)
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
use parsers::csv::CsvFile;
use banking::account::Account;
use crate::banking::asset::Asset;
//use parsers::ini::IniFile;
use std::collections::HashMap;
use rocket_contrib::templates::Template;
use rocket::response::NamedFile;
use std::path::{PathBuf, Path};
use rocket::request::Form;
use rocket::http::RawStr;
use regex::Regex;
use chrono::{NaiveDate, Utc};
use chrono::Datelike;
use crate::web_frontend::util;

#[derive(Serialize)]
struct MonthEarnSpend {
	name : String,
	earned : f32,
	spent : f32,
}


#[derive(Serialize)]
struct BalanceContext {
	account_name : String,
	months : Vec<MonthEarnSpend>,
	date_start : String,
	date_end : String
}


#[get("/balance/<account>?<start>&<end>")]
pub fn balance_handler(account : &RawStr, start : Option<&RawStr>, end : Option<&RawStr>) -> rocket_contrib::templates::Template {
	let account_name = account.to_string();
	let date_start = match start {
		Some(s) => { let mut tmp = s.to_string();
			tmp.push_str("-01");
			chrono::NaiveDate::parse_from_str(&tmp, "%Y-%m-%d").unwrap() },
		None => Utc::today().naive_utc()
	};
	let date_end = match end {
		Some(s) => { let mut tmp = s.to_string();
			tmp.push_str("-01");
			chrono::NaiveDate::parse_from_str(&tmp, "%Y-%m-%d").unwrap() },
		None => Utc::today().naive_utc() 
	};
	let date_range = crate::web_frontend::util::DateRange::new(date_start, date_end);	

	let asset_ini = "data/asset.ini";
	let asset : Asset = crate::banking::asset::Asset::from_ini_file(asset_ini);
    let transactions = asset.get_account_by_name(&account_name);
    let acc;
    match transactions {
	    Some(trans) => acc = trans,
	    None => panic!("could not read file")
    }
    let t = acc.transactions;

    let mut earn_spend_v = Vec::new();
	for date in date_range {
	    let result : Vec<_> = t.iter().filter(|x| x.date.month() == date.month() && x.date.year() == date.year()).collect();
	    let mut earn = 0.0;
	    let mut spend = 0.0;
	    for r in &result {
		    if r.amount > 0.0 {
			    earn = earn + r.amount;
		    } else {
			    spend = spend + r.amount.abs();
		    }
	    }
	    earn_spend_v.push(MonthEarnSpend { name : date.to_string(), earned : earn, spent : spend});
	}
	let context = BalanceContext { account_name : account_name,
		months : earn_spend_v , date_start : date_start.to_string()[0..7].to_string(),
		date_end : date_end.to_string()[0..7].to_string()};
	Template::render("balance", context)
}