[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
+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
}