//! Medals and challenges, computed from the ledger and never stored. A medal is earned by a complete period //! (a month, a quarter, a challenge's last day); what is still running shows how far it is. use crate::goals::spent_in; use crate::plan::month_plan; use crate::spending::is_spending; use crate::subscriptions::{Insight, Status}; use fiscus_ledger::goal::{ChallengeGoal, ChallengeRecord}; use fiscus_ledger::{BudgetId, Date, Decision, Haler, State}; use serde::Serialize; use std::collections::{BTreeMap, BTreeSet}; /// A run of months this long earns the streak medals. pub const STREAK: u32 = 3; /// A goal's milestones, in thousandths of its target. pub const MILESTONES: [u32; 4] = [250, 500, 750, 1000]; #[derive(Clone, Debug, PartialEq, Eq, Serialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum Medal { /// A budget under its limit this many complete months running (3 or more), up to `until`'s month. UnderBudget { budget: BudgetId, name: String, months: u32, until: Date }, /// Every category plan of a month kept (a month with at least one plan). PlansKept { month: Date }, /// A subscription decided "cancel" and not charged since, past the day it would have charged. Cancelled { subscription: String, merchant: String, since: Date }, /// A challenge won. ChallengeWon { challenge: String, goal: ChallengeGoal }, /// Every invoice due in a quarter paid by its due date. InvoicesOnTime { year: i32, quarter: u32 }, /// A goal reached a quarter, a half, three quarters, or all of its target. GoalMilestone { goal: String, name: String, permille: u32 }, /// Money put aside in this many complete months running (3 or more), up to `until`'s month. SavingStreak { months: u32, until: Date }, /// A project done within its budget (it had one). ProjectOnBudget { project: String, name: String }, /// A project done by its end date (it had one). FinishedOnTime { project: String, name: String }, } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct Earned { pub medal: Medal, /// The day it was earned. pub on: Date, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum Outcome { Running, Won, Lost, Abandoned, } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct ChallengeStatus { pub id: String, pub goal: ChallengeGoal, pub starts: Date, pub ends: Date, pub outcome: Outcome, /// Spent in the category (spending challenges) or put aside (saving), so far. pub so_far: Haler, /// The tank: what is left of a spending limit, or what is saved of the amount, in thousandths (at most 1000). pub permille: u32, /// Days to the last day, 0 on it and after. pub days_left: i32, } /// How far the medals still to come are. #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct Progress { /// Complete months running with money put aside, up to last month. pub saving_months: u32, pub saved_this_month: bool, /// Each budget with a limit: complete months running under it, up to last month. pub budgets: Vec<(BudgetId, String, u32)>, /// Each open goal not yet full: its level and the next milestone. pub goals: Vec<(String, String, u32, u32)>, } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct Rewards { /// The latest first. pub medals: Vec, /// Running first (the soonest to end first), then the finished ones, the latest first. pub challenges: Vec, pub progress: Progress, } fn permille(part: i64, whole: i64) -> u32 { if whole <= 0 { return 0; } (i128::from(part.clamp(0, whole)) * 1000 / i128::from(whole)) as u32 } /// Runs of `true` months: (length, last month of the run). fn runs(months: &[(Date, bool)]) -> Vec<(u32, Date)> { let mut out = Vec::new(); let mut n = 0u32; for (i, (m, ok)) in months.iter().enumerate() { if *ok { n += 1; } let ends = !*ok || i + 1 == months.len(); if ends && n > 0 { let last = if *ok { *m } else { months[i - 1].0 }; out.push((n, last)); n = 0; } } out } /// The run that reaches the last month, if it does. fn current(months: &[(Date, bool)]) -> u32 { months.iter().rev().take_while(|(_, ok)| *ok).count() as u32 } /// The complete months from the first payment's month to last month. fn complete_months(state: &State, today: Date) -> Vec { let last = today.month_start().add_months(-1); let Some(first) = state.effective_payments().iter().map(|p| p.date.month_start()).min() else { return Vec::new() }; let mut out = Vec::new(); let mut m = first; while m <= last && out.len() < 1200 { out.push(m); m = m.add_months(1); } out } fn challenge(state: &State, insight: &Insight, c: &ChallengeRecord, today: Date) -> ChallengeStatus { let to = today.min(c.ends); let over = today > c.ends; let (so_far, level, outcome) = match &c.goal { ChallengeGoal::SpendUnder { category, amount } => { let spent = if today < c.starts { Haler::ZERO } else { spent_in(state, category, c.starts, to) }; let outcome = if spent > *amount { Outcome::Lost } else if over { Outcome::Won } else { Outcome::Running }; (spent, permille(amount.0.saturating_sub(spent.0), amount.0), outcome) } ChallengeGoal::NoSpend { category } => { let spent = if today < c.starts { Haler::ZERO } else { spent_in(state, category, c.starts, to) }; let outcome = if spent.0 > 0 { Outcome::Lost } else if over { Outcome::Won } else { Outcome::Running }; (spent, if spent.0 > 0 { 0 } else { 1000 }, outcome) } ChallengeGoal::Cancel { subscription } => { let decided = state .decisions .get(subscription) .and_then(|ds| ds.iter().rev().find(|d| d.on >= c.starts && d.on <= c.ends)) .filter(|d| d.decision == Decision::Cancel); let charged_after = decided.is_some_and(|d| { insight .subscriptions .iter() .filter(|s| &s.key == subscription) .flat_map(|s| s.charges.iter()) .any(|ch| ch.date > d.on && ch.date <= to) }); let outcome = match (decided.is_some(), charged_after, over) { (_, true, _) => Outcome::Lost, (true, false, true) => Outcome::Won, (false, _, true) => Outcome::Lost, _ => Outcome::Running, }; (Haler::ZERO, if decided.is_some() && !charged_after { 1000 } else { 0 }, outcome) } ChallengeGoal::Save { goal, amount } => { let saved = state.goals.get(goal).map(|g| g.savings.iter().filter(|s| s.on >= c.starts && s.on <= to).fold(0i64, |sum, s| sum.saturating_add(s.amount.0))).unwrap_or(0); let outcome = if saved >= amount.0 { Outcome::Won } else if over { Outcome::Lost } else { Outcome::Running }; (Haler(saved), permille(saved, amount.0), outcome) } }; let outcome = match (c.abandoned, outcome) { (Some(_), Outcome::Running | Outcome::Lost) => Outcome::Abandoned, (Some(on), Outcome::Won) if on <= c.ends && !won_before(state, c, on) => Outcome::Abandoned, (_, o) => o, }; ChallengeStatus { id: c.id.clone(), goal: c.goal.clone(), starts: c.starts, ends: c.ends, outcome, so_far, permille: level, days_left: today.days_until(c.ends).max(0) } } /// A saving challenge reached before it was given up stays won. fn won_before(state: &State, c: &ChallengeRecord, on: Date) -> bool { match &c.goal { ChallengeGoal::Save { goal, amount } => { state.goals.get(goal).map(|g| g.savings.iter().filter(|s| s.on >= c.starts && s.on <= on).fold(0i64, |sum, s| sum.saturating_add(s.amount.0))).unwrap_or(0) >= amount.0 } _ => false, } } /// When a challenge was won: a saving challenge on the day it was reached, the others on their last day. fn won_on(state: &State, c: &ChallengeRecord) -> Date { if let ChallengeGoal::Save { goal, amount } = &c.goal { if let Some(g) = state.goals.get(goal) { let mut sum = 0i64; let mut savings: Vec<_> = g.savings.iter().filter(|s| s.on >= c.starts && s.on <= c.ends).collect(); savings.sort_by_key(|s| (s.on, s.seq)); for s in savings { sum = sum.saturating_add(s.amount.0); if sum >= amount.0 { return s.on; } } } } c.ends } /// `shared`: the shared budgets in this log, which earn no budget medal (only your own payments are counted /// here, the limit is everyone's). pub fn rewards(state: &State, insight: &Insight, shared: &BTreeSet, today: Date) -> Rewards { let mut medals: Vec = Vec::new(); let months = complete_months(state, today); // Budgets under their limit (the latest limit), month by month. let mut budgets = Vec::new(); let payments = state.effective_payments(); for b in state.budgets.values().filter(|b| b.limit.0 > 0 && !shared.contains(&b.id)) { let flags: Vec<(Date, bool)> = months .iter() .map(|m| { let spent = payments .iter() .filter(|p| p.budget.as_deref() == Some(b.id.as_str()) && p.date >= *m && p.date <= m.month_end() && is_spending(p)) .fold(0i64, |s, p| s.saturating_add(p.amount.0.saturating_neg())); (*m, spent <= b.limit.0) }) .collect(); for (n, last) in runs(&flags).into_iter().filter(|(n, _)| *n >= STREAK) { medals.push(Earned { medal: Medal::UnderBudget { budget: b.id.clone(), name: b.name.clone(), months: n, until: last }, on: last.month_end() }); } budgets.push((b.id.clone(), b.name.clone(), current(&flags))); } // Months with every plan kept. for m in &months { if let Some(p) = month_plan(state, *m, today) { let planned: Vec<_> = p.rows.iter().filter(|r| r.planned.is_some_and(|x| x.0 > 0)).collect(); if !planned.is_empty() && planned.iter().all(|r| r.left.is_some_and(|l| l.0 >= 0)) { medals.push(Earned { medal: Medal::PlansKept { month: *m }, on: m.month_end() }); } } } // Cancelled and not charged since, past the day it would have charged. for s in insight.subscriptions.iter().filter(|s| s.status == Status::Cancelled && s.next_charge < today) { if let Some(d) = s.decision.as_ref().filter(|d| d.decision == Decision::Cancel) { medals.push(Earned { medal: Medal::Cancelled { subscription: s.key.clone(), merchant: s.merchant.clone(), since: d.on }, on: s.next_charge }); } } // Challenges. let mut challenges: Vec = Vec::new(); for c in state.challenges.values() { let st = challenge(state, insight, c, today); if st.outcome == Outcome::Won { medals.push(Earned { medal: Medal::ChallengeWon { challenge: c.id.clone(), goal: c.goal.clone() }, on: won_on(state, c) }); } challenges.push(st); } challenges.sort_by(|a, b| { let running = |x: &ChallengeStatus| x.outcome == Outcome::Running; running(b).cmp(&running(a)).then_with(|| if running(a) { a.ends.cmp(&b.ends) } else { b.ends.cmp(&a.ends) }).then_with(|| a.id.cmp(&b.id)) }); // Quarters with every invoice due in them paid by its due date. let mut quarters: BTreeMap<(i32, u32), bool> = BTreeMap::new(); for r in state.invoices.values().filter(|r| !r.cancelled) { let (y, m, _) = r.invoice.due.ymd(); let ok = r.paid.as_ref().is_some_and(|p| p.on <= r.invoice.due); let slot = quarters.entry((y, (m - 1) / 3 + 1)).or_insert(true); *slot &= ok; } for ((y, q), ok) in quarters { let end = Date::from_ymd(y, q * 3, 1).map(Date::month_end); if let Some(end) = end.filter(|e| ok && *e < today) { medals.push(Earned { medal: Medal::InvoicesOnTime { year: y, quarter: q }, on: end }); } } // Goals: their milestones, the first day each was reached. let mut goals_progress = Vec::new(); for g in state.goals.values() { let mut savings: Vec<_> = g.savings.iter().collect(); savings.sort_by_key(|s| s.seq); let mut sum = 0i64; let mut reached = 0usize; for s in savings { sum = sum.saturating_add(s.amount.0); let level = permille(sum, g.target.0); while reached < MILESTONES.len() && level >= MILESTONES[reached] { medals.push(Earned { medal: Medal::GoalMilestone { goal: g.id.clone(), name: g.name.clone(), permille: MILESTONES[reached] }, on: s.on }); reached += 1; } } let level = permille(g.saved().0, g.target.0); if g.is_open() && level < 1000 { let next = MILESTONES.iter().copied().find(|m| *m > level).unwrap_or(1000); goals_progress.push((g.id.clone(), g.name.clone(), level, next)); } } // Months running with money put aside (more in than out across the goals). let saved_in = |from: Date, to: Date| { state.goals.values().flat_map(|g| g.savings.iter()).filter(|s| s.on >= from && s.on <= to).fold(0i64, |sum, s| sum.saturating_add(s.amount.0)) }; let first_saving = state.goals.values().flat_map(|g| g.savings.iter()).map(|s| s.on.month_start()).min(); let saving_flags: Vec<(Date, bool)> = match first_saving { Some(first) => months.iter().filter(|m| **m >= first).map(|m| (*m, saved_in(*m, m.month_end()) > 0)).collect(), None => Vec::new(), }; for (n, last) in runs(&saving_flags).into_iter().filter(|(n, _)| *n >= STREAK) { medals.push(Earned { medal: Medal::SavingStreak { months: n, until: last }, on: last.month_end() }); } // Projects done: within their budget, by their end date. let summaries = crate::projects::projects(state, today); for p in state.projects.projects.values().filter(|p| !p.is_open()) { let Some(on) = p.status_on else { continue }; if let Some(s) = summaries.iter().find(|s| s.id == p.id) { if s.planned.0 > 0 && s.spent <= s.planned { medals.push(Earned { medal: Medal::ProjectOnBudget { project: p.id.clone(), name: p.name.clone() }, on }); } } if p.ends.is_some_and(|e| on <= e) { medals.push(Earned { medal: Medal::FinishedOnTime { project: p.id.clone(), name: p.name.clone() }, on }); } } medals.sort_by_key(|m| std::cmp::Reverse(m.on)); let month = today.month_start(); Rewards { medals, challenges, progress: Progress { saving_months: current(&saving_flags), saved_this_month: saved_in(month, today) > 0, budgets, goals: goals_progress, }, } }