aboutsummaryrefslogtreecommitdiff
path: root/src/payer.rs
blob: 0cc80162e04caec8714aaed80127729595cf7f34 (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
use std::collections::HashMap;

use crate::model::user::User;

pub fn exceeding(
    users: &[User],
    user_incomes: &HashMap<i64, i64>,
    user_payments: &HashMap<i64, i64>,
) -> Vec<(String, i64)> {
    let ratios = users.iter().map(|u| {
        let income = *user_incomes.get(&u.id).unwrap_or(&0);
        if income == 0 {
            (u.name.clone(), 0, 0.0)
        } else {
            let payments = *user_payments.get(&u.id).unwrap_or(&0);
            let ratio = payments as f64 / income as f64;
            (u.name.clone(), income, ratio)
        }
    });
    let min_ratio = ratios
        .clone()
        .map(|r| r.2)
        .min_by(|r1, r2| {
            ((r1 * 100_000_000.0).round() as i64)
                .cmp(&((r2 * 100_000_000.0).round() as i64))
        })
        .unwrap_or(0.0);
    ratios
        .filter_map(|r| {
            let exceeding = ((r.2 - min_ratio) * r.1 as f64).round() as i64;
            if exceeding == 0 {
                None
            } else {
                Some((r.0, exceeding))
            }
        })
        .collect()
}