aboutsummaryrefslogtreecommitdiff
path: root/src/jobs/weekly_report.rs
blob: 0c10143522f5f8f13eb72afac6a376b5e7545954 (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
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<String, tera::Error> {
    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)
}