feat(arap)!: documents read their figures from standing lines; control accounts
check / check (push) Canceled after 0s

refuse hand entries (P4b S1, part A)

Plan P4b (D-45), slice S1, the engine half: rules.md B-38.

- ledger-core: every receivables or payables line carries its document
  (Ledger.line_docs: DocRef, Movement, DocTag), written by the document
  commands in the step that posts it, derived on replay from the existing
  document events (the role's account as it stood then; payments by the
  ordinal rule), copied onto a reversal's mirror. Ledger::stands_on;
  doc_state / invoice_state / bill_state (total, paid, outstanding,
  status Open/Partial/Paid/WrittenOff/Void, overdue days) as of any day;
  ar_aging / ap_aging read them, so reversed payments and voids are right.
  The control guard (add_line, add_line_fx, post_entry,
  register_recurring) refuses untagged lines on receivables/payables,
  exempting a reversal's mirror of a legacy line; replay never refuses.
  Bounds (kernel::running_bounds, bounds_kept) on payments and reversals;
  a document reversal never dated before its entry; deposit/payer accounts
  must be cash-like and hold no role. New API: receive_payment_with /
  pay_bill_with (PaymentDetails: instrument, reference), void_document /
  check_void_document, control_check, payments_recorded,
  standing_payments, replay_reverse_entry. Invoice.amount_paid/status
  remain only as derived caches for the MCP layer until part B.
  cashflow bill_splits reads payments from the tags.
- ledger-store: journal feature document_standing (D-39 gated) for a
  payment accepted only because an earlier one was reversed;
  receive_payment_with / pay_bill_with (instrument journaled as
  entry.instrument_set, reference in the description), void_document;
  replay uses replay_reverse_entry; schema 15 drops the projection's
  amount_paid/status. Fixture p4-arap-before + golden figures written by
  the version before S1, adjudicated in arap_standing.rs.
- ledger-gui: party card, cash "coming up" and company owed totals read
  doc_state as of today (late from the derived state).
- Lean Documents.lean (control_agrees and friends); Kani
  bounds_check_matches_definition,
bounds_kept_is_the_definition_on_books_in_bounds;
  rules B-38, B-18/B-23 amended; bookspec `older = true` for legacy hand
  lines; tests that hand-post to 1200/2000 post as replay or renumbered.

Review fixes (both reviews of part A):
- control_role_of guards only an account the role is assigned to or one
  holding its documents' lines (a chart's own 1200 Equipment or card at
  2000 is free until a document posts there); payment accounts check
  other roles by holds_role (type-checked). The MCP tests that failed on
  the guard (oracle_mcp, spec_projects) pass unchanged.
- standing_payments leaves out reversals (sorted, deduped); replayed
  tags match the movement's side; payments_recorded counts every payment
  event (tagged or not, Ledger.payment_events) and refuses overflow.
- The record caches settled (paid + discounted + written off) and owed
  (Invoice/Bill.owed, never serialized): a void never reads as paid.
- assign_role: receivables/payables refuse moving onto an account with
  untagged lines (RoleAccountHasHandLines) and, on their control account
  holding a balance, say DocumentRoleHoldsBalance (no hand entry named);
  B-23 reworded. The reversal-mirror exemption only takes a hand line
  off (even chain depth); putting it back is refused.
- DocStatus Overpaid and Unattached; aging leaves out credit balances;
  ControlCheck.attention lists out-of-bounds and unattached documents.
- stands_on counts a chain in order; indexes (doc_index, doc_accounts,
  order_pos, reversed_by) keep the derived figures linear.
- Viewer reads a post-dated document as of its own date; one state per
  row. bounds_kept's side-crossing documented as intended.
- Tests: ten new spec_documents scenarios, stronger proptests, store
  proptest arap_props (live = replay = snapshot at every date, closed
  months), fuzz ops void/payments with details, a GUI post-dated test;
  Lean Step.assign / Step.release with unattached_zero kept; model
  limits stated in docs/testing.md and B-38.
Review fixes (CPA and engineering lenses): only an assigned role's
account or one holding document lines is a control account (a chart's
own 1200 asset stays free); a role can't move onto untagged lines or off
document lines (Lean Step.assign); a void's cache never reads as paid;
no Decimal sum panics; per-document indexes keep figures linear; a
replayed tag matches its side; the feature gate counts payment events;
a payment's reversal is never listed as standing; an overpaid document
has its own status; the viewer keeps post-dated documents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T3gXMVt7XJPi6ens1or9Dj
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-10-24 09:17:42 -06:00
1 parent 7741e96eb3
commit d7fa16e974
54 files changed
+5997 -649

No files matched your search

+370 -27
View File
@@ -4,8 +4,16 @@
//!
//! * `create_invoice`: Dr `1200` Accounts Receivable, Cr `4000` Revenue.
//! * `create_bill`: Dr `6999` General Expenses, Cr `2000` Accounts Payable.
//! * `receive_payment`: Dr Cash, Cr A/R. Updates the invoice's paid amount.
//! * `pay_bill`: Dr A/P, Cr Cash. Updates the bill's paid amount.
//! * `receive_payment`: Dr Cash, Cr A/R.
//! * `pay_bill`: Dr A/P, Cr Cash.
//!
//! A document keeps no figure of its own (plan P4b, D-45; rules.md B-38):
//! every ledger line on a receivables or payables account carries the
//! document it belongs to ([`DocTag`]), and what is paid and still owed,
//! and the document's status, are read from those lines that stand
//! ([`DocState`], `Ledger::doc_state`), as of any date. A reversal, a void
//! or a bounced payment is therefore right by construction, and the
//! control accounts always equal their documents.
//!
//! The control accounts (`1200`, `2000`) and the default revenue/expense
//! accounts (`4000`, `6999`) are created on demand if missing. Invoices and
@@ -71,7 +79,10 @@ impl Vendor {
}
}
/// Payment status of an invoice or bill.
/// Payment status of an invoice or bill, in the three words the
/// documents' records carried before their figures were derived
/// ([`Invoice::status`]). The full status, a void or a write-off
/// included, is [`DocStatus`].
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum DocumentStatus {
/// Nothing paid yet.
@@ -82,6 +93,320 @@ pub enum DocumentStatus {
Paid,
}
/// A document: an invoice or a bill, the two kinds whose ledger lines
/// carry their document ([`DocTag`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
pub enum DocRef {
/// A sales invoice (receivables).
Invoice(InvoiceId),
/// A vendor bill (payables).
Bill(BillId),
}
impl std::fmt::Display for DocRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DocRef::Invoice(id) => write!(f, "invoice {id}"),
DocRef::Bill(id) => write!(f, "bill {id}"),
}
}
}
impl DocRef {
/// The side that counts plus for this kind of document: a debit to
/// receivables raises what an invoice is owed, a credit to payables
/// what a bill is owed.
pub fn owed_side(self) -> crate::Side {
match self {
DocRef::Invoice(_) => crate::Side::Debit,
DocRef::Bill(_) => crate::Side::Credit,
}
}
/// A line's amount as this document counts it: plus on
/// [`Self::owed_side`], minus on the other.
pub fn counted(self, side: crate::Side, amount: Decimal) -> Decimal {
if side == self.owed_side() {
amount
} else {
-amount
}
}
}
/// Why a ledger line carries its document: what it does to what is owed.
/// Only `Origin` and `Payment` are written today (P4b S1); the rest are
/// the movements later slices write (P4b.6), named here so a tag's kind
/// never changes meaning.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Movement {
/// The document's own control line: what it is for.
Origin,
/// Cash paid against it.
Payment,
/// An early-payment discount taken (S6).
Discount,
/// A bad debt written off (S7).
WriteOff,
/// A legacy hand line adopted as the document (S7).
Adopted,
/// The balance moved with its control role (S7).
RoleMove,
}
/// A ledger line's document tag: which document the line belongs to, and
/// how ([`crate::Ledger::line_doc`]). Kept beside the line, like its
/// cleared flag: the line and its hash never change.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct DocTag {
/// The document.
pub doc: DocRef,
/// What the line does to it.
pub movement: Movement,
}
/// A document's status as of a date ([`DocState`]).
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DocStatus {
/// Nothing paid, discounted or written off.
Open,
/// Some of it settled, some still owed.
Partial,
/// Nothing owed, and some of it paid or discounted.
Paid,
/// Nothing owed, the last of it written off (S7).
WrittenOff,
/// Its own entry doesn't stand: reversed (B-9), number kept.
Void,
/// Less than nothing owed: more paid against it than it is for, a
/// credit balance owed back (to the customer on an invoice, by the
/// vendor on a bill). Only in books an earlier version left out of
/// bounds (B-38 INVARIANT 2); never a receivable or a payable, so
/// never aged.
Overpaid,
/// Its own entry stands but carries no line tagged with it (an older
/// version's entry replay couldn't match): its figures can't be read
/// from the ledger, and the control check lists it.
Unattached,
}
impl DocStatus {
/// Its wire name: `open`, `partial`, `paid`, `written_off`, `void`.
pub fn key(self) -> &'static str {
match self {
DocStatus::Open => "open",
DocStatus::Partial => "partial",
DocStatus::Paid => "paid",
DocStatus::WrittenOff => "written_off",
DocStatus::Void => "void",
DocStatus::Overpaid => "overpaid",
DocStatus::Unattached => "unattached",
}
}
/// Its label for people: `Open`, `Partly paid`, `Paid`, `Written
/// off`, `Void`, `Overpaid`, `Not in the ledger`.
pub fn label(self) -> &'static str {
match self {
DocStatus::Open => "Open",
DocStatus::Partial => "Partly paid",
DocStatus::Paid => "Paid",
DocStatus::WrittenOff => "Written off",
DocStatus::Void => "Void",
DocStatus::Overpaid => "Overpaid",
DocStatus::Unattached => "Not in the ledger",
}
}
}
/// What a document is, as of a date, read from the ledger lines tagged
/// with it ([`crate::Ledger::doc_state`]); never stored.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct DocState {
/// The sum of its lines.
pub total: Decimal,
/// Cash paid against it that stands.
pub paid: Decimal,
/// Discounts taken that stand.
pub discounted: Decimal,
/// Amounts written off that stand.
pub written_off: Decimal,
/// What is still owed: the signed sum of every line tagged with it.
pub outstanding: Decimal,
/// Its status.
pub status: DocStatus,
/// Days past its due date while something is owed; 0 otherwise.
pub overdue_days: i64,
}
impl DocState {
/// It owes less than nothing or more than its total: books an earlier
/// version left out of bounds (B-38 INVARIANT 2; plan P4b.14 item 3),
/// which the control check lists for attention.
pub fn out_of_bounds(&self) -> bool {
self.outstanding < Decimal::ZERO || self.outstanding > self.total
}
}
/// A document's status from its figures ([`DocState`]; plan P4b.3).
///
/// ```text
/// GOAL: one status from the ledger's figures, whatever happened to the
/// document, its payments and their reversals.
/// SOURCE: docs/spec/rules.md B-38; plan/served.md P4b.3 ("Status as of D");
/// ASC 310-10 (a credit balance is not a receivable).
/// INVARIANTS:
/// 1. Void exactly when its own entry doesn't stand (`origin_stands`
/// false), whatever else is tagged.
/// 2. Otherwise Unattached when its own control line carries no tag
/// (`origin_tagged` false): nothing about it can be read.
/// 3. Otherwise: Overpaid when less than nothing is owed; Written off
/// when nothing is owed and something was written off; Paid when
/// nothing is owed; Partial when less than the total is owed; Open
/// when the whole total, or more (DocState::out_of_bounds), is.
/// 4. A pure function of its arguments.
/// ```
pub fn doc_status(
origin_stands: bool,
origin_tagged: bool,
total: Decimal,
outstanding: Decimal,
written_off: Decimal,
) -> DocStatus {
if !origin_stands {
DocStatus::Void
} else if !origin_tagged {
DocStatus::Unattached
} else if outstanding < Decimal::ZERO {
DocStatus::Overpaid
} else if outstanding.is_zero() && written_off > Decimal::ZERO {
DocStatus::WrittenOff
} else if outstanding.is_zero() {
DocStatus::Paid
} else if outstanding < total {
DocStatus::Partial
} else {
DocStatus::Open
}
}
/// One posted ledger line tagged with a document ([`crate::Ledger::doc_lines`]).
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct DocLine {
/// The entry.
pub entry: crate::EntryId,
/// The line's index in it.
pub line: usize,
/// The entry's date.
pub date: NaiveDate,
/// The account the line is on.
pub account: crate::AccountId,
/// What it does to the document.
pub movement: Movement,
/// Its amount as the document counts it ([`DocRef::counted`]): plus
/// raises what is owed.
pub amount: Decimal,
/// The entry reverses another (it is the mirror of a line).
pub reversal: bool,
}
/// A line on a control account that carries no document: one written by
/// hand before the control guard, or by an older version (plan P4b.3,
/// "unattached").
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct UnattachedLine {
/// The entry.
pub entry: crate::EntryId,
/// The line's index in it.
pub line: usize,
/// The entry's date.
pub date: NaiveDate,
/// Its amount as the control account counts it (plus raises the
/// receivable or the payable).
pub amount: Decimal,
}
/// One control account's tie-out as of a date ([`crate::Ledger::control_check`]).
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct ControlCheck {
/// The role whose documents the account holds: `receivables` or
/// `payables`.
pub role: String,
/// The account.
pub account: crate::AccountId,
/// Its balance in the general ledger, on its normal side.
pub balance: Decimal,
/// The sum of what its documents still owe on it.
pub documents_total: Decimal,
/// The lines on it that carry no document, which still stand.
pub unattached: Vec<UnattachedLine>,
/// balance - documents_total - the unattached lines: always zero (both
/// sides sum the same lines); anything else is an engine error.
pub difference: Decimal,
/// The role's documents needing attention as of the day: out of
/// bounds ([`DocState::out_of_bounds`]: a credit balance, which aging
/// leaves out, or more owed than the total) or unattached
/// ([`DocStatus::Unattached`]). Listed on the role's first account.
pub attention: Vec<DocAttention>,
}
/// A document the control check lists for attention ([`ControlCheck::attention`]).
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct DocAttention {
/// The document.
pub doc: DocRef,
/// Its status as of the day.
pub status: DocStatus,
/// Its total.
pub total: Decimal,
/// What it owes as of the day.
pub outstanding: Decimal,
}
/// How a payment is recorded beyond its amount (plan P4b.6, D-40): the
/// payment method it moved through, tagged on its entry in the same call
/// (so a card-paid bill is left out of 1099-NEC without a second call),
/// and the processor's or bank's own reference (a charge id, a trace or
/// check number), carried in the entry's description.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PaymentDetails {
/// The payment method, when known.
pub instrument: Option<crate::InstrumentId>,
/// The reference, when there is one: one line of text.
pub reference: Option<String>,
}
/// The longest payment reference taken, in characters.
pub const MAX_REFERENCE_CHARS: usize = 200;
impl PaymentDetails {
/// The payment entry's description: `base`, then the reference when
/// there is one (`base (ref R)`).
pub fn description(&self, base: &str) -> String {
match self.reference.as_deref().map(str::trim) {
Some(r) if !r.is_empty() => format!("{base} (ref {r})"),
_ => base.to_string(),
}
}
/// Refuse a reference that isn't one line of at most
/// [`MAX_REFERENCE_CHARS`] characters. A blank one is none. (A bank
/// trace number is fifteen digits, so no nine-digit scan here.)
pub fn check(&self) -> Result<(), LedgerError> {
if let Some(r) = &self.reference
&& (r.contains(['\n', '\r']) || r.chars().count() > MAX_REFERENCE_CHARS)
{
return Err(LedgerError::InvalidPayment(format!(
"a payment's reference is one line of at most {MAX_REFERENCE_CHARS} characters"
)));
}
Ok(())
}
}
/// One line on an invoice or bill.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct DocumentLine {
@@ -111,9 +436,22 @@ pub struct Invoice {
pub due_date: NaiveDate,
/// Line items.
pub lines: Vec<DocumentLine>,
/// How much has been paid.
/// What was settled on it at the end of the books: paid, discounted
/// and written off, as they stand ([`crate::Ledger::doc_state`] as of
/// the last day). Derived from the lines tagged with it and refreshed
/// by the ledger with every change (reversals included); never
/// journaled, never state of its own. A void settles nothing, so a
/// voided document never reads as paid.
pub amount_paid: Decimal,
/// Derived from amount_paid vs total.
/// What is still owed on it at the end of the books (`doc_state`'s
/// outstanding as of the last day), derived with
/// [`Self::amount_paid`]: [`Self::balance`]. Nothing for a void.
/// Never serialized: a figure, not part of the record.
#[serde(skip)]
pub owed: Decimal,
/// The three-word status of [`Self::amount_paid`]; derived with it
/// (Open for a void: nothing was paid). The full status (a void, a
/// write-off) is `doc_state`'s.
pub status: DocumentStatus,
/// The auto-posted journal entry.
pub entry_id: u64,
@@ -168,26 +506,18 @@ pub fn document_parts(
.collect()
}
/// What is still owed on a document: its total less what was paid.
fn document_balance(total: Decimal, paid: Decimal, what: &str) -> Result<Decimal, LedgerError> {
total
.checked_sub(paid)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{what}'s balance")))
}
impl Invoice {
/// Total of all lines ([`document_total`]).
pub fn total(&self) -> Result<Decimal, LedgerError> {
document_total(&self.lines, &format!("invoice {}", self.id))
}
/// Amount still owed.
/// Amount still owed at the end of the books ([`Self::owed`]); as
/// of a date, `Ledger::doc_state`. Refused (TooLargeToCompute) when
/// its total can't be summed.
pub fn balance(&self) -> Result<Decimal, LedgerError> {
document_balance(
self.total()?,
self.amount_paid,
&format!("invoice {}", self.id),
)
self.total()?;
Ok(self.owed)
}
}
@@ -204,9 +534,22 @@ pub struct Bill {
pub due_date: NaiveDate,
/// Line items.
pub lines: Vec<DocumentLine>,
/// How much has been paid.
/// What was settled on it at the end of the books: paid, discounted
/// and written off, as they stand ([`crate::Ledger::doc_state`] as of
/// the last day). Derived from the lines tagged with it and refreshed
/// by the ledger with every change (reversals included); never
/// journaled, never state of its own. A void settles nothing, so a
/// voided document never reads as paid.
pub amount_paid: Decimal,
/// Derived from amount_paid vs total.
/// What is still owed on it at the end of the books (`doc_state`'s
/// outstanding as of the last day), derived with
/// [`Self::amount_paid`]: [`Self::balance`]. Nothing for a void.
/// Never serialized: a figure, not part of the record.
#[serde(skip)]
pub owed: Decimal,
/// The three-word status of [`Self::amount_paid`]; derived with it
/// (Open for a void: nothing was paid). The full status (a void, a
/// write-off) is `doc_state`'s.
pub status: DocumentStatus,
/// The auto-posted journal entry.
pub entry_id: u64,
@@ -218,13 +561,12 @@ impl Bill {
document_total(&self.lines, &format!("bill {}", self.id))
}
/// Amount still owed.
/// Amount still owed at the end of the books ([`Self::owed`]); as
/// of a date, `Ledger::doc_state`. Refused (TooLargeToCompute) when
/// its total can't be summed.
pub fn balance(&self) -> Result<Decimal, LedgerError> {
document_balance(
self.total()?,
self.amount_paid,
&format!("bill {}", self.id),
)
self.total()?;
Ok(self.owed)
}
}
@@ -263,7 +605,8 @@ pub fn validate_due_date(date: NaiveDate, due_date: NaiveDate) -> Result<(), Led
Ok(())
}
/// Derive status from paid vs total.
/// The three-word status from what is settled vs the total
/// ([`DocumentStatus`]).
pub fn derive_status(paid: Decimal, total: Decimal) -> DocumentStatus {
if paid.is_zero() {
DocumentStatus::Open
+18 -10
View File
@@ -1030,7 +1030,8 @@ type KindOrder = (u8, u8, String);
/// that part, equipment first, to its payables lines and to its payments,
/// so the payment is an investing outflow (ASC 230-10-45-13(c)). A bill
/// posts to the general-expenses control today, so this is empty until a
/// bill can carry an equipment line.
/// bill can carry an equipment line (P4b S4). A bill's payments are the
/// entries whose payables line carries it (rules.md B-38).
#[derive(Default)]
struct BillSplits {
/// By (entry, line index): the investing part of that payables line,
@@ -1077,15 +1078,20 @@ fn bill_splits(roles: &Roles<'_>, chains: &Chains) -> Result<BillSplits, LedgerE
left -= part;
}
}
// Each payment pays the equipment part first, as the bill records
// them, in order: the part its payables carried (none when the
// payable is financing: its payments are repayments already).
// A payment's own amount bounds what it paid of this bill. A
// reversed payment still counts against what later payments carry
// (the bill keeps it as paid), but not against what is unpaid at a
// period's end after the reversal.
// Each payment pays the equipment part first, in the order paid:
// the part its payables carried (none when the payable is
// financing: its payments are repayments already). A payment's
// own amount bounds what it paid of this bill. A reversed payment
// paid nothing for good: its reversal unpays it on the reversal's
// date, and it leaves the equipment part for the payment that
// stands (P4b.2 gap 6: it used to keep it, as the bill did).
let mut owed = equipment - left;
for &(pay, amount) in ledger.bill_payments(bill.id) {
let payments = ledger
.doc_lines(crate::DocRef::Bill(bill.id))
.into_iter()
.filter(|l| l.movement == crate::Movement::Payment && !l.reversal);
for pl in payments {
let (pay, amount) = (pl.entry, -pl.amount);
let Some(p) = ledger.get_entry(pay) else {
continue;
};
@@ -1111,7 +1117,9 @@ fn bill_splits(roles: &Roles<'_>, chains: &Chains) -> Result<BillSplits, LedgerE
undo = -undo;
cur = r;
}
owed -= part;
if ledger.in_effect(p.id()) {
owed -= part;
}
this -= part;
}
}
+103 -3
View File
@@ -228,9 +228,10 @@ pub enum LedgerError {
role: String,
},
/// A balance sheet role (receivables, payables, withholdings, retained
/// earnings) can't move while its account holds a balance: the control
/// account must keep agreeing with what it controls.
/// A balance sheet role (withholdings, retained earnings) can't move
/// while its account holds a balance: the control account must keep
/// agreeing with what it controls. Receivables and payables refuse
/// with [`Self::DocumentRoleHoldsBalance`] instead.
#[error(
"{role} is in account {code} \"{name}\", which holds {balance}; move that balance to the \
new account with a journal entry first, then assign the role"
@@ -608,6 +609,105 @@ pub enum LedgerError {
#[error("payment of {0} exceeds remaining balance of {1}")]
Overpayment(Decimal, Decimal),
/// A payment's details were refused (its reference): the message says
/// why.
#[error("{0}")]
InvalidPayment(String),
/// Receivables or payables can't move while their account holds a
/// balance (rules.md B-23, B-38): that balance is the documents', and
/// a hand entry moving it is refused by the control guard; it moves
/// with its documents (plan P4b S7).
#[error(
"{role} is in account {code} \"{name}\", which holds {balance} owed on its documents; \
the role can't move until that is settled (paid or voided) or until moving a balance \
with its documents is built: a hand entry to the account is refused"
)]
DocumentRoleHoldsBalance {
/// The role, e.g. "accounts receivable".
role: String,
/// The code of the account filling it now.
code: String,
/// That account's name.
name: String,
/// Its balance.
balance: rust_decimal::Decimal,
},
/// Receivables or payables can't move to an account holding lines
/// that are no document's (rules.md B-38 INVARIANT 1): they would
/// become hand lines on a control account.
#[error(
"account {code} \"{name}\" holds lines no invoice or bill carries (entry {entry} first), \
so it can't take the {role} role: give the role an account of its own"
)]
RoleAccountHasHandLines {
/// The role, e.g. "accounts receivable".
role: String,
/// The account's code.
code: String,
/// Its name.
name: String,
/// The first posted entry with such a line.
entry: u64,
},
/// A payment's deposit or payer account must be a postable asset or
/// liability that holds no role: a bank, a card, a member's payable
/// (plan P4b.3, "Payment accounts").
#[error(
"account {code} \"{name}\" can't take a payment: {why}; pay into or from a bank or card account (or a member's payable)"
)]
PaymentAccount {
/// The account's code.
code: String,
/// Its name.
name: String,
/// Why not, e.g. "it holds the accounts receivable role".
why: String,
},
/// A line on a receivables or payables control account carries no
/// document (rules.md B-23, B-38): the control account must always
/// equal its documents, so only the document commands post there.
#[error(
"account {account} is a control account (its balance is its invoices or bills): {at} can't be posted there by hand. Use books.create_invoice, books.receive_payment, books.create_bill or books.pay_bill; to void a document, books.reverse_entry of its entry"
)]
UntaggedControlLine {
/// The account's code and name, e.g. `1200 "Accounts Receivable"`.
account: String,
/// Which line, e.g. "line 1 of entry 14", "line 0 of the
/// recurring template".
at: String,
},
/// A reversal or payment would leave a document owing less than nothing
/// or more than its total at some date (rules.md B-38 INVARIANT 2): the
/// message says which document, when, and what to reverse first.
#[error("{0}")]
DocumentBounds(String),
/// A reversal of an entry an invoice or bill owns is dated before that
/// entry (rules.md B-9, B-38): a correction comes after what it
/// corrects.
#[error(
"entry {entry} belongs to {document} and is dated {original}: its reversal can't be dated before it, on {date}"
)]
DocumentReversalBeforeOriginal {
/// The entry reversed.
entry: u64,
/// The document, e.g. "invoice 7".
document: String,
/// The entry's date.
original: chrono::NaiveDate,
/// The reversal's date.
date: chrono::NaiveDate,
},
/// A document can't be voided as asked: the message says why.
#[error("{0}")]
InvalidVoid(String),
/// Invoice/bill due date is before its date.
#[error("due date {0} is before document date")]
DueBeforeDate(String),
+6 -3
View File
@@ -370,8 +370,9 @@ mod tests {
/// Hand-worked: A contributes 300 cash and a 700 laptop in one entry
/// (Dr 1000 300, Dr 1500 700 / Cr 3000 1000); B contributes a 200
/// receivable-backed promise (Dr 1200 200 / Cr 3001 200, cash by
/// INVARIANT 3) and pays a 50 expense (Dr 6999 50 / Cr 3001 50).
/// receivable-backed promise (Dr 1200 200 / Cr 3001 200, as an earlier
/// version could write it; cash by INVARIANT 3) and pays a 50 expense
/// (Dr 6999 50 / Cr 3001 50).
#[test]
fn contributions_split_into_cash_and_property() {
let mut l = Ledger::new(Currency::USD);
@@ -402,7 +403,9 @@ mod tests {
(equip, Side::Debit, "700"),
(a, Side::Credit, "1000"),
]);
post(&[(ar, Side::Debit, "200"), (b, Side::Credit, "200")]);
// A hand line on receivables: only books an earlier version wrote
// hold one now (the control guard, rules.md B-38), so replayed.
crate::parties::replaying(|| post(&[(ar, Side::Debit, "200"), (b, Side::Credit, "200")]));
post(&[(exp, Side::Debit, "50"), (b, Side::Credit, "50")]);
let members = [
MemberCapital {
+112
View File
@@ -1512,6 +1512,118 @@ pub fn unrecovered_cost<T: Amount>(revenue: T, expenses: T) -> Option<T> {
Some(if gap > T::ZERO { gap } else { T::ZERO })
}
/// Where a document's running balance first leaves `0 ..= total`, if it
/// ever does ([`running_bounds`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Bounds {
/// Every running balance is within `0 ..= total`.
Within,
/// After step `i` (0-based) the balance is below zero: more paid than
/// the document is for, or a void under a payment that stands.
Below(usize),
/// After step `i` the balance is above the total: more owed than the
/// document is for (a payment's reversal re-instating its document's
/// origin beside another).
Above(usize),
/// A running balance can't be represented exactly.
Overflow,
}
/// A document's bounds over time: `deltas` are what each date moves its
/// outstanding balance by, in date order (one per date, that date's
/// movements summed), starting from nothing owed.
///
/// ```text
/// GOAL: one definition of "a document is never overpaid and never owes
/// more than it is for", at every date, not only at the end.
/// SOURCE: docs/spec/rules.md B-38 INVARIANT 2 (0 <= outstanding(d, D)
/// <= total(d) at every D); plan/served.md P4b.3 (Bounds).
/// INVARIANTS:
/// 1. Within exactly when every prefix sum of `deltas` is within
/// 0 ..= total; else the first prefix that isn't: Below when it is
/// under zero, Above when it is over the total.
/// 2. NEVER wraps: Overflow when a prefix sum can't be represented.
/// 3. Empty `deltas` is Within (nothing owed, nothing paid).
/// ```
pub fn running_bounds<T: Amount>(total: T, deltas: &[T]) -> Bounds {
let mut running = T::ZERO;
for (i, &d) in deltas.iter().enumerate() {
running = match running.checked_add(d) {
Some(r) => r,
None => return Bounds::Overflow,
};
if running < T::ZERO {
return Bounds::Below(i);
}
if running > total {
return Bounds::Above(i);
}
}
Bounds::Within
}
/// How far a running balance is outside `0 ..= total` (zero inside), and
/// whether below; `None` when that can't be represented.
fn out_of_bounds<T: Amount>(total: T, running: T) -> Option<(T, bool)> {
if running < T::ZERO {
Some((running.checked_neg()?, true))
} else if running > total {
Some((running.checked_sub(total)?, false))
} else {
Some((T::ZERO, false))
}
}
/// Whether moving a document from `before` to `after` keeps its bounds:
/// both are its movements by date over the same dates (a date with
/// nothing moving is zero). At every date, `after` must be within
/// `0 ..= total`, or no further outside than `before` was there.
///
/// ```text
/// GOAL: a command never puts a document out of bounds, yet books an
/// earlier version left out of bounds (a void under a payment that
/// stands) take the step that mends them.
/// SOURCE: docs/spec/rules.md B-38 INVARIANT 2, B-28 (replay accepts what
/// was written; the bound is the commands'); plan/served.md
/// P4b.14 item 3 (the remedy: reverse the payment).
/// INVARIANTS:
/// 1. When `before` is within bounds at every date (running_bounds is
/// Within), the result is running_bounds(total, after): the
/// definition exactly.
/// 2. Within means no prefix of `after` is further outside 0 ..= total
/// than the same prefix of `before`; else the first prefix that is,
/// Below or Above by where it went. Only the distance counts, not
/// the side: books out of bounds below (overpaid by 5) may take a
/// step that leaves them above by 3 (over-owed), nearer the range.
/// Intended: any step that mends is taken, and these commands
/// never write a book out of bounds in the first place (INVARIANT 1).
/// 3. NEVER wraps: Overflow when a prefix can't be represented.
/// 4. Slices of different lengths: the missing movements are zero.
/// ```
pub fn bounds_kept<T: Amount>(total: T, before: &[T], after: &[T]) -> Bounds {
let (mut was, mut now) = (T::ZERO, T::ZERO);
for i in 0..before.len().max(after.len()) {
let step = |r: T, d: Option<&T>| r.checked_add(d.copied().unwrap_or(T::ZERO));
let (Some(w), Some(n)) = (step(was, before.get(i)), step(now, after.get(i))) else {
return Bounds::Overflow;
};
(was, now) = (w, n);
let (Some((by_was, _)), Some((by_now, below))) =
(out_of_bounds(total, was), out_of_bounds(total, now))
else {
return Bounds::Overflow;
};
if by_now > by_was {
return if below {
Bounds::Below(i)
} else {
Bounds::Above(i)
};
}
}
Bounds::Within
}
#[cfg(test)]
mod tests {
use super::*;
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -48,8 +48,9 @@ pub mod tax_capital;
pub use account::{Account, AccountId, AccountType, ChartOfAccounts, Side};
pub use arap::{
AgingRow, Bill, BillId, Customer, CustomerId, DocumentLine, DocumentStatus, Invoice, InvoiceId,
Vendor, VendorId,
AgingRow, Bill, BillId, ControlCheck, Customer, CustomerId, DocLine, DocRef, DocState,
DocStatus, DocTag, DocumentLine, DocumentStatus, Invoice, InvoiceId, Movement, PaymentDetails,
UnattachedLine, Vendor, VendorId,
};
pub use assets::{
Asset, AssetBasis, AssetCorrection, AssetId, AssetStatus, BasisRule, DepreciationMethod,
+8
View File
@@ -512,6 +512,14 @@ pub fn replaying<T>(f: impl FnOnce() -> T) -> T {
f()
}
/// Whether a journaled line is being replayed now ([`replaying`]): the
/// rules a later version added that refuse new work (the control guard,
/// a document's bounds, rules.md B-38) never refuse a line an earlier
/// version accepted (B-28).
pub fn is_replaying() -> bool {
REPLAYING.with(std::cell::Cell::get)
}
/// The separators P2 (and every version before P3) read between a TIN's
/// digits: space, hyphen, dot, slash, underscore, the no-break space and
/// the dashes U+2010 to U+2014 and U+2212.
+85
View File
@@ -1807,6 +1807,91 @@ fn unrecovered_cost_laws() {
kani::cover!(u == 0 && revenue > expenses, "repaid, and more");
}
/// `kernel::running_bounds` (rules.md B-38 INVARIANT 2; the bounds every
/// document command and reversal checks), for every total and every
/// sequence of up to `N` dated movements a line could carry: it says
/// Within exactly when every running balance is in `0 ..= total`, and
/// otherwise names the first one that isn't, and which way it left.
#[kani::proof]
#[kani::unwind(6)]
fn bounds_check_matches_definition() {
let total = any_amount();
kani::assume(total > 0);
let deltas: [i64; N] = core::array::from_fn(|_| any_amount());
let n = any_len();
let got = kernel::running_bounds(total, &deltas[..n]);
// The definition, in wide arithmetic: amounts are at most 2^40 and at
// most N are summed, so no prefix overflows (got is never Overflow).
let mut running = 0i64;
let mut first: Option<(usize, bool)> = None;
for (i, &d) in deltas[..n].iter().enumerate() {
running += d;
if first.is_none() && (running < 0 || running > total) {
first = Some((i, running < 0));
}
}
match first {
None => assert_eq!(got, kernel::Bounds::Within),
Some((i, true)) => assert_eq!(got, kernel::Bounds::Below(i)),
Some((i, false)) => assert_eq!(got, kernel::Bounds::Above(i)),
}
kani::cover!(
got == kernel::Bounds::Within && n == N,
"a whole history in bounds"
);
kani::cover!(matches!(got, kernel::Bounds::Below(_)), "overpaid");
kani::cover!(
matches!(got, kernel::Bounds::Above(_)),
"owes more than its total"
);
}
/// `kernel::bounds_kept` (the check every document command and reversal
/// runs, rules.md B-38 INVARIANT 2): on books in bounds at every date it
/// is the definition (`running_bounds` of the books after the step); and
/// whenever it says Within, no running balance after the step is further
/// outside `0 ..= total` than before it, so a step that mends books an
/// earlier version left out of bounds is taken and none makes them worse.
#[kani::proof]
#[kani::unwind(6)]
fn bounds_kept_is_the_definition_on_books_in_bounds() {
let total = any_amount();
kani::assume(total > 0);
let before: [i64; N] = core::array::from_fn(|_| any_amount());
let after: [i64; N] = core::array::from_fn(|_| any_amount());
let n = any_len();
let got = kernel::bounds_kept(total, &before[..n], &after[..n]);
let out = |r: i64| {
if r < 0 {
-r
} else if r > total {
r - total
} else {
0
}
};
let was_within = kernel::running_bounds(total, &before[..n]) == kernel::Bounds::Within;
if was_within {
assert_eq!(got, kernel::running_bounds(total, &after[..n]));
}
if got == kernel::Bounds::Within {
let (mut was, mut now) = (0i64, 0i64);
for i in 0..n {
was += before[i];
now += after[i];
assert!(out(now) <= out(was));
}
}
kani::cover!(
got == kernel::Bounds::Within && !was_within,
"a step that mends out-of-bounds books"
);
kani::cover!(
matches!(got, kernel::Bounds::Below(_)),
"a step that overpays"
);
}
// ---------------------------------------------------------------------------
// The checker itself
// ---------------------------------------------------------------------------