Lines
100 %
Functions
Branches
use std::collections::HashMap;
use finance::error::ReportError;
use num_rational::Rational64;
use num_traits::CheckedSub;
use sqlx::types::Uuid;
use super::super::{ActivityGroupResult, ActivityPeriod, CommodityAmount, ReportNode};
use super::tree::checked_sum;
fn sum_amounts<'a>(
amounts: impl Iterator<Item = &'a CommodityAmount>,
) -> Result<Vec<CommodityAmount>, ReportError> {
let mut out: Vec<CommodityAmount> = Vec::new();
let mut index: HashMap<Uuid, usize> = HashMap::new();
for a in amounts {
match index.get(&a.commodity_id) {
Some(&at) => out[at].amount = checked_sum(out[at].amount, a.amount)?,
None => {
index.insert(a.commodity_id, out.len());
out.push(a.clone());
}
Ok(out)
fn negate(amount: Rational64) -> Result<Rational64, ReportError> {
Rational64::ZERO
.checked_sub(&amount)
.ok_or(ReportError::AmountOverflow)
fn negated(amounts: &[CommodityAmount]) -> Result<Vec<CommodityAmount>, ReportError> {
amounts
.iter()
.map(|a| {
Ok(CommodityAmount {
amount: negate(a.amount)?,
..a.clone()
})
.collect()
impl ReportNode {
fn negated(&self) -> Result<Self, ReportError> {
Ok(Self {
amounts: negated(&self.amounts)?,
own_amounts: negated(&self.own_amounts)?,
children: self
.children
.map(Self::negated)
.collect::<Result<_, _>>()?,
..self.clone()
impl ActivityGroupResult {
/// The group as clients show it: `flip_sign` applied to the rows and the total.
///
/// # Errors
/// [`ReportError::AmountOverflow`] when an amount cannot be negated.
pub fn displayed(&self) -> Result<Self, ReportError> {
if !self.flip_sign {
return Ok(self.clone());
roots: self
.roots
.map(ReportNode::negated)
total: negated(&self.total)?,
/// [`ReportError::AmountOverflow`] when a total does not fit.
pub fn new(
label: String,
flip_sign: bool,
roots: Vec<ReportNode>,
) -> Result<Self, ReportError> {
let total = sum_amounts(
roots
.filter(|r| r.depth == 0)
.flat_map(|r| r.amounts.iter()),
)?;
label,
flip_sign,
roots,
total,
impl ActivityPeriod {
/// [`ReportError::AmountOverflow`] when the net does not fit.
label: Option<String>,
groups: Vec<ActivityGroupResult>,
let net = sum_amounts(groups.iter().flat_map(|g| g.total.iter()))?;
Ok(Self { label, groups, net })
/// The net as clients show it: `sum(displayed_total * (flip_sign ? +1 : -1))`,
/// which is the negated raw sum.
pub fn displayed_net(&self) -> Result<Vec<CommodityAmount>, ReportError> {
negated(&self.net)
#[cfg(test)]
#[path = "totals_tests.rs"]
mod tests;