1
use std::collections::HashMap;
2

            
3
use finance::error::ReportError;
4
use num_rational::Rational64;
5
use num_traits::CheckedSub;
6
use sqlx::types::Uuid;
7

            
8
use super::super::{ActivityGroupResult, ActivityPeriod, CommodityAmount, ReportNode};
9
use super::tree::checked_sum;
10

            
11
44031
fn sum_amounts<'a>(
12
44031
    amounts: impl Iterator<Item = &'a CommodityAmount>,
13
44031
) -> Result<Vec<CommodityAmount>, ReportError> {
14
44031
    let mut out: Vec<CommodityAmount> = Vec::new();
15
44031
    let mut index: HashMap<Uuid, usize> = HashMap::new();
16
44031
    for a in amounts {
17
36839
        match index.get(&a.commodity_id) {
18
4520
            Some(&at) => out[at].amount = checked_sum(out[at].amount, a.amount)?,
19
            None => {
20
32319
                index.insert(a.commodity_id, out.len());
21
32319
                out.push(a.clone());
22
            }
23
        }
24
    }
25
44030
    Ok(out)
26
44031
}
27

            
28
22870
fn negate(amount: Rational64) -> Result<Rational64, ReportError> {
29
22870
    Rational64::ZERO
30
22870
        .checked_sub(&amount)
31
22870
        .ok_or(ReportError::AmountOverflow)
32
22870
}
33

            
34
30250
fn negated(amounts: &[CommodityAmount]) -> Result<Vec<CommodityAmount>, ReportError> {
35
30250
    amounts
36
30250
        .iter()
37
22870
        .map(|a| {
38
            Ok(CommodityAmount {
39
22870
                amount: negate(a.amount)?,
40
22868
                ..a.clone()
41
            })
42
22870
        })
43
        .collect()
44
30250
}
45

            
46
impl ReportNode {
47
8463
    fn negated(&self) -> Result<Self, ReportError> {
48
        Ok(Self {
49
8463
            amounts: negated(&self.amounts)?,
50
8462
            own_amounts: negated(&self.own_amounts)?,
51
8462
            children: self
52
8462
                .children
53
8462
                .iter()
54
8462
                .map(Self::negated)
55
8462
                .collect::<Result<_, _>>()?,
56
8462
            ..self.clone()
57
        })
58
8463
    }
59
}
60

            
61
impl ActivityGroupResult {
62
    /// The group as clients show it: `flip_sign` applied to the rows and the total.
63
    ///
64
    /// # Errors
65
    /// [`ReportError::AmountOverflow`] when an amount cannot be negated.
66
12604
    pub fn displayed(&self) -> Result<Self, ReportError> {
67
12604
        if !self.flip_sign {
68
5941
            return Ok(self.clone());
69
6663
        }
70
        Ok(Self {
71
6663
            roots: self
72
6663
                .roots
73
6663
                .iter()
74
6663
                .map(ReportNode::negated)
75
6663
                .collect::<Result<_, _>>()?,
76
6662
            total: negated(&self.total)?,
77
6662
            ..self.clone()
78
        })
79
12604
    }
80

            
81
    /// # Errors
82
    /// [`ReportError::AmountOverflow`] when a total does not fit.
83
28692
    pub fn new(
84
28692
        label: String,
85
28692
        flip_sign: bool,
86
28692
        roots: Vec<ReportNode>,
87
28692
    ) -> Result<Self, ReportError> {
88
28692
        let total = sum_amounts(
89
28692
            roots
90
28692
                .iter()
91
14634
                .filter(|r| r.depth == 0)
92
14634
                .flat_map(|r| r.amounts.iter()),
93
1
        )?;
94
28691
        Ok(Self {
95
28691
            label,
96
28691
            flip_sign,
97
28691
            roots,
98
28691
            total,
99
28691
        })
100
28692
    }
101
}
102

            
103
impl ActivityPeriod {
104
    /// # Errors
105
    /// [`ReportError::AmountOverflow`] when the net does not fit.
106
15339
    pub fn new(
107
15339
        label: Option<String>,
108
15339
        groups: Vec<ActivityGroupResult>,
109
15339
    ) -> Result<Self, ReportError> {
110
28150
        let net = sum_amounts(groups.iter().flat_map(|g| g.total.iter()))?;
111
15339
        Ok(Self { label, groups, net })
112
15339
    }
113

            
114
    /// The net as clients show it: `sum(displayed_total * (flip_sign ? +1 : -1))`,
115
    /// which is the negated raw sum.
116
    ///
117
    /// # Errors
118
    /// [`ReportError::AmountOverflow`] when an amount cannot be negated.
119
6663
    pub fn displayed_net(&self) -> Result<Vec<CommodityAmount>, ReportError> {
120
6663
        negated(&self.net)
121
6663
    }
122
}
123

            
124
#[cfg(test)]
125
#[path = "totals_tests.rs"]
126
mod tests;