[fiscus-capture] Receipts: the fields every Czech receipt shows, read from an OCR's words; payment.receipt_attached

fiscus_capture::receipt::read takes the OCR's lines (words with boxes and confidence in thousandths) and finds
the total, date and time, IČO (check digit), DIČ and the shop's name by their labels, never a shop's layout;
unsure words mark their field, the shop is always to check; bounded, control characters dropped, a proptest.
The phone's post takes a receipt (source receipt, ico, dic). The ledger gains payment.receipt_attached (the
payment keeps its merchant and key), known_shop and receipt_match (exactly one candidate or none).
docs/07_receipts.md; fixtures/receipts/ waits for redacted samples. v0.9.0.
This commit is contained in:
2026-11-17 19:40:08 +01:00
parent c6805aea8f
commit 507eb62216
17 changed files with 834 additions and 9 deletions
+4
View File
@@ -87,6 +87,10 @@ pub enum EventBody {
PaymentAssigned { payment: PaymentId, budget: BudgetId },
#[serde(rename = "payment.trial_marked")]
PaymentTrialMarked { payment: PaymentId, ends: Date },
/// A receipt for the payment: the shop's name you confirmed, its IČO and DIČ (docs/07_receipts.md). A later one
/// replaces it. The payment keeps its own merchant.
#[serde(rename = "payment.receipt_attached")]
ReceiptAttached { payment: PaymentId, receipt: crate::receipt::ReceiptInfo },
#[serde(rename = "budget.created")]
BudgetCreated { budget: BudgetId, name: String, limit: Haler },
/// A shared budget in a personal log (created here or joined): like `budget.created`, but never the
+2
View File
@@ -13,6 +13,7 @@ pub mod merchant;
pub mod money;
pub mod pay;
pub mod project;
pub mod receipt;
pub mod share;
pub mod split;
pub mod state;
@@ -20,4 +21,5 @@ pub mod state;
pub use date::{Date, Timestamp};
pub use event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, Settlement, SplitId};
pub use money::Haler;
pub use receipt::{KnownShop, ReceiptInfo};
pub use state::{EffectivePayment, Glyph, Origin, ShareView, State};
+78
View File
@@ -0,0 +1,78 @@
//! A receipt attached to a payment (`payment.receipt_attached`, docs/07_receipts.md): the shop's name as you
//! confirmed it, and its IČO and DIČ. The payment keeps its own merchant and merchant key (so the rules that bring
//! a category stay as they are); the receipt only adds what the shop is. Known shops and the payment a receipt
//! fills in are read from the state here, so the PC and the node decide alike.
use crate::date::Date;
use crate::event::{Category, PaymentId};
use crate::invoice::{dic_ok, ico_ok};
use crate::money::Haler;
use crate::state::State;
use serde::{Deserialize, Serialize};
/// The shop's name is 1-100 characters.
pub const MAX_SHOP: usize = 100;
/// A receipt fills in a payment of the same amount at most this many days before or after its date (a card
/// payment can be booked a few days later).
pub const MATCH_DAYS: i32 = 3;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReceiptInfo {
pub shop: String,
pub ico: Option<String>,
pub dic: Option<String>,
}
impl ReceiptInfo {
/// What the ledger accepts: a name without control characters, a valid IČO (with its check digit) and DIČ.
pub fn check(&self) -> Result<(), &'static str> {
let shop = self.shop.trim();
if shop.is_empty() || shop.chars().count() > MAX_SHOP || shop.chars().any(char::is_control) || shop != self.shop {
return Err("a shop's name must be 1-100 characters, trimmed, without control characters");
}
if self.ico.as_deref().is_some_and(|i| !ico_ok(i)) {
return Err("not a valid IČO (8 digits with a check digit)");
}
if self.dic.as_deref().is_some_and(|d| !dic_ok(d)) {
return Err("not a valid DIČ (CZ and 8-10 digits)");
}
Ok(())
}
}
/// What a shop's IČO brings from your earlier receipts: the name you confirmed last, and the category of that
/// payment.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KnownShop {
pub name: String,
pub category: Option<Category>,
pub payment: PaymentId,
}
impl State {
/// The shop of your latest receipt with this IČO, if any.
pub fn known_shop(&self, ico: &str) -> Option<KnownShop> {
self.effective_payments()
.into_iter()
.filter_map(|p| {
let r = p.receipt.as_ref()?;
(r.ico.as_deref() == Some(ico)).then(|| (p.receipt_seq, KnownShop { name: r.shop.clone(), category: p.category.clone(), payment: p.id.clone() }))
})
.max_by_key(|(seq, _)| *seq)
.map(|(_, k)| k)
}
/// The one payment a receipt of `total` (positive) on `date` fills in: an outflow of exactly that amount,
/// within [`MATCH_DAYS`], without a receipt yet. None when there is none, or more than one (then the receipt
/// is a payment of its own, and nothing is guessed).
pub fn receipt_match(&self, total: Haler, date: Date) -> Option<PaymentId> {
let amount = total.checked_neg().ok()?;
let mut found = self
.effective_payments()
.into_iter()
.filter(|p| p.amount == amount && p.receipt.is_none() && p.date.days_until(date).abs() <= MATCH_DAYS)
.map(|p| p.id);
let first = found.next()?;
found.next().is_none().then_some(first)
}
}
+17
View File
@@ -11,6 +11,7 @@ use crate::invoice::{Invoice, InvoiceId, Supplier, Totals};
use crate::merchant::merchant_key;
use crate::money::Haler;
use crate::pay::{spayd, Iban};
use crate::receipt::ReceiptInfo;
use crate::split::Share;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
@@ -67,6 +68,9 @@ pub struct PaymentRecord {
pub category: Option<Stamped<Category>>,
pub budget: Option<Stamped<BudgetId>>,
pub trial_ends: Option<Stamped<Date>>,
/// The receipt attached to it (docs/07_receipts.md).
#[serde(default)]
pub receipt: Option<Stamped<ReceiptInfo>>,
/// The other half of a confirmed pair.
pub partner: Option<PaymentId>,
}
@@ -272,6 +276,9 @@ pub struct EffectivePayment {
pub category_source: CategorySource,
pub budget: Option<BudgetId>,
pub trial_ends: Option<Date>,
/// The receipt attached to it, and when (its event's place in the log; 0 without one).
pub receipt: Option<ReceiptInfo>,
pub receipt_seq: u64,
}
/// A person's name, or one shared subscription name.
@@ -422,6 +429,7 @@ impl State {
category: None,
budget: None,
trial_ends: None,
receipt: None,
partner: None,
},
);
@@ -452,6 +460,7 @@ impl State {
category: None,
budget: None,
trial_ends: None,
receipt: None,
partner: None,
},
);
@@ -480,6 +489,7 @@ impl State {
category: category.clone().map(|value| Stamped { seq, value }),
budget: None,
trial_ends: None,
receipt: None,
partner: None,
},
);
@@ -514,6 +524,10 @@ impl State {
EventBody::PaymentTrialMarked { payment, ends } => {
self.payment_mut(payment)?.trial_ends = Some(Stamped { seq, value: *ends });
}
EventBody::ReceiptAttached { payment, receipt } => {
receipt.check()?;
self.payment_mut(payment)?.receipt = Some(Stamped { seq, value: receipt.clone() });
}
EventBody::BudgetCreated { budget, name, limit } | EventBody::BudgetShared { budget, name, limit } => {
if budget.is_empty() || self.budgets.contains_key(budget) {
return Err("a budget with this id exists");
@@ -595,6 +609,7 @@ impl State {
category: category.clone().map(|value| Stamped { seq, value }),
budget: Some(Stamped { seq, value: budget.clone() }),
trial_ends: None,
receipt: None,
partner: None,
},
);
@@ -1346,6 +1361,8 @@ impl State {
category_source,
budget,
trial_ends: latest(&p.trial_ends, partner.map(|q| &q.trial_ends)),
receipt_seq: [p.receipt.as_ref(), partner.and_then(|q| q.receipt.as_ref())].into_iter().flatten().map(|r| r.seq).max().unwrap_or(0),
receipt: latest(&p.receipt, partner.map(|q| &q.receipt)),
}
}
}
+111
View File
@@ -0,0 +1,111 @@
//! A receipt attached to a payment (`payment.receipt_attached`, docs/07_receipts.md): checked on the way in,
//! visible on the payment (either half of a confirmed pair), the latest one wins; a known shop comes from your
//! latest receipt with its IČO; a receipt fills in exactly one payment or none.
use fiscus_ledger::import::{plan_import, StatementLine};
use fiscus_ledger::{Category, Date, Event, EventBody, Haler, ReceiptInfo, State, Timestamp};
fn d(s: &str) -> Date {
s.parse().unwrap()
}
fn ev(id: &str, body: EventBody) -> Event {
Event::new(id, Timestamp(0), body)
}
fn added(id: &str, amount: i64, date: &str, merchant: &str) -> EventBody {
EventBody::PaymentAdded { payment: id.into(), amount: Haler(amount), date: d(date), merchant: merchant.into(), category: None, note: None }
}
fn captured(id: &str, amount: i64, date: &str) -> EventBody {
EventBody::PaymentCaptured { payment: id.into(), amount: Haler(amount), date: d(date), merchant: "ALBERT HM 4410".into(), card: None }
}
fn info(shop: &str, ico: Option<&str>) -> ReceiptInfo {
ReceiptInfo { shop: shop.into(), ico: ico.map(Into::into), dic: ico.map(|i| format!("CZ{i}")) }
}
fn attach(payment: &str, r: ReceiptInfo) -> EventBody {
EventBody::ReceiptAttached { payment: payment.into(), receipt: r }
}
fn state(bodies: Vec<EventBody>) -> State {
let mut s = State::default();
for (i, b) in bodies.into_iter().enumerate() {
s.apply(&ev(&format!("e{i}"), b));
}
s
}
#[test]
fn a_receipt_is_checked_and_sits_on_its_payment_which_keeps_its_merchant() {
let s = state(vec![captured("p1", -128_490, "2026-11-16"), attach("p1", info("Albert Hypermarket", Some("25672541")))]);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
let p = s.effective_payment("p1").unwrap();
assert_eq!(p.receipt.unwrap().shop, "Albert Hypermarket");
assert_eq!(p.merchant, "ALBERT HM 4410", "the merchant and its rules stay");
for (bad, why) in [
(attach("nope", info("A", None)), "no such payment"),
(attach("p1", info("", None)), "1-100 characters"),
(attach("p1", info(" Albert", None)), "trimmed"),
(attach("p1", info(&"x".repeat(101), None)), "1-100"),
(attach("p1", info("Albert", Some("25672542"))), "IČO"),
(attach("p1", ReceiptInfo { shop: "Albert".into(), ico: None, dic: Some("SK2020123456".into()) }), "DIČ"),
] {
let mut s = state(vec![captured("p1", -128_490, "2026-11-16")]);
let before = s.effective_payment("p1");
s.apply(&ev("bad", bad));
assert!(s.rejected.last().is_some_and(|r| r.reason.contains(why)), "{why}: {:?}", s.rejected);
assert_eq!(s.effective_payment("p1"), before, "a refusal changes nothing");
}
}
#[test]
fn on_a_confirmed_pair_the_receipt_shows_and_the_later_one_wins() {
let mut s = state(vec![captured("p1", -128_490, "2026-11-16"), attach("p1", info("Albert", Some("25672541")))]);
let line = StatementLine { bank: "test".into(), account: "1/0000".into(), booked: d("2026-11-17"), amount: Haler(-128_490), merchant: "ALBERT HM".into(), counterparty: None, variable_symbol: None, message: None, bank_ref: None };
let mut n = 0;
let plan = plan_import(&s, &[line], &mut || {
n += 1;
format!("i{n}")
}, Timestamp(1));
for e in plan.events.iter().chain(&plan.confirmations) {
s.apply(e);
}
let p = s.effective_payment("p1").unwrap();
assert!(p.line.is_some(), "confirmed by its line");
assert_eq!(p.receipt.as_ref().unwrap().shop, "Albert");
s.apply(&ev("later", attach("p1", info("Albert Hypermarket", Some("25672541")))));
assert_eq!(s.effective_payment("p1").unwrap().receipt.unwrap().shop, "Albert Hypermarket");
}
#[test]
fn a_known_shop_is_your_latest_receipt_with_its_ico() {
let s = state(vec![
added("a", -10_000, "2026-11-01", "x"),
EventBody::PaymentCategorised { payment: "a".into(), category: Category::from("groceries") },
attach("a", info("Albert", Some("25672541"))),
added("b", -20_000, "2026-11-05", "y"),
attach("b", info("Albert Hypermarket", Some("25672541"))),
added("c", -30_000, "2026-11-06", "z"),
attach("c", info("Lékárna", None)),
]);
let k = s.known_shop("25672541").unwrap();
assert_eq!((k.name.as_str(), k.payment.as_str()), ("Albert Hypermarket", "b"));
assert!(s.known_shop("61774031").is_none());
}
#[test]
fn a_receipt_fills_in_exactly_one_payment_or_none() {
let base = vec![captured("p1", -128_490, "2026-11-16"), added("p2", -128_490, "2026-11-30", "x"), added("p3", -9_900, "2026-11-16", "y")];
let s = state(base.clone());
assert_eq!(s.receipt_match(Haler(128_490), d("2026-11-18")).as_deref(), Some("p1"), "same amount, two days later");
assert_eq!(s.receipt_match(Haler(128_490), d("2026-11-20")), None, "four days is too far");
assert_eq!(s.receipt_match(Haler(128_400), d("2026-11-16")), None, "another amount");
let mut two = base.clone();
two.push(added("p4", -128_490, "2026-11-15", "z"));
assert_eq!(state(two).receipt_match(Haler(128_490), d("2026-11-16")), None, "two candidates: nothing guessed");
let mut done = base;
done.push(attach("p1", info("Albert", None)));
assert_eq!(state(done).receipt_match(Haler(128_490), d("2026-11-16")), None, "it has its receipt already");
}