From ea4d8bc86e6dff43b65bbdda5f78e8241fa94aea Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 00:16:28 -0700 Subject: [PATCH 1/4] test(core): the adapter runs settlements, recoveries, numbers and vendor references bookspec's X-H1b examples state BS-arap-4, -6 and -10 to -14 through new events and queries; the adapter runs each through the real API, none reimplemented. - settlement: `Store::settle` with the applications, the fee and the deposit account; the party is the first document's customer or vendor, so the engine itself finds an invoice mixed with a bill, two customers, a document twice, more than a document owes, a discount that needs a reason, a discount on an asset bill and a fee above the cash. Each engine error is read as the examples' word (the fee case from the one InvalidSettlement error that can arise from exact inputs). - recovery (BS-arap-11, reverse-then-plain-entry): in the write-off's fiscal year `Store::reverse_entry` of the write-off then `Store::receive_payment`; in a later year a plain entry, deposit debited and the recoveries account credited, naming the invoice. The engine has no recovery command; the two calls are the pick's own procedure. - a bill's vendor reference and duplicate reason go to `BillFields`, so `Ledger::check_vendor_ref` is what refuses a second bill; each invoice is numbered with `Ledger::next_invoice_number`; a line's own account goes to `DocumentLine`. - queries `document` (`Ledger::invoice_state`/`bill_state`) and `invoice_numbers` (the number the engine stored, read as its place in the order of issue). Wanderbooks passes all 80 examples it runs. The runner skips eleven for the options it did not pick (six new: documents-kept-apart, compare-exactly, recovery-movement, net-of-expected-discount, net-against-the-deposit, apportion-across-the-lines), so the pinned count is 11. No engine disagreed with an example. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/tests/bookspec/check.rs | 8 +- crates/ledger-core/tests/bookspec/common.rs | 16 +++ crates/ledger-core/tests/bookspec/events.rs | 131 +++++++++++++++++- crates/ledger-core/tests/bookspec/examples.rs | 13 +- .../tests/bookspec/queries/documents.rs | 83 +++++++++++ .../ledger-core/tests/bookspec/queries/mod.rs | 2 + 6 files changed, 242 insertions(+), 11 deletions(-) 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), From b78b5e9f39caca7eca8988da34c5454478f0e5b9 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 00:16:28 -0700 Subject: [PATCH 2/4] docs(claims): the arap Checked lines name the X-H1b examples B-38, B-40, B-41 and B-42 list the new bookspec examples the adapter runs for the options wanderbooks picked, and those it skips for the options it did not (BS-arap-2, -10, -11, -12, -13, -14). B-40 records that wanderbooks' vendor-reference comparison also drops hyphens, which BS-arap-10's option (case and spaces) does not say; no example distinguishes them yet. B-41 notes the allowance method of BS-arap-5 still has no example (it needs a provision event). Co-Authored-By: Claude Sonnet 5.5 --- docs/spec/claims/arap.md | 42 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/docs/spec/claims/arap.md b/docs/spec/claims/arap.md index 0e7e0b1a..b1afe2d7 100644 --- a/docs/spec/claims/arap.md +++ b/docs/spec/claims/arap.md @@ -74,7 +74,12 @@ Kani `bounds_check_matches_definition`, `bounds_kept_is_the_definition_on_books_ Lean `Documents.control_agrees`, `Documents.Step.document_unattached`, `Documents.Step.reverse_moves`, `Documents.Reachable.unattached_zero` (through role assignments and releases), -`Documents.Reachable.control_is_documents`. The model's limits: it +`Documents.Reachable.control_is_documents`; bookspec examples +`arap-hand-control-posting-refused` (BS-arap-2 `lines-that-stand`: the +hand line is refused, the line an earlier version wrote still reads right), +run by the adapter, and `arap-a-hand-line-on-receivables-is-taken` +(`documents-kept-apart`), which names the option wanderbooks did not pick +and is skipped for it. The model's limits: it starts from empty books (legacy lines are covered by the identity `Documents.control_agrees` alone), it names documents by one id space (an injective coding of `DocRef`), and an account becoming a control account by its @@ -182,6 +187,11 @@ behind the feature `documents_v2`. **Checked:** **Pick:** a vendor's invoice reference is compared after the normalization that drops case and spaces (`Ledger::check_vendor_ref`); the old text names no separate decision for it. **Pick (BS-arap-10):** `ignore-case-and-spaces`; a vendor's invoice reference is compared after the normalization that drops case and spaces. +wanderbooks goes one step past the option: it also drops hyphens, so +"ACME-123", "acme 123" and "Acme123" are one reference (`Ledger::check_vendor_ref`, +pinned by `duplicate_vendor_ref_refused_unless_a_reason_is_given`); the record's option +names case and spaces only, and none of its examples distinguishes the two. + **Enforced:** `Ledger::next_invoice_number`, `Ledger::check_vendor_ref`, `PartySnapshot::from_party` (the snapshots at issue, D-55); `Store::create_invoice_issued` (feature `documents_v2`); @@ -195,7 +205,14 @@ every amount through `amount_parts`). `tests/arap_standing.rs` (`documents_v2_waits_for_the_upgrade`, `issued_pdf_is_filed_with_the_invoice_or_nothing_is`); over the wire `crates/ledger-cli/tests/documents.rs` (`an_invoice_from_issue_to_paid`, -`duplicate_vendor_invoice_refused`); the page `ledger-import` +`duplicate_vendor_invoice_refused`); bookspec examples +`arap-invoice-numbers-run-in-order-and-are-kept` (the adapter numbers each +invoice with `Ledger::next_invoice_number` and reads the place back from the +number the engine stored), `arap-a-vendor-invoice-is-entered-once` +(the refusal of a second bill, from `Ledger::check_vendor_ref`) and, for +BS-arap-10, `arap-a-vendor-reference-differing-in-case-and-spaces-is-a-duplicate`; +`arap-a-vendor-reference-differing-in-case-and-spaces-is-not-a-duplicate` +names `compare-exactly` and is skipped; the page `ledger-import` `tests/spec_import.rs::invoice_pdf_prints_what_it_should` and the unit tests `labels_are_data`, `an_invoice_renders_deterministically`, `two_hundred_lines_paginate`; the viewer @@ -260,7 +277,14 @@ item. `tests/arap_props.rs` (`status_is_a_function_of_journal_and_date` with write-offs); over the wire `crates/ledger-cli/tests/documents.rs` (`write_off_then_recovery`, `write_off_needs_evidence`); bookspec -`bad-debt-direct-write-off`; Lean `Documents.Step.writeOff_unattached`, +`bad-debt-direct-write-off` (BS-arap-5 `direct-write-off`; the allowance +method has no example yet, it needs a provision event) and, for BS-arap-11, +`arap-a-recovery-reverses-the-write-off-in-its-year` (the adapter reverses +the write-off with `Store::reverse_entry` and takes the money with +`Store::receive_payment` in the write-off's tax year, and posts a plain +entry in a later one); +`arap-a-recovery-is-a-movement-on-the-document` names `recovery-movement` +and is skipped; Lean `Documents.Step.writeOff_unattached`, `Documents.writeOff_within_bounds`; the viewer `a_write_off_shows_on_the_timeline`; the item `a_write_off_is_flagged_for_the_cpa`. @@ -324,7 +348,17 @@ check_discount}`, `arap::{Application, Fee, SettleParams, SettlementRow}`, `ledger-store` `tests/arap_standing.rs` (`a_settlement_names_its_lines_and_replays`, `settlement_waits_for_documents_v2`, `legacy_payment_events_keep_the_positional_rule`), `tests/arap_props.rs`; -`ledger-cli` `tests/documents.rs`; `ledger-package`'s aging tie-out test. +`ledger-cli` `tests/documents.rs`; `ledger-package`'s aging tie-out test; +bookspec examples `arap-a-settlement-pays-several-documents-and-names-each-line` +and `arap-a-settlement-that-is-not-exact-is-refused` (BS-arap-6, through +`Store::settle`, each refusal read off the engine's own error), and one per +option picked: `arap-a-discount-taken-is-booked-when-it-is-taken` (BS-arap-12), +`arap-a-processors-fee-is-posted-gross` (BS-arap-13) and +`arap-a-discount-on-an-asset-bill-is-refused` (BS-arap-14); the examples +`arap-a-discount-expected-is-booked-with-the-document`, +`arap-a-processors-fee-is-not-shown-against-the-deposit` and +`arap-a-discount-on-an-asset-bill-is-apportioned` name the options not picked +and are skipped. The Lean step is the document constructor of the Lean documents model, with every control line tagged (`Documents.settle_unattached`); no new step constructor. From d35775922b83038d93eeebf18ab4f420c1c91bf3 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 00:58:02 -0700 Subject: [PATCH 3/4] docs(claims): BS-arap-10's pick is ignore-case-spaces-and-hyphens, as the plan decided The engine has always dropped hyphens too (plan P4b S4, the owner: "(vendor, normalized vendor_ref) (lower-case, spaces and hyphens removed)", pinned by duplicate_vendor_ref_refused_unless_a_reason_is_given); bookspec's record lost the hyphens in transcription and is corrected, so there is no divergence to note. PICKS and the claims file name the option ignore-case-spaces-and-hyphens, "spaces" being any whitespace, and the example ids follow the record's rename. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/tests/bookspec/engine.rs | 2 +- docs/spec/claims/arap.md | 13 ++++--------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/crates/ledger-core/tests/bookspec/engine.rs b/crates/ledger-core/tests/bookspec/engine.rs index f9a4e9f3..60185e0e 100644 --- a/crates/ledger-core/tests/bookspec/engine.rs +++ b/crates/ledger-core/tests/bookspec/engine.rs @@ -120,7 +120,7 @@ pub(crate) const PICKS: &[(Area, u32, &str)] = &[ (Area::Arap, 7, "due-today-is-current"), (Area::Arap, 8, "as-of-the-day"), (Area::Arap, 9, "refuse-a-payment-before-its-document"), - (Area::Arap, 10, "ignore-case-and-spaces"), + (Area::Arap, 10, "ignore-case-spaces-and-hyphens"), (Area::Arap, 11, "reverse-then-plain-entry"), (Area::Arap, 12, "gross-when-taken"), (Area::Arap, 13, "gross"), diff --git a/docs/spec/claims/arap.md b/docs/spec/claims/arap.md index b1afe2d7..4c30327b 100644 --- a/docs/spec/claims/arap.md +++ b/docs/spec/claims/arap.md @@ -184,13 +184,8 @@ behind the feature `documents_v2`. **Checked:** **Claims:** yes -**Pick:** a vendor's invoice reference is compared after the normalization that drops case and spaces (`Ledger::check_vendor_ref`); the old text names no separate decision for it. -**Pick (BS-arap-10):** `ignore-case-and-spaces`; a vendor's invoice reference is compared after the normalization that drops case and spaces. - -wanderbooks goes one step past the option: it also drops hyphens, so -"ACME-123", "acme 123" and "Acme123" are one reference (`Ledger::check_vendor_ref`, -pinned by `duplicate_vendor_ref_refused_unless_a_reason_is_given`); the record's option -names case and spaces only, and none of its examples distinguishes the two. +**Pick:** a vendor's invoice reference is compared after the normalization that drops case, spaces and hyphens (`Ledger::check_vendor_ref`), so "ACME-123", "acme 123" and "Acme123" are one reference (pinned by `duplicate_vendor_ref_refused_unless_a_reason_is_given`); plan P4b S4 (the owner) specifies it. +**Pick (BS-arap-10):** `ignore-case-spaces-and-hyphens`; a vendor's invoice reference is compared after the normalization that drops case, spaces (any whitespace) and hyphens. **Enforced:** `Ledger::next_invoice_number`, `Ledger::check_vendor_ref`, `PartySnapshot::from_party` (the snapshots at issue, D-55); @@ -210,8 +205,8 @@ every amount through `amount_parts`). invoice with `Ledger::next_invoice_number` and reads the place back from the number the engine stored), `arap-a-vendor-invoice-is-entered-once` (the refusal of a second bill, from `Ledger::check_vendor_ref`) and, for -BS-arap-10, `arap-a-vendor-reference-differing-in-case-and-spaces-is-a-duplicate`; -`arap-a-vendor-reference-differing-in-case-and-spaces-is-not-a-duplicate` +BS-arap-10, `arap-a-vendor-reference-differing-in-case-spaces-and-hyphens-is-a-duplicate`; +`arap-a-vendor-reference-differing-in-case-spaces-and-hyphens-is-not-a-duplicate` names `compare-exactly` and is skipped; the page `ledger-import` `tests/spec_import.rs::invoice_pdf_prints_what_it_should` and the unit tests `labels_are_data`, `an_invoice_renders_deterministically`, From 0ffb0935fe323c08446a0c0f7238c7b25776c706 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 01:53:36 -0700 Subject: [PATCH 4/4] fix(core): a fee above the cash is its own refusal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A processor cannot keep more than it was paid. The engine already refused a settlement whose fee is above its cash, but as InvalidSettlement, one message for two causes ("the cash and discounts don't cover the applications exactly, or the fee is above the cash"), so the bookspec adapter had to read the refusal out of the message's prose. Settlement now checks fee > Σ cash itself, in the same place as before (after the per-application checks, before kernel::settle), and returns the typed LedgerError::FeeAboveCash { fee, cash }. InvalidSettlement keeps what remains (a sum too large, a negative fee, a fee that leaves no deposit), and its message no longer claims the fee case. The adapter matches the variant like every sibling. The refusal's precedence is unchanged, and nothing was journaled by a refused settlement before or now (the store journals only a settlement that succeeded); no stored data changes. The only output change is the error text of a fee above the cash and of the leftover InvalidSettlement cases; no golden or test asserted either text, and no caller matched the variant (ledger-mcp, ledger-store, ledger-cli pass them on as text). a_fee_above_the_cash_is_refused_and_changes_nothing encodes the rule (150.00 of cash, a fee of 150.01 refused, books untouched; a fee equal to the cash is the other refusal; a fee of 3.00 posts, deposit 147.00). Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/src/error.rs | 21 ++++++- crates/ledger-core/src/ledger.rs | 15 ++++- crates/ledger-core/tests/bookspec/common.rs | 7 +-- crates/ledger-core/tests/spec_documents.rs | 69 +++++++++++++++++++++ docs/spec/claims/arap.md | 4 +- 5 files changed, 105 insertions(+), 11 deletions(-) diff --git a/crates/ledger-core/src/error.rs b/crates/ledger-core/src/error.rs index bb437d0d..72d434a5 100644 --- a/crates/ledger-core/src/error.rs +++ b/crates/ledger-core/src/error.rs @@ -749,9 +749,24 @@ pub enum LedgerError { #[error("{0}")] InvalidFee(String), - /// A settlement's figures can't be exact: the cash and discounts - /// don't cover the applications, or the fee leaves a negative deposit - /// (BS-arap-6 INVARIANT 1). + /// A processor's fee is above the cash it was withheld from: a + /// processor cannot keep more than it was paid (BS-arap-6). A fee equal + /// to the cash is [`LedgerError::InvalidSettlement`]: the deposit would + /// be nothing. + #[error( + "the processor's fee of {fee} is above the cash of {cash}: a processor can't keep more than it was paid" + )] + FeeAboveCash { + /// The fee asked for. + fee: Decimal, + /// The settlement's cash, summed over its applications. + cash: Decimal, + }, + + /// A settlement's figures can't be exact (BS-arap-6 INVARIANT 1): an + /// amount too large to add, a negative fee, or a fee that leaves + /// nothing to deposit; a fee above the cash is + /// [`LedgerError::FeeAboveCash`]. #[error("{0}")] InvalidSettlement(String), diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index e5a0c005..77b0877b 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -6701,9 +6701,22 @@ impl Ledger { discounts.push(app.discount); } let fee_amount = params.fee.as_ref().map_or(Decimal::ZERO, |f| f.amount); + // A fee above the cash is its own refusal; the kernel would also + // answer `None` for it, with no way to say which of its refusals it + // was. A sum that overflows is left to the kernel (too large). + if let Some(total_cash) = cash + .iter() + .try_fold(Decimal::ZERO, |sum, c| sum.checked_add(*c)) + && fee_amount > total_cash + { + return Err(LedgerError::FeeAboveCash { + fee: fee_amount, + cash: total_cash, + }); + } let settlement = kernel::settle(&cash, &discounts, fee_amount).ok_or_else(|| { LedgerError::InvalidSettlement( - "the cash and discounts don't cover the applications exactly, or the fee is above the cash" + "the settlement's figures aren't exact: an amount is too large, or the fee is negative" .into(), ) })?; diff --git a/crates/ledger-core/tests/bookspec/common.rs b/crates/ledger-core/tests/bookspec/common.rs index eaa2b261..7b0f42f4 100644 --- a/crates/ledger-core/tests/bookspec/common.rs +++ b/crates/ledger-core/tests/bookspec/common.rs @@ -154,12 +154,7 @@ pub(crate) fn refusal(e: &LedgerError) -> String { 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::FeeAboveCash { .. } => "fee_above_cash", LedgerError::UnbalancedEntry { .. } => "unbalanced", LedgerError::TooFewLines => "too_few_lines", LedgerError::NegativeAmountLine => "negative_amount", diff --git a/crates/ledger-core/tests/spec_documents.rs b/crates/ledger-core/tests/spec_documents.rs index 1986e901..66d5bf46 100644 --- a/crates/ledger-core/tests/spec_documents.rs +++ b/crates/ledger-core/tests/spec_documents.rs @@ -2553,3 +2553,72 @@ fn discount_on_an_asset_bill_is_refused_with_the_remedy() { ); b.ties(d(2026, 4, 5)); } + +/// A processor cannot keep more than it was paid: a fee above the cash is +/// refused as its own refusal (`FeeAboveCash`, BS-arap-6) and changes +/// nothing. A fee equal to the cash is a different refusal (the deposit +/// would be nothing), and a fee within the cash still posts. +#[test] +fn a_fee_above_the_cash_is_refused_and_changes_nothing() { + use ledger_core::{Application, DocRef, Fee, SettleParams}; + let mut b = books(); + let first = b.invoice(d(2026, 4, 1), 10_000); + let second = b.invoice(d(2026, 4, 2), 5_000); + let params = |fee: i64| SettleParams { + date: d(2026, 4, 5), + description: "Card payment".into(), + cash_account: b.bank, + party: b.customer, + applications: vec![ + Application { + doc: DocRef::Invoice(first), + cash: cents(10_000), + discount: Decimal::ZERO, + discount_reason: None, + }, + Application { + doc: DocRef::Invoice(second), + cash: cents(5_000), + discount: Decimal::ZERO, + discount_reason: None, + }, + ], + fee: Some(Fee { + amount: cents(fee), + account: None, + vendor: None, + }), + instrument: None, + reference: None, + }; + let posted_before = b.l.posted_entries().count(); + let first_before = b.state(DocRef::Invoice(first), d(2026, 4, 5)); + let second_before = b.state(DocRef::Invoice(second), d(2026, 4, 5)); + // The cash is 150.00 across two applications; a fee of 150.01 is above it. + let refused = b.l.settle(params(15_001)); + assert!( + matches!( + refused, + Err(LedgerError::FeeAboveCash { fee, cash }) + if fee == cents(15_001) && cash == cents(15_000) + ), + "{refused:?}" + ); + assert_eq!(b.l.posted_entries().count(), posted_before); + assert_eq!(b.state(DocRef::Invoice(first), d(2026, 4, 5)), first_before); + assert_eq!( + b.state(DocRef::Invoice(second), d(2026, 4, 5)), + second_before + ); + assert_eq!(b.l.account_balance(b.bank).unwrap(), Decimal::ZERO); + // The fee equal to the cash is the other refusal, not this one. + assert!(matches!( + b.l.settle(params(15_000)), + Err(LedgerError::InvalidSettlement(_)) + )); + assert_eq!(b.l.posted_entries().count(), posted_before); + // A fee within the cash posts: 150.00 gross, 3.00 fee, 147.00 deposit. + b.l.settle(params(300)).unwrap(); + assert_eq!(b.l.account_balance(b.bank).unwrap(), cents(14_700)); + b.ties(d(2026, 4, 5)); +} diff --git a/docs/spec/claims/arap.md b/docs/spec/claims/arap.md index 4c30327b..0bf59ffa 100644 --- a/docs/spec/claims/arap.md +++ b/docs/spec/claims/arap.md @@ -338,7 +338,9 @@ check_discount}`, `arap::{Application, Fee, SettleParams, SettlementRow}`, (`bill_on_terms_with_discount`, `late_discount_needs_a_reason`, `discount_on_an_asset_bill_is_refused_with_the_remedy`, `a_fee_posts_gross_to_receivables_and_net_to_the_bank`, -`a_settlement_names_its_lines_and_refuses_a_document_twice`), +`a_settlement_names_its_lines_and_refuses_a_document_twice`, +`a_fee_above_the_cash_is_refused_and_changes_nothing`: the refusal is +`LedgerError::FeeAboveCash`, its own variant), `tests/kernel_bridge/main.rs::settle_agrees`; Kani `settle_is_exact`; `ledger-store` `tests/arap_standing.rs` (`a_settlement_names_its_lines_and_replays`, `settlement_waits_for_documents_v2`,