use sqlx::sqlite::SqlitePool; use std::collections::HashMap; use tera::{Context, Tera}; use crate::db; use crate::mail; use crate::model::config::Config; use crate::payer; pub async fn send( config: &Config, pool: &SqlitePool, templates: &Tera, ) -> bool { match get_weekly_report(pool, templates).await { Ok(report) => { let users = db::users::list(pool).await; mail::send( config, users .into_iter() .map(|u| mail::Recipient { name: u.name, address: u.email, }) .collect(), "Rapport hebdomadaire".to_string(), report, ) .await } Err(err) => { log::error!("Error preparing weekly report from template: {:?}", err); false } } } async fn get_weekly_report( pool: &SqlitePool, templates: &Tera, ) -> Result { let users = db::users::list(pool).await; let incomes_from = db::incomes::defined_for_all(pool).await; let user_incomes = match incomes_from { Some(from) => db::incomes::cumulative(pool, from).await, None => HashMap::new(), }; let user_payments = db::payments::repartition(pool).await; let exceeding_payers = payer::exceeding(&users, &user_incomes, &user_payments); let last_week_payments = db::payments::last_week(pool).await; let last_week_incomes = db::incomes::last_week(pool).await; let mut context = Context::new(); context.insert("exceeding_payers", &exceeding_payers); context.insert("payments", &last_week_payments); context.insert("incomes", &last_week_incomes); templates.render("report/report.j2", &context) }