Files
mnovak 03dc2061f9 [insight] Plans and statistics: category plans, categories of your own, one definition of spending, the month in numbers; v0.5.0
- category.planned (carries forward, zero removes it; spending categories only) and category.created
- fiscus-insight: spending (outflows, inflow, largest-remainder thousandths that add up to 1000), plan (the
  month against its plan with the pace, a suggested plan from the last three months), stats (pie slices, in,
  out, net, six months, same day last month, top merchants, subscriptions' share)
- docs/04_plans_stats.md; 11 new tests
2026-11-06 13:02:39 +01:00

82 lines
3.3 KiB
Rust

//! One definition of spending, for every screen: money out of your own payments, as positive amounts, by
//! category. Money between your own accounts (`transfers`) is not spending; a payment nobody categorised counts
//! as `uncategorised`. Every sum is checked: `None` when one would not fit, never a wrong number.
use fiscus_ledger::categories::{TRANSFERS, UNCATEGORISED};
use fiscus_ledger::{Category, Date, EffectivePayment, Haler, State};
use std::collections::BTreeMap;
/// The payments dated in `[from, to]`, a confirmed pair as one.
pub fn between(state: &State, from: Date, to: Date) -> Vec<EffectivePayment> {
state.effective_payments().into_iter().filter(|p| p.date >= from && p.date <= to).collect()
}
/// The category a payment counts under.
pub fn category_of(p: &EffectivePayment) -> &str {
p.category.as_deref().unwrap_or(UNCATEGORISED)
}
/// A payment that is spending: money out, not a transfer.
pub fn is_spending(p: &EffectivePayment) -> bool {
p.amount.0 < 0 && category_of(p) != TRANSFERS
}
/// Money out by category, positive.
pub fn outflows(payments: &[EffectivePayment]) -> Option<BTreeMap<Category, Haler>> {
let mut by: BTreeMap<Category, Haler> = BTreeMap::new();
for p in payments.iter().filter(|p| is_spending(p)) {
let slot = by.entry(category_of(p).to_string()).or_insert(Haler::ZERO);
*slot = slot.checked_add(p.amount.checked_neg().ok()?).ok()?;
}
Some(by)
}
/// Money in, not a transfer.
pub fn inflow(payments: &[EffectivePayment]) -> Option<Haler> {
Haler::sum(payments.iter().filter(|p| p.amount.0 > 0 && category_of(p) != TRANSFERS).map(|p| p.amount)).ok()
}
/// Each part's share of their sum in thousandths, by the largest remainder: the shares add up to exactly 1000
/// whenever the sum is above zero (all zeros otherwise). A tie goes to the earlier part, so callers order the
/// parts first. A negative part counts as zero.
pub fn permille(parts: &[Haler]) -> Vec<u32> {
let parts: Vec<i128> = parts.iter().map(|h| i128::from(h.0.max(0))).collect();
let total: i128 = parts.iter().sum();
if total <= 0 {
return vec![0; parts.len()];
}
let mut shares: Vec<u32> = parts.iter().map(|p| (p * 1000 / total) as u32).collect();
let mut left = 1000 - shares.iter().sum::<u32>();
let mut order: Vec<usize> = (0..parts.len()).collect();
// Largest remainder first; the earlier part on a tie (the sort is stable).
order.sort_by_key(|&i| std::cmp::Reverse(parts[i] * 1000 % total));
for i in order {
if left == 0 {
break;
}
shares[i] += 1;
left -= 1;
}
shares
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shares_always_add_up_to_a_thousand() {
let h = |v: &[i64]| v.iter().map(|&x| Haler(x)).collect::<Vec<_>>();
assert_eq!(permille(&h(&[1, 1, 1])), [334, 333, 333]);
assert_eq!(permille(&h(&[2, 1])), [667, 333]);
assert_eq!(permille(&h(&[0, 0])), [0, 0]);
assert_eq!(permille(&h(&[])), Vec::<u32>::new());
assert_eq!(permille(&h(&[i64::MAX, i64::MAX, 1])), [500, 500, 0]);
assert_eq!(permille(&h(&[5, -3])), [1000, 0]);
for n in 1..40i64 {
let parts: Vec<Haler> = (1..=n).map(|i| Haler(i * 7919 % 1013 + 1)).collect();
assert_eq!(permille(&parts).iter().sum::<u32>(), 1000, "{n} parts");
}
}
}