Skip to main content

server/command/report/
totals.rs

1use std::collections::HashMap;
2
3use finance::error::ReportError;
4use num_rational::Rational64;
5use num_traits::CheckedSub;
6use sqlx::types::Uuid;
7
8use super::super::{ActivityGroupResult, ActivityPeriod, CommodityAmount, ReportNode};
9use super::tree::checked_sum;
10
11fn sum_amounts<'a>(
12    amounts: impl Iterator<Item = &'a CommodityAmount>,
13) -> Result<Vec<CommodityAmount>, ReportError> {
14    let mut out: Vec<CommodityAmount> = Vec::new();
15    let mut index: HashMap<Uuid, usize> = HashMap::new();
16    for a in amounts {
17        match index.get(&a.commodity_id) {
18            Some(&at) => out[at].amount = checked_sum(out[at].amount, a.amount)?,
19            None => {
20                index.insert(a.commodity_id, out.len());
21                out.push(a.clone());
22            }
23        }
24    }
25    Ok(out)
26}
27
28fn negate(amount: Rational64) -> Result<Rational64, ReportError> {
29    Rational64::ZERO
30        .checked_sub(&amount)
31        .ok_or(ReportError::AmountOverflow)
32}
33
34fn negated(amounts: &[CommodityAmount]) -> Result<Vec<CommodityAmount>, ReportError> {
35    amounts
36        .iter()
37        .map(|a| {
38            Ok(CommodityAmount {
39                amount: negate(a.amount)?,
40                ..a.clone()
41            })
42        })
43        .collect()
44}
45
46impl ReportNode {
47    fn negated(&self) -> Result<Self, ReportError> {
48        Ok(Self {
49            amounts: negated(&self.amounts)?,
50            own_amounts: negated(&self.own_amounts)?,
51            children: self
52                .children
53                .iter()
54                .map(Self::negated)
55                .collect::<Result<_, _>>()?,
56            ..self.clone()
57        })
58    }
59}
60
61impl 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    pub fn displayed(&self) -> Result<Self, ReportError> {
67        if !self.flip_sign {
68            return Ok(self.clone());
69        }
70        Ok(Self {
71            roots: self
72                .roots
73                .iter()
74                .map(ReportNode::negated)
75                .collect::<Result<_, _>>()?,
76            total: negated(&self.total)?,
77            ..self.clone()
78        })
79    }
80
81    /// # Errors
82    /// [`ReportError::AmountOverflow`] when a total does not fit.
83    pub fn new(
84        label: String,
85        flip_sign: bool,
86        roots: Vec<ReportNode>,
87    ) -> Result<Self, ReportError> {
88        let total = sum_amounts(
89            roots
90                .iter()
91                .filter(|r| r.depth == 0)
92                .flat_map(|r| r.amounts.iter()),
93        )?;
94        Ok(Self {
95            label,
96            flip_sign,
97            roots,
98            total,
99        })
100    }
101}
102
103impl ActivityPeriod {
104    /// # Errors
105    /// [`ReportError::AmountOverflow`] when the net does not fit.
106    pub fn new(
107        label: Option<String>,
108        groups: Vec<ActivityGroupResult>,
109    ) -> Result<Self, ReportError> {
110        let net = sum_amounts(groups.iter().flat_map(|g| g.total.iter()))?;
111        Ok(Self { label, groups, net })
112    }
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    pub fn displayed_net(&self) -> Result<Vec<CommodityAmount>, ReportError> {
120        negated(&self.net)
121    }
122}
123
124#[cfg(test)]
125#[path = "totals_tests.rs"]
126mod tests;