[insight] Goals and rewards: a goal this month (its tank, what is needed, the pace, the split between its ways, where money could come from), medals and challenges from complete periods, the cancel letter in Czech
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
//! The cancel kit: where to cancel a known provider, and a polite email to send when there is no page.
|
||||
|
||||
use crate::subscriptions::Subscription;
|
||||
use fiscus_ledger::invoice::Language;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// `(a word in the merchant key, provider, the page where its subscription is cancelled)`.
|
||||
@@ -46,24 +47,52 @@ fn percent(s: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// The kit with its email in English.
|
||||
pub fn cancel_kit(sub: &Subscription) -> CancelKit {
|
||||
cancel_kit_in(sub, Language::En)
|
||||
}
|
||||
|
||||
/// The kit with its email in Czech or English (the app's language: most Czech providers read Czech).
|
||||
pub fn cancel_kit_in(sub: &Subscription, language: Language) -> CancelKit {
|
||||
let words: Vec<&str> = sub.merchant_key.split(' ').collect();
|
||||
let known = PROVIDERS.iter().find(|(w, _, _)| words.contains(w));
|
||||
let name = known.map(|(_, p, _)| p.to_string()).unwrap_or_else(|| sub.merchant.clone());
|
||||
let cadence = match sub.cadence {
|
||||
crate::subscriptions::Cadence::Monthly => "monthly",
|
||||
crate::subscriptions::Cadence::Yearly => "yearly",
|
||||
};
|
||||
let last = sub.charges.last().map(|c| c.date.to_string()).unwrap_or_default();
|
||||
CancelKit {
|
||||
provider: known.map(|(_, p, _)| p.to_string()),
|
||||
url: known.map(|(_, _, u)| u.to_string()),
|
||||
email_subject: format!("Cancel my {name} subscription"),
|
||||
email_body: format!(
|
||||
"Hello,\n\nplease cancel my {name} subscription ({cadence}, {} CZK, last charged on {last}) \
|
||||
with effect from the end of the current period, and confirm the cancellation by email.\n\n\
|
||||
Please do not charge my card again.\n\nThank you.",
|
||||
sub.cost.to_czk()
|
||||
let monthly = sub.cadence == crate::subscriptions::Cadence::Monthly;
|
||||
let last = sub.charges.last().map(|c| c.date);
|
||||
let cost = sub.cost.to_czk();
|
||||
let (email_subject, email_body) = match language {
|
||||
Language::En => (
|
||||
format!("Cancel my {name} subscription"),
|
||||
format!(
|
||||
"Hello,
|
||||
|
||||
please cancel my {name} subscription ({}, {cost} CZK, last charged on {}) with effect from the end of the current period, and confirm the cancellation by email.
|
||||
|
||||
Please do not charge my card again.
|
||||
|
||||
Thank you.",
|
||||
if monthly { "monthly" } else { "yearly" },
|
||||
last.map(|d| d.to_string()).unwrap_or_default(),
|
||||
),
|
||||
),
|
||||
}
|
||||
Language::Cs => (
|
||||
format!("Zrušení předplatného {name}"),
|
||||
format!(
|
||||
"Dobrý den,
|
||||
|
||||
prosím o zrušení mého předplatného {name} ({}, {cost} Kč, naposledy strženo {}) ke konci aktuálního období a o potvrzení zrušení e-mailem.
|
||||
|
||||
Prosím, dále mi nestrhávejte platby z karty.
|
||||
|
||||
Děkuji.",
|
||||
if monthly { "měsíční" } else { "roční" },
|
||||
last.map(|d| {
|
||||
let (y, m, day) = d.ymd();
|
||||
format!("{day}. {m}. {y}")
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
),
|
||||
),
|
||||
};
|
||||
CancelKit { provider: known.map(|(_, p, _)| p.to_string()), url: known.map(|(_, _, u)| u.to_string()), email_subject, email_body }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
//! Savings goals this month: how full each one is, what is still needed each month to make its date, the month
|
||||
//! you get there at your pace, this month's saving split between the goal's ways, and where the money could come
|
||||
//! from. Fiscus never moves money; these are suggestions, and a goal fills only with what you say you put aside.
|
||||
|
||||
use crate::plan::month_plan;
|
||||
use crate::spending::{between, category_of, inflow, is_spending, outflows};
|
||||
use crate::subscriptions::{Cadence, Insight, Status};
|
||||
use fiscus_ledger::categories::NOT_PLANNABLE;
|
||||
use fiscus_ledger::goal::{Colour, GoalRecord, Way, WayKind};
|
||||
use fiscus_ledger::{Category, Date, Decision, Haler, State};
|
||||
use serde::Serialize;
|
||||
|
||||
/// One way's part of this month's saving.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct WayPart {
|
||||
pub way: Way,
|
||||
/// What the way comes to this month (before what you already put aside by it).
|
||||
pub amount: Haler,
|
||||
/// Put aside by this way this month.
|
||||
pub saved: Haler,
|
||||
/// Still to put aside by it this month: `amount - saved`, never more than the goal still needs.
|
||||
pub left: Haler,
|
||||
/// Round-ups: the card payments rounded up. Leftover / income: the whole amount the share is of.
|
||||
pub basis: Haler,
|
||||
pub payments: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct GoalStatus {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub colour: Colour,
|
||||
pub target: Haler,
|
||||
pub saved: Haler,
|
||||
/// Saved of the target in thousandths, at most 1000: the tank's level.
|
||||
pub permille: u32,
|
||||
pub reached: bool,
|
||||
pub closed: Option<Date>,
|
||||
pub by: Option<Date>,
|
||||
/// Months from this one to the month of `by`, both included; 0 once it has passed.
|
||||
pub months_left: Option<u32>,
|
||||
/// What is still needed each month to make `by`, rounded up to whole crowns.
|
||||
pub needed_per_month: Option<Haler>,
|
||||
/// Put aside per month on average over the last three complete months the goal had savings in reach of.
|
||||
pub pace: Haler,
|
||||
/// The month you get there at that pace; `None` without a pace (or when reached).
|
||||
pub reach_month: Option<Date>,
|
||||
pub parts: Vec<WayPart>,
|
||||
/// All the parts still to put aside this month.
|
||||
pub left_this_month: Haler,
|
||||
pub saved_this_month: Haler,
|
||||
}
|
||||
|
||||
/// Where the money could come from: it only points, it changes nothing.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Source {
|
||||
/// A subscription still charging that you have not decided to keep: what it costs a month.
|
||||
Subscription { key: String, merchant: String, monthly: Haler },
|
||||
/// A category that cost more last month than its average of the three months before.
|
||||
Category { category: Category, last: Haler, average: Haler, extra: Haler },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct GoalsMonth {
|
||||
/// The 1st of this month.
|
||||
pub month: Date,
|
||||
/// Open goals in the order made, then the closed ones, the latest closed first.
|
||||
pub goals: Vec<GoalStatus>,
|
||||
/// What last month's plans did not use (what "leftover" shares are of).
|
||||
pub leftover: Haler,
|
||||
/// Last month's money in (what "income" shares are of).
|
||||
pub income: Haler,
|
||||
/// Leftover and income already given to goals, in thousandths.
|
||||
pub leftover_given: u32,
|
||||
pub income_given: u32,
|
||||
/// Everything in open goals.
|
||||
pub saved: Haler,
|
||||
pub sources: Vec<Source>,
|
||||
}
|
||||
|
||||
/// `a / b` rounded up, both positive.
|
||||
fn div_up(a: i64, b: i64) -> i64 {
|
||||
(a + b - 1) / b
|
||||
}
|
||||
|
||||
fn share(of: Haler, permille: u32) -> Haler {
|
||||
Haler((i128::from(of.0.max(0)) * i128::from(permille) / 1000) as i64)
|
||||
}
|
||||
|
||||
fn months_between(from: Date, to: Date) -> i64 {
|
||||
let (fy, fm, _) = from.ymd();
|
||||
let (ty, tm, _) = to.ymd();
|
||||
i64::from(ty - fy) * 12 + i64::from(tm) - i64::from(fm)
|
||||
}
|
||||
|
||||
/// Round-ups this month: each spending payment rounded up to the next `to`; a payment already a multiple adds 0.
|
||||
pub fn round_ups(state: &State, to: Haler, today: Date) -> (Haler, usize) {
|
||||
if to.0 <= 0 {
|
||||
return (Haler::ZERO, 0);
|
||||
}
|
||||
let mut sum = 0i64;
|
||||
let mut n = 0;
|
||||
for p in between(state, today.month_start(), today).iter().filter(|p| is_spending(p)) {
|
||||
let paid = p.amount.0.saturating_neg();
|
||||
let r = paid % to.0;
|
||||
if r != 0 {
|
||||
sum = sum.saturating_add(to.0 - r);
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
(Haler(sum), n)
|
||||
}
|
||||
|
||||
/// What last month's plans did not use: for each planned category, the plan less what was spent, never below 0.
|
||||
pub fn leftover(state: &State, today: Date) -> Haler {
|
||||
let last = today.month_start().add_months(-1);
|
||||
let Some(p) = month_plan(state, last, today) else { return Haler::ZERO };
|
||||
Haler(p.rows.iter().filter_map(|r| r.left).fold(0i64, |s, l| s.saturating_add(l.0.max(0))))
|
||||
}
|
||||
|
||||
/// Last month's money in, not counting transfers.
|
||||
pub fn last_income(state: &State, today: Date) -> Haler {
|
||||
let last = today.month_start().add_months(-1);
|
||||
inflow(&between(state, last, last.month_end())).unwrap_or(Haler::ZERO)
|
||||
}
|
||||
|
||||
fn saved_in(g: &GoalRecord, from: Date, to: Date, way: Option<WayKind>) -> Haler {
|
||||
Haler(
|
||||
g.savings
|
||||
.iter()
|
||||
.filter(|s| s.on >= from && s.on <= to && (way.is_none() || s.way == way))
|
||||
.fold(0i64, |sum, s| sum.saturating_add(s.amount.0)),
|
||||
)
|
||||
}
|
||||
|
||||
fn status(g: &GoalRecord, today: Date, leftover: Haler, income: Haler, rounds: &mut dyn FnMut(Haler) -> (Haler, usize)) -> GoalStatus {
|
||||
let month = today.month_start();
|
||||
let saved = g.saved();
|
||||
let remaining = Haler(g.target.0.saturating_sub(saved.0).max(0));
|
||||
let reached = remaining.0 == 0;
|
||||
let permille = if g.target.0 > 0 { (i128::from(saved.0.max(0)) * 1000 / i128::from(g.target.0)).min(1000) as u32 } else { 0 };
|
||||
|
||||
let months_left = g.by.map(|by| (months_between(month, by.month_start()) + 1).max(0) as u32);
|
||||
let needed_per_month = match (months_left, reached) {
|
||||
(_, true) | (None, _) => None,
|
||||
(Some(0), false) => Some(remaining),
|
||||
(Some(n), false) => Some(Haler(div_up(div_up(remaining.0, i64::from(n)), 100) * 100)),
|
||||
};
|
||||
|
||||
// The pace: the last three complete months, from the month of the first saving on.
|
||||
let first = g.savings.iter().map(|s| s.on.month_start()).min();
|
||||
let pace = match first {
|
||||
Some(first) if first < month => {
|
||||
let from = month.add_months(-3).max(first);
|
||||
let n = months_between(from, month).max(1);
|
||||
Haler(saved_in(g, from, month.add_days(-1), None).0 / n)
|
||||
}
|
||||
_ => Haler::ZERO,
|
||||
};
|
||||
let reach_month = (!reached && pace.0 > 0 && g.is_open()).then(|| {
|
||||
let n = div_up(remaining.0, pace.0).min(1200) as i32;
|
||||
month.add_months(n)
|
||||
});
|
||||
|
||||
let mut budget = remaining.0;
|
||||
let parts: Vec<WayPart> = if g.is_open() {
|
||||
g.ways
|
||||
.iter()
|
||||
.map(|w| {
|
||||
let (amount, basis, payments) = match *w {
|
||||
Way::Fixed { amount } => (amount, amount, 0),
|
||||
Way::RoundUp { to } => {
|
||||
let (sum, n) = rounds(to);
|
||||
(sum, sum, n)
|
||||
}
|
||||
Way::Leftover { permille } => (share(leftover, u32::from(permille)), leftover, 0),
|
||||
Way::Income { permille } => (share(income, u32::from(permille)), income, 0),
|
||||
};
|
||||
let saved = saved_in(g, month, month.month_end(), Some(w.kind()));
|
||||
let left = amount.0.saturating_sub(saved.0).clamp(0, budget.max(0));
|
||||
budget -= left;
|
||||
WayPart { way: *w, amount, saved, left: Haler(left), basis, payments }
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let left_this_month = Haler(parts.iter().map(|p| p.left.0).sum());
|
||||
|
||||
GoalStatus {
|
||||
id: g.id.clone(),
|
||||
name: g.name.clone(),
|
||||
colour: g.colour,
|
||||
target: g.target,
|
||||
saved,
|
||||
permille,
|
||||
reached,
|
||||
closed: g.closed,
|
||||
by: g.by,
|
||||
months_left,
|
||||
needed_per_month,
|
||||
pace,
|
||||
reach_month,
|
||||
parts,
|
||||
left_this_month,
|
||||
saved_this_month: saved_in(g, month, month.month_end(), None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscriptions still charging and not decided "keep", the costliest a month first; then categories that cost
|
||||
/// more last month than the three months before, by at least 10 % and 200 Kč.
|
||||
pub fn sources(state: &State, insight: &Insight, today: Date) -> Vec<Source> {
|
||||
let mut subs: Vec<Source> = insight
|
||||
.subscriptions
|
||||
.iter()
|
||||
.filter(|s| s.status == Status::Active && s.decision.as_ref().map(|d| d.decision) != Some(Decision::Keep))
|
||||
.map(|s| Source::Subscription {
|
||||
key: s.key.clone(),
|
||||
merchant: s.merchant.clone(),
|
||||
monthly: match s.cadence {
|
||||
Cadence::Monthly => s.cost,
|
||||
Cadence::Yearly => Haler(div_up(s.cost.0, 12)),
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
subs.sort_by_key(|s| match s {
|
||||
Source::Subscription { monthly, .. } => std::cmp::Reverse(monthly.0),
|
||||
_ => std::cmp::Reverse(0),
|
||||
});
|
||||
subs.truncate(5);
|
||||
|
||||
let last = today.month_start().add_months(-1);
|
||||
let first = state.effective_payments().iter().map(|p| p.date.month_start()).min();
|
||||
let mut cats = Vec::new();
|
||||
if let Some(first) = first {
|
||||
let earlier: Vec<Date> = (1..=3).map(|n| last.add_months(-n)).filter(|m| *m >= first).collect();
|
||||
if let (Some(oldest), Some(spent_last)) = (earlier.last().copied(), outflows(&between(state, last, last.month_end()))) {
|
||||
if let Some(spent_before) = outflows(&between(state, oldest, last.add_days(-1))) {
|
||||
for (category, amount) in spent_last {
|
||||
if NOT_PLANNABLE.contains(&category.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let average = Haler(spent_before.get(&category).map(|h| h.0).unwrap_or(0) / earlier.len() as i64);
|
||||
let extra = amount.0.saturating_sub(average.0);
|
||||
if average.0 > 0 && extra >= 20_000 && i128::from(amount.0) * 10 > i128::from(average.0) * 11 {
|
||||
cats.push(Source::Category { category, last: amount, average, extra: Haler(extra) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cats.sort_by_key(|s| match s {
|
||||
Source::Category { extra, .. } => std::cmp::Reverse(extra.0),
|
||||
_ => std::cmp::Reverse(0),
|
||||
});
|
||||
cats.truncate(3);
|
||||
subs.extend(cats);
|
||||
subs
|
||||
}
|
||||
|
||||
pub fn goals_month(state: &State, insight: &Insight, today: Date) -> GoalsMonth {
|
||||
let leftover = leftover(state, today);
|
||||
let income = last_income(state, today);
|
||||
let mut cache: Vec<(Haler, (Haler, usize))> = Vec::new();
|
||||
let mut rounds = |to: Haler| {
|
||||
if let Some((_, r)) = cache.iter().find(|(t, _)| *t == to) {
|
||||
return *r;
|
||||
}
|
||||
let r = round_ups(state, to, today);
|
||||
cache.push((to, r));
|
||||
r
|
||||
};
|
||||
let mut open: Vec<&GoalRecord> = state.goals.values().filter(|g| g.is_open()).collect();
|
||||
open.sort_by_key(|g| g.seq);
|
||||
let mut closed: Vec<&GoalRecord> = state.goals.values().filter(|g| !g.is_open()).collect();
|
||||
closed.sort_by_key(|g| std::cmp::Reverse((g.closed, g.seq)));
|
||||
let given = |kind: WayKind| open.iter().flat_map(|g| g.ways.iter()).map(|w| w.share_of(kind)).sum::<u32>();
|
||||
let (leftover_given, income_given) = (given(WayKind::Leftover), given(WayKind::Income));
|
||||
let saved = Haler(open.iter().fold(0i64, |s, g| s.saturating_add(g.saved().0)));
|
||||
let goals = open.iter().chain(closed.iter()).map(|g| status(g, today, leftover, income, &mut rounds)).collect();
|
||||
GoalsMonth { month: today.month_start(), goals, leftover, income, leftover_given, income_given, saved, sources: sources(state, insight, today) }
|
||||
}
|
||||
|
||||
/// What was spent in one category from `from` to `to`, both included (positive).
|
||||
pub fn spent_in(state: &State, category: &str, from: Date, to: Date) -> Haler {
|
||||
Haler(
|
||||
between(state, from, to)
|
||||
.iter()
|
||||
.filter(|p| is_spending(p) && category_of(p) == category)
|
||||
.fold(0i64, |s, p| s.saturating_add(p.amount.0.saturating_neg())),
|
||||
)
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
//! Fiscus Domi's insight: which subscriptions you pay, what changed price, which trial is about to charge,
|
||||
//! how to cancel, whether the month will stay under its limit, where the money went and how it compares with
|
||||
//! your plan. Pure: "today" and seeds are parameters.
|
||||
//! your plan, how your savings goals fill, and the medals and challenges you earn. Pure: "today" and seeds are parameters.
|
||||
|
||||
pub mod cancel;
|
||||
pub mod forecast;
|
||||
pub mod goals;
|
||||
pub mod household;
|
||||
pub mod plan;
|
||||
pub mod rewards;
|
||||
pub mod spending;
|
||||
pub mod stats;
|
||||
pub mod subscriptions;
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
//! 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 },
|
||||
}
|
||||
|
||||
#[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<Earned>,
|
||||
/// Running first (the soonest to end first), then the finished ones, the latest first.
|
||||
pub challenges: Vec<ChallengeStatus>,
|
||||
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<Date> {
|
||||
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<BudgetId>, today: Date) -> Rewards {
|
||||
let mut medals: Vec<Earned> = 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<ChallengeStatus> = 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() });
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,7 +149,7 @@ pub fn analyse(state: &State, today: Date) -> Insight {
|
||||
let full: Vec<&EffectivePayment> = charges.iter().copied().filter(|p| cost(p) > TRIAL_MAX).collect();
|
||||
|
||||
// Trials: the last card check with no full charge after it, or a payment marked by hand.
|
||||
let last_check = charges.iter().filter(|p| cost(p) <= TRIAL_MAX).next_back();
|
||||
let last_check = charges.iter().rfind(|p| cost(p) <= TRIAL_MAX);
|
||||
for p in charges.iter().filter(|p| p.trial_ends.is_some() || Some(*p) == last_check) {
|
||||
let converted = full.iter().any(|f| f.date > p.date && f.id != p.id);
|
||||
let (ends, estimated) = match p.trial_ends {
|
||||
|
||||
Reference in New Issue
Block a user