From 23e52de969c49685c11687b64c4d12c4846b456d Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 20:47:46 -0700 Subject: [PATCH 1/4] test(core): the adapter runs payments, aging and due dates The bookspec adapter learns the three things X-H1a's examples ask: a `payment` event (Store::receive_payment for an invoice, pay_bill for a bill, a payment dated before its document refused as `payment_before_document` from LedgerError::PaymentBeforeDocument, BS-arap-9); `terms` on a bill or invoice (the document is created with the engine's own Terms, its due date from Terms::due_date, and the engine must print the example's spelling back as written, BS-arap-3); and the `aging` and `document_dates` queries, read from Ledger::{ar_aging, ap_aging} and the stored document's due date and Terms::discount_by. Nothing of aging or terms is recomputed in the test. An example for an option wanderbooks did not pick (`under`, checked against PICKS) is read and not run, in the loader tests as in the runner, which reports it skipped; the 71 others pass: wanderbooks agrees with every example for the options it picks (BS-arap-7 due-today-is-current, BS-arap-8 as-of-the-day, BS-arap-9 refuse-a-payment-before-its-document). Run against bookspec branch x-h1a by patching the dependency; the pin does not move here. Claims for B-18 and B-39 name the new examples. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/tests/bookspec/check.rs | 4 + crates/ledger-core/tests/bookspec/common.rs | 1 + crates/ledger-core/tests/bookspec/engine.rs | 19 ++++ crates/ledger-core/tests/bookspec/events.rs | 101 +++++++++++++++++- crates/ledger-core/tests/bookspec/examples.rs | 55 ++++++++++ crates/ledger-core/tests/bookspec/main.rs | 15 +-- .../tests/bookspec/queries/documents.rs | 98 +++++++++++++++++ .../ledger-core/tests/bookspec/queries/mod.rs | 3 + docs/spec/claims/arap.md | 16 ++- 9 files changed, 299 insertions(+), 13 deletions(-) create mode 100644 crates/ledger-core/tests/bookspec/queries/documents.rs diff --git a/crates/ledger-core/tests/bookspec/check.rs b/crates/ledger-core/tests/bookspec/check.rs index 9e0f6d83..194088fe 100644 --- a/crates/ledger-core/tests/bookspec/check.rs +++ b/crates/ledger-core/tests/bookspec/check.rs @@ -38,6 +38,8 @@ 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.of.is_some(), "of", &["aging"]); only( x.code.is_some(), "code", @@ -101,6 +103,8 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> { "party_totals" => check_party_totals(b, x), "party_tin_last4" => check_party_tin_last4(b, x), "project" => check_project(b, x), + "aging" => check_aging(b, x), + "document_dates" => check_document_dates(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 dc57f41e..5befdcfc 100644 --- a/crates/ledger-core/tests/bookspec/common.rs +++ b/crates/ledger-core/tests/bookspec/common.rs @@ -143,6 +143,7 @@ pub(crate) fn refusal(e: &LedgerError) -> String { LedgerError::InvalidDepreciationPeriod(_) => "invalid_depreciation_period", LedgerError::InvalidSchedule(_) => "invalid_schedule", LedgerError::UntaggedControlLine { .. } => "untagged_control_line", + LedgerError::PaymentBeforeDocument { .. } => "payment_before_document", LedgerError::UnbalancedEntry { .. } => "unbalanced", LedgerError::TooFewLines => "too_few_lines", LedgerError::NegativeAmountLine => "negative_amount", diff --git a/crates/ledger-core/tests/bookspec/engine.rs b/crates/ledger-core/tests/bookspec/engine.rs index 636266a2..f9a4e9f3 100644 --- a/crates/ledger-core/tests/bookspec/engine.rs +++ b/crates/ledger-core/tests/bookspec/engine.rs @@ -41,6 +41,25 @@ impl Engine for Books<'_> { } } +/// Why wanderbooks does not run `ex`: it is an example for an option of a +/// CHOICE rule (`under`) that wanderbooks did not pick (`PICKS`). The +/// runner skips such an example for the same reason; the loader tests do +/// it with this. +pub(crate) fn unpicked_option(ex: &Example) -> Option { + ex.under.iter().find_map(|u| { + let rule = RuleId::parse(&u.rule).ok()?; + let &(_, _, pick) = PICKS + .iter() + .find(|&&(area, n, _)| RuleId::new(area, n) == rule)?; + (pick != u.option).then(|| { + format!( + "for {} under {}; wanderbooks picks {pick}", + u.rule, u.option + ) + }) + }) +} + /// The option wanderbooks picks for each CHOICE record split out of an /// embedded choice (P14 unit S-C7); each is recorded in /// `docs/spec/claims/.md` as `**Pick (BS--):**`. diff --git a/crates/ledger-core/tests/bookspec/events.rs b/crates/ledger-core/tests/bookspec/events.rs index 96f478eb..4153c2e5 100644 --- a/crates/ledger-core/tests/bookspec/events.rs +++ b/crates/ledger-core/tests/bookspec/events.rs @@ -13,6 +13,7 @@ impl Books<'_> { ("bill", e.bill.is_some()), ("invoice", e.invoice.is_some()), ("write_off", e.write_off.is_some()), + ("payment", e.payment.is_some()), ("run_depreciation", e.run_depreciation.is_some()), ("dispose_asset", e.dispose_asset.is_some()), ("run_schedules", e.run_schedules.is_some()), @@ -21,7 +22,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, run_depreciation, dispose_asset, run_schedules or register_schedule", + "{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, payment, run_depreciation, dispose_asset, run_schedules or register_schedule", self.ex.id ), } @@ -35,7 +36,7 @@ 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"); + let dated = own || matches!(kind, "dispose_asset" | "write_off" | "payment"); assert_eq!( e.date.is_some(), dated, @@ -84,6 +85,10 @@ impl Books<'_> { e.write_off.is_none() || kind == "write_off", "{ex} event {n}: a write_off is its own event" ); + assert!( + e.payment.is_none() || kind == "payment", + "{ex} event {n}: a payment is its own event" + ); } /// Take event `n` as the books take it, keep what it posted and tag it @@ -192,11 +197,47 @@ impl Books<'_> { "{what}: entry {id}, which it made, is posted" ); } - if (own || kind == "write_off") && e.refused.is_none() { + if (own || matches!(kind, "write_off" | "payment")) && e.refused.is_none() { assert_eq!(posted.len(), 1, "{what}: {kind} posts one entry"); } } + /// The terms a document's example gives, and the due date the books take + /// them to (BS-arap-3): the engine's own `Terms::due_date`, except for a + /// date the parties agreed ("Due 2026-11-15"), which that call leaves to + /// its caller (the engine's contract: the caller passes the agreed date, + /// which the terms' canonical text carries). The example's spelling is + /// the canonical one, so the engine must print it back as written. + /// Without terms a document is due on its own date. + pub(crate) fn terms_due( + &self, + terms: Option<&str>, + date: NaiveDate, + what: &str, + ) -> (NaiveDate, Option) { + let Some(text) = terms else { + return (date, None); + }; + let parsed = Terms::parse(text).unwrap_or_else(|e| panic!("{what}: terms {text:?}: {e}")); + assert_eq!( + parsed.describe(), + text, + "{what}: the engine prints terms {text:?} back as written" + ); + let due = match parsed.kind() { + TermsKind::Custom => { + let agreed = text.strip_prefix("Due ").unwrap_or_else(|| { + panic!("{what}: custom terms {text:?} carry their date after \"Due \"") + }); + crate::date(agreed, what) + } + _ => parsed + .due_date(date) + .unwrap_or_else(|e| panic!("{what}: terms {text:?} on {date}: {e}")), + }; + (due, Some(parsed)) + } + /// An invoice's or bill's lines: `amount` (one line, described as the /// event) or `lines`, exactly one; each project a `setup.projects` /// name. @@ -368,8 +409,18 @@ impl Books<'_> { v } }; + let (due, terms) = self.terms_due(b.terms.as_deref(), day(), what); self.store - .create_bill(vendor, day(), day(), lines) + .create_bill_with( + vendor, + day(), + due, + lines, + BillFields { + terms, + ..BillFields::default() + }, + ) .map(|_| ()) } "invoice" => { @@ -383,8 +434,18 @@ impl Books<'_> { c } }; + let (due, terms) = self.terms_due(i.terms.as_deref(), day(), what); self.store - .create_invoice(customer, day(), day(), lines) + .create_invoice_with( + customer, + day(), + due, + lines, + InvoiceFields { + terms, + ..InvoiceFields::default() + }, + ) .map(|_| ()) } "write_off" => { @@ -432,6 +493,36 @@ impl Books<'_> { ) .map(drop) } + "payment" => { + let p = e.payment.as_ref().expect("checked: a payment"); + let entry = self.entry_of(p.document, what); + let amount = money(&p.amount); + let cash = self.id(&p.account); + let invoice = self + .store + .ledger() + .invoices() + .into_iter() + .find(|i| i.entry_id == entry) + .map(|i| i.id); + let bill = self + .store + .ledger() + .bills() + .into_iter() + .find(|b| b.entry_id == entry) + .map(|b| b.id); + match (invoice, bill) { + (Some(invoice), _) => self + .store + .receive_payment(invoice, day(), amount, cash) + .map(drop), + (None, Some(bill)) => self.store.pay_bill(bill, day(), amount, cash).map(drop), + (None, None) => { + panic!("{what}: event {} posted no invoice or bill", p.document) + } + } + } "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 70c868a0..727aae7d 100644 --- a/crates/ledger-core/tests/bookspec/examples.rs +++ b/crates/ledger-core/tests/bookspec/examples.rs @@ -1,3 +1,4 @@ +use crate::engine::unpicked_option; use crate::*; /// The `Engine` adapter over `Store` runs every example through the @@ -17,6 +18,40 @@ pub(crate) fn the_runner_reports_every_claimed_rule_green() { "the runner is not green:\n{}", report.failures().join("\n") ); + // An example for an option wanderbooks did not pick is not run; every + // other one is, and passes. + let skipped = report.skipped(); + let unpicked: Vec<&str> = examples + .iter() + .filter(|ex| unpicked_option(ex).is_some()) + .map(|ex| ex.id.as_str()) + .collect(); + assert_eq!( + skipped.len(), + unpicked.len(), + "the runner skips exactly the examples for unpicked options: {skipped:?}" + ); + for id in &unpicked { + assert!( + skipped.iter().any(|s| s.starts_with(&format!("{id}:"))), + "{id} is skipped" + ); + } + let ran = report.examples.len() - skipped.len(); + let passed = report + .examples + .iter() + .filter(|e| e.skipped.is_none() && e.failure.is_none()) + .count(); + eprintln!( + "bookspec runner: {} examples, {ran} run, {passed} passed, {} skipped (an option wanderbooks did not pick)", + report.examples.len(), + skipped.len() + ); + for s in &skipped { + eprintln!(" skipped {s}"); + } + assert_eq!(ran, passed, "every example run passed"); for rule in bookspec_checker::covered_rules() { assert_eq!( report.rules.get(&rule.id), @@ -39,6 +74,7 @@ pub(crate) fn every_bookspec_example_holds() { let files = bookspec_checker::examples(); let mut ids = BTreeSet::new(); let mut checked: BTreeMap = BTreeMap::new(); + let mut skipped = Vec::new(); for (name, text) in &files { let ex = Example::from_toml(text).unwrap_or_else(|e| panic!("{name}: {e}")); let stem = name.strip_suffix(".toml").unwrap(); @@ -57,6 +93,12 @@ pub(crate) fn every_bookspec_example_holds() { ); assert!(!ex.sources.is_empty(), "{}: every rule is sourced", ex.id); assert!(!ex.expect.is_empty(), "{}: something to expect", ex.id); + // The examples for an option wanderbooks did not pick are for + // another engine; they are read (above) and not run. + if let Some(why) = unpicked_option(&ex) { + skipped.push(format!("{} {why}", ex.id)); + continue; + } for (q, by) in run(&ex) { if let Some(by) = by { eprintln!("{}: {q} is checked by {by}", ex.id); @@ -102,8 +144,21 @@ pub(crate) fn every_bookspec_example_holds() { ("k1_tax_basis", 4), ("k1_reconciliation", 2), ("project", 6), + ("aging", 4), + ("document_dates", 8), ] { let n = checked.get(q).copied().unwrap_or(0); assert!(n >= at_least, "{q} ran {n} times, fewer than {at_least}"); } + eprintln!( + "bookspec examples: {} files, {} run, {} skipped (an option wanderbooks did not pick): {skipped:?}", + files.len(), + files.len() - skipped.len(), + skipped.len() + ); + assert_eq!( + skipped.len(), + 3, + "the three unpicked-option examples: {skipped:?}" + ); } diff --git a/crates/ledger-core/tests/bookspec/main.rs b/crates/ledger-core/tests/bookspec/main.rs index 69fca17e..e0f9c456 100644 --- a/crates/ledger-core/tests/bookspec/main.rs +++ b/crates/ledger-core/tests/bookspec/main.rs @@ -50,13 +50,13 @@ pub(crate) use ledger_core::parties::{Basis, MoneyAccounts}; pub(crate) use ledger_core::settings::{Company, Source}; pub(crate) use ledger_core::tax_capital::TaxCapitalRow; pub(crate) use ledger_core::{ - AccountType, AssetId, CashFlowParams, CashFlowSection, CashFlowStatement, CloseTo, Currency, - Dated1099, Decision1099, DocumentLine, EntryId, EntryStatus, ExemptReason, Form1099, - InstrumentId, InstrumentKind, Ledger, LedgerError, MemberCapital, MemberClose, Money, NewAsset, - NewSchedule, PartyId, PartyMember, PartyShare, PaymentAccounts, ReconcilingKind, Role, - ScheduleConvention, ScheduleId, ScheduleKind, Share, Side, TinFacts, TinType, VendorId, - W9Facts, cash_flow, members_equity, profit_and_loss_for_period, trial_balance_as_of, - vendor_1099_report, + AccountType, AssetId, BillFields, CashFlowParams, CashFlowSection, CashFlowStatement, CloseTo, + Currency, Dated1099, Decision1099, DocumentLine, EntryId, EntryStatus, ExemptReason, Form1099, + InstrumentId, InstrumentKind, InvoiceFields, Ledger, LedgerError, MemberCapital, MemberClose, + Money, NewAsset, NewSchedule, PartyId, PartyMember, PartyShare, PaymentAccounts, + ReconcilingKind, Role, ScheduleConvention, ScheduleId, ScheduleKind, Share, Side, Terms, + TermsKind, TinFacts, TinType, VendorId, W9Facts, cash_flow, members_equity, + profit_and_loss_for_period, trial_balance_as_of, vendor_1099_report, }; pub(crate) use ledger_store::{DepreciationRun, DisposalPreview, Store, StoreError}; pub(crate) use rust_decimal::Decimal; @@ -75,6 +75,7 @@ pub(crate) use common::*; pub(crate) use queries::assets::*; pub(crate) use queries::commands::*; pub(crate) use queries::dates::*; +pub(crate) use queries::documents::*; pub(crate) use queries::formats::*; pub(crate) use queries::parties::*; pub(crate) use queries::statements::*; diff --git a/crates/ledger-core/tests/bookspec/queries/documents.rs b/crates/ledger-core/tests/bookspec/queries/documents.rs new file mode 100644 index 00000000..ff40d161 --- /dev/null +++ b/crates/ledger-core/tests/bookspec/queries/documents.rs @@ -0,0 +1,98 @@ +use crate::*; + +/// The buckets of an aging, as the examples key them (BS-arap-1), beside +/// the engine's `AgingRow` fields they read. +const BUCKETS: [&str; 5] = ["current", "1-30", "31-60", "61-90", "90+"]; + +impl Books<'_> { + /// The engine's `ar_aging` or `ap_aging` as of the day (BS-arap-1): the + /// buckets in total, `total`, and each party's buckets, read straight + /// from the engine's rows, never recomputed here. + pub(crate) fn answer_aging(&self, q: &Query) -> Result { + let as_of = self.q_day(q)?; + let rows = match q.of.as_deref() { + Some("receivables") => self.l().ar_aging(as_of), + Some("payables") => self.l().ap_aging(as_of), + _ => return Err(self.missing("receivables or payables")), + } + .map_err(|e| engine_refusal(RuleId::new(Area::Arap, 1), e))?; + let mut m = JsonMap::new(); + let mut totals = [Decimal::ZERO; 5]; + for row in &rows { + let buckets = [ + row.current, + row.days_30, + row.days_60, + row.days_90, + row.days_90_plus, + ]; + for ((name, owed), total) in BUCKETS.iter().zip(buckets).zip(totals.iter_mut()) { + m.insert(format!("{}.{name}", row.name), Value::String(figure(owed))); + *total += owed; + } + } + for (name, total) in BUCKETS.iter().zip(totals) { + m.insert(name.to_string(), Value::String(figure(total))); + } + m.insert( + "total".to_string(), + Value::String(figure(totals.iter().copied().sum())), + ); + Ok(Value::Object(m)) + } + + /// The due date and discount date the document event's terms give + /// (BS-arap-3), as the engine stored the document and its terms. + pub(crate) fn answer_document_dates(&self, q: &Query) -> Result { + let n = q.document.ok_or_else(|| self.missing("document"))?; + let entry = self.entry_or_refuse(n)?; + let l = self.l(); + let (date, due, terms) = match ( + l.invoices().into_iter().find(|i| i.entry_id == entry), + l.bills().into_iter().find(|b| b.entry_id == entry), + ) { + (Some(i), _) => (i.date, i.due_date, i.terms.clone()), + (None, Some(b)) => (b.date, b.due_date, b.terms.clone()), + (None, None) => return Err(self.missing("invoice or bill")), + }; + let discount_by = terms + .and_then(|t| t.discount_by(date)) + .map_or_else(|| "none".to_string(), |d| d.to_string()); + Ok(json_figures([ + ("due".to_string(), due.to_string()), + ("discount_by".to_string(), discount_by), + ])) + } +} + +/// Check an `aging` expectation: every figure the engine gives, and no +/// other (the example lists everything it covers). +pub(crate) fn check_aging(b: &Books<'_>, x: &Expect) { + check_figures(b, x, b.answer_aging(&x.query())); +} + +/// Check a `document_dates` expectation: `due` and `discount_by`, both +/// given. +pub(crate) fn check_document_dates(b: &Books<'_>, x: &Expect) { + check_figures(b, x, b.answer_document_dates(&x.query())); +} + +fn check_figures(b: &Books<'_>, x: &Expect, answer: Result) { + let ex = b.ex; + let Value::Object(got) = + answer.unwrap_or_else(|r| panic!("{}: {}: {}", ex.id, x.query, r.reason)) + else { + panic!("{}: {} answers a table", ex.id, x.query) + }; + let keys: BTreeSet = got.keys().cloned().collect(); + exactly(ex, x, &keys); + for (key, want) in x.figures(&ex.id) { + assert_eq!( + got[key].as_str(), + Some(want.as_str()), + "{}: {} {key}", + ex.id, + x.query + ); + } +} diff --git a/crates/ledger-core/tests/bookspec/queries/mod.rs b/crates/ledger-core/tests/bookspec/queries/mod.rs index a49400b2..a1e6a4aa 100644 --- a/crates/ledger-core/tests/bookspec/queries/mod.rs +++ b/crates/ledger-core/tests/bookspec/queries/mod.rs @@ -3,6 +3,7 @@ use crate::*; pub(crate) mod assets; pub(crate) mod commands; pub(crate) mod dates; +pub(crate) mod documents; pub(crate) mod formats; pub(crate) mod parties; pub(crate) mod statements; @@ -84,6 +85,8 @@ impl Books<'_> { "party_totals" => self.answer_party_totals(q), "party_tin_last4" => self.answer_party_tin_last4(q), "project" => self.answer_project(q), + "aging" => self.answer_aging(q), + "document_dates" => self.answer_document_dates(q), "run" => self.answer_run(q), "disposal" => self.answer_disposal(q), "depreciation_schedule" => self.answer_depreciation_schedule(q), diff --git a/docs/spec/claims/arap.md b/docs/spec/claims/arap.md index 11ec2997..cc9ee638 100644 --- a/docs/spec/claims/arap.md +++ b/docs/spec/claims/arap.md @@ -27,6 +27,17 @@ Rules: B-18, B-38, B-39, B-40, B-41, B-42. `a_payment_never_predates_its_document`, `aging_as_of_ignores_a_later_reversal`, `a_voided_invoice_never_ages`, `status_is_a_function_of_journal_and_date`. +**Bookspec examples:** `arap-aging-buckets` (BS-arap-1); +`arap-a-document-due-today-is-current` (BS-arap-7); +`arap-an-aging-shows-what-stood-on-its-day` (BS-arap-8); +`arap-a-payment-before-its-invoice-is-refused` (BS-arap-9), run by the +adapter through `Ledger::{ar_aging, ap_aging, receive_payment, pay_bill}` +(`tests/bookspec/queries/documents.rs`). The examples for the options +wanderbooks did not pick (`arap-a-document-due-today-is-one-day-past-due`, +`arap-an-aging-shows-what-stands-today`, +`arap-a-payment-before-its-invoice-is-accepted`) name them (`under`) and the +runner skips them for the pick above. + ## B-38 A document's figures are its ledger lines that stand; a control account is its documents **bookspec:** `BS-arap-2` @@ -137,7 +148,10 @@ check_void_document}`, the control guard). **Checked:** **Enforced:** `ledger_core::Terms` (`new`, `parse`, `due_date`, `discount_by`, `describe`), `kernel::discount_max`, `kernel::line_amount`, `Ledger::check_document_line_account`. -**Checked:** `ledger-core` `tests/spec_documents.rs` +**Checked:** bookspec example `arap-terms-give-due-and-discount-dates` +(the adapter takes each due date from `Terms::due_date`, but for a date +the parties agreed, which that call leaves to its caller, and each discount +date from `Terms::discount_by`); `ledger-core` `tests/spec_documents.rs` (`terms_derive_due_dates`, `discount_bounds_and_late_reason`, `terms_describe_and_parse_round_trip`, `qty_times_price_must_equal_amount`, `document_line_account_refuses_roles_cash_and_placeholders`, From 71a4e7e59d9dc85b0dbaf9226ff48414dbe0248b Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:25:16 -0700 Subject: [PATCH 2/4] fix(core): custom terms are due on the date they give BS-arap-3 statement 1: custom terms ("Due 2026-11-15") are due on the date they give. Terms::due_date returned the document's own date for them, so the MCP path (create_invoice / create_bill, from the terms given or a party's default) stored an invoice dated 2026-11-01 on "Due 2026-11-15" as due 2026-11-01: a document that read past due two weeks early in the aging. Terms now keeps the agreed date (a new `agreed` field, Some exactly for custom terms, with Terms::agreed_date), and due_date returns it, refusing an agreed date before the document's like any due date before its document. TermsKind keeps its shape, so stored kinds read as before. Terms read back from storage fill `agreed` from their canonical text when it is missing, and a custom terms with no readable date is refused rather than invented. Stored books: the journal records each document's due_date itself (invoice.created / bill.created payloads) and replay reads it, never recomputing it from the terms, so a document already written keeps the due date it recorded (posted is forever). New journal entries with custom terms carry the extra "agreed" key; older ones read as before. No golden under crates/*/tests/golden holds custom terms, so none changes; the live books have no invoices or bills. Through the tool, an invoice dated 2026-11-01 on "Due 2026-11-15": due 2026-11-01 before, 2026-11-15 after. Tests: ledger-core custom_terms_are_due_on_the_date_they_give (Terms, the stored document, the storage round trip incl. the older form, and the refusals) and the same through books.create_invoice / create_bill / a party's default terms and the refusal of a document dated after the agreed day (ledger-cli documents.rs). Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-cli/tests/documents.rs | 62 +++++++++++++++ crates/ledger-core/src/arap.rs | 90 ++++++++++++++++++---- crates/ledger-core/tests/spec_documents.rs | 54 +++++++++++++ 3 files changed, 192 insertions(+), 14 deletions(-) diff --git a/crates/ledger-cli/tests/documents.rs b/crates/ledger-cli/tests/documents.rs index f7368c28..83f450b3 100644 --- a/crates/ledger-cli/tests/documents.rs +++ b/crates/ledger-cli/tests/documents.rs @@ -496,6 +496,68 @@ fn terms_fall_back_in_order() { assert_eq!(bill["terms"], "Net 10", "{bill}"); } +/// BS-arap-3 statement 1 through the tool: terms "Due 2026-11-15", from +/// the caller or from a party's defaults, make an invoice or a bill due on +/// the 15th, not on the document's own date; a document dated after the +/// agreed day is refused and writes nothing. +#[test] +fn custom_terms_are_due_on_the_date_they_give() { + let books = Books::new("documents-custom-terms"); + let mut m = Mcp::spawn(&books); + let harbor = m.customer("Harbor Coffee"); + let line = json!([{"description": "Work", "amount": "100.00"}]); + let invoice = |date: &str, extra: Value| { + let mut args = json!({"customer": harbor.to_string(), "date": date, + "lines": line, "confirmed": true}); + for (k, v) in extra.as_object().unwrap() { + args[k] = v.clone(); + } + args + }; + + // Terms given. + let given = m.call( + "books.create_invoice", + invoice("2026-11-01", json!({"terms": "Due 2026-11-15"})), + ); + assert_eq!(given["due_date"], "2026-11-15", "{given}"); + assert_eq!(given["terms"], "Due 2026-11-15", "{given}"); + + // The customer's default terms. + let party = m.party_of("Harbor Coffee"); + m.call( + "books.update_party", + json!({"party": party.to_string(), "default_terms_as_customer": "Due 2026-12-01"}), + ); + let by_party = m.call("books.create_invoice", invoice("2026-11-02", json!({}))); + assert_eq!(by_party["due_date"], "2026-12-01", "{by_party}"); + assert_eq!(by_party["terms"], "Due 2026-12-01", "{by_party}"); + + // A bill, terms given. + let coast = m.vendor("Coastline Hosting"); + m.expense("6500", "Hosting"); + let file = m.upload(b"coastline", "coastline.pdf", "receipt"); + let bill = m.call( + "books.create_bill", + json!({"vendor": coast.to_string(), "date": "2026-11-01", "vendor_ref": "CH-1", + "terms": "Due 2026-11-20", + "lines": [{"description": "Hosting", "amount": "100.00", "account": "6500"}], + "upload_id": file, "confirmed": true}), + ); + assert_eq!(bill["due_date"], "2026-11-20", "{bill}"); + + // Dated after the agreed day: refused. + let before = books.journal(); + let late = m + .try_call( + "books.create_invoice", + invoice("2026-11-16", json!({"terms": "Due 2026-11-15"})), + ) + .unwrap_err(); + assert!(late.contains("due"), "{late}"); + assert_eq!(books.journal(), before, "a refusal writes nothing"); +} + /// A customer given by id and by name is the same record (the old /// `party_id` spelling is gone, P5); a number that is one record's id and /// another's name is refused, never guessed. diff --git a/crates/ledger-core/src/arap.rs b/crates/ledger-core/src/arap.rs index 2a89a679..5f92f1ae 100644 --- a/crates/ledger-core/src/arap.rs +++ b/crates/ledger-core/src/arap.rs @@ -497,9 +497,9 @@ pub enum TermsKind { /// Due `n` days after the last day of the document's month (Net n /// EOM). NetEom(u16), - /// Due on a date the parties agreed; the caller passes it to - /// [`Terms::due_date`], and [`Terms::describe`] carries it for - /// people. + /// Due on a date the parties agreed. The date lives in the [`Terms`] + /// ([`Terms::agreed_date`]); [`Terms::due_date`] returns it, and + /// [`Terms::describe`] prints it for people. Custom, } @@ -523,7 +523,8 @@ pub struct EarlyDiscount { /// goods; for services, the contract. /// INVARIANTS: /// 1. Net n = date + n; Net n EOM = the last day of date's month + n; -/// due on receipt = date; Custom = the given date. Every result is +/// due on receipt = date; Custom = the date the terms give (never +/// the document's own date). Every result is /// >= the document date and in the calendar (calendar::check); n is /// 0..=3650. /// 2. discount_by = date + d, d < the net days; no discount with due on @@ -532,6 +533,7 @@ pub struct EarlyDiscount { /// canonical spellings, case-insensitively, and nothing else. /// ``` #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(try_from = "TermsWire")] pub struct Terms { /// How the due date counts. kind: TermsKind, @@ -541,6 +543,52 @@ pub struct Terms { /// The canonical text: "Net 30", "Net 15 EOM", "2/10 net 30", "Due on /// receipt", "Due 2026-11-15". text: String, + /// The date custom terms give, and only custom terms: `Some` exactly + /// when `kind` is [`TermsKind::Custom`]. Terms stored before this field + /// existed carry the date only in their text; reading them fills it + /// from there ([`TermsWire`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + agreed: Option, +} + +/// Terms as stored. Reading is the one place a missing `agreed` is filled +/// from the canonical text ("Due 2026-11-15"), so a book written before +/// custom terms carried their date still reads, and a Custom without any +/// readable date is refused rather than invented. +#[derive(Deserialize)] +struct TermsWire { + kind: TermsKind, + #[serde(default)] + discount: Option, + text: String, + #[serde(default)] + agreed: Option, +} + +impl TryFrom for Terms { + type Error = String; + + fn try_from(w: TermsWire) -> Result { + let agreed = match (w.kind, w.agreed) { + (TermsKind::Custom, Some(d)) => Some(d), + (TermsKind::Custom, None) => Some( + w.text + .trim() + .to_lowercase() + .strip_prefix("due ") + .and_then(|r| NaiveDate::parse_from_str(r.trim(), "%Y-%m-%d").ok()) + .ok_or_else(|| format!("custom terms {:?} give no date", w.text))?, + ), + (_, None) => None, + (_, Some(_)) => return Err("only custom terms carry an agreed date".into()), + }; + Ok(Terms { + kind: w.kind, + discount: w.discount, + text: w.text, + agreed, + }) + } } impl Terms { @@ -579,18 +627,20 @@ impl Terms { kind, discount, text: compose_terms_text(kind, discount), + agreed: None, }) } /// Custom terms due on `due`: the parties agreed a date rather than a - /// count of days. Its text carries the date for people; the document - /// stores the due date itself. + /// count of days. The terms keep the date ([`Terms::agreed_date`]) and + /// print it for people; [`Terms::due_date`] returns it. pub fn custom(due: NaiveDate) -> Result { crate::calendar::check(due)?; Ok(Terms { kind: TermsKind::Custom, discount: None, text: format!("Due {due}"), + agreed: Some(due), }) } @@ -599,6 +649,11 @@ impl Terms { self.kind } + /// The date custom terms give; `None` for every other kind. + pub fn agreed_date(&self) -> Option { + self.agreed + } + /// The early-payment discount, when there is one. pub fn discount(&self) -> Option { self.discount @@ -611,17 +666,24 @@ impl Terms { /// The date payment is due for a document dated `date`. /// - /// For [`TermsKind::Custom`] the caller passes the agreed date itself - /// (there is no count to derive it from); for every other kind `date` - /// is the document's date. The result is never before `date` and - /// always in the calendar: a due date past 9999-12-31 is refused + /// `date` is the document's date. Custom terms are due on the date + /// they give, whatever `date` is (BS-arap-3 statement 1); an agreed + /// date before `date` is refused like any due date before its + /// document ([`validate_due_date`]). The result is never before `date` + /// and always in the calendar: a due date past 9999-12-31 is refused /// ([`LedgerError::DateOverflow`]), never a panic. pub fn due_date(&self, date: NaiveDate) -> Result { crate::calendar::check(date)?; - let due = match self.kind { - TermsKind::DueOnReceipt | TermsKind::Custom => date, - TermsKind::Net(n) => add_days(date, n)?, - TermsKind::NetEom(n) => add_days(last_day_of_month(date)?, n)?, + let due = match (self.kind, self.agreed) { + (TermsKind::Custom, Some(agreed)) => agreed, + (TermsKind::Custom, None) => { + return Err(LedgerError::TermsUnreadable( + "custom terms give no date".into(), + )); + } + (TermsKind::DueOnReceipt, _) => date, + (TermsKind::Net(n), _) => add_days(date, n)?, + (TermsKind::NetEom(n), _) => add_days(last_day_of_month(date)?, n)?, }; validate_due_date(date, due)?; Ok(due) diff --git a/crates/ledger-core/tests/spec_documents.rs b/crates/ledger-core/tests/spec_documents.rs index 2b638f36..1986e901 100644 --- a/crates/ledger-core/tests/spec_documents.rs +++ b/crates/ledger-core/tests/spec_documents.rs @@ -1637,6 +1637,60 @@ fn doc_line( } } +/// BS-arap-3 statement 1: custom terms are due on the date they give, not +/// on the document's own date. A document dated 2026-11-01 on "Due +/// 2026-11-15" is due on the 15th (through Terms::due_date and through the +/// stored document); an agreed date before the document's is refused like +/// any due date before its document; terms read back from storage (even +/// written before they carried the date) keep the date. +#[test] +fn custom_terms_are_due_on_the_date_they_give() { + let on = d(2026, 11, 1); + let agreed = d(2026, 11, 15); + let terms = Terms::parse("Due 2026-11-15").unwrap(); + assert_eq!(terms.agreed_date(), Some(agreed)); + assert_eq!(terms.due_date(on).unwrap(), agreed); + // The same, whichever day the document is dated (up to the 15th). + assert_eq!(terms.due_date(d(2026, 11, 15)).unwrap(), agreed); + assert_eq!(terms.due_date(d(2026, 1, 3)).unwrap(), agreed); + // Dated after the agreed day, the terms contradict the document. + assert!(terms.due_date(d(2026, 11, 16)).is_err()); + // Other kinds give no agreed date. + assert_eq!(Terms::parse("Net 30").unwrap().agreed_date(), None); + + // Through the engine: an invoice and a bill on those terms. + let mut b = books(); + let invoice = + b.l.create_invoice_with( + b.customer, + on, + terms.due_date(on).unwrap(), + line("Work", 10_000), + InvoiceFields { + terms: Some(terms.clone()), + ..InvoiceFields::default() + }, + ) + .unwrap(); + let stored = b.l.get_invoice(invoice).unwrap(); + assert_eq!(stored.due_date, agreed); + assert_eq!(stored.terms.as_ref().unwrap().describe(), "Due 2026-11-15"); + + // Storage round-trips the date; an older stored form, which had the + // text only, reads back with the date from its text. + let json = serde_json::to_value(&terms).unwrap(); + assert_eq!(json["agreed"], "2026-11-15"); + assert_eq!(serde_json::from_value::(json).unwrap(), terms); + let old = serde_json::json!({"kind": "custom", "text": "Due 2026-11-15"}); + assert_eq!(serde_json::from_value::(old).unwrap(), terms); + // Custom terms with no readable date are refused, not invented. + let none = serde_json::json!({"kind": "custom", "text": "Due"}); + assert!(serde_json::from_value::(none).is_err()); + // A date on any other kind is refused. + let stray = serde_json::json!({"kind": {"net": 30}, "text": "Net 30", "agreed": "2026-11-15"}); + assert!(serde_json::from_value::(stray).is_err()); +} + /// BS-arap-3 SCENARIOS: Net 30, Net 15 EOM, a leap day, due on receipt, a /// custom date, and the 9999-12 bound refused instead of panicking. #[test] From e6c0d0d51b43b5d06ab724acae0827399cc211e2 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:25:16 -0700 Subject: [PATCH 3/4] test(core): the adapter reads due dates from the engine The bookspec adapter took a custom terms' due date by parsing the example's terms text, which sidestepped the engine bug that custom terms were due on the document's own date, so no example could catch it. It now takes every due date, custom included, from Terms::due_date; an example on "Due 2026-11-15" passes only if the engine computes 2026-11-15 (BS-arap-3). Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/tests/bookspec/events.rs | 26 +++++++-------------- crates/ledger-core/tests/bookspec/main.rs | 4 ++-- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/crates/ledger-core/tests/bookspec/events.rs b/crates/ledger-core/tests/bookspec/events.rs index 4153c2e5..00eba781 100644 --- a/crates/ledger-core/tests/bookspec/events.rs +++ b/crates/ledger-core/tests/bookspec/events.rs @@ -203,12 +203,12 @@ impl Books<'_> { } /// The terms a document's example gives, and the due date the books take - /// them to (BS-arap-3): the engine's own `Terms::due_date`, except for a - /// date the parties agreed ("Due 2026-11-15"), which that call leaves to - /// its caller (the engine's contract: the caller passes the agreed date, - /// which the terms' canonical text carries). The example's spelling is - /// the canonical one, so the engine must print it back as written. - /// Without terms a document is due on its own date. + /// them to (BS-arap-3): the engine's own `Terms::due_date` for every + /// kind, a date the parties agreed ("Due 2026-11-15") included. The + /// example's spelling is the canonical one, so the engine must print it + /// back as written. Nothing of the date is read out of the text here: + /// the example can only pass if the engine computes it. Without terms a + /// document is due on its own date. pub(crate) fn terms_due( &self, terms: Option<&str>, @@ -224,17 +224,9 @@ impl Books<'_> { text, "{what}: the engine prints terms {text:?} back as written" ); - let due = match parsed.kind() { - TermsKind::Custom => { - let agreed = text.strip_prefix("Due ").unwrap_or_else(|| { - panic!("{what}: custom terms {text:?} carry their date after \"Due \"") - }); - crate::date(agreed, what) - } - _ => parsed - .due_date(date) - .unwrap_or_else(|e| panic!("{what}: terms {text:?} on {date}: {e}")), - }; + let due = parsed + .due_date(date) + .unwrap_or_else(|e| panic!("{what}: terms {text:?} on {date}: {e}")); (due, Some(parsed)) } diff --git a/crates/ledger-core/tests/bookspec/main.rs b/crates/ledger-core/tests/bookspec/main.rs index e0f9c456..f835ecaf 100644 --- a/crates/ledger-core/tests/bookspec/main.rs +++ b/crates/ledger-core/tests/bookspec/main.rs @@ -55,8 +55,8 @@ pub(crate) use ledger_core::{ InstrumentId, InstrumentKind, InvoiceFields, Ledger, LedgerError, MemberCapital, MemberClose, Money, NewAsset, NewSchedule, PartyId, PartyMember, PartyShare, PaymentAccounts, ReconcilingKind, Role, ScheduleConvention, ScheduleId, ScheduleKind, Share, Side, Terms, - TermsKind, TinFacts, TinType, VendorId, W9Facts, cash_flow, members_equity, - profit_and_loss_for_period, trial_balance_as_of, vendor_1099_report, + TinFacts, TinType, VendorId, W9Facts, cash_flow, members_equity, profit_and_loss_for_period, + trial_balance_as_of, vendor_1099_report, }; pub(crate) use ledger_store::{DepreciationRun, DisposalPreview, Store, StoreError}; pub(crate) use rust_decimal::Decimal; From 08733c6fa2043c5ea2b33aa55c67029d1942f73b Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:56:37 -0700 Subject: [PATCH 4/4] test(core): five examples are for options wanderbooks did not pick The bookspec adapter's test pinned the examples for an unpicked option at three (the other option of BS-arap-7, -8 and -9). The bookspec fixes give BS-prepaid-2's equal-months and BS-ledger-20's refuse each an example of their own, so no option-example allow-list grows; wanderbooks picks daily and warn-by-default, so it skips both, and the count is five. The runner and the loader tests still agree on exactly which. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/tests/bookspec/examples.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ledger-core/tests/bookspec/examples.rs b/crates/ledger-core/tests/bookspec/examples.rs index 727aae7d..a8e5b0be 100644 --- a/crates/ledger-core/tests/bookspec/examples.rs +++ b/crates/ledger-core/tests/bookspec/examples.rs @@ -156,9 +156,12 @@ pub(crate) fn every_bookspec_example_holds() { files.len() - skipped.len(), 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). assert_eq!( skipped.len(), - 3, - "the three unpicked-option examples: {skipped:?}" + 5, + "the five unpicked-option examples: {skipped:?}" ); }