aboutsummaryrefslogtreecommitdiff
path: root/src/controller/balance.rs
blob: 228ff041972845daa38e1538ce64e4f2efa67146 (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
use hyper::{Body, Response};
use std::collections::HashMap;
use tera::Context;

use crate::controller::utils;
use crate::controller::wallet::Wallet;
use crate::db;
use crate::model::user::User;
use crate::payer;
use crate::templates;

pub async fn get(wallet: &Wallet) -> Response<Body> {
    let users = db::users::list(&wallet.pool).await;

    let incomes_from = db::incomes::defined_for_all(&wallet.pool).await;
    let user_incomes = match incomes_from {
        Some(from) => db::incomes::cumulative(&wallet.pool, from).await,
        None => HashMap::new(),
    };
    let template_user_incomes =
        get_template_user_incomes(&users, &user_incomes);
    let total_income: i64 = user_incomes.values().sum();

    let user_payments = db::payments::repartition(&wallet.pool).await;
    let template_user_payments =
        get_template_user_payments(&users, &user_payments);
    let total_payments: i64 =
        user_payments.clone().into_iter().map(|p| p.1).sum();

    let exceeding_payers =
        payer::exceeding(&users, &user_incomes, &user_payments);

    let mut context = Context::new();
    context.insert("header", &templates::Header::Balance);
    context.insert("connected_user", &wallet.user);
    context.insert(
        "incomes_from",
        &incomes_from.map(|d| d.format("%d/%m/%Y").to_string()),
    );
    context.insert("total_income", &total_income);
    context.insert("user_incomes", &template_user_incomes);
    context.insert("total_payments", &total_payments);
    context.insert("user_payments", &template_user_payments);
    context.insert("exceeding_payers", &exceeding_payers);

    utils::template(&wallet.assets, &wallet.templates, "balance.html", context)
}

fn get_template_user_payments(
    users: &Vec<User>,
    user_payments: &HashMap<i64, i64>,
) -> Vec<(String, i64)> {
    let mut user_payments: Vec<(String, i64)> = users
        .into_iter()
        .map(|u| (u.name.clone(), *user_payments.get(&u.id).unwrap_or(&0)))
        .collect();
    user_payments.sort_by_key(|i| i.1);
    user_payments
}

fn get_template_user_incomes(
    users: &Vec<User>,
    user_incomes: &HashMap<i64, i64>,
) -> Vec<(String, i64)> {
    let mut user_incomes: Vec<(String, i64)> = users
        .into_iter()
        .map(|u| (u.name.clone(), *user_incomes.get(&u.id).unwrap_or(&0)))
        .collect();
    user_incomes.sort_by_key(|i| i.1);
    user_incomes
}