merge: the adapter runs settlements, recoveries, invoice numbers and vendor references; a fee above the cash is its own refusal (X-H1b's wanderbooks half; reviewed, re-checked)

Wanderbooks passes every bookspec example for the options it picked: 80
run, 80 passed, 11 for options it did not pick. The settlement refusal
that read a fee above the cash out of one half of an error message's 'or'
is now a typed refusal (LedgerError::FeeAboveCash), checked before the
kernel's settle at the same point, so no refusal's order changes; the
remaining message names only what is left (an amount too large, a
negative fee). BS-arap-10's pick is ignore-case-spaces-and-hyphens, as
plan P4b S4 decided and the engine always did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-11-09 01:56:38 -07:00
commit 81bc16c386
11 files changed
+377 -23

No files matched your search

+18 -3
View File
@@ -749,9 +749,24 @@ pub enum LedgerError {
#[error("{0}")] #[error("{0}")]
InvalidFee(String), InvalidFee(String),
/// A settlement's figures can't be exact: the cash and discounts /// A processor's fee is above the cash it was withheld from: a
/// don't cover the applications, or the fee leaves a negative deposit /// processor cannot keep more than it was paid (BS-arap-6). A fee equal
/// (BS-arap-6 INVARIANT 1). /// to the cash is [`LedgerError::InvalidSettlement`]: the deposit would
/// be nothing.
#[error(
"the processor's fee of {fee} is above the cash of {cash}: a processor can't keep more than it was paid"
)]
FeeAboveCash {
/// The fee asked for.
fee: Decimal,
/// The settlement's cash, summed over its applications.
cash: Decimal,
},
/// A settlement's figures can't be exact (BS-arap-6 INVARIANT 1): an
/// amount too large to add, a negative fee, or a fee that leaves
/// nothing to deposit; a fee above the cash is
/// [`LedgerError::FeeAboveCash`].
#[error("{0}")] #[error("{0}")]
InvalidSettlement(String), InvalidSettlement(String),
+14 -1
View File
@@ -6703,9 +6703,22 @@ impl Ledger {
discounts.push(app.discount); discounts.push(app.discount);
} }
let fee_amount = params.fee.as_ref().map_or(Decimal::ZERO, |f| f.amount); let fee_amount = params.fee.as_ref().map_or(Decimal::ZERO, |f| f.amount);
// A fee above the cash is its own refusal; the kernel would also
// answer `None` for it, with no way to say which of its refusals it
// was. A sum that overflows is left to the kernel (too large).
if let Some(total_cash) = cash
.iter()
.try_fold(Decimal::ZERO, |sum, c| sum.checked_add(*c))
&& fee_amount > total_cash
{
return Err(LedgerError::FeeAboveCash {
fee: fee_amount,
cash: total_cash,
});
}
let settlement = kernel::settle(&cash, &discounts, fee_amount).ok_or_else(|| { let settlement = kernel::settle(&cash, &discounts, fee_amount).ok_or_else(|| {
LedgerError::InvalidSettlement( LedgerError::InvalidSettlement(
"the cash and discounts don't cover the applications exactly, or the fee is above the cash" "the settlement's figures aren't exact: an amount is too large, or the fee is negative"
.into(), .into(),
) )
})?; })?;
+7 -1
View File
@@ -38,7 +38,11 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> {
); );
only(x.basis.is_some(), "basis", &["party_totals"]); only(x.basis.is_some(), "basis", &["party_totals"]);
only(x.payee.is_some(), "payee", &["vendor_1099"]); 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.of.is_some(), "of", &["aging"]);
only( only(
x.code.is_some(), x.code.is_some(),
@@ -105,6 +109,8 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> {
"project" => check_project(b, x), "project" => check_project(b, x),
"aging" => check_aging(b, x), "aging" => check_aging(b, x),
"document_dates" => check_document_dates(b, x), "document_dates" => check_document_dates(b, x),
"document" => check_document(b, x),
"invoice_numbers" => check_invoice_numbers(b, x),
q => { q => {
let &(_, by) = FORMAT_QUERIES let &(_, by) = FORMAT_QUERIES
.iter() .iter()
@@ -144,6 +144,17 @@ pub(crate) fn refusal(e: &LedgerError) -> String {
LedgerError::InvalidSchedule(_) => "invalid_schedule", LedgerError::InvalidSchedule(_) => "invalid_schedule",
LedgerError::UntaggedControlLine { .. } => "untagged_control_line", LedgerError::UntaggedControlLine { .. } => "untagged_control_line",
LedgerError::PaymentBeforeDocument { .. } => "payment_before_document", 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::UnbalancedEntry { .. } => "unbalanced",
LedgerError::TooFewLines => "too_few_lines", LedgerError::TooFewLines => "too_few_lines",
LedgerError::NegativeAmountLine => "negative_amount", LedgerError::NegativeAmountLine => "negative_amount",
+1 -1
View File
@@ -120,7 +120,7 @@ pub(crate) const PICKS: &[(Area, u32, &str)] = &[
(Area::Arap, 7, "due-today-is-current"), (Area::Arap, 7, "due-today-is-current"),
(Area::Arap, 8, "as-of-the-day"), (Area::Arap, 8, "as-of-the-day"),
(Area::Arap, 9, "refuse-a-payment-before-its-document"), (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, 11, "reverse-then-plain-entry"),
(Area::Arap, 12, "gross-when-taken"), (Area::Arap, 12, "gross-when-taken"),
(Area::Arap, 13, "gross"), (Area::Arap, 13, "gross"),
+125 -6
View File
@@ -14,6 +14,8 @@ impl Books<'_> {
("invoice", e.invoice.is_some()), ("invoice", e.invoice.is_some()),
("write_off", e.write_off.is_some()), ("write_off", e.write_off.is_some()),
("payment", e.payment.is_some()), ("payment", e.payment.is_some()),
("settlement", e.settlement.is_some()),
("recovery", e.recovery.is_some()),
("run_depreciation", e.run_depreciation.is_some()), ("run_depreciation", e.run_depreciation.is_some()),
("dispose_asset", e.dispose_asset.is_some()), ("dispose_asset", e.dispose_asset.is_some()),
("run_schedules", e.run_schedules.is_some()), ("run_schedules", e.run_schedules.is_some()),
@@ -22,7 +24,7 @@ impl Books<'_> {
match kinds.iter().filter(|(_, given)| *given).collect::<Vec<_>>()[..] { match kinds.iter().filter(|(_, given)| *given).collect::<Vec<_>>()[..] {
[(kind, _)] => kind, [(kind, _)] => kind,
_ => panic!( _ => 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 or register_schedule",
self.ex.id self.ex.id
), ),
} }
@@ -36,7 +38,11 @@ impl Books<'_> {
// disposal is dated; the other commands date their own entries, // disposal is dated; the other commands date their own entries,
// and every command describes its own. // and every command describes its own.
let own = matches!(kind, "lines" | "reverses" | "close" | "bill" | "invoice"); 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!( assert_eq!(
e.date.is_some(), e.date.is_some(),
dated, dated,
@@ -74,8 +80,8 @@ impl Books<'_> {
"{ex} event {n}: {kind} is tagged with no parties or payment method" "{ex} event {n}: {kind} is tagged with no parties or payment method"
); );
assert!( assert!(
e.refused.is_none() || !matches!(kind, "close" | "bill" | "invoice"), e.refused.is_none() || !matches!(kind, "close" | "invoice"),
"{ex} event {n}: refused is for a reversal, an entry or a command, which the books take whole or not at all" "{ex} event {n}: refused is for a reversal, an entry, a bill or a command, which the books take whole or not at all"
); );
assert!( assert!(
!(e.older && e.refused.is_some()), !(e.older && e.refused.is_some()),
@@ -89,6 +95,14 @@ impl Books<'_> {
e.payment.is_none() || kind == "payment", e.payment.is_none() || kind == "payment",
"{ex} event {n}: a payment is its own event" "{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 /// Take event `n` as the books take it, keep what it posted and tag it
@@ -197,9 +211,18 @@ impl Books<'_> {
"{what}: entry {id}, which it made, is posted" "{what}: entry {id}, which it made, is 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"); 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 /// The terms a document's example gives, and the due date the books take
@@ -230,6 +253,20 @@ impl Books<'_> {
(due, Some(parsed)) (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 /// An invoice's or bill's lines: `amount` (one line, described as the
/// event) or `lines`, exactly one; each project a `setup.projects` /// event) or `lines`, exactly one; each project a `setup.projects`
/// name. /// name.
@@ -264,7 +301,7 @@ impl Books<'_> {
panic!("{what}: project {p:?} not in setup.projects") panic!("{what}: project {p:?} not in setup.projects")
}) })
}), }),
account: None, account: l.account.as_deref().map(|code| self.id(code)),
quantity: None, quantity: None,
unit_price: None, unit_price: None,
}) })
@@ -410,6 +447,8 @@ impl Books<'_> {
lines, lines,
BillFields { BillFields {
terms, terms,
vendor_ref: b.vendor_ref.clone(),
duplicate_reason: b.duplicate_reason.clone(),
..BillFields::default() ..BillFields::default()
}, },
) )
@@ -427,6 +466,9 @@ impl Books<'_> {
} }
}; };
let (due, terms) = self.terms_due(i.terms.as_deref(), day(), what); 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 self.store
.create_invoice_with( .create_invoice_with(
customer, customer,
@@ -434,6 +476,7 @@ impl Books<'_> {
due, due,
lines, lines,
InvoiceFields { InvoiceFields {
number: Some(number),
terms, terms,
..InvoiceFields::default() ..InvoiceFields::default()
}, },
@@ -515,6 +558,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" => { "run_depreciation" => {
let r = e.run_depreciation.as_ref().expect("checked: a run"); let r = e.run_depreciation.as_ref().expect("checked: a run");
let asset = self.asset(&r.asset, what); let asset = self.asset(&r.asset, what);
@@ -146,6 +146,8 @@ pub(crate) fn every_bookspec_example_holds() {
("project", 6), ("project", 6),
("aging", 4), ("aging", 4),
("document_dates", 8), ("document_dates", 8),
("document", 8),
("invoice_numbers", 1),
] { ] {
let n = checked.get(q).copied().unwrap_or(0); let n = checked.get(q).copied().unwrap_or(0);
assert!(n >= at_least, "{q} ran {n} times, fewer than {at_least}"); assert!(n >= at_least, "{q} ran {n} times, fewer than {at_least}");
@@ -157,11 +159,14 @@ pub(crate) fn every_bookspec_example_holds() {
skipped.len() skipped.len()
); );
// The examples for an option wanderbooks did not pick: the other option // 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 // of BS-arap-2 (documents-kept-apart), -7, -8, -9, -10 (compare-exactly),
// refuse (each option's example, so no allow-list grows). // -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).
assert_eq!( assert_eq!(
skipped.len(), skipped.len(),
5, 11,
"the five unpicked-option examples: {skipped:?}" "the eleven unpicked-option examples: {skipped:?}"
); );
} }
@@ -63,6 +63,63 @@ impl Books<'_> {
("discount_by".to_string(), discount_by), ("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 /// Check an `aging` expectation: every figure the engine gives, and no
@@ -71,6 +128,32 @@ pub(crate) fn check_aging(b: &Books<'_>, x: &Expect) {
check_figures(b, x, b.answer_aging(&x.query())); 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 /// Check a `document_dates` expectation: `due` and `discount_by`, both
/// given. /// given.
pub(crate) fn check_document_dates(b: &Books<'_>, x: &Expect) { pub(crate) fn check_document_dates(b: &Books<'_>, x: &Expect) {
@@ -87,6 +87,8 @@ impl Books<'_> {
"project" => self.answer_project(q), "project" => self.answer_project(q),
"aging" => self.answer_aging(q), "aging" => self.answer_aging(q),
"document_dates" => self.answer_document_dates(q), "document_dates" => self.answer_document_dates(q),
"document" => self.answer_document(q),
"invoice_numbers" => self.answer_invoice_numbers(q),
"run" => self.answer_run(q), "run" => self.answer_run(q),
"disposal" => self.answer_disposal(q), "disposal" => self.answer_disposal(q),
"depreciation_schedule" => self.answer_depreciation_schedule(q), "depreciation_schedule" => self.answer_depreciation_schedule(q),
@@ -2553,3 +2553,72 @@ fn discount_on_an_asset_bill_is_refused_with_the_remedy() {
); );
b.ties(d(2026, 4, 5)); 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));
}
+38 -7
View File
@@ -74,7 +74,12 @@ Kani `bounds_check_matches_definition`, `bounds_kept_is_the_definition_on_books_
Lean `Documents.control_agrees`, `Documents.Step.document_unattached`, Lean `Documents.control_agrees`, `Documents.Step.document_unattached`,
`Documents.Step.reverse_moves`, `Documents.Reachable.unattached_zero` `Documents.Step.reverse_moves`, `Documents.Reachable.unattached_zero`
(through role assignments and releases), (through role assignments and releases),
`Documents.Reachable.control_is_documents`. The model's limits: it `Documents.Reachable.control_is_documents`; bookspec examples
`arap-hand-control-posting-refused` (BS-arap-2 `lines-that-stand`: the
hand line is refused, the line an earlier version wrote still reads right),
run by the adapter, and `arap-a-hand-line-on-receivables-is-taken`
(`documents-kept-apart`), which names the option wanderbooks did not pick
and is skipped for it. The model's limits: it
starts from empty books (legacy lines are covered by the identity starts from empty books (legacy lines are covered by the identity
`Documents.control_agrees` alone), it names documents by one id space (an injective `Documents.control_agrees` alone), it names documents by one id space (an injective
coding of `DocRef`), and an account becoming a control account by its coding of `DocRef`), and an account becoming a control account by its
@@ -179,8 +184,8 @@ behind the feature `documents_v2`. **Checked:**
**Claims:** yes **Claims:** yes
**Pick:** a vendor's invoice reference is compared after the normalization that drops case and spaces (`Ledger::check_vendor_ref`); the old text names no separate decision for it. **Pick:** a vendor's invoice reference is compared after the normalization that drops case, spaces and hyphens (`Ledger::check_vendor_ref`), so "ACME-123", "acme 123" and "Acme123" are one reference (pinned by `duplicate_vendor_ref_refused_unless_a_reason_is_given`); plan P4b S4 (the owner) specifies it.
**Pick (BS-arap-10):** `ignore-case-and-spaces`; a vendor's invoice reference is compared after the normalization that drops case and spaces. **Pick (BS-arap-10):** `ignore-case-spaces-and-hyphens`; a vendor's invoice reference is compared after the normalization that drops case, spaces (any whitespace) and hyphens.
**Enforced:** `Ledger::next_invoice_number`, `Ledger::check_vendor_ref`, **Enforced:** `Ledger::next_invoice_number`, `Ledger::check_vendor_ref`,
`PartySnapshot::from_party` (the snapshots at issue, D-55); `PartySnapshot::from_party` (the snapshots at issue, D-55);
@@ -195,7 +200,14 @@ every amount through `amount_parts`).
`tests/arap_standing.rs` (`documents_v2_waits_for_the_upgrade`, `tests/arap_standing.rs` (`documents_v2_waits_for_the_upgrade`,
`issued_pdf_is_filed_with_the_invoice_or_nothing_is`); over the wire `issued_pdf_is_filed_with_the_invoice_or_nothing_is`); over the wire
`crates/ledger-cli/tests/documents.rs` (`an_invoice_from_issue_to_paid`, `crates/ledger-cli/tests/documents.rs` (`an_invoice_from_issue_to_paid`,
`duplicate_vendor_invoice_refused`); the page `ledger-import` `duplicate_vendor_invoice_refused`); bookspec examples
`arap-invoice-numbers-run-in-order-and-are-kept` (the adapter numbers each
invoice with `Ledger::next_invoice_number` and reads the place back from the
number the engine stored), `arap-a-vendor-invoice-is-entered-once`
(the refusal of a second bill, from `Ledger::check_vendor_ref`) and, for
BS-arap-10, `arap-a-vendor-reference-differing-in-case-spaces-and-hyphens-is-a-duplicate`;
`arap-a-vendor-reference-differing-in-case-spaces-and-hyphens-is-not-a-duplicate`
names `compare-exactly` and is skipped; the page `ledger-import`
`tests/spec_import.rs::invoice_pdf_prints_what_it_should` and the unit tests `tests/spec_import.rs::invoice_pdf_prints_what_it_should` and the unit tests
`labels_are_data`, `an_invoice_renders_deterministically`, `labels_are_data`, `an_invoice_renders_deterministically`,
`two_hundred_lines_paginate`; the viewer `two_hundred_lines_paginate`; the viewer
@@ -260,7 +272,14 @@ item.
`tests/arap_props.rs` (`status_is_a_function_of_journal_and_date` with `tests/arap_props.rs` (`status_is_a_function_of_journal_and_date` with
write-offs); over the wire `crates/ledger-cli/tests/documents.rs` write-offs); over the wire `crates/ledger-cli/tests/documents.rs`
(`write_off_then_recovery`, `write_off_needs_evidence`); bookspec (`write_off_then_recovery`, `write_off_needs_evidence`); bookspec
`bad-debt-direct-write-off`; Lean `Documents.Step.writeOff_unattached`, `bad-debt-direct-write-off` (BS-arap-5 `direct-write-off`; the allowance
method has no example yet, it needs a provision event) and, for BS-arap-11,
`arap-a-recovery-reverses-the-write-off-in-its-year` (the adapter reverses
the write-off with `Store::reverse_entry` and takes the money with
`Store::receive_payment` in the write-off's tax year, and posts a plain
entry in a later one);
`arap-a-recovery-is-a-movement-on-the-document` names `recovery-movement`
and is skipped; Lean `Documents.Step.writeOff_unattached`,
`Documents.writeOff_within_bounds`; the viewer `Documents.writeOff_within_bounds`; the viewer
`a_write_off_shows_on_the_timeline`; the item `a_write_off_shows_on_the_timeline`; the item
`a_write_off_is_flagged_for_the_cpa`. `a_write_off_is_flagged_for_the_cpa`.
@@ -319,12 +338,24 @@ check_discount}`, `arap::{Application, Fee, SettleParams, SettlementRow}`,
(`bill_on_terms_with_discount`, `late_discount_needs_a_reason`, (`bill_on_terms_with_discount`, `late_discount_needs_a_reason`,
`discount_on_an_asset_bill_is_refused_with_the_remedy`, `discount_on_an_asset_bill_is_refused_with_the_remedy`,
`a_fee_posts_gross_to_receivables_and_net_to_the_bank`, `a_fee_posts_gross_to_receivables_and_net_to_the_bank`,
`a_settlement_names_its_lines_and_refuses_a_document_twice`), `a_settlement_names_its_lines_and_refuses_a_document_twice`,
`a_fee_above_the_cash_is_refused_and_changes_nothing`: the refusal is
`LedgerError::FeeAboveCash`, its own variant),
`tests/kernel_bridge/main.rs::settle_agrees`; Kani `settle_is_exact`; `tests/kernel_bridge/main.rs::settle_agrees`; Kani `settle_is_exact`;
`ledger-store` `tests/arap_standing.rs` `ledger-store` `tests/arap_standing.rs`
(`a_settlement_names_its_lines_and_replays`, `settlement_waits_for_documents_v2`, (`a_settlement_names_its_lines_and_replays`, `settlement_waits_for_documents_v2`,
`legacy_payment_events_keep_the_positional_rule`), `tests/arap_props.rs`; `legacy_payment_events_keep_the_positional_rule`), `tests/arap_props.rs`;
`ledger-cli` `tests/documents.rs`; `ledger-package`'s aging tie-out test. `ledger-cli` `tests/documents.rs`; `ledger-package`'s aging tie-out test;
bookspec examples `arap-a-settlement-pays-several-documents-and-names-each-line`
and `arap-a-settlement-that-is-not-exact-is-refused` (BS-arap-6, through
`Store::settle`, each refusal read off the engine's own error), and one per
option picked: `arap-a-discount-taken-is-booked-when-it-is-taken` (BS-arap-12),
`arap-a-processors-fee-is-posted-gross` (BS-arap-13) and
`arap-a-discount-on-an-asset-bill-is-refused` (BS-arap-14); the examples
`arap-a-discount-expected-is-booked-with-the-document`,
`arap-a-processors-fee-is-not-shown-against-the-deposit` and
`arap-a-discount-on-an-asset-bill-is-apportioned` name the options not picked
and are skipped.
The Lean step is the document constructor of the Lean documents model, with The Lean step is the document constructor of the Lean documents model, with
every control line tagged (`Documents.settle_unattached`); no new step every control line tagged (`Documents.settle_unattached`); no new step
constructor. constructor.