[ledger] Core: haléře, dates, the event log and apply(), merchant keys and rules, one-to-one matching, import planning

This commit is contained in:
2026-11-03 18:52:36 +01:00
parent da672b132e
commit 6572f31b1d
14 changed files with 1731 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
//! The categories the app offers. A category is an id; the label is what the app shows.
pub const UNCATEGORISED: &str = "uncategorised";
/// `(id, label)` in the order the app lists them.
pub const DEFAULT: &[(&str, &str)] = &[
("groceries", "Groceries"),
("eating-out", "Eating out"),
("transport", "Transport"),
("housing", "Housing"),
("utilities", "Utilities"),
("subscriptions", "Subscriptions"),
("shopping", "Shopping"),
("health", "Health"),
("kids", "Kids"),
("fun", "Fun"),
("travel", "Travel"),
("gifts", "Gifts"),
("income", "Income"),
("transfers", "Transfers"),
("other", "Other"),
(UNCATEGORISED, "Uncategorised"),
];
/// A category id is lowercase ASCII letters, digits and `-`, 1–40 characters.
pub fn is_valid(id: &str) -> bool {
(1..=40).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
pub fn label(id: &str) -> &str {
DEFAULT.iter().find(|(i, _)| *i == id).map(|(_, l)| *l).unwrap_or(id)
}
+192
View File
@@ -0,0 +1,192 @@
//! Civil dates as days since 1970-01-01 (proleptic Gregorian), and timestamps the app hands in.
//! There is no clock here: "today" is always a parameter.
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::str::FromStr;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Date(i32);
/// Milliseconds since the Unix epoch, as given by the app.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Timestamp(pub i64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("not a date (expected YYYY-MM-DD)")]
pub struct DateError;
const MIN_YEAR: i32 = 1900;
const MAX_YEAR: i32 = 2200;
pub fn is_leap(y: i32) -> bool {
(y % 4 == 0 && y % 100 != 0) || y % 400 == 0
}
pub fn days_in_month(y: i32, m: u32) -> u32 {
match m {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if is_leap(y) => 29,
2 => 28,
_ => 0,
}
}
impl Date {
/// `None` for an impossible date or a year outside 1900–2200.
pub fn from_ymd(y: i32, m: u32, d: u32) -> Option<Date> {
if !(MIN_YEAR..=MAX_YEAR).contains(&y) || !(1..=12).contains(&m) || d == 0 || d > days_in_month(y, m) {
return None;
}
// Howard Hinnant's days_from_civil.
let y = if m <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let mp = (m as i32 + 9) % 12;
let doy = (153 * mp + 2) / 5 + d as i32 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
Some(Date(era * 146_097 + doe - 719_468))
}
pub fn from_days(days: i32) -> Date {
Date(days)
}
pub fn days(self) -> i32 {
self.0
}
pub fn ymd(self) -> (i32, u32, u32) {
let z = self.0 + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { y + 1 } else { y }, m, d)
}
pub fn add_days(self, n: i32) -> Date {
Date(self.0 + n)
}
/// Days from `self` to `other` (positive when `other` is later).
pub fn days_until(self, other: Date) -> i32 {
other.0 - self.0
}
/// The same day `n` months later, clamped to the month's last day (31 Jan + 1 = 28/29 Feb).
pub fn add_months(self, n: i32) -> Date {
let (y, m, d) = self.ymd();
let idx = y * 12 + (m as i32 - 1) + n;
let (ny, nm) = (idx.div_euclid(12), (idx.rem_euclid(12) + 1) as u32);
let nd = d.min(days_in_month(ny, nm));
Date::from_ymd(ny, nm, nd).unwrap_or(self)
}
pub fn add_years(self, n: i32) -> Date {
self.add_months(n * 12)
}
pub fn month_start(self) -> Date {
let (y, m, _) = self.ymd();
Date::from_ymd(y, m, 1).unwrap_or(self)
}
pub fn month_end(self) -> Date {
let (y, m, _) = self.ymd();
Date::from_ymd(y, m, days_in_month(y, m)).unwrap_or(self)
}
/// `(year, month)` — the key of a monthly budget period.
pub fn month(self) -> (i32, u32) {
let (y, m, _) = self.ymd();
(y, m)
}
/// The civil date of a timestamp in UTC. The app passes local "today" as a `Date`; this is for the log.
pub fn from_timestamp_utc(t: Timestamp) -> Date {
Date(t.0.div_euclid(86_400_000) as i32)
}
}
impl fmt::Display for Date {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (y, m, d) = self.ymd();
write!(f, "{y:04}-{m:02}-{d:02}")
}
}
impl FromStr for Date {
type Err = DateError;
fn from_str(s: &str) -> Result<Date, DateError> {
let b = s.as_bytes();
if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
return Err(DateError);
}
let num = |r: std::ops::Range<usize>| -> Result<u32, DateError> {
let part = &s[r];
if !part.bytes().all(|c| c.is_ascii_digit()) {
return Err(DateError);
}
part.parse().map_err(|_| DateError)
};
Date::from_ymd(num(0..4)? as i32, num(5..7)?, num(8..10)?).ok_or(DateError)
}
}
impl Serialize for Date {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Date {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Date, D::Error> {
let s = String::deserialize(d)?;
s.parse().map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_every_day_for_three_centuries() {
let start = Date::from_ymd(1900, 1, 1).unwrap();
let end = Date::from_ymd(2200, 12, 31).unwrap();
let mut day = start;
while day <= end {
let (y, m, d) = day.ymd();
assert_eq!(Date::from_ymd(y, m, d), Some(day));
assert_eq!(day.to_string().parse::<Date>(), Ok(day));
day = day.add_days(1);
}
assert_eq!(Date::from_ymd(1970, 1, 1).unwrap().days(), 0);
}
#[test]
fn months_clamp() {
let d = |s: &str| s.parse::<Date>().unwrap();
assert_eq!(d("2026-01-31").add_months(1), d("2026-02-28"));
assert_eq!(d("2028-01-31").add_months(1), d("2028-02-29"));
assert_eq!(d("2026-12-15").add_months(1), d("2027-01-15"));
assert_eq!(d("2026-03-31").add_months(-1), d("2026-02-28"));
assert_eq!(d("2028-02-29").add_years(1), d("2029-02-28"));
assert_eq!(d("2026-11-03").month_end(), d("2026-11-30"));
}
#[test]
fn refuses_what_is_not_a_date() {
for bad in ["2026-02-29", "2026-13-01", "2026-00-10", "26-01-01", "2026-1-01", "2026-01-01T", "+026-01-01", "1899-12-31"] {
assert!(bad.parse::<Date>().is_err(), "{bad}");
}
}
}
+76
View File
@@ -0,0 +1,76 @@
//! The event log. Append only: a correction is a new event, nothing is ever edited or removed.
use crate::date::{Date, Timestamp};
use crate::import::StatementLine;
use crate::money::Haler;
use serde::{Deserialize, Serialize};
/// Ids are opaque strings the app generates (random, unguessable); the core never makes one up.
pub type EventId = String;
pub type PaymentId = String;
pub type BudgetId = String;
pub type RuleId = String;
/// A category id, e.g. `groceries` (see [`crate::categories`]).
pub type Category = String;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Event {
pub id: EventId,
/// When the event was written (the app's clock), for display and sync; never for ordering.
pub at: Timestamp,
#[serde(flatten)]
pub body: EventBody,
}
impl Event {
pub fn new(id: impl Into<EventId>, at: Timestamp, body: EventBody) -> Event {
Event { id: id.into(), at, body }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Decision {
Keep,
Cancel,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum EventBody {
/// A phone saw a card payment (○).
#[serde(rename = "payment.captured")]
PaymentCaptured { payment: PaymentId, amount: Haler, date: Date, merchant: String, card: Option<String> },
/// One statement line (●). `line_key` identifies the line across imports.
#[serde(rename = "payment.imported")]
PaymentImported { payment: PaymentId, line: StatementLine, line_key: String },
/// Added by hand (◆). The merchant may be empty (cash, "groceries").
#[serde(rename = "payment.added")]
PaymentAdded {
payment: PaymentId,
amount: Haler,
date: Date,
merchant: String,
category: Option<Category>,
note: Option<String>,
},
/// A captured or hand-added payment and the statement line that confirms it are one payment.
#[serde(rename = "payment.confirmed")]
PaymentConfirmed { payment: PaymentId, line: PaymentId },
#[serde(rename = "payment.categorised")]
PaymentCategorised { payment: PaymentId, category: Category },
#[serde(rename = "payment.assigned")]
PaymentAssigned { payment: PaymentId, budget: BudgetId },
#[serde(rename = "payment.trial_marked")]
PaymentTrialMarked { payment: PaymentId, ends: Date },
#[serde(rename = "budget.created")]
BudgetCreated { budget: BudgetId, name: String, limit: Haler },
#[serde(rename = "budget.limit_set")]
BudgetLimitSet { budget: BudgetId, limit: Haler },
/// "Always <merchant key> → <category>".
#[serde(rename = "rule.created")]
RuleCreated { rule: RuleId, merchant_key: String, category: Category },
/// Keep or cancel a subscription (by its key), seen at `amount` (a positive cost) on `on`.
#[serde(rename = "subscription.decided")]
SubscriptionDecided { subscription: String, decision: Decision, amount: Haler, on: Date },
}
+109
View File
@@ -0,0 +1,109 @@
//! Turning parsed statement lines into events: new lines only, then the matches they make.
use crate::date::{Date, Timestamp};
use crate::event::{Event, EventBody};
use crate::matching::{find_matches, MatchReport};
use crate::money::Haler;
use crate::state::State;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
/// One line of a bank statement, as a bank parser produced it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatementLine {
/// The parser's bank id, e.g. `fio`.
pub bank: String,
/// The statement's own account, as the bank writes it.
pub account: String,
pub booked: Date,
pub amount: Haler,
/// The merchant or payee text; may be empty.
pub merchant: String,
pub counterparty: Option<String>,
pub variable_symbol: Option<String>,
pub message: Option<String>,
/// The bank's own id for the transaction, when the format has one.
pub bank_ref: Option<String>,
}
impl StatementLine {
/// No control characters and nothing over 500 characters, in any text field.
pub fn is_clean(&self) -> bool {
let ok = |s: &str| s.chars().count() <= 500 && !s.chars().any(|c| c.is_control());
[&self.bank, &self.account, &self.merchant].iter().all(|s| ok(s))
&& [&self.counterparty, &self.variable_symbol, &self.message, &self.bank_ref]
.iter()
.all(|s| s.as_deref().is_none_or(ok))
}
}
/// The identity of each line across imports. With the bank's own id: bank|account|id. Without one: the line's
/// fields plus how many identical lines came before it in this file, so two identical coffees stay two lines
/// and the same file imported again gives the same keys.
pub fn line_keys(lines: &[StatementLine]) -> Vec<String> {
let mut seen: BTreeMap<String, u32> = BTreeMap::new();
lines
.iter()
.map(|l| {
let base = match &l.bank_ref {
Some(r) => format!("{}|{}|ref:{}", l.bank, l.account, r),
None => format!(
"{}|{}|{}|{}|{}|{}|{}|{}",
l.bank,
l.account,
l.booked,
l.amount.0,
l.merchant,
l.counterparty.as_deref().unwrap_or(""),
l.variable_symbol.as_deref().unwrap_or(""),
l.message.as_deref().unwrap_or("")
),
};
let n = seen.entry(base.clone()).or_insert(0);
*n += 1;
if l.bank_ref.is_some() {
base
} else {
format!("{base}#{n}")
}
})
.collect()
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImportPlan {
/// One `payment.imported` per new line, in file order.
pub events: Vec<Event>,
/// One `payment.confirmed` per certain match, to append after `events` when the user confirms.
pub confirmations: Vec<Event>,
/// Lines already in the ledger (or repeated in the file under the same bank id), skipped.
pub duplicates: usize,
/// The matches as they would be with the new lines in.
pub report: MatchReport,
}
/// Plans an import. Nothing is applied: the app appends `events`, then `confirmations`.
/// `ids` gives fresh ids: for each new line its payment id then its event id, then one per confirmation.
pub fn plan_import(state: &State, lines: &[StatementLine], ids: &mut dyn FnMut() -> String, at: Timestamp) -> ImportPlan {
let mut sim = state.clone();
let mut plan = ImportPlan::default();
let mut batch: BTreeSet<String> = BTreeSet::new();
for (line, key) in lines.iter().zip(line_keys(lines)) {
if state.line_keys.contains_key(&key) || !batch.insert(key.clone()) {
plan.duplicates += 1;
continue;
}
let payment = ids();
let event = Event::new(ids(), at, EventBody::PaymentImported { payment, line: line.clone(), line_key: key });
sim.apply(&event);
plan.events.push(event);
}
plan.report = find_matches(&sim);
plan.confirmations = plan
.report
.pairs
.iter()
.map(|(payment, line)| Event::new(ids(), at, EventBody::PaymentConfirmed { payment: payment.clone(), line: line.clone() }))
.collect();
plan
}
+16
View File
@@ -0,0 +1,16 @@
//! Fiscus Domi's ledger: money in haléře, civil dates, the append-only event log and the state derived from
//! it, merchant keys and rules, and capture ↔ statement matching. Pure: no I/O, no clock, no randomness.
pub mod categories;
pub mod date;
pub mod event;
pub mod import;
pub mod matching;
pub mod merchant;
pub mod money;
pub mod state;
pub use date::{Date, Timestamp};
pub use event::{BudgetId, Category, Decision, Event, EventBody, EventId, PaymentId};
pub use money::Haler;
pub use state::{EffectivePayment, Glyph, Origin, State};
+114
View File
@@ -0,0 +1,114 @@
//! Capture ↔ statement matching. One to one, never a guess: a pair is matched only when each side is the
//! other's single best candidate; everything else is reported for the user.
use crate::event::PaymentId;
use crate::merchant::compatible;
use crate::state::{Origin, PaymentRecord, State};
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
/// A statement line may be booked this many days before the capture …
pub const WINDOW_BEFORE: i32 = 1;
/// … and this many days after it.
pub const WINDOW_AFTER: i32 = 5;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ambiguity {
/// The captured or hand-added payment.
pub payment: PaymentId,
/// Statement lines it could be, best first.
pub candidates: Vec<PaymentId>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MatchReport {
/// `(captured or hand-added, statement line)`, matched with certainty.
pub pairs: Vec<(PaymentId, PaymentId)>,
/// Unmatched payments that have possible lines: the user picks.
pub ambiguous: Vec<Ambiguity>,
/// Every captured or hand-added payment not in `pairs`.
pub unmatched_captured: Vec<PaymentId>,
/// Every statement line not in `pairs`.
pub unmatched_lines: Vec<PaymentId>,
}
/// How well a line fits a payment. `None`: it cannot be the same payment.
/// `Some((strong, exact, -gap))`, compared as a tuple; only strong fits are ever matched automatically.
fn fit(p: &PaymentRecord, l: &PaymentRecord) -> Option<(bool, bool, i32)> {
if p.amount != l.amount {
return None;
}
let gap = p.date.days_until(l.date);
if !(-WINDOW_BEFORE..=WINDOW_AFTER).contains(&gap) {
return None;
}
if p.merchant_key.is_empty() || l.merchant_key.is_empty() {
return Some((false, false, -gap.abs()));
}
if !compatible(&p.merchant_key, &l.merchant_key) {
return None;
}
Some((true, p.merchant_key == l.merchant_key, -gap.abs()))
}
/// The single best candidate, if it is strictly better than the second.
fn unique_best<'a>(cands: impl Iterator<Item = (&'a PaymentId, (bool, bool, i32))>) -> Option<&'a PaymentId> {
let mut v: Vec<_> = cands.filter(|(_, s)| s.0).collect();
v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
match v.as_slice() {
[] => None,
[only] => Some(only.0),
[first, second, ..] if first.1 > second.1 => Some(first.0),
_ => None,
}
}
pub fn find_matches(state: &State) -> MatchReport {
let mut left: Vec<&PaymentRecord> =
state.payments.values().filter(|p| p.origin != Origin::Imported && p.partner.is_none()).collect();
let mut right: Vec<&PaymentRecord> =
state.payments.values().filter(|p| p.origin == Origin::Imported && p.partner.is_none()).collect();
left.sort_by_key(|p| p.seq);
right.sort_by_key(|p| p.seq);
let mut done_l: BTreeSet<&PaymentId> = BTreeSet::new();
let mut done_r: BTreeSet<&PaymentId> = BTreeSet::new();
let mut pairs: Vec<(u64, PaymentId, PaymentId)> = Vec::new();
loop {
let mut found = Vec::new();
for p in left.iter().filter(|p| !done_l.contains(&p.id)) {
let open_r = right.iter().filter(|l| !done_r.contains(&l.id));
let Some(best) = unique_best(open_r.filter_map(|l| fit(p, l).map(|s| (&l.id, s)))) else { continue };
let line = right.iter().find(|l| &l.id == best).expect("best comes from right");
let open_l = left.iter().filter(|q| !done_l.contains(&q.id));
if unique_best(open_l.filter_map(|q| fit(q, line).map(|s| (&q.id, s)))) == Some(&p.id) {
found.push((p.seq, &p.id, &line.id));
}
}
if found.is_empty() {
break;
}
for (seq, p, l) in found {
done_l.insert(p);
done_r.insert(l);
pairs.push((seq, p.clone(), l.clone()));
}
}
pairs.sort();
let mut report = MatchReport { pairs: pairs.into_iter().map(|(_, p, l)| (p, l)).collect(), ..Default::default() };
for p in left.iter().filter(|p| !done_l.contains(&p.id)) {
report.unmatched_captured.push(p.id.clone());
let mut cands: Vec<_> = right
.iter()
.filter(|l| !done_r.contains(&l.id))
.filter_map(|l| fit(p, l).map(|s| (s, &l.id)))
.collect();
cands.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(b.1)));
if !cands.is_empty() {
report.ambiguous.push(Ambiguity { payment: p.id.clone(), candidates: cands.into_iter().map(|(_, id)| id.clone()).collect() });
}
}
report.unmatched_lines = right.iter().filter(|l| !done_r.contains(&l.id)).map(|l| l.id.clone()).collect();
report
}
+107
View File
@@ -0,0 +1,107 @@
//! Merchant keys: the same shop written differently by a phone, a bank and a person becomes one key.
//! Rules and subscriptions are keyed on it.
/// `PAYPAL *SPOTIFY P1234` → `spotify`; `ALBERT 1234 PRAHA 4 CZ` → `albert praha`; `Žabka` → `zabka`.
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,
_ => folded.as_str(),
};
let cleaned: String = rest.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' }).collect();
let mut words: Vec<&str> = cleaned
.split_whitespace()
.filter(|w| !w.bytes().any(|b| b.is_ascii_digit()))
.collect();
while words.len() > 1 && matches!(words.last(), Some(&"cz") | Some(&"cze") | Some(&"czech")) {
words.pop();
}
words.join(" ")
}
/// Whether two merchant keys can be the same shop: equal, one inside the other, or the same first word of
/// at least three letters. An empty key is never compatible.
pub fn compatible(a: &str, b: &str) -> bool {
if a.is_empty() || b.is_empty() {
return false;
}
if a == b || contains_words(a, b) || contains_words(b, a) {
return true;
}
match (a.split(' ').next(), b.split(' ').next()) {
(Some(x), Some(y)) => x == y && x.len() >= 3,
_ => false,
}
}
/// `needle`'s words appear in `hay` as a run of whole words.
fn contains_words(hay: &str, needle: &str) -> bool {
let h: Vec<&str> = hay.split(' ').collect();
let n: Vec<&str> = needle.split(' ').collect();
n.len() <= h.len() && h.windows(n.len()).any(|w| w == n.as_slice())
}
/// ASCII folding of the Latin letters a Czech (or Slovak, German, Polish) shop name uses.
fn fold(c: char) -> std::iter::Once<char> {
let r = match c {
'á' | 'ä' | 'à' | 'â' | 'ą' => 'a',
'Á' | 'Ä' | 'À' | 'Â' | 'Ą' => 'A',
'č' | 'ć' | 'ç' => 'c',
'Č' | 'Ć' | 'Ç' => 'C',
'ď' => 'd',
'Ď' => 'D',
'é' | 'ě' | 'ë' | 'è' | 'ê' | 'ę' => 'e',
'É' | 'Ě' | 'Ë' | 'È' | 'Ê' | 'Ę' => 'E',
'í' | 'ï' | 'î' => 'i',
'Í' | 'Ï' | 'Î' => 'I',
'ľ' | 'ĺ' | 'ł' => 'l',
'Ľ' | 'Ĺ' | 'Ł' => 'L',
'ň' | 'ń' => 'n',
'Ň' | 'Ń' => 'N',
'ó' | 'ö' | 'ô' | 'ő' => 'o',
'Ó' | 'Ö' | 'Ô' | 'Ő' => 'O',
'ř' | 'ŕ' => 'r',
'Ř' | 'Ŕ' => 'R',
'š' | 'ś' => 's',
'Š' | 'Ś' => 'S',
'ť' => 't',
'Ť' => 'T',
'ú' | 'ů' | 'ü' | 'ű' => 'u',
'Ú' | 'Ů' | 'Ü' | 'Ű' => 'U',
'ý' | 'ÿ' => 'y',
'Ý' => 'Y',
'ž' | 'ź' | 'ż' => 'z',
'Ž' | 'Ź' | 'Ż' => 'Z',
'ß' => 's',
other => other,
};
std::iter::once(r)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys() {
assert_eq!(merchant_key("PAYPAL *SPOTIFY P1234"), "spotify");
assert_eq!(merchant_key("ALBERT 1234 PRAHA 4 CZ"), "albert praha");
assert_eq!(merchant_key("Žabka"), "zabka");
assert_eq!(merchant_key("NETFLIX.COM"), "netflix com");
assert_eq!(merchant_key("SumUp *Kavárna Dobrá"), "kavarna dobra");
assert_eq!(merchant_key(" "), "");
assert_eq!(merchant_key("123 456"), "");
assert_eq!(merchant_key("Kč * "), "kc");
}
#[test]
fn compatibility() {
assert!(compatible("albert", "albert praha"));
assert!(compatible("albert praha", "albert brno"));
assert!(compatible("netflix com", "netflix"));
assert!(!compatible("lidl", "albert"));
assert!(!compatible("", "albert"));
assert!(!compatible("od praha", "od brno"), "a two-letter first word is not enough");
}
}
+143
View File
@@ -0,0 +1,143 @@
//! Money: whole haléře in an `i64`. Outflows are negative, as on a statement. Every operation is checked.
use serde::{Deserialize, Serialize};
use std::fmt;
/// An amount in haléře (1 CZK = 100 haléřů).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Haler(pub i64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum MoneyError {
#[error("the amount is too large")]
Overflow,
#[error("there is nobody to split between")]
NoWeight,
#[error("not an amount in CZK")]
NotAnAmount,
}
impl Haler {
pub const ZERO: Haler = Haler(0);
pub fn checked_add(self, other: Haler) -> Result<Haler, MoneyError> {
self.0.checked_add(other.0).map(Haler).ok_or(MoneyError::Overflow)
}
pub fn checked_sub(self, other: Haler) -> Result<Haler, MoneyError> {
self.0.checked_sub(other.0).map(Haler).ok_or(MoneyError::Overflow)
}
pub fn checked_neg(self) -> Result<Haler, MoneyError> {
self.0.checked_neg().map(Haler).ok_or(MoneyError::Overflow)
}
pub fn is_outflow(self) -> bool {
self.0 < 0
}
/// The sum, or `Overflow`. Integer addition is associative, so the order never matters.
pub fn sum<I: IntoIterator<Item = Haler>>(items: I) -> Result<Haler, MoneyError> {
items.into_iter().try_fold(Haler::ZERO, Haler::checked_add)
}
/// `-1 234,50`: a space between thousands, a decimal comma, always two decimals, no currency.
pub fn to_czk(self) -> String {
let neg = self.0 < 0;
let abs = self.0.unsigned_abs();
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 {
grouped.push(' ');
}
grouped.push(c);
}
format!("{}{},{:02}", if neg { "-" } else { "" }, grouped, abs % 100)
}
/// The inverse of [`Haler::to_czk`], also taking a plain `1234`, `1234,5` or `1234.50` as typed by hand.
/// Strict: one optional leading minus, ASCII digits, spaces only between groups of three, at most two
/// decimals after one `,` or `.`.
pub fn parse_czk(text: &str) -> Result<Haler, MoneyError> {
let t = text.trim();
let (neg, t) = match t.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, t),
};
let (int, frac) = match t.find([',', '.']) {
Some(i) => (&t[..i], Some(&t[i + 1..])),
None => (t, None),
};
let groups: Vec<&str> = int.split(' ').collect();
if groups.iter().any(|g| g.is_empty() || !g.bytes().all(|b| b.is_ascii_digit()))
|| groups.iter().skip(1).any(|g| g.len() != 3)
|| (groups.len() > 1 && groups[0].len() > 3)
{
return Err(MoneyError::NotAnAmount);
}
let digits: String = groups.concat();
let cents = match frac {
None => 0,
Some(f) if (1..=2).contains(&f.len()) && f.bytes().all(|b| b.is_ascii_digit()) => {
let v: i64 = f.parse().map_err(|_| MoneyError::NotAnAmount)?;
if f.len() == 1 {
v * 10
} else {
v
}
}
Some(_) => return Err(MoneyError::NotAnAmount),
};
let whole: i64 = digits.parse().map_err(|_| MoneyError::Overflow)?;
let abs = whole.checked_mul(100).and_then(|w| w.checked_add(cents)).ok_or(MoneyError::Overflow)?;
Ok(Haler(if neg { -abs } else { abs }))
}
}
impl fmt::Display for Haler {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} Kč", self.to_czk())
}
}
/// Splits `total` by `weights` so that the shares always sum to `total` exactly.
///
/// Largest remainder: each share is `floor(|total|·w/Σw)`; the haléře left over go one each to the largest
/// remainders, ties to the lower index. A negative total is split as its absolute value, then mirrored.
pub fn split(total: Haler, weights: &[u64]) -> Result<Vec<Haler>, MoneyError> {
let sum_w: u128 = weights.iter().map(|w| *w as u128).sum();
if sum_w == 0 {
return Err(MoneyError::NoWeight);
}
let abs = total.0.unsigned_abs() as u128;
let mut shares: Vec<u128> = Vec::with_capacity(weights.len());
let mut rems: Vec<(u128, usize)> = Vec::with_capacity(weights.len());
for (i, w) in weights.iter().enumerate() {
let num = abs * (*w as u128);
shares.push(num / sum_w);
rems.push((num % sum_w, i));
}
let given: u128 = shares.iter().sum();
let mut left = abs - given; // < weights.len()
// Largest remainder first; equal remainders by index.
rems.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
for (rem, i) in rems {
if left == 0 {
break;
}
if rem == 0 && weights[i] == 0 {
continue;
}
shares[i] += 1;
left -= 1;
}
shares
.into_iter()
.map(|s| {
let s = i64::try_from(s).map_err(|_| MoneyError::Overflow)?;
Ok(Haler(if total.0 < 0 { -s } else { s }))
})
.collect()
}
+439
View File
@@ -0,0 +1,439 @@
//! State = `apply()` folded over the log. Deterministic: every collection is ordered, nothing depends on a
//! clock or a hash seed, and `apply()` is total (an event that does not fit is recorded as rejected).
use crate::categories;
use crate::date::Date;
use crate::event::{BudgetId, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId};
use crate::import::StatementLine;
use crate::merchant::merchant_key;
use crate::money::Haler;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
const MAX_TEXT: usize = 500;
/// Where a payment record came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Origin {
Captured,
Imported,
Added,
}
/// What the app shows next to a payment: ○ captured, ● on a statement, ◆ added by hand.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Glyph {
Captured,
Confirmed,
Hand,
}
impl Glyph {
pub fn symbol(self) -> char {
match self {
Glyph::Captured => '○',
Glyph::Confirmed => '●',
Glyph::Hand => '◆',
}
}
}
/// A value and the position in the log that set it: the later one wins.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Stamped<T> {
pub seq: u64,
pub value: T,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaymentRecord {
pub id: PaymentId,
pub origin: Origin,
pub seq: u64,
pub amount: Haler,
pub date: Date,
pub merchant: String,
pub merchant_key: String,
pub card: Option<String>,
pub note: Option<String>,
pub line: Option<StatementLine>,
pub category: Option<Stamped<Category>>,
pub budget: Option<Stamped<BudgetId>>,
pub trial_ends: Option<Stamped<Date>>,
/// The other half of a confirmed pair.
pub partner: Option<PaymentId>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Budget {
pub id: BudgetId,
pub name: String,
pub limit: Haler,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rule {
pub id: RuleId,
pub category: Category,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DecisionRecord {
pub decision: Decision,
pub amount: Haler,
pub on: Date,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rejection {
pub event: EventId,
pub seq: u64,
pub reason: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct State {
/// Events seen, accepted or not.
pub seq: u64,
pub events: BTreeSet<EventId>,
pub payments: BTreeMap<PaymentId, PaymentRecord>,
pub line_keys: BTreeMap<String, PaymentId>,
pub budgets: BTreeMap<BudgetId, Budget>,
/// The first budget created: where a payment goes when nobody assigned it.
pub default_budget: Option<BudgetId>,
/// Merchant key → the latest rule for it.
pub rules: BTreeMap<String, Rule>,
/// Subscription key → its decisions, oldest first.
pub decisions: BTreeMap<String, Vec<DecisionRecord>>,
pub rejected: Vec<Rejection>,
}
/// Why a category is what it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CategorySource {
Explicit,
Rule,
None,
}
/// One payment as the user sees it: a confirmed pair is one payment.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EffectivePayment {
/// The captured or hand-added id when there is one (so a row keeps its id when confirmed), else the line's.
pub id: PaymentId,
pub captured: Option<PaymentId>,
pub line: Option<PaymentId>,
pub glyph: Glyph,
pub origin: Origin,
pub seq: u64,
pub amount: Haler,
pub date: Date,
pub merchant: String,
pub merchant_key: String,
pub card: Option<String>,
pub note: Option<String>,
pub counterparty: Option<String>,
pub variable_symbol: Option<String>,
pub message: Option<String>,
pub category: Option<Category>,
pub category_source: CategorySource,
pub budget: Option<BudgetId>,
pub trial_ends: Option<Date>,
}
fn text_ok(s: &str) -> bool {
s.chars().count() <= MAX_TEXT && !s.chars().any(|c| c.is_control())
}
fn opt_text_ok(s: &Option<String>) -> bool {
s.as_deref().is_none_or(text_ok)
}
fn latest<T: Clone>(a: &Option<Stamped<T>>, b: Option<&Option<Stamped<T>>>) -> Option<T> {
let b = b.and_then(|b| b.as_ref());
match (a.as_ref(), b) {
(Some(x), Some(y)) => Some(if x.seq >= y.seq { x.value.clone() } else { y.value.clone() }),
(Some(x), None) => Some(x.value.clone()),
(None, Some(y)) => Some(y.value.clone()),
(None, None) => None,
}
}
impl State {
pub fn replay<'a, I: IntoIterator<Item = &'a Event>>(log: I) -> State {
let mut s = State::default();
for e in log {
s.apply(e);
}
s
}
/// Applies one event. Never panics; an event that does not fit is recorded in `rejected`.
pub fn apply(&mut self, e: &Event) {
self.seq += 1;
let seq = self.seq;
if !self.events.insert(e.id.clone()) {
self.reject(e, "the same event twice");
return;
}
if let Err(reason) = self.try_apply(&e.body, seq) {
self.reject(e, reason);
}
}
fn reject(&mut self, e: &Event, reason: &str) {
self.rejected.push(Rejection { event: e.id.clone(), seq: self.seq, reason: reason.into() });
}
fn new_payment(&self, id: &PaymentId, amount: Haler) -> Result<(), &'static str> {
if id.is_empty() || id.len() > 100 {
return Err("a payment id must be 1-100 characters");
}
if self.payments.contains_key(id) {
return Err("a payment with this id exists");
}
if amount == Haler::ZERO {
return Err("a payment of zero");
}
Ok(())
}
fn payment_mut(&mut self, id: &PaymentId) -> Result<&mut PaymentRecord, &'static str> {
self.payments.get_mut(id).ok_or("no such payment")
}
fn try_apply(&mut self, body: &EventBody, seq: u64) -> Result<(), &'static str> {
match body {
EventBody::PaymentCaptured { payment, amount, date, merchant, card } => {
self.new_payment(payment, *amount)?;
if !text_ok(merchant) || !opt_text_ok(card) {
return Err("a text field is too long or has control characters");
}
self.payments.insert(
payment.clone(),
PaymentRecord {
id: payment.clone(),
origin: Origin::Captured,
seq,
amount: *amount,
date: *date,
merchant: merchant.clone(),
merchant_key: merchant_key(merchant),
card: card.clone(),
note: None,
line: None,
category: None,
budget: None,
trial_ends: None,
partner: None,
},
);
}
EventBody::PaymentImported { payment, line, line_key } => {
// A zero line (a card check) is still a line: allowed, unlike a zero capture.
self.new_payment(payment, Haler(1))?;
if line_key.is_empty() || self.line_keys.contains_key(line_key) {
return Err("this statement line was imported before");
}
if !line.is_clean() {
return Err("a text field is too long or has control characters");
}
self.line_keys.insert(line_key.clone(), payment.clone());
self.payments.insert(
payment.clone(),
PaymentRecord {
id: payment.clone(),
origin: Origin::Imported,
seq,
amount: line.amount,
date: line.booked,
merchant: line.merchant.clone(),
merchant_key: merchant_key(&line.merchant),
card: None,
note: None,
line: Some(line.clone()),
category: None,
budget: None,
trial_ends: None,
partner: None,
},
);
}
EventBody::PaymentAdded { payment, amount, date, merchant, category, note } => {
self.new_payment(payment, *amount)?;
if !text_ok(merchant) || !opt_text_ok(note) {
return Err("a text field is too long or has control characters");
}
if category.as_deref().is_some_and(|c| !categories::is_valid(c)) {
return Err("not a category id");
}
self.payments.insert(
payment.clone(),
PaymentRecord {
id: payment.clone(),
origin: Origin::Added,
seq,
amount: *amount,
date: *date,
merchant: merchant.clone(),
merchant_key: merchant_key(merchant),
card: None,
note: note.clone(),
line: None,
category: category.clone().map(|value| Stamped { seq, value }),
budget: None,
trial_ends: None,
partner: None,
},
);
}
EventBody::PaymentConfirmed { payment, line } => {
let p = self.payments.get(payment).ok_or("no such payment")?;
let l = self.payments.get(line).ok_or("no such statement line")?;
if p.origin == Origin::Imported || l.origin != Origin::Imported {
return Err("a confirmation ties a captured or hand-added payment to a statement line");
}
if p.partner.is_some() || l.partner.is_some() {
return Err("already confirmed");
}
if p.amount != l.amount {
return Err("the amounts differ");
}
self.payment_mut(payment)?.partner = Some(line.clone());
self.payment_mut(line)?.partner = Some(payment.clone());
}
EventBody::PaymentCategorised { payment, category } => {
if !categories::is_valid(category) {
return Err("not a category id");
}
self.payment_mut(payment)?.category = Some(Stamped { seq, value: category.clone() });
}
EventBody::PaymentAssigned { payment, budget } => {
if !self.budgets.contains_key(budget) {
return Err("no such budget");
}
self.payment_mut(payment)?.budget = Some(Stamped { seq, value: budget.clone() });
}
EventBody::PaymentTrialMarked { payment, ends } => {
self.payment_mut(payment)?.trial_ends = Some(Stamped { seq, value: *ends });
}
EventBody::BudgetCreated { budget, name, limit } => {
if budget.is_empty() || self.budgets.contains_key(budget) {
return Err("a budget with this id exists");
}
let name = name.trim();
if name.is_empty() || name.chars().count() > 60 || !text_ok(name) {
return Err("a budget name must be 1-60 characters");
}
if limit.0 < 0 {
return Err("a limit cannot be negative");
}
self.budgets.insert(budget.clone(), Budget { id: budget.clone(), name: name.into(), limit: *limit, seq });
if self.default_budget.is_none() {
self.default_budget = Some(budget.clone());
}
}
EventBody::BudgetLimitSet { budget, limit } => {
if limit.0 < 0 {
return Err("a limit cannot be negative");
}
self.budgets.get_mut(budget).ok_or("no such budget")?.limit = *limit;
}
EventBody::RuleCreated { rule, merchant_key: key, category } => {
if key.is_empty() || merchant_key(key) != *key {
return Err("not a merchant key");
}
if !categories::is_valid(category) {
return Err("not a category id");
}
self.rules.insert(key.clone(), Rule { id: rule.clone(), category: category.clone(), seq });
}
EventBody::SubscriptionDecided { subscription, decision, amount, on } => {
if subscription.is_empty() || !text_ok(subscription) {
return Err("not a subscription key");
}
if amount.0 < 0 {
return Err("a subscription's amount is a cost, not negative");
}
self.decisions
.entry(subscription.clone())
.or_default()
.push(DecisionRecord { decision: *decision, amount: *amount, on: *on, seq });
}
}
Ok(())
}
/// Every payment as the user sees it, a confirmed pair as one, in date order (then log order).
pub fn effective_payments(&self) -> Vec<EffectivePayment> {
let mut out: Vec<EffectivePayment> = self
.payments
.values()
.filter(|p| !(p.origin == Origin::Imported && p.partner.is_some()))
.map(|p| self.effective(p))
.collect();
out.sort_by(|a, b| a.date.cmp(&b.date).then(a.seq.cmp(&b.seq)));
out
}
/// The effective payment that contains `id` (either half of a pair).
pub fn effective_payment(&self, id: &str) -> Option<EffectivePayment> {
let p = self.payments.get(id)?;
let primary = match (&p.origin, &p.partner) {
(Origin::Imported, Some(partner)) => self.payments.get(partner)?,
_ => p,
};
Some(self.effective(primary))
}
fn effective(&self, p: &PaymentRecord) -> EffectivePayment {
let partner = p.partner.as_ref().and_then(|id| self.payments.get(id));
let line_rec = if p.origin == Origin::Imported { Some(p) } else { partner };
let line = line_rec.and_then(|r| r.line.as_ref());
let merchant = match line {
Some(l) if !l.merchant.trim().is_empty() => l.merchant.clone(),
_ => p.merchant.clone(),
};
let key = merchant_key(&merchant);
let explicit = latest(&p.category, partner.map(|q| &q.category));
let (category, category_source) = match explicit {
Some(c) => (Some(c), CategorySource::Explicit),
None => match self.rules.get(&key) {
Some(r) => (Some(r.category.clone()), CategorySource::Rule),
None => (None, CategorySource::None),
},
};
let budget = latest(&p.budget, partner.map(|q| &q.budget)).or_else(|| self.default_budget.clone());
EffectivePayment {
id: p.id.clone(),
captured: if p.origin == Origin::Imported { None } else { Some(p.id.clone()) },
line: line_rec.map(|r| r.id.clone()),
glyph: match (line_rec.is_some(), p.origin) {
(true, _) => Glyph::Confirmed,
(false, Origin::Added) => Glyph::Hand,
(false, _) => Glyph::Captured,
},
origin: p.origin,
seq: p.seq,
amount: line_rec.map(|r| r.amount).unwrap_or(p.amount),
date: line_rec.map(|r| r.date).unwrap_or(p.date),
merchant,
merchant_key: key,
card: p.card.clone(),
note: p.note.clone(),
counterparty: line.and_then(|l| l.counterparty.clone()),
variable_symbol: line.and_then(|l| l.variable_symbol.clone()),
message: line.and_then(|l| l.message.clone()),
category,
category_source,
budget,
trial_ends: latest(&p.trial_ends, partner.map(|q| &q.trial_ends)),
}
}
}