diff --git a/crates/ledger-core/src/audit.rs b/crates/ledger-core/src/audit.rs index 2c8ed2ed..80e70507 100644 --- a/crates/ledger-core/src/audit.rs +++ b/crates/ledger-core/src/audit.rs @@ -1,4 +1,4 @@ -//! The audit's statements checks (plan P8; BS-ledger-13): the books, +//! The audit's statements checks (plan P8; WB-ledger-16): the books, //! read as an auditor would, through a date, as a list of findings. //! //! ```text @@ -481,24 +481,36 @@ fn closes(ledger: &Ledger, through: NaiveDate) -> Vec { continue; } if let Some((_, split)) = ledger.member_close_split(p.id) { - out.extend(check_split(p.id, &p.name, &split, unit)); + let trued_up = ledger.member_close_trued_up(p.id).unwrap_or(false); + out.extend(check_split(p.id, &p.name, &split, unit, trued_up)); } } out } /// One close's members: each one's running total of the closes must be -/// within a minor unit of its exact share (the cumulative rule, -/// `kernel::apportion_cumulative`). +/// under a minor unit from its exact share (the cumulative rule, +/// `kernel::apportion_cumulative`; BS-partner-1 statement 5). +/// +/// `trued_up` says the count has had a close under the cumulative rule +/// that posted an entry ([`crate::Ledger::member_close_trued_up`]). Until +/// then the count may still carry the rounding of closes made under the +/// older rules, which the first such close trues up (BS-partner-1 +/// statement 6; WB-partner-1), so only a drift beyond a unit is raised. +/// Once trued up, a drift of a unit or more is raised: the bound is strict. pub fn check_split( period: u64, name: &str, split: &[crate::periods::MemberSplit], unit: Decimal, + trued_up: bool, ) -> Vec { split .iter() - .filter(|m| (m.running - m.exact).abs() > unit) + .filter(|m| { + let drift = (m.running - m.exact).abs(); + if trued_up { drift >= unit } else { drift > unit } + }) .map(|m| { Finding::new( "close_split_drifts", @@ -670,7 +682,7 @@ fn settings_problems(problems: &[String]) -> Vec { } // --------------------------------------------------------------------------- -// Scope, method and the attestation bar (BS-ledger-13; D-9) +// Scope, method and the attestation bar (WB-ledger-16; D-9) // --------------------------------------------------------------------------- /// What an audit covers. @@ -763,7 +775,7 @@ impl Effort { } /// How an attestation was made, as the client says (self-reported: the -/// books record the claim, never prove it; BS-ledger-13). +/// books record the claim, never prove it; WB-ledger-16). #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)] pub struct Method { /// The model that checked, as it names itself. diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index 6687c61e..0de607ec 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -3991,6 +3991,7 @@ impl Ledger { closed: Decimal::ZERO, given: vec![Decimal::ZERO; members.len()], order: Vec::new(), + trued_up: false, }; for p in closed { let Some(m) = &p.members_closed else { @@ -4000,6 +4001,8 @@ impl Ledger { break; } regime.since_seq = p.close_seq; + regime.trued_up |= matches!(m.rule, periods::MemberRule::Cumulative { .. }) + && p.closing_entry.is_some(); regime.order.clone_from(&m.members); regime.closed += m.net; for ((capital, _), part) in m.members.iter().zip(&m.parts) { @@ -4044,6 +4047,24 @@ impl Ledger { Some((since_seq, split)) } + /// Whether a closed members period's count has been trued up by the + /// close or an earlier one of its count: a close under the cumulative + /// rule that posted an entry has run the first true-up of the rounding + /// of closes under earlier rules (WB-partner-1), so each member's + /// running total is then strictly under one minor unit from exact + /// (BS-partner-1 statement 5). Before that, a count that holds closes + /// from the older rules may still be a unit or more away. `None` for a + /// period not closed to members. + pub fn member_close_trued_up(&self, id: PeriodId) -> Option { + let p = self.periods.get(&id)?; + let m = p.members_closed.as_ref()?; + let seq = p.close_seq?; + Some( + self.regime_where(&m.members, |q| q.close_seq <= Some(seq)) + .trued_up, + ) + } + /// The net closed by the run of cumulative members closes, with exactly /// these members and shares, that ends with the latest close: zero if /// the latest close was anything else (or there is none). @@ -9665,6 +9686,11 @@ pub(crate) struct Regime { /// count the next members close begins, when it is these members' /// ([`Ledger::members_regime`]). Empty when there is none. pub order: Vec<(AccountId, Decimal)>, + /// Whether a close under the cumulative rule that posted an entry is + /// among the count's closes: its true-up has run, so each member's + /// running total is then under one minor unit from exact + /// (BS-partner-1 statement 5). + pub trued_up: bool, } impl Regime { diff --git a/crates/ledger-core/tests/audit.rs b/crates/ledger-core/tests/audit.rs index 1702e2e3..a0ec1917 100644 --- a/crates/ledger-core/tests/audit.rs +++ b/crates/ledger-core/tests/audit.rs @@ -196,6 +196,7 @@ fn seeds() -> Vec<(&'static str, Vec)> { exact: dec("1.05"), }], dec("0.01"), + true, ), )); diff --git a/crates/ledger-core/tests/audit_branches.rs b/crates/ledger-core/tests/audit_branches.rs new file mode 100644 index 00000000..02c53c1c --- /dev/null +++ b/crates/ledger-core/tests/audit_branches.rs @@ -0,0 +1,677 @@ +//! The audit's branches (plan P14 unit V-D2): the words, orders and +//! thresholds of `audit.rs` that `tests/audit.rs`'s one-seed-per-code +//! test does not reach. Coverage found `audit.rs` at 80% of lines and 61% +//! of branches. +//! +//! ```text +//! GOAL: an audit says exactly what is wrong, in a fixed order, from the +//! ledger alone, and an attestation counts only against the bar the +//! books set. +//! SOURCE: WB-ledger-16; BS-statement-1 (the statements an +//! audit reads); BS-arap-2 (control accounts); BS-partner-1 (the +//! cumulative split a close must keep); BS-entry-5 (evidence); +//! DECISION D-9 (the bar), D-47 (a reversal's evidence is its +//! original's). +//! ``` +//! +//! The "cannot be made" arms for equation, control and register (a +//! statement that overflows exact arithmetic) are not reachable through a +//! posted book: a line is capped at one quadrillion units +//! (`kernel::MAX_LINE_AMOUNT`) so no realistic sum overflows. They stay +//! unexercised here and are named in the unit's report. + +use std::collections::BTreeSet; + +use chrono::NaiveDate; +use ledger_core::arap::{ControlCheck, DocAttention, UnattachedLine}; +use ledger_core::audit::{ + self, AttestationBar, AuditInput, CODES, Effort, Finding, Method, Scope, Severity, Subject, +}; +use ledger_core::cashflow::CashFlowFooting; +use ledger_core::periods::MemberSplit; +use ledger_core::settings::{Change, Settings, Source}; +use ledger_core::{ + AccountType, CloseTo, Currency, DocRef, DocStatus, EntryId, Ledger, MemberClose, Money, Side, +}; +use rust_decimal::Decimal; +use serde_json::json; +use std::str::FromStr; + +fn d(m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(2026, m, day).unwrap() +} + +fn dec(s: &str) -> Decimal { + Decimal::from_str(s).unwrap() +} + +fn usd(s: &str) -> Money { + Money::new(dec(s), Currency::USD) +} + +fn post(l: &mut Ledger, date: NaiveDate, dr: u64, cr: u64, amt: &str) -> EntryId { + let e = l.create_entry(date, "x"); + l.add_line(e, dr, Side::Debit, usd(amt)).unwrap(); + l.add_line(e, cr, Side::Credit, usd(amt)).unwrap(); + l.post_entry(e).unwrap(); + e +} + +struct Books { + l: Ledger, + cash: u64, + expense: u64, + revenue: u64, +} + +fn books() -> Books { + let mut l = Ledger::new(Currency::USD); + let mut a = |code: &str, name: &str, t| l.add_account(code, name, t, None, false).unwrap(); + let cash = a("1000", "Bank", AccountType::Asset); + a("3000", "Capital", AccountType::Equity); + let revenue = a("4000", "Sales", AccountType::Revenue); + let expense = a("6000", "Supplies", AccountType::Expense); + l.set_account_tax(revenue, Some("gross_receipts"), None) + .unwrap(); + l.set_account_tax(expense, Some("supplies"), None).unwrap(); + Books { + l, + cash, + expense, + revenue, + } +} + +fn run( + l: &Ledger, + settings: &Settings, + receipts: &BTreeSet, + through: NaiveDate, +) -> Vec { + audit::statements( + l, + &AuditInput { + settings, + receipts, + cash_flow: None, + settings_problems: &[], + undecided_1099: &[], + }, + through, + ) +} + +fn codes(f: &[Finding]) -> Vec<&'static str> { + f.iter().map(|f| f.code).collect() +} + +// ---------------------------------------------------------------- the words + +/// WB-ledger-16: a finding's severity comes from its code's row; a code no +/// row names is a Failure (a check the table forgot is never softened). +/// Failures sort before warnings before info. +#[test] +fn a_finding_takes_its_codes_severity_and_an_unknown_code_is_a_failure() { + for row in CODES { + assert_eq!( + Finding::new(row.code, Subject::Books, "x").severity, + row.severity, + "{}", + row.code + ); + } + assert_eq!( + Finding::new("not_a_code", Subject::Books, "x").severity, + Severity::Failure + ); + assert!(Severity::Failure < Severity::Warning && Severity::Warning < Severity::Info); + assert_eq!( + [Severity::Failure, Severity::Warning, Severity::Info].map(Severity::key), + ["failure", "warning", "info"] + ); +} + +/// WB-ledger-16: what a finding is about, in words. +#[test] +fn a_subject_describes_itself_in_words() { + let cases = [ + (Subject::Books, "books"), + (Subject::Account(4), "account 4"), + (Subject::Entry(9), "entry 9"), + (Subject::Invoice(2), "invoice 2"), + (Subject::Bill(3), "bill 3"), + (Subject::Period(1), "period 1"), + (Subject::Schedule(5), "schedule 5"), + (Subject::Attachment(8), "attachment 8"), + (Subject::Vendor("Dana Co".into()), "vendor Dana Co"), + (Subject::Named("audit.log".into()), "audit.log"), + ]; + for (subject, words) in cases { + assert_eq!(subject.describe(), words); + } +} + +/// WB-ledger-16 invariant 1 (a check that cannot be made is a finding): +/// the statement of cash flows is tried by the caller. Nothing tried says +/// nothing; one that foots says nothing; one that does not foot, and one +/// that could not be made, each say so with the figures or the reason. +#[test] +fn the_cash_flow_check_says_what_it_found() { + assert_eq!(audit::check_cash_flow(None), None); + let foots = Ok(CashFlowFooting { + sections_sum: dec("40.00"), + net_change: dec("40.00"), + difference: Decimal::ZERO, + }); + assert_eq!(audit::check_cash_flow(Some(&foots)), None); + + let off = Ok(CashFlowFooting { + sections_sum: dec("40.00"), + net_change: dec("45.00"), + difference: dec("-5.00"), + }); + let f = audit::check_cash_flow(Some(&off)).unwrap(); + assert_eq!( + (f.code, f.severity), + ("cash_flow_unfooted", Severity::Failure) + ); + // The finding carries both figures (the sentence is the engine's own). + assert!( + f.message.contains("40.00") && f.message.contains("45.00"), + "{}", + f.message + ); + + let unmade: Result = Err("no cash accounts named".into()); + let f = audit::check_cash_flow(Some(&unmade)).unwrap(); + assert_eq!(f.code, "cash_flow_unfooted"); + assert!( + f.message.contains("no cash accounts named"), + "the reason it could not be made is carried: {}", + f.message + ); +} + +/// BS-arap-2 as an audit reads it: a control account whose balance differs +/// from its documents is a failure naming the account and the figures; a +/// line carrying no document is a warning on its entry; an overpaid bill is +/// a warning on the bill (and an invoice on the invoice); a document in +/// another status needing attention says nothing here. +#[test] +fn control_accounts_report_differences_unattached_lines_and_overpaid_documents() { + let clean = ControlCheck { + role: "payables".into(), + account: 12, + balance: dec("200.00"), + documents_total: dec("200.00"), + unattached: vec![], + difference: Decimal::ZERO, + attention: vec![], + }; + assert!(audit::check_control(std::slice::from_ref(&clean)).is_empty()); + + let off = ControlCheck { + difference: dec("3.50"), + balance: dec("203.50"), + ..clean.clone() + }; + let f = audit::check_control(&[off]); + assert_eq!(codes(&f), ["control_difference"]); + assert_eq!(f[0].subject, Subject::Account(12)); + assert_eq!( + f[0].message, + "the payables account's balance 203.50 differs from its documents 200.00 by 3.50" + ); + + let loose = ControlCheck { + unattached: vec![UnattachedLine { + entry: 31, + line: 1, + date: d(3, 4), + amount: dec("75.00"), + }], + ..clean.clone() + }; + let f = audit::check_control(&[loose]); + assert_eq!(codes(&f), ["unattached_control_line"]); + assert_eq!(f[0].subject, Subject::Entry(31)); + assert!(f[0].message.contains("line 1 of entry 31")); + assert!(f[0].message.contains("75.00 on the payables account")); + + let attention = |doc, status| DocAttention { + doc, + status, + total: dec("90.00"), + outstanding: dec("-10.00"), + }; + let overpaid = ControlCheck { + attention: vec![ + attention(DocRef::Bill(6), DocStatus::Overpaid), + attention(DocRef::Invoice(2), DocStatus::Overpaid), + attention(DocRef::Bill(7), DocStatus::Unattached), + ], + ..clean + }; + let f = audit::check_control(&[overpaid]); + assert_eq!(codes(&f), ["document_overpaid", "document_overpaid"]); + assert_eq!(f[0].subject, Subject::Bill(6)); + assert_eq!(f[1].subject, Subject::Invoice(2)); + assert!(f.iter().all(|x| x.severity == Severity::Warning)); +} + +/// BS-partner-1 statement 5 (the cumulative rule): after a close that +/// posts, a member's running total MUST be under one minor unit from its +/// exact share, so a drift of exactly one unit is raised, in either +/// direction. Statement 6 (WB-partner-1) lets a count that has not yet had +/// its first true-up carry the rounding of the older rules, so there +/// only a drift beyond one unit is raised. +#[test] +fn a_close_split_drifts_by_the_regime_it_was_made_under() { + let m = |running: &str, exact: &str| MemberSplit { + capital: 3001, + share: dec("0.3"), + part: dec("0.32"), + running: dec(running), + exact: dec(exact), + }; + let unit = dec("0.01"); + // Trued up: strictly under a unit is fine; a unit is drift. + assert!(audit::check_split(1, "Jan", &[m("0.32", "0.315")], unit, true).is_empty()); + assert!(audit::check_split(1, "Jan", &[m("0.325", "0.32")], unit, true).is_empty()); + assert!(audit::check_split(1, "Jan", &[m("0.32", "0.325")], unit, true).is_empty()); + for (running, exact) in [("0.32", "0.31"), ("0.31", "0.32"), ("0.28", "0.3")] { + let f = audit::check_split(1, "Jan", &[m(running, exact)], unit, true); + assert_eq!(f.len(), 1, "{running} against {exact}"); + assert_eq!(f[0].code, "close_split_drifts"); + } + // Not yet trued up: a unit is the allowance; beyond it is drift. + assert!(audit::check_split(1, "Jan", &[m("0.32", "0.31")], unit, false).is_empty()); + assert!(audit::check_split(1, "Jan", &[m("0.31", "0.32")], unit, false).is_empty()); + assert_eq!( + audit::check_split(1, "Jan", &[m("0.32", "0.309")], unit, false).len(), + 1 + ); + let f = audit::check_split( + 4, + "Jan 2026", + &[m("0.31", "0.3"), m("0.27", "0.3"), m("0.33", "0.3")], + unit, + false, + ); + assert_eq!( + f.len(), + 2, + "the first is within the unit; the other two are not" + ); + assert!(f.iter().all(|x| x.code == "close_split_drifts")); + assert_eq!(f[0].subject, Subject::Period(4)); + assert_eq!( + f[0].message, + "after the close of Jan 2026, account 3001 holds 0.27 of the closes where its exact share is 0.3" + ); +} + +/// BS-partner-1 statement 6 and 8 (WB-partner-1): a count is trued up by +/// the first close under the cumulative rule that posts an entry, not by +/// a close of an older rule or one that posts nothing; the books say so +/// from what each close records (its rule and whether it posted). +#[test] +fn a_count_is_trued_up_by_the_first_cumulative_close_that_posts() { + let mut b = books(); + let caps: Vec = ["3001", "3002"] + .iter() + .map(|c| { + b.l.add_account(c, c, AccountType::Equity, None, false) + .unwrap() + }) + .collect(); + let members = || -> Vec { + caps.iter() + .map(|&capital| MemberClose { + capital, + share: dec("0.5"), + distributions: None, + }) + .collect() + }; + post(&mut b.l, d(1, 5), b.cash, b.revenue, "0.03"); + let jan = b.l.create_period("2026-01", d(1, 1), d(1, 31)).unwrap(); + let feb = b.l.create_period("2026-02", d(2, 1), d(2, 28)).unwrap(); + let mar = b.l.create_period("2026-03", d(3, 1), d(3, 31)).unwrap(); + let apr = b.l.create_period("2026-04", d(4, 1), d(4, 30)).unwrap(); + let may = b.l.create_period("2026-05", d(5, 1), d(5, 31)).unwrap(); + + // January under the per-close rule: not a close the audit reads, and + // no true-up. + b.l.close_period_to(jan, &CloseTo::MembersPerClose(members())) + .unwrap(); + assert_eq!(b.l.member_close_trued_up(jan), Some(false)); + assert!(b.l.member_close_split(jan).is_none()); + // February posts nothing under the cumulative rule: the count still + // carries January's rounding. + assert_eq!( + b.l.close_period_to(feb, &CloseTo::Members(members())) + .unwrap(), + None + ); + assert_eq!(b.l.member_close_trued_up(feb), Some(false)); + // March posts: the true-up has run, here and from then on. + post(&mut b.l, d(3, 5), b.cash, b.revenue, "0.01"); + assert!( + b.l.close_period_to(mar, &CloseTo::Members(members())) + .unwrap() + .is_some() + ); + assert_eq!(b.l.member_close_trued_up(mar), Some(true)); + // April posts nothing, after the true-up: still trued up; February, + // before it, still is not. + assert_eq!( + b.l.close_period_to(apr, &CloseTo::Members(members())) + .unwrap(), + None + ); + assert_eq!(b.l.member_close_trued_up(apr), Some(true)); + assert_eq!(b.l.member_close_trued_up(feb), Some(false)); + // The trued-up count is strictly within a unit of exact. + let (_, split) = b.l.member_close_split(apr).unwrap(); + assert!( + split + .iter() + .all(|m| (m.running - m.exact).abs() < dec("0.01")) + ); + // A period not closed to members has no answer; the audit is quiet. + assert_eq!(b.l.member_close_trued_up(may), None); + let f = run(&b.l, &Settings::default(), &all_receipts(&b.l), d(12, 31)); + assert!( + !codes(&f).contains(&"close_split_drifts"), + "{:?}", + codes(&f) + ); +} + +/// BS-partner-1 read by the audit end to end: a members close that splits +/// 1.05 among 0.3 / 0.3 / 0.4 cumulatively leaves every member within a +/// cent of their exact share, so the closed period raises nothing and the +/// books' own checks stay quiet. +#[test] +fn a_members_close_the_audit_walks_raises_nothing() { + let mut b = books(); + let caps: Vec = ["3001", "3002", "3003"] + .iter() + .map(|c| { + b.l.add_account(c, c, AccountType::Equity, None, false) + .unwrap() + }) + .collect(); + post(&mut b.l, d(1, 5), b.cash, b.revenue, "1.05"); + let jan = b.l.create_period("2026-01", d(1, 1), d(1, 31)).unwrap(); + let members = caps + .iter() + .zip(["0.3", "0.3", "0.4"]) + .map(|(&capital, s)| MemberClose { + capital, + share: dec(s), + distributions: None, + }) + .collect(); + b.l.close_period_to(jan, &CloseTo::Members(members)) + .unwrap(); + // 0.315, 0.315, 0.42 to the cent, odd cent by largest remainder. + let parts: Vec = caps + .iter() + .map(|&a| b.l.account_balance(a).unwrap()) + .collect(); + assert_eq!(parts.iter().sum::(), dec("1.05")); + let f = run(&b.l, &Settings::default(), &all_receipts(&b.l), d(12, 31)); + assert!( + f.iter().all(|x| x.severity == Severity::Info), + "{:?}", + codes(&f) + ); + // Through a date before the close the period is not read at all. + let before = run(&b.l, &Settings::default(), &all_receipts(&b.l), d(1, 20)); + assert!(!codes(&before).contains(&"close_split_drifts")); +} + +fn all_receipts(l: &Ledger) -> BTreeSet { + l.posted_entries().map(|e| e.id()).collect() +} + +// ---------------------------------------------------------------- evidence + +fn set(l: &mut Ledger, key: &str, value: serde_json::Value) { + let src = Source { + decided_by: "Owner".into(), + decided_on: d(11, 9), + citation: None, + note: None, + }; + let changes = [Change { + key: key.into(), + value: Some(value), + }]; + let made = l.check_settings(&changes, &src).unwrap(); + l.apply_settings(&made, &src, 1).unwrap(); +} + +/// audit.rs's own invariant 3 (only entries on or before the date count; +/// the evidence is BS-entry-5 statement 1): an uncovered entry dated after `through` is not yet a +/// finding, and one with a receipt never is. +#[test] +fn evidence_is_missing_only_through_the_date_and_only_without_a_receipt() { + let mut b = books(); + let early = post(&mut b.l, d(2, 1), b.expense, b.cash, "40.00"); + let late = post(&mut b.l, d(6, 1), b.expense, b.cash, "40.00"); + let settings = Settings::default(); + let none = BTreeSet::new(); + + let f = run(&b.l, &settings, &none, d(3, 31)); + assert_eq!(codes(&f), ["evidence_missing"]); + assert_eq!(f[0].subject, Subject::Entry(early)); + assert!( + f[0].message + .contains("strictly greater than the 25.00 threshold") + ); + + let f = run(&b.l, &settings, &none, d(12, 31)); + assert_eq!(codes(&f), ["evidence_missing", "evidence_missing"]); + + let have = BTreeSet::from([early]); + let f = run(&b.l, &settings, &have, d(12, 31)); + assert_eq!(f.len(), 1); + assert_eq!(f[0].subject, Subject::Entry(late)); +} + +/// D-47 as an audit reads it: a reversal the policy WOULD cover, with no +/// receipt of its own, is an Info finding (its original's evidence stands +/// for it) and is not a failure; under a policy that would not cover it +/// (a threshold above its debits) it says nothing. +#[test] +fn a_reversal_without_its_own_receipt_is_info_and_only_when_the_policy_would_cover_it() { + let mut b = books(); + let big = post(&mut b.l, d(2, 1), b.expense, b.cash, "500.00"); + let rev = b.l.reverse_entry(big, d(2, 2), "Returned").unwrap(); + let settings = Settings::default(); + // The original has its receipt; the reversal has none. + let have = BTreeSet::from([big]); + let f = run(&b.l, &settings, &have, d(12, 31)); + assert_eq!(codes(&f), ["legacy_reversal_exempt"]); + assert_eq!(f[0].severity, Severity::Info); + assert_eq!(f[0].subject, Subject::Entry(rev)); + assert_eq!( + f[0].message, + format!("entry {rev} reverses entry {big}: its evidence is the original's") + ); + // With a receipt of its own, nothing. + let both = BTreeSet::from([big, rev]); + assert!(run(&b.l, &settings, &both, d(12, 31)).is_empty()); + + // A policy whose threshold is above the reversal's debits would not + // have covered it: nothing to say about the reversal (nor the original). + set(&mut b.l, "policy.evidence.threshold", json!("1000.00")); + assert!(run(&b.l, b.l.settings(), &have, d(12, 31)).is_empty()); +} + +/// audit.rs's own draft check (its scenario 2): a draft dated on or before +/// the date is exactly `draft_open`; one dated after is not mentioned. +#[test] +fn a_draft_is_open_only_through_the_date() { + let mut b = books(); + let e1 = b.l.create_entry(d(3, 3), "March draft"); + let e2 = b.l.create_entry(d(9, 9), "September draft"); + for e in [e1, e2] { + b.l.add_line(e, b.expense, Side::Debit, usd("1.00")) + .unwrap(); + b.l.add_line(e, b.cash, Side::Credit, usd("1.00")).unwrap(); + } + let f = run(&b.l, &Settings::default(), &BTreeSet::new(), d(4, 30)); + assert_eq!(codes(&f), ["draft_open"]); + assert_eq!(f[0].subject, Subject::Entry(e1)); + assert_eq!( + f[0].message, + "draft 1 (2026-03-03) \"March draft\" is not posted" + ); +} + +/// WB-ledger-16: the facts the caller reads from around the books are +/// passed through as findings: a settings problem as it was worded, a +/// vendor paid in a way that could need a 1099 by name and amount. +#[test] +fn the_callers_facts_become_findings_in_order() { + let b = books(); + let settings = Settings::default(); + let receipts = BTreeSet::new(); + let problems = ["books.cash_accounts names 1099, which the chart lacks".to_string()]; + let undecided = [("Dana Co".to_string(), dec("1250.00"))]; + let f = audit::statements( + &b.l, + &AuditInput { + settings: &settings, + receipts: &receipts, + cash_flow: None, + settings_problems: &problems, + undecided_1099: &undecided, + }, + d(12, 31), + ); + assert_eq!(codes(&f), ["settings_problem", "vendor_1099_undecided"]); + assert_eq!(f[0].message, problems[0]); + assert_eq!(f[1].subject, Subject::Vendor("Dana Co".into())); + assert_eq!( + f[1].message, + "Dana Co was paid 1250.00 in a way that could need a 1099 and has no decision" + ); +} + +// ---------------------------------------------------------------- the bar (D-9) + +/// D-9: a scope's and an effort's words round-trip; case and padding are +/// forgiven; anything else is not a scope or an effort. +#[test] +fn scopes_and_efforts_round_trip_their_words() { + for s in [Scope::Month, Scope::Annual, Scope::CpaHandoff, Scope::Full] { + assert_eq!(Scope::parse(s.key()), Some(s)); + assert_eq!( + Scope::parse(&format!(" {}\n", s.key().to_uppercase())), + Some(s) + ); + } + assert_eq!(Scope::parse("quarter"), None); + assert_eq!(Scope::parse(""), None); + for e in [ + Effort::Low, + Effort::Medium, + Effort::High, + Effort::Xhigh, + Effort::Max, + ] { + assert_eq!(Effort::parse(e.key()), Some(e)); + assert_eq!( + Effort::parse(&format!(" {} ", e.key().to_uppercase())), + Some(e) + ); + } + assert_eq!(Effort::parse("extreme"), None); + assert!(Effort::Low < Effort::Medium && Effort::Xhigh < Effort::Max); +} + +/// D-9: only a month's audit is held to the effort alone; the other scopes +/// are held to the whole bar. Only the CPA hand-off and a full audit are +/// ones the CPA package may rest on. +#[test] +fn scopes_say_which_bar_they_carry_and_which_serve_the_hand_off() { + let table = [ + (Scope::Month, false, false), + (Scope::Annual, true, false), + (Scope::CpaHandoff, true, true), + (Scope::Full, true, true), + ]; + for (scope, full, handoff) in table { + assert_eq!(scope.full_bar(), full, "{scope:?}"); + assert_eq!(scope.serves_handoff(), handoff, "{scope:?}"); + } +} + +/// D-9: the bar's setting text. Words in any order, split by spaces or +/// commas, long and short spellings, an omitted word keeps its default; a +/// word that is not `key=value`, a value out of range and an unknown key +/// are each refused with the offending word named. +#[test] +fn the_bar_setting_parses_what_it_names_and_refuses_the_rest() { + let default = AttestationBar::default(); + assert_eq!(AttestationBar::parse("").unwrap(), default); + assert_eq!(AttestationBar::parse(" , ,").unwrap(), default); + let bar = + AttestationBar::parse("reasoning_effort=max,verifier_agents=64 adversarial=false").unwrap(); + assert_eq!(bar.describe(), "effort=max verifiers=64 adversarial=false"); + assert_eq!( + AttestationBar::parse("verifiers=1").unwrap().describe(), + "effort=high verifiers=1 adversarial=true" + ); + + let refused = |text: &str, fragment: &str| { + let e = AttestationBar::parse(text).unwrap_err(); + assert!(e.contains(fragment), "{text:?}: {e}"); + }; + refused("effort", "expected key=value"); + refused("effort=wild", "is not low, medium, high, xhigh or max"); + refused("verifiers=0", "not a count from 1 to 64"); + refused("verifiers=65", "not a count from 1 to 64"); + refused("verifiers=two", "not a count from 1 to 64"); + refused("verifiers=-1", "not a count from 1 to 64"); + refused("adversarial=maybe", "is not true or false"); + refused("adversarial=True", "is not true or false"); + refused("strict=yes", "is not a part of the bar"); +} + +/// D-9: what counts, at the edges. The effort is a floor (equal counts), +/// the verifiers a floor (equal counts), the adversarial check is needed +/// only when the bar asks for it, and a month's attestation needs the +/// effort alone however few verifiers it names. +#[test] +fn the_bar_counts_at_its_edges_and_only_asks_for_what_it_sets() { + let method = |effort, adversarial, agents| Method { + model: Some("claude".into()), + reasoning_effort: effort, + adversarial, + verifier_agents: agents, + }; + let bar = AttestationBar::default(); + let at_edge = method(Some(Effort::High), Some(true), Some(2)); + assert!(bar.counts(&at_edge, true, false)); + assert!(bar.counts(&at_edge, false, false)); + // Month: effort alone. + assert!(bar.counts(&method(Some(Effort::High), None, None), false, false)); + assert!(!bar.counts( + &method(Some(Effort::Medium), Some(true), Some(9)), + false, + false + )); + // A bar that does not ask for the adversarial check does not need it, + // but still needs the verifiers. + let open = AttestationBar::parse("adversarial=false").unwrap(); + assert!(open.counts(&method(Some(Effort::High), None, Some(2)), true, false)); + assert!(!open.counts(&method(Some(Effort::High), None, Some(1)), true, false)); + // A disagreeing claim never counts, whatever else is true. + assert!(!open.counts(&at_edge, false, true)); +} diff --git a/crates/ledger-core/tests/conventions_refusals.rs b/crates/ledger-core/tests/conventions_refusals.rs new file mode 100644 index 00000000..2f51851e --- /dev/null +++ b/crates/ledger-core/tests/conventions_refusals.rs @@ -0,0 +1,1006 @@ +//! Conventions, decisions, open items and approvals refuse what their +//! rules refuse, and a refusal changes nothing (plan P14 unit V-D2; +//! coverage found `conventions.rs` at 78% of lines, the gap being its +//! validation refusals). +//! +//! ```text +//! GOAL: a company's way of working is kept in the books checked, sourced +//! and whole: a bad id, text, template, rule, decision, open item or +//! approval is refused with a reason, and nothing is journaled. +//! SOURCE: WB-ledger-5 (conventions, decisions, open items and approvals +//! are kept in the journal); WB-ledger-6 (no full TIN anywhere); +//! WB-ledger-9 (a template splits an amount exactly); +//! WB-ledger-10 (approval rules, enforced only on request); +//! BS-entry-4 (replay takes what was journaled); +//! conventions.rs INVARIANTS 1 to 6. +//! ``` +//! +//! Every refusal here is asked of the public checks the store calls before +//! it journals (`check_*`), and the books are compared to a clone taken +//! before: a check changes nothing, and the `apply_*` commands that refuse +//! on replay change nothing either. + +use chrono::NaiveDate; +use ledger_core::conventions::{ + self, Approval, ConventionKind, DecisionSource, NewConvention, NewDecision, NewOpenItem, +}; +use ledger_core::settings::{Change, Source}; +use ledger_core::{ + AccountType, Currency, EntryId, Ledger, LedgerError, Money, PartyShare, Share, Side, +}; +use rust_decimal::Decimal; +use serde_json::{Value, json}; +use std::collections::BTreeMap; +use std::str::FromStr; + +fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() +} + +fn dec(s: &str) -> Decimal { + Decimal::from_str(s).unwrap() +} + +fn src() -> Source { + Source { + decided_by: "Owner".into(), + decided_on: d(2026, 11, 9), + citation: None, + note: None, + } +} + +/// The message of an InvalidConvention refusal; any other error fails. +fn why(r: Result) -> String { + match r { + Err(LedgerError::InvalidConvention(m)) => m, + other => panic!("expected an InvalidConvention refusal, got {other:?}"), + } +} + +fn convention(id: &str, kind: ConventionKind, structured: Option) -> NewConvention { + NewConvention { + id: id.into(), + kind, + title: "Software subscriptions".into(), + body_md: "How we book them.".into(), + structured, + source: src(), + } +} + +fn tline(account: &str, side: &str, share: &str) -> Value { + json!({"account": account, "side": side, "share": share}) +} + +fn two_line_template(id: &str) -> NewConvention { + convention( + id, + ConventionKind::PostingTemplate, + Some(json!({"lines": [tline("6000", "debit", "1"), tline("1000", "credit", "1")]})), + ) +} + +fn rule(id: &str, structured: Value) -> NewConvention { + convention(id, ConventionKind::ApprovalRule, Some(structured)) +} + +struct Books { + l: Ledger, + expense: u64, + bank: u64, +} + +fn books() -> Books { + let mut l = Ledger::new(Currency::USD); + let expense = l + .add_account("6000", "Software", AccountType::Expense, None, false) + .unwrap(); + let bank = l + .add_account("1000", "Bank", AccountType::Asset, None, false) + .unwrap(); + l.add_account("5000", "Costs (heading)", AccountType::Expense, None, true) + .unwrap(); + Books { l, expense, bank } +} + +fn set_convention(l: &mut Ledger, c: &NewConvention, seq: u64) { + let c = l.check_convention(c).unwrap(); + l.apply_convention(c, seq).unwrap(); +} + +fn settle(l: &mut Ledger, key: &str, value: Value) { + let changes = [Change { + key: key.into(), + value: Some(value), + }]; + let made = l.check_settings(&changes, &src()).unwrap(); + l.apply_settings(&made, &src(), 1).unwrap(); +} + +// ---------------------------------------------------------------- INVARIANT 1: ids + +/// INVARIANT 1 and WB-ledger-6: an id is a slug of 1 to 64 lowercase +/// letters, digits and hyphens, not starting with a hyphen, and never one +/// that reads as a full TIN. +#[test] +fn a_convention_id_is_a_slug_and_never_a_tin() { + let b = books(); + let before = b.l.clone(); + let id_error = |id: &str| why(b.l.check_convention(&two_line_template(id))); + for bad in [ + "", + "Upper", + "under_score", + "-leading", + "has space", + &"a".repeat(65), + ] { + let m = id_error(bad); + assert!( + m.contains("1 to 64 lowercase letters, digits and hyphens"), + "{bad:?}: {m}" + ); + } + assert!(id_error("123-45-6789").contains("full TIN")); + for ok in ["a", "0", "software-2026", &"a".repeat(64)] { + assert!(b.l.check_convention(&two_line_template(ok)).is_ok(), "{ok}"); + } + assert_eq!(b.l, before, "a check changes nothing"); +} + +/// INVARIANT 1: setting a live id revises it (the revision counts up and +/// the source is the latest); its kind can't change; a retired id is never +/// reused; saying exactly what is already said is refused. +#[test] +fn revising_a_convention_is_one_way_and_a_retired_id_is_gone_for_good() { + let mut b = books(); + set_convention(&mut b.l, &two_line_template("subs"), 1); + let first = b.l.conventions().convention("subs").unwrap().clone(); + assert_eq!((first.revision, first.seq), (1, 1)); + + // The same text again says nothing new. + let m = why(b.l.check_convention(&two_line_template("subs"))); + assert_eq!(m, "convention subs already says exactly that"); + + // A different body is a revision. + let mut revised = two_line_template("subs"); + revised.body_md = "Booked on the 1st.".into(); + set_convention(&mut b.l, &revised, 2); + let now = b.l.conventions().convention("subs").unwrap(); + assert_eq!((now.revision, now.seq), (2, 2)); + assert_eq!(now.body_md, "Booked on the 1st."); + + // Its kind can't change. + let policy = convention("subs", ConventionKind::Policy, None); + let m = why(b.l.check_convention(&policy)); + assert!( + m.contains("is a posting_template; its kind can't change"), + "{m}" + ); + // The replay path refuses the same two things. + let mut replayed = b.l.clone(); + let e = replayed.apply_convention(policy.clone(), 3).unwrap_err(); + assert!(matches!(&e, LedgerError::InvalidConvention(m) if m.contains("its kind can't change"))); + assert_eq!(replayed, b.l, "a refused apply changes nothing"); + + // Retire it: the id is never reused. + let reason = + b.l.check_retire_convention("subs", "superseded", &src()) + .unwrap(); + b.l.apply_retire_convention("subs", reason, src(), 4) + .unwrap(); + assert!( + b.l.conventions() + .convention("subs") + .unwrap() + .retired + .is_some() + ); + let m = why(b.l.check_convention(&revised)); + assert!(m.contains("is retired; ids are never reused"), "{m}"); + let before = b.l.clone(); + let e = b.l.apply_convention(revised, 5).unwrap_err(); + assert!(matches!(&e, LedgerError::InvalidConvention(m) if m.contains("ids are never reused"))); + assert_eq!(b.l, before); +} + +// ---------------------------------------------------------------- INVARIANT 2: templates + +/// INVARIANT 2 and WB-ledger-9: a posting template is two to fifty lines, +/// each share a decimal in (0, 1] and each side summing to exactly 1; a +/// slot is a lowercase name in braces; a template needs its structure and +/// a convention that is not a template or a rule takes none. +#[test] +fn a_posting_template_is_refused_unless_each_side_sums_to_one() { + let b = books(); + let refused = |structured: Option| { + why(b.l.check_convention(&convention( + "t", + ConventionKind::PostingTemplate, + structured, + ))) + }; + let lines = |ls: Vec| Some(json!({ "lines": ls })); + + assert!(refused(None).contains("a posting template needs structured")); + assert!(refused(Some(json!({"lines": "x"}))).starts_with("posting template: ")); + assert!(refused(Some(json!({"lines": [], "extra": 1}))).starts_with("posting template: ")); + assert!(refused(lines(vec![tline("6000", "debit", "1")])).contains("2 to 50 lines")); + let fifty_one: Vec = (0..51).map(|_| tline("6000", "debit", "0.02")).collect(); + assert!(refused(lines(fifty_one)).contains("2 to 50 lines")); + // A share outside (0, 1], or not a number. + for bad in ["0", "-0.5", "1.5", "half", ""] { + let m = refused(lines(vec![ + tline("6000", "debit", bad), + tline("1000", "credit", "1"), + ])); + assert!(m.contains("template line 1: share"), "{bad:?}: {m}"); + } + // Shares that don't sum to 1 on a side. + let m = refused(lines(vec![ + tline("6000", "debit", "0.6"), + tline("1000", "credit", "1"), + ])); + assert!(m.contains("debits 0.6, credits 1"), "{m}"); + let m = refused(lines(vec![ + tline("6000", "debit", "1"), + tline("1000", "credit", "0.5"), + tline("1000", "credit", "0.6"), + ])); + assert!(m.contains("credits 1.1"), "{m}"); + // A bad slot; a good one. + let m = refused(lines(vec![ + tline("{Expense}", "debit", "1"), + tline("1000", "credit", "1"), + ])); + assert!(m.contains("template line 1: slot"), "{m}"); + assert!( + b.l.check_convention(&convention( + "t", + ConventionKind::PostingTemplate, + lines(vec![ + tline("{expense}", "debit", "1"), + tline("1000", "credit", "1") + ]), + )) + .is_ok() + ); + // A side that is neither. + let m = refused(lines(vec![ + tline("6000", "left", "1"), + tline("1000", "credit", "1"), + ])); + assert!(m.contains("debit or credit"), "{m}"); + // A blank description. + let m = refused(Some(json!({ + "description": " ", + "lines": [tline("6000", "debit", "1"), tline("1000", "credit", "1")] + }))); + assert!(m.contains("template description is blank"), "{m}"); + // A non-template takes no structure; a rule needs one. + let m = why(b + .l + .check_convention(&convention("p", ConventionKind::Policy, Some(json!({}))))); + assert!( + m.contains("a policy convention takes no structured part"), + "{m}" + ); + let m = why(b + .l + .check_convention(&convention("r", ConventionKind::ApprovalRule, None))); + assert!(m.contains("an approval rule needs structured"), "{m}"); +} + +/// INVARIANT 2: the template's accounts must be in the chart and take +/// postings, a slot excepted (a draft names it). +#[test] +fn a_templates_accounts_are_checked_against_the_chart() { + let b = books(); + let t = |a: &str| { + convention( + "t", + ConventionKind::PostingTemplate, + Some(json!({"lines": [tline(a, "debit", "1"), tline("1000", "credit", "1")]})), + ) + }; + assert_eq!( + why(b.l.check_convention(&t("7777"))), + "template account 7777 is not in the chart" + ); + assert!(why(b.l.check_convention(&t("5000"))).contains("is a placeholder")); + assert!(b.l.check_convention(&t("{anything}")).is_ok()); + assert!(b.l.check_convention(&t("6000")).is_ok()); +} + +/// INVARIANT 3 and WB-ledger-10: a rule names an approver and limits +/// itself by accounts that take postings, an amount at least zero, or +/// both; accounts are listed once. +#[test] +fn an_approval_rule_needs_an_approver_and_a_limit() { + let b = books(); + let refused = |s: Value| why(b.l.check_convention(&rule("r", s))); + assert!( + refused(json!({"approver": "Steve"})) + .contains("covers some accounts, entries over an amount, or both") + ); + assert!(refused(json!({"approver": " ", "amount_over": "10"})).contains("approver is blank")); + for bad in ["-1", "ten", "", "99999999999999999"] { + let m = refused(json!({"approver": "Steve", "amount_over": bad})); + assert!( + m.contains("must be a decimal at least zero"), + "{bad:?}: {m}" + ); + } + assert!( + refused(json!({"approver": "Steve", "accounts": ["9999"]})) + .contains("approval rule account 9999 is not in the chart") + ); + assert!( + refused(json!({"approver": "Steve", "accounts": ["5000"]})) + .contains("is a placeholder (a heading)") + ); + assert!(refused(json!({"approver": "Steve", "bogus": 1})).starts_with("approval rule: ")); + + // Duplicates collapse and an amount is kept in its canonical text. + let ok = + b.l.check_convention(&rule( + "r", + json!({"approver": "Steve", "accounts": ["6000", "6000"], "amount_over": "25.50"}), + )) + .unwrap(); + assert_eq!( + ok.structured.unwrap(), + json!({"approver": "Steve", "accounts": ["6000"], "amount_over": "25.50"}) + ); +} + +/// INVARIANT 6 and WB-ledger-6: no convention text holds a full TIN, a +/// control character or more than its length; its source is checked like +/// a setting's. +#[test] +fn convention_text_is_bounded_and_holds_no_tin() { + let b = books(); + let with = |f: fn(&mut NewConvention)| { + let mut c = two_line_template("t"); + f(&mut c); + why(b.l.check_convention(&c)) + }; + assert!(with(|c| c.title = " ".into()).contains("title is blank")); + assert!(with(|c| c.title = "x".repeat(201)).contains("title is longer than 200")); + assert!(with(|c| c.title = "bad\nline".into()).contains("title holds a line break")); + assert!(with(|c| c.body_md = "EIN 12-3456789 on file".into()).contains("body")); + assert!(with(|c| c.body_md = "x".repeat(20_001)).contains("body is longer than 20000")); + assert!(with(|c| c.source.decided_by = " ".into()).contains("decided_by is blank")); + assert!( + with(|c| c.source.decided_on = NaiveDate::MAX) + .contains("outside the calendar the books keep") + ); + assert!(with(|c| c.source.citation = Some("x".repeat(2_001))).contains("citation")); + assert!(with(|c| c.source.note = Some("123-45-6789".into())).contains("note")); +} + +// ---------------------------------------------------------------- source corrections + +/// WB-ledger-5: a convention's source can be corrected alone, with a +/// reason: the text, revision and line stay. It is refused for an unknown +/// or retired convention, a changed text, a changed kind, the same source, +/// a blank reason. +#[test] +fn a_conventions_source_is_corrected_alone_and_with_a_reason() { + let mut b = books(); + set_convention(&mut b.l, &two_line_template("subs"), 1); + let mut fixed = two_line_template("subs"); + fixed.source.decided_by = "Steve".into(); + fixed.source.citation = Some("Operating agreement 4.2".into()); + + let (source, reason) = + b.l.check_convention_source(&fixed, " named the wrong person ") + .unwrap(); + assert_eq!(source, fixed.source); + assert_eq!(reason, "named the wrong person"); + + let refuse = |l: &Ledger, c: &NewConvention, r: &str| why(l.check_convention_source(c, r)); + assert_eq!(refuse(&b.l, &fixed, " "), "reason is blank"); + assert!(refuse(&b.l, &fixed, "123-45-6789").starts_with("reason")); + assert!(refuse(&b.l, &two_line_template("subs"), "same").contains("already has that source")); + let mut other_text = fixed.clone(); + other_text.body_md = "different".into(); + assert!(refuse(&b.l, &other_text, "r").contains("changes more than its source")); + let mut other_kind = fixed.clone(); + other_kind.kind = ConventionKind::Policy; + other_kind.structured = None; + assert!(refuse(&b.l, &other_kind, "r").contains("its kind can't change")); + let mut unknown = fixed.clone(); + unknown.id = "nope".into(); + assert!(refuse(&b.l, &unknown, "r").contains("unknown convention \"nope\"")); + + let before = b.l.clone(); + assert!(matches!( + b.l.apply_convention_source("nope", fixed.source.clone()), + Err(LedgerError::InvalidConvention(m)) if m.contains("unknown convention") + )); + assert_eq!(b.l, before); + + b.l.apply_convention_source("subs", source).unwrap(); + let c = b.l.conventions().convention("subs").unwrap(); + assert_eq!(c.source.decided_by, "Steve"); + assert_eq!((c.revision, c.body_md.as_str()), (1, "How we book them.")); + + // Retired: refused. + let reason = b.l.check_retire_convention("subs", "gone", &src()).unwrap(); + b.l.apply_retire_convention("subs", reason, src(), 2) + .unwrap(); + let mut again = fixed.clone(); + again.source.decided_by = "Third".into(); + assert!(refuse(&b.l, &again, "r").contains("is retired")); +} + +/// WB-ledger-5: retiring needs a known live convention, a good source and +/// a reason; the replay path refuses an unknown or already retired id. +#[test] +fn a_convention_is_retired_once_with_a_reason() { + let mut b = books(); + set_convention(&mut b.l, &two_line_template("subs"), 1); + assert!(why(b.l.check_retire_convention("nope", "r", &src())).contains("unknown convention")); + assert!(why(b.l.check_retire_convention("subs", " ", &src())).contains("reason is blank")); + let mut bad = src(); + bad.decided_by = "".into(); + assert!(why(b.l.check_retire_convention("subs", "r", &bad)).contains("decided_by is blank")); + + let reason = + b.l.check_retire_convention("subs", "no longer used", &src()) + .unwrap(); + assert_eq!(reason, "no longer used"); + b.l.apply_retire_convention("subs", reason.clone(), src(), 2) + .unwrap(); + assert!(why(b.l.check_retire_convention("subs", "again", &src())).contains("already retired")); + let before = b.l.clone(); + assert!( + b.l.apply_retire_convention("subs", reason.clone(), src(), 3) + .is_err() + ); + assert!( + b.l.apply_retire_convention("nope", reason, src(), 3) + .is_err() + ); + assert_eq!(b.l, before); + let closing = + b.l.conventions() + .convention("subs") + .unwrap() + .retired + .clone() + .unwrap(); + assert_eq!((closing.text.as_str(), closing.seq), ("no longer used", 2)); +} + +// ---------------------------------------------------------------- decisions + +fn decision(subject: &str) -> NewDecision { + NewDecision { + subject: subject.into(), + decision_md: "We keep cash-basis books for 2026.".into(), + decided_by: vec!["Steve".into(), "Tobin".into()], + decided_on: d(2026, 11, 1), + evidence_attachment: None, + supersedes: None, + citation: Some("Minutes, 2026-11-01".into()), + projects: vec![], + } +} + +/// INVARIANT 4 and 6: a decision names who decided and when, holds no TIN +/// and no unbounded text; its projects exist and are named once; it +/// supersedes at most one live decision. +#[test] +fn a_decision_is_refused_for_text_projects_and_supersession() { + let mut b = books(); + let refused = |f: fn(&mut NewDecision)| { + let mut x = decision("Basis"); + f(&mut x); + b.l.check_decision(&x).unwrap_err() + }; + let msg = |e: LedgerError| match e { + LedgerError::InvalidConvention(m) => m, + other => panic!("{other:?}"), + }; + assert!(msg(refused(|x| x.decided_by.clear())).contains("names at least one person")); + assert!(msg(refused(|x| x.decided_by = vec![" ".into()])).contains("decided_by is blank")); + assert!( + msg(refused(|x| x.decided_on = NaiveDate::MIN)) + .contains("outside the calendar the books keep") + ); + assert!(msg(refused(|x| x.subject = "\t".into())).contains("subject is blank")); + assert!(msg(refused(|x| x.decision_md = "SSN 123-45-6789".into())).contains("decision")); + assert!(msg(refused(|x| x.citation = Some("x".repeat(2_001)))).contains("citation")); + assert_eq!( + refused(|x| x.projects = vec![99]), + LedgerError::UnknownClass(99) + ); + let p = b.l.add_class("Launch").unwrap(); + let q = b.l.add_class("Maintenance").unwrap(); + let mut twice = decision("Basis"); + twice.projects = vec![p, q, p]; + assert!( + msg(b.l.check_decision(&twice).unwrap_err()) + .contains(&format!("project {p} is named twice")) + ); + let mut ok = decision("Basis"); + ok.projects = vec![p, q]; + let (id, kept) = b.l.check_decision(&ok).unwrap(); + assert_eq!(id, 1); + assert_eq!(kept.projects, vec![p, q]); + + // Supersession. + let mut sup = decision("Basis, again"); + sup.supersedes = Some(7); + assert!(msg(b.l.check_decision(&sup).unwrap_err()).contains("decision 7 doesn't exist")); + b.l.apply_decision(1, ok, 10).unwrap(); + sup.supersedes = Some(1); + let (id2, kept) = b.l.check_decision(&sup).unwrap(); + assert_eq!(id2, 2); + b.l.apply_decision(id2, kept, 11).unwrap(); + assert_eq!( + b.l.conventions().decision(1).unwrap().superseded_by, + Some(2) + ); + // A decision already superseded can't be again, by check or by replay. + let mut third = decision("Basis, thrice"); + third.supersedes = Some(1); + assert!(msg(b.l.check_decision(&third).unwrap_err()).contains("already superseded by 2")); + let before = b.l.clone(); + assert!(b.l.apply_decision(3, third.clone(), 12).is_err()); + third.supersedes = Some(42); + assert!(b.l.apply_decision(3, third, 12).is_err()); + // An id that isn't the next one is refused (ids are allocated in order). + assert!(b.l.apply_decision(9, decision("Out of order"), 13).is_err()); + assert_eq!(b.l, before, "refused applies change nothing"); +} + +/// WB-ledger-5: a decision's source is corrected alone with a reason; the +/// same source, an unknown decision, a bad source or a blank reason are +/// refused. +#[test] +fn a_decisions_source_is_corrected_alone_and_with_a_reason() { + let mut b = books(); + let (id, kept) = b.l.check_decision(&decision("Basis")).unwrap(); + b.l.apply_decision(id, kept, 1).unwrap(); + let fixed = DecisionSource { + decided_by: vec!["Steve".into()], + decided_on: d(2026, 11, 2), + citation: None, + }; + assert!(why(b.l.check_decision_source(9, &fixed, "r")).contains("decision 9 doesn't exist")); + let mut empty = fixed.clone(); + empty.decided_by.clear(); + assert!(why(b.l.check_decision_source(id, &empty, "r")).contains("names at least one person")); + let same = decision("Basis").source(); + assert!(why(b.l.check_decision_source(id, &same, "r")).contains("already has that source")); + assert!(why(b.l.check_decision_source(id, &fixed, " ")).contains("reason is blank")); + + let (source, reason) = b.l.check_decision_source(id, &fixed, " typo ").unwrap(); + assert_eq!(reason, "typo"); + let before = b.l.clone(); + assert!(b.l.apply_decision_source(9, source.clone()).is_err()); + assert_eq!(b.l, before); + b.l.apply_decision_source(id, source).unwrap(); + let kept = b.l.conventions().decision(id).unwrap(); + assert_eq!(kept.new.decided_by, vec!["Steve".to_string()]); + assert_eq!(kept.new.decided_on, d(2026, 11, 2)); + assert_eq!(kept.new.citation, None); + assert_eq!(kept.new.subject, "Basis", "only the source moved"); +} + +// ---------------------------------------------------------------- open items + +fn item(title: &str) -> NewOpenItem { + NewOpenItem { + title: title.into(), + detail_md: Some("Waiting on the CPA.".into()), + due: Some(d(2026, 12, 15)), + source: src(), + } +} + +/// INVARIANT 4 and 6: an open item has a titled, sourced, bounded text and +/// a due date inside the calendar; ids are allocated in order; an item +/// resolves once, with a resolution; its source is corrected alone. +#[test] +fn an_open_item_is_raised_resolved_once_and_its_source_corrected() { + let mut b = books(); + let mut e = item(" "); + assert!(why(b.l.check_open_item(&e)).contains("title is blank")); + e = item("Ask CPA"); + e.due = Some(NaiveDate::MAX); + assert!(why(b.l.check_open_item(&e)).contains("outside the calendar the books keep")); + e = item("Ask CPA"); + e.source.decided_by = "".into(); + assert!(why(b.l.check_open_item(&e)).contains("decided_by is blank")); + e = item("Ask CPA"); + e.detail_md = Some("SSN 123-45-6789".into()); + assert!(why(b.l.check_open_item(&e)).contains("detail")); + + let (id, kept) = b.l.check_open_item(&item(" Ask CPA ")).unwrap(); + assert_eq!((id, kept.title.as_str()), (1, "Ask CPA")); + let before = b.l.clone(); + assert!( + b.l.apply_open_item(5, kept.clone(), 1).is_err(), + "not the next id" + ); + assert_eq!(b.l, before); + b.l.apply_open_item(id, kept, 1).unwrap(); + assert_eq!(b.l.conventions().next_open_item_id(), 2); + + // Resolution. + assert!(why(b.l.check_resolve_item(9, "done", &src())).contains("unknown open item 9")); + assert!(why(b.l.check_resolve_item(id, " ", &src())).contains("resolution is blank")); + let mut bad = src(); + bad.decided_on = NaiveDate::MAX; + assert!( + why(b.l.check_resolve_item(id, "done", &bad)) + .contains("outside the calendar the books keep") + ); + let text = + b.l.check_resolve_item(id, " Filed 2026-12-01 ", &src()) + .unwrap(); + assert_eq!(text, "Filed 2026-12-01"); + assert!(b.l.apply_resolve_item(9, text.clone(), src(), 2).is_err()); + b.l.apply_resolve_item(id, text.clone(), src(), 2).unwrap(); + assert!(why(b.l.check_resolve_item(id, "again", &src())).contains("already resolved")); + let before = b.l.clone(); + assert!(b.l.apply_resolve_item(id, text, src(), 3).is_err()); + assert_eq!(b.l, before); + + // Source correction. + let mut fixed = src(); + fixed.decided_by = "Tobin".into(); + assert!(why(b.l.check_open_item_source(9, &fixed, "r")).contains("unknown open item 9")); + assert!(why(b.l.check_open_item_source(id, &src(), "r")).contains("already has that source")); + assert!(why(b.l.check_open_item_source(id, &fixed, "")).contains("reason is blank")); + let mut bad = fixed.clone(); + bad.decided_by = "".into(); + assert!(why(b.l.check_open_item_source(id, &bad, "r")).contains("decided_by is blank")); + let (source, reason) = + b.l.check_open_item_source(id, &fixed, "wrong name") + .unwrap(); + assert_eq!(reason, "wrong name"); + assert!(b.l.apply_open_item_source(9, source.clone()).is_err()); + b.l.apply_open_item_source(id, source).unwrap(); + assert_eq!( + b.l.conventions() + .open_item(id) + .unwrap() + .new + .source + .decided_by, + "Tobin" + ); +} + +// ---------------------------------------------------------------- approvals + +fn draft(l: &mut Ledger, accounts: (u64, u64), amount: &str) -> EntryId { + let e = l.create_entry(d(2026, 11, 2), "Spend"); + let m = Money::new(dec(amount), Currency::USD); + l.add_line(e, accounts.0, Side::Debit, m).unwrap(); + l.add_line(e, accounts.1, Side::Credit, m).unwrap(); + e +} + +/// WB-ledger-10: an approval is of a draft that exists and is not posted, +/// by a named approver, with a bounded note and a good source. +#[test] +fn an_approval_is_refused_for_a_posted_or_unknown_entry_and_bad_text() { + let mut b = books(); + let e = draft(&mut b.l, (b.expense, b.bank), "50.00"); + assert_eq!( + b.l.check_approval(99, "Steve", None, &src()).unwrap_err(), + LedgerError::UnknownEntry(99) + ); + assert!(why(b.l.check_approval(e, " ", None, &src())).contains("approver is blank")); + assert!( + why(b + .l + .check_approval(e, "Steve", Some("SSN 123-45-6789"), &src())) + .contains("note") + ); + let mut bad = src(); + bad.decided_by = "".into(); + assert!(why(b.l.check_approval(e, "Steve", None, &bad)).contains("decided_by is blank")); + + let a = + b.l.check_approval(e, " Steve ", Some(" fine "), &src()) + .unwrap(); + assert_eq!( + (a.approver.as_str(), a.note.as_deref()), + ("Steve", Some("fine")) + ); + assert!(!a.fingerprint.is_empty()); + assert_eq!( + b.l.apply_approval(99, a.clone()).unwrap_err(), + LedgerError::UnknownEntry(99) + ); + b.l.apply_approval(e, a).unwrap(); + assert_eq!(b.l.conventions().approvals(e).len(), 1); + + b.l.post_entry(e).unwrap(); + assert_eq!( + b.l.check_approval(e, "Steve", None, &src()).unwrap_err(), + LedgerError::EntryAlreadyPosted(e) + ); +} + +/// WB-ledger-10 and INVARIANT 3: approvals bind only when the company +/// enforces them. Off: nothing is missing, whatever the rules. Enforced: a +/// covered draft lacks its approver until that approver (matched by name, +/// however spelled) approved it AS IT STANDS; a rule this version cannot +/// read covers everything and names no approver (fail closed); an unknown +/// entry is refused. +#[test] +fn approvals_are_missing_only_under_enforcement_and_fail_closed() { + let mut b = books(); + set_convention( + &mut b.l, + &rule( + "big-spend", + json!({"approver": "Steve", "amount_over": "100"}), + ), + 1, + ); + let small = draft(&mut b.l, (b.expense, b.bank), "100.00"); + let big = draft(&mut b.l, (b.expense, b.bank), "100.01"); + + assert_eq!( + b.l.approvals_missing(big).unwrap(), + vec![], + "off by default" + ); + settle(&mut b.l, "policy.approval_rules", json!("enforce")); + assert_eq!( + b.l.approvals_missing(99).unwrap_err(), + LedgerError::UnknownEntry(99) + ); + assert!( + b.l.approvals_missing(small).unwrap().is_empty(), + "exactly the amount is not over it" + ); + assert_eq!( + b.l.approvals_missing(big).unwrap(), + vec![("big-spend".to_string(), "Steve".to_string())] + ); + + // Approved as it stands (name matched loosely): satisfied. + let a = b.l.check_approval(big, "steve", None, &src()).unwrap(); + b.l.apply_approval(big, a).unwrap(); + assert!(b.l.approvals_missing(big).unwrap().is_empty()); + // A line added after: the approval no longer fits the draft. + b.l.add_line( + big, + b.expense, + Side::Debit, + Money::new(dec("1.00"), Currency::USD), + ) + .unwrap(); + b.l.add_line( + big, + b.bank, + Side::Credit, + Money::new(dec("1.00"), Currency::USD), + ) + .unwrap(); + assert_eq!(b.l.approvals_missing(big).unwrap().len(), 1); + + // A rule this version cannot read (a newer version's structure, as + // replay takes it) covers every entry and names no approver. + let future = convention( + "future", + ConventionKind::ApprovalRule, + Some(json!({"quorum": 3})), + ); + b.l.apply_convention(future, 5).unwrap(); + let missing = b.l.approvals_missing(small).unwrap(); + assert_eq!( + missing, + vec![( + "future".to_string(), + "an approver this version can't read".to_string() + )] + ); +} + +/// WB-ledger-10: a rule that names accounts covers an entry touching one +/// of them; the fingerprint is how an approval notices its draft changed: +/// a party, a share's kind and amount, or a stated reason for having none +/// each change it, and a decimal's spelling does not. +#[test] +fn the_fingerprint_notices_parties_shares_and_reasons() { + let mut b = books(); + let e = draft(&mut b.l, (b.expense, b.bank), "20.00"); + let entry = b.l.get_entry(e).unwrap(); + let share = |share| PartyShare { party: 1, share }; + let fp = + |parties: &[PartyShare], none: Option<&str>| conventions::fingerprint(entry, parties, none); + + let plain = fp(&[], None); + let derived = fp(&[share(Share::Derived)], None); + let amount = fp(&[share(Share::Amount(dec("12.50")))], None); + let percent = fp(&[share(Share::Percent(dec("50")))], None); + let none = fp(&[], Some("company expense")); + let all = [&plain, &derived, &amount, &percent, &none]; + for (i, x) in all.iter().enumerate() { + for y in &all[i + 1..] { + assert_ne!(x, y); + } + } + // Trailing zeros are not a change; another amount is; another party is. + assert_eq!(amount, fp(&[share(Share::Amount(dec("12.500")))], None)); + assert_ne!(amount, fp(&[share(Share::Amount(dec("12.51")))], None)); + assert_ne!( + amount, + fp( + &[PartyShare { + party: 2, + share: Share::Amount(dec("12.50")) + }], + None + ) + ); + assert_eq!(percent, fp(&[share(Share::Percent(dec("50.0")))], None)); + assert_ne!(none, fp(&[], Some("owner expense"))); +} + +// ---------------------------------------------------------------- drafting from a template + +/// WB-ledger-9: drafting from a template names the accounts for its slots, +/// splits the amount exactly on each side and refuses anything it cannot +/// make whole: an unknown, retired or non-template convention, a missing or +/// surplus slot, an amount that is not above zero, over the line limit, in +/// fractions of a cent, too small to split, or an account the chart lacks +/// or a heading. +#[test] +fn drafting_from_a_template_refuses_what_it_cannot_make_whole() { + let mut b = books(); + b.l.add_account("1010", "Savings", AccountType::Asset, None, false) + .unwrap(); + let three_way = convention( + "split", + ConventionKind::PostingTemplate, + Some(json!({"description": "Split purchase", "lines": [ + tline("{expense}", "debit", "0.5"), + tline("6000", "debit", "0.5"), + tline("1000", "credit", "0.5"), + tline("1010", "credit", "0.5"), + ]})), + ); + set_convention(&mut b.l, &three_way, 1); + set_convention(&mut b.l, &convention("note", ConventionKind::Note, None), 2); + set_convention(&mut b.l, &two_line_template("old"), 3); + let reason = b.l.check_retire_convention("old", "r", &src()).unwrap(); + b.l.apply_retire_convention("old", reason, src(), 4) + .unwrap(); + + let slots = |pairs: &[(&str, &str)]| -> BTreeMap { + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() + }; + let before = b.l.clone(); + let go = |id: &str, amount: &str, s: &BTreeMap| { + b.l.template_lines(id, dec(amount), s) + }; + + assert!(why(go("missing", "10", &slots(&[]))).contains("unknown convention")); + assert!(why(go("old", "10", &slots(&[]))).contains("template old is retired")); + assert!(why(go("note", "10", &slots(&[]))).contains("is a note, not a posting template")); + let m = why(go("split", "10", &slots(&[]))); + assert!( + m.contains("needs an account for expense: pass accounts {\"expense\": \"\"}"), + "{m}" + ); + let m = why(go( + "split", + "10", + &slots(&[("expense", "6000"), ("bank", "1000")]), + )); + assert!( + m.contains("has no slot \"bank\"; its slots: expense"), + "{m}" + ); + let m = why(go("old2", "10", &slots(&[]))); + assert!(m.contains("unknown convention")); + let ok_slots = slots(&[("expense", "6000")]); + assert!(why(go("split", "0", &ok_slots)).contains("must be above zero")); + assert!(why(go("split", "-5", &ok_slots)).contains("must be above zero")); + assert!(matches!( + go("split", "1000000000000000.01", &ok_slots), + Err(LedgerError::AmountOutOfRange) + )); + assert!( + go("split", "10.001", &ok_slots).is_err(), + "a fraction of a cent" + ); + // 0.01 split in halves: 0.005 each side is under a minor unit, so a part is zero. + assert!(why(go("split", "0.01", &ok_slots)).contains("too small to split")); + assert!(why(go("split", "10", &slots(&[("expense", "7777")]))).contains("is not in the chart")); + assert!(why(go("split", "10", &slots(&[("expense", "5000")]))).contains("is a placeholder")); + + // And made whole: 10.01 in halves is 5.01 / 5.00 by largest remainder + // on each side, summing to 10.01 exactly. + let (description, lines) = go("split", "10.01", &ok_slots).unwrap(); + assert_eq!(description.as_deref(), Some("Split purchase")); + for side in [Side::Debit, Side::Credit] { + let parts: Vec = lines + .iter() + .filter(|(_, s, _)| *s == side) + .map(|(_, _, m)| m.amount) + .collect(); + assert_eq!(parts.len(), 2); + assert_eq!(parts.iter().sum::(), dec("10.01"), "{side:?}"); + } + assert_eq!(b.l, before, "drafting asks and changes nothing"); +} + +// ---------------------------------------------------------------- the pure helpers + +/// WB-ledger-9: a template's split is exact. With no rounding places, +/// each part is amount × share and the last absorbs any difference; with +/// places, each part is truncated and the leftover goes by largest +/// remainder; either way the parts sum to the amount. +#[test] +fn a_split_sums_to_its_amount_exactly() { + let thirds = [dec("0.333"), dec("0.333"), dec("0.334")]; + let exact = conventions::split(dec("100.00"), &thirds, None).unwrap(); + assert_eq!(exact.iter().sum::(), dec("100.00")); + assert_eq!(exact[0], dec("33.300")); + assert_eq!(exact[1], dec("33.300")); + + let cents = conventions::split( + dec("100.00"), + &[dec("0.3333333"), dec("0.3333333"), dec("0.3333334")], + Some(2), + ) + .unwrap(); + assert_eq!(cents.iter().sum::(), dec("100.00")); + assert!(cents.iter().all(|p| p.scale() <= 2)); + + let odd = conventions::split(dec("0.05"), &[dec("0.5"), dec("0.5")], Some(2)).unwrap(); + assert_eq!(odd.iter().sum::(), dec("0.05")); + assert_eq!(odd.iter().copied().max().unwrap(), dec("0.03")); + + // Past exact arithmetic: refused, not a panic. + assert_eq!( + conventions::split(Decimal::MAX, &[dec("1.5"), dec("1.5")], None), + None + ); +} + +/// The convention kinds' words round-trip, and an unknown word is none. +#[test] +fn convention_kinds_round_trip_their_words() { + for k in ConventionKind::ALL { + assert_eq!(ConventionKind::parse(k.key()), Some(k)); + } + assert_eq!(ConventionKind::parse("Policy"), None); + assert_eq!(ConventionKind::parse(""), None); +} + +/// `Approval` carries what an approval needs and nothing a refused one +/// would leave behind: constructing one by hand and applying it is how +/// replay restores it. +#[test] +fn replay_restores_an_approval_as_journaled() { + let mut b = books(); + let e = draft(&mut b.l, (b.expense, b.bank), "5.00"); + let a = Approval { + approver: "Steve".into(), + fingerprint: "deadbeef".into(), + note: None, + source: src(), + seq: 4, + }; + b.l.apply_approval(e, a.clone()).unwrap(); + assert_eq!(b.l.conventions().approvals(e), [a]); + assert!(b.l.conventions().approvals(e + 100).is_empty()); +} diff --git a/crates/ledger-core/tests/document_commands.rs b/crates/ledger-core/tests/document_commands.rs new file mode 100644 index 00000000..e33e7bbc --- /dev/null +++ b/crates/ledger-core/tests/document_commands.rs @@ -0,0 +1,631 @@ +//! The document commands refuse what their rules refuse, and a refusal +//! changes nothing (plan P14 unit V-D2): `mark_sent`, `settle`, +//! `write_off` and the aging list. Coverage found `mark_sent_steps` wholly +//! unreached from the core's own suite and `settle`'s and `write_off`'s +//! refusal arms thin (the store's replay tests are their other callers). +//! +//! ```text +//! GOAL: an invoice's send, a settlement and a write-off are recorded only +//! when the books can stand them; each refusal says why and leaves the +//! books as they were; each success moves exactly the figures its +//! rule says. +//! SOURCE: BS-arap-2 (a document keeps no figure of its own); BS-arap-5 +//! (the direct write-off); BS-arap-6 (settlement); BS-ledger-5, +//! BS-ledger-6 (reversal and void); BS-period-2 (a closed period +//! takes no postings); BS-format-1 (the invoice.sent line). +//! ``` +//! +//! Every test compares the whole ledger to a clone taken before a refused +//! command (`Ledger: PartialEq`) and shows the numbers a successful one +//! moves. + +use chrono::NaiveDate; +use ledger_core::arap::{Application, Fee, InvoiceFields, SendKind, SentVia, SettleParams}; +use ledger_core::settings::{Change, Source}; +use ledger_core::{ + AccountId, AccountType, Currency, DocRef, DocStatus, DocumentLine, Ledger, LedgerError, Sent, +}; +use rust_decimal::Decimal; +use serde_json::json; +use std::str::FromStr; + +fn d(m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(2026, m, day).unwrap() +} + +fn dec(s: &str) -> Decimal { + Decimal::from_str(s).unwrap() +} + +fn lines(amount: &str) -> Vec { + vec![DocumentLine { + description: "Work".into(), + amount: dec(amount), + class_id: None, + account: None, + quantity: None, + unit_price: None, + }] +} + +struct Books { + l: Ledger, + bank: AccountId, + revenue: AccountId, + fees: AccountId, + customer: u64, + other_customer: u64, + vendor: u64, +} + +fn books() -> Books { + let mut l = Ledger::new(Currency::USD); + let mut a = |code: &str, name: &str, t| l.add_account(code, name, t, None, false).unwrap(); + let bank = a("1000", "Bank", AccountType::Asset); + let revenue = a("4010", "Consulting", AccountType::Revenue); + let fees = a("6950", "Card fees", AccountType::Expense); + let customer = l.add_customer("Fernhill Labs").unwrap(); + let other_customer = l.add_customer("Birchwood").unwrap(); + let vendor = l.add_vendor("Tobin Harlow Supply").unwrap(); + Books { + l, + bank, + revenue, + fees, + customer, + other_customer, + vendor, + } +} + +impl Books { + fn invoice(&mut self, on: NaiveDate, amount: &str) -> u64 { + self.l + .create_invoice(self.customer, on, on + chrono::Days::new(30), lines(amount)) + .unwrap() + } + fn bill(&mut self, on: NaiveDate, amount: &str) -> u64 { + self.l + .create_bill(self.vendor, on, on + chrono::Days::new(30), lines(amount)) + .unwrap() + } + fn balance(&self, code: &str) -> Decimal { + match self.l.chart().find_by_code(code) { + Some(a) => self.l.account_balance(a.id).unwrap(), + None => Decimal::ZERO, + } + } +} + +/// Run `f`, which must be refused, and the ledger must be as it was. +fn refused( + l: &mut Ledger, + f: impl FnOnce(&mut Ledger) -> Result, +) -> LedgerError { + let before = l.clone(); + let e = f(l).expect_err("the command should be refused"); + assert_eq!(*l, before, "a refusal changes nothing"); + e +} + +fn sent(on: NaiveDate, to: &[&str]) -> Sent { + Sent { + on, + by: "Steve".into(), + via: SentVia::Email, + to: to.iter().map(|s| s.to_string()).collect(), + kind: SendKind::Original, + reference: None, + note: None, + } +} + +// ---------------------------------------------------------------- mark_sent + +/// BS-arap-2 / mark_sent INVARIANT 4: a send moves no money. The invoice's +/// state is the same on every date before and after, the trial balance is +/// the same, and the send is recorded in order. +#[test] +fn a_send_is_a_fact_of_the_invoices_life_and_moves_no_figure() { + let mut b = books(); + let inv = b.invoice(d(3, 1), "500.00"); + let doc = DocRef::Invoice(inv); + let dates = [d(3, 1), d(3, 15), d(4, 15), d(12, 31)]; + let states = |l: &Ledger| -> Vec<_> { + dates + .iter() + .map(|&x| l.doc_state(doc, x).unwrap()) + .collect() + }; + let (before_states, before_ar, before_bank) = + (states(&b.l), b.balance("1200"), b.balance("1000")); + assert_eq!(before_ar, dec("500.00")); + + let mut first = sent(d(3, 2), &["ap@fernhill.example"]); + first.reference = Some("".into()); + b.l.mark_sent(inv, first.clone()).unwrap(); + let mut reminder = sent(d(4, 5), &["ap@fernhill.example", "ceo@fernhill.example"]); + reminder.kind = SendKind::Reminder; + reminder.note = Some("Second notice".into()); + b.l.mark_sent(inv, reminder.clone()).unwrap(); + + assert_eq!(b.l.get_invoice(inv).unwrap().sends, vec![first, reminder]); + assert_eq!(states(&b.l), before_states, "no figure moved on any date"); + // Receivables still owe the invoice, and the bank is where it was. + assert_eq!(b.balance("1200"), dec("500.00")); + assert_eq!(b.balance("1200"), before_ar); + assert_eq!(b.balance("1000"), before_bank); +} + +/// mark_sent INVARIANT 1 and SCENARIO 1: the invoice must exist and the +/// send must not be dated before it; each refusal changes nothing. +#[test] +fn a_send_needs_an_invoice_and_a_date_no_earlier_than_it() { + let mut b = books(); + let inv = b.invoice(d(3, 10), "500.00"); + let e = refused(&mut b.l, |l| { + l.mark_sent(99, sent(d(3, 11), &["a@b.example"])) + }); + assert_eq!(e, LedgerError::UnknownInvoice(99)); + let e = refused(&mut b.l, |l| { + l.mark_sent(inv, sent(d(3, 9), &["a@b.example"])) + }); + assert!( + matches!(&e, LedgerError::InvalidSend(m) + if m.contains("is dated 2026-03-10") && m.contains("on 2026-03-09")), + "{e:?}" + ); + // The same day is fine. + b.l.mark_sent(inv, sent(d(3, 10), &["a@b.example"])) + .unwrap(); +} + +/// mark_sent INVARIANT 2: a void invoice is never sent (DocumentVoid) but +/// is judged on the day of the send: a void LATER than the send does not +/// un-send it, a void BEFORE it does. Open, partial, paid and written-off +/// invoices all may be sent (a receipt copy, a reminder). +#[test] +fn a_void_invoice_is_not_sent_but_the_day_of_the_send_decides() { + let mut b = books(); + let voided = b.invoice(d(3, 1), "100.00"); + b.l.void_document(DocRef::Invoice(voided), d(3, 20), "duplicate") + .unwrap(); + // Sent before it was voided: allowed. After: refused. + b.l.mark_sent(voided, sent(d(3, 10), &["a@b.example"])) + .unwrap(); + let e = refused(&mut b.l, |l| { + l.mark_sent(voided, sent(d(3, 25), &["a@b.example"])) + }); + assert_eq!(e, LedgerError::DocumentVoid(voided)); + + // Paid, partly paid and written off are all sendable. + let paid = b.invoice(d(4, 1), "100.00"); + b.l.receive_payment(paid, d(4, 5), dec("100.00"), b.bank) + .unwrap(); + let partial = b.invoice(d(4, 1), "100.00"); + b.l.receive_payment(partial, d(4, 5), dec("40.00"), b.bank) + .unwrap(); + let written_off = b.invoice(d(4, 1), "100.00"); + b.l.write_off(written_off, d(4, 6), dec("100.00"), "uncollectible") + .unwrap(); + for (inv, status) in [ + (paid, DocStatus::Paid), + (partial, DocStatus::Partial), + (written_off, DocStatus::WrittenOff), + ] { + assert_eq!( + b.l.doc_state(DocRef::Invoice(inv), d(4, 10)) + .unwrap() + .unwrap() + .status, + status + ); + b.l.mark_sent(inv, sent(d(4, 10), &["a@b.example"])) + .unwrap(); + } +} + +/// mark_sent INVARIANT 3: at least one recipient, and every recipient, the +/// reference and the note pass the party text rule (no full TIN, no +/// control character, at most 500 characters). +#[test] +fn a_send_needs_a_recipient_and_clean_text() { + let mut b = books(); + let inv = b.invoice(d(3, 1), "500.00"); + let e = refused(&mut b.l, |l| l.mark_sent(inv, sent(d(3, 2), &[]))); + assert!( + matches!(&e, LedgerError::InvalidSend(m) if m.contains("needs at least one recipient")), + "{e:?}" + ); + + let e = refused(&mut b.l, |l| { + l.mark_sent(inv, sent(d(3, 2), &["ok@x.example", "SSN 123-45-6789"])) + }); + assert!( + matches!(&e, LedgerError::InvalidSend(m) if m.contains("recipient") && m.contains("taxpayer identification")), + "{e:?}" + ); + let e = refused(&mut b.l, |l| { + l.mark_sent(inv, sent(d(3, 2), &["a\u{7}b@x.example"])) + }); + assert!( + matches!(&e, LedgerError::InvalidSend(m) if m.contains("control characters")), + "{e:?}" + ); + + let mut with_ref = sent(d(3, 2), &["a@b.example"]); + with_ref.reference = Some("x".repeat(501)); + let e = refused(&mut b.l, |l| l.mark_sent(inv, with_ref)); + assert!( + matches!(&e, LedgerError::InvalidSend(m) if m.contains("the reference is at most 500")), + "{e:?}" + ); + + let mut with_note = sent(d(3, 2), &["a@b.example"]); + with_note.note = Some("EIN 12-3456789".into()); + let e = refused(&mut b.l, |l| l.mark_sent(inv, with_note)); + assert!( + matches!(&e, LedgerError::InvalidSend(m) if m.contains("the note")), + "{e:?}" + ); + assert!(b.l.get_invoice(inv).unwrap().sends.is_empty()); +} + +// ---------------------------------------------------------------- settle + +fn settle_one(b: &Books, inv: u64, cash: &str) -> SettleParams { + SettleParams { + date: d(3, 20), + description: String::new(), + cash_account: b.bank, + party: b.customer, + applications: vec![Application { + doc: DocRef::Invoice(inv), + cash: dec(cash), + discount: Decimal::ZERO, + discount_reason: None, + }], + fee: None, + instrument: None, + reference: None, + } +} + +/// BS-arap-6 statements 1, 4, 5 and 6 (invariants 4 and 5): each thing a +/// settlement can be refused for, +/// refused with its own error, the books untouched. The invoice is for +/// 500.00 dated March 1; the payment is dated March 20. +#[test] +fn a_settlement_is_refused_for_what_it_cannot_make_whole() { + let mut b = books(); + let inv = b.invoice(d(3, 1), "500.00"); + let other = + b.l.create_invoice(b.other_customer, d(3, 1), d(3, 31), lines("80.00")) + .unwrap(); + let bill = b.bill(d(3, 1), "300.00"); + let go = |b: &mut Books, f: &dyn Fn(&mut SettleParams)| { + let mut p = settle_one(b, inv, "100.00"); + f(&mut p); + refused(&mut b.l, |l| l.settle(p)) + }; + + assert_eq!( + go(&mut b, &|p| p.applications.clear()), + LedgerError::SettlementEmpty + ); + assert!(matches!( + go(&mut b, &|p| p.applications.push(Application { + doc: DocRef::Bill(bill), cash: dec("1.00"), discount: Decimal::ZERO, discount_reason: None + })), + LedgerError::SettlementMixedKinds(m) if m.contains(&bill.to_string()) + )); + assert!(matches!( + go(&mut b, &|p| p.applications.push(Application { + doc: DocRef::Invoice(other), cash: dec("1.00"), discount: Decimal::ZERO, discount_reason: None + })), + LedgerError::SettlementPartiesDiffer(_, party) if party == b.customer + )); + assert_eq!( + go(&mut b, &|p| p.applications[0].doc = DocRef::Invoice(77)), + LedgerError::UnknownInvoice(77) + ); + assert!(matches!( + go(&mut b, &|p| p.date = NaiveDate::MAX), + LedgerError::DateOutOfRange(_) + )); + assert_eq!( + go(&mut b, &|p| p.instrument = Some(9)), + LedgerError::UnknownInstrument(9) + ); + let revenue = b.revenue; + assert!(matches!( + go(&mut b, &|p| p.cash_account = revenue), + LedgerError::PaymentAccount { why, .. } if why.contains("revenue") + )); + assert!(matches!( + go(&mut b, &|p| p.applications.push(p.applications[0].clone())), + LedgerError::SettlementDuplicateDocument(_) + )); + assert_eq!( + go(&mut b, &|p| p.applications[0].cash = Decimal::ZERO), + LedgerError::InvalidPaymentAmount(Decimal::ZERO) + ); + assert!(matches!( + go(&mut b, &|p| p.applications[0].discount = dec("-1.00")), + LedgerError::InvalidSettlement(m) if m.contains("a discount cannot be negative") + )); + assert!(matches!( + go(&mut b, &|p| p.date = d(2, 28)), + LedgerError::PaymentBeforeDocument { .. } + )); + assert_eq!( + go(&mut b, &|p| p.applications[0].cash = dec("500.01")), + LedgerError::Overpayment(dec("500.01"), dec("500.00")) + ); + for bad in ["two\nlines".to_string(), "x".repeat(300)] { + assert!(matches!( + go(&mut b, &|p| { + p.applications[0].discount = dec("1.00"); + p.applications[0].discount_reason = Some(bad.clone()); + }), + LedgerError::InvalidDiscountReason(_) + )); + } + // A discount the terms don't state and no reason is refused, saying why. + assert!(matches!( + go(&mut b, &|p| p.applications[0].discount = dec("1.00")), + LedgerError::DiscountNeedsReason { because, .. } + if because.contains("no early-payment discount") + )); +} + +/// BS-arap-6, the fee: it comes out of a customer payment gross, goes to an +/// expense account, and cannot be the whole payment; the cash and +/// discounts must cover the applications exactly. A closed period takes no +/// settlement. +#[test] +fn a_fee_is_an_expense_taken_from_the_payment_and_a_closed_period_refuses() { + let mut b = books(); + let inv = b.invoice(d(3, 1), "500.00"); + let fee = |amount: &str, account: Option| { + Some(Fee { + amount: dec(amount), + account, + vendor: None, + }) + }; + // The fee is the whole payment: nothing would be deposited. + let mut p = settle_one(&b, inv, "100.00"); + p.fee = fee("100.00", Some(b.fees)); + assert!(matches!( + refused(&mut b.l, |l| l.settle(p)), + LedgerError::InvalidSettlement(m) if m.contains("deposit would be nothing") + )); + // The fee is above the cash. + let mut p = settle_one(&b, inv, "100.00"); + p.fee = fee("100.01", Some(b.fees)); + assert_eq!( + refused(&mut b.l, |l| l.settle(p)), + LedgerError::FeeAboveCash { + fee: dec("100.01"), + cash: dec("100.00") + } + ); + // The fee's account must be an expense that takes postings. + let mut p = settle_one(&b, inv, "100.00"); + p.fee = fee("3.20", Some(b.revenue)); + assert!(matches!( + refused(&mut b.l, |l| l.settle(p)), + LedgerError::InvalidFee(m) if m.contains("is not an expense account") + )); + + // A real one: 100.00 paid, 3.20 withheld: the receivable falls by the + // gross 100.00, the fee is 3.20 of expense, the bank gets 96.80. + let mut p = settle_one(&b, inv, "100.00"); + p.fee = fee("3.20", Some(b.fees)); + p.description = "Stripe payout".into(); + let entry = b.l.settle(p).unwrap(); + assert_eq!(b.l.get_entry(entry).unwrap().description(), "Stripe payout"); + assert_eq!(b.balance("1000"), dec("96.80")); + assert_eq!(b.balance("6950"), dec("3.20")); + assert_eq!(b.balance("1200"), dec("400.00")); + let st = + b.l.doc_state(DocRef::Invoice(inv), d(3, 31)) + .unwrap() + .unwrap(); + assert_eq!( + (st.paid, st.outstanding, st.status), + (dec("100.00"), dec("400.00"), DocStatus::Partial) + ); + + // A closed period takes no settlement. + let q = b.l.create_period("March", d(3, 1), d(3, 31)).unwrap(); + b.l.close_period(q).unwrap(); + let p = settle_one(&b, inv, "100.00"); + assert!( + matches!(refused(&mut b.l, |l| l.settle(p)), LedgerError::ClosedPeriod(id, _) if id == q) + ); +} + +/// BS-arap-6 and the settlement's own description: with no description it +/// says how many documents; a payment on a bill is the mirror (Dr payables, +/// Cr cash) and a fee on a bill is not a thing. +#[test] +fn a_bill_settlement_mirrors_an_invoices_and_describes_itself() { + let mut b = books(); + let bill = b.bill(d(3, 1), "300.00"); + let p = SettleParams { + date: d(3, 20), + description: " ".into(), + cash_account: b.bank, + party: b.vendor, + applications: vec![Application { + doc: DocRef::Bill(bill), + cash: dec("300.00"), + discount: Decimal::ZERO, + discount_reason: None, + }], + fee: None, + instrument: None, + reference: None, + }; + let entry = b.l.settle(p).unwrap(); + assert_eq!( + b.l.get_entry(entry).unwrap().description(), + "Settlement of 1 document" + ); + assert_eq!(b.balance("2000"), Decimal::ZERO, "the payable is settled"); + assert_eq!(b.balance("1000"), dec("-300.00")); + let st = + b.l.doc_state(DocRef::Bill(bill), d(3, 31)) + .unwrap() + .unwrap(); + assert_eq!(st.status, DocStatus::Paid); +} + +// ---------------------------------------------------------------- write_off + +/// BS-arap-5 statements 2, 4 and 6 (invariants 2, 3 and 5; the one-line +/// reason is the engine's own guard, beside statement 9's evidence of the +/// debt): a write-off is refused on the cash basis, +/// without a one-line reason, for an amount that is not above zero, off the +/// calendar, before the invoice, in a closed period, or more than the +/// invoice owes on every day from then on; the refusals change nothing. +#[test] +fn a_write_off_is_refused_for_each_rule_it_breaks() { + let mut b = books(); + let inv = b.invoice(d(3, 1), "100.00"); + b.l.receive_payment(inv, d(4, 10), dec("30.00"), b.bank) + .unwrap(); + let off = |l: &mut Ledger, date, amount: &str, reason: &str| { + refused(l, |l| l.write_off(inv, date, dec(amount), reason)) + }; + let msg = |e: LedgerError| match e { + LedgerError::InvalidWriteOff(m) => m, + other => panic!("{other:?}"), + }; + + assert!(msg(off(&mut b.l, d(4, 1), "10.00", " ")).contains("needs its reason")); + assert!(msg(off(&mut b.l, d(4, 1), "10.00", "a\nb")).contains("needs its reason")); + assert!(msg(off(&mut b.l, d(4, 1), "10.00", &"x".repeat(300))).contains("needs its reason")); + assert!(msg(off(&mut b.l, d(4, 1), "0", "gone")).contains("must be above zero")); + assert!(msg(off(&mut b.l, d(4, 1), "-5", "gone")).contains("must be above zero")); + let e = refused(&mut b.l, |l| { + l.write_off(inv, NaiveDate::MAX, dec("5"), "gone") + }); + assert!(matches!(e, LedgerError::DateOutOfRange(_))); + assert!(msg(off(&mut b.l, d(2, 20), "10.00", "gone")).contains("can't be before invoice")); + let e = refused(&mut b.l, |l| l.write_off(77, d(4, 1), dec("5"), "gone")); + assert_eq!(e, LedgerError::UnknownInvoice(77)); + // On April 1 the invoice owes 100.00, but the 30.00 payment on April 10 + // means no day may owe less than nothing: only 70.00 can go. + let m = msg(off(&mut b.l, d(4, 1), "80.00", "gone")); + assert!( + m.contains("more than invoice") && m.contains("100.00") && m.contains("70.00"), + "{m}" + ); + // After the payment the room is what is owed; more than that is refused + // without the "once payments after it are counted" clause. + let m = msg(off(&mut b.l, d(4, 15), "70.01", "gone")); + assert!( + m.contains("owes on 2026-04-15: 70.00") && !m.contains("once the payments"), + "{m}" + ); + + // A closed period. + let q = b.l.create_period("March", d(3, 1), d(3, 31)).unwrap(); + b.l.close_period(q).unwrap(); + let e = refused(&mut b.l, |l| l.write_off(inv, d(3, 20), dec("5"), "gone")); + assert!(matches!(e, LedgerError::ClosedPeriod(id, _) if id == q)); + + // Written off at the room that is left: bad debt 70.00, receivable 0. + let entry = + b.l.write_off(inv, d(4, 15), dec("70.00"), " uncollectible ") + .unwrap(); + assert_eq!( + b.l.get_entry(entry).unwrap().description(), + "Write off invoice 1: uncollectible" + ); + assert_eq!(b.balance("6990"), dec("70.00")); + assert_eq!(b.balance("1200"), Decimal::ZERO); +} + +/// BS-arap-5 statement 6 (invariant 5): on cash-basis books nothing is receivable to +/// write off, so the command is refused whatever else is true. +#[test] +fn a_write_off_is_refused_on_the_cash_basis() { + let mut b = books(); + let inv = b.invoice(d(3, 1), "100.00"); + let src = Source { + decided_by: "Owner".into(), + decided_on: d(11, 9), + citation: None, + note: None, + }; + let changes = [Change { + key: "books.accounting_basis".into(), + value: Some(json!("cash")), + }]; + let made = b.l.check_settings(&changes, &src).unwrap(); + b.l.apply_settings(&made, &src, 1).unwrap(); + let e = refused(&mut b.l, |l| { + l.write_off(inv, d(4, 1), dec("10.00"), "gone") + }); + assert_eq!(e, LedgerError::WriteOffOnCashBasis); +} + +// ---------------------------------------------------------------- aging + +/// BS-arap-2: the aging list is the documents that owe something on the +/// day, oldest due first, each in the bucket its due date puts it in, and +/// invoices and bills are listed apart. A paid, void or not yet issued +/// document is not listed. +#[test] +fn aging_lists_what_is_owed_oldest_due_first() { + let mut b = books(); + let late = b.invoice(d(1, 5), "100.00"); // due Feb 4 + let newer = b.invoice(d(3, 1), "200.00"); // due Mar 31 + let paid = b.invoice(d(1, 6), "50.00"); + b.l.receive_payment(paid, d(1, 10), dec("50.00"), b.bank) + .unwrap(); + let voided = b.invoice(d(1, 7), "60.00"); + b.l.void_document(DocRef::Invoice(voided), d(1, 8), "dup") + .unwrap(); + let future = b.invoice(d(6, 1), "70.00"); + let bill = b.bill(d(2, 1), "300.00"); + b.l.pay_bill(bill, d(2, 5), dec("100.00"), b.bank).unwrap(); + + let aging = b.l.aging_documents(d(4, 15), true).unwrap(); + let ids: Vec = aging.iter().map(|a| a.doc).collect(); + assert_eq!(ids, vec![DocRef::Invoice(late), DocRef::Invoice(newer)]); + assert!(!ids.contains(&DocRef::Invoice(future))); + assert_eq!(aging[0].party, "Fernhill Labs"); + assert_eq!(aging[0].outstanding, dec("100.00")); + assert_eq!(aging[0].due_date, d(2, 4)); + assert!(aging[0].days_overdue > aging[1].days_overdue); + assert_eq!(aging[1].bucket, "days_30"); + + let bills = b.l.aging_documents(d(4, 15), false).unwrap(); + assert_eq!(bills.len(), 1); + assert_eq!(bills[0].doc, DocRef::Bill(bill)); + assert_eq!( + (bills[0].total, bills[0].paid, bills[0].outstanding), + (dec("300.00"), dec("100.00"), dec("200.00")) + ); + assert_eq!(bills[0].party, "Tobin Harlow Supply"); + + // With a terms string the list shows it. + let fields = InvoiceFields { + terms: Some(ledger_core::arap::Terms::parse("2/10 net 30").unwrap()), + ..InvoiceFields::default() + }; + let termed = + b.l.create_invoice_with(b.customer, d(4, 1), d(5, 1), lines("10.00"), fields) + .unwrap(); + let aging = b.l.aging_documents(d(4, 15), true).unwrap(); + let t = aging + .iter() + .find(|a| a.doc == DocRef::Invoice(termed)) + .unwrap(); + assert_eq!(t.terms.as_deref(), Some("2/10 net 30")); +} diff --git a/crates/ledger-core/tests/evidence_gate.rs b/crates/ledger-core/tests/evidence_gate.rs new file mode 100644 index 00000000..3d30e330 --- /dev/null +++ b/crates/ledger-core/tests/evidence_gate.rs @@ -0,0 +1,768 @@ +//! The evidence requirement and the annotation's checks, branch by branch +//! (plan P14 unit V-D2; coverage found `evidence.rs` at 34% of lines from +//! the core's own suite, its callers being the store, the server and the +//! viewer). +//! +//! ```text +//! GOAL: which entry needs evidence, under which rule, and what an +//! annotation may record, decided by the engine alone and read the +//! same by every caller. +//! SOURCE: BS-entry-5; WB-entry-5; WB-entry-6; WB-ledger-15; +//! IRS Pub. 583 (records that support entries). +//! ``` +//! +//! Every test goes through the public API: `evidence::{requirement, +//! Policy, Annotation}` and the `Ledger` commands that make an entry of +//! each origin. A requirement is a pure question (WB-entry-5): each test +//! that asks one also checks the books are as they were. + +use chrono::NaiveDate; +use ledger_core::evidence::{Annotation, AnnotationFields, Origin, Policy, Requirement}; +use ledger_core::settings::{Change, Source}; +use ledger_core::{ + AccountId, AccountType, Currency, DocumentLine, EntryId, EntryStatus, Frequency, Ledger, + LedgerError, Money, NewAsset, NewSchedule, PayrollLine, ScheduleConvention, ScheduleKind, Side, +}; +use rust_decimal::Decimal; +use serde_json::{Value, json}; +use std::str::FromStr; + +fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() +} + +fn dec(s: &str) -> Decimal { + Decimal::from_str(s).unwrap() +} + +fn usd(s: &str) -> Money { + Money::new(dec(s), Currency::USD) +} + +fn src() -> Source { + Source { + decided_by: "Owner".into(), + decided_on: d(2026, 11, 9), + citation: None, + note: None, + } +} + +/// Set books settings the way a human does: checked, then applied. +fn set(l: &mut Ledger, pairs: &[(&str, Value)]) { + let changes: Vec = pairs + .iter() + .map(|(k, v)| Change { + key: (*k).into(), + value: Some(v.clone()), + }) + .collect(); + let made = l.check_settings(&changes, &src()).unwrap(); + l.apply_settings(&made, &src(), 1).unwrap(); +} + +struct Books { + l: Ledger, + cash: AccountId, + capital: AccountId, + revenue: AccountId, + supplies: AccountId, + meals: AccountId, +} + +fn books() -> Books { + let mut l = Ledger::new(Currency::USD); + let mut a = |code: &str, name: &str, t| l.add_account(code, name, t, None, false).unwrap(); + let cash = a("1000", "Cash", AccountType::Asset); + let capital = a("3000", "Capital", AccountType::Equity); + let revenue = a("4100", "Sales", AccountType::Revenue); + let supplies = a("6200", "Supplies", AccountType::Expense); + let meals = a("6300", "Meals", AccountType::Expense); + Books { + l, + cash, + capital, + revenue, + supplies, + meals, + } +} + +/// A balanced draft: `debit` debited, `credit` credited, `amount` each way. +fn draft( + l: &mut Ledger, + date: NaiveDate, + what: &str, + debit: AccountId, + credit: AccountId, + amount: &str, +) -> EntryId { + let e = l.create_entry(date, what); + l.add_line(e, debit, Side::Debit, usd(amount)).unwrap(); + l.add_line(e, credit, Side::Credit, usd(amount)).unwrap(); + e +} + +fn post( + l: &mut Ledger, + date: NaiveDate, + what: &str, + debit: AccountId, + credit: AccountId, + amount: &str, +) -> EntryId { + let e = draft(l, date, what, debit, credit, amount); + l.post_entry(e).unwrap(); + e +} + +fn requirement(l: &Ledger, e: EntryId) -> Requirement { + let before = l.clone(); + let r = ledger_core::evidence::requirement(l, l.get_entry(e).unwrap(), l.settings()); + assert_eq!(*l, before, "asking is pure (WB-entry-5)"); + r +} + +fn required_reason(r: &Requirement) -> &str { + match r { + Requirement::Required { reason } => reason, + Requirement::Exempt { source } => panic!("expected Required, got Exempt: {source}"), + } +} + +fn exempt_source(r: &Requirement) -> &'static str { + match r { + Requirement::Exempt { source } => source, + Requirement::Required { reason } => panic!("expected Exempt, got Required: {reason}"), + } +} + +// ---------------------------------------------------------------- annotations + +/// WB-ledger-15 invariant 4: an annotation's fields are a closed list; text is +/// kept trimmed and a blank one is not kept; every field is optional. +#[test] +fn annotation_fields_are_trimmed_and_blank_ones_dropped() { + let fields = AnnotationFields { + receipt_number: Some(7), + payee: Some(" Fernhill Labs ".into()), + amount: Some(dec("20.00")), + date: Some(d(2026, 11, 3)), + instrument: Some(" ".into()), + category: Some("\treceipt\n".into()), + source: Some("".into()), + reimbursable_to: Some(" Steve ".into()), + }; + let kept = fields.checked().unwrap(); + assert_eq!(kept.receipt_number, Some(7)); + assert_eq!(kept.payee.as_deref(), Some("Fernhill Labs")); + assert_eq!(kept.amount, Some(dec("20.00"))); + assert_eq!(kept.date, Some(d(2026, 11, 3))); + assert_eq!(kept.instrument, None, "a blank text is no fact"); + assert_eq!(kept.category.as_deref(), Some("receipt")); + assert_eq!(kept.source, None); + assert_eq!(kept.reimbursable_to.as_deref(), Some("Steve")); + assert!(!kept.is_empty()); +} + +/// WB-ledger-15 invariant 4: "nothing recorded" is judged field by field: any +/// one field alone makes the record non-empty, and none makes it empty. +#[test] +fn an_annotation_field_alone_is_a_record() { + assert!(AnnotationFields::default().is_empty()); + let one = |f: fn(&mut AnnotationFields)| { + let mut x = AnnotationFields::default(); + f(&mut x); + x + }; + let each = [ + one(|x| x.receipt_number = Some(1)), + one(|x| x.payee = Some("a".into())), + one(|x| x.amount = Some(Decimal::ZERO)), + one(|x| x.date = Some(d(2026, 1, 1))), + one(|x| x.instrument = Some("a".into())), + one(|x| x.category = Some("a".into())), + one(|x| x.source = Some("a".into())), + one(|x| x.reimbursable_to = Some("a".into())), + ]; + for (i, f) in each.iter().enumerate() { + assert!(!f.is_empty(), "field {i} alone is a fact"); + } +} + +/// WB-ledger-15 invariant 4 and its numbering (the receipt rule's): a +/// receipt number is positive, an amount is not negative, a date is in the +/// books' calendar (0001-01-01..=9999-12-31). A zero amount is a fact (a +/// no-charge receipt). +#[test] +fn an_annotation_refuses_a_zero_number_a_negative_amount_and_a_date_off_the_calendar() { + let bad = |f: AnnotationFields| f.checked().unwrap_err(); + // The variant, and the fact each refusal states; the sentence around + // it is the engine's own. + assert!(matches!( + bad(AnnotationFields { + receipt_number: Some(0), + ..Default::default() + }), + LedgerError::InvalidEvidence(m) if m.contains("positive") + )); + assert!(matches!( + bad(AnnotationFields { + amount: Some(dec("-0.01")), + ..Default::default() + }), + LedgerError::InvalidEvidence(m) if m.contains("negative") + )); + let off = NaiveDate::MAX; + assert_eq!( + bad(AnnotationFields { + date: Some(off), + ..Default::default() + }), + LedgerError::DateOutOfRange(off) + ); + // The edges that are fine. + let ok = AnnotationFields { + receipt_number: Some(1), + amount: Some(Decimal::ZERO), + date: Some(d(9999, 12, 31)), + ..Default::default() + }; + assert_eq!(ok.clone().checked().unwrap(), ok); +} + +/// WB-ledger-15 invariant 4: an annotation records at least one field or a +/// note; the note is trimmed, and a blank one is no note. +#[test] +fn an_annotation_needs_a_field_or_a_note() { + let ann = |fields, note: Option<&str>| Annotation { + attachment_id: 3, + fields, + note: note.map(str::to_string), + }; + let none = ann(AnnotationFields::default(), None); + assert_eq!( + none.checked().unwrap_err(), + LedgerError::InvalidEvidence("an annotation records at least one field or a note".into()) + ); + // Texts that trim to nothing leave nothing. + let blank = ann( + AnnotationFields { + payee: Some(" ".into()), + ..Default::default() + }, + Some(" \n"), + ); + assert!(matches!( + blank.checked().unwrap_err(), + LedgerError::InvalidEvidence(_) + )); + // A note alone is enough, and is kept trimmed. + let noted = ann(AnnotationFields::default(), Some(" faded, read twice ")) + .checked() + .unwrap(); + assert_eq!(noted.note.as_deref(), Some("faded, read twice")); + assert_eq!(noted.attachment_id, 3); + // A field alone is enough; its error from `AnnotationFields` comes through. + assert!( + ann( + AnnotationFields { + receipt_number: Some(9), + ..Default::default() + }, + None + ) + .checked() + .is_ok() + ); + assert!( + ann( + AnnotationFields { + receipt_number: Some(0), + ..Default::default() + }, + Some("note") + ) + .checked() + .is_err() + ); +} + +// ---------------------------------------------------------------- the policy + +/// BS-entry-5: the policy is the books' settings; the default threshold is +/// 25.00, and its words say how strictly. +#[test] +fn the_policy_reads_the_books_settings() { + let mut b = books(); + let p = Policy::from_settings(b.l.settings()); + assert_eq!(p.threshold, dec("25.00")); + assert!(p.required_accounts.is_empty() && p.exempt_accounts.is_empty()); + // The description states the threshold and that it is strict (the + // wording is the engine's own). + let described = p.describe(); + assert!( + described.contains("strictly greater") && described.contains("25.00"), + "{described}" + ); + + set( + &mut b.l, + &[ + ("policy.evidence.threshold", json!("0.00")), + ("policy.evidence.required_accounts", json!(["6300"])), + ("policy.evidence.exempt_accounts", json!(["1000", "3000"])), + ], + ); + let p = Policy::from_settings(b.l.settings()); + assert_eq!(p.threshold, Decimal::ZERO); + assert_eq!(p.required_accounts, vec!["6300".to_string()]); + assert_eq!( + p.exempt_accounts, + vec!["1000".to_string(), "3000".to_string()] + ); + assert_eq!(p.describe(), "receipts required on every entry"); +} + +/// BS-entry-5, "strictly greater" (owner, 2026-10-12): at the threshold no +/// receipt, one cent over, a receipt. A required account needs one at any +/// amount; the exemption holds only when EVERY line is on an exempt account. +#[test] +fn the_threshold_is_strict_and_the_exemption_needs_every_line() { + let policy = Policy { + threshold: dec("25.00"), + required_accounts: vec!["6300".into()], + exempt_accounts: vec!["1000".into(), "6200".into()], + }; + assert!(!policy.receipt_required_for(&["6200", "1000"], dec("25.00"))); + assert!(policy.receipt_required_for(&["6100", "1000"], dec("25.01"))); + // Over the threshold but every line exempt: none. + assert!(!policy.receipt_required_for(&["6200", "1000"], dec("5000.00"))); + // One line off the exempt list brings the policy back. + assert!(policy.receipt_required_for(&["6200", "1000", "6100"], dec("5000.00"))); + // A required account needs one at a cent, and beats the exemption. + assert!(policy.receipt_required_for(&["6300", "1000"], dec("0.01"))); + assert!(policy.receipt_required_for(&["6300"], dec("0.00"))); + // An account the chart does not have is a code like another. + assert!(!policy.receipt_required_for(&[], dec("25.00"))); +} + +/// BS-entry-5 / WB-entry-5: the answer carries its reason, in words a +/// refusal or a checklist can show; a hand entry under the threshold is +/// Exempt with the policy as its source. +#[test] +fn a_hand_entry_is_required_above_the_threshold_with_its_reason() { + let mut b = books(); + let big = post( + &mut b.l, + d(2026, 11, 2), + "Printer", + b.supplies, + b.cash, + "40.00", + ); + let small = post( + &mut b.l, + d(2026, 11, 2), + "Pens", + b.supplies, + b.cash, + "25.00", + ); + let r = requirement(&b.l, big); + assert!(r.is_required()); + // The reason carries the figures and the strict comparison (the + // sentence is the engine's own). + let why = required_reason(&r); + assert!( + why.contains("40.00") && why.contains("25.00") && why.contains("strictly greater"), + "{why}" + ); + let r = requirement(&b.l, small); + assert!(!r.is_required()); + assert!(exempt_source(&r).contains("under the threshold, or on exempt accounts")); +} + +/// BS-entry-5: a required account (`policy.evidence.required_accounts`) +/// makes any amount need a receipt, and the reason names the account. +#[test] +fn a_required_account_always_needs_a_receipt() { + let mut b = books(); + set( + &mut b.l, + &[("policy.evidence.required_accounts", json!(["6300"]))], + ); + let e = post(&mut b.l, d(2026, 11, 2), "Lunch", b.meals, b.cash, "4.50"); + assert_eq!( + required_reason(&requirement(&b.l, e)), + "it touches account 6300, which always needs a receipt" + ); + let f = post(&mut b.l, d(2026, 11, 2), "Pens", b.supplies, b.cash, "4.50"); + assert!(!requirement(&b.l, f).is_required()); +} + +/// BS-entry-5: threshold 0.00 requires a receipt on everything, except an +/// entry whose every line is on an exempt account (an owner contribution +/// between cash and capital). +#[test] +fn exempt_accounts_exempt_only_whole_entries() { + let mut b = books(); + set( + &mut b.l, + &[ + ("policy.evidence.threshold", json!("0.00")), + ("policy.evidence.exempt_accounts", json!(["1000", "3000"])), + ], + ); + let contribution = post( + &mut b.l, + d(2026, 11, 1), + "Capital", + b.cash, + b.capital, + "9000.00", + ); + let purchase = post(&mut b.l, d(2026, 11, 2), "Pens", b.supplies, b.cash, "0.50"); + assert!(!requirement(&b.l, contribution).is_required()); + assert!(requirement(&b.l, purchase).is_required()); +} + +/// BS-entry-4 and BS-entry-5: a draft's lines are as journaled, of any +/// size. Debits past exact arithmetic are refused (TooLargeToCompute) when +/// summed directly and are past any threshold when a requirement is +/// asked: Required, never a panic. +#[test] +fn debits_past_exact_arithmetic_are_refused_by_the_sum_and_past_the_threshold_for_the_gate() { + let mut b = books(); + let e = b.l.create_entry(d(2026, 11, 2), "Absurd"); + for _ in 0..2 { + b.l.replay_add_line( + e, + b.supplies, + Side::Debit, + Money::new(Decimal::MAX, Currency::USD), + ) + .unwrap(); + } + let entry = b.l.get_entry(e).unwrap(); + assert!(matches!( + Policy::entry_debits(entry), + Err(LedgerError::TooLargeToCompute(_)) + )); + let r = requirement(&b.l, e); + assert!(r.is_required()); + let policy = Policy::from_settings(b.l.settings()); + assert!(policy.receipt_required(&b.l, entry)); + // And no split group is reported for it: it is past the threshold alone. + assert!(policy.split_group(&b.l, e, entry).is_empty()); +} + +// ---------------------------------------------------------------- split groups + +/// WB-entry-6 (an entry "as part of a split group"), the anti-gaming +/// rule: four same-day, same-description, same-debit-account entries of +/// 10.00 are one 40.00 purchase. The draft +/// that brings the group past the threshold needs a receipt and names the +/// group; the ones before it, and a posted entry, do not (a posted entry's +/// decision was made when it posted). +#[test] +fn a_split_purchase_is_one_purchase() { + let mut b = books(); + let day = d(2026, 11, 4); + let a = post(&mut b.l, day, "Office chairs", b.supplies, b.cash, "10.00"); + let c = post(&mut b.l, day, "office CHAIRS", b.supplies, b.cash, "10.00"); + // Two of 10.00 are 20.00: still under 25.00, nothing is flagged. + let third = draft(&mut b.l, day, "Office chairs", b.supplies, b.cash, "10.00"); + let r = requirement(&b.l, third); + assert!( + required_reason(&r).contains("split group"), + "30.00 together is over 25.00: {r:?}" + ); + assert!(required_reason(&r).contains(&format!("{a}"))); + assert!(required_reason(&r).contains(&format!("{c}"))); + assert!( + required_reason(&r).contains("applies to the group total"), + "the reason says what the policy applies to" + ); + // Posted entries are not judged again from their neighbours. + b.l.post_entry(third).unwrap(); + assert!(!requirement(&b.l, a).is_required()); + assert!(!requirement(&b.l, third).is_required()); +} + +/// WB-entry-6: what is NOT a split group. A different day, a different +/// description, a different debit account, a group still under the +/// threshold and a reversal in the group (reversals are exempt) leave the +/// new draft alone. +#[test] +fn only_the_same_day_description_and_accounts_make_a_split_group() { + let mut b = books(); + let day = d(2026, 11, 4); + let first = post(&mut b.l, day, "Chairs", b.supplies, b.cash, "20.00"); + let policy = Policy::from_settings(b.l.settings()); + + let other_day = draft( + &mut b.l, + d(2026, 11, 5), + "Chairs", + b.supplies, + b.cash, + "10.00", + ); + let other_text = draft(&mut b.l, day, "Desks", b.supplies, b.cash, "10.00"); + let other_account = draft(&mut b.l, day, "Chairs", b.meals, b.cash, "10.00"); + for e in [other_day, other_text, other_account] { + let entry = b.l.get_entry(e).unwrap(); + assert!(policy.split_group(&b.l, e, entry).is_empty()); + assert!(!requirement(&b.l, e).is_required()); + } + + // A reversal is exempt from the policy, so it is not counted: reversing + // the 20.00 purchase leaves a posted reversal on the same day with the + // same description that DEBITS cash. A 20.00 draft that also debits + // cash is not "the same purchase" again, though 20.00 + 20.00 > 25.00. + let rev = b.l.reverse_entry(first, day, "Chairs").unwrap(); + assert!(b.l.get_entry(rev).unwrap().reversal_of().is_some()); + let refund = draft(&mut b.l, day, "Chairs", b.cash, b.supplies, "20.00"); + let entry = b.l.get_entry(refund).unwrap(); + assert!(policy.split_group(&b.l, refund, entry).is_empty()); + assert!(!requirement(&b.l, refund).is_required()); +} + +// ---------------------------------------------------------------- the origins + +/// WB-entry-6: a reversal is exempt, even of a large hand entry: its +/// evidence is its original's (D-47, D-12). +#[test] +fn a_reversal_of_a_large_entry_needs_no_receipt_of_its_own() { + let mut b = books(); + let big = post( + &mut b.l, + d(2026, 11, 2), + "Server", + b.supplies, + b.cash, + "5000.00", + ); + assert!(requirement(&b.l, big).is_required()); + let rev = + b.l.reverse_entry(big, d(2026, 11, 3), "Server returned") + .unwrap(); + let src = exempt_source(&requirement(&b.l, rev)); + assert!(src.starts_with("a reversal"), "{src}"); + assert!(src.contains("BS-entry-5")); +} + +/// WB-entry-6: a period's closing entry is derived from the books. +#[test] +fn a_closing_entry_is_derived_so_it_needs_no_receipt() { + let mut b = books(); + post( + &mut b.l, + d(2026, 1, 15), + "Sales", + b.cash, + b.revenue, + "900.00", + ); + let p = + b.l.create_period("Q1", d(2026, 1, 1), d(2026, 3, 31)) + .unwrap(); + let close = b.l.close_period(p).unwrap().expect("revenue to close"); + let entry = b.l.get_entry(close).unwrap(); + assert!( + Policy::entry_debits(entry).unwrap() > dec("25.00"), + "past the threshold, so only its origin exempts it" + ); + assert!(exempt_source(&requirement(&b.l, close)).starts_with("a period's closing entry")); +} + +/// WB-entry-6: a schedule month's posting has the schedule as its +/// evidence. +#[test] +fn a_schedule_months_posting_has_the_schedule_for_evidence() { + let mut b = books(); + let prepaid = + b.l.add_account("1300", "Prepaid", AccountType::Asset, None, false) + .unwrap(); + post( + &mut b.l, + d(2026, 3, 1), + "Insurance paid", + prepaid, + b.cash, + "1200.00", + ); + let id = + b.l.register_schedule(NewSchedule { + description: "Insurance".into(), + kind: ScheduleKind::PrepaidExpense, + total: usd("1200.00"), + start: d(2026, 3, 1), + months: 12, + balance_account: prepaid, + pl_account: b.supplies, + convention: ScheduleConvention::MonthlyEven, + }) + .unwrap(); + let month = b.l.post_schedule_month(id, d(2026, 3, 31)).unwrap(); + assert_eq!(b.l.get_entry(month).unwrap().status(), EntryStatus::Posted); + assert!(exempt_source(&requirement(&b.l, month)).starts_with("a schedule month's posting")); +} + +/// WB-entry-6: a depreciation run's posting has the asset's schedule as +/// its evidence. +#[test] +fn a_depreciation_run_has_the_assets_schedule_for_evidence() { + let mut b = books(); + let equipment = + b.l.add_account("1500", "Equipment", AccountType::Asset, None, false) + .unwrap(); + let accum = + b.l.add_account( + "1510", + "Accumulated Depreciation", + AccountType::Asset, + None, + false, + ) + .unwrap(); + let depr = + b.l.add_account("6900", "Depreciation", AccountType::Expense, None, false) + .unwrap(); + let asset = + b.l.register_asset(NewAsset { + description: "Laptop".into(), + in_service_date: d(2026, 1, 1), + cost: usd("1200.00"), + salvage_value: usd("0.00"), + useful_life_months: 12, + cost_account: equipment, + accum_depr_account: accum, + expense_account: depr, + }) + .unwrap(); + let run = post( + &mut b.l, + d(2026, 1, 31), + "Depreciation 2026-01", + depr, + accum, + "100.00", + ); + // Before the run is recorded it is a hand entry over the threshold. + assert!(requirement(&b.l, run).is_required()); + b.l.record_depreciation_run(asset, "2026-01", run, dec("100.00")) + .unwrap(); + assert!(exempt_source(&requirement(&b.l, run)).starts_with("a depreciation run")); +} + +/// WB-entry-6: an asset's disposal and a payroll tax remittance are named +/// by the origin the ledger was told; a hand entry of the same size is +/// still the policy's. +#[test] +fn disposals_and_remittances_are_exempt_by_their_recorded_origin() { + let mut b = books(); + let disposal = post( + &mut b.l, + d(2026, 6, 1), + "Sold laptop", + b.cash, + b.revenue, + "600.00", + ); + let remit = post( + &mut b.l, + d(2026, 6, 2), + "Tax deposit", + b.supplies, + b.cash, + "800.00", + ); + let hand = post( + &mut b.l, + d(2026, 6, 3), + "Same size", + b.supplies, + b.cash, + "800.00", + ); + b.l.note_entry_origin(disposal, Origin::AssetDisposal); + b.l.note_entry_origin(remit, Origin::PayrollRemittance); + assert!(exempt_source(&requirement(&b.l, disposal)).starts_with("an asset's disposal")); + assert!(exempt_source(&requirement(&b.l, remit)).starts_with("a payroll tax remittance")); + assert!(requirement(&b.l, hand).is_required()); +} + +/// WB-entry-6: an entry a document command posts (an invoice here) and a +/// payroll run carry their own evidence. +#[test] +fn a_document_entry_and_a_payroll_run_carry_their_own_evidence() { + let mut b = books(); + let customer = b.l.add_customer("Fernhill Labs").unwrap(); + let inv = + b.l.create_invoice( + customer, + d(2026, 11, 2), + d(2026, 12, 2), + vec![DocumentLine { + description: "Consulting".into(), + amount: dec("500.00"), + class_id: None, + account: None, + quantity: None, + unit_price: None, + }], + ) + .unwrap(); + let inv_entry = b.l.get_invoice(inv).unwrap().entry_id; + assert!( + Policy::entry_debits(b.l.get_entry(inv_entry).unwrap()).unwrap() > dec("25.00"), + "over the threshold, so the document is what exempts it" + ); + assert!(exempt_source(&requirement(&b.l, inv_entry)).starts_with("a document's entry")); + + let run = + b.l.run_payroll( + d(2026, 11, 15), + vec![PayrollLine { + employee_name: "Alice".into(), + employee: None, + gross_pay: dec("1000.00"), + federal_withholding: dec("100.00"), + state_withholding: dec("40.00"), + ss_employee: dec("62.00"), + medicare_employee: dec("14.50"), + ss_employer: dec("62.00"), + medicare_employer: dec("14.50"), + other_deductions: Decimal::ZERO, + }], + b.cash, + ) + .unwrap(); + let run_entry = b.l.get_payroll_run(run).unwrap().entry_id; + assert!(exempt_source(&requirement(&b.l, run_entry)).starts_with("a payroll run")); +} + +/// WB-entry-6 closes the list: recurring drafts are NOT exempt ("Every +/// other entry, hand entries and recurring drafts included, is the +/// policy's"). +#[test] +fn a_recurring_draft_is_the_policys() { + let mut b = books(); + let rec = + b.l.register_recurring(ledger_core::NewRecurring { + description: "Rent".into(), + lines: vec![ + (b.supplies, Side::Debit, usd("900.00")), + (b.cash, Side::Credit, usd("900.00")), + ], + frequency: Frequency::Monthly, + start: d(2026, 11, 1), + end: None, + }) + .unwrap(); + let made = b.l.generate_recurring(rec, d(2026, 11, 1)).unwrap(); + assert_eq!(b.l.get_entry(made).unwrap().status(), EntryStatus::Draft); + assert!(required_reason(&requirement(&b.l, made)).contains("900.00")); +} diff --git a/crates/ledger-core/tests/ledger_edits.rs b/crates/ledger-core/tests/ledger_edits.rs new file mode 100644 index 00000000..6a8edfea --- /dev/null +++ b/crates/ledger-core/tests/ledger_edits.rs @@ -0,0 +1,473 @@ +//! The ledger's small edits and their refusals (plan P14 unit V-D2): +//! renumbering an account, a party's fields, an asset's description and +//! disposal, a vendor's W-9 flag, the fiscal year under closed periods, +//! annotations and settlements of evidence. Each is a command whose +//! refusal arms the core's own suite did not reach. +//! +//! ```text +//! GOAL: an edit the books can stand is made; one they cannot is refused +//! with its reason and changes nothing. +//! SOURCE: BS-ledger-19 (refuse rather than renumber); WB-ledger-10 (an +//! account an approval rule names is not renumbered); BS-partner-8 +//! and WB-partner-4 (no full TIN in the books' text); BS-asset-1 +//! (disposal); BS-period-2 (closed periods) with the fiscal-year +//! rule of settings.rs (IRS Form 1128); WB-ledger-15 (annotations +//! and `entry.settles`). +//! ``` + +use chrono::NaiveDate; +use ledger_core::evidence::{Annotation, AnnotationFields}; +use ledger_core::settings::{Change, Source}; +use ledger_core::{ + AccountType, Currency, Ledger, LedgerError, Money, NewAsset, PartyField, Role, Side, +}; +use rust_decimal::Decimal; +use serde_json::json; +use std::str::FromStr; + +fn d(m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(2026, m, day).unwrap() +} + +fn dec(s: &str) -> Decimal { + Decimal::from_str(s).unwrap() +} + +fn usd(s: &str) -> Money { + Money::new(dec(s), Currency::USD) +} + +fn src() -> Source { + Source { + decided_by: "Owner".into(), + decided_on: d(11, 9), + citation: None, + note: None, + } +} + +/// Run `f`, which must be refused; the ledger must be as it was. +fn refused( + l: &mut Ledger, + f: impl FnOnce(&mut Ledger) -> Result, +) -> LedgerError { + let before = l.clone(); + let e = f(l).expect_err("the command should be refused"); + assert_eq!(*l, before, "a refusal changes nothing"); + e +} + +// ---------------------------------------------------------------- renumbering + +/// BS-ledger-19, WB-ledger-10: an account is renumbered to a code that is +/// free, not blank; not while an approval rule names its code (the rule +/// would cover nothing); not onto a control role's default code when its +/// type or placeholder-ness does not fit the role. +#[test] +fn an_account_is_renumbered_only_where_the_books_can_stand_it() { + let mut l = Ledger::new(Currency::USD); + let rent = l + .add_account("6100", "Rent", AccountType::Expense, None, false) + .unwrap(); + let bank = l + .add_account("1000", "Bank", AccountType::Asset, None, false) + .unwrap(); + + assert_eq!( + l.renumber_account(99, "7000").unwrap_err(), + LedgerError::UnknownAccount(99) + ); + assert_eq!( + refused(&mut l, |l| l.renumber_account(rent, " ")), + LedgerError::EmptyAccountCode + ); + assert_eq!( + refused(&mut l, |l| l.renumber_account(rent, "1000")), + LedgerError::DuplicateAccountCode("1000".into()) + ); + // 1200 is the receivables role's default code: an expense can't take it. + assert!(matches!( + refused(&mut l, |l| l.renumber_account(rent, "1200")), + LedgerError::ControlAccountMismatch { + expected: AccountType::Asset, + found: AccountType::Expense, + .. + } + )); + + // An approval rule names 6100: the account stays put until the rule is revised. + let rule = ledger_core::conventions::NewConvention { + id: "rent-approval".into(), + kind: ledger_core::conventions::ConventionKind::ApprovalRule, + title: "Rent needs Steve".into(), + body_md: "Rent over nothing needs approval.".into(), + structured: Some(json!({"approver": "Steve", "accounts": ["6100"]})), + source: src(), + }; + let checked = l.check_convention(&rule).unwrap(); + l.apply_convention(checked, 1).unwrap(); + let e = refused(&mut l, |l| l.renumber_account(rent, "6150")); + assert!( + matches!(&e, LedgerError::InvalidConvention(m) + if m.contains("approval rule rent-approval names account 6100")), + "{e:?}" + ); + // An account the rule does not name moves freely. + l.renumber_account(bank, "1010").unwrap(); + assert_eq!(l.chart().get(bank).unwrap().code, "1010"); + assert!(l.chart().find_by_code("1000").is_none()); +} + +// ---------------------------------------------------------------- parties + +/// WB-partner-4 / BS-partner-8: a party's fields are text the books print, +/// so none holds a full TIN, a control character or more than 500 +/// characters; a name is not blank or another party's; an archived party +/// returns only if no live party took its name; emails are addresses. +#[test] +fn a_party_field_is_checked_before_it_changes() { + let mut l = Ledger::new(Currency::USD); + let dana = l.add_party("Dana Co", &[Role::Employee]).unwrap(); + let pat = l.add_party("Pat Co", &[Role::Employee]).unwrap(); + let bad = |e: LedgerError| match e { + LedgerError::InvalidParty(m) => m, + other => panic!("{other:?}"), + }; + + assert_eq!( + l.update_party(99, PartyField::Archived(true)).unwrap_err(), + LedgerError::UnknownParty(99) + ); + assert!( + bad(refused(&mut l, |l| l + .update_party(dana, PartyField::Name(" ".into())))) + .contains("needs a name") + ); + assert!( + bad(refused(&mut l, |l| l + .update_party(dana, PartyField::Name("123-45-6789".into())))) + .contains("taxpayer identification") + ); + assert!( + bad(refused(&mut l, |l| l + .update_party(dana, PartyField::Name(" pat co ".into())))) + .contains("already exists") + ); + // The name it already has is its own. + l.update_party(dana, PartyField::Name("Dana Co".into())) + .unwrap(); + l.update_party(dana, PartyField::Name("Dana & Sons".into())) + .unwrap(); + assert_eq!(l.get_party(dana).unwrap().name, "Dana & Sons"); + + for field in [ + PartyField::DisplayName(Some("EIN 12-3456789".into())), + PartyField::Website(Some("x".repeat(501))), + PartyField::Address(Some("1 Main\u{7}St".into())), + PartyField::Notes(Some("SSN 123-45-6789".into())), + PartyField::Phone(Some("123-45-6789".into())), + PartyField::Contact(Some("x".repeat(501))), + PartyField::BillingAddress(Some("123-45-6789".into())), + PartyField::ShippingAddress(Some("123-45-6789".into())), + ] { + let f = format!("{field:?}"); + assert!( + !bad(refused(&mut l, |l| l.update_party(dana, field))).is_empty(), + "{f}" + ); + } + for field in [ + PartyField::Email(Some("not an email".into())), + PartyField::BillingEmail(Some("a b@x".into())), + ] { + let m = bad(refused(&mut l, |l| l.update_party(dana, field))); + assert!(m.contains("email"), "{m}"); + } + // Good values pass and are kept; `None` clears. + l.update_party(dana, PartyField::Email(Some("dana@example.com".into()))) + .unwrap(); + l.update_party( + dana, + PartyField::BillingEmail(Some("ap@example.com".into())), + ) + .unwrap(); + l.update_party(dana, PartyField::Phone(Some("+1 555 0100".into()))) + .unwrap(); + l.update_party(dana, PartyField::Notes(None)).unwrap(); + assert_eq!( + l.get_party(dana).unwrap().email.as_deref(), + Some("dana@example.com") + ); + + // Archive Pat, take the name, and Pat cannot come back until one is renamed. + l.update_party(pat, PartyField::Archived(true)).unwrap(); + let taker = l.add_party("Pat Co", &[Role::Employee]).unwrap(); + let m = bad(refused(&mut l, |l| { + l.update_party(pat, PartyField::Archived(false)) + })); + assert!( + m.contains("another party is named \"Pat Co\"; rename one first"), + "{m}" + ); + l.update_party(taker, PartyField::Name("Pat Co II".into())) + .unwrap(); + l.update_party(pat, PartyField::Archived(false)).unwrap(); + assert!(!l.get_party(pat).unwrap().archived); +} + +/// A vendor's W-9 flag reports whether it changed. +#[test] +fn a_vendors_w9_flag_says_whether_it_moved() { + let mut l = Ledger::new(Currency::USD); + let v = l.add_vendor("Tobin Harlow Supply").unwrap(); + assert_eq!( + l.set_vendor_w9_flag(99, true).unwrap_err(), + LedgerError::UnknownVendor(99) + ); + assert!(l.set_vendor_w9_flag(v, true).unwrap()); + assert!(!l.set_vendor_w9_flag(v, true).unwrap(), "already on file"); + assert!(l.set_vendor_w9_flag(v, false).unwrap()); +} + +// ---------------------------------------------------------------- assets + +fn asset_books() -> (Ledger, u64, ledger_core::AssetId) { + let mut l = Ledger::new(Currency::USD); + let mut a = |code: &str, name: &str, t| l.add_account(code, name, t, None, false).unwrap(); + let cash = a("1000", "Bank", AccountType::Asset); + let equipment = a("1500", "Equipment", AccountType::Asset); + let accum = a("1510", "Accumulated Depreciation", AccountType::Asset); + let depr = a("6900", "Depreciation", AccountType::Expense); + let capital = a("3000", "Capital", AccountType::Equity); + let e = l.create_entry(d(1, 2), "Fund"); + l.add_line(e, cash, Side::Debit, usd("5000.00")).unwrap(); + l.add_line(e, capital, Side::Credit, usd("5000.00")) + .unwrap(); + l.post_entry(e).unwrap(); + let id = l + .register_asset(NewAsset { + description: "Laptop".into(), + in_service_date: d(1, 15), + cost: usd("1200.00"), + salvage_value: usd("0.00"), + useful_life_months: 12, + cost_account: equipment, + accum_depr_account: accum, + expense_account: depr, + }) + .unwrap(); + (l, cash, id) +} + +/// An asset's description is edited to something, never nothing, for an +/// asset that exists; the figures stay. +#[test] +fn an_assets_description_is_never_blank() { + let (mut l, _, id) = asset_books(); + assert_eq!( + l.set_asset_description(99, "x").unwrap_err(), + LedgerError::UnknownAsset(99) + ); + assert_eq!( + refused(&mut l, |l| l.set_asset_description(id, " ")), + LedgerError::EmptyAssetDescription + ); + let cost = l.get_asset(id).unwrap().cost; + l.set_asset_description(id, "MacBook Pro 16\"").unwrap(); + assert_eq!(l.get_asset(id).unwrap().description, "MacBook Pro 16\""); + assert_eq!(l.get_asset(id).unwrap().cost, cost); +} + +/// BS-asset-1: a disposal is refused for proceeds in another currency, +/// negative proceeds, an unknown asset, a day before the asset was +/// acquired, a second disposal; a disposal done is of an active asset +/// once. +#[test] +fn a_disposal_is_refused_unless_the_asset_is_active_and_the_proceeds_make_sense() { + let (mut l, _, id) = asset_books(); + let eur = Money::new(dec("100.00"), Currency::EUR); + assert!(matches!( + refused(&mut l, |l| l.dispose_asset(id, d(6, 1), eur)), + LedgerError::CurrencyMismatch { .. } + )); + assert_eq!( + refused(&mut l, |l| l.dispose_asset(99, d(6, 1), usd("1.00"))), + LedgerError::UnknownAsset(99) + ); + assert_eq!( + refused(&mut l, |l| l.dispose_asset(id, d(6, 1), usd("-1.00"))), + LedgerError::NegativeProceeds(dec("-1.00")) + ); + // The laptop went into service on 1/15: a day before that is refused. + assert!(matches!( + refused(&mut l, |l| l.dispose_asset(id, d(1, 14), usd("1.00"))), + LedgerError::DisposalBeforeAcquisition { .. } + )); + l.dispose_asset(id, d(6, 1), usd("700.00")).unwrap(); + assert_eq!( + refused(&mut l, |l| l.dispose_asset(id, d(7, 1), usd("1.00"))), + LedgerError::AssetAlreadyDisposed(id) + ); +} + +// ---------------------------------------------------------------- the fiscal year + +fn set_checked( + l: &mut Ledger, + key: &str, + value: serde_json::Value, + adopting: bool, +) -> Result<(), LedgerError> { + let made = l.check_settings_adopting( + &[Change { + key: key.into(), + value: Some(value), + }], + &src(), + adopting, + )?; + l.apply_settings(&made, &src(), 1) +} + +/// Settings rule on the fiscal year: it can't move under a closed period +/// (the year's earnings would restate; a tax year changes only with the +/// IRS's consent, Form 1128). With no period closed it moves freely; a +/// settings file being adopted for the first time (the books' settings not +/// yet journaled) brings its year in whole. +#[test] +fn the_fiscal_year_does_not_move_under_a_closed_period() { + let mut l = Ledger::new(Currency::USD); + let cash = l + .add_account("1000", "Bank", AccountType::Asset, None, false) + .unwrap(); + let sales = l + .add_account("4000", "Sales", AccountType::Revenue, None, false) + .unwrap(); + // No period closed: free. + set_checked(&mut l, "company.fiscal_year_start", json!("07-01"), false).unwrap(); + set_checked(&mut l, "company.fiscal_year_start", json!("01-01"), false).unwrap(); + + let e = l.create_entry(d(1, 10), "Sale"); + l.add_line(e, cash, Side::Debit, usd("100.00")).unwrap(); + l.add_line(e, sales, Side::Credit, usd("100.00")).unwrap(); + l.post_entry(e).unwrap(); + let p = l.create_period("Jan", d(1, 1), d(1, 31)).unwrap(); + l.close_period(p).unwrap(); + + let before = l.clone(); + let e = set_checked(&mut l, "company.fiscal_year_start", json!("07-01"), false).unwrap_err(); + assert!( + matches!(&e, LedgerError::InvalidSetting(m) + if m.contains("can't change from 01-01 to 07-01") && m.contains("Form 1128")), + "{e:?}" + ); + assert_eq!(l, before); + // The same year again is no change, and other settings move freely. + set_checked(&mut l, "company.fiscal_year_start", json!("01-01"), false).unwrap(); + set_checked(&mut l, "company.name", json!("Wanderland Labs LLC"), false).unwrap(); +} + +// ---------------------------------------------------------------- evidence on the ledger + +/// WB-ledger-15 invariants 4 and 5: annotations are checked as `Annotation:: +/// checked` says before they are kept; a second annotation of the same file +/// replaces the first; receipt numbers run from the highest annotated, so a +/// human's duplicate is not renumbered. +#[test] +fn annotations_replace_by_file_and_receipt_numbers_run_from_the_max() { + let mut l = Ledger::new(Currency::USD); + assert_eq!(l.next_receipt_number(), 1); + let ann = |id: u64, n: Option, payee: &str| Annotation { + attachment_id: id, + fields: AnnotationFields { + receipt_number: n, + payee: Some(payee.into()), + ..Default::default() + }, + note: None, + }; + let empty = Annotation { + attachment_id: 1, + fields: AnnotationFields::default(), + note: None, + }; + let before = l.clone(); + assert!(matches!( + l.annotate_attachment(empty), + Err(LedgerError::InvalidEvidence(_)) + )); + assert!(matches!( + l.annotate_attachment(ann(1, Some(0), "x")), + Err(LedgerError::InvalidEvidence(_)) + )); + assert_eq!(l, before); + + l.annotate_attachment(ann(1, Some(7), " Staples ")).unwrap(); + l.annotate_attachment(ann(2, Some(7), "Costco")).unwrap(); + assert_eq!( + l.next_receipt_number(), + 8, + "a duplicate 7 is not renumbered" + ); + assert_eq!( + l.annotation(1).unwrap().fields.payee.as_deref(), + Some("Staples") + ); + l.annotate_attachment(ann(1, Some(3), "Staples")).unwrap(); + assert_eq!( + l.annotation(1).unwrap().fields.receipt_number, + Some(3), + "replaced" + ); + assert_eq!(l.annotations().count(), 2); + l.replay_annotate_attachment(ann(3, Some(u32::MAX), "Big")) + .unwrap(); + assert_eq!(l.next_receipt_number(), u32::MAX, "saturates, never wraps"); +} + +/// WB-ledger-15 invariant 5: `entry.settles` names entries that exist, never +/// the entry itself, never one twice; "reimbursed" is derived from it +/// alone; a refusal changes nothing. +#[test] +fn a_settlement_of_entries_names_existing_distinct_entries_only() { + let mut l = Ledger::new(Currency::USD); + let cash = l + .add_account("1000", "Bank", AccountType::Asset, None, false) + .unwrap(); + let exp = l + .add_account("6000", "Meals", AccountType::Expense, None, false) + .unwrap(); + let mk = |l: &mut Ledger, day| { + let e = l.create_entry(d(3, day), "x"); + l.add_line(e, exp, Side::Debit, usd("20.00")).unwrap(); + l.add_line(e, cash, Side::Credit, usd("20.00")).unwrap(); + l.post_entry(e).unwrap(); + e + }; + let (a, b, reimbursement) = (mk(&mut l, 1), mk(&mut l, 2), mk(&mut l, 9)); + + assert_eq!( + refused(&mut l, |l| l.set_entry_settles(99, vec![a])), + LedgerError::UnknownEntry(99) + ); + assert!(matches!( + refused(&mut l, |l| l.set_entry_settles(reimbursement, vec![a, reimbursement])), + LedgerError::InvalidEvidence(m) if m.contains("doesn't settle itself") + )); + assert_eq!( + refused(&mut l, |l| l.set_entry_settles(reimbursement, vec![a, 98])), + LedgerError::UnknownEntry(98) + ); + assert!(matches!( + refused(&mut l, |l| l.set_entry_settles(reimbursement, vec![a, b, a])), + LedgerError::InvalidEvidence(m) if m.contains(&format!("entry {a} is settled twice by entry {reimbursement}")) + )); + + assert!(l.entry_settles(reimbursement).is_empty()); + assert!(!l.settles_entry(a)); + l.set_entry_settles(reimbursement, vec![a, b]).unwrap(); + assert_eq!(l.entry_settles(reimbursement), [a, b]); + assert!(l.settles_entry(a) && l.settles_entry(b) && !l.settles_entry(reimbursement)); + l.replay_set_entry_settles(reimbursement, vec![b]).unwrap(); + assert!(!l.settles_entry(a), "replaced, not added to"); +} diff --git a/crates/ledger-core/tests/replay_documents.rs b/crates/ledger-core/tests/replay_documents.rs new file mode 100644 index 00000000..640c490b --- /dev/null +++ b/crates/ledger-core/tests/replay_documents.rs @@ -0,0 +1,387 @@ +//! Replaying document events the way a journaling store does (plan P14 +//! unit V-D2). The store rebuilds a payment's entry from its own entry +//! events and then tells the ledger which of its lines is the payment, the +//! discount, the write-off; the ledger tags the line when it can and +//! leaves it untagged, never refusing, when it cannot. The core's own suite +//! reached none of this (only the store's replay tests did). +//! +//! ```text +//! GOAL: books written under earlier rules, or by a newer version's events, +//! open and tie out: a document's payment is read from the line an +//! event names, the control check lists what it could not match. +//! SOURCE: BS-entry-4 (replay takes what was journaled); BS-arap-6 +//! invariant 2 (every control line a settlement posts carries its +//! document, so the posting rows' line indices are stable); +//! BS-arap-2 (a document's figures are read from its tagged lines, +//! and the control account ties to them plus the untagged lines). +//! ``` + +use chrono::NaiveDate; +use ledger_core::{ + AccountId, AccountType, Currency, DocRef, DocStatus, DocumentLine, EntryId, Ledger, + LedgerError, Money, Side, +}; +use rust_decimal::Decimal; +use std::str::FromStr; + +fn d(m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(2026, m, day).unwrap() +} + +fn dec(s: &str) -> Decimal { + Decimal::from_str(s).unwrap() +} + +fn usd(s: &str) -> Money { + Money::new(dec(s), Currency::USD) +} + +struct Books { + l: Ledger, + bank: AccountId, + allowance: AccountId, + invoice: u64, + bill: u64, +} + +/// A 500.00 invoice and a 300.00 bill, dated March 1. +fn books() -> Books { + let mut l = Ledger::new(Currency::USD); + let bank = l + .add_account("1000", "Bank", AccountType::Asset, None, false) + .unwrap(); + let allowance = l + .add_account( + "4900", + "Sales allowances", + AccountType::Revenue, + None, + false, + ) + .unwrap(); + let customer = l.add_customer("Fernhill Labs").unwrap(); + let vendor = l.add_vendor("Tobin Harlow Supply").unwrap(); + let line = |amount: &str| { + vec![DocumentLine { + description: "Work".into(), + amount: dec(amount), + class_id: None, + account: None, + quantity: None, + unit_price: None, + }] + }; + let invoice = l + .create_invoice(customer, d(3, 1), d(3, 31), line("500.00")) + .unwrap(); + let bill = l + .create_bill(vendor, d(3, 1), d(3, 31), line("300.00")) + .unwrap(); + Books { + l, + bank, + allowance, + invoice, + bill, + } +} + +impl Books { + fn code(&self, code: &str) -> AccountId { + self.l.chart().find_by_code(code).unwrap().id + } + + /// An entry as a journal would rebuild it: lines pushed as recorded, + /// then posted by replay (no control guard, no bounds). + fn rebuilt(&mut self, on: NaiveDate, lines: &[(AccountId, Side, &str)]) -> EntryId { + let e = self.l.create_entry(on, "replayed"); + for &(account, side, amount) in lines { + self.l + .replay_add_line(e, account, side, usd(amount)) + .unwrap(); + } + self.l.replay_post_entry(e).unwrap(); + e + } + + fn unattached(&self, on: NaiveDate) -> Vec<(EntryId, usize)> { + self.l + .control_check(on) + .unwrap() + .iter() + .flat_map(|c| c.unattached.iter().map(|u| (u.entry, u.line))) + .collect() + } + + /// Every control account (receivables and payables) ties out. + fn ties(&self, on: NaiveDate) -> bool { + let checks = self.l.control_check(on).unwrap(); + !checks.is_empty() && checks.iter().all(|c| c.difference.is_zero()) + } +} + +/// BS-arap-6 invariant 2: a payment event that names the line (index 1, the +/// receivables credit) tags exactly that line. The invoice then reads 40.00 +/// paid and 460.00 owed, and the control account ties out with nothing +/// untagged. +#[test] +fn a_payment_event_tags_the_line_it_names() { + let mut b = books(); + let ar = b.code("1200"); + let e = b.rebuilt( + d(3, 10), + &[(b.bank, Side::Debit, "40.00"), (ar, Side::Credit, "40.00")], + ); + b.l.replay_invoice_payment_at(b.invoice, dec("40.00"), e, Some(1), Decimal::ZERO, None) + .unwrap(); + let st = + b.l.doc_state(DocRef::Invoice(b.invoice), d(3, 31)) + .unwrap() + .unwrap(); + assert_eq!( + (st.paid, st.outstanding, st.status), + (dec("40.00"), dec("460.00"), DocStatus::Partial) + ); + assert!(b.unattached(d(3, 31)).is_empty()); + assert!(b.ties(d(3, 31))); + assert_eq!(b.l.account_balance(ar).unwrap(), dec("460.00")); + // The payment's entry is with the invoice's customer, like the invoice's own. + let own = b.l.get_invoice(b.invoice).unwrap().entry_id; + assert!(b.l.entry_party(e).is_some()); + assert_eq!(b.l.entry_party(e), b.l.entry_party(own)); +} + +/// BS-entry-4: an event that names a line the entry cannot answer to (the +/// wrong account, the wrong amount, no such line) is not refused: the line +/// stays untagged and the control check lists it, so the human sees it and +/// the control account still ties (balance = documents + untagged). +#[test] +fn a_payment_event_that_names_a_line_that_does_not_match_leaves_it_untagged() { + let mut b = books(); + let ar = b.code("1200"); + for (named, amount) in [(Some(0), "40.00"), (Some(1), "41.00"), (Some(9), "40.00")] { + let e = b.rebuilt( + d(3, 10), + &[(b.bank, Side::Debit, "40.00"), (ar, Side::Credit, "40.00")], + ); + b.l.replay_invoice_payment_at(b.invoice, dec(amount), e, named, Decimal::ZERO, None) + .unwrap(); + assert!( + b.unattached(d(3, 31)).contains(&(e, 1)), + "{named:?} {amount}: the receivables line is listed, not tagged" + ); + assert!(b.ties(d(3, 31))); + } + // A named line already tagged is not tagged twice. + let e = b.rebuilt( + d(3, 12), + &[(b.bank, Side::Debit, "10.00"), (ar, Side::Credit, "10.00")], + ); + b.l.replay_invoice_payment_at(b.invoice, dec("10.00"), e, Some(1), Decimal::ZERO, None) + .unwrap(); + b.l.replay_invoice_payment_at(b.invoice, dec("10.00"), e, Some(1), Decimal::ZERO, None) + .unwrap(); + assert!(!b.unattached(d(3, 31)).contains(&(e, 1))); +} + +/// BS-arap-6 statement 3 and invariant 2: a payment with an early-payment discount posts a +/// payment line and a discount line against the same control account; the +/// event names both. A 500.00 invoice settled with 490.00 in cash and +/// 10.00 of discount reads paid 490.00, discounted 10.00, nothing owed. +#[test] +fn a_payment_event_names_its_payment_line_and_its_discount_line() { + let mut b = books(); + let ar = b.code("1200"); + let e = b.rebuilt( + d(3, 10), + &[ + (b.bank, Side::Debit, "490.00"), + (b.allowance, Side::Debit, "10.00"), + (ar, Side::Credit, "490.00"), + (ar, Side::Credit, "10.00"), + ], + ); + b.l.replay_invoice_payment_at(b.invoice, dec("490.00"), e, Some(2), dec("10.00"), Some(3)) + .unwrap(); + let st = + b.l.doc_state(DocRef::Invoice(b.invoice), d(3, 31)) + .unwrap() + .unwrap(); + assert_eq!( + (st.paid, st.discounted, st.outstanding, st.status), + (dec("490.00"), dec("10.00"), Decimal::ZERO, DocStatus::Paid) + ); + assert!(b.unattached(d(3, 31)).is_empty()); + assert_eq!(b.l.account_balance(ar).unwrap(), Decimal::ZERO); + // A discount named with no line to tag is just not tagged. + let e2 = b.rebuilt( + d(3, 11), + &[(b.bank, Side::Debit, "5.00"), (ar, Side::Credit, "5.00")], + ); + b.l.replay_invoice_payment_at(b.invoice, dec("5.00"), e2, Some(1), dec("2.00"), None) + .unwrap(); +} + +/// BS-arap-6: a bill's payment is the mirror (a debit to payables), and the +/// event that names the wrong side leaves the line untagged. +#[test] +fn a_bill_payment_event_is_the_mirror() { + let mut b = books(); + let ap = b.code("2000"); + let e = b.rebuilt( + d(3, 10), + &[ + (ap, Side::Debit, "100.00"), + (b.bank, Side::Credit, "100.00"), + ], + ); + b.l.replay_bill_payment_at(b.bill, dec("100.00"), e, Some(0), Decimal::ZERO, None) + .unwrap(); + let st = + b.l.doc_state(DocRef::Bill(b.bill), d(3, 31)) + .unwrap() + .unwrap(); + assert_eq!((st.paid, st.outstanding), (dec("100.00"), dec("200.00"))); + assert!(b.unattached(d(3, 31)).is_empty()); + + // Payables credited instead (the side a bill's own line takes): not a payment line. + let wrong = b.rebuilt( + d(3, 11), + &[(b.bank, Side::Debit, "50.00"), (ap, Side::Credit, "50.00")], + ); + b.l.replay_bill_payment_at(b.bill, dec("50.00"), wrong, Some(1), Decimal::ZERO, None) + .unwrap(); + assert!(b.unattached(d(3, 31)).contains(&(wrong, 1))); + + // The old form (no line named) tags the first untagged line of that amount. + let old = b.rebuilt( + d(3, 12), + &[(ap, Side::Debit, "25.00"), (b.bank, Side::Credit, "25.00")], + ); + b.l.replay_bill_payment(b.bill, dec("25.00"), old).unwrap(); + assert!(!b.unattached(d(3, 31)).contains(&(old, 0))); + + // A bill's discount line, named, is tagged as a discount. + let ap2 = b.rebuilt( + d(3, 13), + &[ + (ap, Side::Debit, "20.00"), + (ap, Side::Debit, "5.00"), + (b.bank, Side::Credit, "20.00"), + (b.allowance, Side::Credit, "5.00"), + ], + ); + b.l.replay_bill_payment_at(b.bill, dec("20.00"), ap2, Some(0), dec("5.00"), Some(1)) + .unwrap(); + let st = + b.l.doc_state(DocRef::Bill(b.bill), d(3, 31)) + .unwrap() + .unwrap(); + assert_eq!(st.discounted, dec("5.00")); +} + +/// BS-entry-4: replay of a payment or a write-off for a document the books +/// do not have is the one thing it refuses, naming it; the ledger is +/// unchanged. The write-off tags the receivables credit of the amount. +#[test] +fn replaying_for_an_unknown_document_is_the_one_refusal_and_a_write_off_tags_its_line() { + let mut b = books(); + let ar = b.code("1200"); + let e = b.rebuilt( + d(3, 10), + &[(b.bank, Side::Debit, "5.00"), (ar, Side::Credit, "5.00")], + ); + let before = b.l.clone(); + assert_eq!( + b.l.replay_invoice_payment_at(77, dec("5.00"), e, Some(1), Decimal::ZERO, None) + .unwrap_err(), + LedgerError::UnknownInvoice(77) + ); + assert_eq!( + b.l.replay_bill_payment_at(88, dec("5.00"), e, Some(0), Decimal::ZERO, None) + .unwrap_err(), + LedgerError::UnknownBill(88) + ); + assert_eq!( + b.l.replay_invoice_write_off(77, dec("5.00"), e) + .unwrap_err(), + LedgerError::UnknownInvoice(77) + ); + assert_eq!(b.l, before); + + let bad_debt = + b.l.add_account("6990", "Bad debt", AccountType::Expense, None, false) + .unwrap(); + let w = b.rebuilt( + d(3, 20), + &[ + (bad_debt, Side::Debit, "60.00"), + (ar, Side::Credit, "60.00"), + ], + ); + b.l.replay_invoice_write_off(b.invoice, dec("60.00"), w) + .unwrap(); + let st = + b.l.doc_state(DocRef::Invoice(b.invoice), d(3, 31)) + .unwrap() + .unwrap(); + assert_eq!( + (st.written_off, st.outstanding), + (dec("60.00"), dec("440.00")) + ); + assert!(!b.unattached(d(3, 31)).contains(&(w, 1))); +} + +/// BS-entry-4: a draft's state is restored on a draft that exists; one +/// naming an entry since posted is refused like the command; a foreign +/// line as journaled is restored in the base amount booked, and a foreign +/// line in the wrong base currency is refused. +#[test] +fn a_draft_state_and_a_foreign_line_replay_as_journaled() { + let mut b = books(); + let e = b.l.create_entry(d(3, 5), "Draft"); + b.l.replay_set_draft_state( + e, + ledger_core::DraftState::AwaitingEvidence { + note: "Figma invoice due".into(), + }, + ) + .unwrap(); + assert!(matches!( + b.l.get_entry(e).unwrap().draft_state(), + ledger_core::DraftState::AwaitingEvidence { note } if note == "Figma invoice due" + )); + + b.l.replay_add_line_fx( + e, + b.bank, + Side::Debit, + usd("108.35"), + Currency::EUR, + dec("100.00"), + ) + .unwrap(); + let line = &b.l.get_entry(e).unwrap().lines()[0]; + assert_eq!( + (line.amount.amount, line.foreign_amount), + (dec("108.35"), Some(dec("100.00"))) + ); + let eur = Money::new(dec("1.00"), Currency::EUR); + assert!(matches!( + b.l.replay_add_line_fx(e, b.bank, Side::Debit, eur, Currency::EUR, dec("1.00")), + Err(LedgerError::CurrencyMismatch { .. }) + )); + + // Posted: the command's refusal stands for replay. + let posted = b.rebuilt( + d(3, 6), + &[ + (b.bank, Side::Debit, "1.00"), + (b.allowance, Side::Credit, "1.00"), + ], + ); + assert!( + b.l.replay_set_draft_state(posted, ledger_core::DraftState::Building) + .is_err() + ); +} diff --git a/crates/ledger-core/tests/settings_refusals.rs b/crates/ledger-core/tests/settings_refusals.rs new file mode 100644 index 00000000..487e07b6 --- /dev/null +++ b/crates/ledger-core/tests/settings_refusals.rs @@ -0,0 +1,620 @@ +//! The settings registry refuses what its kinds refuse, and replay takes +//! what it was given (plan P14 unit V-D2; coverage found the validators of +//! `settings.rs` among its uncovered lines: members, payment methods, the +//! attestation bar, terms, the changes of a whole command). +//! +//! ```text +//! GOAL: a setting is checked by its key's kind and kept in one spelling +//! before it is journaled; a change is all or nothing; old books +//! whose values a later version would refuse still open. +//! SOURCE: WB-ledger-5 (settings are kept in the journal); WB-ledger-6 (no +//! full TIN in a setting); WB-ledger-8 (a key this version +//! doesn't know is a newer version's); BS-entry-4 (replay takes +//! any value of the right shape); settings.rs INVARIANTS 1 to 8. +//! ``` +//! +//! Each test asks the public check (`settings::check`, `Settings:: +//! check_changes`, `Ledger::check_settings`) and, for a refused command, +//! compares the settings to what they were: a refusal changes nothing. + +use chrono::NaiveDate; +use ledger_core::settings::{ + ApprovalMode, Change, Company, Member, PartyPolicy, Settings, Source, TaxCategoryPolicy, check, + display, key, shape, today_in, +}; +use ledger_core::{AccountType, Currency, Ledger, PartyField, Role, ScheduleConvention}; +use rust_decimal::Decimal; +use serde_json::{Value, json}; + +fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() +} + +fn src() -> Source { + Source { + decided_by: "Owner".into(), + decided_on: d(2026, 11, 9), + citation: None, + note: None, + } +} + +fn change(k: &str, v: Value) -> Change { + Change { + key: k.into(), + value: Some(v), + } +} + +fn checked(name: &str, v: Value) -> Result { + check(key(name).unwrap_or_else(|| panic!("no key {name}")), &v) +} + +fn refused(name: &str, v: Value) -> String { + checked(name, v.clone()).expect_err(&format!("{name} = {v} should be refused")) +} + +/// Settings holding `pairs`, checked then applied as one change. +fn settings(pairs: &[(&str, Value)]) -> Settings { + let changes: Vec = pairs.iter().map(|(k, v)| change(k, v.clone())).collect(); + let mut s = Settings::default(); + let made = s.check_changes(&changes, &src()).unwrap(); + s.apply(&made, &src(), 1).unwrap(); + s +} + +fn member(name: &str, share: &str, capital: &str) -> Value { + json!({"name": name, "share": share, "capital_account": capital}) +} + +// ---------------------------------------------------------------- members + +/// INVARIANT 1, `company.members`: each member has a name, a share and a +/// capital account; the shares sum to exactly 100%; nobody is listed twice +/// or shares a capital account; a distributions account is not another +/// member's capital account; a joint filer names a member who names them +/// back. Every refusal names the member. +#[test] +fn members_are_refused_unless_they_hold_together() { + let members = |v: Vec| refused("company.members", Value::Array(v)); + let ok = [member("Mo", "50%", "3001"), member("Tobin", "0.5", "3002")]; + + // Shape. + assert!( + members(vec![json!("Mo")]).contains("member 1: expected {name, share, capital_account}") + ); + assert!( + members(vec![ + json!({"name": "Mo", "share": "1", "capital_account": "3001", "age": 3}) + ]) + .contains("member 1: unknown field \"age\"") + ); + assert!( + members(vec![ + json!({"name": 7, "share": "1", "capital_account": "3001"}) + ]) + .contains("member 1 name: expected a string") + ); + assert!( + members(vec![ + json!({"name": " ", "share": "1", "capital_account": "3001"}) + ]) + .contains("member 1: name is blank") + ); + assert!( + members(vec![json!({"name": "Mo", "capital_account": "3001"})]) + .contains("member Mo: share is required") + ); + assert!( + members(vec![json!({"name": "Mo", "share": "1"})]) + .contains("member Mo: capital_account is required") + ); + assert!(members(vec![member("Mo", "lots", "3001")]).contains("member Mo: share")); + assert!(members(vec![member("Mo", "150%", "3001")]).contains("member Mo: share")); + assert!(members(vec![member("Mo", "0", "3001")]).contains("member Mo: share")); + + // Together. + assert!( + members(vec![member("Mo", "1", "3001"), member("Mo", "1", "3002")]) + .contains("member Mo is listed twice") + ); + assert!( + members(vec![ + member("Mo", "50%", "3001"), + member("Tobin", "50%", "3001") + ]) + .contains("members Mo and Tobin share capital account 3001") + ); + let short = members(vec![ + member("Mo", "50%", "3001"), + member("Tobin", "40%", "3002"), + ]); + assert_eq!(short, "member shares sum to 0.90, not 100%"); + let mut crossed = ok.clone(); + crossed[0]["distribution_account"] = json!("3002"); + assert!( + members(crossed.to_vec()) + .contains("Mo's distributions account 3002 is Tobin's capital account") + ); + + // Joint filers. + let mut selfish = ok.clone(); + selfish[0]["files_jointly_with"] = json!("Mo"); + assert!(members(selfish.to_vec()).contains("files_jointly_with names themself")); + let mut stranger = ok.clone(); + stranger[0]["files_jointly_with"] = json!("Pat"); + assert!(members(stranger.to_vec()).contains("files_jointly_with \"Pat\" isn't a member")); + let mut one_sided = ok.clone(); + one_sided[0]["files_jointly_with"] = json!("Tobin"); + assert!(members(one_sided.to_vec()).contains("set it on both")); + + // And both sides saying so, with a distributions account, is kept in a + // canonical spelling. + let mut both = ok.clone(); + both[0]["files_jointly_with"] = json!("Tobin"); + both[1]["files_jointly_with"] = json!("Mo"); + both[0]["distribution_account"] = json!("3901"); + let kept = checked("company.members", Value::Array(both.to_vec())).unwrap(); + assert_eq!(kept[0]["share"], json!("0.5")); + assert_eq!(kept[0]["distribution_account"], json!("3901")); + assert_eq!(kept[0]["files_jointly_with"], json!("Tobin")); + assert_eq!(kept[1]["files_jointly_with"], json!("Mo")); +} + +/// Members as party shares see them: a member whose name matches no party +/// with the member role, or whose capital account the chart lacks, is left +/// out; a distributions account the chart lacks is none; the live party of +/// a name wins over an archived one. +#[test] +fn party_members_leave_out_who_cannot_be_derived() { + let mut l = Ledger::new(Currency::USD); + let cap_mo = l + .add_account("3001", "Capital Mo", AccountType::Equity, None, false) + .unwrap(); + let cap_pat = l + .add_account("3002", "Capital Pat", AccountType::Equity, None, false) + .unwrap(); + let dist_mo = l + .add_account("3901", "Draws Mo", AccountType::Equity, None, false) + .unwrap(); + let old_mo = l.add_party("Mo", &[Role::Member]).unwrap(); + l.update_party(old_mo, PartyField::Archived(true)).unwrap(); + let mo = l.add_party("MO", &[Role::Member]).unwrap(); + let _pat = l.add_party("Pat", &[Role::Employee]).unwrap(); + let _lee = l.add_party("Lee", &[Role::Member]).unwrap(); + + let m = |name: &str, share: &str, capital: &str, dist: Option<&str>| Member { + name: name.into(), + share: share.parse().unwrap(), + capital_account: capital.into(), + distribution_account: dist.map(str::to_string), + files_jointly_with: None, + }; + let c = Company { + members: vec![ + m("mo", "0.4", "3001", Some("3901")), + m("Pat", "0.3", "3002", None), // a vendor, not a member + m("Lee", "0.2", "3999", None), // capital account not in the chart + m("Nobody", "0.1", "3002", Some("39")), // no such party + ], + ..Company::default() + }; + let got = c.party_members(&l); + assert_eq!(got.len(), 1); + assert_eq!( + got[0].party, mo, + "the live party of the name, not the archived one" + ); + assert_eq!( + (got[0].capital, got[0].distributions), + (cap_mo, Some(dist_mo)) + ); + + let c = Company { + members: vec![m("mo", "1", "3001", Some("3777"))], + ..Company::default() + }; + assert_eq!( + c.party_members(&l)[0].distributions, + None, + "a code the chart lacks is none" + ); + let _ = cap_pat; +} + +// ---------------------------------------------------------------- payment methods + +/// INVARIANTS 1, 7: `invoicing.payment_methods` is at most eight objects of +/// `{kind, label, lines, link?, qr?}`; the kind is one of the list, lines +/// are strings, a flag is true or false or the words a file writes. Every +/// refusal names the method (1-based). +#[test] +fn payment_methods_are_refused_for_shape_and_flags() { + let methods = |v: Vec| refused("invoicing.payment_methods", Value::Array(v)); + let ach = |extra: Value| { + let mut m = json!({"kind": "ach", "label": "Bank", "lines": ["Routing 021000021"]}); + for (k, v) in extra.as_object().unwrap() { + m[k] = v.clone(); + } + m + }; + let nine: Vec = (0..9).map(|_| ach(json!({}))).collect(); + assert!(methods(nine).contains("at most 8 payment methods")); + assert!(methods(vec![json!("ach")]).contains("method 1: expected {kind, label, lines}")); + assert!( + methods(vec![ach(json!({"colour": "red"}))]).contains("method 1: unknown field \"colour\"") + ); + assert!(methods(vec![ach(json!({"kind": "barter"}))]).contains("method 1: kind is one of")); + assert!(methods(vec![ach(json!({"kind": 3}))]).contains("method 1: kind is one of")); + assert!(methods(vec![ach(json!({"label": ""}))]).contains("method 1 label is blank")); + let mut no_lines = ach(json!({})); + no_lines.as_object_mut().unwrap().remove("lines"); + assert!(methods(vec![no_lines]).contains("method 1: lines is a list of strings")); + assert!(methods(vec![ach(json!({"lines": [4]}))]).contains("method 1: each line is a string")); + assert!(methods(vec![ach(json!({})), ach(json!({"link": 4}))]).contains("method 2 link")); + assert!(methods(vec![ach(json!({"link": " "}))]).contains("method 1 link is blank")); + assert!( + methods(vec![ach(json!({"qr": "yes"}))]) + .contains("method 1 qr \"yes\": expected true or false") + ); + assert!(methods(vec![ach(json!({"qr": 1}))]).contains("expected true or false")); + + // The kept form: kind lowercased, a flag as a bool whatever it was + // written as, optional parts only when present. + let kept = checked( + "invoicing.payment_methods", + json!([ + {"kind": "ACH", "label": " Bank ", "lines": ["Routing 021000021"], "qr": "true"}, + {"kind": "link", "label": "Pay online", "lines": [], "link": "https://pay.example/inv", "qr": false, "extra": null} + ]), + ); + // `extra` is an unknown field even when null. + assert!(kept.is_err()); + let kept = checked( + "invoicing.payment_methods", + json!([ + {"kind": "ACH", "label": " Bank ", "lines": ["Routing 021000021"], "qr": "true"}, + {"kind": "link", "label": "Pay online", "lines": [], "link": "https://pay.example/inv", "qr": "false"}, + {"kind": "check", "label": "Cheque", "lines": ["Payable to Wanderland"], "qr": null, "link": null} + ]), + ) + .unwrap(); + assert_eq!( + kept[0], + json!({"kind": "ach", "label": "Bank", "lines": ["Routing 021000021"], "qr": true}) + ); + assert_eq!(kept[1]["qr"], json!(false)); + assert_eq!(kept[1]["link"], json!("https://pay.example/inv")); + assert_eq!( + kept[2], + json!({"kind": "check", "label": "Cheque", "lines": ["Payable to Wanderland"]}) + ); +} + +/// INVARIANT 3 / BS-entry-4: replay takes any value of the right shape. +/// For payment methods the shape is the list of objects with a kind and a +/// label (strings), lines (a list of strings), a link string and a flag +/// that is a bool or null; for members, shares in (0, 1]; for amounts, a +/// decimal at all; for the bar, one `AttestationBar::parse` reads. +#[test] +fn replay_takes_any_value_of_the_right_shape() { + let shaped = |name: &str, v: Value| shape(key(name).unwrap(), &v); + // Payment methods. + let method = json!({"kind": "weird-kind-from-the-future", "label": "L", "lines": ["x"], "link": "u", "qr": true}); + assert!(shaped("invoicing.payment_methods", json!([method.clone()])).is_ok()); + assert!(shaped("invoicing.payment_methods", json!("nope")).is_err()); + assert!( + shaped("invoicing.payment_methods", json!([5])) + .unwrap_err() + .contains("method 1: expected an object") + ); + for missing in ["kind", "label", "lines"] { + let mut m = method.clone(); + m.as_object_mut().unwrap().remove(missing); + let e = shaped("invoicing.payment_methods", json!([m])).unwrap_err(); + assert!(e.contains(&format!("method 1: no {missing}")), "{e}"); + } + let mut bad_line = method.clone(); + bad_line["lines"] = json!([1]); + assert!(shaped("invoicing.payment_methods", json!([bad_line])).is_err()); + let mut bad_link = method.clone(); + bad_link["link"] = json!(1); + assert!(shaped("invoicing.payment_methods", json!([bad_link])).is_err()); + let mut null_link = method.clone(); + null_link["link"] = Value::Null; + null_link["qr"] = Value::Null; + assert!(shaped("invoicing.payment_methods", json!([null_link])).is_ok()); + let mut bad_qr = method.clone(); + bad_qr["qr"] = json!("yes"); + assert!( + shaped("invoicing.payment_methods", json!([bad_qr])) + .unwrap_err() + .contains("method 1 qr: expected true or false") + ); + + // Members: a share past (0, 1] could overflow the figures that + // multiply by it, so even replay refuses it. + let over = json!([{"name": "Mo", "share": "1.5", "capital_account": "3001"}]); + assert!( + shaped("company.members", over) + .unwrap_err() + .contains("outside (0, 1]") + ); + let zero = json!([{"name": "Mo", "share": "0", "capital_account": "3001"}]); + assert!(shaped("company.members", zero).is_err()); + let odd_total = json!([{"name": "Mo", "share": "0.4", "capital_account": "3001"}]); + assert!( + shaped("company.members", odd_total).is_ok(), + "the total is not replay's to refuse" + ); + assert!( + shaped("company.members", json!([{"name": "Mo"}])) + .unwrap_err() + .contains("company.members 1: bad share") + ); + assert!( + shaped( + "company.members", + json!([{"share": "1", "capital_account": "3"}]) + ) + .unwrap_err() + .contains("bad name") + ); + assert!( + shaped("company.members", json!([{"name": "Mo", "share": "1"}])) + .unwrap_err() + .contains("bad capital_account") + ); + + // Amounts, counts, the bar, code lists. + assert!( + shaped("policy.evidence.threshold", json!("-3.00")).is_ok(), + "negative is for new commands to refuse" + ); + assert!( + shaped("policy.evidence.threshold", json!("lots")) + .unwrap_err() + .contains("is not a decimal") + ); + assert!(shaped("policy.attestation_bar", json!("effort=high")).is_ok()); + assert!( + shaped("policy.attestation_bar", json!("effort=wild")) + .unwrap_err() + .starts_with("policy.attestation_bar: ") + ); + assert!(shaped("books.cash_accounts", json!(["1000", "x"])).is_ok()); + assert!(shaped("books.cash_accounts", json!([1000])).is_err()); + assert!(shaped("invoicing.unsent_days", json!(3)).is_ok()); +} + +// ---------------------------------------------------------------- other kinds + +/// INVARIANT 1 and 6: a month start is zero-padded; payment terms keep one +/// spelling; the attestation bar is kept as `describe` spells it; a time +/// zone is one the database knows. A refusal names the key. +#[test] +fn month_terms_bar_and_zone_keep_one_spelling() { + assert_eq!( + checked("company.fiscal_year_start", json!("7-1")).unwrap(), + json!("07-01") + ); + assert!(!refused("company.fiscal_year_start", json!("07-15")).is_empty()); + assert!(!refused("company.fiscal_year_start", json!("13-01")).is_empty()); + + assert_eq!( + checked("invoicing.default_terms", json!("net 30")).unwrap(), + json!("Net 30") + ); + assert!( + refused("invoicing.default_terms", json!("whenever")) + .starts_with("invoicing.default_terms: ") + ); + + assert_eq!( + checked( + "policy.attestation_bar", + json!("verifiers=3, adversarial=false") + ) + .unwrap(), + json!("effort=high verifiers=3 adversarial=false") + ); + assert!( + refused("policy.attestation_bar", json!("verifiers=0")) + .starts_with("policy.attestation_bar: ") + ); + + assert!(checked("company.timezone", json!("America/Los_Angeles")).is_ok()); + assert!(!refused("company.timezone", json!("Mars/Olympus_Mons")).is_empty()); + // "Today" in an unknown zone is the computer's, never a panic. + assert_eq!(today_in(Some("Mars/Olympus_Mons")), today_in(None)); + assert!(today_in(Some("America/Los_Angeles")) >= d(2026, 11, 9)); +} + +/// INVARIANT 8: an invoice number's prefix is 1 to 12 visible ASCII +/// characters, no spaces. +#[test] +fn an_invoice_prefix_is_short_and_visible() { + assert_eq!( + checked("invoicing.number_prefix", json!("WL-")).unwrap(), + json!("WL-") + ); + for bad in ["WANDERLAND-2026-", "A B", "É-"] { + assert!( + refused("invoicing.number_prefix", json!(bad)).contains("1 to 12 visible ASCII"), + "{bad}" + ); + } + assert!(!refused("invoicing.number_prefix", json!("")).is_empty()); +} + +// ---------------------------------------------------------------- a whole change + +/// INVARIANT 2: a change is all or nothing. A key listed twice, an unknown +/// key (a newer version's), a value of the wrong kind, a source without a +/// name, refuse the whole command; changes that change nothing are left +/// out; `null` clears a key; applying the checked changes then agrees. +#[test] +fn a_change_is_all_or_nothing_and_leaves_out_what_changes_nothing() { + let mut s = settings(&[("company.name", json!("Wanderland Labs LLC"))]); + let before = s.clone(); + + let twice = [ + change("company.name", json!("A")), + change("company.name", json!("B")), + ]; + assert_eq!( + s.check_changes(&twice, &src()).unwrap_err(), + "company.name is changed twice" + ); + let unknown = [change("company.nme", json!("A"))]; + assert!( + s.check_changes(&unknown, &src()) + .unwrap_err() + .contains("unknown setting \"company.nme\"") + ); + let half_bad = [ + change("company.name", json!("Wanderland Labs, Inc.")), + change("invoicing.first_number", json!("zero")), + ]; + assert!(s.check_changes(&half_bad, &src()).is_err()); + let mut nameless = src(); + nameless.decided_by = " ".into(); + assert!( + s.check_changes(&[change("company.name", json!("A"))], &nameless) + .is_err() + ); + assert_eq!(s, before, "a refused change changes nothing"); + + // The same name again is no change; a clear of an unset key is none. + let same = [change("company.name", json!("Wanderland Labs LLC"))]; + assert!(s.check_changes(&same, &src()).unwrap().is_empty()); + let clear_unset = [Change { + key: "company.cpa".into(), + value: None, + }]; + assert!(s.check_changes(&clear_unset, &src()).unwrap().is_empty()); + + // A real change and a clear, together: both are made, in canonical form. + let both = [ + change("company.cpa", json!(" Pat Accountant ")), + Change { + key: "company.name".into(), + value: Some(Value::Null), + }, + ]; + let made = s.check_changes(&both, &src()).unwrap(); + assert_eq!(made.len(), 2); + s.apply(&made, &src(), 2).unwrap(); + assert_eq!(s.company("USD").name, "Unnamed company"); +} + +// ---------------------------------------------------------------- the readers + +/// INVARIANT 5: unset keys mean the defaults; a set key means its word. +/// `policy.cpa_package_requires_audit` has three states (unset, warn, +/// refuse). +#[test] +fn readers_give_the_default_unset_and_the_word_when_set() { + let unset = Settings::default(); + assert_eq!(unset.schedule_convention(), ScheduleConvention::Daily); + assert_eq!(unset.parties(), PartyPolicy::Suggest); + assert_eq!(unset.require_tax_category(), TaxCategoryPolicy::Warn); + assert_eq!(unset.approval_rules(), ApprovalMode::Off); + assert_eq!( + unset.attestation_bar().describe(), + "effort=high verifiers=2 adversarial=true" + ); + assert_eq!(unset.cpa_package_requires_audit(), None); + assert_eq!(unset.backup_git_remote(), None); + assert_eq!(unset.backup_folder(), None); + assert_eq!(unset.receipt_threshold(), None); + + let set = settings(&[ + ("books.schedule_convention", json!("monthly_even")), + ("policy.parties", json!("require")), + ("policy.require_tax_category", json!("refuse")), + ("policy.approval_rules", json!("enforce")), + ( + "policy.attestation_bar", + json!("effort=max verifiers=4 adversarial=false"), + ), + ("policy.cpa_package_requires_audit", json!("refuse")), + ("backup.git_remote", json!("git@git.example:books.git")), + ("backup.folder", json!("/mnt/backup/books")), + ]); + assert_eq!(set.schedule_convention(), ScheduleConvention::MonthlyEven); + assert_eq!(set.parties(), PartyPolicy::Require); + assert_eq!(set.require_tax_category(), TaxCategoryPolicy::Refuse); + assert_eq!(set.approval_rules(), ApprovalMode::Enforce); + assert_eq!( + set.attestation_bar().describe(), + "effort=max verifiers=4 adversarial=false" + ); + assert_eq!(set.cpa_package_requires_audit(), Some(true)); + assert_eq!(set.backup_git_remote(), Some("git@git.example:books.git")); + assert_eq!(set.backup_folder(), Some("/mnt/backup/books")); + + let warn = settings(&[("policy.cpa_package_requires_audit", json!("warn"))]); + assert_eq!(warn.cpa_package_requires_audit(), Some(false)); +} + +/// The company the settings describe: a lenient fiscal year start that a +/// later version may have written, cash basis, a tax form from the +/// classification when none is set, members as written. +#[test] +fn the_company_is_read_from_the_settings() { + let s = settings(&[ + ("company.name", json!("Wanderland Labs LLC")), + ("company.fiscal_year_start", json!("07-01")), + ("books.accounting_basis", json!("cash")), + ("company.tax_classification", json!("partnership")), + ( + "company.members", + json!([member("Mo", "50%", "3001"), member("Tobin", "50%", "3002")]), + ), + ]); + let c = s.company("USD"); + assert_eq!(c.name, "Wanderland Labs LLC"); + assert_eq!(c.fiscal_year_start, (7, 1)); + assert_eq!(c.basis, "Cash"); + assert!(c.tax_form.is_some()); + assert_eq!(c.members.len(), 2); + assert_eq!(c.members[0].share, Decimal::new(5, 1)); + + // Tax form set outright wins over the classification. + let s = settings(&[ + ("company.tax_form", json!("1120")), + ("company.tax_classification", json!("partnership")), + ]); + assert_eq!( + s.company("USD").tax_form, + ledger_core::TaxForm::parse("1120") + ); +} + +/// What a setting looks like to a reader: a list of payment methods by +/// label, other lists joined, an identity number masked unless the reader +/// is a report, a plain value as it is. +#[test] +fn display_shows_what_a_reader_may_see() { + let methods = key("invoicing.payment_methods").unwrap(); + let v = json!([ + {"kind": "ach", "label": "Bank", "lines": []}, + {"kind": "link", "label": "Pay online", "lines": []} + ]); + assert_eq!(display(methods, &v, false), "Bank, Pay online"); + let codes = key("books.cash_accounts").unwrap(); + assert_eq!( + display(codes, &json!(["1000", "1010"]), false), + "1000, 1010" + ); + let ein = key("company.ein").unwrap(); + let masked = display(ein, &json!("12-3456789"), false); + assert!(!masked.contains("3456"), "{masked}"); + assert!(masked.ends_with("6789"), "{masked}"); + assert_eq!(display(ein, &json!("12-3456789"), true), "12-3456789"); + assert_eq!( + display(key("invoicing.unsent_days").unwrap(), &json!(3), false), + "3" + ); +} diff --git a/crates/ledger-core/tests/spec_bounds.rs b/crates/ledger-core/tests/spec_bounds.rs index 9bf2e97f..123d41a6 100644 --- a/crates/ledger-core/tests/spec_bounds.rs +++ b/crates/ledger-core/tests/spec_bounds.rs @@ -934,6 +934,64 @@ fn the_bound_is_the_line_limit_itself() { ); } +/// Opening old books is a real input: a draft line an earlier version +/// accepted past the line limit replays as journaled (the line is kept), +/// and the post of that draft refuses it, `AmountOutOfRange`, leaving it a +/// draft (BS-entry-4: the limit is a line's; a refusal changes nothing). +/// A foreign line is bounded by its booked base amount, the same way. (A +/// journal's foreign original is kept as written; no journal writes one +/// whose base amount is in range and itself is not, so that is not pinned +/// here.) +#[test] +fn a_replayed_line_past_the_limit_is_refused_when_it_posts() { + let mut b = books(); + let (cash, revenue) = (b.cash, b.revenue); + for fx in [false, true] { + let e = b.ledger.create_entry(d(2026, 2, 1), "old and huge"); + for amount in [Decimal::MAX, too_big()] { + let e2 = b.ledger.create_entry(d(2026, 2, 1), "old and huge"); + if fx { + b.ledger + .replay_add_line_fx( + e2, + cash, + Side::Debit, + usd(amount), + Currency::EUR, + Decimal::ONE, + ) + .unwrap(); + } else { + b.ledger + .replay_add_line(e2, cash, Side::Debit, usd(amount)) + .unwrap(); + } + b.ledger + .replay_add_line(e2, revenue, Side::Credit, usd(amount)) + .unwrap(); + let before = b.ledger.clone(); + assert_eq!( + b.ledger.replay_post_entry(e2).unwrap_err(), + LedgerError::AmountOutOfRange, + "fx: {fx}, amount {amount}" + ); + assert_eq!(b.ledger, before, "the refused post changed nothing"); + assert_eq!( + b.ledger.get_entry(e2).unwrap().status(), + ledger_core::EntryStatus::Draft + ); + } + // The same draft at the limit itself posts: the bound is the + // limit's, nothing stricter. + for (account, side) in [(cash, Side::Debit), (revenue, Side::Credit)] { + b.ledger + .replay_add_line(e, account, side, usd(MAX_LINE_AMOUNT)) + .unwrap(); + } + b.ledger.replay_post_entry(e).unwrap(); + } +} + // ------------------------------------------------- P3: assets, schedules /// The equipment accounts an asset needs, on these books. diff --git a/crates/ledger-store/src/reconcilable.rs b/crates/ledger-store/src/reconcilable.rs index e05fcf95..7ebd8484 100644 --- a/crates/ledger-store/src/reconcilable.rs +++ b/crates/ledger-store/src/reconcilable.rs @@ -5,21 +5,25 @@ //! ```text //! GOAL: the monthly close's reconciliation step can't be forgotten, and //! the digest and the viewer never disagree on what is due. -//! SOURCE: docs/parties-and-attachments.md "Reconciliations" (Needs -//! attention: an account with activity not reconciled through last -//! month's end); CONVENTION (bank and card statements close -//! monthly); AGENTS.md's monthly close. +//! SOURCE: WB-ledger-17; docs/parties-and-attachments.md "Reconciliations" +//! (Needs attention: an account with activity not reconciled +//! through last month's end); CONVENTION (bank and card statements +//! close monthly); AGENTS.md's monthly close. //! DEFINITIONS: //! cash accounts: `[books] cash_accounts`, resolved; when none are set, //! the asset accounts (not placeholders) whose names say they hold -//! cash ("cash", "bank", "checking", "savings", "money market"). +//! cash ("cash", "bank", "checking", "savings", "money market"), in +//! ascending account id; the configured ones keep the order given. //! card accounts: `ledger_core::parties::card_accounts`: the //! liabilities of the business-card payment methods the books record, //! else (none recorded) the liabilities whose names say "card" but -//! not "gift"; never a member's card or a platform's account. +//! not "gift"; never a member's card or a platform's account; in +//! ascending account id. //! INVARIANTS: //! 1. reconcilable_accounts: the cash accounts, then the card accounts, -//! then every other liability with a recorded statement, each once. +//! then every other liability with a recorded statement (in the +//! order the statements are given: the store's are by period end, +//! then file), each once. //! A card is expected before its first statement, so its first //! reconciliation is asked for; a liability named otherwise (an Amex) //! joins once its first statement is recorded. @@ -45,7 +49,9 @@ pub fn cash_accounts(ledger: &Ledger, configured: &[String]) -> Vec { .filter_map(|c| ledger.chart().find_by_code(c).map(|a| a.id)) .collect(); } - ledger + // In ascending account id, as `card_accounts` sorts: the chart's own + // iteration order is unspecified (`ChartOfAccounts::all`). + let mut found: Vec = ledger .chart() .all() .filter(|a| { @@ -55,7 +61,9 @@ pub fn cash_accounts(ledger: &Ledger, configured: &[String]) -> Vec { && CASH_WORDS.iter().any(|w| n.contains(w)) }) .map(|a| a.id) - .collect() + .collect(); + found.sort_unstable(); + found } /// The card accounts (`ledger_core::parties::card_accounts`: the diff --git a/crates/ledger-store/tests/reconcilable.rs b/crates/ledger-store/tests/reconcilable.rs new file mode 100644 index 00000000..19bc4e64 --- /dev/null +++ b/crates/ledger-store/tests/reconcilable.rs @@ -0,0 +1,565 @@ +//! Which accounts the monthly close reconciles, and when one is due +//! (`ledger_store::reconcilable`; plan P14 unit V-D2). The server's +//! `books.digest` and the viewer's Needs attention both read this module, +//! so the store's own suite checks it: coverage found it at 0% there. +//! +//! ```text +//! GOAL: the monthly close's reconciliation step can't be forgotten, and +//! the digest and the viewer never disagree on what is due. +//! SOURCE: WB-ledger-17; docs/parties-and-attachments.md "Reconciliations" +//! (Needs attention: an account with activity not reconciled +//! through last month's end); CONVENTION (bank and card statements +//! close monthly). +//! ``` +//! +//! Every test builds real books in a `Store`, records real statements and +//! completes real reconciliations through the public API, then asks the +//! module. Expected values are worked by hand from the two invariants of +//! the module's spec block. + +use chrono::NaiveDate; +use ledger_core::{AccountId, AccountType, Currency, EntryId, InstrumentKind, Money, Side}; +use ledger_store::Store; +use ledger_store::reconcilable::{ + CASH_WORDS, card_accounts, cash_accounts, last_month_end, reconcilable_accounts, + reconciled_through, reconciliation_due, +}; +use ledger_store::store::{Reconciliation, Statement}; +use rust_decimal::Decimal; +use std::path::PathBuf; +use std::str::FromStr; + +/// A test's dir, removed when the test ends, pass or panic. +struct TestDir(PathBuf); + +impl std::ops::Deref for TestDir { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn test_dir(name: &str) -> TestDir { + let dir = std::env::temp_dir().join(format!("wb-reconcilable-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + TestDir(dir) +} + +fn dec(s: &str) -> Decimal { + Decimal::from_str(s).unwrap() +} + +fn usd(s: &str) -> Money { + Money::new(dec(s), Currency::USD) +} + +fn date(y: i32, m: u32, d: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, d).unwrap() +} + +fn post( + s: &mut Store, + d: NaiveDate, + desc: &str, + dr: AccountId, + cr: AccountId, + amt: &str, +) -> EntryId { + let e = s.create_entry(d, desc).unwrap(); + s.add_line(e, dr, Side::Debit, usd(amt)).unwrap(); + s.add_line(e, cr, Side::Credit, usd(amt)).unwrap(); + s.post_entry(e).unwrap(); + e +} + +fn account(s: &mut Store, code: &str, name: &str, t: AccountType, placeholder: bool) -> AccountId { + s.add_account(code, name, t, None, placeholder).unwrap() +} + +fn file(s: &mut Store, name: &str) -> u64 { + s.file_document( + "accounting", + name, + "application/pdf", + format!("%PDF {name}").as_bytes(), + Some(name), + ) + .unwrap() + .0 +} + +fn statement( + s: &mut Store, + name: &str, + account: AccountId, + start: NaiveDate, + end: NaiveDate, + opening: &str, + closing: &str, +) -> u64 { + let attachment_id = file(s, name); + s.record_statement(Statement { + attachment_id, + account_id: account, + period_start: start, + period_end: end, + opening_balance: dec(opening), + closing_balance: dec(closing), + }) + .unwrap(); + attachment_id +} + +/// What the module reads: the live ledger, statements and reconciliations. +fn due(s: &Store, account: AccountId, today: NaiveDate) -> Option { + reconciliation_due( + s.ledger(), + &s.reconciliations(None).unwrap(), + account, + today, + ) +} + +fn names(s: &Store, ids: &[AccountId]) -> Vec { + ids.iter() + .map(|&i| s.ledger().chart().get(i).unwrap().name.clone()) + .collect() +} + +// ---------------------------------------------------------------- the cash accounts + +/// WB-ledger-17 invariant 1, cash accounts: with none configured, the +/// asset accounts (not placeholders) whose names say they hold cash. A +/// name is matched in any case; an expense called "Bank Fees", a +/// placeholder group and an asset that holds no cash are not cash. +#[test] +fn cash_accounts_are_the_assets_whose_names_say_cash() { + let dir = test_dir("cash-by-name"); + let mut s = Store::create(&dir, Currency::USD).unwrap(); + let checking = account( + &mut s, + "1000", + "Business CHECKING", + AccountType::Asset, + false, + ); + let _group = account( + &mut s, + "1050", + "Cash and Bank (group)", + AccountType::Asset, + true, + ); + let _equipment = account(&mut s, "1500", "Equipment", AccountType::Asset, false); + let _fees = account(&mut s, "6500", "Bank Fees", AccountType::Expense, false); + let _loan = account(&mut s, "2500", "Bank Loan", AccountType::Liability, false); + let savings = account(&mut s, "1010", "Savings", AccountType::Asset, false); + let petty = account(&mut s, "1020", "Petty cash box", AccountType::Asset, false); + let mm = account( + &mut s, + "1030", + "Money Market fund", + AccountType::Asset, + false, + ); + + assert_eq!(CASH_WORDS.len(), 5); + let mut found = cash_accounts(s.ledger(), &[]); + // Which accounts, not in which order: the order is the next test's. + found.sort_unstable(); + assert_eq!(found, vec![checking, savings, petty, mm]); + assert_eq!( + names(&s, &found), + [ + "Business CHECKING", + "Savings", + "Petty cash box", + "Money Market fund" + ] + ); +} + +/// WB-ledger-17 invariant 1, the order within a group. FINDING (V-D2, +/// fixed in `cash_accounts`): the cash accounts found by name came out in +/// the order the chart's `HashMap` yields them (`ChartOfAccounts::all` +/// says "order unspecified"), so `books.digest`'s `unreconciled_accounts` +/// could list them differently on two runs of the same books. They now +/// come in ascending account id, as `card_accounts` sorts. The order is the +/// id's, not the chart code's: the codes below are deliberately out of +/// creation order, so a sort by code would fail this test. +#[test] +fn cash_accounts_by_name_come_in_ascending_account_id() { + let dir = test_dir("cash-order"); + let mut s = Store::create(&dir, Currency::USD).unwrap(); + let mut expected = Vec::new(); + // (code, name) in creation order; the codes do not ascend with it. + for (code, name) in [ + ("1400", "Checking"), + ("1100", "Savings"), + ("1300", "Petty cash"), + ("1000", "Money market"), + ("1200", "Bank two"), + ("1500", "Cash three"), + ] { + expected.push(account(&mut s, code, name, AccountType::Asset, false)); + } + let mut by_code = expected.clone(); + by_code.sort_by_key(|&i| s.ledger().chart().get(i).unwrap().code.clone()); + assert_ne!( + by_code, expected, + "the codes must tell id order from code order" + ); + // Six accounts in a HashMap come out in any of 720 orders; ascending id + // is one of them, and the codes' order another. + assert_eq!(cash_accounts(s.ledger(), &[]), expected); +} + +/// DEFINITIONS, cash accounts: `[books] cash_accounts` wins when it is set, +/// resolved by code in the order given; a code the chart lacks is dropped, +/// and a cash-named account that is not configured is not cash. +#[test] +fn configured_cash_accounts_win_by_code() { + let dir = test_dir("cash-configured"); + let mut s = Store::create(&dir, Currency::USD).unwrap(); + let checking = account(&mut s, "1000", "Checking", AccountType::Asset, false); + let drawer = account(&mut s, "1100", "Till", AccountType::Asset, false); + let _savings = account(&mut s, "1010", "Savings", AccountType::Asset, false); + + let configured = vec!["1100".to_string(), "9999".to_string(), "1000".to_string()]; + assert_eq!( + cash_accounts(s.ledger(), &configured), + vec![drawer, checking] + ); + // Only an unknown code configured: none, and the names are NOT then consulted. + assert!(cash_accounts(s.ledger(), &["9999".to_string()]).is_empty()); +} + +// ---------------------------------------------------------------- the card accounts + +/// DEFINITIONS, card accounts: while the books record no business-card +/// payment method, the liabilities whose names say "card" and not "gift" +/// (ledger_core::parties::card_accounts); once one is recorded, the +/// recorded cards are the cards and the names are no longer consulted. +#[test] +fn card_accounts_follow_the_recorded_method_else_the_name() { + let dir = test_dir("cards"); + let mut s = Store::create(&dir, Currency::USD).unwrap(); + let corp_card = account( + &mut s, + "2050", + "Corporate Card", + AccountType::Liability, + false, + ); + let _gift = account( + &mut s, + "2060", + "Gift Card Liability", + AccountType::Liability, + false, + ); + let amex = account( + &mut s, + "2070", + "Amex Platinum", + AccountType::Liability, + false, + ); + let _asset_card = account(&mut s, "1900", "Card Reader", AccountType::Asset, false); + + assert_eq!(card_accounts(s.ledger()), vec![corp_card]); + + s.add_instrument( + InstrumentKind::BusinessCard, + "Amex Platinum", + Some("1234"), + None, + amex, + ) + .unwrap(); + assert_eq!( + card_accounts(s.ledger()), + vec![amex], + "the recorded method decides; the name 'Corporate Card' no longer does" + ); +} + +// ---------------------------------------------------------------- INVARIANT 1 + +/// INVARIANT 1: the accounts the books reconcile are the cash accounts, +/// then the card accounts, then every other liability with a recorded +/// statement, each once. A card is expected before its first statement; a +/// liability named otherwise joins once its first statement is recorded; an +/// asset with a statement but no cash name never does. +#[test] +fn reconcilable_accounts_are_cash_then_cards_then_liabilities_with_statements() { + let dir = test_dir("reconcilable"); + let mut s = Store::create(&dir, Currency::USD).unwrap(); + let checking = account(&mut s, "1000", "Checking", AccountType::Asset, false); + let equipment = account(&mut s, "1500", "Equipment", AccountType::Asset, false); + let card = account(&mut s, "2050", "Visa Card", AccountType::Liability, false); + let amex = account(&mut s, "2070", "Amex", AccountType::Liability, false); + let capital = account(&mut s, "3000", "Capital", AccountType::Equity, false); + post( + &mut s, + date(2026, 1, 2), + "Open", + checking, + capital, + "1000.00", + ); + post( + &mut s, + date(2026, 1, 3), + "Laptop", + equipment, + capital, + "500.00", + ); + post( + &mut s, + date(2026, 1, 4), + "Amex buy", + equipment, + amex, + "50.00", + ); + + let cash = cash_accounts(s.ledger(), &[]); + let all = |s: &Store| reconcilable_accounts(s.ledger(), &cash, &s.statements(None).unwrap()); + // No statements: cash, then the card by name; the Amex is not yet. + assert_eq!(all(&s), vec![checking, card]); + + // Statements for the Amex (a liability), the equipment (an asset) and + // the card (already expected): only the Amex joins, and the card once. + statement( + &mut s, + "amex.pdf", + amex, + date(2026, 1, 1), + date(2026, 1, 31), + "0.00", + "50.00", + ); + statement( + &mut s, + "equip.pdf", + equipment, + date(2026, 1, 1), + date(2026, 1, 31), + "0.00", + "550.00", + ); + statement( + &mut s, + "visa.pdf", + card, + date(2026, 1, 1), + date(2026, 1, 31), + "0.00", + "0.00", + ); + assert_eq!(all(&s), vec![checking, card, amex]); + + // The cash list comes first even when a statement is for a cash account. + statement( + &mut s, + "chk.pdf", + checking, + date(2026, 1, 1), + date(2026, 1, 31), + "0.00", + "1000.00", + ); + assert_eq!(all(&s), vec![checking, card, amex]); +} + +// ---------------------------------------------------------------- INVARIANT 2 + +/// The last day of the month before today's, across a leap year and a +/// year boundary: the due date the digest and the viewer both print. +#[test] +fn last_month_end_is_the_last_day_of_the_month_before() { + assert_eq!(last_month_end(date(2026, 3, 15)), date(2026, 2, 28)); + assert_eq!(last_month_end(date(2024, 3, 1)), date(2024, 2, 29)); + assert_eq!(last_month_end(date(2026, 1, 1)), date(2025, 12, 31)); + assert_eq!(last_month_end(date(2026, 1, 31)), date(2025, 12, 31)); + assert_eq!(last_month_end(date(2026, 12, 31)), date(2026, 11, 30)); +} + +/// INVARIANT 2, the newest reconciliation not voided: the date an account +/// is reconciled through ignores voided ones and other accounts', and is +/// None when there is none. +#[test] +fn reconciled_through_is_the_newest_standing_reconciliation() { + let rec = |id, account_id, d: NaiveDate, voided: Option<&str>| Reconciliation { + id, + account_id, + statement_date: d, + statement_balance: Decimal::ZERO, + attachment_id: id, + cleared: vec![], + voided: voided.map(str::to_string), + }; + let recs = vec![ + rec(1, 7, date(2026, 1, 31), None), + rec(2, 7, date(2026, 2, 28), Some("wrong statement")), + rec(3, 8, date(2026, 3, 31), None), + rec(4, 7, date(2025, 12, 31), None), + ]; + assert_eq!(reconciled_through(&recs, 7), Some(date(2026, 1, 31))); + assert_eq!(reconciled_through(&recs, 8), Some(date(2026, 3, 31))); + assert_eq!(reconciled_through(&recs, 9), None); + assert_eq!(reconciled_through(&[], 7), None); +} + +/// INVARIANT 2 end to end: an account is due iff it has a posted line dated +/// on or before last month's end and no standing reconciliation reaches +/// it. Worked by hand, with today = 2026-03-10 (so through = 2026-02-28): +/// +/// - checking has January activity and nothing reconciled: due through Feb 28; +/// - reconciled through Jan 31 (statement 0.00 -> 380.00): Jan 31 < Feb 28, still due; +/// - reconciled through Feb 28 (380.00 -> 350.00 after the 30.00 February +/// purchase): not due; +/// - voiding that reconciliation makes it due again. +#[test] +fn an_account_is_due_until_a_reconciliation_reaches_last_months_end() { + let dir = test_dir("due"); + let mut s = Store::create(&dir, Currency::USD).unwrap(); + let checking = account(&mut s, "1000", "Checking", AccountType::Asset, false); + let capital = account(&mut s, "3000", "Capital", AccountType::Equity, false); + let software = account(&mut s, "6000", "Software", AccountType::Expense, false); + let e1 = post( + &mut s, + date(2026, 1, 1), + "Opening", + checking, + capital, + "500.00", + ); + let e2 = post( + &mut s, + date(2026, 1, 15), + "Tool", + software, + checking, + "120.00", + ); + let e3 = post( + &mut s, + date(2026, 2, 3), + "Tool 2", + software, + checking, + "30.00", + ); + let today = date(2026, 3, 10); + let through = date(2026, 2, 28); + + assert_eq!(due(&s, checking, today), Some(through)); + + s.mark_cleared(e1, 0, true).unwrap(); + s.mark_cleared(e2, 1, true).unwrap(); + let jan = statement( + &mut s, + "jan.pdf", + checking, + date(2026, 1, 1), + date(2026, 1, 31), + "0.00", + "380.00", + ); + let rec_jan = s.complete_reconciliation(jan).unwrap(); + assert_eq!(rec_jan.statement_date, date(2026, 1, 31)); + assert_eq!( + due(&s, checking, today), + Some(through), + "reconciled through Jan 31 is short of Feb 28" + ); + + s.mark_cleared(e3, 1, true).unwrap(); + let feb = statement( + &mut s, + "feb.pdf", + checking, + date(2026, 2, 1), + date(2026, 2, 28), + "380.00", + "350.00", + ); + let rec_feb = s.complete_reconciliation(feb).unwrap(); + assert_eq!( + due(&s, checking, today), + None, + "reconciled through last month's end" + ); + // The same books asked in April are due for March again. + assert_eq!(due(&s, checking, date(2026, 4, 2)), Some(date(2026, 3, 31))); + // A reconciliation dated after last month's end also satisfies it. + assert_eq!(due(&s, checking, date(2026, 2, 10)), None); + + s.void_reconciliation(rec_feb.id, "statement was the wrong month") + .unwrap(); + assert_eq!( + due(&s, checking, today), + Some(through), + "a voided reconciliation reaches nothing; January's still stands but is short" + ); + assert_eq!( + reconciled_through(&s.reconciliations(None).unwrap(), checking), + Some(date(2026, 1, 31)) + ); +} + +/// INVARIANT 2, "None otherwise (including activity only this month)": an +/// account whose only posted line is dated this month is not due; one +/// dated exactly last month's last day is; a draft line counts for +/// nothing; an account with no lines at all is not due. +#[test] +fn only_posted_activity_through_last_months_end_makes_an_account_due() { + let dir = test_dir("activity"); + let mut s = Store::create(&dir, Currency::USD).unwrap(); + let a_this_month = account(&mut s, "1000", "Checking", AccountType::Asset, false); + let a_edge = account(&mut s, "1010", "Savings", AccountType::Asset, false); + let a_draft = account(&mut s, "1020", "Money Market", AccountType::Asset, false); + let a_idle = account(&mut s, "1030", "Cash Box", AccountType::Asset, false); + let capital = account(&mut s, "3000", "Capital", AccountType::Equity, false); + let today = date(2026, 3, 10); + + post( + &mut s, + date(2026, 3, 1), + "March only", + a_this_month, + capital, + "10.00", + ); + post( + &mut s, + date(2026, 2, 28), + "Last day of Feb", + a_edge, + capital, + "10.00", + ); + let draft = s.create_entry(date(2026, 1, 5), "Not posted").unwrap(); + s.add_line(draft, a_draft, Side::Debit, usd("10.00")) + .unwrap(); + s.add_line(draft, capital, Side::Credit, usd("10.00")) + .unwrap(); + + assert_eq!(due(&s, a_this_month, today), None); + assert_eq!(due(&s, a_edge, today), Some(date(2026, 2, 28))); + assert_eq!(due(&s, a_draft, today), None); + assert_eq!(due(&s, a_idle, today), None); + // Asked before March began, the edge account has no February behind it + // yet: its last day is not on or before January's end. + assert_eq!(due(&s, a_edge, date(2026, 2, 5)), None); +} diff --git a/docs/coverage-floor.md b/docs/coverage-floor.md index de882316..181eb75d 100644 --- a/docs/coverage-floor.md +++ b/docs/coverage-floor.md @@ -31,14 +31,44 @@ report drift down unnoticed. measurement movement; more means a test stopped reaching what it used to. -**Floor: `ledger-core` 90.01% lines, `ledger-store` 91.71% lines** (2026-11-08: the first measurement, from the full `just coverage` run; `ledger-core` 16,839 of 18,708 lines, `ledger-store` 14,255 of 15,543; 256-case properties everywhere, no special shard settings. The store measured 91.98% on an earlier run the same day; properties choose random cases, so a few tenths move between runs, which the 0.5 pp tolerance absorbs. The floor records the lower run.) +**Floor: `ledger-core` 95.49% lines, `ledger-store` 92.58% lines** (2026-11-09: `ledger-core` from the full `just coverage` run on V-D2's merged, reviewed tree, 18,422 of 19,292 lines; `ledger-store` stays at 92.58%, its V-D2 measurement, since that run measured 92.45% (14,359 of 15,531, the same lines as before: main's store changes were comments and the fixes added no store code), a few tenths of run-to-run movement in the store's property and process tests that the 0.5 pp tolerance absorbs. A floor only rises: a run inside the tolerance is recorded in the table below, never written over the floor. 256-case properties everywhere, no special shard settings. The first floors, 90.01% and 91.71% (2026-11-08), are in the history below.) | Crate | Lines | Regions | Branches | Lines (covered / total) | Measured | |---|---|---|---|---|---| -| `ledger-core` | 90.01% | 88.86% | 82.65% | 16,839 / 18,708 | 2026-11-08 | -| `ledger-store` | 91.71% | 85.27% | 80.73% | 14,255 / 15,543 | 2026-11-08 | +| `ledger-core` | 95.49% | 93.09% | 88.98% | 18,422 / 19,292 | 2026-11-09 (V-D2, reviewed) | +| `ledger-store` | 92.45% | 85.86% | 81.72% | 14,359 / 15,531 | 2026-11-09 (V-D2, reviewed) | +| `ledger-core` | 95.45% | 93.06% | 88.90% | 18,391 / 19,267 | 2026-11-09 (V-D2, before review) | +| `ledger-store` | 92.58% | 85.98% | 81.72% | 14,379 / 15,531 | 2026-11-09 (V-D2, before review) | +| `ledger-core` | 90.01% | 88.86% | 82.65% | 16,839 / 18,708 | 2026-11-08 (first) | +| `ledger-store` | 91.71% | 85.27% | 80.73% | 14,255 / 15,543 | 2026-11-08 (first) | -## First measurement: the fifteen files with the most uncovered lines +## Second measurement: V-D2, tests where coverage was thinnest (2026-11-09) + +The first measurement named its holes; V-D2 wrote the tests that reach +them, each encoding the rule the code serves (the rule ids are in the +commits and in `docs/testing.md`, "V-D2"). The run at the start of the +unit, on the same code and tools, is the "before": the core had drifted to +89.79% (the code had grown since 2026-11-08), the store to 92.09%. + +| File | Lines before | Lines after | Branches before | Branches after | +|---|---|---|---|---| +| `ledger-core/src/evidence.rs` | 33.85% (129 of 195 missed) | 100.00% (0 missed) | 8.93% | 96.43% | +| `ledger-core/src/conventions.rs` | 77.76% (145 of 652 missed) | 97.24% (18 missed) | 78.21% | 96.15% | +| `ledger-core/src/audit.rs` | 80.33% (94 of 478 missed) | 94.14% (28 missed) | 61.36% | 84.09% | +| `ledger-core/src/settings.rs` | 91.05% (117 of 1,307 missed) | 98.16% (24 missed) | 81.25% | 89.84% | +| `ledger-core/src/ledger.rs` | 86.00% (862 of 6,158 missed) | 96.87% (193 missed) | 80.38% | 91.32% | +| `ledger-store/src/reconcilable.rs` | 0.00% (76 of 76 missed) | 100.00% (0 of 78 missed) | 0.00% | 100.00% | +| `ledger-core` total | 89.79% (17,299 of 19,267) | 95.45% (18,391 of 19,267) | 82.26% | 88.90% | +| `ledger-store` total | 92.09% (14,301 of 15,529) | 92.58% (14,379 of 15,531) | 80.92% | 81.72% | + +What is left in the core is mostly arms no posted book reaches: a sum past +exact arithmetic in the audit's equation, control and register checks (a +journal line is capped at 1e15, so no realistic sum overflows `Decimal`), +and the defensive arms of `ledger.rs` (about 190 lines of scattered +replay-only and overflow refusals). `reconcilable.rs` gained two lines +because the fix to the digest's account order (its own commit) added them. + +## First measurement: the fifteen files with the most uncovered lines (2026-11-08) | File | Lines | Regions | Branches | Uncovered lines | |---|---|---|---|---| diff --git a/docs/spec/claims/entry.md b/docs/spec/claims/entry.md index c1556792..148ad484 100644 --- a/docs/spec/claims/entry.md +++ b/docs/spec/claims/entry.md @@ -239,7 +239,14 @@ of the exemption). The store's gate, the server's previews and digest, the viewer and Needs attention all call it; none decides on its own. **Enforced:** `ledger_core::evidence::{requirement, Requirement}`, `Store::post_entry_checked`. **Checked:** `ledger-cli` `tests/drafts.rs` -(`gui_and_server_gate_agree`). +(`gui_and_server_gate_agree`); `ledger-core` `tests/evidence_gate.rs` +(`a_hand_entry_is_required_above_the_threshold_with_its_reason`, +`a_required_account_always_needs_a_receipt`, +`exempt_accounts_exempt_only_whole_entries`, +`the_threshold_is_strict_and_the_exemption_needs_every_line`, +`a_split_purchase_is_one_purchase`, +`only_the_same_day_description_and_accounts_make_a_split_group`, +`debits_past_exact_arithmetic_are_refused_by_the_sum_and_past_the_threshold_for_the_gate`). **WB-entry-6** Exempt by origin, each with its source: a period's closing entry (derived from the books), a schedule month's or a depreciation @@ -254,7 +261,14 @@ account, or as part of a split group; exempt only when every line is on an exempt account. **Enforced:** `ledger_core::evidence::requirement`. **Checked:** `ledger-cli` `tests/drafts.rs` (`a_reversal_needs_no_receipt_of_its_own`, -`a_draft_waits_for_its_receipt_and_posts`). +`a_draft_waits_for_its_receipt_and_posts`); `ledger-core` +`tests/evidence_gate.rs` (`a_reversal_of_a_large_entry_needs_no_receipt_of_its_own`, +`a_closing_entry_is_derived_so_it_needs_no_receipt`, +`a_schedule_months_posting_has_the_schedule_for_evidence`, +`a_depreciation_run_has_the_assets_schedule_for_evidence`, +`disposals_and_remittances_are_exempt_by_their_recorded_origin`, +`a_document_entry_and_a_payroll_run_carry_their_own_evidence`, +`a_recurring_draft_is_the_policys`). **WB-entry-7** A draft has a state: `building` (the default) or `awaiting_evidence` with a note. A state is a note on the draft; it moves diff --git a/docs/spec/claims/ledger.md b/docs/spec/claims/ledger.md index cffad93e..455edae3 100644 --- a/docs/spec/claims/ledger.md +++ b/docs/spec/claims/ledger.md @@ -256,7 +256,7 @@ checked to change no figure or entry; **WB-ledger-10** Approval rules block anything only when the company enforces them (`policy.approval_rules = enforce`; off by default). Then a draft a rule covers posts only once its approver approved it as it stands (its fingerprint: date, description, every line and class), and an operation that would post such an entry at once (an invoice, a bill, a payment, payroll, a remittance, a disposal) is refused: it is drafted instead. Reversals, closes, depreciation and amortization follow from entries already posted and are exempt. A rule names accounts that take postings, and an account a rule names can't be renumbered until the rule is revised. *Enforced:* `Ledger::approvals_missing`; `Store::post_entry` and `approval_gate` (`ApprovalRequired`, `ApprovalNeedsDraft`), `check_renumber_account`; `ledger-mcp` `books.post_entry` (`approval_required`). -*Checked:* `ledger-store` `tests/settings.rs` (`approval_rules_off_by_default`, `approvals_cover_every_post`). +*Checked:* `ledger-store` `tests/settings.rs` (`approval_rules_off_by_default`, `approvals_cover_every_post`); `ledger-core` `tests/conventions_refusals.rs` (`approvals_are_missing_only_under_enforcement_and_fail_closed`, `the_fingerprint_notices_parties_shares_and_reasons`, `an_approval_is_refused_for_a_posted_or_unknown_entry_and_bad_text`, `an_approval_rule_needs_an_approver_and_a_limit`), `tests/ledger_edits.rs` (`an_account_is_renumbered_only_where_the_books_can_stand_it`). ## B-31 Renaming an account changes its label, nothing else @@ -417,7 +417,13 @@ withdraw_attachment_duplicate}` and `Store::attach`'s dedup; feature `reimbursed_is_derived_from_settles_only`); `ledger-cli` `tests/evidence.rs` (`get_receipt_default_has_text_and_no_bytes`, `page_image_is_a_png_of_the_page`, -`consolidation_never_removes_an_entrys_only_evidence`); fuzz targets +`consolidation_never_removes_an_entrys_only_evidence`); `ledger-core` +`tests/evidence_gate.rs` (`annotation_fields_are_trimmed_and_blank_ones_dropped`, +`an_annotation_field_alone_is_a_record`, +`an_annotation_refuses_a_zero_number_a_negative_amount_and_a_date_off_the_calendar`, +`an_annotation_needs_a_field_or_a_note`), `tests/ledger_edits.rs` +(`annotations_replace_by_file_and_receipt_numbers_run_from_the_max`, +`a_settlement_of_entries_names_existing_distinct_entries_only`); fuzz targets `fuzz_extract_pdf` and `fuzz_extract_xlsx`. ## B-45 An audit is deterministic over the books; an attestation is a claim by a named client @@ -485,6 +491,14 @@ INVARIANTS: which is journaled as a decision. 7. Nothing here moves a figure. Every refusal leaves the journal unchanged; every write waits for the feature `audits`. + 8. `close_split_drifts` holds a members close to BS-partner-1 + statement 5: once the count has had a close under the cumulative + rule that posted an entry (its true-up, statement 6; the close + journals its rule and whether it posted), a member's running total + MUST be under one minor unit from its exact share, so a drift of a + unit or more is a finding. Before that true-up the count may still + carry the rounding of closes made under the older rules, so only a + drift beyond one unit is. Closes under the older rules are not read. SCENARIOS: 1. The same books audited twice through one day: one run, one workpaper; the second call files and journals nothing. @@ -502,7 +516,8 @@ SCENARIOS: ``` *Enforced:* `ledger_core::audit` (`statements`, `Finding`, `CODES`, -`AttestationBar::counts`, `Scope`, `Method`), `ledger_store::audit` +`AttestationBar::counts`, `Scope`, `Method`, `check_split`; +`Ledger::member_close_trued_up`), `ledger_store::audit` (`Store::figure_head`, `integrity_findings`, `record_audit_run`, `attest_receipt`, `review_entry`, `attest_period`, `run_for_period`, `attestations`, `PROGRAM_VERSION`), `ledger_import::workpaper_pdf`, @@ -510,10 +525,67 @@ ledger-mcp `tools/audit.rs` and the gate in `books.export_cpa_package`, journal feature `audits`. *Checked:* `ledger-core` `tests/audit.rs` (`audit_detects_each_seeded_defect`, `below_bar_not_counted`, -`amount_mismatch_never_counts`); `ledger-store` `tests/audit.rs` +`amount_mismatch_never_counts`), `tests/audit_branches.rs` +(`the_cash_flow_check_says_what_it_found`, +`control_accounts_report_differences_unattached_lines_and_overpaid_documents`, +`a_close_split_drifts_by_the_regime_it_was_made_under`, +`a_count_is_trued_up_by_the_first_cumulative_close_that_posts`, +`a_reversal_without_its_own_receipt_is_info_and_only_when_the_policy_would_cover_it`, +`the_bar_setting_parses_what_it_names_and_refuses_the_rest`, +`the_bar_counts_at_its_edges_and_only_asks_for_what_it_sets`); `ledger-store` `tests/audit.rs` (`audit_writes_wait_for_audits`, `a_run_is_idempotent_on_the_figure_head`, `stale_head_period_attestation_refused`, `integrity_detects_each_seeded_defect`, `books_the_version_before_p8_wrote_wait_for_the_upgrade`); `ledger-import` `workpaper_pdf_is_deterministic`; `ledger-cli` `tests/audit.rs` (`audit_is_deterministic`, `cpa_package_refuses_without_a_counted_audit_unless_a_reason_is_given`, `audits_wait_for_the_upgrade`). + +## Reconciliations: which accounts the monthly close reconciles, and when each is due + +**bookspec:** none + +**Claims:** yes (wholly a product rule: no bookspec rule states it) + +**Pick:** CONVENTION, `docs/parties-and-attachments.md` "Reconciliations" (Needs attention: an account with activity not reconciled through last month's end; bank and card statements close monthly). No authority states it, so it is the product's own. + +### Product rules + +**WB-ledger-17** The accounts the monthly close reconciles, and when each is due, are one rule (`ledger_store::reconcilable`), read by the digest's `unreconciled_accounts` and the viewer's Needs attention alike. + +```text +GOAL: the monthly close's reconciliation step can't be forgotten, and + the digest and the viewer never disagree on what is due. +SOURCE: CONVENTION (bank and card statements close monthly); + docs/parties-and-attachments.md "Reconciliations". +INVARIANTS: + 1. The accounts reconciled are the cash accounts, then the card + accounts, then every other liability with a recorded statement, each + once. The cash accounts are `books.cash_accounts` resolved by code, in + the order given (a code the chart lacks is dropped, and the names are + not then consulted); when none is set, the asset accounts that are + not placeholders and whose names say cash ("cash", "bank", + "checking", "savings", "money market"), in ascending account id. The + card accounts are `ledger_core::parties::card_accounts`, in ascending + account id. The liabilities with a statement follow in the order the + statements are given (the store's: period end, then file). A card is + expected before its first statement; a liability not named a card + joins once its first statement is recorded; an asset with a statement + and no cash name never does. + 2. An account is due through the last day of the month before today's + when it has a posted line dated on or before that day and no + reconciliation not voided reaches it (is dated on or after that + day); otherwise it is not due. A draft line, activity only this + month, and an account with no lines are not due; a voided + reconciliation reaches nothing. +SCENARIOS: + 1. Cash named "Checking" and a card named "Visa Card", an "Amex" with + no statement: the checking and the card are reconciled, the Amex is + not; once the Amex has a statement it joins, after the card. + 2. Today is March 10th, the checking has January activity and a + reconciliation through January 31st: it is due through February + 28th; one through February 28th clears it; voiding that one makes it + due again. +``` + +**Enforced:** `reconcilable_accounts`, `cash_accounts`, `card_accounts`, `last_month_end`, `reconciled_through`, `reconciliation_due` (`ledger_store::reconcilable`). +**Checked:** `ledger-store` `tests/reconcilable.rs` (`cash_accounts_are_the_assets_whose_names_say_cash`, `cash_accounts_by_name_come_in_ascending_account_id`, `configured_cash_accounts_win_by_code`, `card_accounts_follow_the_recorded_method_else_the_name`, `reconcilable_accounts_are_cash_then_cards_then_liabilities_with_statements`, `last_month_end_is_the_last_day_of_the_month_before`, `reconciled_through_is_the_newest_standing_reconciliation`, `an_account_is_due_until_a_reconciliation_reaches_last_months_end`, `only_posted_activity_through_last_months_end_makes_an_account_due`). diff --git a/docs/testing.md b/docs/testing.md index 9613fc4f..4455356c 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -4207,6 +4207,54 @@ open/closed ids (a remembered size must not leak between them); equality gates, the `agent_later` flag. *(Consolidated, with the other units' targets, in "P12: the checklists" at the end of this file.)* +## V-D2: tests where coverage was thinnest (2026-11-09) + +The V-D report (`docs/coverage-floor.md`) named the holes; V-D2 wrote 94 +tests that reach them. Each goes through the public API, names the rule it +encodes in its doc comment (a `BS-` id, or a `WB-` product rule), and where +it drives a command shows that a refusal changes nothing (the whole `Ledger` +equals its clone; `Ledger: PartialEq`) and a success moves the numbers its +rule says. + +| Area | File (tests) | Rules it encodes | +|---|---|---| +| `ledger-store` `reconcilable.rs` (0% -> 100%) | `ledger-store/tests/reconcilable.rs` (9) | the module's own INVARIANTS 1 and 2 and its SOURCE (`docs/parties-and-attachments.md` "Reconciliations"; no `BS-`/`WB-` id covers it yet, see the finding below): which accounts are reconciled (cash by name or by configured code, cards by the recorded method else the name, liabilities with a statement), and when one is due (a posted line through last month's end, no standing reconciliation reaching it; a voided one reaches nothing) | +| `evidence.rs` (34% -> 100%, branches 9% -> 96%) | `ledger-core/tests/evidence_gate.rs` (19) | BS-entry-5, WB-entry-5, WB-entry-6 (strictly above the threshold, required and exempt accounts, the split-group rule, each exempt origin with its source, debits past exact arithmetic never a panic); WB-ledger-15 (an annotation's closed list of fields, trimmed, a positive number, a non-negative amount, a date in the calendar) | +| `conventions.rs` (78% -> 97%) | `ledger-core/tests/conventions_refusals.rs` (18) | WB-ledger-5, -6, -9, -10 and the module's INVARIANTS 1 to 6: slug ids and no TIN, revisions and retirement, template shares summing to exactly 1, approval rules and the fingerprint, decisions and open items in order, source corrections, drafting from a template | +| `settings.rs` (91% -> 98%) | `ledger-core/tests/settings_refusals.rs` (10) | WB-ledger-5, -6, -8, BS-entry-4 and the module's INVARIANTS 1 to 8: members, payment methods, replay's shapes, a change all or nothing, defaults | +| `audit.rs` (80% -> 94%, branches 61% -> 84%) | `ledger-core/tests/audit_branches.rs` (14) | BS-ledger-13 / WB-ledger-16, BS-partner-1, BS-entry-5, D-9: severities and subjects, the cash flow and control checks, a split drifts only past a minor unit, evidence only through the date, the bar's parse and edges | +| `ledger.rs` command steps (86% -> 97%) | `ledger-core/tests/document_commands.rs` (10), `ledger_edits.rs` (8), `replay_documents.rs` (6) | BS-arap-2, -5, -6 (send, settle, write-off, aging), BS-entry-4 (replay never refuses a line it cannot match), BS-ledger-19 / WB-ledger-10 (renumbering), BS-partner-8 / WB-partner-4 (party text), BS-asset-1 (disposal), the fiscal-year rule (Form 1128), WB-ledger-15 (annotations, `entry.settles`) | + +Coverage, from `just coverage` before and after (`docs/coverage-floor.md` +has the per-file table): `ledger-core` 89.79% -> 95.49% lines, 82.26% -> +88.98% branches; `ledger-store` 92.09% -> 92.45% lines. The floors are +those numbers (the store's is 0.13 pp under the first run's: see the coverage-floor note). + +**Finding (fixed in its own commit).** `reconcilable::cash_accounts` returned +the name-matched cash accounts in `HashMap` order (`ChartOfAccounts::all` is +"order unspecified"), so `books.digest`'s `unreconciled_accounts` could list +the same books' accounts in a different order from run to run; `card_accounts` +beside it sorts by account id. The test that found it +(`cash_accounts_by_name_come_in_ascending_account_id`) was committed `#[ignore]`d with the +finding in its reason; the fix sorts the list and is the commit after the +tests, so it can be dropped without touching them. + +**Not reached, by design.** The "cannot be made" arms of the audit's +equation, control and register checks need a sum past `Decimal`'s range; a +journal line is capped at 1e15 (`kernel::MAX_LINE_AMOUNT`), so no posted +book reaches them, and a draft is not read by those statements. The same +holds for most of the roughly 190 lines left in `ledger.rs`: replay-only and +overflow refusals. + +**For P12 (mutation targets).** `evidence::Policy::reason_for` (the strict +`<=` and the exempt-all test), `Policy::split_group` (the three equalities +that make a group, the reversal skip, the `total > threshold` end), +`conventions::check_template` (the share bounds and the sum), `check_rule` +(the amount bound), `Ledger::settlement_lines` (each refusal's order), +`Ledger::mark_sent_steps` (the day of the send against a later void), +`audit::check_split` (`> unit`, not `>=`), `AttestationBar::parse`'s range +(1..=64), `reconcilable::reconciliation_due` (`<=` through, `<` reconciled). + ## P12: the checklists The **For P12** paragraphs above (kept where they were written, with their