[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:
Generated
+4
-4
@@ -139,7 +139,7 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-capture"
|
||||
version = "0.5.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"fiscus-ledger",
|
||||
"proptest",
|
||||
@@ -150,7 +150,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-insight"
|
||||
version = "0.5.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"fiscus-ledger",
|
||||
"serde",
|
||||
@@ -159,7 +159,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-ledger"
|
||||
version = "0.5.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -169,7 +169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-statement"
|
||||
version = "0.5.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"fiscus-ledger",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "2"
|
||||
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.5.0"
|
||||
version = "0.6.0"
|
||||
edition = "2021"
|
||||
license = "MPL-2.0"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic"
|
||||
|
||||
@@ -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 },
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Savings goals and challenges in the ledger: what is accepted, and every refusal changing nothing. A goal never
|
||||
//! holds less than nothing, the shares of "what's left" and "income" never add up to more than all of it, and a
|
||||
//! closed goal takes no more money.
|
||||
|
||||
use fiscus_ledger::goal::{ChallengeGoal, Colour, Way, WayKind};
|
||||
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
fn ev(id: &str, body: EventBody) -> Event {
|
||||
Event::new(id, Timestamp(0), body)
|
||||
}
|
||||
|
||||
fn goal(id: &str, name: &str, target: i64) -> EventBody {
|
||||
EventBody::GoalCreated { goal: id.into(), name: name.into(), target: Haler(target), by: Some(d("2027-06-30")), colour: Colour::Teal }
|
||||
}
|
||||
|
||||
fn saved(goal: &str, saving: &str, amount: i64, way: Option<WayKind>) -> EventBody {
|
||||
EventBody::GoalSaved { goal: goal.into(), saving: saving.into(), amount: Haler(amount), on: d("2026-11-05"), way }
|
||||
}
|
||||
|
||||
fn ways(goal: &str, ways: Vec<Way>) -> EventBody {
|
||||
EventBody::GoalWaysSet { goal: goal.into(), ways }
|
||||
}
|
||||
|
||||
/// The base ledger, then `body`: the reason it was refused, or `None` when it was accepted.
|
||||
fn refusal(base: &[EventBody], body: EventBody) -> Option<String> {
|
||||
let mut log: Vec<Event> = base.iter().enumerate().map(|(i, b)| ev(&format!("b{i}"), b.clone())).collect();
|
||||
let before = State::replay(&log);
|
||||
assert!(before.rejected.is_empty(), "{:?}", before.rejected);
|
||||
log.push(ev("x", body));
|
||||
let after = State::replay(&log);
|
||||
match after.rejected.last() {
|
||||
Some(r) => {
|
||||
assert_eq!(after.goals, before.goals, "a refusal changes no goal");
|
||||
assert_eq!(after.challenges, before.challenges, "a refusal changes no challenge");
|
||||
Some(r.reason.clone())
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_goal_fills_with_what_you_put_aside_and_empties_only_to_zero() {
|
||||
let s = State::replay(&[
|
||||
ev("e1", goal("g1", "Holiday", 4_000_000)),
|
||||
ev("e2", ways("g1", vec![Way::Fixed { amount: Haler(200_000) }, Way::RoundUp { to: Haler(5_000) }])),
|
||||
ev("e3", saved("g1", "s1", 200_000, Some(WayKind::Fixed))),
|
||||
ev("e4", saved("g1", "s2", 31_200, Some(WayKind::RoundUp))),
|
||||
ev("e5", saved("g1", "s3", -50_000, None)),
|
||||
]);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
let g = &s.goals["g1"];
|
||||
assert_eq!(g.saved(), Haler(181_200));
|
||||
assert_eq!(g.ways.len(), 2);
|
||||
assert!(g.is_open());
|
||||
|
||||
let base = [goal("g1", "Holiday", 4_000_000), saved("g1", "s1", 100_000, None)];
|
||||
assert_eq!(refusal(&base, saved("g1", "s2", -100_001, None)).as_deref(), Some("more than the goal holds"));
|
||||
assert_eq!(refusal(&base, saved("g1", "s1", 5_000, None)).as_deref(), Some("a saving with this id exists"), "counted once");
|
||||
assert_eq!(refusal(&base, saved("g1", "s2", 0, None)).as_deref(), Some("an amount saved is 0,01-100 000 000 CZK either way"));
|
||||
assert_eq!(refusal(&base, saved("g1", "s2", 5_000, Some(WayKind::Income))).as_deref(), Some("the goal is not saved for that way"));
|
||||
assert_eq!(refusal(&base, saved("nope", "s2", 5_000, None)).as_deref(), Some("no such goal"));
|
||||
assert_eq!(refusal(&base, saved("g1", "s2", -100_000, None)), None, "down to exactly zero");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_goal_is_checked_when_made_and_changed() {
|
||||
assert_eq!(refusal(&[], goal("g1", "", 100_000)).as_deref(), Some("a goal name must be 1-60 characters"));
|
||||
assert_eq!(refusal(&[], goal("g1", " Holiday", 100_000)).as_deref(), Some("a goal name must be 1-60 characters"));
|
||||
assert_eq!(refusal(&[], goal("g1", &"x".repeat(61), 100_000)).as_deref(), Some("a goal name must be 1-60 characters"));
|
||||
assert_eq!(refusal(&[], goal("g1", "Bad\u{7}", 100_000)).as_deref(), Some("a goal name must be 1-60 characters"));
|
||||
assert_eq!(refusal(&[], goal("g1", "Holiday", 99)).as_deref(), Some("a goal target is 1-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&[], goal("g1", "Holiday", 10_000_000_001)).as_deref(), Some("a goal target is 1-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&[goal("g1", "Holiday", 100_000)], goal("g1", "Car", 100_000)).as_deref(), Some("a goal with this id exists"));
|
||||
let twenty: Vec<EventBody> = (0..20).map(|i| goal(&format!("g{i}"), "Goal", 100_000)).collect();
|
||||
assert_eq!(refusal(&twenty, goal("g20", "One more", 100_000)).as_deref(), Some("at most 20 goals are open at once"));
|
||||
let mut closed_one = twenty.clone();
|
||||
closed_one.push(EventBody::GoalClosed { goal: "g3".into(), on: d("2026-11-05") });
|
||||
assert_eq!(refusal(&closed_one, goal("g20", "One more", 100_000)), None, "a closed goal frees its place");
|
||||
|
||||
let base = [goal("g1", "Holiday", 100_000)];
|
||||
let change = |name: &str, target: i64| EventBody::GoalChanged { goal: "g1".into(), name: name.into(), target: Haler(target), by: None, colour: Colour::Coral };
|
||||
assert_eq!(refusal(&base, change("Summer", 200_000)), None);
|
||||
assert_eq!(refusal(&base, change("", 200_000)).as_deref(), Some("a goal name must be 1-60 characters"));
|
||||
let s = State::replay(&[ev("a", base[0].clone()), ev("b", change("Summer", 200_000))]);
|
||||
assert_eq!((s.goals["g1"].name.as_str(), s.goals["g1"].target, s.goals["g1"].colour, s.goals["g1"].by), ("Summer", Haler(200_000), Colour::Coral, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ways_are_one_of_each_kind_and_shares_never_add_up_to_more_than_all() {
|
||||
let base = [goal("g1", "Holiday", 4_000_000), goal("g2", "Car", 9_000_000)];
|
||||
assert_eq!(refusal(&base, ways("g1", vec![Way::Fixed { amount: Haler(100) }, Way::Fixed { amount: Haler(200) }])).as_deref(), Some("a goal has at most one way of each kind"));
|
||||
assert_eq!(refusal(&base, ways("g1", vec![Way::Fixed { amount: Haler(99) }])).as_deref(), Some("a fixed amount is 1-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&base, ways("g1", vec![Way::RoundUp { to: Haler(2_000) }])).as_deref(), Some("round-ups go to 10, 50 or 100 CZK"));
|
||||
assert_eq!(refusal(&base, ways("g1", vec![Way::Income { permille: 0 }])).as_deref(), Some("a share is 1-1000 thousandths"));
|
||||
assert_eq!(refusal(&base, ways("g1", vec![Way::Leftover { permille: 1001 }])).as_deref(), Some("a share is 1-1000 thousandths"));
|
||||
|
||||
let mut split = base.to_vec();
|
||||
split.push(ways("g1", vec![Way::Leftover { permille: 600 }, Way::Income { permille: 100 }]));
|
||||
assert_eq!(refusal(&split, ways("g2", vec![Way::Leftover { permille: 401 }])).as_deref(), Some("the shares of one way across the goals add up to more than all of it"));
|
||||
assert_eq!(refusal(&split, ways("g2", vec![Way::Leftover { permille: 400 }, Way::Income { permille: 900 }])), None, "exactly all of it");
|
||||
assert_eq!(refusal(&split, ways("g1", vec![Way::Leftover { permille: 1000 }])), None, "a goal's own earlier share is replaced, not added");
|
||||
let mut closed = split.clone();
|
||||
closed.push(EventBody::GoalClosed { goal: "g1".into(), on: d("2026-11-05") });
|
||||
assert_eq!(refusal(&closed, ways("g2", vec![Way::Leftover { permille: 1000 }])), None, "a closed goal gives its share back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_goal_takes_no_more_and_keeps_its_history() {
|
||||
let base = [goal("g1", "Holiday", 100_000), saved("g1", "s1", 100_000, None), EventBody::GoalClosed { goal: "g1".into(), on: d("2026-11-06") }];
|
||||
assert_eq!(refusal(&base, saved("g1", "s2", 5_000, None)).as_deref(), Some("the goal is closed"));
|
||||
assert_eq!(refusal(&base, ways("g1", vec![])).as_deref(), Some("the goal is closed"));
|
||||
assert_eq!(refusal(&base, EventBody::GoalClosed { goal: "g1".into(), on: d("2026-11-07") }).as_deref(), Some("the goal is closed"));
|
||||
let s = State::replay(&base.iter().enumerate().map(|(i, b)| ev(&format!("e{i}"), b.clone())).collect::<Vec<_>>());
|
||||
assert_eq!((s.goals["g1"].saved(), s.goals["g1"].closed), (Haler(100_000), Some(d("2026-11-06"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_challenge_is_checked_and_given_up_once() {
|
||||
let start = |goal: ChallengeGoal, starts: &str, ends: &str| EventBody::ChallengeStarted { challenge: "c1".into(), goal, starts: d(starts), ends: d(ends) };
|
||||
let under = |category: &str, amount: i64| ChallengeGoal::SpendUnder { category: category.into(), amount: Haler(amount) };
|
||||
assert_eq!(refusal(&[], start(under("eating-out", 300_000), "2026-11-01", "2026-11-30")), None);
|
||||
assert_eq!(refusal(&[], start(under("eating-out", 300_000), "2026-11-01", "2027-01-31")), None, "92 days");
|
||||
assert_eq!(refusal(&[], start(under("eating-out", 300_000), "2026-11-01", "2027-02-01")).as_deref(), Some("a challenge lasts 1-92 days"));
|
||||
assert_eq!(refusal(&[], start(under("eating-out", 300_000), "2026-11-02", "2026-11-01")).as_deref(), Some("a challenge lasts 1-92 days"));
|
||||
assert_eq!(refusal(&[], start(under("income", 300_000), "2026-11-01", "2026-11-30")).as_deref(), Some("not a category you spend in"));
|
||||
assert_eq!(refusal(&[], start(under("nope", 300_000), "2026-11-01", "2026-11-30")).as_deref(), Some("not a category you spend in"));
|
||||
assert_eq!(refusal(&[], start(under("fun", 0), "2026-11-01", "2026-11-30")).as_deref(), Some("the amount of a challenge is 1-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&[], start(ChallengeGoal::NoSpend { category: "transfers".into() }, "2026-11-01", "2026-11-30")).as_deref(), Some("not a category you spend in"));
|
||||
assert_eq!(refusal(&[], start(ChallengeGoal::Cancel { subscription: String::new() }, "2026-11-01", "2026-11-30")).as_deref(), Some("not a subscription key"));
|
||||
let save = ChallengeGoal::Save { goal: "g1".into(), amount: Haler(500_000) };
|
||||
assert_eq!(refusal(&[], start(save.clone(), "2026-11-01", "2026-11-30")).as_deref(), Some("no such open goal"));
|
||||
assert_eq!(refusal(&[goal("g1", "Holiday", 4_000_000)], start(save.clone(), "2026-11-01", "2026-11-30")), None);
|
||||
|
||||
let base = [start(under("fun", 100_000), "2026-11-01", "2026-11-30")];
|
||||
assert_eq!(refusal(&base, start(under("fun", 100_000), "2026-11-01", "2026-11-30")).as_deref(), Some("a challenge with this id exists"));
|
||||
let give_up = EventBody::ChallengeAbandoned { challenge: "c1".into(), on: d("2026-11-10") };
|
||||
assert_eq!(refusal(&base, give_up.clone()), None);
|
||||
let mut given_up = base.to_vec();
|
||||
given_up.push(give_up.clone());
|
||||
assert_eq!(refusal(&given_up, give_up).as_deref(), Some("already given up"));
|
||||
assert_eq!(refusal(&base, EventBody::ChallengeAbandoned { challenge: "c2".into(), on: d("2026-11-10") }).as_deref(), Some("no such challenge"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_ways_and_goals_do_not_parse() {
|
||||
for bad in [
|
||||
r#"{"id":"x","at":0,"type":"goal.ways_set","goal":"g1","ways":[{"kind":"fixed","amount":100,"extra":1}]}"#,
|
||||
r#"{"id":"x","at":0,"type":"goal.ways_set","goal":"g1","ways":[{"kind":"lottery"}]}"#,
|
||||
r#"{"id":"x","at":0,"type":"goal.ways_set","goal":"g1","ways":[{"kind":"income","permille":1.5}]}"#,
|
||||
r#"{"id":"x","at":0,"type":"goal.created","goal":"g1","name":"A","target":100.0,"by":null,"colour":"teal"}"#,
|
||||
r#"{"id":"x","at":0,"type":"goal.created","goal":"g1","name":"A","target":100,"by":null,"colour":"pink"}"#,
|
||||
r#"{"id":"x","at":0,"type":"challenge.started","challenge":"c","goal":{"kind":"no_spend","category":"fun","amount":5},"starts":"2026-11-01","ends":"2026-11-30"}"#,
|
||||
] {
|
||||
assert!(serde_json::from_str::<Event>(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user