diff --git a/crates/ledger-core/tests/bookspec/check.rs b/crates/ledger-core/tests/bookspec/check.rs index 194088fe..019a21a6 100644 --- a/crates/ledger-core/tests/bookspec/check.rs +++ b/crates/ledger-core/tests/bookspec/check.rs @@ -38,7 +38,11 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> { ); only(x.basis.is_some(), "basis", &["party_totals"]); only(x.payee.is_some(), "payee", &["vendor_1099"]); - only(x.document.is_some(), "document", &["document_dates"]); + only( + x.document.is_some(), + "document", + &["document_dates", "document"], + ); only(x.of.is_some(), "of", &["aging"]); only( x.code.is_some(), @@ -105,6 +109,8 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> { "project" => check_project(b, x), "aging" => check_aging(b, x), "document_dates" => check_document_dates(b, x), + "document" => check_document(b, x), + "invoice_numbers" => check_invoice_numbers(b, x), q => { let &(_, by) = FORMAT_QUERIES .iter() diff --git a/crates/ledger-core/tests/bookspec/common.rs b/crates/ledger-core/tests/bookspec/common.rs index 5befdcfc..eaa2b261 100644 --- a/crates/ledger-core/tests/bookspec/common.rs +++ b/crates/ledger-core/tests/bookspec/common.rs @@ -144,6 +144,22 @@ pub(crate) fn refusal(e: &LedgerError) -> String { LedgerError::InvalidSchedule(_) => "invalid_schedule", LedgerError::UntaggedControlLine { .. } => "untagged_control_line", LedgerError::PaymentBeforeDocument { .. } => "payment_before_document", + LedgerError::DuplicateVendorRef { .. } => "duplicate_vendor_reference", + // An invoice with a bill, and documents of two parties, are the one + // refusal: a customer and a vendor are two parties (BS-arap-6). + LedgerError::SettlementMixedKinds(_) | LedgerError::SettlementPartiesDiffer(..) => { + "settlement_mixes_parties" + } + LedgerError::SettlementDuplicateDocument(_) => "settlement_repeats_a_document", + LedgerError::Overpayment(..) => "application_above_owed", + LedgerError::DiscountNeedsReason { .. } => "discount_needs_reason", + LedgerError::DiscountOnAssetBill { .. } => "discount_on_asset_bill", + // The cash and the discounts the adapter hands over always cover the + // applications exactly, so the one way the engine's exactness check + // fails is a fee above the cash (BS-arap-6). + LedgerError::InvalidSettlement(why) if why.contains("the fee is above the cash") => { + "fee_above_cash" + } LedgerError::UnbalancedEntry { .. } => "unbalanced", LedgerError::TooFewLines => "too_few_lines", LedgerError::NegativeAmountLine => "negative_amount", diff --git a/crates/ledger-core/tests/bookspec/events.rs b/crates/ledger-core/tests/bookspec/events.rs index 00eba781..82a35e55 100644 --- a/crates/ledger-core/tests/bookspec/events.rs +++ b/crates/ledger-core/tests/bookspec/events.rs @@ -14,6 +14,8 @@ impl Books<'_> { ("invoice", e.invoice.is_some()), ("write_off", e.write_off.is_some()), ("payment", e.payment.is_some()), + ("settlement", e.settlement.is_some()), + ("recovery", e.recovery.is_some()), ("run_depreciation", e.run_depreciation.is_some()), ("dispose_asset", e.dispose_asset.is_some()), ("run_schedules", e.run_schedules.is_some()), @@ -22,7 +24,7 @@ impl Books<'_> { match kinds.iter().filter(|(_, given)| *given).collect::>()[..] { [(kind, _)] => kind, _ => panic!( - "{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, payment, run_depreciation, dispose_asset, run_schedules or register_schedule", + "{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, payment, settlement, recovery, run_depreciation, dispose_asset, run_schedules or register_schedule", self.ex.id ), } @@ -36,7 +38,11 @@ impl Books<'_> { // disposal is dated; the other commands date their own entries, // and every command describes its own. let own = matches!(kind, "lines" | "reverses" | "close" | "bill" | "invoice"); - let dated = own || matches!(kind, "dispose_asset" | "write_off" | "payment"); + let dated = own + || matches!( + kind, + "dispose_asset" | "write_off" | "payment" | "settlement" | "recovery" + ); assert_eq!( e.date.is_some(), dated, @@ -74,8 +80,8 @@ impl Books<'_> { "{ex} event {n}: {kind} is tagged with no parties or payment method" ); assert!( - e.refused.is_none() || !matches!(kind, "close" | "bill" | "invoice"), - "{ex} event {n}: refused is for a reversal, an entry or a command, which the books take whole or not at all" + e.refused.is_none() || !matches!(kind, "close" | "invoice"), + "{ex} event {n}: refused is for a reversal, an entry, a bill or a command, which the books take whole or not at all" ); assert!( !(e.older && e.refused.is_some()), @@ -89,6 +95,14 @@ impl Books<'_> { e.payment.is_none() || kind == "payment", "{ex} event {n}: a payment is its own event" ); + assert!( + e.settlement.is_none() || kind == "settlement", + "{ex} event {n}: a settlement is its own event" + ); + assert!( + e.recovery.is_none() || kind == "recovery", + "{ex} event {n}: a recovery is its own event" + ); } /// Take event `n` as the books take it, keep what it posted and tag it @@ -197,9 +211,18 @@ impl Books<'_> { "{what}: entry {id}, which it made, is posted" ); } - if (own || matches!(kind, "write_off" | "payment")) && e.refused.is_none() { + if (own || matches!(kind, "write_off" | "payment" | "settlement")) && e.refused.is_none() { assert_eq!(posted.len(), 1, "{what}: {kind} posts one entry"); } + // A recovery posts one entry or two, as the engine's pick under + // BS-arap-11 says: a plain entry, or the write-off's reversal and + // the payment. + if kind == "recovery" && e.refused.is_none() { + assert!( + matches!(posted.len(), 1 | 2), + "{what}: a recovery posts one entry or two" + ); + } } /// The terms a document's example gives, and the due date the books take @@ -230,6 +253,20 @@ impl Books<'_> { (due, Some(parsed)) } + /// The invoice or bill event `event` posted, and its customer or vendor. + pub(crate) fn document_of(&self, event: usize, what: &str) -> (ledger_core::DocRef, u64) { + let entry = self.entry_of(event, what); + let l = self.l(); + match ( + l.invoices().into_iter().find(|i| i.entry_id == entry), + l.bills().into_iter().find(|b| b.entry_id == entry), + ) { + (Some(i), _) => (ledger_core::DocRef::Invoice(i.id), i.customer_id), + (None, Some(b)) => (ledger_core::DocRef::Bill(b.id), b.vendor_id), + (None, None) => panic!("{what}: event {event} posted no invoice or bill"), + } + } + /// An invoice's or bill's lines: `amount` (one line, described as the /// event) or `lines`, exactly one; each project a `setup.projects` /// name. @@ -264,7 +301,7 @@ impl Books<'_> { panic!("{what}: project {p:?} not in setup.projects") }) }), - account: None, + account: l.account.as_deref().map(|code| self.id(code)), quantity: None, unit_price: None, }) @@ -410,6 +447,8 @@ impl Books<'_> { lines, BillFields { terms, + vendor_ref: b.vendor_ref.clone(), + duplicate_reason: b.duplicate_reason.clone(), ..BillFields::default() }, ) @@ -427,6 +466,9 @@ impl Books<'_> { } }; let (due, terms) = self.terms_due(i.terms.as_deref(), day(), what); + // The books number every invoice in order of issue (BS-arap-4), + // as their invoicing settings default to. + let number = self.l().next_invoice_number("INV-", 1); self.store .create_invoice_with( customer, @@ -434,6 +476,7 @@ impl Books<'_> { due, lines, InvoiceFields { + number: Some(number), terms, ..InvoiceFields::default() }, @@ -515,6 +558,82 @@ impl Books<'_> { } } } + "settlement" => { + let st = e.settlement.as_ref().expect("checked: a settlement"); + let first = &st.applications[0]; + let (first_doc, party) = self.document_of(first.document, what); + let applications: Vec = st + .applications + .iter() + .map(|a| ledger_core::Application { + doc: self.document_of(a.document, what).0, + cash: exact(&a.cash, what), + discount: a + .discount + .as_deref() + .map_or(Decimal::ZERO, |d| exact(d, what)), + discount_reason: a.discount_reason.clone(), + }) + .collect(); + debug_assert_eq!(applications[0].doc, first_doc); + let params = ledger_core::SettleParams { + date: day(), + description: String::new(), + cash_account: self.id(&st.account), + party, + applications, + fee: st.fee.as_deref().map(|f| ledger_core::Fee { + amount: exact(f, what), + account: None, + vendor: None, + }), + instrument: None, + reference: None, + }; + self.store.settle(params).map(drop) + } + "recovery" => { + // BS-arap-11, the pick reverse-then-plain-entry: in the tax + // year of the write-off the write-off is reversed and the + // money is recorded as any payment; in a later year a plain + // entry debits the deposit account and credits the recoveries + // account, naming the invoice. + let r = e.recovery.as_ref().expect("checked: a recovery"); + let amount = exact(&r.amount, what); + let (cash, income) = (self.id(&r.account), self.id(&r.income_account)); + let write_off = self.entry_of(r.write_off, what); + let written = &self.ex.events[r.write_off - 1]; + let invoice_event = written + .write_off + .as_ref() + .map(|w| w.invoice) + .unwrap_or_else(|| panic!("{what}: event {} is no write-off", r.write_off)); + let (doc, _) = self.document_of(invoice_event, what); + let ledger_core::DocRef::Invoice(invoice) = doc else { + panic!("{what}: a write-off is of an invoice") + }; + let written_on = date(written.date.as_deref().expect("a write-off is dated"), what); + let year = + |d| ledger_core::calendar::fiscal_year_start_on(fiscal_year_start(self.ex), d); + if year(written_on) == year(day()) { + self.store.reverse_entry( + write_off, + day(), + "Recovered: the write-off is reversed", + )?; + self.store + .receive_payment(invoice, day(), amount, cash) + .map(drop) + } else { + let entry = self + .store + .create_entry(day(), &format!("Recovery of invoice {invoice}"))?; + let money = Money::new(amount, self.currency); + self.store.add_line(entry, cash, Side::Debit, money)?; + self.store.add_line(entry, income, Side::Credit, money)?; + self.store.post_entry(entry) + } + } "run_depreciation" => { let r = e.run_depreciation.as_ref().expect("checked: a run"); let asset = self.asset(&r.asset, what); diff --git a/crates/ledger-core/tests/bookspec/examples.rs b/crates/ledger-core/tests/bookspec/examples.rs index a8e5b0be..c1d34691 100644 --- a/crates/ledger-core/tests/bookspec/examples.rs +++ b/crates/ledger-core/tests/bookspec/examples.rs @@ -146,6 +146,8 @@ pub(crate) fn every_bookspec_example_holds() { ("project", 6), ("aging", 4), ("document_dates", 8), + ("document", 8), + ("invoice_numbers", 1), ] { let n = checked.get(q).copied().unwrap_or(0); assert!(n >= at_least, "{q} ran {n} times, fewer than {at_least}"); @@ -157,11 +159,14 @@ pub(crate) fn every_bookspec_example_holds() { skipped.len() ); // The examples for an option wanderbooks did not pick: the other option - // of BS-arap-7, -8 and -9, BS-prepaid-2's equal-months and BS-ledger-20's - // refuse (each option's example, so no allow-list grows). + // of BS-arap-2 (documents-kept-apart), -7, -8, -9, -10 (compare-exactly), + // -11 (recovery-movement), -12 (net-of-expected-discount), -13 + // (net-against-the-deposit) and -14 (apportion-across-the-lines), + // BS-prepaid-2's equal-months and BS-ledger-20's refuse (each option's + // example, so no allow-list grows). assert_eq!( skipped.len(), - 5, - "the five unpicked-option examples: {skipped:?}" + 11, + "the eleven unpicked-option examples: {skipped:?}" ); } diff --git a/crates/ledger-core/tests/bookspec/queries/documents.rs b/crates/ledger-core/tests/bookspec/queries/documents.rs index ff40d161..e47bd5fd 100644 --- a/crates/ledger-core/tests/bookspec/queries/documents.rs +++ b/crates/ledger-core/tests/bookspec/queries/documents.rs @@ -63,6 +63,63 @@ impl Books<'_> { ("discount_by".to_string(), discount_by), ])) } + + /// What the ledger lines tagged with the document event `document` come + /// to as of the day (BS-arap-2), straight from the engine's `DocState`: + /// `total`, `paid`, `discounted`, `written_off` and `owes` (its + /// `outstanding`). The engine keeps no recovery movement (BS-arap-11 + /// reverse-then-plain-entry), so it gives no `recovered`. + pub(crate) fn answer_document(&self, q: &Query) -> Result { + let n = q.document.ok_or_else(|| self.missing("document"))?; + let as_of = self.q_day(q)?; + let (doc, _) = self.document_of(n, "a document query"); + let state = match doc { + ledger_core::DocRef::Invoice(id) => self.l().invoice_state(id, as_of), + ledger_core::DocRef::Bill(id) => self.l().bill_state(id, as_of), + } + .map_err(|e| engine_refusal(RuleId::new(Area::Arap, 2), e))? + .ok_or_else(|| self.missing("document, dated by the day asked"))?; + Ok(json_figures([ + ("total".to_string(), figure(state.total)), + ("paid".to_string(), figure(state.paid)), + ("discounted".to_string(), figure(state.discounted)), + ("written_off".to_string(), figure(state.written_off)), + ("owes".to_string(), figure(state.outstanding)), + ])) + } + + /// The place of each invoice in the order of issue, and of the next + /// (BS-arap-4): read from the number the engine stored at issue, + /// `INV-0003` being the third, a voided invoice keeping its own. + pub(crate) fn answer_invoice_numbers(&self, _q: &Query) -> Result { + let place = |number: &str| -> String { + let digits: String = number.chars().filter(char::is_ascii_digit).collect(); + digits.trim_start_matches('0').to_string() + }; + let l = self.l(); + let mut m = JsonMap::new(); + for (i, e) in self.ex.events.iter().enumerate() { + if e.invoice.is_none() || i >= self.posted.len() { + continue; + } + let entry = self.entry_or_refuse(i + 1)?; + let invoice = l + .invoices() + .into_iter() + .find(|inv| inv.entry_id == entry) + .ok_or_else(|| self.missing("invoice"))?; + let number = invoice + .number + .as_deref() + .ok_or_else(|| self.missing("invoice number"))?; + m.insert((i + 1).to_string(), Value::String(place(number))); + } + m.insert( + "next".to_string(), + Value::String(place(&l.next_invoice_number("INV-", 1))), + ); + Ok(Value::Object(m)) + } } /// Check an `aging` expectation: every figure the engine gives, and no @@ -71,6 +128,32 @@ pub(crate) fn check_aging(b: &Books<'_>, x: &Expect) { check_figures(b, x, b.answer_aging(&x.query())); } +/// Check a `document` expectation: the figures it names, as the engine's +/// document figures give them. +pub(crate) fn check_document(b: &Books<'_>, x: &Expect) { + let answer = b.answer_document(&x.query()); + let Value::Object(got) = + answer.unwrap_or_else(|r| panic!("{}: {}: {}", b.ex.id, x.query, r.reason)) + else { + panic!("{}: {} answers a table", b.ex.id, x.query) + }; + for (key, want) in x.figures(&b.ex.id) { + assert_eq!( + got.get(key).and_then(Value::as_str), + Some(want.as_str()), + "{}: {} {key}", + b.ex.id, + x.query + ); + } +} + +/// Check an `invoice_numbers` expectation: every invoice and the next, +/// and no other. +pub(crate) fn check_invoice_numbers(b: &Books<'_>, x: &Expect) { + check_figures(b, x, b.answer_invoice_numbers(&x.query())); +} + /// Check a `document_dates` expectation: `due` and `discount_by`, both /// given. pub(crate) fn check_document_dates(b: &Books<'_>, x: &Expect) { diff --git a/crates/ledger-core/tests/bookspec/queries/mod.rs b/crates/ledger-core/tests/bookspec/queries/mod.rs index a1e6a4aa..8ad9af2c 100644 --- a/crates/ledger-core/tests/bookspec/queries/mod.rs +++ b/crates/ledger-core/tests/bookspec/queries/mod.rs @@ -87,6 +87,8 @@ impl Books<'_> { "project" => self.answer_project(q), "aging" => self.answer_aging(q), "document_dates" => self.answer_document_dates(q), + "document" => self.answer_document(q), + "invoice_numbers" => self.answer_invoice_numbers(q), "run" => self.answer_run(q), "disposal" => self.answer_disposal(q), "depreciation_schedule" => self.answer_depreciation_schedule(q),