[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:
@@ -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)),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user