From 71a4e7e59d9dc85b0dbaf9226ff48414dbe0248b Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 21:25:16 -0700 Subject: [PATCH] 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]