Files
FiscusPublic/crates/fiscus-ledger/src/invoice.rs
T

344 lines
13 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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>,
}
/// The language an invoice is printed in, chosen per invoice.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Language {
#[default]
Cs,
En,
}
#[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 the printed invoice is in. Absent in an event: Czech.
#[serde(default)]
pub language: Language,
}
/// 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);
}
}