//! 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, pub dic: Option, } 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, 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 { 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 { 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) } }