use http_body_util::Full; use hyper::body::Bytes; use hyper::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> { 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.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: &[User], user_payments: &HashMap, ) -> Vec<(String, i64)> { let mut user_payments: Vec<(String, i64)> = users .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: &[User], user_incomes: &HashMap, ) -> Vec<(String, i64)> { let mut user_incomes: Vec<(String, i64)> = users .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 }