03dc2061f9
- 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
130 lines
5.5 KiB
Rust
130 lines
5.5 KiB
Rust
//! The month against your plan: for each category, what you meant to spend (`category.planned`), what you
|
|
//! spent, what is left, and whether you are ahead of the pace the plan allows by today. Only your own payments
|
|
//! count, as in the forecast; what other members of a shared budget spend is theirs.
|
|
|
|
use crate::spending::{between, outflows};
|
|
use fiscus_ledger::categories::{self, NOT_PLANNABLE};
|
|
use fiscus_ledger::date::days_in_month;
|
|
use fiscus_ledger::{Category, Date, Haler, State};
|
|
use serde::Serialize;
|
|
|
|
/// How a planned category is doing.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub enum Pace {
|
|
/// Below 90 % of what the plan allows by today (or, for a past month, within the plan).
|
|
Under,
|
|
OnPace,
|
|
/// Above 110 % of what the plan allows by today, not over the plan yet.
|
|
Ahead,
|
|
/// More than the whole month's plan.
|
|
Over,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
|
pub struct PlanRow {
|
|
pub category: Category,
|
|
pub planned: Option<Haler>,
|
|
pub spent: Haler,
|
|
/// Planned less spent; negative when over. `None` without a plan.
|
|
pub left: Option<Haler>,
|
|
/// Spent of the plan in thousandths, capped at 1000 (for a bar); 0 without a plan.
|
|
pub permille: u32,
|
|
/// `None` without a plan, and for a month that has not begun.
|
|
pub pace: Option<Pace>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
|
pub struct MonthPlan {
|
|
/// The 1st of the month.
|
|
pub month: Date,
|
|
/// The categories with a plan this month, in the app's order, then those spent on without a plan, the
|
|
/// largest first.
|
|
pub rows: Vec<PlanRow>,
|
|
/// All the plans of the month together.
|
|
pub planned: Haler,
|
|
/// Everything spent this month.
|
|
pub spent: Haler,
|
|
/// Of that, spent in categories without a plan.
|
|
pub unplanned: Haler,
|
|
}
|
|
|
|
fn pace(planned: Haler, spent: Haler, month: Date, today: Date) -> Option<Pace> {
|
|
if today < month {
|
|
return None;
|
|
}
|
|
if spent > planned {
|
|
return Some(Pace::Over);
|
|
}
|
|
if today > month.month_end() {
|
|
return Some(Pace::Under);
|
|
}
|
|
let (y, m, day) = today.ymd();
|
|
let allowed = i128::from(planned.0) * i128::from(day) / i128::from(days_in_month(y, m));
|
|
let spent = i128::from(spent.0) * 100;
|
|
Some(if spent > allowed * 110 {
|
|
Pace::Ahead
|
|
} else if spent < allowed * 90 {
|
|
Pace::Under
|
|
} else {
|
|
Pace::OnPace
|
|
})
|
|
}
|
|
|
|
/// The month of `month` against its plans. For this month, what is spent up to `today`; a later month has
|
|
/// nothing spent yet. `None` when a sum would not fit.
|
|
pub fn month_plan(state: &State, month: Date, today: Date) -> Option<MonthPlan> {
|
|
let start = month.month_start();
|
|
let end = start.month_end().min(today);
|
|
let spent_by = if end < start { Default::default() } else { outflows(&between(state, start, end))? };
|
|
let spent_in = |c: &str| spent_by.get(c).copied().unwrap_or(Haler::ZERO);
|
|
|
|
let mut rows = Vec::new();
|
|
for (category, _) in state.categories() {
|
|
let Some(planned) = state.plan_for(&category, start) else { continue };
|
|
let spent = spent_in(&category);
|
|
let permille = (i128::from(spent.0) * 1000 / i128::from(planned.0)).clamp(0, 1000) as u32;
|
|
rows.push(PlanRow { left: Some(planned.checked_sub(spent).ok()?), planned: Some(planned), permille, pace: pace(planned, spent, start, today), spent, category });
|
|
}
|
|
let mut extra: Vec<(&Category, &Haler)> = spent_by.iter().filter(|(c, _)| state.plan_for(c, start).is_none()).collect();
|
|
extra.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
|
|
let unplanned = Haler::sum(extra.iter().map(|(_, a)| **a)).ok()?;
|
|
rows.extend(extra.into_iter().map(|(c, a)| PlanRow { category: c.clone(), planned: None, spent: *a, left: None, permille: 0, pace: None }));
|
|
|
|
Some(MonthPlan {
|
|
month: start,
|
|
planned: Haler::sum(rows.iter().filter_map(|r| r.planned)).ok()?,
|
|
spent: Haler::sum(spent_by.values().copied()).ok()?,
|
|
unplanned,
|
|
rows,
|
|
})
|
|
}
|
|
|
|
/// A plan from your history: for each category you can plan, the average of what you spent on it over the last
|
|
/// three complete months, rounded **up** to whole hundreds of crowns. Only months since your first payment
|
|
/// count, so a ledger a month old is not divided by three. Categories you spent nothing on are left out.
|
|
pub fn suggest(state: &State, today: Date) -> Vec<(Category, Haler)> {
|
|
let this_month = today.month_start();
|
|
let Some(first) = state.effective_payments().first().map(|p| p.date.month_start()) else { return Vec::new() };
|
|
let months: Vec<Date> = (1..=3).map(|n| this_month.add_months(-n)).filter(|m| *m >= first).collect();
|
|
let Some(oldest) = months.last().copied() else { return Vec::new() };
|
|
let Some(spent) = outflows(&between(state, oldest, this_month.add_days(-1))) else { return Vec::new() };
|
|
let hundred = 10_000i128;
|
|
let mut out = Vec::new();
|
|
for (category, _) in state.categories() {
|
|
if NOT_PLANNABLE.contains(&category.as_str()) {
|
|
continue;
|
|
}
|
|
let Some(total) = spent.get(&category).filter(|t| t.0 > 0) else { continue };
|
|
// Both are positive: rounding up is (a + b - 1) / b.
|
|
let n = months.len() as i128;
|
|
let avg = (i128::from(total.0) + n - 1) / n;
|
|
let up = (avg + hundred - 1) / hundred * hundred;
|
|
match i64::try_from(up) {
|
|
Ok(v) if Haler(v) <= categories::MAX_PLAN => out.push((category, Haler(v))),
|
|
_ => out.push((category, categories::MAX_PLAN)),
|
|
}
|
|
}
|
|
out
|
|
}
|