Lines
99.56 %
Functions
97.3 %
Branches
100 %
//! View projections shared across report consumers.
//!
//! Flattens `ReportData` / `ActivityData` / `BreakdownData` server
//! responses into small row-oriented structs. Report table handlers, the
//! chart adapters in the `plotting` crate, and the CLI all consume these
//! instead of re-walking the tree.
use std::borrow::Cow;
use finance::error::ReportError;
use num_rational::Rational64;
use sqlx::types::Uuid;
use super::super::{ActivityData, BreakdownData, ReportData, ReportNode, UNCATEGORIZED_KEY};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AmountView {
pub commodity_symbol: String,
pub amount: Rational64,
}
pub struct ReportRowView {
pub account_id: Uuid,
pub parent_id: Option<Uuid>,
pub account_name: String,
pub depth: usize,
pub has_children: bool,
pub amounts: Vec<AmountView>,
/// The account's own splits, one entry per commodity (symbols may repeat).
pub own: Vec<AmountView>,
pub struct GroupView {
pub label: String,
pub flip_sign: bool,
pub rows: Vec<ReportRowView>,
pub total: Vec<AmountView>,
pub struct PeriodActivityView {
pub groups: Vec<GroupView>,
pub net: Vec<AmountView>,
pub struct BreakdownRowView {
pub tag_value: String,
pub is_uncategorized: bool,
pub struct BreakdownPeriodView {
pub rows: Vec<BreakdownRowView>,
fn amount_views(amounts: &[super::super::CommodityAmount]) -> Vec<AmountView> {
amounts
.iter()
.map(|a| AmountView {
commodity_symbol: a.commodity_symbol.clone(),
amount: a.amount,
})
.collect()
fn flatten_nodes(nodes: &[ReportNode], parent: Option<Uuid>, out: &mut Vec<ReportRowView>) {
for node in nodes {
out.push(ReportRowView {
account_id: node.account_id,
parent_id: parent,
account_name: node.account_name.clone(),
depth: node.depth,
has_children: !node.children.is_empty(),
amounts: amount_views(&node.amounts),
own: amount_views(&node.own_amounts),
});
flatten_nodes(&node.children, Some(node.account_id), out);
/// Flatten a point-in-time or period-activity `ReportData` into a single row
/// list. The outer `PeriodData` wrapper collapses because Balance always
/// returns exactly one period.
#[must_use]
pub fn flatten_report_data(data: &ReportData) -> Vec<ReportRowView> {
let mut rows = Vec::new();
for period in &data.periods {
flatten_nodes(&period.roots, None, &mut rows);
rows
/// Flatten an `ActivityData` into per-period / per-group row lists with
/// totals. `flip_sign` is applied to amounts and to the per-period net,
/// following the convention documented in `doc/reporting.org`:
/// `Net = sum(group_total * (flip_sign ? +1 : -1))`.
///
/// # Errors
/// [`ReportError::AmountOverflow`] when an amount cannot be negated.
pub fn flatten_activity_data(data: &ActivityData) -> Result<Vec<PeriodActivityView>, ReportError> {
data.periods
.map(|period| {
let groups: Vec<GroupView> = period
.groups
.map(|g| {
let g = g.displayed()?;
flatten_nodes(&g.roots, None, &mut rows);
Ok(GroupView {
label: g.label,
flip_sign: g.flip_sign,
rows,
total: amount_views(&g.total),
.collect::<Result<_, ReportError>>()?;
Ok(PeriodActivityView {
label: period.label.clone().unwrap_or_default(),
groups,
net: amount_views(&period.displayed_net()?),
/// Flatten a `BreakdownData` into per-period row lists. The uncategorized
/// sentinel bucket is translated into `is_uncategorized = true` so consumers
/// can render it differently without knowing the sentinel value.
pub fn flatten_breakdown_data(data: &BreakdownData) -> Vec<BreakdownPeriodView> {
.map(|p| BreakdownPeriodView {
label: p.label.clone().unwrap_or_default(),
rows: p
.rows
.map(|r| BreakdownRowView {
tag_value: r.tag_value.clone(),
is_uncategorized: r.is_uncategorized || r.tag_value == UNCATEGORIZED_KEY,
amounts: amount_views(&r.amounts),
.collect(),
/// Excel reads a BOM-less CSV in the system code page, mangling non-ASCII names.
const BOM: &str = "\u{feff}";
const UNCATEGORIZED: &str = "(uncategorized)";
/// The category report as CSV, as the web's export serves it.
pub fn category_csv(data: &BreakdownData) -> String {
breakdown_csv(&data.tag_name, &flatten_breakdown_data(data))
/// One record per category and commodity, in table order; a `Period`
/// column leads only when the report is grouped.
fn breakdown_csv(tag_name: &str, periods: &[BreakdownPeriodView]) -> String {
let grouped = periods.iter().any(|period| !period.label.is_empty());
let mut out = String::from(BOM);
let period_header = grouped.then_some("Period");
push_record(
&mut out,
period_header
.into_iter()
.chain([tag_name, "Commodity", "Amount"]),
);
for period in periods {
let label = grouped.then_some(period.label.as_str());
for row in &period.rows {
let category = match row.is_uncategorized {
true => UNCATEGORIZED,
false => row.tag_value.as_str(),
};
for amount in &row.amounts {
let value = decimal(amount.amount);
label.into_iter().chain([
category,
amount.commodity_symbol.as_str(),
value.as_str(),
]),
out
fn push_record<'a>(out: &mut String, fields: impl IntoIterator<Item = &'a str>) {
let line = fields.into_iter().map(csv_field).collect::<Vec<_>>();
out.push_str(&line.join(","));
out.push_str("\r\n");
/// RFC 4180 quoting.
fn csv_field(field: &str) -> Cow<'_, str> {
match field.contains([',', '"', '\n', '\r']) {
true => Cow::Owned(format!("\"{}\"", field.replace('"', "\"\""))),
false => Cow::Borrowed(field),
/// `value` rounded half away from zero to at most two fraction digits, as the
/// table's `formatRational` shows it, without grouping separators.
fn decimal(value: Rational64) -> String {
let (numer, denom) = (i128::from(*value.numer()), i128::from(*value.denom()));
let cents = (numer.abs() * 200 + denom) / (denom * 2);
let sign = if numer < 0 && cents > 0 { "-" } else { "" };
let (units, fraction) = (cents / 100, cents % 100);
match fraction {
0 => format!("{sign}{units}"),
f if f % 10 == 0 => format!("{sign}{units}.{}", f / 10),
f => format!("{sign}{units}.{f:02}"),
#[cfg(test)]
#[path = "view_csv_tests.rs"]
mod csv_tests;
mod tests {
use super::super::super::{
ActivityGroupResult, ActivityPeriod, BreakdownPeriod, BreakdownRow, CommodityAmount,
PeriodData, ReportMeta,
use super::*;
fn commodity(symbol: &str, num: i64) -> CommodityAmount {
CommodityAmount {
commodity_id: Uuid::from_u128(u128::from(symbol.as_bytes()[0])),
commodity_symbol: symbol.to_string(),
amount: Rational64::new(num, 1),
fn node(
name: &str,
depth: usize,
amounts: Vec<CommodityAmount>,
children: Vec<ReportNode>,
) -> ReportNode {
ReportNode {
account_id: Uuid::new_v4(),
account_name: name.to_string(),
account_path: name.to_string(),
depth,
account_type: None,
own_amounts: amounts.clone(),
amounts,
children,
#[test]
fn flatten_report_data_preserves_parent_links() {
let child = node("Checking", 1, vec![commodity("USD", 100)], vec![]);
let child_id = child.account_id;
let parent = node("Assets", 0, vec![commodity("USD", 100)], vec![child]);
let parent_id = parent.account_id;
let data = ReportData {
meta: ReportMeta {
date_from: None,
date_to: None,
target_commodity_id: None,
},
periods: vec![PeriodData {
label: None,
roots: vec![parent],
}],
let rows = flatten_report_data(&data);
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].account_id, parent_id);
assert!(rows[0].parent_id.is_none());
assert!(rows[0].has_children);
assert_eq!(rows[1].account_id, child_id);
assert_eq!(rows[1].parent_id, Some(parent_id));
assert!(!rows[1].has_children);
fn flatten_activity_data_flips_income_sign_and_nets() {
let income = ActivityGroupResult::new(
"Income".to_string(),
true,
vec![node("Salary", 0, vec![commodity("USD", -500)], vec![])],
)
.expect("income total");
let expense = ActivityGroupResult::new(
"Expense".to_string(),
false,
vec![node("Rent", 0, vec![commodity("USD", 200)], vec![])],
.expect("expense total");
let data = ActivityData {
periods: vec![
ActivityPeriod::new(Some("2026-04".to_string()), vec![income, expense])
.expect("net"),
],
let periods = flatten_activity_data(&data).expect("displayed");
assert_eq!(periods.len(), 1);
let p = &periods[0];
assert_eq!(p.label, "2026-04");
assert_eq!(
p.groups[0].rows[0].amounts[0].amount,
Rational64::new(500, 1)
assert_eq!(p.groups[0].total[0].amount, Rational64::new(500, 1));
assert_eq!(p.groups[1].total[0].amount, Rational64::new(200, 1));
// Net: income flipped (+500) minus expense (200) = 300.
assert_eq!(p.net.len(), 1);
assert_eq!(p.net[0].commodity_symbol, "USD");
assert_eq!(p.net[0].amount, Rational64::new(300, 1));
fn flatten_breakdown_data_marks_sentinel_uncategorized() {
let data = BreakdownData {
tag_name: "category".to_string(),
periods: vec![BreakdownPeriod {
rows: vec![
BreakdownRow {
tag_value: "food".to_string(),
is_uncategorized: false,
amounts: vec![commodity("USD", 50)],
tag_value: UNCATEGORIZED_KEY.to_string(),
is_uncategorized: true,
amounts: vec![commodity("USD", 10)],
let periods = flatten_breakdown_data(&data);
assert_eq!(periods[0].rows.len(), 2);
assert!(!periods[0].rows[0].is_uncategorized);
assert!(periods[0].rows[1].is_uncategorized);