Files
FiscusPublic/crates/fiscus-ledger/tests/invoices.rs
T

366 lines
18 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 (v1.1): the totals to the haléř with and without VAT, the number that is the variable symbol, a paid
//! invoice found on a statement and landing in its budget with the reserve set aside, and everything hostile or
//! inconsistent refused.
use fiscus_ledger::import::StatementLine;
use fiscus_ledger::invoice::{dic_ok, ico_ok, invoice_number, line_amount, plan_invoice_payments, same_vs, totals, Invoice, InvoiceError, InvoiceLine, Language, Party, Supplier};
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
fn d(s: &str) -> Date {
s.parse().unwrap()
}
struct Ids(u64);
impl Ids {
fn next(&mut self) -> String {
self.0 += 1;
format!("id{:04}", self.0)
}
}
fn ev(ids: &mut Ids, body: EventBody) -> Event {
Event::new(ids.next(), Timestamp(0), body)
}
fn party(name: &str) -> Party {
Party { name: name.into(), address: vec!["Dlouhá 1".into(), "110 00 Praha 1".into()], ico: Some("45244782".into()), dic: None }
}
fn supplier(vat_payer: bool, reserve_permille: u16) -> Supplier {
let mut p = party("Marek Novák");
p.ico = Some("27074358".into());
p.dic = vat_payer.then(|| "CZ8001011234".into());
Supplier { party: p, vat_payer, reserve_permille, registration: Some("Fyzická osoba zapsaná v živnostenském rejstříku.".into()) }
}
fn line(text: &str, quantity: i64, price: i64, vat: Option<u8>) -> InvoiceLine {
InvoiceLine { text: text.into(), quantity, unit: "h".into(), unit_price: Haler(price), vat }
}
fn invoice(id: &str, number: &str, issued: &str, lines: Vec<InvoiceLine>, vat: bool) -> Invoice {
Invoice {
id: id.into(),
number: number.into(),
issued: d(issued),
due: d(issued).add_days(14),
taxable: vat.then(|| d(issued)),
customer: party("Odběratel s.r.o."),
lines,
budget: None,
language: Language::Cs,
}
}
fn imported(ids: &mut Ids, amount: i64, booked: &str, vs: Option<&str>) -> (Event, String) {
let payment = ids.next();
let line = StatementLine {
bank: "test".into(),
account: "1".into(),
booked: d(booked),
amount: Haler(amount),
merchant: "Odběratel s.r.o.".into(),
counterparty: Some("123/0100".into()),
variable_symbol: vs.map(Into::into),
message: None,
bank_ref: Some(payment.clone()),
};
(ev(ids, EventBody::PaymentImported { payment: payment.clone(), line, line_key: format!("test|1|{payment}") }), payment)
}
fn apply(state: &mut State, events: &[Event]) {
for e in events {
state.apply(e);
}
}
#[test]
fn ico_and_dic_are_checked() {
assert!(ico_ok("45244782")); // Česká spořitelna
assert!(ico_ok("27074358"));
assert!(!ico_ok("45244783"));
assert!(!ico_ok("4524478"));
assert!(!ico_ok("4524478a"));
assert!(dic_ok("CZ45244782") && dic_ok("CZ8001011234"));
assert!(!dic_ok("SK45244782") && !dic_ok("CZ1234567") && !dic_ok("CZ1234567890123"));
}
#[test]
fn an_invoice_without_vat_adds_up_to_the_haler() {
let t = totals(&[line("Konzultace", 1_500, 120_000, None), line("Licence", 3_000, 33_333, None)], false).unwrap();
assert_eq!(t.lines, vec![Haler(180_000), Haler(99_999)]);
assert_eq!((t.net, t.vat, t.total), (Haler(279_999), Haler(0), Haler(279_999)));
assert!(t.rates.is_empty());
// 0,333 h at 1 000 Kč is 333,00; at 1 000,05 Kč 333,016… → 333,02. Rounded half away from zero.
assert_eq!(line_amount(333, Haler(100_000)).unwrap(), Haler(33_300));
assert_eq!(line_amount(333, Haler(100_005)).unwrap(), Haler(33_302));
assert_eq!(line_amount(1, Haler(50)).unwrap(), Haler(0), "0,0005 Kč is nothing");
assert_eq!(line_amount(500, Haler(1)).unwrap(), Haler(1), "0,005 Kč rounds up to 0,01");
}
#[test]
fn a_vat_invoice_computes_vat_once_per_rate_from_its_base() {
let t = totals(&[line("Vývoj", 10_000, 100_000, Some(21)), line("Kniha", 1_000, 100_000, Some(12)), line("Vývoj", 1_000, 3, Some(21)), line("Pojištění", 1_000, 5_000, Some(0))], true).unwrap();
// 21 %: base 10 000,03 → VAT 2 100,0063 → 2 100,01; 12 %: 1 000 → 120; 0 %: 50 → 0.
assert_eq!(t.rates, vec![(21, Haler(1_000_003), Haler(210_001)), (12, Haler(100_000), Haler(12_000)), (0, Haler(5_000), Haler(0))]);
assert_eq!((t.net, t.vat, t.total), (Haler(1_105_003), Haler(222_001), Haler(1_327_004)));
// Per rate, not per line: three lines of 0,05 at 21 % are 0,15 → 0,03 VAT (per line it would be 3 × 0,01).
let t = totals(&[line("a", 1_000, 5, Some(21)), line("b", 1_000, 5, Some(21)), line("c", 1_000, 5, Some(21))], true).unwrap();
assert_eq!(t.vat, Haler(3));
}
#[test]
fn bad_lines_are_refused() {
let ok = line("Práce", 1_000, 100_000, None);
assert_eq!(totals(&[], false), Err(InvoiceError::Lines));
assert_eq!(totals(&vec![ok.clone(); 51], false), Err(InvoiceError::Lines));
assert_eq!(totals(&[line("Práce", 0, 100, None)], false), Err(InvoiceError::Quantity));
assert_eq!(totals(&[line("Práce", 1_000, 0, None)], false), Err(InvoiceError::Price));
assert_eq!(totals(&[line("Práce", 1_000, -100, None)], false), Err(InvoiceError::Price));
assert_eq!(totals(&[line("", 1_000, 100, None)], false), Err(InvoiceError::LineText));
assert_eq!(totals(&[line("A\u{0}B", 1_000, 100, None)], false), Err(InvoiceError::LineText));
assert_eq!(totals(&[line("Práce", 1_000, 100, Some(21))], false), Err(InvoiceError::RateUse), "a rate without being a VAT payer");
assert_eq!(totals(&[line("Práce", 1_000, 100, None)], true), Err(InvoiceError::RateUse), "a VAT invoice line without a rate");
assert_eq!(totals(&[line("Práce", 1_000, 100, Some(15))], true), Err(InvoiceError::Rate));
// Over what QR Platba and a statement can carry.
assert_eq!(totals(&[line("Práce", 1_000_000_000, 999_999_999, None)], false), Err(InvoiceError::Total));
assert_eq!(totals(&[line("Práce", 2_000, 999_999_999, None)], false), Err(InvoiceError::Total));
}
#[test]
fn numbers_are_the_year_and_a_sequence_and_the_variable_symbol() {
assert_eq!(invoice_number(2026, 1).unwrap(), "20260001");
assert_eq!(invoice_number(2026, 0), Err(InvoiceError::Number));
assert_eq!(invoice_number(2026, 10_000), Err(InvoiceError::Number));
assert!(same_vs("0020260001", "20260001") && same_vs(" 20260001 ", "20260001"));
assert!(!same_vs("20260002", "20260001") && !same_vs("", "") && !same_vs("000", "0"));
let mut ids = Ids(0);
let mut s = State::default();
assert_eq!(s.next_invoice_number(2026).as_deref(), Some("20260001"));
let events = [
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-03-01", vec![line("Práce", 1_000, 100_000, None)], false) }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i2", "20260002", "2026-04-01", vec![line("Práce", 1_000, 100_000, None)], false) }),
];
apply(&mut s, &events);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
assert_eq!(s.next_invoice_number(2026).as_deref(), Some("20260003"));
assert_eq!(s.next_invoice_number(2027).as_deref(), Some("20270001"), "each year starts again");
}
#[test]
fn an_invoice_that_does_not_fit_is_rejected_and_changes_nothing() {
let mut ids = Ids(0);
let mut s = State::default();
let good = || invoice("i1", "20260001", "2026-03-01", vec![line("Práce", 1_000, 100_000, None)], false);
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: good() })]);
assert_eq!(s.rejected.len(), 1, "no supplier yet");
apply(&mut s, &[ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) })]);
let mut cases: Vec<Invoice> = Vec::new();
let mut i = good();
i.number = "20250001".into(); // not this year's
cases.push(i);
let mut i = good();
i.number = "20260000".into();
cases.push(i);
let mut i = good();
i.number = "2026001".into();
cases.push(i);
let mut i = good();
i.due = d("2026-02-28");
cases.push(i);
let mut i = good();
i.taxable = Some(d("2026-03-01")); // a DUZP without being a VAT payer
cases.push(i);
let mut i = good();
i.customer.ico = Some("12345678".into());
cases.push(i);
let mut i = good();
i.customer.name = "X\u{7}".into();
cases.push(i);
let mut i = good();
i.customer.address = vec![];
cases.push(i);
let mut i = good();
i.budget = Some("no-such".into());
cases.push(i);
let before = s.rejected.len();
for c in cases.iter().cloned() {
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: c })]);
}
assert_eq!(s.rejected.len() - before, cases.len());
assert!(s.invoices.is_empty() && s.invoice_numbers.is_empty());
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: good() })]);
let mut again = good();
again.id = "i2".into();
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: again })]);
assert_eq!(s.invoices.len(), 1, "a number is used once");
// A VAT payer without a DIČ, a reserve over 60 %.
let mut no_dic = supplier(true, 150);
no_dic.party.dic = None;
let before = s.rejected.len();
apply(&mut s, &[ev(&mut ids, EventBody::SupplierSet { supplier: no_dic }), ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 601) })]);
assert_eq!(s.rejected.len() - before, 2);
assert_eq!(s.supplier, Some(supplier(false, 150)));
}
#[test]
fn a_paid_invoice_lands_in_its_budget_with_the_reserve_set_aside_untouched() {
let mut ids = Ids(0);
let mut s = State::default();
let mut inv = invoice("i1", "20260001", "2026-03-01", vec![line("Konzultace", 10_000, 150_000, None)], false);
inv.budget = Some("home".into());
apply(
&mut s,
&[
ev(&mut ids, EventBody::BudgetCreated { budget: "home".into(), name: "Home".into(), limit: Haler(3_000_000) }),
ev(&mut ids, EventBody::AccountSet { iban: "CZ6508000000192000145399".into(), name: "Marek Novak".into() }),
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: inv }),
],
);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
assert_eq!(s.invoices["i1"].totals.total, Haler(1_500_000));
let qr = s.invoice_spayd("i1").unwrap();
assert!(qr.contains("*AM:15000.00*") && qr.contains("*X-VS:20260001") && qr.contains("*MSG:Faktura 20260001"), "{qr}");
// The statement brings three lines: the wrong amount, no symbol, and the payment (the bank pads the symbol).
let (wrong, _) = imported(&mut ids, 1_400_000, "2026-03-10", Some("20260001"));
let (nosym, _) = imported(&mut ids, 1_500_000, "2026-03-11", None);
let (right, paid_by) = imported(&mut ids, 1_500_000, "2026-03-12", Some("0020260001"));
apply(&mut s, &[wrong, nosym, right]);
let plan = plan_invoice_payments(&s, &mut || ids.next(), Timestamp(0));
let kinds: Vec<String> = plan.iter().map(|e| format!("{:?}", e.body).split_whitespace().next().unwrap().to_string()).collect();
assert_eq!(kinds, vec!["InvoicePaid", "PaymentCategorised", "PaymentAssigned"]);
apply(&mut s, &plan);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
let paid = s.invoices["i1"].paid.clone().unwrap();
assert_eq!((paid.payment.as_deref(), paid.on), (Some(paid_by.as_str()), d("2026-03-12")));
assert_eq!(paid.reserve, Haler(225_000), "15 % of 15 000 Kč");
assert_eq!(s.reserve_balance(), Haler(225_000));
let p = s.effective_payment(&paid_by).unwrap();
assert_eq!((p.category.as_deref(), p.budget.as_deref()), (Some("income"), Some("home")));
assert_eq!(s.invoice_spayd("i1"), None, "no QR for a paid invoice");
// Planning again finds nothing: paid once.
assert!(plan_invoice_payments(&s, &mut || ids.next(), Timestamp(0)).is_empty());
// The reserve pays the tax: no more than it holds.
let before = s.rejected.len();
apply(&mut s, &[ev(&mut ids, EventBody::ReserveWithdrawn { withdrawal: "w1".into(), amount: Haler(225_001), on: d("2027-03-31"), note: "Daň z příjmů".into() })]);
assert_eq!(s.rejected.len() - before, 1);
apply(&mut s, &[ev(&mut ids, EventBody::ReserveWithdrawn { withdrawal: "w1".into(), amount: Haler(200_000), on: d("2027-03-31"), note: "Daň z příjmů".into() })]);
assert_eq!(s.reserve_balance(), Haler(25_000), "{:?}", s.rejected);
}
#[test]
fn a_vat_payer_sets_aside_all_the_vat_and_the_share_of_the_rest() {
let mut ids = Ids(0);
let mut s = State::default();
apply(
&mut s,
&[
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(true, 100) }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-03-01", vec![line("Vývoj", 10_000, 100_000, Some(21))], true) }),
],
);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
assert_eq!(s.invoices["i1"].totals.total, Haler(1_210_000));
apply(&mut s, &[ev(&mut ids, EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-03-05") })]);
// VAT 2 100 Kč, and 10 % of 10 000 Kč.
assert_eq!(s.reserve_balance(), Haler(310_000));
// A later change of the supplier does not change an invoice issued before it.
apply(&mut s, &[ev(&mut ids, EventBody::SupplierSet { supplier: supplier(true, 300) })]);
assert_eq!(s.invoices["i1"].supplier.reserve_permille, 100);
}
#[test]
fn a_payment_pays_one_invoice_once_and_only_its_own_amount() {
let mut ids = Ids(0);
let mut s = State::default();
let one = |id: &str, n: &str| invoice(id, n, "2026-03-01", vec![line("Práce", 1_000, 100_000, None)], false);
apply(
&mut s,
&[
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: one("i1", "20260001") }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: one("i2", "20260002") }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: one("i3", "20260003") }),
],
);
let (line_event, line) = imported(&mut ids, 100_000, "2026-03-02", Some("20260001"));
let (small, small_id) = imported(&mut ids, 99_999, "2026-03-02", Some("20260002"));
let (early, _) = imported(&mut ids, 100_000, "2026-02-27", Some("20260003"));
apply(&mut s, &[line_event, small, early]);
let before = s.rejected.len();
apply(
&mut s,
&[
ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: Some(small_id), on: d("2026-03-02") }), // wrong amount
ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: Some("no-such".into()), on: d("2026-03-02") }),
ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: None, on: d("2026-02-01") }), // before it was issued
ev(&mut ids, EventBody::InvoicePaid { invoice: "nope".into(), payment: None, on: d("2026-03-02") }),
],
);
assert_eq!(s.rejected.len() - before, 4);
// The early line (before the invoice was issued) pays nothing; the right one pays i1 only.
let plan = plan_invoice_payments(&s, &mut || ids.next(), Timestamp(0));
let paid: Vec<String> = plan.iter().filter_map(|e| match &e.body { EventBody::InvoicePaid { invoice, .. } => Some(invoice.clone()), _ => None }).collect();
assert_eq!(paid, vec!["i1"]);
apply(&mut s, &plan);
let before = s.rejected.len();
apply(
&mut s,
&[
ev(&mut ids, EventBody::InvoicePaid { invoice: "i3".into(), payment: Some(line.clone()), on: d("2026-03-02") }), // used by i1
ev(&mut ids, EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-03-02") }), // paid already
ev(&mut ids, EventBody::InvoiceCancelled { invoice: "i1".into() }), // paid: cannot be cancelled
],
);
assert_eq!(s.rejected.len() - before, 3);
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceCancelled { invoice: "i2".into() })]);
assert!(s.invoices["i2"].cancelled);
let before = s.rejected.len();
apply(&mut s, &[ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: None, on: d("2026-03-03") })]);
assert_eq!(s.rejected.len() - before, 1, "a cancelled invoice is not paid");
}
#[test]
fn the_events_round_trip_and_keep_their_names() {
let mut ids = Ids(0);
let events = vec![
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(true, 150) }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-03-01", vec![line("Práce", 1_000, 100_000, Some(21))], true) }),
ev(&mut ids, EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-03-05") }),
ev(&mut ids, EventBody::InvoiceCancelled { invoice: "i1".into() }),
ev(&mut ids, EventBody::ReserveWithdrawn { withdrawal: "w".into(), amount: Haler(1), on: d("2026-03-05"), note: String::new() }),
];
let json = serde_json::to_string(&events).unwrap();
for name in ["supplier.set", "invoice.issued", "invoice.paid", "invoice.cancelled", "reserve.withdrawn"] {
assert!(json.contains(&format!("\"type\":\"{name}\"")), "{name}");
}
let back: Vec<Event> = serde_json::from_str(&json).unwrap();
assert_eq!(back, events);
// Replaying the log twice gives the same state.
assert_eq!(State::replay(&events), State::replay(&back));
}
#[test]
fn an_invoice_is_printed_in_czech_or_english_and_czech_when_unsaid() {
let mut i = invoice("i1", "20260001", "2026-03-01", vec![line("Work", 1_000, 100_000, None)], false);
i.language = Language::En;
let json = serde_json::to_string(&i).unwrap();
assert!(json.contains("\"language\":\"en\""), "{json}");
assert_eq!(serde_json::from_str::<Invoice>(&json).unwrap(), i);
// An event written without the field reads as Czech.
let older = json.replace(",\"language\":\"en\"", "");
assert!(!older.contains("language"));
assert_eq!(serde_json::from_str::<Invoice>(&older).unwrap().language, Language::Cs);
// Anything else is refused.
assert!(serde_json::from_str::<Invoice>(&json.replace("\"en\"", "\"de\"")).is_err());
}