[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:
@@ -3,9 +3,10 @@
|
||||
|
||||
pub mod amount;
|
||||
pub mod notification;
|
||||
pub mod receipt;
|
||||
pub mod shortcut;
|
||||
|
||||
use fiscus_ledger::{Date, Haler, Timestamp};
|
||||
use fiscus_ledger::{Date, Haler, ReceiptInfo, Timestamp};
|
||||
|
||||
/// One card payment a phone saw: an outflow, so `amount` is negative.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -15,6 +16,8 @@ pub struct Capture {
|
||||
pub at: Timestamp,
|
||||
pub merchant: String,
|
||||
pub card: Option<String>,
|
||||
/// A receipt read on the phone (`"source": "receipt"`): the shop is the merchant, with its IČO and DIČ.
|
||||
pub receipt: Option<ReceiptInfo>,
|
||||
}
|
||||
|
||||
/// 1–200 characters, no control characters.
|
||||
|
||||
@@ -175,5 +175,5 @@ fn capture(fields: &Fields, date: Date, at: Timestamp) -> Option<Capture> {
|
||||
if card.is_some_and(|c| !card_ok(c)) {
|
||||
return None;
|
||||
}
|
||||
Some(Capture { amount, date, at, merchant: merchant.to_string(), card: card.filter(|c| !c.is_empty()).map(str::to_string) })
|
||||
Some(Capture { amount, date, at, merchant: merchant.to_string(), card: card.filter(|c| !c.is_empty()).map(str::to_string), receipt: None })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
//! A receipt's text as an OCR read it (lines of words, each with its box and confidence; docs/07_receipts.md).
|
||||
//! What every Czech receipt must show is found by its label, never by a shop's layout: the total (`Celkem`,
|
||||
//! `K úhradě`…), the date and time, the IČO (with its check digit) and DIČ, and the shop's name above them.
|
||||
//!
|
||||
//! Hostile input: bounded in size, control characters dropped, and a field is either read whole or not at all.
|
||||
//! A field read from words the OCR was not sure of is marked `sure: false`, for you to check; the shop's name is
|
||||
//! always to check. Amounts are read from their text into haléře, never through a float, and confidence is in
|
||||
//! thousandths.
|
||||
|
||||
use crate::amount;
|
||||
use fiscus_ledger::invoice::{dic_ok, ico_ok};
|
||||
use fiscus_ledger::{Date, Haler};
|
||||
|
||||
/// At most this many lines, words in a line, and characters in a word.
|
||||
pub const MAX_LINES: usize = 600;
|
||||
pub const MAX_WORDS: usize = 120;
|
||||
pub const MAX_WORD: usize = 80;
|
||||
/// A word read with at least this confidence (thousandths) counts as sure.
|
||||
pub const SURE: u16 = 800;
|
||||
|
||||
/// A box in the image's pixels (as the OCR gives it, upright).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct BBox {
|
||||
pub x: u32,
|
||||
pub y: u32,
|
||||
pub w: u32,
|
||||
pub h: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Word {
|
||||
pub text: String,
|
||||
/// 0-1000.
|
||||
pub confidence: u16,
|
||||
pub bbox: BBox,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Line {
|
||||
pub words: Vec<Word>,
|
||||
}
|
||||
|
||||
/// One field read, where it was on the image, and whether every word of it was read surely.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Field<T> {
|
||||
pub value: T,
|
||||
pub sure: bool,
|
||||
pub boxes: Vec<BBox>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Receipt {
|
||||
/// What was paid, positive.
|
||||
pub total: Option<Field<Haler>>,
|
||||
pub date: Option<Field<Date>>,
|
||||
/// Hours and minutes.
|
||||
pub time: Option<Field<(u8, u8)>>,
|
||||
pub shop: Option<Field<String>>,
|
||||
pub ico: Option<Field<String>>,
|
||||
pub dic: Option<Field<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ReceiptError {
|
||||
#[error("there is more text than a receipt holds")]
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
/// The labels of the total, best first: what is to pay beats a sum that might be before a discount.
|
||||
const TOTAL_LABELS: [(&str, u8); 9] = [
|
||||
("K UHRADE", 0),
|
||||
("CASTKA K UHRADE", 0),
|
||||
("CELKEM K UHRADE", 0),
|
||||
("CELKEM", 1),
|
||||
("CELKOVA CASTKA", 1),
|
||||
("CELKEM KC", 1),
|
||||
("CELKEM CZK", 1),
|
||||
("SUMA", 2),
|
||||
("TOTAL", 2),
|
||||
];
|
||||
/// A line with one of these is about VAT, a subtotal or rounding, never the total.
|
||||
const NOT_TOTAL: [&str; 6] = ["DPH", "ZAKLAD", "SAZBA", "MEZISOUCET", "ZAOKROUHLENI", "VRACENO"];
|
||||
|
||||
/// A word as it reads for matching labels: upper case, Czech letters without their marks, punctuation at the
|
||||
/// ends dropped.
|
||||
fn fold(s: &str) -> String {
|
||||
let up: String = s
|
||||
.chars()
|
||||
.flat_map(char::to_uppercase)
|
||||
.map(|c| match c {
|
||||
'Á' | 'Ä' => 'A',
|
||||
'Č' => 'C',
|
||||
'Ď' => 'D',
|
||||
'É' | 'Ě' => 'E',
|
||||
'Í' => 'I',
|
||||
'Ň' => 'N',
|
||||
'Ó' | 'Ö' => 'O',
|
||||
'Ř' => 'R',
|
||||
'Š' => 'S',
|
||||
'Ť' => 'T',
|
||||
'Ú' | 'Ů' | 'Ü' => 'U',
|
||||
'Ý' => 'Y',
|
||||
'Ž' => 'Z',
|
||||
c => c,
|
||||
})
|
||||
.collect();
|
||||
up.trim_matches(|c: char| !c.is_alphanumeric()).to_string()
|
||||
}
|
||||
|
||||
struct Prepared<'a> {
|
||||
words: Vec<&'a Word>,
|
||||
texts: Vec<String>,
|
||||
folded: Vec<String>,
|
||||
}
|
||||
|
||||
impl Prepared<'_> {
|
||||
fn sure(&self, idx: &[usize]) -> bool {
|
||||
idx.iter().all(|&i| self.words[i].confidence >= SURE)
|
||||
}
|
||||
fn boxes(&self, idx: &[usize]) -> Vec<BBox> {
|
||||
idx.iter().map(|&i| self.words[i].bbox).collect()
|
||||
}
|
||||
/// Where `label` (folded words) starts in this line, if it is there as whole words.
|
||||
fn find(&self, label: &str) -> Option<usize> {
|
||||
let want: Vec<&str> = label.split(' ').collect();
|
||||
(0..self.folded.len()).find(|&i| i + want.len() <= self.folded.len() && want.iter().enumerate().all(|(k, w)| self.folded[i + k] == *w))
|
||||
}
|
||||
}
|
||||
|
||||
/// The receipt's fields, as far as they can be read. Nothing found is an empty [`Receipt`], not an error.
|
||||
pub fn read(lines: &[Line]) -> Result<Receipt, ReceiptError> {
|
||||
if lines.len() > MAX_LINES || lines.iter().any(|l| l.words.len() > MAX_WORDS || l.words.iter().any(|w| w.text.chars().count() > MAX_WORD)) {
|
||||
return Err(ReceiptError::TooLarge);
|
||||
}
|
||||
let prepared: Vec<Prepared> = lines
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let words: Vec<&Word> = l.words.iter().filter(|w| !clean(&w.text).is_empty()).collect();
|
||||
let texts: Vec<String> = words.iter().map(|w| clean(&w.text)).collect();
|
||||
let folded = texts.iter().map(|t| fold(t)).collect();
|
||||
Prepared { words, texts, folded }
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut out = Receipt { total: total(&prepared), ..Default::default() };
|
||||
let (date, time) = date_time(&prepared);
|
||||
out.date = date;
|
||||
out.time = time;
|
||||
out.dic = dic(&prepared);
|
||||
let ico_line;
|
||||
(out.ico, ico_line) = ico(&prepared);
|
||||
if out.ico.is_none() {
|
||||
// A company's DIČ is CZ and its IČO.
|
||||
out.ico = out.dic.as_ref().filter(|d| d.value.len() == 10 && ico_ok(&d.value[2..])).map(|d| Field { value: d.value[2..].to_string(), sure: d.sure, boxes: d.boxes.clone() });
|
||||
}
|
||||
out.shop = shop(&prepared, ico_line);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The word's text without control characters, trimmed.
|
||||
fn clean(s: &str) -> String {
|
||||
s.chars().filter(|c| !c.is_control()).collect::<String>().trim().to_string()
|
||||
}
|
||||
|
||||
/// An amount written over words `i..=j`: `1 284,90`, `1284.90`, `-89,00` (a sign is ignored), with `Kč` after it
|
||||
/// dropped. Groups of three digits may be split over words. `Some(None)`: well formed, but not a payment Fiscus
|
||||
/// believes (over 10 000 000 Kč, or nothing); `None`: not an amount.
|
||||
fn amount_at(p: &Prepared, i: usize, j: usize) -> Option<Option<Haler>> {
|
||||
let text = p.texts[i..=j].join(" ");
|
||||
let t = text.trim_start_matches(['-', '−']).trim_end_matches(|c: char| c.is_alphabetic() || c == '.').trim();
|
||||
let (int, frac) = t.rsplit_once([',', '.'])?;
|
||||
if frac.len() != 2 || !frac.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let groups: Vec<&str> = int.split([' ', '.', '\u{a0}']).collect();
|
||||
let ok = if groups.len() == 1 {
|
||||
(1..=7).contains(&groups[0].len()) && groups[0].bytes().all(|b| b.is_ascii_digit())
|
||||
} else {
|
||||
(1..=3).contains(&groups[0].len()) && groups.iter().all(|g| g.bytes().all(|b| b.is_ascii_digit())) && groups[1..].iter().all(|g| g.len() == 3)
|
||||
};
|
||||
if !ok {
|
||||
return None;
|
||||
}
|
||||
Some(amount::parse_positive(&format!("{},{frac}", groups.concat())))
|
||||
}
|
||||
|
||||
/// The rightmost amount in a line from word `from` on, and the words it was written in.
|
||||
fn last_amount(p: &Prepared, from: usize) -> Option<(Haler, Vec<usize>)> {
|
||||
for j in (from..p.texts.len()).rev() {
|
||||
// The longest reading that ends at j, so "1 284,90" wins over "284,90"; and one too large is refused
|
||||
// whole, never read as its tail.
|
||||
if let Some((i, a)) = (j.saturating_sub(2).max(from)..=j).find_map(|i| amount_at(p, i, j).map(|a| (i, a))) {
|
||||
return a.map(|a| (a, (i..=j).collect()));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn total(lines: &[Prepared]) -> Option<Field<Haler>> {
|
||||
let mut best: Option<(u8, Field<Haler>)> = None;
|
||||
for (n, p) in lines.iter().enumerate() {
|
||||
if NOT_TOTAL.iter().any(|w| p.folded.iter().any(|f| f == w)) {
|
||||
continue;
|
||||
}
|
||||
let Some((rank, at, len)) = TOTAL_LABELS.iter().filter_map(|(l, r)| p.find(l).map(|at| (*r, at, l.split(' ').count()))).min_by_key(|(r, _, len)| (*r, usize::MAX - len)) else { continue };
|
||||
let label: Vec<usize> = (at..at + len).collect();
|
||||
// On the label's line, or alone on the next one.
|
||||
let found = last_amount(p, at + len).map(|(a, idx)| (a, idx, p)).or_else(|| {
|
||||
let next = lines.get(n + 1)?;
|
||||
let (a, idx) = last_amount(next, 0)?;
|
||||
(idx.len() == next.texts.len()).then_some((a, idx, next))
|
||||
});
|
||||
let Some((amount, idx, q)) = found else { continue };
|
||||
let field = Field { value: amount, sure: p.sure(&label) && q.sure(&idx), boxes: [p.boxes(&label), q.boxes(&idx)].concat() };
|
||||
let better = match &best {
|
||||
None => true,
|
||||
Some((r, f)) => rank < *r || (rank == *r && amount > f.value),
|
||||
};
|
||||
if better {
|
||||
best = Some((rank, field));
|
||||
}
|
||||
}
|
||||
best.map(|(_, f)| f)
|
||||
}
|
||||
|
||||
/// Digits only, if the text is digits (a stray `.` or `:` at the ends is dropped).
|
||||
fn digits(s: &str) -> Option<&str> {
|
||||
let d = s.trim_matches(|c: char| !c.is_ascii_alphanumeric());
|
||||
(!d.is_empty() && d.bytes().all(|b| b.is_ascii_digit())).then_some(d)
|
||||
}
|
||||
|
||||
/// A date in one word or over up to three (`16.11.2026`, `16. 11. 2026`, `16.11.26`, `2026-11-16`, `16/11/2026`).
|
||||
fn date_at(p: &Prepared, i: usize) -> Option<(Date, Vec<usize>)> {
|
||||
for len in 1..=3 {
|
||||
if i + len > p.texts.len() {
|
||||
break;
|
||||
}
|
||||
let text: String = p.texts[i..i + len].concat();
|
||||
let t = text.trim_end_matches('.');
|
||||
let parts: Vec<&str> = t.split(['.', '-', '/']).collect();
|
||||
if parts.len() != 3 || parts.iter().any(|x| x.is_empty() || !x.bytes().all(|b| b.is_ascii_digit())) {
|
||||
continue;
|
||||
}
|
||||
let n = |s: &str| s.parse::<u32>().ok();
|
||||
let (y, m, d) = if parts[0].len() == 4 {
|
||||
(n(parts[0])?, n(parts[1])?, n(parts[2])?)
|
||||
} else if parts[2].len() == 4 && parts[0].len() <= 2 && parts[1].len() <= 2 {
|
||||
(n(parts[2])?, n(parts[1])?, n(parts[0])?)
|
||||
} else if parts[2].len() == 2 && parts[0].len() <= 2 && parts[1].len() <= 2 {
|
||||
(2000 + n(parts[2])?, n(parts[1])?, n(parts[0])?)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if !(2000..=2100).contains(&y) {
|
||||
continue;
|
||||
}
|
||||
if let Some(date) = Date::from_ymd(y as i32, m, d) {
|
||||
return Some((date, (i..i + len).collect()));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `14:32` or `14:32:05` in one word.
|
||||
fn time_at(p: &Prepared, i: usize) -> Option<(u8, u8)> {
|
||||
let parts: Vec<&str> = p.texts[i].split(':').collect();
|
||||
if !(2..=3).contains(&parts.len()) || parts.iter().any(|x| x.len() != 2 || !x.bytes().all(|b| b.is_ascii_digit())) {
|
||||
return None;
|
||||
}
|
||||
let (h, m) = (parts[0].parse::<u8>().ok()?, parts[1].parse::<u8>().ok()?);
|
||||
(h <= 23 && m <= 59).then_some((h, m))
|
||||
}
|
||||
|
||||
type DateTime = (Option<Field<Date>>, Option<Field<(u8, u8)>>);
|
||||
|
||||
/// The date (one with a time on its line first), and the time on its line or anywhere.
|
||||
fn date_time(lines: &[Prepared]) -> DateTime {
|
||||
let mut first: Option<(Field<Date>, usize)> = None;
|
||||
for (n, p) in lines.iter().enumerate() {
|
||||
for i in 0..p.texts.len() {
|
||||
let Some((date, idx)) = date_at(p, i) else { continue };
|
||||
let field = Field { value: date, sure: p.sure(&idx), boxes: p.boxes(&idx) };
|
||||
if let Some(t) = (0..p.texts.len()).find_map(|k| time_at(p, k).map(|t| (t, k))) {
|
||||
let time = Field { value: t.0, sure: p.sure(&[t.1]), boxes: p.boxes(&[t.1]) };
|
||||
return (Some(field), Some(time));
|
||||
}
|
||||
if first.is_none() {
|
||||
first = Some((field, n));
|
||||
}
|
||||
}
|
||||
}
|
||||
let time = lines.iter().find_map(|p| (0..p.texts.len()).find_map(|k| time_at(p, k).map(|t| Field { value: t, sure: p.sure(&[k]), boxes: p.boxes(&[k]) })));
|
||||
(first.map(|(f, _)| f), time)
|
||||
}
|
||||
|
||||
/// The IČO after its label (`IČ`, `IČO`, `IČ:`), 8 digits with a check digit; and its line.
|
||||
fn ico(lines: &[Prepared]) -> (Option<Field<String>>, Option<usize>) {
|
||||
for (n, p) in lines.iter().enumerate() {
|
||||
for (i, f) in p.folded.iter().enumerate() {
|
||||
if f != "IC" && f != "ICO" {
|
||||
continue;
|
||||
}
|
||||
for k in i + 1..(i + 3).min(p.texts.len()) {
|
||||
if let Some(d) = digits(&p.texts[k]) {
|
||||
let value = format!("{d:0>8}");
|
||||
if d.len() <= 8 && ico_ok(&value) {
|
||||
return (Some(Field { value, sure: p.sure(&[i, k]), boxes: p.boxes(&[i, k]) }), Some(n));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(None, None)
|
||||
}
|
||||
|
||||
/// The DIČ: `CZ` and 8-10 digits, in one word or two (`CZ 25672541`).
|
||||
fn dic(lines: &[Prepared]) -> Option<Field<String>> {
|
||||
for p in lines {
|
||||
for i in 0..p.texts.len() {
|
||||
for len in 1..=2 {
|
||||
if i + len > p.texts.len() {
|
||||
break;
|
||||
}
|
||||
let t: String = p.texts[i..i + len].concat().trim_matches(|c: char| !c.is_ascii_alphanumeric()).to_uppercase();
|
||||
let t = t.strip_prefix("DIC:").unwrap_or(&t).to_string();
|
||||
if t.starts_with("CZ") && dic_ok(&t) {
|
||||
let idx: Vec<usize> = (i..i + len).collect();
|
||||
return Some(Field { value: t, sure: p.sure(&idx), boxes: p.boxes(&idx) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The shop's name: the first line from the top with three letters or more and no label of its own, above the
|
||||
/// IČO's line (or among the first six lines without one). All capitals become Title Case. Always to check.
|
||||
fn shop(lines: &[Prepared], ico_line: Option<usize>) -> Option<Field<String>> {
|
||||
let end = ico_line.unwrap_or(6).min(lines.len());
|
||||
const SKIP: [&str; 10] = ["IC", "ICO", "DIC", "TEL", "WWW", "EMAIL", "PROVOZOVNA", "ADRESA", "DANOVY", "UCTENKA"];
|
||||
for p in &lines[..end] {
|
||||
let letters = p.texts.iter().flat_map(|t| t.chars()).filter(|c| c.is_alphabetic()).count();
|
||||
let digits = p.texts.iter().flat_map(|t| t.chars()).filter(|c| c.is_ascii_digit()).count();
|
||||
if letters < 3 || digits * 2 > letters || p.folded.iter().any(|f| SKIP.contains(&f.as_str()) || f.contains('@') || f.starts_with("WWW") || f.starts_with("HTTP")) {
|
||||
continue;
|
||||
}
|
||||
let name: Vec<String> = p.texts.iter().map(|t| title(t)).collect();
|
||||
let value: String = name.join(" ").chars().take(fiscus_ledger::receipt::MAX_SHOP).collect::<String>().trim().to_string();
|
||||
if value.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let idx: Vec<usize> = (0..p.texts.len()).collect();
|
||||
return Some(Field { value, sure: false, boxes: p.boxes(&idx) });
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `ALBERT` → `Albert`; a word with lower case letters, or not all letters (`s.r.o.`, `4×3,90`), stays.
|
||||
fn title(w: &str) -> String {
|
||||
if w.chars().count() > 1 && w.chars().all(|c| c.is_alphabetic() && !c.is_lowercase()) {
|
||||
let mut c = w.chars();
|
||||
let first = c.next().map(|f| f.to_string()).unwrap_or_default();
|
||||
first + &c.as_str().to_lowercase()
|
||||
} else {
|
||||
w.to_string()
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
//! The iPhone Shortcut post (`POST /inbox`). We write the Shortcut, so the shape is ours:
|
||||
//! `{"amount", "merchant", "card", "time"}` and an optional `"currency": "CZK"`, nothing else.
|
||||
//! `{"amount", "merchant", "card", "time"}` and an optional `"currency": "CZK"`, nothing else. The Android app
|
||||
//! posts a receipt it read the same way, with `"source": "receipt"` and the shop's optional `"ico"` and `"dic"`
|
||||
//! (docs/07_receipts.md).
|
||||
|
||||
use crate::{amount, card_ok, merchant_ok, Capture};
|
||||
use fiscus_ledger::{Date, Timestamp};
|
||||
use fiscus_ledger::{Date, ReceiptInfo, Timestamp};
|
||||
use serde::Deserialize;
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
@@ -25,6 +27,10 @@ pub enum CaptureError {
|
||||
Card,
|
||||
#[error("the time is not ISO 8601 with an offset (2026-11-03T14:05:00+01:00)")]
|
||||
Time,
|
||||
#[error("the source is not receipt")]
|
||||
Source,
|
||||
#[error("an IČO or DIČ comes only with a receipt, and must be valid (8 digits with a check digit; CZ and 8-10 digits)")]
|
||||
Receipt,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -36,6 +42,9 @@ struct Post<'a> {
|
||||
card: String,
|
||||
time: String,
|
||||
currency: Option<String>,
|
||||
source: Option<String>,
|
||||
ico: Option<String>,
|
||||
dic: Option<String>,
|
||||
}
|
||||
|
||||
/// One post → one capture, or the first thing wrong with it.
|
||||
@@ -63,6 +72,16 @@ pub fn parse(body: &[u8]) -> Result<Capture, CaptureError> {
|
||||
return Err(CaptureError::Card);
|
||||
}
|
||||
let (date, at) = parse_time(&post.time).ok_or(CaptureError::Time)?;
|
||||
let receipt = match post.source.as_deref() {
|
||||
None if post.ico.is_none() && post.dic.is_none() => None,
|
||||
None => return Err(CaptureError::Receipt),
|
||||
Some("receipt") => {
|
||||
let info = ReceiptInfo { shop: post.merchant.trim().chars().take(fiscus_ledger::receipt::MAX_SHOP).collect::<String>().trim().to_string(), ico: post.ico, dic: post.dic };
|
||||
info.check().map_err(|_| CaptureError::Receipt)?;
|
||||
Some(info)
|
||||
}
|
||||
Some(_) => return Err(CaptureError::Source),
|
||||
};
|
||||
let card = post.card.trim();
|
||||
Ok(Capture {
|
||||
amount: amount.checked_neg().map_err(|_| CaptureError::Amount)?,
|
||||
@@ -70,6 +89,7 @@ pub fn parse(body: &[u8]) -> Result<Capture, CaptureError> {
|
||||
at,
|
||||
merchant: post.merchant.trim().to_string(),
|
||||
card: (!card.is_empty()).then(|| card.to_string()),
|
||||
receipt,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Receipts read from an OCR's lines (docs/07_receipts.md): the fields every Czech receipt shows, found by their
|
||||
//! labels; what to pay beats a sum before a discount; VAT lines are never the total; an IČO needs its check digit;
|
||||
//! unsure words are marked; hostile text is bounded and never panics. Synthetic text here: real receipts come as
|
||||
//! redacted OCR output in `fixtures/receipts/` (none yet).
|
||||
|
||||
use fiscus_capture::receipt::{read, BBox, Line, ReceiptError, Word, MAX_LINES};
|
||||
use fiscus_ledger::{Date, Haler};
|
||||
use proptest::prelude::*;
|
||||
|
||||
/// A receipt as text, one line per `\n`; a word ending in `?` was read with low confidence (and loses the `?`).
|
||||
fn page(text: &str) -> Vec<Line> {
|
||||
text.lines()
|
||||
.enumerate()
|
||||
.map(|(y, l)| Line {
|
||||
words: l
|
||||
.split_whitespace()
|
||||
.enumerate()
|
||||
.map(|(x, w)| {
|
||||
let (t, c) = match w.strip_suffix('?') {
|
||||
Some(t) if !t.is_empty() => (t, 420),
|
||||
_ => (w, 960),
|
||||
};
|
||||
Word { text: t.into(), confidence: c, bbox: BBox { x: x as u32 * 50, y: y as u32 * 20, w: 40, h: 16 } }
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
const ALBERT: &str = "ALBERT HYPERMARKET
|
||||
Praha 5
|
||||
IČ: 25672541 DIČ: CZ25672541
|
||||
Rohlík tukový 4×3,90 15,60
|
||||
Mléko polotučné 1 l 24,90
|
||||
Káva zrnková 1 kg 389,00
|
||||
CELKEM Kč 1 284,90
|
||||
Platba kartou 1 284,90
|
||||
DPH 12 % 137,67
|
||||
16.11.2026 14:32 Pokl. 07
|
||||
Děkujeme za nákup";
|
||||
|
||||
#[test]
|
||||
fn a_supermarket_receipt_gives_every_field() {
|
||||
let r = read(&page(ALBERT)).unwrap();
|
||||
let total = r.total.unwrap();
|
||||
assert_eq!((total.value, total.sure), (Haler(128_490), true));
|
||||
assert_eq!(total.boxes.len(), 4, "the label and the amount, over two words each");
|
||||
assert_eq!(r.date.unwrap().value, d("2026-11-16"));
|
||||
assert_eq!(r.time.unwrap().value, (14, 32));
|
||||
assert_eq!(r.ico.unwrap().value, "25672541");
|
||||
assert_eq!(r.dic.unwrap().value, "CZ25672541");
|
||||
let shop = r.shop.unwrap();
|
||||
assert_eq!((shop.value.as_str(), shop.sure), ("Albert Hypermarket", false), "the shop's name is always to check");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_to_pay_beats_a_sum_before_a_discount_and_vat_lines_are_never_the_total() {
|
||||
let r = read(&page("OBI\nIČO 25672541\nCELKEM 1 400,00\nSleva -115,10\nZáklad DPH 21 % 1 061,90\nK ÚHRADĚ 1 284,90\n2. 11. 2026")).unwrap();
|
||||
assert_eq!(r.total.unwrap().value, Haler(128_490));
|
||||
let r = read(&page("DPH celkem 223,00\nZaokrouhlení 0,10\nSUMA 89,90")).unwrap();
|
||||
assert_eq!(r.total.unwrap().value, Haler(8_990));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_amount_alone_on_the_line_after_its_label_counts() {
|
||||
let r = read(&page("CELKEM\n389,00\n16.11.2026")).unwrap();
|
||||
assert_eq!(r.total.unwrap().value, Haler(38_900));
|
||||
let r = read(&page("CELKEM\n2 ks 389,00")).unwrap();
|
||||
assert!(r.total.is_none(), "a next line that is more than an amount is not the total");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_read_without_confidence_marks_its_field() {
|
||||
let r = read(&page("CELKEM 1 284,90?\n16.11.2026? 14:32")).unwrap();
|
||||
assert!(!r.total.unwrap().sure);
|
||||
assert!(!r.date.unwrap().sure);
|
||||
assert!(r.time.unwrap().sure);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dates_in_the_ways_receipts_print_them() {
|
||||
for (text, want) in [("16. 11. 2026", "2026-11-16"), ("2026-11-16", "2026-11-16"), ("16.11.26", "2026-11-16"), ("1/2/2027", "2027-02-01"), ("Datum: 05.01.2027 08:15", "2027-01-05")] {
|
||||
assert_eq!(read(&page(text)).unwrap().date.map(|f| f.value), Some(d(want)), "{text}");
|
||||
}
|
||||
for text in ["31.02.2026", "16.11.1999", "16.13.2026", "1.2.3.4"] {
|
||||
assert!(read(&page(text)).unwrap().date.is_none(), "{text}");
|
||||
}
|
||||
assert_eq!(read(&page("Čas 25:61\n09:05")).unwrap().time.map(|f| f.value), Some((9, 5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ico_needs_its_check_digit_and_a_company_dic_gives_one() {
|
||||
assert!(read(&page("IČ: 25672542")).unwrap().ico.is_none(), "the check digit does not fit");
|
||||
assert_eq!(read(&page("IČO 2567254 1")).unwrap().ico, None, "split digits are not an IČO");
|
||||
let r = read(&page("DIČ: CZ 25672541")).unwrap();
|
||||
assert_eq!((r.dic.as_ref().unwrap().value.as_str(), r.ico.unwrap().value.as_str()), ("CZ25672541", "25672541"));
|
||||
let r = read(&page("DIČ: CZ7811241234")).unwrap();
|
||||
assert!(r.ico.is_none(), "a person's DIČ is a birth number, not an IČO");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shop_is_the_first_line_with_a_name_above_the_ico() {
|
||||
let r = read(&page("www.example.cz\n123 456\nLékárna U Anděla\nIČ 25672541\nCELKEM 189,00")).unwrap();
|
||||
assert_eq!(r.shop.unwrap().value, "Lékárna U Anděla");
|
||||
let r = read(&page("IČ 25672541\nZboží 189,00")).unwrap();
|
||||
assert!(r.shop.is_none(), "nothing above the IČO");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_to_go_on_is_an_empty_receipt_not_an_error() {
|
||||
assert_eq!(read(&[]).unwrap(), Default::default());
|
||||
let r = read(&page("Děkujeme za nákup\nNa shledanou")).unwrap();
|
||||
assert!(r.total.is_none() && r.date.is_none() && r.ico.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_text_is_bounded_and_control_characters_are_dropped() {
|
||||
let many: Vec<Line> = (0..=MAX_LINES).map(|_| Line::default()).collect();
|
||||
assert_eq!(read(&many), Err(ReceiptError::TooLarge));
|
||||
let long = vec![Line { words: vec![Word { text: "x".repeat(81), confidence: 900, bbox: BBox::default() }] }];
|
||||
assert_eq!(read(&long), Err(ReceiptError::TooLarge));
|
||||
let r = read(&page("CELKEM\u{7} 1\u{0} 284,90\nALB\u{1b}ERT")).unwrap();
|
||||
assert_eq!(r.total.unwrap().value, Haler(128_490));
|
||||
let r = read(&page("CELKEM 99 999 999,00")).unwrap();
|
||||
assert!(r.total.is_none(), "over the largest payment Fiscus believes");
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn any_text_reads_without_panicking_and_a_total_is_a_believable_payment(words in prop::collection::vec(prop::collection::vec("[ -~ÁČĎÉĚÍŇÓŘŠŤÚŮÝŽáčďéěíňóřšťúůýž×−]{0,12}", 0..12), 0..40)) {
|
||||
let lines: Vec<Line> = words.iter().map(|l| Line { words: l.iter().map(|t| Word { text: t.clone(), confidence: 900, bbox: BBox::default() }).collect() }).collect();
|
||||
if let Ok(r) = read(&lines) {
|
||||
if let Some(t) = r.total {
|
||||
prop_assert!(t.value.0 > 0 && t.value <= fiscus_capture::amount::MAX);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,3 +90,25 @@ proptest! {
|
||||
prop_assert!(parse(&full.as_bytes()[..cut]).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_receipt_read_on_the_phone_carries_its_shop_ico_and_dic_and_nothing_else_does() {
|
||||
let body = |extra: &str| format!(r#"{{"amount":"1 284,90","merchant":" Albert Hypermarket ","card":"","time":"2026-11-16T14:32:00+01:00"{extra}}}"#);
|
||||
let c = parse(body(r#","source":"receipt","ico":"25672541","dic":"CZ25672541""#).as_bytes()).unwrap();
|
||||
assert_eq!(c.amount, Haler(-128_490));
|
||||
assert_eq!(c.card, None);
|
||||
let r = c.receipt.unwrap();
|
||||
assert_eq!((r.shop.as_str(), r.ico.as_deref(), r.dic.as_deref()), ("Albert Hypermarket", Some("25672541"), Some("CZ25672541")));
|
||||
let c = parse(body(r#","source":"receipt""#).as_bytes()).unwrap();
|
||||
assert_eq!(c.receipt.unwrap().ico, None, "a receipt without an IČO is fine");
|
||||
assert_eq!(parse(post("129.5").as_bytes()).unwrap().receipt, None, "a card capture has no receipt");
|
||||
for (extra, why) in [
|
||||
(r#","ico":"25672541""#, CaptureError::Receipt),
|
||||
(r#","source":"receipt","ico":"25672542""#, CaptureError::Receipt),
|
||||
(r#","source":"receipt","dic":"SK2020123456""#, CaptureError::Receipt),
|
||||
(r#","source":"card""#, CaptureError::Source),
|
||||
(r#","source":"receipt","items":[]"#, CaptureError::Malformed),
|
||||
] {
|
||||
assert_eq!(parse(body(extra).as_bytes()), Err(why), "{extra}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user