From 688ab951d39e6e87479a35354ee6d8ed06af6b81 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 10:49:44 -0700 Subject: [PATCH] test(core): the adapter runs schedules that take the pick, settings, role accounts, tax summaries and an export's line ending A schedule may now leave its convention to the engine, so an example can show BS-prepaid-2's pick: the adapter registers such a schedule by the day, wanderbooks' method (D-11, D-37), and the equal-months examples are skipped as the runner skips another engine's option. The yen examples run through `Store::register_schedule`, whose `schedule_minor_unit` feature rounds a monthly-even month to the currency's minor unit (D-72, K-U5); `answer_schedule_plan` now prints each month as the plan holds it, so a yen month is 333 and not 333.00. The new events and queries go through the engine's own commands, never a reimplementation: `set_setting` is `Store::change_settings` with its `Source` (who decided and when), the setting query reads `Ledger::settings`, the role account query reads `Ledger::role_account`, the tax summary is `tax::tax_summary`'s once-rounded lines, and the line ending is the `ledger_import` file's own CR LF. The BS-format-9 example uses an entry posted as an earlier version wrote it, so its memo is the example's and no document's wording stands between the file and the check. The skip count moves from 16 to 22, the six new unpicked-option examples (the cent rule, the file's place, one fiscal year, closes written, the platform line ending and per-account rounding). Co-Authored-By: DeepSeek V4.1 Flash --- crates/ledger-core/tests/bookspec/books.rs | 13 +- crates/ledger-core/tests/bookspec/check.rs | 5 + crates/ledger-core/tests/bookspec/events.rs | 19 ++- crates/ledger-core/tests/bookspec/examples.rs | 26 ++-- crates/ledger-core/tests/bookspec/main.rs | 7 +- .../tests/bookspec/queries/assets.rs | 8 +- .../tests/bookspec/queries/book.rs | 132 ++++++++++++++++++ .../tests/bookspec/queries/formats.rs | 32 ++++- .../ledger-core/tests/bookspec/queries/mod.rs | 6 +- 9 files changed, 227 insertions(+), 21 deletions(-) create mode 100644 crates/ledger-core/tests/bookspec/queries/book.rs diff --git a/crates/ledger-core/tests/bookspec/books.rs b/crates/ledger-core/tests/bookspec/books.rs index 8d0ae520..5a58b652 100644 --- a/crates/ledger-core/tests/bookspec/books.rs +++ b/crates/ledger-core/tests/bookspec/books.rs @@ -216,8 +216,14 @@ pub(crate) fn new_schedule( months: s.months, balance_account: account(&s.balance_account), pl_account: account(&s.pl_account), - convention: ScheduleConvention::parse(&s.convention) - .unwrap_or_else(|| panic!("{what}: schedule convention {:?}", s.convention)), + // A schedule that names no convention takes the engine's method for + // new schedules (BS-prepaid-2): wanderbooks spreads new schedules by + // the day (D-11, D-37). + convention: match s.convention.as_deref() { + Some(c) => ScheduleConvention::parse(c) + .unwrap_or_else(|| panic!("{what}: schedule convention {c:?}")), + None => ScheduleConvention::Daily, + }, } } @@ -358,7 +364,8 @@ impl<'a> Books<'a> { &what, ); if let Some(c) = &a.tax_category { - took(self.store.set_account_tax(account, Some(c), None), &what); + let percent = a.deductible_percent.as_deref().map(|p| exact(p, &what)); + took(self.store.set_account_tax(account, Some(c), percent), &what); } } let first = ex diff --git a/crates/ledger-core/tests/bookspec/check.rs b/crates/ledger-core/tests/bookspec/check.rs index 1c6fd669..e7890441 100644 --- a/crates/ledger-core/tests/bookspec/check.rs +++ b/crates/ledger-core/tests/bookspec/check.rs @@ -58,6 +58,8 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> { "code", &["rename_account", "set_tax_category"], ); + only(x.key.is_some(), "key", &["setting"]); + only(x.role.is_some(), "role", &["role_account"]); only(x.name.is_some(), "name", &["rename_account"]); only(x.category.is_some(), "category", &["set_tax_category"]); only(x.account.is_some(), "account", &["add_account"]); @@ -144,6 +146,9 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> { "invoice_numbers" => check_invoice_numbers(b, x), "draft_state" => check_draft_state(b, x), "evidence" => check_evidence(b, x), + "setting" => check_setting(b, x), + "role_account" => check_role_account(b, x), + "tax_summary" => check_tax_summary(b, x), q => { let &(_, by) = FORMAT_QUERIES .iter() diff --git a/crates/ledger-core/tests/bookspec/events.rs b/crates/ledger-core/tests/bookspec/events.rs index 40ecbfee..7cb041b8 100644 --- a/crates/ledger-core/tests/bookspec/events.rs +++ b/crates/ledger-core/tests/bookspec/events.rs @@ -25,11 +25,12 @@ impl Books<'_> { ("attach_receipt", e.attach_receipt.is_some()), ("discard_draft", e.discard_draft.is_some()), ("assign_role", e.assign_role.is_some()), + ("set_setting", e.set_setting.is_some()), ]; match kinds.iter().filter(|(_, given)| *given).collect::>()[..] { [(kind, _)] => kind, _ => panic!( - "{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, payment, settlement, recovery, run_depreciation, dispose_asset, run_schedules, register_schedule, post_draft, set_draft_state, attach_receipt, discard_draft or assign_role", + "{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, payment, settlement, recovery, run_depreciation, dispose_asset, run_schedules, register_schedule, post_draft, set_draft_state, attach_receipt, discard_draft, assign_role or set_setting", self.ex.id ), } @@ -827,6 +828,22 @@ impl Books<'_> { // account before it writes anything (BS-ledger-19). self.store.assign_role(&a.role, Some(account)) } + "set_setting" => { + let s = e.set_setting.as_ref().expect("checked: a setting"); + // The books' own journaled command: the fact and who decided + // it are kept in the journal (BS-ledger-9). + let change = Change { + key: s.key.clone(), + value: Some(Value::String(s.value.clone())), + }; + let source = Source { + decided_by: s.decided_by.clone(), + decided_on: date(&s.decided_on, what), + citation: None, + note: None, + }; + self.store.change_settings(&[change], &source).map(|_| ()) + } other => unreachable!("{other} is no event"), } } diff --git a/crates/ledger-core/tests/bookspec/examples.rs b/crates/ledger-core/tests/bookspec/examples.rs index f741ecb3..0324b5a2 100644 --- a/crates/ledger-core/tests/bookspec/examples.rs +++ b/crates/ledger-core/tests/bookspec/examples.rs @@ -126,6 +126,10 @@ pub(crate) fn every_bookspec_example_holds() { ("party_tin_last4", 5), ("iif_lines", 1), ("iif_changes", 1), + ("iif_line_ending", 1), + ("setting", 1), + ("role_account", 1), + ("tax_summary", 1), ("period", 6), ("day", 1), ("calendar_year", 1), @@ -162,17 +166,19 @@ pub(crate) fn every_bookspec_example_holds() { // of BS-arap-2 (documents-kept-apart), -7, -8, -9, -10 (compare-exactly), // -11 (recovery-movement), -12 (net-of-expected-discount), -13 // (net-against-the-deposit) and -14 (apportion-across-the-lines), - // BS-prepaid-2's equal-months and BS-ledger-20's refuse (each option's - // example, so no allow-list grows), BS-entry-6's check-only-when-posting - // and BS-ledger-17's reversal-needs-its-own (wanderbooks refuses a line on - // a header as it is added, and a reversal needs no evidence of its own), - // and BS-period-4's allow-partial-overlap, BS-1099-2's - // carry-the-last-amount and BS-partner-8's nowhere (wanderbooks nests - // periods, refuses a year whose threshold it does not know, and keeps - // the full TIN outside the books). + // BS-prepaid-2's equal-months, BS-prepaid-4's cent rule and BS-ledger-20's + // refuse (each option's example, so no allow-list grows), BS-entry-6's + // check-only-when-posting and BS-ledger-17's reversal-needs-its-own + // (wanderbooks refuses a line on a header as it is added, and a reversal + // needs no evidence of its own), BS-format-5's file place, -6's one + // fiscal year, -8's closes-written and -4's platform line ending, + // BS-ledger-21's round-per-account, BS-period-4's allow-partial-overlap, + // BS-1099-2's carry-the-last-amount and BS-partner-8's nowhere + // (wanderbooks nests periods, refuses a year whose threshold it does not + // know, and keeps the full TIN outside the books). assert_eq!( skipped.len(), - 16, - "the sixteen unpicked-option examples: {skipped:?}" + 22, + "the twenty-two unpicked-option examples: {skipped:?}" ); } diff --git a/crates/ledger-core/tests/bookspec/main.rs b/crates/ledger-core/tests/bookspec/main.rs index be75bacf..7c584fae 100644 --- a/crates/ledger-core/tests/bookspec/main.rs +++ b/crates/ledger-core/tests/bookspec/main.rs @@ -47,7 +47,7 @@ pub(crate) use std::path::{Path, PathBuf}; pub(crate) use chrono::{Datelike, NaiveDate}; pub(crate) use ledger_core::calendar::{PeriodDefaults, period_defaults}; pub(crate) use ledger_core::parties::{Basis, MoneyAccounts}; -pub(crate) use ledger_core::settings::{Company, Source}; +pub(crate) use ledger_core::settings::{Change, Company, Source}; pub(crate) use ledger_core::tax_capital::TaxCapitalRow; pub(crate) use ledger_core::{ AccountType, AssetId, BillFields, CashFlowParams, CashFlowSection, CashFlowStatement, CloseTo, @@ -55,8 +55,8 @@ pub(crate) use ledger_core::{ InstrumentId, InstrumentKind, InvoiceFields, Ledger, LedgerError, MemberCapital, MemberClose, Money, NewAsset, NewSchedule, PartyId, PartyMember, PartyShare, PaymentAccounts, ReconcilingKind, Role, ScheduleConvention, ScheduleId, ScheduleKind, Share, Side, Terms, - TinFacts, TinType, VendorId, W9Facts, cash_flow, members_equity, profit_and_loss_for_period, - trial_balance_as_of, vendor_1099_report, + TinFacts, TinType, VendorId, W9Facts, cash_flow, control_account, members_equity, + profit_and_loss_for_period, tax_summary, trial_balance_as_of, vendor_1099_report, }; pub(crate) use ledger_store::{DepreciationRun, DisposalPreview, Store, StoreError}; pub(crate) use ledger_vault::{Tin, Vault}; @@ -74,6 +74,7 @@ pub(crate) use books::*; pub(crate) use check::check; pub(crate) use common::*; pub(crate) use queries::assets::*; +pub(crate) use queries::book::*; pub(crate) use queries::commands::*; pub(crate) use queries::dates::*; pub(crate) use queries::documents::*; diff --git a/crates/ledger-core/tests/bookspec/queries/assets.rs b/crates/ledger-core/tests/bookspec/queries/assets.rs index 55734397..123511aa 100644 --- a/crates/ledger-core/tests/bookspec/queries/assets.rs +++ b/crates/ledger-core/tests/bookspec/queries/assets.rs @@ -110,10 +110,14 @@ impl Books<'_> { let mut m = JsonMap::new(); let mut total = Decimal::ZERO; for (d, amount) in &plan { - m.insert(d.to_string(), Value::String(figure(*amount))); + // The plan's own amounts are already whole units of the + // currency (BS-prepaid-1, -4): a yen schedule's month is 333, + // not 333.00, and a dollar schedule's 33.33. Printed as they + // stand, never padded to the cent. + m.insert(d.to_string(), Value::String(amount.to_string())); total += *amount; } - m.insert("total".to_string(), Value::String(figure(total))); + m.insert("total".to_string(), Value::String(total.to_string())); Ok(Value::Object(m)) } diff --git a/crates/ledger-core/tests/bookspec/queries/book.rs b/crates/ledger-core/tests/bookspec/queries/book.rs new file mode 100644 index 00000000..d4cf135f --- /dev/null +++ b/crates/ledger-core/tests/bookspec/queries/book.rs @@ -0,0 +1,132 @@ +use crate::*; + +impl Books<'_> { + /// A `setting` query (BS-ledger-9): the value the books keep, with who + /// decided it and when. The books hold their settings in the journal + /// (wanderbooks' pick, facts-in-the-books), so a replay reaches them. + pub(crate) fn answer_setting(&self, q: &Query) -> Result { + let rule = RuleId::new(Area::Ledger, 9); + let key = q.key.as_deref().ok_or_else(|| self.missing("key"))?; + let recorded = self.l().settings().get(key).ok_or_else(|| { + Refusal::new(rule.clone(), format!("no setting {key:?} in the books")) + })?; + let value = match &recorded.value { + Value::String(s) => s.clone(), + other => other.to_string(), + }; + Ok(json_figures([ + ("value".to_string(), value), + ("decided_by".to_string(), recorded.source.decided_by.clone()), + ( + "decided_on".to_string(), + recorded.source.decided_on.to_string(), + ), + ])) + } + + /// A `role_account` query (BS-ledger-18): the account a control role + /// posts to, read from the books' own journaled assignment. + pub(crate) fn answer_role_account(&self, q: &Query) -> Result { + let rule = RuleId::new(Area::Ledger, 18); + let role = q.role.as_deref().ok_or_else(|| self.missing("role"))?; + let control = control_account(role) + .ok_or_else(|| Refusal::new(rule.clone(), format!("{role:?} is no control role")))?; + let account = self + .l() + .role_account(control) + .and_then(|id| self.l().chart().get(id)) + .map(|a| a.code.clone()) + .unwrap_or_else(|| "unassigned".to_string()); + Ok(json_figures([("account".to_string(), account)])) + } + + /// A `tax_summary` query (BS-ledger-21): each category's deductible + /// amount, as `tax::tax_summary` figures it (one rounding, on the + /// category's exact total: wanderbooks' pick, round-once-on-the-total). + pub(crate) fn answer_tax_summary(&self, q: &Query) -> Result { + let rule = RuleId::new(Area::Ledger, 21); + let (from, to) = self.q_period(q)?; + let summary = tax_summary(self.l(), from, to, None).map_err(|e| engine_refusal(rule, e))?; + let mut out = JsonMap::new(); + for line in summary + .income + .iter() + .chain(&summary.cost_of_goods) + .chain(&summary.deductions) + .chain(&summary.separately_stated) + { + out.insert(line.category.clone(), Value::String(figure(line.tax))); + } + Ok(Value::Object(out)) + } +} + +/// Check one `setting` expectation (BS-ledger-9): the value, who decided it +/// and when, as the books keep them. +pub(crate) fn check_setting(b: &Books<'_>, x: &Expect) { + let ex = b.ex; + undated(ex, x); + exactly( + ex, + x, + &["decided_by", "decided_on", "value"] + .map(String::from) + .into(), + ); + let got = b + .answer(&x.query()) + .unwrap_or_else(|e| panic!("{}: setting refused ({})", ex.id, e.reason)); + let got = got.as_object().expect("a setting answers figures"); + for (k, want) in x.figures(&ex.id) { + assert_eq!( + got.get(k).and_then(Value::as_str), + Some(want.as_str()), + "{}: setting {k}", + ex.id + ); + } +} + +/// Check one `role_account` expectation (BS-ledger-18): the code the role's +/// account has in the books. +pub(crate) fn check_role_account(b: &Books<'_>, x: &Expect) { + let ex = b.ex; + undated(ex, x); + exactly(ex, x, &["account".to_string()].into()); + let got = b + .answer(&x.query()) + .unwrap_or_else(|e| panic!("{}: role_account refused ({})", ex.id, e.reason)); + let got = got.as_object().expect("a role account answers figures"); + for (k, want) in x.figures(&ex.id) { + assert_eq!( + got.get(k).and_then(Value::as_str), + Some(want.as_str()), + "{}: role_account {k}", + ex.id + ); + } +} + +/// Check one `tax_summary` expectation (BS-ledger-21): each category's +/// deductible amount, by category key. +pub(crate) fn check_tax_summary(b: &Books<'_>, x: &Expect) { + let ex = b.ex; + let (from, to) = period(ex, x); + assert!( + from <= to, + "{}: tax_summary from {from} after to {to}", + ex.id + ); + let got = b + .answer(&x.query()) + .unwrap_or_else(|e| panic!("{}: tax_summary refused ({})", ex.id, e.reason)); + let got = got.as_object().expect("a tax summary answers figures"); + for (k, want) in x.figures(&ex.id) { + assert_eq!( + got.get(k).and_then(Value::as_str), + Some(want.as_str()), + "{}: tax_summary {k}", + ex.id + ); + } +} diff --git a/crates/ledger-core/tests/bookspec/queries/formats.rs b/crates/ledger-core/tests/bookspec/queries/formats.rs index 37f1216c..53876950 100644 --- a/crates/ledger-core/tests/bookspec/queries/formats.rs +++ b/crates/ledger-core/tests/bookspec/queries/formats.rs @@ -26,6 +26,22 @@ impl Books<'_> { .collect(), )) } + "iif_line_ending" => { + // The file's own bytes: CR LF (wanderbooks' pick, cr-lf) + // or the host's line ending. The engine writes CR LF on + // every platform, so the first line ending is the file's. + let ending = if iif.text.contains("\r\n") { + "cr-lf" + } else if iif.text.contains('\n') { + "lf" + } else { + "cr-lf" + }; + Ok(json_figures([( + "line_ending".to_string(), + ending.to_string(), + )])) + } _ => Ok(Value::Array( iif.changes .iter() @@ -53,7 +69,7 @@ impl Books<'_> { /// The formats appendix's queries, and the test (another crate's) that /// checks them against the engine. -pub(crate) const FORMAT_QUERIES: [(&str, &str); 2] = [ +pub(crate) const FORMAT_QUERIES: [(&str, &str); 3] = [ ( "iif_lines", "ledger-package the_bookspec_iif_example_matches_the_engine", @@ -62,6 +78,10 @@ pub(crate) const FORMAT_QUERIES: [(&str, &str); 2] = [ "iif_changes", "ledger-package the_bookspec_iif_example_matches_the_engine", ), + ( + "iif_line_ending", + "ledger-core the_runner_reports_every_claimed_rule_green", + ), ]; /// A refused format query (BS-format-10): the appendix and the day, no @@ -98,6 +118,16 @@ pub(crate) fn check_format_shape(ex: &Example, x: &Expect) { assert_eq!(r.len(), 3, "{}: iif_changes row {r:?}", ex.id); } } + ("iif_line_ending", Values::Figures(f)) => { + assert!( + matches!( + f.get("line_ending").map(String::as_str), + Some("cr-lf" | "lf") + ), + "{}: iif_line_ending is cr-lf or lf: {f:?}", + ex.id + ); + } (q, _) => panic!("{}: {q}: values of the wrong shape", ex.id), } } diff --git a/crates/ledger-core/tests/bookspec/queries/mod.rs b/crates/ledger-core/tests/bookspec/queries/mod.rs index 5b923b5b..6e0639ad 100644 --- a/crates/ledger-core/tests/bookspec/queries/mod.rs +++ b/crates/ledger-core/tests/bookspec/queries/mod.rs @@ -1,6 +1,7 @@ use crate::*; pub(crate) mod assets; +pub(crate) mod book; pub(crate) mod commands; pub(crate) mod dates; pub(crate) mod documents; @@ -93,6 +94,9 @@ impl Books<'_> { "invoice_numbers" => self.answer_invoice_numbers(q), "draft_state" => self.answer_draft_state(q), "evidence" => self.answer_evidence(q), + "setting" => self.answer_setting(q), + "role_account" => self.answer_role_account(q), + "tax_summary" => self.answer_tax_summary(q), "run" => self.answer_run(q), "disposal" => self.answer_disposal(q), "depreciation_schedule" => self.answer_depreciation_schedule(q), @@ -127,7 +131,7 @@ impl Books<'_> { .map(|a| Value::String(format!("{} {}", a.code, a.name))) .collect(), )), - "iif_lines" | "iif_changes" => self.answer_iif(q), + "iif_lines" | "iif_changes" | "iif_line_ending" => self.answer_iif(q), "rename_account" | "add_account" | "set_tax_category" => self.answer_command(q), other => Err(Refusal::new( RuleId::new(Area::Ledger, 1),