[ledger] Goals and challenges: goal.created/changed/ways_set/saved/closed and challenge.started/abandoned, with their checks; v0.6.0

This commit is contained in:
2026-11-07 22:39:54 +01:00
parent 2e8eee6007
commit c3cb1dd060
9 changed files with 467 additions and 7 deletions
+22
View File
@@ -1,6 +1,7 @@
//! The event log. Append only: a correction is a new event, nothing is ever edited or removed.
use crate::date::{Date, Timestamp};
use crate::goal::{ChallengeGoal, ChallengeId, Colour, GoalId, Way, WayKind};
use crate::import::StatementLine;
use crate::invoice::{Invoice, InvoiceId, Supplier};
use crate::money::Haler;
@@ -165,4 +166,25 @@ pub enum EventBody {
/// A category of your own (an id as [`crate::categories::is_valid`]) and the name the app shows for it.
#[serde(rename = "category.created")]
CategoryCreated { category: Category, label: String },
/// A savings goal (see [`crate::goal`]): a name, a target, an optional date to reach it by, the tank's colour.
#[serde(rename = "goal.created")]
GoalCreated { goal: GoalId, name: String, target: Haler, by: Option<Date>, colour: Colour },
/// A goal's name, target, date or colour changed; the latest counts.
#[serde(rename = "goal.changed")]
GoalChanged { goal: GoalId, name: String, target: Haler, by: Option<Date>, colour: Colour },
/// How a goal is saved for: up to one way of each kind. Replaces the goal's earlier ways.
#[serde(rename = "goal.ways_set")]
GoalWaysSet { goal: GoalId, ways: Vec<Way> },
/// Money put aside for a goal (positive) or taken out (negative), by one of its ways or by hand (`None`).
#[serde(rename = "goal.saved")]
GoalSaved { goal: GoalId, saving: String, amount: Haler, on: Date, way: Option<WayKind> },
/// Reached or given up: no more saving into it. Its history stays.
#[serde(rename = "goal.closed")]
GoalClosed { goal: GoalId, on: Date },
/// A challenge you set yourself, from `starts` to `ends` (both included, at most 92 days).
#[serde(rename = "challenge.started")]
ChallengeStarted { challenge: ChallengeId, goal: ChallengeGoal, starts: Date, ends: Date },
/// Given up; a challenge is given up once.
#[serde(rename = "challenge.abandoned")]
ChallengeAbandoned { challenge: ChallengeId, on: Date },
}
+136
View File
@@ -0,0 +1,136 @@
//! Savings goals and challenges: what you mean to put aside and how, and the challenges you set yourself. Fiscus
//! never moves money: a goal holds what you said you put aside (`goal.saved`), so it is never full unless you
//! filled it. Personal log only, like plans: a shared budget's members never see them.
use crate::event::Category;
use crate::money::Haler;
use crate::date::Date;
use serde::{Deserialize, Serialize};
pub type GoalId = String;
pub type ChallengeId = String;
/// At most this many goals open at once.
pub const MAX_OPEN_GOALS: usize = 20;
/// At most this many challenges running (not ended, not given up) at once.
pub const MAX_OPEN_CHALLENGES: usize = 20;
/// A goal's target, a fixed monthly amount, a challenge's amount: 1 Kč to 100 000 000 Kč.
pub const MIN_AMOUNT: Haler = Haler(100);
pub const MAX_AMOUNT: Haler = Haler(10_000_000_000);
/// A challenge lasts at most 92 days, its first and last day included.
pub const MAX_CHALLENGE_DAYS: i32 = 92;
/// Round-ups go to the next 10, 50 or 100 Kč.
pub const ROUND_UP_TO: [Haler; 3] = [Haler(1_000), Haler(5_000), Haler(10_000)];
/// The tank's colour, from the app's palette.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Colour {
Teal,
Amber,
Coral,
Blue,
Violet,
Green,
}
/// How a goal's monthly saving is found. A goal has at most one of each kind.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Way {
/// The same amount every month.
Fixed { amount: Haler },
/// Each card payment of the month rounded up to the next `to` (10, 50 or 100 Kč); the differences add up.
RoundUp { to: Haler },
/// This share (in thousandths) of what last month's category plans did not use.
Leftover { permille: u16 },
/// This share (in thousandths) of last month's money in.
Income { permille: u16 },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WayKind {
Fixed,
RoundUp,
Leftover,
Income,
}
impl Way {
pub fn kind(&self) -> WayKind {
match self {
Way::Fixed { .. } => WayKind::Fixed,
Way::RoundUp { .. } => WayKind::RoundUp,
Way::Leftover { .. } => WayKind::Leftover,
Way::Income { .. } => WayKind::Income,
}
}
/// The share of the month's leftover or income this way takes, in thousandths (0 for the others).
pub fn share_of(&self, kind: WayKind) -> u32 {
match (self, kind) {
(Way::Leftover { permille }, WayKind::Leftover) | (Way::Income { permille }, WayKind::Income) => u32::from(*permille),
_ => 0,
}
}
}
/// What a challenge asks.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ChallengeGoal {
/// Spend less than `amount` in `category` from the first day to the last.
SpendUnder { category: Category, amount: Haler },
/// Spend nothing in `category`.
NoSpend { category: Category },
/// Decide to cancel this subscription (its key) and not be charged for it again before the end.
Cancel { subscription: String },
/// Put `amount` aside for this goal.
Save { goal: GoalId, amount: Haler },
}
/// One amount put aside (positive) or taken out (negative).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Saving {
pub id: String,
pub amount: Haler,
pub on: Date,
pub way: Option<WayKind>,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GoalRecord {
pub id: GoalId,
pub name: String,
pub target: Haler,
pub by: Option<Date>,
pub colour: Colour,
pub ways: Vec<Way>,
/// In log order.
pub savings: Vec<Saving>,
pub closed: Option<Date>,
pub seq: u64,
}
impl GoalRecord {
/// Everything put aside less everything taken out; never negative (the ledger refuses that).
pub fn saved(&self) -> Haler {
Haler(self.savings.iter().fold(0i64, |s, x| s.saturating_add(x.amount.0)))
}
pub fn is_open(&self) -> bool {
self.closed.is_none()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChallengeRecord {
pub id: ChallengeId,
pub goal: ChallengeGoal,
pub starts: Date,
pub ends: Date,
pub abandoned: Option<Date>,
pub seq: u64,
}
+1
View File
@@ -5,6 +5,7 @@
pub mod categories;
pub mod date;
pub mod event;
pub mod goal;
pub mod import;
pub mod invoice;
pub mod matching;
+1 -1
View File
@@ -6,7 +6,7 @@ pub fn merchant_key(raw: &str) -> String {
let folded: String = raw.chars().flat_map(fold).collect::<String>().to_lowercase();
// A processor's prefix before `*`: "paypal *spotify", "sumup *kavarna", "sq *bistro".
let rest = match folded.split_once('*') {
Some((head, tail)) if !tail.trim().is_empty() && head.trim().split_whitespace().count() <= 2 => tail,
Some((head, tail)) if !tail.trim().is_empty() && head.split_whitespace().count() <= 2 => tail,
_ => folded.as_str(),
};
let cleaned: String = rest.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' }).collect();
+1 -1
View File
@@ -49,7 +49,7 @@ impl Haler {
let whole = (abs / 100).to_string();
let mut grouped = String::with_capacity(whole.len() + whole.len() / 3);
for (i, c) in whole.chars().enumerate() {
if i > 0 && (whole.len() - i) % 3 == 0 {
if i > 0 && (whole.len() - i).is_multiple_of(3) {
grouped.push(' ');
}
grouped.push(c);
+141
View File
@@ -4,6 +4,7 @@
use crate::categories;
use crate::date::Date;
use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId};
use crate::goal::{self, ChallengeGoal, ChallengeId, ChallengeRecord, GoalId, GoalRecord, Saving, Way, WayKind};
use crate::import::StatementLine;
use crate::invoice::{Invoice, InvoiceId, Supplier, Totals};
use crate::merchant::merchant_key;
@@ -227,6 +228,12 @@ pub struct State {
pub category_plans: BTreeMap<Category, Vec<PlanRecord>>,
/// Your own categories: id → the name shown (`category.created`).
pub custom_categories: BTreeMap<Category, String>,
/// Savings goals by id (`goal.*`).
pub goals: BTreeMap<GoalId, GoalRecord>,
/// Every `goal.saved` id, so none is counted twice.
pub saving_ids: BTreeSet<String>,
/// Challenges by id (`challenge.*`).
pub challenges: BTreeMap<ChallengeId, ChallengeRecord>,
pub rejected: Vec<Rejection>,
}
@@ -280,6 +287,17 @@ fn name_ok(s: &str, max: usize) -> bool {
!s.trim().is_empty() && s.chars().count() <= max && text_ok(s)
}
/// A goal's name and target, for `goal.created` and `goal.changed`.
fn goal_fields(name: &str, target: Haler) -> Result<(), &'static str> {
if !name_ok(name, 60) || name.trim() != name {
return Err("a goal name must be 1-60 characters");
}
if target < goal::MIN_AMOUNT || target > goal::MAX_AMOUNT {
return Err("a goal target is 1-100 000 000 CZK");
}
Ok(())
}
fn id_ok(s: &str) -> bool {
!s.is_empty() && s.len() <= 100 && text_ok(s)
}
@@ -770,6 +788,129 @@ impl State {
return Err("a subscription name appears twice");
}
}
EventBody::GoalCreated { goal, name, target, by, colour } => {
if !id_ok(goal) || self.goals.contains_key(goal) {
return Err("a goal with this id exists");
}
goal_fields(name, *target)?;
if self.goals.values().filter(|g| g.is_open()).count() >= goal::MAX_OPEN_GOALS {
return Err("at most 20 goals are open at once");
}
self.goals.insert(
goal.clone(),
GoalRecord { id: goal.clone(), name: name.clone(), target: *target, by: *by, colour: *colour, ways: Vec::new(), savings: Vec::new(), closed: None, seq },
);
}
EventBody::GoalChanged { goal, name, target, by, colour } => {
goal_fields(name, *target)?;
let g = self.goals.get_mut(goal).ok_or("no such goal")?;
if !g.is_open() {
return Err("the goal is closed");
}
(g.name, g.target, g.by, g.colour) = (name.clone(), *target, *by, *colour);
}
EventBody::GoalWaysSet { goal, ways } => {
let g = self.goals.get(goal).ok_or("no such goal")?;
if !g.is_open() {
return Err("the goal is closed");
}
if ways.iter().map(Way::kind).collect::<BTreeSet<_>>().len() != ways.len() {
return Err("a goal has at most one way of each kind");
}
for w in ways {
match w {
Way::Fixed { amount } if *amount < goal::MIN_AMOUNT || *amount > goal::MAX_AMOUNT => return Err("a fixed amount is 1-100 000 000 CZK"),
Way::RoundUp { to } if !goal::ROUND_UP_TO.contains(to) => return Err("round-ups go to 10, 50 or 100 CZK"),
Way::Leftover { permille } | Way::Income { permille } if *permille == 0 || *permille > 1000 => return Err("a share is 1-1000 thousandths"),
_ => {}
}
}
for kind in [WayKind::Leftover, WayKind::Income] {
let others: u32 = self.goals.values().filter(|o| o.is_open() && &o.id != goal).flat_map(|o| o.ways.iter()).map(|w| w.share_of(kind)).sum();
let mine: u32 = ways.iter().map(|w| w.share_of(kind)).sum();
if others + mine > 1000 {
return Err("the shares of one way across the goals add up to more than all of it");
}
}
self.goals.get_mut(goal).expect("checked").ways = ways.clone();
}
EventBody::GoalSaved { goal, saving, amount, on, way } => {
if !id_ok(saving) || self.saving_ids.contains(saving) {
return Err("a saving with this id exists");
}
let g = self.goals.get(goal).ok_or("no such goal")?;
if !g.is_open() {
return Err("the goal is closed");
}
if amount.0 == 0 || amount.0.unsigned_abs() > goal::MAX_AMOUNT.0 as u64 {
return Err("an amount saved is 0,01-100 000 000 CZK either way");
}
if g.saved().checked_add(*amount).map_err(|_| "the goal would not fit")?.0 < 0 {
return Err("more than the goal holds");
}
if let Some(k) = way {
if !g.ways.iter().any(|w| w.kind() == *k) {
return Err("the goal is not saved for that way");
}
}
self.saving_ids.insert(saving.clone());
self.goals.get_mut(goal).expect("checked").savings.push(Saving { id: saving.clone(), amount: *amount, on: *on, way: *way, seq });
}
EventBody::GoalClosed { goal, on } => {
let g = self.goals.get_mut(goal).ok_or("no such goal")?;
if !g.is_open() {
return Err("the goal is closed");
}
g.closed = Some(*on);
}
EventBody::ChallengeStarted { challenge, goal, starts, ends } => {
if !id_ok(challenge) || self.challenges.contains_key(challenge) {
return Err("a challenge with this id exists");
}
let days = starts.days_until(*ends);
if !(0..goal::MAX_CHALLENGE_DAYS as i64).contains(&(days as i64)) {
return Err("a challenge lasts 1-92 days");
}
match goal {
ChallengeGoal::SpendUnder { category, amount } => {
if !self.category_known(category) || categories::NOT_PLANNABLE.contains(&category.as_str()) {
return Err("not a category you spend in");
}
if *amount < goal::MIN_AMOUNT || *amount > goal::MAX_AMOUNT {
return Err("the amount of a challenge is 1-100 000 000 CZK");
}
}
ChallengeGoal::NoSpend { category } => {
if !self.category_known(category) || categories::NOT_PLANNABLE.contains(&category.as_str()) {
return Err("not a category you spend in");
}
}
ChallengeGoal::Cancel { subscription } => {
if subscription.is_empty() || subscription.len() > 100 || !text_ok(subscription) {
return Err("not a subscription key");
}
}
ChallengeGoal::Save { goal: g, amount } => {
if !self.goals.get(g).is_some_and(GoalRecord::is_open) {
return Err("no such open goal");
}
if *amount < goal::MIN_AMOUNT || *amount > goal::MAX_AMOUNT {
return Err("the amount of a challenge is 1-100 000 000 CZK");
}
}
}
if self.challenges.values().filter(|c| c.abandoned.is_none() && c.ends >= *starts).count() >= goal::MAX_OPEN_CHALLENGES {
return Err("at most 20 challenges run at once");
}
self.challenges.insert(challenge.clone(), ChallengeRecord { id: challenge.clone(), goal: goal.clone(), starts: *starts, ends: *ends, abandoned: None, seq });
}
EventBody::ChallengeAbandoned { challenge, on } => {
let c = self.challenges.get_mut(challenge).ok_or("no such challenge")?;
if c.abandoned.is_some() {
return Err("already given up");
}
c.abandoned = Some(*on);
}
}
Ok(())
}