[ledger] Invoices: supplier, invoice numbers as variable symbols, VAT per rate, paid by a matching statement line, the tax reserve; v0.4.0

This commit is contained in:
2026-11-05 14:44:22 +01:00
parent deb31374ea
commit 0068d4b69a
8 changed files with 886 additions and 5 deletions
+17
View File
@@ -2,6 +2,7 @@
use crate::date::{Date, Timestamp};
use crate::import::StatementLine;
use crate::invoice::{Invoice, InvoiceId, Supplier};
use crate::money::Haler;
use crate::split::Share;
use crate::state::Glyph;
@@ -141,4 +142,20 @@ pub enum EventBody {
/// author replaces the earlier ones; an empty list withdraws them.
#[serde(rename = "subscriptions.shared")]
SubscriptionsShared { budget: BudgetId, names: Vec<String> },
/// Who issues invoices from this ledger, and what share of each paid one is set aside for tax. The latest
/// counts from then on; an invoice keeps the supplier it was issued under.
#[serde(rename = "supplier.set")]
SupplierSet { supplier: Supplier },
#[serde(rename = "invoice.issued")]
InvoiceIssued { invoice: Invoice },
/// Paid: by `payment` (a statement line whose amount and variable symbol match), or marked paid by hand
/// (`None`: cash, another account). The reserve is set aside then.
#[serde(rename = "invoice.paid")]
InvoicePaid { invoice: InvoiceId, payment: Option<PaymentId>, on: Date },
/// Cancelled before it was paid.
#[serde(rename = "invoice.cancelled")]
InvoiceCancelled { invoice: InvoiceId },
/// Money taken out of the tax reserve (the tax or insurance paid from it).
#[serde(rename = "reserve.withdrawn")]
ReserveWithdrawn { withdrawal: String, amount: Haler, on: Date, note: String },
}
+331
View File
@@ -0,0 +1,331 @@
//! Invoices (faktury): the supplier, the customer, the lines and their totals, the number that is also the
//! variable symbol, and the tax reserve set aside when one is paid. Money in haléře; quantities in thousandths.
//!
//! - A line's amount is `quantity × unit price`, rounded half away from zero to the haléř.
//! - A VAT invoice (the supplier is a VAT payer): the base of each rate is the sum of its lines; the VAT of a rate
//! is `base × rate / 100`, rounded the same way, once per rate (§ 37 ZDPH: from the base, per rate).
//! - A non-VAT invoice has no rates, no taxable-supply date, and says the supplier is not a VAT payer.
//! - The number is `YYYYNNNN`: the year it was issued and the invoice's place in that year. The same digits are
//! the variable symbol, so a payment is matched by them.
use crate::date::{Date, Timestamp};
use crate::event::{Event, EventBody};
use crate::money::Haler;
use crate::pay::MAX_AMOUNT;
use crate::state::{CategorySource, EffectivePayment, InvoiceRecord, State};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
pub type InvoiceId = String;
/// The VAT rates in force in Czechia (from 2024): 21 %, 12 %, and 0 % for exempt supplies.
pub const VAT_RATES: [u8; 3] = [21, 12, 0];
/// At most this many lines on one invoice.
pub const MAX_LINES: usize = 50;
/// A quantity, in thousandths: from 0,001 to 1 000 000.
pub const MAX_QUANTITY: i64 = 1_000_000_000;
/// The share of a paid invoice set aside for tax, in thousandths: at most 60 %.
pub const MAX_RESERVE_PERMILLE: u16 = 600;
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum InvoiceError {
#[error("a name must be 1-100 characters")]
Name,
#[error("an address has 1-4 lines of at most 100 characters")]
Address,
#[error("not a valid IČO (8 digits with a check digit)")]
Ico,
#[error("not a valid DIČ (CZ and 8-10 digits)")]
Dic,
#[error("an invoice has 1-50 lines")]
Lines,
#[error("a line's text must be 1-200 characters, its unit at most 10")]
LineText,
#[error("a quantity is between 0,001 and 1 000 000")]
Quantity,
#[error("a unit price is between 0,01 and 9 999 999,99 CZK")]
Price,
#[error("a VAT rate is 21, 12 or 0 %")]
Rate,
#[error("a VAT invoice gives every line a rate; an invoice without VAT gives none")]
RateUse,
#[error("the total must be between 0,01 and 9 999 999,99 CZK")]
Total,
#[error("an invoice number is the year and 4 digits, e.g. 20260001")]
Number,
#[error("the due date is before the issue date")]
Due,
#[error("a VAT invoice needs the date of the taxable supply; one without VAT has none")]
Taxable,
#[error("a VAT payer has a DIČ")]
PayerDic,
#[error("the reserve is 0-60 %")]
Reserve,
}
/// Someone on an invoice: the supplier or the customer.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Party {
pub name: String,
/// Street, town and postcode, country: 1-4 lines.
pub address: Vec<String>,
pub ico: Option<String>,
pub dic: Option<String>,
}
/// The person issuing invoices from this ledger.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Supplier {
pub party: Party,
pub vat_payer: bool,
/// Of each paid invoice's amount without VAT, this many thousandths are set aside for income tax and
/// insurance (a VAT payer's VAT is always set aside in full, on top).
pub reserve_permille: u16,
/// A line printed on the invoice, such as the trade register entry. Optional.
pub registration: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvoiceLine {
pub text: String,
/// Thousandths: 1 500 is 1,5.
pub quantity: i64,
/// `ks`, `h`, …; may be empty.
pub unit: String,
/// Per unit, without VAT on a VAT invoice.
pub unit_price: Haler,
/// The VAT rate in percent on a VAT invoice; `None` on an invoice without VAT.
pub vat: Option<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Invoice {
pub id: InvoiceId,
/// `YYYYNNNN`, also the variable symbol.
pub number: String,
pub issued: Date,
pub due: Date,
/// The date of the taxable supply (DUZP), on a VAT invoice only.
pub taxable: Option<Date>,
pub customer: Party,
pub lines: Vec<InvoiceLine>,
/// The budget the payment goes into when it arrives; `None`: the default budget.
pub budget: Option<String>,
}
/// What an invoice adds up to.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Totals {
/// Each line's amount, in order.
pub lines: Vec<Haler>,
/// Rate → (base, VAT), highest rate first. Empty on an invoice without VAT.
pub rates: Vec<(u8, Haler, Haler)>,
/// Without VAT.
pub net: Haler,
pub vat: Haler,
/// What the customer pays.
pub total: Haler,
}
/// `a × b / d`, rounded half away from zero, or `None` when it does not fit an `i64`.
fn mul_div_round(a: i64, b: i64, d: i64) -> Option<i64> {
let n = i128::from(a) * i128::from(b);
let d = i128::from(d);
let q = n / d;
let r = n % d;
let q = if 2 * r.abs() >= d { q + n.signum() } else { q };
i64::try_from(q).ok()
}
fn text_ok(s: &str, min: usize, max: usize) -> bool {
let n = s.trim().chars().count();
(min..=max).contains(&n) && s.chars().count() <= max + 20 && !s.chars().any(|c| c.is_control())
}
/// An IČO: 8 digits whose last is the weighted mod-11 check of the first seven.
pub fn ico_ok(s: &str) -> bool {
if s.len() != 8 || !s.bytes().all(|b| b.is_ascii_digit()) {
return false;
}
let d: Vec<u32> = s.bytes().map(|b| u32::from(b - b'0')).collect();
let sum: u32 = (0..7).map(|i| d[i] * (8 - i as u32)).sum();
let check = (11 - sum % 11) % 10;
d[7] == check
}
/// A Czech DIČ: `CZ` and 8-10 digits.
pub fn dic_ok(s: &str) -> bool {
s.len() >= 10 && s.len() <= 12 && s.starts_with("CZ") && s[2..].bytes().all(|b| b.is_ascii_digit())
}
impl Party {
pub fn check(&self) -> Result<(), InvoiceError> {
if !text_ok(&self.name, 1, 100) {
return Err(InvoiceError::Name);
}
if self.address.is_empty() || self.address.len() > 4 || !self.address.iter().all(|l| text_ok(l, 1, 100)) {
return Err(InvoiceError::Address);
}
if self.ico.as_deref().is_some_and(|i| !ico_ok(i)) {
return Err(InvoiceError::Ico);
}
if self.dic.as_deref().is_some_and(|d| !dic_ok(d)) {
return Err(InvoiceError::Dic);
}
Ok(())
}
}
impl Supplier {
pub fn check(&self) -> Result<(), InvoiceError> {
self.party.check()?;
if self.vat_payer && self.party.dic.is_none() {
return Err(InvoiceError::PayerDic);
}
if self.reserve_permille > MAX_RESERVE_PERMILLE {
return Err(InvoiceError::Reserve);
}
if self.registration.as_deref().is_some_and(|r| !text_ok(r, 1, 200)) {
return Err(InvoiceError::Name);
}
Ok(())
}
/// What is set aside when an invoice with these totals is paid: all of its VAT, and the reserve share of
/// the rest.
pub fn reserve_for(&self, t: &Totals) -> Haler {
let share = mul_div_round(t.net.0, i64::from(self.reserve_permille), 1000).unwrap_or(0);
Haler(t.vat.0.saturating_add(share))
}
}
/// The amount of one line.
pub fn line_amount(quantity: i64, unit_price: Haler) -> Result<Haler, InvoiceError> {
if !(1..=MAX_QUANTITY).contains(&quantity) {
return Err(InvoiceError::Quantity);
}
if unit_price.0 <= 0 || unit_price > MAX_AMOUNT {
return Err(InvoiceError::Price);
}
mul_div_round(quantity, unit_price.0, 1000).map(Haler).ok_or(InvoiceError::Total)
}
/// The totals of `lines`, for a VAT payer or not. Checks every line.
pub fn totals(lines: &[InvoiceLine], vat_payer: bool) -> Result<Totals, InvoiceError> {
if lines.is_empty() || lines.len() > MAX_LINES {
return Err(InvoiceError::Lines);
}
let mut amounts = Vec::with_capacity(lines.len());
let mut bases: BTreeMap<u8, i64> = BTreeMap::new();
let mut net: i64 = 0;
for l in lines {
if !text_ok(&l.text, 1, 200) || !text_ok(&l.unit, 0, 10) {
return Err(InvoiceError::LineText);
}
match (vat_payer, l.vat) {
(true, Some(r)) if VAT_RATES.contains(&r) => {}
(true, Some(_)) => return Err(InvoiceError::Rate),
(false, None) => {}
_ => return Err(InvoiceError::RateUse),
}
let a = line_amount(l.quantity, l.unit_price)?;
amounts.push(a);
net = net.checked_add(a.0).ok_or(InvoiceError::Total)?;
if let Some(r) = l.vat {
let b = bases.entry(r).or_default();
*b = b.checked_add(a.0).ok_or(InvoiceError::Total)?;
}
}
let mut rates = Vec::new();
let mut vat: i64 = 0;
for (r, base) in bases.into_iter().rev() {
let v = mul_div_round(base, i64::from(r), 100).ok_or(InvoiceError::Total)?;
vat = vat.checked_add(v).ok_or(InvoiceError::Total)?;
rates.push((r, Haler(base), Haler(v)));
}
let total = net.checked_add(vat).ok_or(InvoiceError::Total)?;
if total <= 0 || Haler(total) > MAX_AMOUNT {
return Err(InvoiceError::Total);
}
Ok(Totals { lines: amounts, rates, net: Haler(net), vat: Haler(vat), total: Haler(total) })
}
/// The number of the `seq`-th invoice of `year`: `20260001`.
pub fn invoice_number(year: i32, seq: u32) -> Result<String, InvoiceError> {
if !(2000..=9999).contains(&year) || !(1..=9999).contains(&seq) {
return Err(InvoiceError::Number);
}
Ok(format!("{year}{seq:04}"))
}
impl Invoice {
/// Everything about the invoice that does not depend on the ledger; the totals when it is sound.
pub fn check(&self, supplier: &Supplier) -> Result<Totals, InvoiceError> {
let (year, _, _) = self.issued.ymd();
let n = &self.number;
if n.len() != 8 || !n.bytes().all(|b| b.is_ascii_digit()) || n[..4] != year.to_string() || &n[4..] == "0000" {
return Err(InvoiceError::Number);
}
if self.due < self.issued {
return Err(InvoiceError::Due);
}
if supplier.vat_payer != self.taxable.is_some() {
return Err(InvoiceError::Taxable);
}
self.customer.check()?;
totals(&self.lines, supplier.vat_payer)
}
}
/// A variable symbol as banks write it, compared without leading zeros (`0020260001` is `20260001`).
pub fn same_vs(a: &str, b: &str) -> bool {
let t = |s: &str| s.trim().trim_start_matches('0').to_string();
!t(a).is_empty() && t(a) == t(b)
}
/// The events that record invoices paid by statement lines. A line pays an unpaid invoice when its amount is the
/// invoice's total and its variable symbol is the invoice's number; the earliest such line wins, and a line pays
/// one invoice only. The line becomes income, in the invoice's budget. Nothing is guessed: a line of another
/// amount, or without the symbol, stays for the person to look at.
pub fn plan_invoice_payments(state: &State, ids: &mut dyn FnMut() -> String, at: Timestamp) -> Vec<Event> {
let mut open: Vec<&InvoiceRecord> = state.invoices.values().filter(|r| r.paid.is_none() && !r.cancelled).collect();
open.sort_by_key(|r| r.seq);
let lines: Vec<EffectivePayment> = state.effective_payments().into_iter().filter(|p| p.line.is_some() && p.amount.0 > 0).collect();
let mut taken: BTreeSet<String> = state.invoice_payments.keys().cloned().collect();
let mut out = Vec::new();
for r in open {
let found = lines.iter().find(|p| {
let line = p.line.as_deref().unwrap_or_default();
p.amount == r.totals.total
&& p.date >= r.invoice.issued
&& p.variable_symbol.as_deref().is_some_and(|vs| same_vs(vs, &r.invoice.number))
&& !taken.contains(line)
&& !taken.contains(&p.id)
});
let Some(p) = found else { continue };
let line = p.line.clone().unwrap_or_default();
taken.insert(line.clone());
taken.insert(p.id.clone());
out.push(Event::new(ids(), at, EventBody::InvoicePaid { invoice: r.invoice.id.clone(), payment: Some(line.clone()), on: p.date }));
if p.category_source != CategorySource::Explicit {
out.push(Event::new(ids(), at, EventBody::PaymentCategorised { payment: line.clone(), category: "income".into() }));
}
if let Some(b) = &r.invoice.budget {
out.push(Event::new(ids(), at, EventBody::PaymentAssigned { payment: line, budget: b.clone() }));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rounding_is_half_away_from_zero() {
assert_eq!(mul_div_round(1, 5, 10), Some(1));
assert_eq!(mul_div_round(1, 4, 10), Some(0));
assert_eq!(mul_div_round(-1, 5, 10), Some(-1));
assert_eq!(mul_div_round(i64::MAX, i64::MAX, 1), None);
}
}
+1
View File
@@ -6,6 +6,7 @@ pub mod categories;
pub mod date;
pub mod event;
pub mod import;
pub mod invoice;
pub mod matching;
pub mod merchant;
pub mod money;
+126
View File
@@ -5,6 +5,7 @@ use crate::categories;
use crate::date::Date;
use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId};
use crate::import::StatementLine;
use crate::invoice::{Invoice, InvoiceId, Supplier, Totals};
use crate::merchant::merchant_key;
use crate::money::Haler;
use crate::pay::{spayd, Iban};
@@ -142,6 +143,37 @@ pub struct ShareView {
pub spayd: Option<String>,
}
/// An issued invoice, its totals, and what became of it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvoiceRecord {
pub invoice: Invoice,
/// The supplier as it was when the invoice was issued.
pub supplier: Supplier,
pub totals: Totals,
pub paid: Option<Paid>,
pub cancelled: bool,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Paid {
/// The statement line that paid it; `None` when marked paid by hand.
pub payment: Option<PaymentId>,
pub on: Date,
/// Set aside for tax: the VAT, and the reserve share of the rest.
pub reserve: Haler,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Withdrawal {
pub id: String,
pub amount: Haler,
pub on: Date,
pub note: String,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rejection {
pub event: EventId,
@@ -175,6 +207,13 @@ pub struct State {
pub profile_name: Option<String>,
/// The shared budgets I share my subscription names with (`household.sharing_set`).
pub household_sharing: BTreeSet<BudgetId>,
pub supplier: Option<Supplier>,
pub invoices: BTreeMap<InvoiceId, InvoiceRecord>,
/// Invoice number → invoice.
pub invoice_numbers: BTreeMap<String, InvoiceId>,
/// A statement line → the invoice it paid.
pub invoice_payments: BTreeMap<PaymentId, InvoiceId>,
pub withdrawals: Vec<Withdrawal>,
pub rejected: Vec<Rejection>,
}
@@ -618,6 +657,68 @@ impl State {
return Err("a name must be 1-40 characters");
}
}
EventBody::SupplierSet { supplier } => {
supplier.check().map_err(|_| "not a valid supplier")?;
self.supplier = Some(supplier.clone());
}
EventBody::InvoiceIssued { invoice } => {
let supplier = self.supplier.clone().ok_or("set the supplier before issuing an invoice")?;
if !id_ok(&invoice.id) || self.invoices.contains_key(&invoice.id) {
return Err("an invoice with this id exists");
}
if self.invoice_numbers.contains_key(&invoice.number) {
return Err("an invoice with this number exists");
}
if invoice.budget.as_ref().is_some_and(|b| !self.budgets.contains_key(b)) {
return Err("no such budget");
}
let totals = invoice.check(&supplier).map_err(|_| "not a valid invoice")?;
self.invoice_numbers.insert(invoice.number.clone(), invoice.id.clone());
self.invoices.insert(invoice.id.clone(), InvoiceRecord { invoice: invoice.clone(), supplier, totals, paid: None, cancelled: false, seq });
}
EventBody::InvoicePaid { invoice, payment, on } => {
let rec = self.invoices.get(invoice).ok_or("no such invoice")?;
if rec.cancelled || rec.paid.is_some() {
return Err("the invoice is cancelled or paid already");
}
if *on < rec.invoice.issued {
return Err("paid before it was issued");
}
if let Some(p) = payment {
if self.invoice_payments.contains_key(p) {
return Err("this payment paid another invoice");
}
let e = self.effective_payment(p).ok_or("no such payment")?;
if e.line.is_none() || e.amount != rec.totals.total {
return Err("the payment is not a statement line of the invoice's amount");
}
}
let reserve = rec.supplier.reserve_for(&rec.totals);
if let Some(p) = payment {
self.invoice_payments.insert(p.clone(), invoice.clone());
}
let rec = self.invoices.get_mut(invoice).ok_or("no such invoice")?;
rec.paid = Some(Paid { payment: payment.clone(), on: *on, reserve, seq });
}
EventBody::InvoiceCancelled { invoice } => {
let rec = self.invoices.get_mut(invoice).ok_or("no such invoice")?;
if rec.paid.is_some() || rec.cancelled {
return Err("only an unpaid invoice can be cancelled");
}
rec.cancelled = true;
}
EventBody::ReserveWithdrawn { withdrawal, amount, on, note } => {
if !id_ok(withdrawal) || self.withdrawals.iter().any(|w| &w.id == withdrawal) {
return Err("a withdrawal with this id exists");
}
if amount.0 <= 0 || *amount > self.reserve_balance() {
return Err("more than the reserve holds");
}
if note.chars().count() > 200 || !text_ok(note) {
return Err("a note is at most 200 characters");
}
self.withdrawals.push(Withdrawal { id: withdrawal.clone(), amount: *amount, on: *on, note: note.clone(), seq });
}
EventBody::SubscriptionsShared { budget, names } => {
if !self.budgets.contains_key(budget) {
return Err("no such budget");
@@ -636,6 +737,31 @@ impl State {
Ok(())
}
/// What the tax reserve holds: everything set aside for paid invoices, less what was taken out.
pub fn reserve_balance(&self) -> Haler {
let set: i64 = self.invoices.values().filter_map(|r| r.paid.as_ref()).map(|p| p.reserve.0).fold(0, i64::saturating_add);
let out: i64 = self.withdrawals.iter().map(|w| w.amount.0).fold(0, i64::saturating_add);
Haler(set.saturating_sub(out))
}
/// The number the next invoice issued in `year` gets.
pub fn next_invoice_number(&self, year: i32) -> Option<String> {
let prefix = year.to_string();
let last = self.invoice_numbers.keys().filter(|n| n.starts_with(&prefix)).filter_map(|n| n[4..].parse::<u32>().ok()).max().unwrap_or(0);
crate::invoice::invoice_number(year, last + 1).ok()
}
/// QR Platba for an unpaid invoice: its total, its number as the variable symbol, to the account set.
pub fn invoice_spayd(&self, invoice: &str) -> Option<String> {
let r = self.invoices.get(invoice)?;
if r.paid.is_some() || r.cancelled {
return None;
}
let a = self.account.as_ref()?;
let iban = Iban::parse(&a.iban).ok()?;
spayd(&iban, r.totals.total, Some(&a.name), &format!("Faktura {}", r.invoice.number), Some(&r.invoice.number)).ok()
}
/// Whether a phone's capture token (its SHA-256 in hex) may post captures.
pub fn capture_token_active(&self, token: &str) -> bool {
self.capture_tokens.get(token).is_some_and(|t| !t.revoked)