Merge branch 'main' into t3/coverage-gap-tests-v-d2

This commit is contained in:
swaits committed 2026-11-09 05:07:33 -07:00
commit 5fd382450b
100 files changed
+1793 -374

No files matched your search

@@ -216,6 +216,50 @@ pub(crate) fn new_schedule(
}
}
/// A store of the books as they stood (see [`Books::rehearsal`]), and the
/// directory it lives in, which goes with it.
pub(crate) struct Rehearsal {
store: Store,
_dir: tempfile::TempDir,
}
impl std::ops::Deref for Rehearsal {
type Target = Store;
fn deref(&self) -> &Store {
&self.store
}
}
impl std::ops::DerefMut for Rehearsal {
fn deref_mut(&mut self) -> &mut Store {
&mut self.store
}
}
/// Copy the directory `from` to `to`, the entries `keep` names (by file
/// name) only, subdirectories whole.
fn copy_tree(
from: &std::path::Path,
to: &std::path::Path,
keep: &dyn Fn(&str) -> bool,
) -> std::io::Result<()> {
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)? {
let entry = entry?;
let name = entry.file_name();
if !keep(&name.to_string_lossy()) {
continue;
}
let target = to.join(&name);
if entry.file_type()?.is_dir() {
copy_tree(&entry.path(), &target, &|_| true)?;
} else {
std::fs::copy(entry.path(), target)?;
}
}
Ok(())
}
impl<'a> Books<'a> {
/// The books an example sets up, before any event: its shape checked,
/// its accounts, fixed assets, schedules, parties, members, payees,
@@ -502,6 +546,21 @@ impl<'a> Books<'a> {
"{what}: twice"
);
}
// The evidence policy the example assumes (BS-entry-5): the books'
// own setting, as an engine holds it (BS-ledger-9). An example that
// states none has no policy, and its drafts post by the primitive.
if let Some(over) = &s.evidence_over {
use ledger_core::settings::Change;
let change = Change {
key: "policy.evidence.threshold".into(),
value: Some(serde_json::json!(over)),
};
took(
self.store
.change_settings(&[change], &bookspec_source(&ex.id)),
&format!("{}: the evidence policy", ex.id),
);
}
self.members = members;
self.party_members = party_members;
self.parties = parties;
@@ -544,6 +603,27 @@ impl<'a> Books<'a> {
/// The entry event `event` (counting from 1) posted: an event applied
/// already, that posted exactly one.
/// The books as they stand, replayed from their journal into a store of
/// their own (a copy of the journal and the blobs, opened as any store
/// is), for a step the books must refuse without keeping a trace: a store
/// journals a draft the moment it is made, so a refused entry is made on
/// this and dropped with it. The directory lives as long as the store.
pub(crate) fn rehearsal(&self, what: &str) -> Rehearsal {
let from = self._dir.path().join("books");
let dir = tempfile::tempdir().unwrap();
let to = dir.path().join("books");
// The journal is the books; the database is derived, and the lock is
// this process's own.
copy_tree(&from, &to, &|name| {
name != ledger_store::store::LOCK_FILE
&& !ledger_store::store::is_database_file(name)
&& !name.contains(".db-")
})
.unwrap_or_else(|e| panic!("{what}: copying the books for a rehearsal: {e}"));
let store = took(Store::open(&to), &format!("{what}: the rehearsal"));
Rehearsal { store, _dir: dir }
}
pub(crate) fn entry_of(&self, event: usize, what: &str) -> EntryId {
assert!(
event >= 1 && event <= self.posted.len(),
+14 -2
View File
@@ -18,7 +18,11 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> {
queries.join(" and ")
);
};
only(x.entry.is_some(), "entry", &["entry", "party_part"]);
only(
x.entry.is_some(),
"entry",
&["entry", "party_part", "draft_state", "evidence"],
);
only(x.event.is_some(), "event", &["run"]);
only(
x.asset.is_some(),
@@ -38,7 +42,11 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> {
);
only(x.basis.is_some(), "basis", &["party_totals"]);
only(x.payee.is_some(), "payee", &["vendor_1099"]);
only(x.document.is_some(), "document", &["document_dates"]);
only(
x.document.is_some(),
"document",
&["document_dates", "document"],
);
only(x.of.is_some(), "of", &["aging"]);
only(
x.code.is_some(),
@@ -105,6 +113,10 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> {
"project" => check_project(b, x),
"aging" => check_aging(b, x),
"document_dates" => check_document_dates(b, x),
"document" => check_document(b, x),
"invoice_numbers" => check_invoice_numbers(b, x),
"draft_state" => check_draft_state(b, x),
"evidence" => check_evidence(b, x),
q => {
let &(_, by) = FORMAT_QUERIES
.iter()
@@ -144,6 +144,17 @@ pub(crate) fn refusal(e: &LedgerError) -> String {
LedgerError::InvalidSchedule(_) => "invalid_schedule",
LedgerError::UntaggedControlLine { .. } => "untagged_control_line",
LedgerError::PaymentBeforeDocument { .. } => "payment_before_document",
LedgerError::DuplicateVendorRef { .. } => "duplicate_vendor_reference",
// An invoice with a bill, and documents of two parties, are the one
// refusal: a customer and a vendor are two parties (BS-arap-6).
LedgerError::SettlementMixedKinds(_) | LedgerError::SettlementPartiesDiffer(..) => {
"settlement_mixes_parties"
}
LedgerError::SettlementDuplicateDocument(_) => "settlement_repeats_a_document",
LedgerError::Overpayment(..) => "application_above_owed",
LedgerError::DiscountNeedsReason { .. } => "discount_needs_reason",
LedgerError::DiscountOnAssetBill { .. } => "discount_on_asset_bill",
LedgerError::FeeAboveCash { .. } => "fee_above_cash",
LedgerError::UnbalancedEntry { .. } => "unbalanced",
LedgerError::TooFewLines => "too_few_lines",
LedgerError::NegativeAmountLine => "negative_amount",
@@ -152,6 +163,17 @@ pub(crate) fn refusal(e: &LedgerError) -> String {
LedgerError::ParentTypeMismatch { .. } => "parent_type_mismatch",
LedgerError::EntryAlreadyReversed(..) => "already_reversed",
LedgerError::ClosedPeriod(..) => "period_closed",
// A line on a header account (a placeholder takes no postings),
// BS-entry-1 and BS-entry-6.
LedgerError::PlaceholderAccount(_) => "header_account",
// A close with a draft dated in its period (BS-period-2).
LedgerError::DraftsInPeriod(_) => "drafts_in_period",
// A draft's command on an entry that is no draft: it is posted
// already (a post, a state, a discard), or was discarded and is
// gone (BS-entry-5).
LedgerError::EntryAlreadyPosted(_)
| LedgerError::PostedEntryImmutable
| LedgerError::UnknownEntry(_) => "not_drafted",
other => return format!("another refusal: {other}"),
}
.to_string()
@@ -162,6 +184,8 @@ pub(crate) fn refusal(e: &LedgerError) -> String {
pub(crate) fn store_refusal(e: &StoreError) -> String {
match e {
StoreError::Ledger(e) => refusal(e),
// The evidence gate (BS-entry-5): the entry needs a document.
StoreError::ReceiptRequired(_) => "evidence_required".to_string(),
other => format!("another refusal: {other}"),
}
}
@@ -199,6 +223,7 @@ pub(crate) fn exact(s: &str, what: &str) -> Decimal {
pub(crate) fn store_refusal_obj(e: &StoreError) -> Refusal {
match e {
StoreError::Ledger(e) => Refusal::of_reason(refusal(e)),
StoreError::ReceiptRequired(_) => Refusal::of_reason("evidence_required"),
other => Refusal::of_reason(format!("another refusal: {other}")),
}
}
+1 -1
View File
@@ -120,7 +120,7 @@ pub(crate) const PICKS: &[(Area, u32, &str)] = &[
(Area::Arap, 7, "due-today-is-current"),
(Area::Arap, 8, "as-of-the-day"),
(Area::Arap, 9, "refuse-a-payment-before-its-document"),
(Area::Arap, 10, "ignore-case-and-spaces"),
(Area::Arap, 10, "ignore-case-spaces-and-hyphens"),
(Area::Arap, 11, "reverse-then-plain-entry"),
(Area::Arap, 12, "gross-when-taken"),
(Area::Arap, 13, "gross"),
+317 -37
View File
@@ -14,15 +14,21 @@ impl Books<'_> {
("invoice", e.invoice.is_some()),
("write_off", e.write_off.is_some()),
("payment", e.payment.is_some()),
("settlement", e.settlement.is_some()),
("recovery", e.recovery.is_some()),
("run_depreciation", e.run_depreciation.is_some()),
("dispose_asset", e.dispose_asset.is_some()),
("run_schedules", e.run_schedules.is_some()),
("register_schedule", e.register_schedule.is_some()),
("post_draft", e.post_draft.is_some()),
("set_draft_state", e.set_draft_state.is_some()),
("attach_receipt", e.attach_receipt.is_some()),
("discard_draft", e.discard_draft.is_some()),
];
match kinds.iter().filter(|(_, given)| *given).collect::<Vec<_>>()[..] {
[(kind, _)] => kind,
_ => panic!(
"{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, payment, run_depreciation, dispose_asset, run_schedules or register_schedule",
"{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, payment, settlement, recovery, run_depreciation, dispose_asset, run_schedules, register_schedule, post_draft, set_draft_state, attach_receipt or discard_draft",
self.ex.id
),
}
@@ -36,7 +42,11 @@ impl Books<'_> {
// disposal is dated; the other commands date their own entries,
// and every command describes its own.
let own = matches!(kind, "lines" | "reverses" | "close" | "bill" | "invoice");
let dated = own || matches!(kind, "dispose_asset" | "write_off" | "payment");
let dated = own
|| matches!(
kind,
"dispose_asset" | "write_off" | "payment" | "settlement" | "recovery"
);
assert_eq!(
e.date.is_some(),
dated,
@@ -74,8 +84,20 @@ impl Books<'_> {
"{ex} event {n}: {kind} is tagged with no parties or payment method"
);
assert!(
e.refused.is_none() || !matches!(kind, "close" | "bill" | "invoice"),
"{ex} event {n}: refused is for a reversal, an entry or a command, which the books take whole or not at all"
e.refused.is_none() || kind != "invoice",
"{ex} event {n}: refused is for a reversal, an entry, a bill, a command or a close, which the books take whole or not at all"
);
assert!(
!e.draft || matches!(kind, "lines" | "reverses"),
"{ex} event {n}: draft is an entry's lines or a reversal, prepared and not yet posted"
);
assert!(
!e.draft
|| (e.parties.is_empty()
&& e.instrument.is_none()
&& e.payee.is_none()
&& !e.older),
"{ex} event {n}: a draft carries no payee, parties or payment method"
);
assert!(
!(e.older && e.refused.is_some()),
@@ -89,6 +111,14 @@ impl Books<'_> {
e.payment.is_none() || kind == "payment",
"{ex} event {n}: a payment is its own event"
);
assert!(
e.settlement.is_none() || kind == "settlement",
"{ex} event {n}: a settlement is its own event"
);
assert!(
e.recovery.is_none() || kind == "recovery",
"{ex} event {n}: a recovery is its own event"
);
}
/// Take event `n` as the books take it, keep what it posted and tag it
@@ -190,16 +220,33 @@ impl Books<'_> {
&self.posted[n - 1],
"{what}: what the event posted is kept"
);
// What a draft event made stands as a draft (until a `post_draft`
// posts it); what any other event made is posted.
let made = if e.draft {
EntryStatus::Draft
} else {
EntryStatus::Posted
};
for &id in &posted {
assert_eq!(
self.l().get_entry(id).map(|x| x.status()),
Some(EntryStatus::Posted),
"{what}: entry {id}, which it made, is posted"
Some(made),
"{what}: entry {id}, which it made, is {}",
if e.draft { "a draft" } else { "posted" }
);
}
if (own || matches!(kind, "write_off" | "payment")) && e.refused.is_none() {
if (own || matches!(kind, "write_off" | "payment" | "settlement")) && e.refused.is_none() {
assert_eq!(posted.len(), 1, "{what}: {kind} posts one entry");
}
// A recovery posts one entry or two, as the engine's pick under
// BS-arap-11 says: a plain entry, or the write-off's reversal and
// the payment.
if kind == "recovery" && e.refused.is_none() {
assert!(
matches!(posted.len(), 1 | 2),
"{what}: a recovery posts one entry or two"
);
}
}
/// The terms a document's example gives, and the due date the books take
@@ -230,6 +277,20 @@ impl Books<'_> {
(due, Some(parsed))
}
/// The invoice or bill event `event` posted, and its customer or vendor.
pub(crate) fn document_of(&self, event: usize, what: &str) -> (ledger_core::DocRef, u64) {
let entry = self.entry_of(event, what);
let l = self.l();
match (
l.invoices().into_iter().find(|i| i.entry_id == entry),
l.bills().into_iter().find(|b| b.entry_id == entry),
) {
(Some(i), _) => (ledger_core::DocRef::Invoice(i.id), i.customer_id),
(None, Some(b)) => (ledger_core::DocRef::Bill(b.id), b.vendor_id),
(None, None) => panic!("{what}: event {event} posted no invoice or bill"),
}
}
/// An invoice's or bill's lines: `amount` (one line, described as the
/// event) or `lines`, exactly one; each project a `setup.projects`
/// name.
@@ -264,7 +325,7 @@ impl Books<'_> {
panic!("{what}: project {p:?} not in setup.projects")
})
}),
account: None,
account: l.account.as_deref().map(|code| self.id(code)),
quantity: None,
unit_price: None,
})
@@ -296,12 +357,117 @@ impl Books<'_> {
};
let day = || when.expect("checked: dated");
match kind {
// A draft (BS-entry-5, BS-entry-6): the entry prepared, and posted
// by nothing here. The engine refuses a line on a header account
// as it is added (it picks check-when-line-added), and the books
// take an entry whole or not at all, so the draft is tried on a
// clone first: a refusal leaves no half-made draft in the journal.
"lines" if e.draft => {
let lines: Vec<_> = e
.lines
.iter()
.map(|line| {
let side = match line.side.as_str() {
"debit" => Side::Debit,
"credit" => Side::Credit,
other => panic!("{what}: side {other:?}"),
};
let class = line.project.as_ref().map(|p| {
*self.projects.get(p).unwrap_or_else(|| {
panic!("{what}: project {p:?} not in setup.projects")
})
});
(
self.id(&line.account),
side,
Money::new(money(&line.amount), self.currency),
class,
)
})
.collect();
let mut probe = self.store.ledger().clone();
let entry = probe.try_create_entry(day(), description)?;
for (i, &(account, side, amount, class)) in lines.iter().enumerate() {
probe.add_line(entry, account, side, amount)?;
if class.is_some() {
probe.set_line_class(entry, i, class)?;
}
}
let entry = self.store.create_entry(day(), description)?;
for (i, &(account, side, amount, class)) in lines.iter().enumerate() {
self.store.add_line(entry, account, side, amount)?;
if class.is_some() {
self.store.set_line_class(entry, i, class)?;
}
}
Ok(())
}
// Not a panic: the example fails as an engine refusal (`another
// refusal: ...`), and the harness goes on to report it.
"reverses" if e.draft => Err(StoreError::Io(std::io::Error::new(
std::io::ErrorKind::Unsupported,
format!(
"{what}: wanderbooks has no draft reversal: it picks reversal-evidence-is-originals (BS-ledger-17), under which a reversal posts at once"
),
))),
"post_draft" => {
let p = e.post_draft.as_ref().expect("checked: a post");
let entry = self.entry_of(p.entry, what);
// With an evidence policy the post is the gate's: the
// server's path for a hand-made draft; without one, the
// primitive.
if self.has_policy() {
self.store.post_entry_checked(entry)
} else {
self.store.post_entry(entry)
}
}
"set_draft_state" => {
let s = e.set_draft_state.as_ref().expect("checked: a state");
let entry = self.entry_of(s.entry, what);
let state = match (s.state.as_str(), &s.note) {
("building", None) => ledger_core::DraftState::Building,
("awaiting_evidence", Some(note)) => {
ledger_core::DraftState::AwaitingEvidence { note: note.clone() }
}
other => panic!("{what}: draft state {other:?}"),
};
self.store.set_draft_state(entry, state)
}
"attach_receipt" => {
let r = e.attach_receipt.as_ref().expect("checked: a receipt");
let entry = self.entry_of(r.entry, what);
// The document, by its reference: its own bytes, so that two
// references are two documents (identical bytes are one file,
// plan P6 step 4).
let bytes = format!("%PDF-1.4\n{}\n%%EOF\n", r.receipt);
self.store
.attach_receipt(
Some(entry),
&format!("{}.pdf", r.receipt.replace([' ', ',', '/'], "-")),
"application/pdf",
bytes.as_bytes(),
Some(&r.receipt),
)
.map(drop)
}
"discard_draft" => {
let d = e.discard_draft.as_ref().expect("checked: a discard");
let entry = self.entry_of(d.entry, what);
self.store.discard_draft(entry, &d.reason)
}
"lines" if e.refused.is_some() => {
// The books take an entry whole or not at all, so a
// refused one leaves no draft behind: it is tried on a
// clone, which is how the engine refuses it.
let mut probe = self.store.ledger().clone();
let entry = probe.create_entry(day(), description);
// refused one leaves no draft behind. The store journals a
// draft the moment it is made, so the entry is made, lined
// and posted on a rehearsal: the same books, replayed from
// their journal into a store of their own, which the engine
// refuses through its own gate (`post_entry_checked` under a
// policy, the server's path for a hand entry) and which is
// then thrown away. The refusal is the engine's, never
// rebuilt here.
let mut rehearsal = self.rehearsal(what);
let entry = rehearsal.create_entry(day(), description)?;
for (i, line) in e.lines.iter().enumerate() {
let side = match line.side.as_str() {
"debit" => Side::Debit,
@@ -310,15 +476,19 @@ impl Books<'_> {
};
let amount = Money::new(money(&line.amount), self.currency);
let account = self.id(&line.account);
probe.add_line(entry, account, side, amount)?;
rehearsal.add_line(entry, account, side, amount)?;
if let Some(p) = &line.project {
let class = *self.projects.get(p).unwrap_or_else(|| {
panic!("{what}: project {p:?} not in setup.projects")
});
probe.set_line_class(entry, i, Some(class))?;
rehearsal.set_line_class(entry, i, Some(class))?;
}
}
Ok(probe.post_entry(entry)?)
if self.has_policy() {
rehearsal.post_entry_checked(entry)
} else {
rehearsal.post_entry(entry)
}
}
"lines" => {
let post = |this: &mut Self| -> Result<(), StoreError> {
@@ -340,7 +510,11 @@ impl Books<'_> {
this.store.set_line_class(entry, i, Some(class))?;
}
}
this.store.post_entry(entry)
if this.has_policy() {
this.store.post_entry_checked(entry)
} else {
this.store.post_entry(entry)
}
};
if e.older {
ledger_core::parties::replaying(|| post(self))
@@ -362,30 +536,20 @@ impl Books<'_> {
"close" => {
let c = e.close.as_ref().expect("checked: a close");
let start = date(&c.start, what);
if e.refused.is_some() {
// A close the books refuse (a draft stands in the period,
// BS-period-2) opens no period and posts nothing: it is
// tried on a clone, with the same close below.
let mut probe = self.store.ledger().clone();
let p = probe.create_period(&format!("event {n}"), start, day())?;
return Ok(probe
.close_period_to(p, &self.close_to(c, what))
.map(drop)?);
}
let p = self
.store
.create_period(&format!("event {n}"), start, day())?;
let members: Vec<MemberClose> = self
.members
.iter()
.map(|m| MemberClose {
capital: m.capital_account,
share: m.share,
distributions: None,
})
.collect();
if c.to == "members" {
assert!(
!members.is_empty() && members.iter().all(|m| m.share > Decimal::ZERO),
"{what}: a close to the members needs their shares"
);
}
let to = match (c.to.as_str(), c.rounding.as_deref()) {
("members", None) => CloseTo::Members(members),
("members", Some("per-close")) => CloseTo::MembersPerClose(members),
("retained_earnings", None) => CloseTo::RetainedEarnings { sweep: vec![] },
other => panic!("{what}: close {other:?}"),
};
let to = self.close_to(c, what);
let closed = self.store.close_period_to(p, &to)?;
assert!(closed.is_some(), "{what}: the close has nothing to close");
Ok(())
@@ -410,6 +574,8 @@ impl Books<'_> {
lines,
BillFields {
terms,
vendor_ref: b.vendor_ref.clone(),
duplicate_reason: b.duplicate_reason.clone(),
..BillFields::default()
},
)
@@ -427,6 +593,9 @@ impl Books<'_> {
}
};
let (due, terms) = self.terms_due(i.terms.as_deref(), day(), what);
// The books number every invoice in order of issue (BS-arap-4),
// as their invoicing settings default to.
let number = self.l().next_invoice_number("INV-", 1);
self.store
.create_invoice_with(
customer,
@@ -434,6 +603,7 @@ impl Books<'_> {
due,
lines,
InvoiceFields {
number: Some(number),
terms,
..InvoiceFields::default()
},
@@ -515,6 +685,82 @@ impl Books<'_> {
}
}
}
"settlement" => {
let st = e.settlement.as_ref().expect("checked: a settlement");
let first = &st.applications[0];
let (first_doc, party) = self.document_of(first.document, what);
let applications: Vec<ledger_core::Application> = st
.applications
.iter()
.map(|a| ledger_core::Application {
doc: self.document_of(a.document, what).0,
cash: exact(&a.cash, what),
discount: a
.discount
.as_deref()
.map_or(Decimal::ZERO, |d| exact(d, what)),
discount_reason: a.discount_reason.clone(),
})
.collect();
debug_assert_eq!(applications[0].doc, first_doc);
let params = ledger_core::SettleParams {
date: day(),
description: String::new(),
cash_account: self.id(&st.account),
party,
applications,
fee: st.fee.as_deref().map(|f| ledger_core::Fee {
amount: exact(f, what),
account: None,
vendor: None,
}),
instrument: None,
reference: None,
};
self.store.settle(params).map(drop)
}
"recovery" => {
// BS-arap-11, the pick reverse-then-plain-entry: in the tax
// year of the write-off the write-off is reversed and the
// money is recorded as any payment; in a later year a plain
// entry debits the deposit account and credits the recoveries
// account, naming the invoice.
let r = e.recovery.as_ref().expect("checked: a recovery");
let amount = exact(&r.amount, what);
let (cash, income) = (self.id(&r.account), self.id(&r.income_account));
let write_off = self.entry_of(r.write_off, what);
let written = &self.ex.events[r.write_off - 1];
let invoice_event = written
.write_off
.as_ref()
.map(|w| w.invoice)
.unwrap_or_else(|| panic!("{what}: event {} is no write-off", r.write_off));
let (doc, _) = self.document_of(invoice_event, what);
let ledger_core::DocRef::Invoice(invoice) = doc else {
panic!("{what}: a write-off is of an invoice")
};
let written_on = date(written.date.as_deref().expect("a write-off is dated"), what);
let year =
|d| ledger_core::calendar::fiscal_year_start_on(fiscal_year_start(self.ex), d);
if year(written_on) == year(day()) {
self.store.reverse_entry(
write_off,
day(),
"Recovered: the write-off is reversed",
)?;
self.store
.receive_payment(invoice, day(), amount, cash)
.map(drop)
} else {
let entry = self
.store
.create_entry(day(), &format!("Recovery of invoice {invoice}"))?;
let money = Money::new(amount, self.currency);
self.store.add_line(entry, cash, Side::Debit, money)?;
self.store.add_line(entry, income, Side::Credit, money)?;
self.store.post_entry(entry)
}
}
"run_depreciation" => {
let r = e.run_depreciation.as_ref().expect("checked: a run");
let asset = self.asset(&r.asset, what);
@@ -575,6 +821,40 @@ impl Books<'_> {
}
}
}
impl Books<'_> {
/// Whether the example states an evidence policy (`setup.evidence_over`):
/// the books' own setting, which the server's post gate reads.
pub(crate) fn has_policy(&self) -> bool {
self.ex.setup.evidence_over.is_some()
}
/// Where a close sends the period's income: to retained earnings, or to
/// the members by their shares.
pub(crate) fn close_to(&self, c: &bookspec_checker::CloseSpec, what: &str) -> CloseTo {
let members: Vec<MemberClose> = self
.members
.iter()
.map(|m| MemberClose {
capital: m.capital_account,
share: m.share,
distributions: None,
})
.collect();
if c.to == "members" {
assert!(
!members.is_empty() && members.iter().all(|m| m.share > Decimal::ZERO),
"{what}: a close to the members needs their shares"
);
}
match (c.to.as_str(), c.rounding.as_deref()) {
("members", None) => CloseTo::Members(members),
("members", Some("per-close")) => CloseTo::MembersPerClose(members),
("retained_earnings", None) => CloseTo::RetainedEarnings { sweep: vec![] },
other => panic!("{what}: close {other:?}"),
}
}
}
impl Books<'_> {
/// Make a change that posts no entry (after event `after`).
/// Make a change that posts no entry (after event `after`), or say why
+11 -4
View File
@@ -146,6 +146,8 @@ pub(crate) fn every_bookspec_example_holds() {
("project", 6),
("aging", 4),
("document_dates", 8),
("document", 8),
("invoice_numbers", 1),
] {
let n = checked.get(q).copied().unwrap_or(0);
assert!(n >= at_least, "{q} ran {n} times, fewer than {at_least}");
@@ -157,11 +159,16 @@ pub(crate) fn every_bookspec_example_holds() {
skipped.len()
);
// The examples for an option wanderbooks did not pick: the other option
// of BS-arap-7, -8 and -9, BS-prepaid-2's equal-months and BS-ledger-20's
// refuse (each option's example, so no allow-list grows).
// of BS-arap-2 (documents-kept-apart), -7, -8, -9, -10 (compare-exactly),
// -11 (recovery-movement), -12 (net-of-expected-discount), -13
// (net-against-the-deposit) and -14 (apportion-across-the-lines),
// BS-prepaid-2's equal-months and BS-ledger-20's refuse (each option's
// example, so no allow-list grows), 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).
assert_eq!(
skipped.len(),
5,
"the five unpicked-option examples: {skipped:?}"
13,
"the thirteen unpicked-option examples: {skipped:?}"
);
}
@@ -629,3 +629,61 @@ pub(crate) fn an_invoice_lines_project_is_what_the_project_counts() {
},
);
}
/// A draft's state the engine does not hold is a failure, not a pass: the
/// example says the entry is still `building` after it posted.
#[test]
#[should_panic(expected = "state")]
pub(crate) fn a_wrong_draft_state_fails() {
run_edited(
"entry-a-draft-waits-on-its-evidence-and-posts-once-it-has-it.toml",
|t| t.replacen("state = \"posted\"", "state = \"building\"", 1),
);
}
/// An evidence decision the engine does not give is a failure.
#[test]
#[should_panic(expected = "decision")]
pub(crate) fn a_wrong_evidence_decision_fails() {
run_edited("entry-evidence-is-decided-in-one-place.toml", |t| {
t.replacen("decision = \"required\"", "decision = \"exempt\"", 1)
});
}
/// A post the gate refuses is a refusal the example must say: leaving it out
/// is a failure (the engine refused an event the example takes).
#[test]
#[should_panic(expected = "post_draft")]
pub(crate) fn a_post_without_its_evidence_must_be_marked_refused() {
run_edited(
"entry-a-draft-waits-on-its-evidence-and-posts-once-it-has-it.toml",
|t| t.replacen("refused = \"evidence_required\"\n", "", 1),
);
}
/// A discard of a posted entry is refused: saying it is accepted fails.
#[test]
#[should_panic(expected = "discard_draft")]
pub(crate) fn a_discard_of_a_posted_entry_must_be_marked_refused() {
run_edited(
"entry-a-drafts-state-is-a-note-and-a-posted-entry-has-none.toml",
|t| {
t.replacen(
"discard_draft = { entry = 1, reason = \"Posted by mistake\" }\nrefused = \"not_drafted\"",
"discard_draft = { entry = 1, reason = \"Posted by mistake\" }",
1,
)
},
);
}
/// A close the books hold back for a draft in its period is refused and
/// changes nothing: saying it is accepted fails.
#[test]
#[should_panic(expected = "draft entries exist")]
pub(crate) fn a_close_with_a_draft_in_its_period_must_be_marked_refused() {
run_edited(
"period-a-draft-holds-its-period-open-until-it-is-discarded.toml",
|t| t.replacen("refused = \"drafts_in_period\"\n", "", 1),
);
}
@@ -76,6 +76,7 @@ pub(crate) use queries::assets::*;
pub(crate) use queries::commands::*;
pub(crate) use queries::dates::*;
pub(crate) use queries::documents::*;
pub(crate) use queries::drafts::*;
pub(crate) use queries::formats::*;
pub(crate) use queries::parties::*;
pub(crate) use queries::statements::*;
@@ -96,4 +97,5 @@ mod rules_md;
mod run;
mod source_refs;
mod sources;
mod sub_refs;
mod traceability;
@@ -364,7 +364,7 @@ pub(crate) fn check_schedule_plan(b: &Books<'_>, x: &Expect) {
}
/// Check one `register_row` expectation: the asset's row of the fixed
/// asset register as of `as_of` (BS-asset-1 rules 7 and 8, BS-asset-3):
/// asset register as of `as_of` (BS-asset-1 statements 23, 24 and 28, BS-asset-3):
/// `acquired` and `in_service` (`YYYY-MM-DD`), `cost`,
/// `accumulated_scheduled` (the schedule's), `accumulated_posted` (what
/// the books carry), `unposted` (the one less the other), `book_value`
@@ -63,6 +63,63 @@ impl Books<'_> {
("discount_by".to_string(), discount_by),
]))
}
/// What the ledger lines tagged with the document event `document` come
/// to as of the day (BS-arap-2), straight from the engine's `DocState`:
/// `total`, `paid`, `discounted`, `written_off` and `owes` (its
/// `outstanding`). The engine keeps no recovery movement (BS-arap-11
/// reverse-then-plain-entry), so it gives no `recovered`.
pub(crate) fn answer_document(&self, q: &Query) -> Result<Value, Refusal> {
let n = q.document.ok_or_else(|| self.missing("document"))?;
let as_of = self.q_day(q)?;
let (doc, _) = self.document_of(n, "a document query");
let state = match doc {
ledger_core::DocRef::Invoice(id) => self.l().invoice_state(id, as_of),
ledger_core::DocRef::Bill(id) => self.l().bill_state(id, as_of),
}
.map_err(|e| engine_refusal(RuleId::new(Area::Arap, 2), e))?
.ok_or_else(|| self.missing("document, dated by the day asked"))?;
Ok(json_figures([
("total".to_string(), figure(state.total)),
("paid".to_string(), figure(state.paid)),
("discounted".to_string(), figure(state.discounted)),
("written_off".to_string(), figure(state.written_off)),
("owes".to_string(), figure(state.outstanding)),
]))
}
/// The place of each invoice in the order of issue, and of the next
/// (BS-arap-4): read from the number the engine stored at issue,
/// `INV-0003` being the third, a voided invoice keeping its own.
pub(crate) fn answer_invoice_numbers(&self, _q: &Query) -> Result<Value, Refusal> {
let place = |number: &str| -> String {
let digits: String = number.chars().filter(char::is_ascii_digit).collect();
digits.trim_start_matches('0').to_string()
};
let l = self.l();
let mut m = JsonMap::new();
for (i, e) in self.ex.events.iter().enumerate() {
if e.invoice.is_none() || i >= self.posted.len() {
continue;
}
let entry = self.entry_or_refuse(i + 1)?;
let invoice = l
.invoices()
.into_iter()
.find(|inv| inv.entry_id == entry)
.ok_or_else(|| self.missing("invoice"))?;
let number = invoice
.number
.as_deref()
.ok_or_else(|| self.missing("invoice number"))?;
m.insert((i + 1).to_string(), Value::String(place(number)));
}
m.insert(
"next".to_string(),
Value::String(place(&l.next_invoice_number("INV-", 1))),
);
Ok(Value::Object(m))
}
}
/// Check an `aging` expectation: every figure the engine gives, and no
@@ -71,13 +128,39 @@ pub(crate) fn check_aging(b: &Books<'_>, x: &Expect) {
check_figures(b, x, b.answer_aging(&x.query()));
}
/// Check a `document` expectation: the figures it names, as the engine's
/// document figures give them.
pub(crate) fn check_document(b: &Books<'_>, x: &Expect) {
let answer = b.answer_document(&x.query());
let Value::Object(got) =
answer.unwrap_or_else(|r| panic!("{}: {}: {}", b.ex.id, x.query, r.reason))
else {
panic!("{}: {} answers a table", b.ex.id, x.query)
};
for (key, want) in x.figures(&b.ex.id) {
assert_eq!(
got.get(key).and_then(Value::as_str),
Some(want.as_str()),
"{}: {} {key}",
b.ex.id,
x.query
);
}
}
/// Check an `invoice_numbers` expectation: every invoice and the next,
/// and no other.
pub(crate) fn check_invoice_numbers(b: &Books<'_>, x: &Expect) {
check_figures(b, x, b.answer_invoice_numbers(&x.query()));
}
/// Check a `document_dates` expectation: `due` and `discount_by`, both
/// given.
pub(crate) fn check_document_dates(b: &Books<'_>, x: &Expect) {
check_figures(b, x, b.answer_document_dates(&x.query()));
}
fn check_figures(b: &Books<'_>, x: &Expect, answer: Result<Value, Refusal>) {
pub(crate) fn check_figures(b: &Books<'_>, x: &Expect, answer: Result<Value, Refusal>) {
let ex = b.ex;
let Value::Object(got) =
answer.unwrap_or_else(|r| panic!("{}: {}: {}", ex.id, x.query, r.reason))
@@ -0,0 +1,81 @@
use crate::*;
impl Books<'_> {
/// Where the entry event `q.entry` made stands (BS-entry-5), read from
/// the engine's own books: a draft's state (with its note when it awaits
/// evidence), posted (a posted entry has no state of its own), or gone
/// (a discarded draft leaves the ledger).
pub(crate) fn answer_draft_state(&self, q: &Query) -> Result<Value, Refusal> {
let n = q.entry.ok_or_else(|| self.missing("entry"))?;
let id = self.entry_or_refuse(n)?;
let mut m = JsonMap::new();
let state = match self.l().get_entry(id) {
None => "discarded",
Some(e) if e.status() == EntryStatus::Posted => "posted",
Some(e) => match e.draft_state() {
ledger_core::DraftState::Building => "building",
ledger_core::DraftState::AwaitingEvidence { note } => {
m.insert("note".to_string(), Value::String(note.clone()));
"awaiting_evidence"
}
},
};
m.insert("state".to_string(), Value::String(state.to_string()));
Ok(Value::Object(m))
}
/// The engine's one decision whether the entry event `q.entry` made
/// needs evidence (`ledger_core::evidence::requirement`, BS-entry-5): the
/// decision as the engine gives it, its reason or exemption read into
/// the examples' closed words.
pub(crate) fn answer_evidence(&self, q: &Query) -> Result<Value, Refusal> {
use ledger_core::evidence::{Requirement, requirement};
let n = q.entry.ok_or_else(|| self.missing("entry"))?;
let id = self.entry_or_refuse(n)?;
let entry = self
.l()
.get_entry(id)
.ok_or_else(|| self.missing("entry"))?;
let (decision, because) = match requirement(self.l(), entry, self.l().settings()) {
Requirement::Required { .. } => ("required", "policy"),
Requirement::Exempt { source } => (
"exempt",
// The engine words the source of an exemption in sentences;
// the examples' words are the closed list of BS-entry-5.
match source {
s if s.starts_with("the receipt policy") => "policy",
s if s.starts_with("a reversal") => "reversal",
s if s.starts_with("a period's closing entry") => "closing_entry",
s if s.starts_with("a schedule month's posting") => "schedule_posting",
s if s.starts_with("a depreciation run") => "depreciation_run",
s if s.starts_with("an asset's disposal") => "asset_disposal",
// A payroll command's posting (a run, or the tax
// remittance) is its own source, not a document's.
s if s.starts_with("a payroll") => "payroll_posting",
s if s.starts_with("a document's entry") => "document_entry",
other => {
return Err(engine_refusal(
RuleId::new(Area::Entry, 5),
format!("an exemption with no word in the examples: {other}"),
));
}
},
),
};
Ok(json_figures([
("decision".to_string(), decision.to_string()),
("because".to_string(), because.to_string()),
]))
}
}
/// Check a `draft_state` expectation: the state, and the note when the draft
/// awaits evidence, and nothing else.
pub(crate) fn check_draft_state(b: &Books<'_>, x: &Expect) {
check_figures(b, x, b.answer_draft_state(&x.query()));
}
/// Check an `evidence` expectation: the decision and why, both given.
pub(crate) fn check_evidence(b: &Books<'_>, x: &Expect) {
check_figures(b, x, b.answer_evidence(&x.query()));
}
@@ -4,6 +4,7 @@ pub(crate) mod assets;
pub(crate) mod commands;
pub(crate) mod dates;
pub(crate) mod documents;
pub(crate) mod drafts;
pub(crate) mod formats;
pub(crate) mod parties;
pub(crate) mod statements;
@@ -87,6 +88,10 @@ impl Books<'_> {
"project" => self.answer_project(q),
"aging" => self.answer_aging(q),
"document_dates" => self.answer_document_dates(q),
"document" => self.answer_document(q),
"invoice_numbers" => self.answer_invoice_numbers(q),
"draft_state" => self.answer_draft_state(q),
"evidence" => self.answer_evidence(q),
"run" => self.answer_run(q),
"disposal" => self.answer_disposal(q),
"depreciation_schedule" => self.answer_depreciation_schedule(q),
@@ -299,7 +299,7 @@ pub(crate) fn check_vendor_1099(b: &Books<'_>, x: &Expect) {
/// The money party shares resolve against: the cash accounts (every
/// asset account but receivables when none are named), the cards and the
/// financing accounts (BS-partner-3 item 5).
/// financing accounts (BS-partner-3 statement 7).
pub(crate) fn party_money(ex: &Example, l: &Ledger) -> MoneyAccounts {
ledger_core::parties::money_accounts(
l,
@@ -368,7 +368,7 @@ pub(crate) fn check_party_part(b: &Books<'_>, x: &Expect) {
/// Check one `party_totals` expectation: what was `paid` to and
/// `received` from the party from `from` through `to` on `basis` (`cash`:
/// money; `all`: money and property in kind), each entry's part on its
/// root original's side (BS-partner-3 item 4); both given.
/// root original's side (BS-partner-3 statement 5); both given.
pub(crate) fn check_party_totals(b: &Books<'_>, x: &Expect) {
let (ex, l) = (b.ex, b.l());
assert!(
@@ -0,0 +1,635 @@
//! The sub-reference checks (unit S-E3).
//!
//! Unit S-E rewrote every `B-n` citation to its bookspec id and kept the
//! sub-reference after it ("item 7", "rule 11", "INVARIANT 2") as it was,
//! but those numbers counted parts of the retired rules.md text, not of
//! bookspec's records. S-E3 mapped each by content, and this check keeps
//! them true: every `BS-<area>-<n> statement k`, `invariant k` or
//! `scenario k` in any tracked file outside `plan/` names a part its
//! pinned record has (k from 1 to the length of that list), and the old
//! vocabulary (`item`, `rule`, `INVARIANT`, `SCENARIO`, `r`, or any
//! other word that is not exactly `statement`, `invariant` or
//! `scenario`) after a bookspec id fails, whether a number follows it or
//! the word stands bare (`BS-arap-3 SCENARIOS: ...`, on the id's line).
//!
//! A product rule's id (`WB-<area>-<n>`) takes the same check against the
//! parts its own claim states: the numbered `INVARIANTS:` and
//! `SCENARIOS:` lists of its spec block in `docs/spec/claims/*.md`. A
//! product rule with no such list takes no sub-number, and has no
//! statements (those are bookspec's).
//!
//! A reference may be a list ("statements 5, 11 and 13"), a range
//! ("statements 27-30"), parenthesised, wrapped across lines behind a
//! comment prefix, backticked after the id (`` `BS-asset-1` statements
//! 23-24 ``), or continued on the same id ("invariant 2 and statement
//! 11"); each number, each member of a range, is one reference checked.
//! The count is floored and printed. This file is not scanned: its
//! self-tests quote the forms they must refuse.
use crate::*;
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
}
/// How many references the scan must find, at least: exactly the number
/// found when it was last set, so none can vanish silently. Raise it, in
/// the same commit, when references are added; it never falls.
const CHECKED_FLOOR: usize = 361;
/// The tracked file this check does not scan: its own self-tests quote
/// the forms it refuses.
const SELF: &str = "crates/ledger-core/tests/bookspec/sub_refs.rs";
/// The parts a record has: its statements, invariants and scenarios.
#[derive(Clone, Copy, Default)]
struct Parts {
statements: usize,
invariants: usize,
scenarios: usize,
}
fn record_parts() -> BTreeMap<String, Parts> {
bookspec_checker::records()
.iter()
.map(|r| {
(
r.id.to_string(),
Parts {
statements: r.statement.len(),
invariants: r.invariants.len(),
scenarios: r.scenarios.len(),
},
)
})
.collect()
}
/// The parts each product rule `WB-<area>-<n>` states in
/// `docs/spec/claims/*.md`: under its `**WB-…**` paragraph, the numbered
/// items (` 1. …`) below `INVARIANTS:` and below `SCENARIOS:`. A list
/// must count 1, 2, 3, … : an irregular one is a failure, not a guess.
fn product_rule_parts(root: &Path) -> BTreeMap<String, Parts> {
let dir = root.join("docs/spec/claims");
let mut files: Vec<PathBuf> = std::fs::read_dir(&dir)
.expect("docs/spec/claims exists")
.map(|e| e.expect("a directory entry").path())
.filter(|p| p.extension().is_some_and(|x| x == "md"))
.collect();
files.sort();
let mut out: BTreeMap<String, Parts> = BTreeMap::new();
for file in files {
let text = std::fs::read_to_string(&file).expect("a claims file reads");
let mut current: Option<String> = None;
// 'i' under INVARIANTS:, 'c' under SCENARIOS:, none elsewhere.
let mut mode: Option<char> = None;
for line in text.lines() {
if let Some(rest) = line.strip_prefix("**WB-") {
let id: String = rest.chars().take_while(|c| *c != '*').collect();
current = Some(format!("WB-{id}"));
out.entry(format!("WB-{id}")).or_default();
mode = None;
continue;
}
if line.starts_with('#') {
current = None;
mode = None;
continue;
}
let Some(id) = &current else { continue };
if line == "INVARIANTS:" {
mode = Some('i');
} else if line == "SCENARIOS:" {
mode = Some('c');
} else if line.starts_with("```")
|| line.split_once(':').is_some_and(|(head, _)| {
!head.is_empty() && head.chars().all(|c| c.is_ascii_uppercase())
})
{
mode = None;
} else if let Some(kind) = mode {
let digits: String = line
.strip_prefix(" ")
.unwrap_or("")
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
if !digits.is_empty() && line[2 + digits.len()..].starts_with(". ") {
let p = out.get_mut(id).expect("the rule was entered");
let count = if kind == 'i' {
&mut p.invariants
} else {
&mut p.scenarios
};
assert_eq!(
digits.parse::<usize>().ok(),
Some(*count + 1),
"{}: {id}'s numbered list counts 1, 2, 3, ...: {line:?}",
file.display()
);
*count += 1;
}
}
}
}
out
}
/// Every id a part can be cited on: bookspec's records and the product
/// rules of the claims.
fn all_parts() -> BTreeMap<String, Parts> {
let mut parts = record_parts();
parts.extend(product_rule_parts(&repo_root()));
parts
}
/// The text with each line's comment prefix and indentation dropped and
/// the lines joined by one space, so a reference wrapped across lines
/// reads as one; and the byte offset where each line starts in it.
fn flatten(text: &str) -> (String, Vec<usize>) {
let mut flat = String::with_capacity(text.len());
let mut starts = Vec::new();
for line in text.lines() {
starts.push(flat.len());
let mut rest = line.trim_start();
for prefix in ["///", "//!", "//", "#", "*", ">"] {
if let Some(after) = rest.strip_prefix(prefix) {
rest = after.trim_start();
break;
}
}
flat.push_str(rest.trim_end());
flat.push(' ');
}
(flat, starts)
}
fn line_at(starts: &[usize], offset: usize) -> usize {
starts.partition_point(|&s| s <= offset)
}
/// The kind a word names: `Some(true)` for the new vocabulary, exactly
/// `statement`, `invariant`, `scenario` (or the plural); `Some(false)`
/// for any old or miscased word; `None` for a word that is no part word.
fn part_word(word: &str) -> Option<(Option<char>, bool)> {
let lower = word.to_ascii_lowercase();
let singular = lower.strip_suffix('s').unwrap_or(&lower);
let kind = match singular {
"statement" => 's',
"invariant" => 'i',
"scenario" => 'c',
"item" | "rule" => 'o',
_ if lower == "r" => 'o',
_ => return None,
};
let new = kind != 'o'
&& matches!(
word,
"statement" | "statements" | "invariant" | "invariants" | "scenario" | "scenarios"
);
Some((if kind == 'o' { None } else { Some(kind) }, new))
}
fn is_id_char(c: char) -> bool {
c.is_ascii_alphanumeric() || c == '-' || c == '_'
}
/// The numbers after a part word: `5`, `5, 11 and 13`, `27-30`.
/// Returns each (low, high) and the chars consumed.
fn number_list(tail: &[char], start: usize) -> (Vec<(usize, usize)>, usize) {
let mut at = start;
let mut out = Vec::new();
loop {
// One element: digits, optionally `-` or an en dash and digits.
let mut j = at;
while j < tail.len() && tail[j].is_ascii_digit() {
j += 1;
}
let len = j - at;
if len == 0 || (!out.is_empty() && len > 3) || len > 4 {
break;
}
let low: usize = tail[at..j].iter().collect::<String>().parse().unwrap_or(0);
let mut high = low;
let mut end = j;
if end + 1 < tail.len()
&& (tail[end] == '-' || tail[end] == '–')
&& tail[end + 1].is_ascii_digit()
{
let mut k = end + 1;
while k < tail.len() && tail[k].is_ascii_digit() {
k += 1;
}
if k - (end + 1) <= 3 {
high = tail[end + 1..k]
.iter()
.collect::<String>()
.parse()
.unwrap_or(0);
end = k;
}
}
// A date or a number glued to letters is no part number.
if !out.is_empty()
&& end < tail.len()
&& (tail[end].is_ascii_alphanumeric()
|| (tail[end] == '-' && end + 1 < tail.len() && tail[end + 1].is_ascii_digit()))
{
break;
}
out.push((low, high));
at = end;
// A separator and another number: `, `, ` and `, `, and `, ` or `.
let mut k = at;
let mut sep = false;
for word in [", and ", ", ", " and ", " or "] {
let w: Vec<char> = word.chars().collect();
if tail.len() >= k + w.len() && tail[k..k + w.len()] == w[..] {
k += w.len();
sep = true;
break;
}
}
if !sep || k >= tail.len() || !tail[k].is_ascii_digit() {
break;
}
at = k;
}
(out, at)
}
/// How many references a list of (low, high) numbers is: each number, each
/// member of a range, once. A range that runs backwards is one.
fn count_of(nums: &[(usize, usize)]) -> usize {
nums.iter()
.map(|&(low, high)| if high >= low { high - low + 1 } else { 1 })
.sum()
}
/// Scan `text`; returns the references checked and the problems found.
fn scan(text: &str, at: &str, parts: &BTreeMap<String, Parts>) -> (usize, Vec<String>) {
let (flat, starts) = flatten(text);
let mut checked = 0usize;
let mut problems = Vec::new();
let mut hits: Vec<(usize, &str)> = ["BS-", "WB-"]
.iter()
.flat_map(|prefix| flat.match_indices(prefix).map(|(pos, _)| (pos, *prefix)))
.collect();
hits.sort();
for (pos, prefix) in hits {
if flat[..pos].chars().next_back().is_some_and(is_id_char) {
continue;
}
let after = &flat[pos + 3..];
let rest: Vec<char> = after.chars().take(240).collect();
let offsets: Vec<usize> = after.char_indices().map(|(b, _)| b).take(240).collect();
// <BS|WB>-<area>-<n>
let mut i = 0;
while i < rest.len() && (rest[i].is_ascii_lowercase() || rest[i].is_ascii_digit()) {
i += 1;
}
if i == 0 || i >= rest.len() || rest[i] != '-' {
continue;
}
let area: String = rest[..i].iter().collect();
i += 1;
let digits_from = i;
while i < rest.len() && rest[i].is_ascii_digit() {
i += 1;
}
if i == digits_from {
continue;
}
let number: String = rest[digits_from..i].iter().collect();
let id = format!("{prefix}{area}-{number}");
let line = line_at(&starts, pos);
// Optional closing backtick, optional 's, optional comma, spaces,
// optional filler `states`, optional parenthesis.
while rest.get(i) == Some(&'`') {
i += 1;
}
if rest.get(i) == Some(&'\'') && rest.get(i + 1) == Some(&'s') {
i += 2;
}
if rest.get(i) == Some(&',') {
i += 1;
}
let spaces_from = i;
while rest.get(i) == Some(&' ') {
i += 1;
}
if i == spaces_from {
continue;
}
for filler in ["states ", "state "] {
let w: Vec<char> = filler.chars().collect();
if rest.len() >= i + w.len() && rest[i..i + w.len()] == w[..] {
i += w.len();
break;
}
}
if rest.get(i) == Some(&'(') {
i += 1;
}
// A reference, then continuations on the same id.
let mut first = true;
loop {
let word_from = i;
while i < rest.len() && rest[i].is_ascii_alphabetic() {
i += 1;
}
let word: String = rest[word_from..i].iter().collect();
let Some((kind, new)) = part_word(&word) else {
break;
};
if rest.get(i) != Some(&' ') || !rest.get(i + 1).is_some_and(|c| c.is_ascii_digit()) {
// A bare spec-block word (`BS-arap-3 SCENARIOS: ...`) on
// the id's own line is the old vocabulary with no number.
let shown_line = offsets
.get(word_from)
.map(|b| line_at(&starts, pos + 3 + b));
let upper = word.len() > 1 && word == word.to_ascii_uppercase();
if first && kind.is_some() && !new && upper && shown_line == Some(line) {
problems.push(format!(
"{at}:{line}: {id} {word}: the old vocabulary; say `statements`, `invariants` or `scenarios` k-m, as bookspec numbers its parts"
));
}
break;
}
let (nums, end) = number_list(&rest, i + 1);
let shown: String = rest[word_from..end].iter().collect();
if !new {
problems.push(format!(
"{at}:{line}: {id} {shown}: the old vocabulary; say `statement`, `invariant` or `scenario` k, as bookspec numbers its parts"
));
} else if let Some(p) = parts.get(&id) {
let (have, name) = match kind {
Some('s') => (p.statements, "statements"),
Some('i') => (p.invariants, "invariants"),
_ => (p.scenarios, "scenarios"),
};
checked += count_of(&nums);
for (low, high) in &nums {
if *low < 1 || *high < *low || *high > have {
problems.push(format!(
"{at}:{line}: {id} {shown}: the record has {have} {name}"
));
}
}
} else {
checked += count_of(&nums);
problems.push(format!("{at}:{line}: {id} {shown}: no such rule"));
}
i = end;
// `, and`, `and`, `with`, `,` and then another part word.
let mut k = i;
let mut moved = false;
for sep in [", and ", ", ", " and ", " with "] {
let w: Vec<char> = sep.chars().collect();
if rest.len() >= k + w.len() && rest[k..k + w.len()] == w[..] {
k += w.len();
moved = true;
break;
}
}
if !moved {
break;
}
i = k;
first = false;
}
}
(checked, problems)
}
fn tracked_text_files(root: &Path) -> Vec<(String, String)> {
let output = std::process::Command::new("git")
.args(["ls-files", "-z"])
.current_dir(root)
.output()
.expect("git ls-files");
assert!(output.status.success(), "git ls-files succeeds");
let listing = String::from_utf8_lossy(&output.stdout).into_owned();
let mut files = Vec::new();
for rel in listing.split('\0').filter(|s| !s.is_empty()) {
if rel.starts_with("plan/") || rel == SELF {
continue;
}
let Ok(text) = std::fs::read_to_string(root.join(rel)) else {
continue;
};
if text.contains('\0') {
continue;
}
files.push((rel.to_string(), text));
}
files
}
#[test]
pub(crate) fn every_sub_reference_names_a_part_its_record_has() {
let parts = all_parts();
assert!(!parts.is_empty(), "the pinned bookspec has records");
let root = repo_root();
let mut checked = 0usize;
let mut bad = Vec::new();
for (rel, text) in tracked_text_files(&root) {
let (n, problems) = scan(&text, &rel, &parts);
checked += n;
bad.extend(problems);
}
println!("sub-references checked: {checked}");
assert!(
checked >= CHECKED_FLOOR,
"sub-references were found ({checked}, floor {CHECKED_FLOOR})"
);
assert!(
bad.is_empty(),
"every sub-reference names a part its record has, in bookspec's words:\n{}",
bad.join("\n")
);
}
fn problems_in(text: &str) -> Vec<String> {
scan(text, "t", &all_parts()).1
}
#[test]
pub(crate) fn a_statement_the_record_lacks_fails() {
// The bounds come from the pinned record, so a record that gains or
// loses a part moves them with it (BS-entry-1 lost a statement and its
// scenario in X-H1c; a hard-coded four would have broken here).
let parts = all_parts();
let id = "BS-arap-2";
let p = parts[id];
let (s, i, c) = (p.statements, p.invariants, p.scenarios);
assert!(s > 1 && i > 1 && c > 1, "{id} has every kind of part");
for text in [
format!("{id} statement {}", s + 50),
format!("{id} statement {}", s + 1),
format!("{id} statement 0"),
format!("{id} invariant {}", i + 1),
format!("{id} scenario {}", c + 1),
"BS-nosuch-9 statement 1".to_string(),
] {
assert_eq!(problems_in(&text).len(), 1, "{text}");
}
for text in [
format!("{id} statement {s}"),
format!("{id} invariant {i}"),
format!("{id} scenario {c}"),
] {
assert_eq!(scan(&text, "t", &parts), (1, vec![]), "{text}");
}
}
#[test]
pub(crate) fn lists_ranges_wraps_and_continuations_are_each_checked() {
let parts = all_parts();
// Every number of a list or range, in the parentheses a comment gives.
assert_eq!(
scan("(BS-arap-2 statements 1, 2 and 4)", "t", &parts),
(3, vec![])
);
assert_eq!(problems_in("(BS-arap-2 statements 1, 2 and 99)").len(), 1);
assert_eq!(problems_in("BS-arap-2 statements 2-99").len(), 1);
// A range counts each of its members; a list each of its numbers.
assert_eq!(scan("BS-arap-2 statements 1-4", "t", &parts), (4, vec![]));
assert_eq!(
scan("BS-arap-2 statements 1-2 and 4", "t", &parts),
(3, vec![])
);
assert_eq!(problems_in("BS-arap-2 statements 3-2").len(), 1);
assert_eq!(problems_in("BS-nosuch-9 statements 1-3").len(), 1);
assert_eq!(scan("BS-nosuch-9 statements 1-3", "t", &parts).0, 3);
// A reference wrapped across a comment prefix reads as one.
assert_eq!(problems_in("/// (BS-arap-2\n/// statement 99)").len(), 1);
assert_eq!(problems_in("//! BS-arap-2 statement\n//! 99").len(), 1);
// A continuation on the same id is checked too, and one in the old
// vocabulary fails.
assert_eq!(
scan("BS-arap-2 invariant 1 and statement 3", "t", &parts),
(2, vec![])
);
assert_eq!(
problems_in("BS-arap-2 invariant 1 and statement 99").len(),
1
);
assert_eq!(problems_in("BS-arap-2 invariant 1 and item 3").len(), 1);
// A date or a number after a list is no reference.
assert_eq!(
scan("BS-arap-2 statement 2, 2026-11-08", "t", &parts),
(1, vec![])
);
// Prose that merely follows an id is no sub-reference.
assert_eq!(
scan("BS-arap-2 states that a rule holds", "t", &parts),
(0, vec![])
);
assert_eq!(
scan("BS-arap-2 rule: debits equal credits", "t", &parts),
(0, vec![])
);
}
#[test]
pub(crate) fn the_old_vocabulary_fails() {
for old in [
"BS-entry-1 item 2",
"BS-entry-1 items 1 and 2",
"BS-entry-1 rule 2",
"BS-entry-1, rule 2",
"BS-entry-1's rules 1, 2",
"BS-entry-1 INVARIANT 2",
"BS-entry-1 INVARIANTS 1-2",
"BS-entry-1 SCENARIO 1",
"BS-entry-1 r 2",
"BS-entry-1 Statement 2",
"(BS-entry-1 item 2)",
"// BS-entry-1\n// INVARIANT 2",
] {
assert_eq!(problems_in(old).len(), 1, "{old:?} fails");
}
// A bare word with no number is no better.
assert_eq!(problems_in("BS-arap-3 SCENARIOS: Net 30, Net 15").len(), 1);
assert_eq!(
problems_in("/// BS-arap-3 INVARIANTS: the due date").len(),
1
);
assert_eq!(problems_in("BS-arap-3 SCENARIO").len(), 1);
// But only on the id's own line, as the text of a spec block runs on
// from its SOURCE line to the next heading.
assert_eq!(
problems_in("SOURCE: BS-arap-3\nSCENARIOS:\n 1. a").len(),
0
);
assert_eq!(problems_in("SOURCE: BS-arap-3.\nINVARIANTS:").len(), 0);
}
#[test]
pub(crate) fn the_old_vocabulary_fails_after_a_closing_backtick() {
for old in [
"`BS-asset-1` rules 23-24",
"(… are `BS-asset-1` rules 23-24.)",
"`BS-asset-1` states (rules 25-26: the dates)",
"`BS-asset-1`'s item 3",
"`BS-asset-1`, INVARIANT 2",
] {
assert_eq!(problems_in(old).len(), 1, "{old:?} fails");
}
// The new vocabulary behind a backtick is checked like any other.
let parts = all_parts();
assert_eq!(
scan("`BS-asset-1` statements 23-24", "t", &parts),
(2, vec![])
);
assert_eq!(
scan(
"`BS-asset-1` states (statements 25-26: the dates)",
"t",
&parts
),
(2, vec![])
);
assert_eq!(problems_in("`BS-asset-1` statements 23-99").len(), 1);
// Prose after a backticked id is no reference.
assert_eq!(
scan("`BS-asset-1` states that a rule holds", "t", &parts),
(0, vec![])
);
}
#[test]
pub(crate) fn product_rule_parts_are_the_numbered_lists_of_their_claims() {
let parts = all_parts();
// WB-ledger-15 states six invariants and seven scenarios.
let p = parts
.get("WB-ledger-15")
.expect("WB-ledger-15 is a product rule");
assert_eq!((p.invariants, p.scenarios, p.statements), (6, 7, 0));
assert_eq!(scan("WB-ledger-15 invariant 3", "t", &parts), (1, vec![]));
assert_eq!(
scan("WB-ledger-15 invariants 1-6 and scenario 7", "t", &parts),
(7, vec![])
);
assert_eq!(problems_in("WB-ledger-15 invariant 7").len(), 1);
assert_eq!(problems_in("WB-ledger-15 scenario 8").len(), 1);
// A product rule has no statements of bookspec's kind.
assert_eq!(problems_in("WB-ledger-15 statement 1").len(), 1);
// The old vocabulary fails here too.
assert_eq!(problems_in("WB-ledger-15 INVARIANT 3").len(), 1);
assert_eq!(problems_in("WB-ledger-15 item 2").len(), 1);
assert_eq!(problems_in("`WB-ledger-15` rule 2").len(), 1);
// A product rule that states no list takes no sub-number.
let (id, p) = parts
.iter()
.find(|(id, p)| id.starts_with("WB-") && p.invariants == 0 && p.scenarios == 0)
.expect("some product rule states no list");
assert_eq!(problems_in(&format!("{id} invariant 1")).len(), 1, "{id}");
assert_eq!((p.statements, p.invariants), (0, 0));
// And one that does not exist takes none either.
assert_eq!(problems_in("WB-nosuch-9 invariant 1").len(), 1);
// A bare product-rule id is no sub-reference.
assert_eq!(problems_in("WB-ledger-15").len(), 0);
assert_eq!(problems_in("the INVARIANT 2 of kernel::settle").len(), 0);
}
+1 -1
View File
@@ -2317,7 +2317,7 @@ proptest! {
}
}
/// BS-partner-3 item 9: party totals and the 1099 worksheet never
/// BS-partner-3 statement 11: party totals and the 1099 worksheet never
/// contradict. For books whose cash accounts are named, whose company
/// card is recorded as a business-card payment method (or that have
/// no card at all: without the method, 2050's name says nothing, so
+1 -1
View File
@@ -798,7 +798,7 @@ fn cash_flow_reconciles_to_change_in_cash() {
// Operating, by the direct method: collected 1,500 (class (a)); paid
// 2,500 for equipment (not a registered asset: operating,
// BS-statement-3 rule 12's limits) and 800 rent (class (d)) = -1,800. Reconciled:
// BS-statement-3 statement 17's limits) and 800 rent (class (d)) = -1,800. Reconciled:
// 3,200 net income - 2,500 increase in AR (4,000 billed - 1,500
// collected) - 2,500 increase in equipment = -1,800.
// Financing: +10,000 owner contribution. Sum = 8,200. Reconciles.
@@ -278,7 +278,7 @@ proptest! {
}
}
/// BS-statement-3 rule 3: the statement of cash flows' per-entry split
/// BS-statement-3 statement 4: the statement of cash flows' per-entry split
/// (`kernel::entry_flows`, Kani `entry_flows_*`) is the same at both
/// instantiations, on balanced and unbalanced lines alike.
#[test]
@@ -325,7 +325,7 @@ proptest! {
);
}
/// BS-statement-3 rule 11: `kernel::constructive` (what a member or
/// BS-statement-3 statement 16: `kernel::constructive` (what a member or
/// lender paid or received for the company; Kani
/// `constructive_nets_to_zero`, `constructive_mirrors`) agrees at both
/// instantiations.
+5 -5
View File
@@ -680,7 +680,7 @@ proptest! {
prop_assert_eq!(scheduled_book_value(a, on).unwrap(), want.book_value);
}
/// BS-asset-1 rule 3 (defect 22), against arithmetic written here: through
/// BS-asset-1 statement 4 (defect 22), against arithmetic written here: through
/// any day k of the life's final month (its d days), accumulated is C +
/// (D − C) × k / d rounded half up to the cent, C the exact charge of
/// the months before (D × each month's days held over its days, over
@@ -719,7 +719,7 @@ proptest! {
}
}
/// BS-asset-1 rule 4 (depreciation_schedule INVARIANT 6; P3 depreciation brief 2.3, R1, R8): through every
/// BS-asset-1 statement 6 (depreciation_schedule INVARIANT 6; P3 depreciation brief 2.3, R1, R8): through every
/// month end of the life, the schedule is the pre-P3 running total
/// (USD, a two-place currency), except where the exact cumulative is a
/// half-cent tie, which the old 28-digit Decimal quotients could round
@@ -937,7 +937,7 @@ proptest! {
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
/// BS-statement-5 item 3: for any tags and any period, the projects'
/// BS-statement-5 statement 3: for any tags and any period, the projects'
/// figures plus the untagged lines' are the period's profit and loss
/// (no line counted twice or lost), each through
/// ledger_core::project_figures.
@@ -1002,7 +1002,7 @@ proptest! {
prop_assert_eq!(exp_sum + untagged_exp, all.total_expenses);
}
/// BS-statement-5 item 7: the snapshot's contribution is
/// WB-statement-7: the snapshot's contribution is
/// project_to_date's net, revenue less direct costs, whatever the
/// tags and sides (a refund debits revenue, a reimbursement credits an
/// expense below zero): the accounts sum to the totals, each month's
@@ -1091,7 +1091,7 @@ proptest! {
}
}
/// BS-statement-5 item 3: project_entries codes its own signs, so the
/// BS-statement-5 statement 2: project_entries codes its own signs, so the
/// posted entries' project amounts must sum to project_to_date's net
/// (with no entry dated after the day), whatever the tags, the sides,
/// a tagged balance-sheet line, or drafts beside them.
+2 -2
View File
@@ -1088,8 +1088,8 @@ fn register_of_no_assets_is_empty() {
/// 1,000.00 and June's 10/30: 5,333.33 scheduled. Before P3 the disposed
/// schedule ended in a plug, so the register showed 12,000.00 and 0.00.
/// The same in the life's final month: on 2026-12-15, 11,483.87. Book
/// value is cost less what the books carry (defect 13, BS-asset-1 rule
/// 8): the fixture's runs, January to March, 3,000.00, so 9,000.00.
/// value is cost less what the books carry (defect 13, BS-asset-1 statement
/// 28): the fixture's runs, January to March, 3,000.00, so 9,000.00.
#[test]
fn register_as_of_a_day_before_a_same_month_disposal_is_prorated() {
let (mut l, _, laptop, _) = register_fixture();
+22 -23
View File
@@ -168,7 +168,7 @@ fn s(t: &str) -> String {
t.to_string()
}
/// The laws every statement keeps (BS-statement-3 rules 8 and 9): each
/// The laws every statement keeps (BS-statement-3 statements 13 and 14): each
/// section is its lines, and its kinds; the sections are the change in
/// cash; net income and the reconciling items are operating.
fn foots(cf: &CashFlowStatement) {
@@ -205,7 +205,7 @@ fn no_distribution(cf: &CashFlowStatement) {
/// The minimal reproduction of defect 1. Property contributed (Dr
/// Equipment 2,340 / Cr Capital), the asset registered, the entry reversed
/// the same day. No cash moved, and the entry and its reversal cancel
/// (BS-statement-3 rules 1, 6): every section 0.00, no lines, no
/// (BS-statement-3 statements 2 and 11): every section 0.00, no lines, no
/// disclosures, footing 0 / 0 / 0. Before the fix: investing −2,340.00
/// against a change in cash of 0.00 (the reversal's credit to the
/// equipment account belonged to no section).
@@ -876,7 +876,7 @@ fn a_property_contribution_is_a_noncash_disclosure() {
assert_eq!(n.label, format!("Laptop contributed (#{e})"));
}
/// D-42, BS-statement-3 rule 11 (ASC 230 is silent on a payment a third
/// D-42, BS-statement-3 statement 16 (ASC 230 is silent on a payment a third
/// party makes on the entity's behalf; PwC FSP 6.9.3.1, DART Roadmap 7.2
/// and BDO Blueprint 3.4 present it by substance, as constructive receipt
/// and disbursement). An expense a member pays personally (Dr Supplies
@@ -1011,7 +1011,7 @@ fn equipment_a_lender_paid_for_is_borrowed_and_invested() {
assert_eq!(cf.net_change_in_cash, x("-500.00"));
}
/// The expense-to-capital case (BS-statement-3 rule 11): a member pays a
/// The expense-to-capital case (BS-statement-3 statement 16): a member pays a
/// vendor for the company and the books credit the member's capital (Dr
/// Supplies 80 / Cr Capital — Member A), no cash. The member paid cash to
/// a third party on the company's behalf, as through 2100; only the form
@@ -1150,7 +1150,7 @@ fn equipment_on_the_sellers_credit_stays_noncash_and_flagged() {
assert!(w.message.contains("borrowed and spent"), "{}", w.message);
}
/// BS-statement-3 rule 6 with rule 11: a payment a member made for the
/// BS-statement-3 statement 11 with statement 16: a payment a member made for the
/// company and its reversal, both in February, drop out together (their
/// flows, constructive cash included, are exact negatives: Kani
/// `constructive_mirrors`); no line, no disclosure, no total moves. The
@@ -1351,7 +1351,7 @@ fn interest_and_guaranteed_payments_charged_to_a_creditor_stay_noncash() {
);
}
/// BS-statement-3 rule 6 (BS-ledger-5: a correction undoes what it corrects): an
/// BS-statement-3 statement 11 (BS-ledger-5: a correction undoes what it corrects): an
/// entry and its reversal both in the period drop out of every line and
/// disclosure, and no total moves (their flows are exact negatives, Kani
/// `entry_flows_of_a_reversal_mirror`).
@@ -1390,7 +1390,7 @@ fn an_entry_and_its_reversal_in_the_period_drop_out() {
assert_eq!(cf.net_change_in_cash, before.net_change_in_cash);
}
/// BS-statement-3 rule 6: a reversal shown alone (its original in an
/// BS-statement-3 statement 11: a reversal shown alone (its original in an
/// earlier period) is labelled "Reversal of #N — <N's description>" and
/// listed under its original's kind, never as a distribution (D1-c).
#[test]
@@ -1414,7 +1414,7 @@ fn a_reversal_alone_is_labelled_reversal_of() {
no_distribution(&cf);
}
/// BS-statement-3 rules 4 and 6: a reversal takes its chain root's
/// BS-statement-3 statements 5 and 11: a reversal takes its chain root's
/// sections, class and kind, with its own sign. Reversing January's cash
/// sale at a 300 gain in February: investing −500 under "Proceeds from
/// sales of property and equipment", G +300 (the gain, reversed, is still
@@ -1766,7 +1766,7 @@ fn operating_classes_follow_asc_230_10_45_25() {
/// ASC 230-10-45-28(b): depreciation is an item of net income with no
/// cash effect, a reconciling item; it is not an investing or financing
/// activity, so nothing is disclosed (BS-statement-3 rule 7).
/// activity, so nothing is disclosed (BS-statement-3 statement 12).
#[test]
fn depreciation_is_reconciling_not_disclosed() {
let mut b = funded();
@@ -1862,7 +1862,7 @@ fn operating_reconciliation_ties_to_operating_cash() {
);
}
/// BS-period-1 and BS-statement-3 rule 10: a period close moves earnings into
/// BS-period-1 and BS-statement-3 statement 15: a period close moves earnings into
/// equity; it earns and spends nothing, so it is never in the statement.
#[test]
fn closing_entries_never_appear() {
@@ -1881,7 +1881,7 @@ fn closing_entries_never_appear() {
assert!(!text.contains(&format!("entry: {close},")));
}
/// The period is [start, end] inclusive (BS-statement-3 rule 1): a
/// The period is [start, end] inclusive (BS-statement-3 statement 2): a
/// contribution on the start date is a flow, not opening cash.
#[test]
fn cash_flow_starts_counting_on_the_start_date() {
@@ -1921,8 +1921,7 @@ fn a_transfer_between_cash_accounts_is_not_a_flow() {
assert!(cf.noncash_disclosures.is_empty());
}
/// Review round 2, footing in odd shapes (BS-statement-3 rules 1, 6, 9,
/// 11), by hand:
/// Review round 2, footing in odd shapes (BS-statement-3 statements 2, 11, 14 and 16), by hand:
/// - two cash accounts in one entry, a transfer less its fee (Dr Savings
/// 99, Dr Supplies 1 / Cr Cash 100): only the net, −1, moves cash,
/// operating (d); no investing or financing;
@@ -2217,7 +2216,7 @@ fn financing_lists_each_members_contributions_and_distributions() {
/// "at a minimum" apart from the other classes, so an entry's operating
/// cash is classed kind by kind: its interest lines are (b) or (e)
/// whatever else it settles, the rest by its structure (BS-statement-3
/// rule 5). By hand:
/// statement 7). By hand:
/// - a payment of 900 on a loan the settings leave operating, with 100
/// interest (Dr 2500 900, Dr 6200 100 / Cr cash 1,000): (d) −900 and
/// (e) −100, not (e) −1,000;
@@ -2547,7 +2546,7 @@ fn a_reversed_bill_payment_leaves_the_purchase_unpaid() {
}
// ---------------------------------------------------------------------------
// Role refusals (BS-statement-3 rule 2) and the footing check (rule 9).
// Role refusals (BS-statement-3 statement 3) and the footing check (statement 14).
// ---------------------------------------------------------------------------
fn refused(b: &Books, cash: &[&str], financing: &[&str], investing: &[&str]) -> String {
@@ -2617,7 +2616,7 @@ fn a_registered_asset_account_cannot_be_cash() {
assert!(m.contains("a registered fixed asset's account"), "{m}");
}
/// BS-statement-3 rule 9: any difference between the sections and the
/// BS-statement-3 statement 14: any difference between the sections and the
/// change in cash is an engine error, never a statement.
#[test]
fn foot_refuses_any_difference() {
@@ -3244,7 +3243,7 @@ fn a_disposals_depreciation_credit_back_is_depreciation() {
assert_eq!(cf.cash_from_investing, x("975.00"));
}
/// BS-statement-3 rule 5 (the P3 cutover review's open point 2): ASC
/// BS-statement-3 statement 8 (the P3 cutover review's open point 2): ASC
/// 230-10-45-17(c), "Cash payments to governments for taxes, duties,
/// fines, and other fees or penalties", is not 45-17(b)'s "Cash payments
/// to other suppliers and employees": a state's filing fee booked to an
@@ -3316,7 +3315,7 @@ fn a_payment_to_a_government_is_other_operating() {
assert_eq!((line.class, line.amount), (Some(OtherPayments), x("75.00")));
}
/// BS-statement-3 rule 5: the payee decides on any account, and the tax
/// BS-statement-3 statement 8: the payee decides on any account, and the tax
/// category still does without one: a license on `taxes_licenses` with no
/// party is (g). An entry naming a government and a supplier together
/// (half each) is split by their shares, as ASC 230-10-45-22 has each
@@ -3371,7 +3370,7 @@ fn a_government_payee_moves_a_fee_on_any_account() {
assert_eq!(classes(&cf, shared), [(OtherPayments, x("-100.00"))]);
}
/// BS-statement-3 rule 5: a split by shares that leaves an odd cent rounds
/// BS-statement-3 statement 8: a split by shares that leaves an odd cent rounds
/// the government's part half to even, the supplier's the rest, so the
/// line still sums to the payment; its reversal next month mirrors it to
/// the cent. Fixed amounts split as given.
@@ -3450,7 +3449,7 @@ fn a_shared_government_payment_splits_to_the_cent() {
);
}
/// BS-statement-3 rule 5: a reversal takes its original's payee, so the
/// BS-statement-3 statement 8: a reversal takes its original's payee, so the
/// pair always lands in one class and nets. A state's fee paid in
/// February and reversed in March: (g) both. The books keep a reversal
/// chain's parties one (Ledger::set_entry_parties INVARIANT 5): tagging
@@ -3500,7 +3499,7 @@ fn a_reversal_takes_its_originals_payee() {
assert_eq!(classes(&b), both(ToSuppliersAndEmployees));
}
/// BS-statement-3 rules 5 and 11: a payment shared between a state and an
/// BS-statement-3 statements 8 and 16: a payment shared between a state and an
/// agent that a member paid personally (Dr 6000 137.00 / Cr 2100, the
/// members' financing account) is borrowed and spent, and its spending is
/// split by the parties' shares as a bank payment's is, the part no bank
@@ -3577,7 +3576,7 @@ fn a_shared_government_payment_a_member_paid_splits_both_ways() {
assert_eq!(cf.net_change_in_cash, Decimal::ZERO);
}
/// BS-statement-3 rule 5 (CONVENTION): payroll keeps its structure. Taxes
/// BS-statement-3 statement 9 (CONVENTION): payroll keeps its structure. Taxes
/// withheld from employees and remitted to the tax agency are the
/// employees' pay (45-17(b), "Cash payments to other suppliers and
/// employees"), and the payroll payables mix them with the employer's
@@ -3636,7 +3635,7 @@ fn a_payroll_remittance_to_a_tax_agency_stays_pay() {
assert_eq!(class(employer), Some(OtherPayments));
}
/// BS-statement-3 rule 5: a government selling goods or services is a
/// BS-statement-3 statement 8: a government selling goods or services is a
/// supplier (45-17(b), "for other goods or services"), not 45-17(c)'s
/// taxes, fees or penalties: the post office named with the `vendor`
/// role, postage stays (d). The roles decide, so a post office given the
@@ -1,12 +1,12 @@
//! An invoice's or bill's lines name their projects (BS-statement-5 item
//! 8): the posted entry's revenue or expense side is one line per project,
//! An invoice's or bill's lines name their projects (BS-statement-5 statement
//! 6): the posted entry's revenue or expense side is one line per project,
//! the untagged lines' as one; the receivable or payable line, and the
//! payments, never take one.
//!
//! ```text
//! GOAL: a client project's invoiced revenue and a contractor's billed
//! cost count toward the project, every other figure as before.
//! SOURCE: BS-statement-5 items 3 and 8 (job costing), BS-statement-3 (the
//! SOURCE: BS-statement-5 statements 2, 3 and 6 (job costing, and the
//! projects with the untagged lines partition the P&L), BS-1099-1 and
//! BS-partner-3 (1099 and party figures follow the money, not the tags).
//! ```
@@ -170,7 +170,7 @@ fn a_bills_cost_is_one_line_per_project_and_the_payable_none() {
}
/// Reversing a tagged invoice's or bill's entry carries each line's
/// project to the reversal (BS-statement-5 item 3: each line on its normal side), so
/// project to the reversal (BS-statement-5 statement 2: each line on its normal side), so
/// every project nets back to zero; a partial payment, cash against the
/// receivable, moves no project figure.
#[test]
@@ -295,7 +295,7 @@ fn a_line_naming_an_unknown_project_is_refused_whole() {
}
/// Finished and abandoned projects still take a document's lines (BS-statement-5
/// item 5: a late cost, a final invoice).
/// statement 7: a late cost, a final invoice).
#[test]
fn a_finished_project_still_takes_an_invoice() {
let mut b = books();
+86 -16
View File
@@ -110,7 +110,7 @@ impl Books {
}
/// Every control account's tie-out holds: no difference (BS-arap-2
/// INVARIANT 1).
/// invariant 1).
fn ties(&self, on: NaiveDate) {
for c in self.l.control_check(on).unwrap() {
assert_eq!(c.difference, Decimal::ZERO, "{c:?}");
@@ -1067,7 +1067,7 @@ fn out_of_bounds_documents_are_listed_not_aged() {
/// Reversing a legacy hand line takes it off; reversing that reversal
/// would put it back, and is refused: no command adds an untagged control
/// line (BS-arap-2 INVARIANT 1 and item 3; first review of S1).
/// line (BS-arap-2 invariant 2 and statement 11; first review of S1).
#[test]
fn putting_back_a_removed_hand_line_is_refused() {
let mut b = books();
@@ -1204,7 +1204,7 @@ fn a_chain_counts_in_order() {
// Write-offs (plan P4b S7; BS-arap-5)
// ---------------------------------------------------------------------------
/// BS-arap-2 SCENARIO 7 and BS-arap-5 INVARIANT 1: half of an invoice paid, the rest
/// BS-arap-2 scenario 7 and BS-arap-5 invariant 1: half of an invoice paid, the rest
/// written off, reads Written off with 50 paid and 50 written off, and
/// receivables falls by the write-off alone.
#[test]
@@ -1261,7 +1261,7 @@ fn half_paid_rest_written_off_is_written_off() {
assert!(check.iter().all(|c| c.difference.is_zero()));
}
/// BS-arap-5 INVARIANT 3: a cash-basis company never counted the invoice as
/// BS-arap-5 statement 6: a cash-basis company never counted the invoice as
/// income, so it has no basis to deduct (IRC §166; Treas. Reg.
/// §1.166-1(e)).
#[test]
@@ -1308,7 +1308,7 @@ fn write_off_refused_on_cash_basis() {
);
}
/// BS-arap-5 INVARIANT 1: at most what is owed, a partial write-off allowed
/// BS-arap-5 invariant 2 and statement 3: at most what is owed, a partial write-off allowed
/// (Treas. Reg. §1.166-3(a)); more is refused, naming what is owed, and
/// nothing changes.
#[test]
@@ -1351,7 +1351,7 @@ fn write_off_above_outstanding_refused() {
assert_eq!((st.paid, st.written_off), (cents(4_000), cents(6_000)));
}
/// D-49's same-year recovery, and BS-arap-5 INVARIANT 2: reversing the
/// D-49's same-year recovery, and BS-arap-5 invariant 4: reversing the
/// write-off re-instates the debt (it is not a new movement), and the
/// payment then recorded settles it; a recovery is income, never a
/// payment event.
@@ -1502,7 +1502,7 @@ fn days(b: &Books) -> Vec<NaiveDate> {
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
/// BS-arap-2 INVARIANTS 1, 2 and 6 over random histories of creates,
/// BS-arap-2 invariants 1, 2, 3, 6 and 9 over random histories of creates,
/// payments, voids, reversals of any entry and refused hand lines: at
/// every date the control accounts equal their documents (no
/// difference, nothing unattached: no command adds a hand line), each
@@ -1538,9 +1538,9 @@ proptest! {
}
}
/// BS-arap-2 INVARIANT 5: the aging as of a day partitions what the
/// BS-arap-2 invariant 8: the aging as of a day partitions what the
/// documents owe then (in books these commands write, none owes less
/// than nothing). INVARIANT 4 (Store, replay and Snapshot agree) is
/// than nothing). Invariant 7 (Store, replay and Snapshot agree) is
/// ledger-store's `status_is_a_function_of_journal_and_date`.
#[test]
fn aging_partitions_what_documents_owe(ops in prop::collection::vec(arb_op(), 0..30)) {
@@ -1562,7 +1562,7 @@ proptest! {
}
}
/// BS-arap-2 INVARIANT 3: reversing a tagged entry moves its documents by
/// BS-arap-2 invariant 4: reversing a tagged entry moves its documents by
/// exactly the opposite of the entry's own tagged lines from the
/// reversal's day (read from the entry reversed, not from the mirror,
/// so a mirror that lost its tag is caught); reversing that reversal
@@ -1691,8 +1691,9 @@ fn custom_terms_are_due_on_the_date_they_give() {
assert!(serde_json::from_value::<Terms>(stray).is_err());
}
/// BS-arap-3 SCENARIOS: Net 30, Net 15 EOM, a leap day, due on receipt, a
/// custom date, and the 9999-12 bound refused instead of panicking.
/// BS-arap-3 scenarios 1-5 (Net 30, Net 15 EOM, a leap day, due on receipt,
/// and the 9999-12 bound refused instead of panicking) and statement 1 (a
/// custom date).
#[test]
fn terms_derive_due_dates() {
let net30 = Terms::new(TermsKind::Net(30), None).unwrap();
@@ -1725,7 +1726,7 @@ fn terms_derive_due_dates() {
assert!(Terms::new(TermsKind::NetEom(3_651), None).is_err());
}
/// BS-arap-3 INVARIANT 2: the discount's bound, its date, and the terms that
/// BS-arap-3 invariant 2: the discount's bound, its date, and the terms that
/// cannot carry one.
#[test]
fn discount_bounds_and_late_reason() {
@@ -1795,7 +1796,7 @@ fn discount_bounds_and_late_reason() {
assert_eq!(kernel::discount_max(cents(-1), 200), None);
}
/// BS-arap-3 INVARIANT 3: the canonical spellings read back as they print.
/// BS-arap-3 invariant 3: the canonical spellings read back as they print.
#[test]
fn terms_describe_and_parse_round_trip() {
for text in [
@@ -2286,7 +2287,7 @@ fn bill_on_terms_with_discount() {
}
/// A discount taken after the discount date needs a reason (BS-arap-6
/// INVARIANT 2); a bill with an asset or prepaid line refuses one with the
/// invariant 6); a bill with an asset or prepaid line refuses one with the
/// D-49 remedy, and none of the refusals changes the books.
#[test]
fn late_discount_needs_a_reason() {
@@ -2433,7 +2434,7 @@ fn a_fee_posts_gross_to_receivables_and_net_to_the_bank() {
/// A payment that settles more than one document names its lines in
/// application order, and two applications on one document are refused:
/// each document's bound is one bound (BS-arap-6 INVARIANTS 1 and 2).
/// each document's bound is one bound (BS-arap-6 invariants 4 and 5).
#[test]
fn a_settlement_names_its_lines_and_refuses_a_document_twice() {
use ledger_core::{Application, DocRef, SettleParams};
@@ -2553,3 +2554,72 @@ fn discount_on_an_asset_bill_is_refused_with_the_remedy() {
);
b.ties(d(2026, 4, 5));
}
/// A processor cannot keep more than it was paid: a fee above the cash is
/// refused as its own refusal (`FeeAboveCash`, BS-arap-6) and changes
/// nothing. A fee equal to the cash is a different refusal (the deposit
/// would be nothing), and a fee within the cash still posts.
#[test]
fn a_fee_above_the_cash_is_refused_and_changes_nothing() {
use ledger_core::{Application, DocRef, Fee, SettleParams};
let mut b = books();
let first = b.invoice(d(2026, 4, 1), 10_000);
let second = b.invoice(d(2026, 4, 2), 5_000);
let params = |fee: i64| SettleParams {
date: d(2026, 4, 5),
description: "Card payment".into(),
cash_account: b.bank,
party: b.customer,
applications: vec![
Application {
doc: DocRef::Invoice(first),
cash: cents(10_000),
discount: Decimal::ZERO,
discount_reason: None,
},
Application {
doc: DocRef::Invoice(second),
cash: cents(5_000),
discount: Decimal::ZERO,
discount_reason: None,
},
],
fee: Some(Fee {
amount: cents(fee),
account: None,
vendor: None,
}),
instrument: None,
reference: None,
};
let posted_before = b.l.posted_entries().count();
let first_before = b.state(DocRef::Invoice(first), d(2026, 4, 5));
let second_before = b.state(DocRef::Invoice(second), d(2026, 4, 5));
// The cash is 150.00 across two applications; a fee of 150.01 is above it.
let refused = b.l.settle(params(15_001));
assert!(
matches!(
refused,
Err(LedgerError::FeeAboveCash { fee, cash })
if fee == cents(15_001) && cash == cents(15_000)
),
"{refused:?}"
);
assert_eq!(b.l.posted_entries().count(), posted_before);
assert_eq!(b.state(DocRef::Invoice(first), d(2026, 4, 5)), first_before);
assert_eq!(
b.state(DocRef::Invoice(second), d(2026, 4, 5)),
second_before
);
assert_eq!(b.l.account_balance(b.bank).unwrap(), Decimal::ZERO);
// The fee equal to the cash is the other refusal, not this one.
assert!(matches!(
b.l.settle(params(15_000)),
Err(LedgerError::InvalidSettlement(_))
));
assert_eq!(b.l.posted_entries().count(), posted_before);
// A fee within the cash posts: 150.00 gross, 3.00 fee, 147.00 deposit.
b.l.settle(params(300)).unwrap();
assert_eq!(b.l.account_balance(b.bank).unwrap(), cents(14_700));
b.ties(d(2026, 4, 5));
}
+3 -3
View File
@@ -1461,10 +1461,10 @@ fn entry_flow_takes_across_in_order_until_used_up() {
);
}
/// Oracle: shares::target DEFINITIONS, case 3 (BS-partner-3): members
/// Oracle: shares::target DEFINITIONS (BS-partner-3 statement 3 (c)): members
/// named on an entry moving no money split what moved equity, E (here
/// −4.00 of a draft not yet balanced), received, in kind (the equipment's
/// 10.00, at most |E|); case 5: with a party named who isn't a member,
/// 10.00, at most |E|); (e): with a party named who isn't a member,
/// the total debits, direction neither, counting nothing.
#[test]
fn a_share_target_without_money_is_the_capital_or_the_debits() {
@@ -1919,7 +1919,7 @@ mod shares {
assert_eq!((a.paid, a.received), (Decimal::ZERO, Decimal::ZERO));
}
/// BS-partner-3 item 3 (capital first): a members' entry counts what
/// BS-partner-3 statement 3 (capital first): a members' entry counts what
/// moved their capital, not other money on it: 300.00 in, 200.00 of it
/// Tobin's capital and 100.00 an expense refunded, is Tobin's 200.00
/// received (cash) and nothing of Morgan's. (Before P3 the 300.00 net
+10 -10
View File
@@ -550,7 +550,7 @@ fn defect14_shares_take_the_partys_side_and_reversals_flip() {
);
}
/// BS-partner-3 item 4: on the member-only entries, basis all is the statement of
/// BS-partner-3 statement 6: on the member-only entries, basis all is the statement of
/// members' equity (contributions and distributions, the same dates), and
/// basis cash is the K-1 worksheet's cash contributions.
#[test]
@@ -655,7 +655,7 @@ fn defect24_an_accrual_through_another_liability_counts_once() {
assert_eq!(b.totals(c, Basis::All), (Decimal::ZERO, d("1200.00")));
}
/// Defect 24 and BS-partner-3 item 6: a credit to what the company owes a party
/// Defect 24 and BS-partner-3 statement 8: a credit to what the company owes a party
/// itself never counts as paying it. A fee on the issuer's own card is a
/// bill from the issuer (counted when the card is paid); a distribution
/// still owed to a member counts when it is paid; equipment bought on the
@@ -778,7 +778,7 @@ fn a_distribution_owed_counts_twice_until_the_members_are_named_its_creditors()
/// again when paid (400.00); now it counts nothing until it is paid, then
/// 200.00, once, on both bases (Helvering v. Price; party_target
/// INVARIANT 2). The statement of members' equity counts it when declared:
/// party totals catch up when it is paid (BS-partner-3 item 4's conditions).
/// party totals catch up when it is paid (BS-partner-3 statement 6's conditions).
#[test]
fn defect24_a_distribution_declared_to_a_payable_counts_once_when_paid() {
let mut b = books();
@@ -829,7 +829,7 @@ fn defect24_a_distribution_declared_to_a_payable_counts_once_when_paid() {
assert_eq!(b.totals(t, Basis::Cash), (d("300.00"), Decimal::ZERO));
}
/// BS-partner-3 item 3: a distribution's cash is the money it paid and its in
/// BS-partner-3 statement 3: a distribution's cash is the money it paid and its in
/// kind the property it gave. Equipment carried at 1,000.00 less 300.00
/// depreciated, and 100.00 in cash, distributed: 100.00 cash and 700.00
/// in kind (it read 800.00 in kind and no cash, the equipment's cost
@@ -868,7 +868,7 @@ fn a_distribution_of_money_and_depreciated_property_splits_by_what_moved() {
assert_eq!(b.resolved(gain).1, vec![part(t, "900.00", "0", "900.00")]);
}
/// Defect 24 and the card rule (BS-partner-3 item 5): a gift card the company
/// Defect 24 and the card rule (BS-partner-3 statement 7): a gift card the company
/// sold is deferred revenue, a promise, though its account's name says
/// "card". It counted as received when sold and again when redeemed
/// (200.00); now once, when the money came in. A card the company pays
@@ -892,7 +892,7 @@ fn defect24_a_gift_card_sold_is_received_once() {
assert_eq!(b.totals(c, Basis::All), (Decimal::ZERO, d("100.00")));
}
/// BS-partner-3 item 5 and `parties::card_accounts` INVARIANTS 1-4: one rule for
/// BS-partner-3 statement 7 and `parties::card_accounts` INVARIANTS 1-4: one rule for
/// what a card is. Before any business card is recorded, the liabilities
/// whose names say "card" but not "gift" (2050 Business Card; never 2410
/// Gift Card Liability), less a member's card's account; once one is
@@ -958,7 +958,7 @@ fn a_card_is_a_recorded_business_card_else_a_liability_named_card() {
assert_eq!(b.resolved(on_2050).0.direction, Direction::Neither);
}
/// BS-partner-3 item 3, case 3: E is the movement of equity other than retained
/// BS-partner-3 statement 3 (c): E is the movement of equity other than retained
/// earnings, so a members' entry reads as the statement of members' equity
/// reads it. Retained earnings given up for equipment moves no member's
/// capital: neither, as the statement shows no distribution. Retained
@@ -1035,7 +1035,7 @@ fn a_refund_is_received_from_the_vendor() {
assert_eq!(b.totals(v, Basis::Cash), (d("100.00"), d("20.00")));
}
/// BS-partner-3 item 3 (capital first): a mixed contribution is split into money
/// BS-partner-3 statement 3 (capital first): a mixed contribution is split into money
/// and property exactly as the K-1 worksheet splits it (its SCENARIO 3),
/// whichever member the shares list first; an expense a member pays
/// straight to capital is cash, as on the K-1 (k1 INVARIANT 3); a debt
@@ -1168,7 +1168,7 @@ fn a_members_entry_keeps_its_reading_after_they_leave() {
);
}
/// BS-partner-3 item 3, case 1: a period's closing entry moves nothing with
/// BS-partner-3 statement 3 (a): a period's closing entry moves nothing with
/// anyone: direction neither, its members' part their income allocated
/// (credited to their capital: negative), counted in no total.
#[test]
@@ -1661,7 +1661,7 @@ proptest! {
/// account converted to capital, some through their distributions
/// accounts, some declared to distributions payable and paid later,
/// and reverse some of it later in the year. For each member, over
/// every span from the year's start to any date (BS-partner-3 item 4's
/// every span from the year's start to any date (BS-partner-3 statement 6's
/// conditions hold: a reversal in such a span always has its original
/// in it): basis all is the statement of members' equity's
/// contributions and distributions, but for a distribution declared
+3 -3
View File
@@ -534,7 +534,7 @@ fn a_reversal_nets_a_project_to_zero() {
let entries = project_entries(&b.l, c);
assert_eq!(entries, vec![(r, cents(180_000)), (e, cents(-180_000))]);
// Nothing left on an account, but two lines tagged: it breaks even,
// it isn't untagged (BS-statement-5 item 7).
// it isn't untagged (WB-statement-7).
assert!(t.expenses_by_account.is_empty());
assert_eq!((t.revenue_lines, t.expenses_lines), (0, 2));
assert!(t.any_tagged());
@@ -652,7 +652,7 @@ fn differs_from_names_projects() {
assert_eq!(a.l.differs_from(&before), vec!["projects"]);
}
/// BS-statement-5 item 7: the margin is the contribution's share of
/// WB-statement-7: the margin is the contribution's share of
/// revenue, one place, half to even, and none without revenue.
#[test]
fn contribution_margin_is_one_place_and_none_without_revenue() {
@@ -671,7 +671,7 @@ fn contribution_margin_is_one_place_and_none_without_revenue() {
assert_eq!(pct(Decimal::MAX, cents(1)), None, "never panics");
}
/// BS-statement-5 item 7: each month's net to date opens on the lines
/// WB-statement-7: each month's net to date opens on the lines
/// before the months (a deposit last year) and ends on the net to date;
/// a reimbursement credited above its cost leaves the expense below zero.
#[test]
+2 -2
View File
@@ -2505,9 +2505,9 @@ proptest! {
/// the cash part of the equity and designated-debt movements: each
/// entry's cash applied to the sections moving against it, operating,
/// investing, financing, each up to its own movement (BS-statement-3
/// rule 3), then to the kinds within each section in their order;
/// statement 4), then to the kinds within each section in their order;
/// plus what the loan or a member's capital paid or received for the
/// company (rule 11, D-42): the loan pays for operating lines (the
/// company (statement 16, D-42): the loan pays for operating lines (the
/// balance-sheet ones first) and receives for revenue and expense;
/// capital pays and receives for revenue and expense only. Written
/// here apart from the kernel.
+2 -2
View File
@@ -1444,7 +1444,7 @@ fn lines(ls: &[ledger_core::reports::CashFlowLine]) -> Vec<(String, Decimal)> {
/// amounts borrowed"): borrowing and repayment are separate lines, one
/// per entry, borrowing first (each lender's, by code), then repayments.
/// The software the owner paid personally is borrowed from the owner and
/// spent on its date (BS-statement-3 rule 11, D-42: constructive receipt
/// spent on its date (BS-statement-3 statement 16, D-42: constructive receipt
/// and disbursement). Financing: +100 + 1,000 − 100 − 400 = 600; nothing
/// is disclosed.
#[test]
@@ -1487,7 +1487,7 @@ fn a_loan_the_entity_makes_is_investing_gross() {
assert_eq!(cf.cash_from_investing, dec(-300));
}
/// Oracle: D-42 (BS-statement-3 rule 11; ASC 230 is silent on a payment
/// Oracle: D-42 (BS-statement-3 statement 16; ASC 230 is silent on a payment
/// made on the entity's behalf, PwC FSP 6.9.3.1 and DART Roadmap 7.2
/// present it as constructive receipt and disbursement). The owner paying
/// software personally is cash the company borrowed (financing +100) and