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
// ---------------------------------------------------------------------------
+34 -17
View File
@@ -383,6 +383,12 @@ struct Event {
/// The payment method (an `setup.instruments` label) it was paid with.
#[serde(default)]
instrument: Option<String>,
/// An entry as an earlier version could write it and this version's
/// commands refuse: a line by hand on a receivables or payables
/// account (the control guard, rules.md B-38). Posted as replay posts
/// it, since books that hold it must still read right.
#[serde(default)]
older: bool,
}
/// A depreciation run of `asset` for `period` ("YYYY-MM"): what is due
@@ -1315,6 +1321,10 @@ impl<'a> Books<'a> {
"describes its own entries: no description"
}
);
assert!(
!e.older || kind == "lines",
"{ex} event {n}: older is an entry's lines, as an earlier version wrote them"
);
assert!(
e.payee.is_none() || kind == "lines",
"{ex} event {n}: a payee is an entry's: a reversal takes its original's, a bill names its vendor, an invoice its customer, a close and a command have none"
@@ -1471,25 +1481,32 @@ impl<'a> Books<'a> {
let day = || when.expect("checked: dated");
match kind {
"lines" => {
let entry = self.store.create_entry(day(), description)?;
for (i, line) in e.lines.iter().enumerate() {
let side = match line.side.as_str() {
"debit" => Side::Debit,
"credit" => Side::Credit,
other => panic!("{what}: side {other:?}"),
};
let amount = Money::new(money(&line.amount), self.currency);
let account = self.id(&line.account);
self.store.add_line(entry, account, side, amount)?;
// Tagged as books.add_line tags it: after the line.
if let Some(p) = &line.project {
let class = *self.projects.get(p).unwrap_or_else(|| {
panic!("{what}: project {p:?} not in setup.projects")
});
self.store.set_line_class(entry, i, Some(class))?;
let post = |this: &mut Self| -> Result<(), StoreError> {
let entry = this.store.create_entry(day(), description)?;
for (i, line) in e.lines.iter().enumerate() {
let side = match line.side.as_str() {
"debit" => Side::Debit,
"credit" => Side::Credit,
other => panic!("{what}: side {other:?}"),
};
let amount = Money::new(money(&line.amount), this.currency);
let account = this.id(&line.account);
this.store.add_line(entry, account, side, amount)?;
// Tagged as books.add_line tags it: after the line.
if let Some(p) = &line.project {
let class = *this.projects.get(p).unwrap_or_else(|| {
panic!("{what}: project {p:?} not in setup.projects")
});
this.store.set_line_class(entry, i, Some(class))?;
}
}
this.store.post_entry(entry)
};
if e.older {
ledger_core::parties::replaying(|| post(self))
} else {
post(self)
}
self.store.post_entry(entry)
}
"reverses" => {
let of = e.reverses.expect("checked: a reversal");
+20 -10
View File
@@ -114,11 +114,17 @@ fn pay(
cr: AccountId,
amt: &str,
) -> EntryId {
let e = l.create_entry(date, "payment");
let m = Money::new(dec(amt), Currency::USD);
l.add_line(e, dr, Side::Debit, m).unwrap();
l.add_line(e, cr, Side::Credit, m).unwrap();
l.post_entry(e).unwrap();
// As replay posts it: money from a vendor on receivables (1200) by
// hand, as books an earlier version wrote can hold it; the control
// guard (rules.md B-38) refuses that as new work.
let e = ledger_core::parties::replaying(|| {
let e = l.create_entry(date, "payment");
let m = Money::new(dec(amt), Currency::USD);
l.add_line(e, dr, Side::Debit, m).unwrap();
l.add_line(e, cr, Side::Credit, m).unwrap();
l.post_entry(e).unwrap();
e
});
if let Some(v) = vendor {
l.set_entry_vendor(e, Some(v)).unwrap();
}
@@ -2433,11 +2439,15 @@ proptest! {
if dr == cr {
continue;
}
let e = l.create_entry(d(2026, month, 10), "generated");
let m = Money::new(Decimal::new(i64::from(cents), 2), Currency::USD);
l.add_line(e, accounts[dr], Side::Debit, m).unwrap();
l.add_line(e, accounts[cr], Side::Credit, m).unwrap();
l.post_entry(e).unwrap();
// As replay posts it (a hand line on receivables: see `pay`).
let e = ledger_core::parties::replaying(|| {
let e = l.create_entry(d(2026, month, 10), "generated");
let m = Money::new(Decimal::new(i64::from(cents), 2), Currency::USD);
l.add_line(e, accounts[dr], Side::Debit, m).unwrap();
l.add_line(e, accounts[cr], Side::Credit, m).unwrap();
l.post_entry(e).unwrap();
e
});
l.set_entry_vendor(e, Some(vendors[v])).unwrap();
if let Some(i) = methods[method % methods.len()] {
l.set_entry_instrument(e, Some(i)).unwrap();
+97 -38
View File
@@ -32,11 +32,17 @@ fn usd(amount: u64) -> Money {
/// Post a balanced entry in one call. Panics on programmer error: fixtures
/// must be valid by construction.
fn post(ledger: &mut Ledger, date: NaiveDate, description: &str, lines: &[(AccountId, Side, u64)]) {
let id = ledger.create_entry(date, description);
for (account, side, amount) in lines {
ledger.add_line(id, *account, *side, usd(*amount)).unwrap();
}
ledger.post_entry(id).unwrap();
// As replay posts it: these books hold hand lines on receivables or
// payables (1200, 2000), which books an earlier version wrote still
// hold and every report must read; the control guard (rules.md B-38)
// refuses them as new work.
ledger_core::parties::replaying(|| {
let id = ledger.create_entry(date, description);
for (account, side, amount) in lines {
ledger.add_line(id, *account, *side, usd(*amount)).unwrap();
}
ledger.post_entry(id).unwrap();
})
}
struct Company {
@@ -649,21 +655,26 @@ fn random_balanced_journals_preserve_invariants() {
c.rent,
];
for i in 0..300u32 {
let total = rng.next(100_000) + 100;
let nd = (rng.next(3) + 1) as usize;
let nc = (rng.next(3) + 1) as usize;
let id = ledger.create_entry(date(21), &format!("random {i}"));
for part in split_total(&mut rng, total, nd) {
let acct = accounts[rng.next(accounts.len() as u64) as usize];
ledger.add_line(id, acct, Side::Debit, usd(part)).unwrap();
// As replay posts them: random lines land on receivables and
// payables by hand, as books an earlier version wrote can hold them
// (the control guard, rules.md B-38, refuses them as new work).
ledger_core::parties::replaying(|| {
for i in 0..300u32 {
let total = rng.next(100_000) + 100;
let nd = (rng.next(3) + 1) as usize;
let nc = (rng.next(3) + 1) as usize;
let id = ledger.create_entry(date(21), &format!("random {i}"));
for part in split_total(&mut rng, total, nd) {
let acct = accounts[rng.next(accounts.len() as u64) as usize];
ledger.add_line(id, acct, Side::Debit, usd(part)).unwrap();
}
for part in split_total(&mut rng, total, nc) {
let acct = accounts[rng.next(accounts.len() as u64) as usize];
ledger.add_line(id, acct, Side::Credit, usd(part)).unwrap();
}
ledger.post_entry(id).unwrap();
}
for part in split_total(&mut rng, total, nc) {
let acct = accounts[rng.next(accounts.len() as u64) as usize];
ledger.add_line(id, acct, Side::Credit, usd(part)).unwrap();
}
ledger.post_entry(id).unwrap();
}
});
// Every invariant still holds after 300 random balanced entries.
let tb = trial_balance(&ledger);
@@ -1484,27 +1495,61 @@ fn a_period_ending_inside_a_closed_period_cannot_close() {
}
/// Replay (for journaling stores) rebuilds invoice and bill records
/// exactly: ids follow the allocator, payments accumulate, vendors tag
/// the entries. A record replayed out of order is refused.
/// exactly: ids follow the allocator, each record tags its entry's control
/// line and each payment its entry's (rules.md B-38), vendors tag the
/// entries. A record replayed out of order is refused.
#[test]
fn replayed_documents_and_payments_rebuild_the_records() {
use ledger_core::DocumentStatus;
let mut l = books_with("2000", "Accounts Payable", AccountType::Liability, false);
let cash = l.chart().find_by_code("1000").unwrap().id;
let ap = l.chart().find_by_code("2000").unwrap().id;
let ar = l
.add_account(
"1200",
"Accounts Receivable",
AccountType::Asset,
None,
false,
)
.unwrap();
let revenue = l
.add_account("4000", "Revenue", AccountType::Revenue, None, false)
.unwrap();
let expense = l
.add_account(
"6999",
"General Expenses",
AccountType::Expense,
None,
false,
)
.unwrap();
// An entry as replay rebuilds it from its own events.
let entry = |l: &mut Ledger, dr, cr, n: u64| {
let e = l.create_entry(date(5), "replayed");
l.replay_add_line(e, dr, Side::Debit, usd(n)).unwrap();
l.replay_add_line(e, cr, Side::Credit, usd(n)).unwrap();
l.replay_post_entry(e).unwrap();
e
};
let c = l.add_customer("Acme").unwrap();
let v = l.add_vendor("Vend").unwrap();
let inv = l.next_invoice_id();
let e = entry(&mut l, ar, revenue, 100);
assert_eq!(
l.replay_invoice(inv + 1, c, date(5), date(30), doc(100), 10),
l.replay_invoice(inv + 1, c, date(5), date(30), doc(100), e),
Err(LedgerError::ReplayIdMismatch(inv + 1, inv))
);
l.replay_invoice(inv, c, date(5), date(30), doc(100), 10)
l.replay_invoice(inv, c, date(5), date(30), doc(100), e)
.unwrap();
// Each later record replays at the id the allocator now predicts.
let mut ids = vec![inv];
for entry in [13, 14] {
for _ in 0..2 {
let next = l.next_invoice_id();
l.replay_invoice(next, c, date(5), date(30), doc(1), entry)
let e = entry(&mut l, ar, revenue, 1);
l.replay_invoice(next, c, date(5), date(30), doc(1), e)
.unwrap();
ids.push(next);
}
@@ -1512,38 +1557,52 @@ fn replayed_documents_and_payments_rebuild_the_records() {
ids.dedup();
assert_eq!(ids.len(), 3);
assert!(ids.iter().all(|&i| l.get_invoice(i).is_some()));
l.replay_invoice_payment(inv, Decimal::from(30), 11)
.unwrap();
l.replay_invoice_payment(inv, Decimal::from(20), 12)
.unwrap();
for n in [30, 20] {
let p = entry(&mut l, cash, ar, n);
l.replay_invoice_payment(inv, Decimal::from(n), p).unwrap();
assert_eq!(
l.line_doc(p, 1).map(|t| t.doc),
Some(ledger_core::DocRef::Invoice(inv))
);
}
let i = l.get_invoice(inv).unwrap();
assert_eq!(i.amount_paid, Decimal::from(50));
assert_eq!(i.balance().unwrap(), Decimal::from(50));
assert_eq!(i.status, DocumentStatus::Partial);
let st = l.invoice_state(inv, date(31)).unwrap().unwrap();
assert_eq!(
(st.paid, st.outstanding),
(Decimal::from(50), Decimal::from(50))
);
let bill = l.next_bill_id();
let e = entry(&mut l, expense, ap, 100);
assert_eq!(
l.replay_bill(bill + 1, v, date(5), date(30), doc(100), 20),
l.replay_bill(bill + 1, v, date(5), date(30), doc(100), e),
Err(LedgerError::ReplayIdMismatch(bill + 1, bill))
);
assert_eq!(l.entry_vendor(20), None);
l.replay_bill(bill, v, date(5), date(30), doc(100), 20)
assert_eq!(l.entry_vendor(e), None);
l.replay_bill(bill, v, date(5), date(30), doc(100), e)
.unwrap();
assert_eq!(l.entry_vendor(20), Some(v));
assert_eq!(l.entry_vendor(e), Some(v));
let mut ids = vec![bill];
for entry in [23, 24] {
for _ in 0..2 {
let next = l.next_bill_id();
l.replay_bill(next, v, date(5), date(30), doc(1), entry)
let e = entry(&mut l, expense, ap, 1);
l.replay_bill(next, v, date(5), date(30), doc(1), e)
.unwrap();
ids.push(next);
}
ids.sort();
ids.dedup();
assert_eq!(ids.len(), 3);
l.replay_bill_payment(bill, Decimal::from(30), 21).unwrap();
l.replay_bill_payment(bill, Decimal::from(70), 22).unwrap();
let mut last = 0;
for n in [30, 70] {
last = entry(&mut l, ap, cash, n);
l.replay_bill_payment(bill, Decimal::from(n), last).unwrap();
}
let b = l.get_bill(bill).unwrap();
assert_eq!(b.amount_paid, Decimal::from(100));
assert_eq!(b.status, DocumentStatus::Paid);
assert_eq!(l.entry_vendor(22), Some(v));
assert_eq!(l.entry_vendor(last), Some(v));
}
+4 -1
View File
@@ -360,7 +360,10 @@ impl Model {
// Commands
// ---------------------------------------------------------------------------
const CODES: [&str; 7] = ["1000", "2000", "3000", "3999", "4000", "6000", "1900"];
// No 1200 or 2000: a line by hand on a receivables or payables account is
// refused (the control guard, rules.md B-38), which this model leaves to
// spec_arap.rs.
const CODES: [&str; 7] = ["1000", "2100", "3000", "3999", "4000", "6000", "1900"];
/// New names: a free one, its own in other capitals and spacing, a
/// sibling's (the accounts are named for their codes), blank, nine
/// digits, the engine's own name for retained earnings.
+7 -4
View File
@@ -173,9 +173,10 @@ fn net_for(lines: &[(AccountId, Side, Decimal)], account: AccountId) -> Decimal
// ------------------------------------------------- Invoice / Bill methods
/// Oracle: Invoice doc: total() is "Total of all lines", balance() is
/// "Amount still owed" = total - amount_paid.
/// "Amount still owed" (its `owed`, derived by the ledger beside
/// amount_paid: total - amount_paid while it stands).
#[test]
fn invoice_total_is_sum_of_lines_and_balance_is_total_minus_paid() {
fn invoice_total_is_sum_of_lines_and_balance_is_what_is_owed() {
let inv = Invoice {
id: 7,
customer_id: 1,
@@ -183,6 +184,7 @@ fn invoice_total_is_sum_of_lines_and_balance_is_total_minus_paid() {
due_date: d(2026, 3, 31),
lines: vec![line("a", "100.10"), line("b", "0.05"), line("c", "49.85")],
amount_paid: dec("60.00"),
owed: dec("90.00"),
status: DocumentStatus::Partial,
entry_id: 1,
};
@@ -190,9 +192,9 @@ fn invoice_total_is_sum_of_lines_and_balance_is_total_minus_paid() {
assert_eq!(inv.balance().unwrap(), dec("90.00"));
}
/// Oracle: Bill doc: total() is the sum of lines, balance() total - paid.
/// Oracle: Bill doc: total() is the sum of lines, balance() what is owed.
#[test]
fn bill_total_is_sum_of_lines_and_balance_is_total_minus_paid() {
fn bill_total_is_sum_of_lines_and_balance_is_what_is_owed() {
let bill = Bill {
id: 3,
vendor_id: 2,
@@ -200,6 +202,7 @@ fn bill_total_is_sum_of_lines_and_balance_is_total_minus_paid() {
due_date: d(2026, 3, 1),
lines: vec![line("x", "19.99"), line("y", "0.01")],
amount_paid: dec("20.00"),
owed: Decimal::ZERO,
status: DocumentStatus::Paid,
entry_id: 9,
};
+10 -14
View File
@@ -605,9 +605,10 @@ fn replayed_bases_and_shares_past_the_limit_are_accepted() {
);
}
/// A replayed payment is as journaled: no bound but exact arithmetic (a
/// paid amount past it is refused, never wrapped). The command's bound is
/// the balance (Overpayment).
/// A replayed payment is as journaled: no bound (rules.md B-28), and no
/// refusal: it tags the line of its entry that carries it, or (an entry
/// it doesn't match) nothing. The command's bound is what the invoice
/// owes (Overpayment).
#[test]
fn replayed_payments_are_as_journaled() {
let mut b = books();
@@ -630,24 +631,19 @@ fn replayed_payments_are_as_journaled() {
.receive_payment(invoice, d(2026, 1, 15), too_big(), b.cash),
Err(LedgerError::Overpayment(..))
));
let before = b.ledger.clone();
b.ledger
.replay_invoice_payment(invoice, too_big(), 98)
.unwrap();
b.ledger
.replay_invoice_payment(invoice, Decimal::MAX - too_big(), 99)
.unwrap();
// No entry 98 or 99 carries them: nothing is tagged, nothing paid.
let doc = ledger_core::DocRef::Invoice(invoice);
assert_eq!(b.ledger.doc_lines(doc), before.doc_lines(doc));
assert_eq!(
b.ledger.get_invoice(invoice).unwrap().amount_paid,
Decimal::MAX
);
assert!(matches!(
b.ledger.replay_invoice_payment(invoice, Decimal::ONE, 100),
Err(LedgerError::TooLargeToCompute(_))
));
// Refused before anything changed.
assert_eq!(
b.ledger.get_invoice(invoice).unwrap().amount_paid,
Decimal::MAX
b.ledger.get_invoice(invoice).unwrap().balance(),
Ok(Decimal::new(10000, 2))
);
}
+15 -9
View File
@@ -50,15 +50,21 @@ impl Books {
}
fn post(&mut self, date: NaiveDate, desc: &str, lines: &[(&str, Side, &str)]) -> EntryId {
let e = self.l.create_entry(date, desc);
for &(code, side, amount) in lines {
let a = self.id(code);
self.l
.add_line(e, a, side, Money::new(x(amount), Currency::USD))
.unwrap();
}
self.l.post_entry(e).unwrap();
e
// As replay posts it: these books hold hand lines on receivables
// or payables (1200, 2000), which books an earlier version wrote
// still hold and every report must read; the control guard
// (rules.md B-38) refuses them as new work.
ledger_core::parties::replaying(|| {
let e = self.l.create_entry(date, desc);
for &(code, side, amount) in lines {
let a = self.id(code);
self.l
.add_line(e, a, side, Money::new(x(amount), Currency::USD))
.unwrap();
}
self.l.post_entry(e).unwrap();
e
})
}
fn reverse(&mut self, e: EntryId, date: NaiveDate) -> EntryId {
@@ -201,10 +201,15 @@ fn reversing_a_tagged_document_takes_its_projects_to_zero() {
(t.revenue, t.expenses)
};
assert_eq!(to_date(&b.l, z), (cents(300_000), cents(120_000)));
b.l.receive_payment(inv, d(2026, 3, 20), cents(100_000), b.cash)
.unwrap();
let pay =
b.l.receive_payment(inv, d(2026, 3, 20), cents(100_000), b.cash)
.unwrap();
assert_eq!(to_date(&b.l, z), (cents(300_000), cents(120_000)));
assert_eq!(to_date(&b.l, h), (cents(20_000), Decimal::ZERO));
// The payment first: a void waits on the payments that stand (B-38
// scenario 3); its reversal moves no project figure either.
b.l.reverse_entry(pay, d(2026, 3, 30), "Bounced").unwrap();
assert_eq!(to_date(&b.l, z), (cents(300_000), cents(120_000)));
for e in [
b.l.get_invoice(inv).unwrap().entry_id,
b.l.get_bill(bill).unwrap().entry_id,
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -2468,7 +2468,7 @@ proptest! {
let mut l = Ledger::new(Currency::USD);
let ids: Vec<_> = [
("1000", AccountType::Asset),
("2000", AccountType::Liability),
("2100", AccountType::Liability),
("4000", AccountType::Revenue),
("6100", AccountType::Expense),
]
@@ -2564,7 +2564,7 @@ proptest! {
let mut l = Ledger::new(Currency::USD);
let ids: Vec<_> = [
("1000", AccountType::Asset),
("2000", AccountType::Liability),
("2100", AccountType::Liability),
("4000", AccountType::Revenue),
("6100", AccountType::Expense),
]
+2 -2
View File
@@ -28,7 +28,7 @@ fn usd(c: i64) -> Money {
Money::new(cents(c), Currency::USD)
}
/// Cash 1000, equipment 1200, revenue 4000, contractors 6000, rent 6200.
/// Cash 1000, equipment 1500, revenue 4000, contractors 6000, rent 6200.
struct Books {
l: Ledger,
cash: u64,
@@ -42,7 +42,7 @@ fn books() -> Books {
let mut l = Ledger::new(Currency::USD);
let mut add = |code: &str, t| l.add_account(code, code, t, None, false).unwrap();
let cash = add("1000", AccountType::Asset);
let equipment = add("1200", AccountType::Asset);
let equipment = add("1500", AccountType::Asset);
let revenue = add("4000", AccountType::Revenue);
let contractors = add("6000", AccountType::Expense);
let rent = add("6200", AccountType::Expense);
@@ -283,22 +283,43 @@ fn a_draft_of_decimals_largest_is_refused_where_summed() {
assert!(why.contains("too large to compute"), "{why}");
}
/// A document is restored as journaled: its total and balance are exact,
/// or refused past exact arithmetic; aging sums by party, checked.
/// A document is restored as journaled: its total is exact, or refused
/// past exact arithmetic; what it owes is what the ledger lines tagged
/// with it carry (rules.md B-38), exact, whatever the journal held (paid
/// above its total included); aging refuses a document whose total it
/// can't compute.
#[test]
fn documents_and_aging_are_exact_or_refused() {
let mut l = Ledger::new(Currency::USD);
let ar = l
.add_account("1200", "Receivables", AccountType::Asset, None, false)
.unwrap();
let revenue = l
.add_account("4000", "Revenue", AccountType::Revenue, None, false)
.unwrap();
let cash = l
.add_account("1000", "Cash", AccountType::Asset, None, false)
.unwrap();
let customer = l.add_customer("Client").unwrap();
let line = |a: Decimal| DocumentLine {
description: "x".into(),
amount: a,
class_id: None,
};
// An entry as replay rebuilds it: Dr `dr` / Cr `cr` for `a`.
let replayed = |l: &mut Ledger, dr, cr, a: Decimal| {
let e = l.create_entry(d(2026, 3, 1), "replayed");
l.replay_add_line(e, dr, Side::Debit, usd(a)).unwrap();
l.replay_add_line(e, cr, Side::Credit, usd(a)).unwrap();
l.replay_post_entry(e).unwrap();
e
};
let fine = vec![
line(Decimal::new(1, 11)),
line("9.99999999999".parse().unwrap()),
];
l.replay_invoice(1, customer, d(2026, 3, 1), d(2026, 3, 31), fine, 1)
let e1 = replayed(&mut l, ar, revenue, Decimal::TEN);
l.replay_invoice(1, customer, d(2026, 3, 1), d(2026, 3, 31), fine, e1)
.unwrap();
let inv = l.get_invoice(1).unwrap();
assert_eq!(inv.total(), Ok(Decimal::TEN));
@@ -307,8 +328,9 @@ fn documents_and_aging_are_exact_or_refused() {
// 62 days past due on June 1st: 61-90.
assert_eq!(rows[0].days_90, Decimal::TEN);
assert_eq!(rows[0].total(), Ok(Decimal::TEN));
// Two documents of half Decimal's largest each: each is exact, the
// party's aging bucket is not.
// Two documents of half Decimal's largest each, their totals exact; no
// line carries them (no entry could), so they owe nothing and age
// nowhere.
let half = Decimal::MAX / Decimal::TWO;
for id in [2, 3] {
l.replay_invoice(
@@ -317,40 +339,44 @@ fn documents_and_aging_are_exact_or_refused() {
d(2026, 3, 1),
d(2026, 3, 31),
vec![line(half)],
id,
100 + id,
)
.unwrap();
assert_eq!(l.get_invoice(id).unwrap().total(), Ok(half));
let st = l.invoice_state(id, d(2026, 6, 1)).unwrap().unwrap();
assert_eq!(st.outstanding, Decimal::ZERO);
}
assert!(too_large(l.ar_aging(d(2026, 6, 1))));
assert_eq!(
l.ar_aging(d(2026, 6, 1)).unwrap()[0].total(),
Ok(Decimal::TEN)
);
// Paid more than its total, as journaled: a negative balance, exact.
l.replay_invoice_payment(1, Decimal::from(11), 9).unwrap();
let p = replayed(&mut l, cash, ar, Decimal::from(11));
l.replay_invoice_payment(1, Decimal::from(11), p).unwrap();
assert_eq!(l.get_invoice(1).unwrap().balance(), Ok(-Decimal::ONE));
// A total of lines that overflow, and its balance.
let st = l.invoice_state(1, d(2026, 6, 1)).unwrap().unwrap();
assert_eq!(
(st.paid, st.outstanding),
(Decimal::from(11), -Decimal::ONE)
);
// A payment event naming an amount no line of its entry carries tags
// nothing, and is refused nothing (B-28).
l.replay_invoice_payment(1, -Decimal::ONE, p).unwrap();
assert_eq!(l.get_invoice(1).unwrap().balance(), Ok(-Decimal::ONE));
// A total of lines that overflow, and its balance; aging refuses it.
l.replay_invoice(
4,
customer,
d(2026, 3, 1),
d(2026, 3, 31),
vec![line(Decimal::MAX), line(Decimal::MAX)],
4,
104,
)
.unwrap();
assert!(too_large(l.get_invoice(4).unwrap().total()));
assert!(too_large(l.get_invoice(4).unwrap().balance()));
// A balance past exact arithmetic: a total of Decimal's largest paid
// a negative amount.
l.replay_invoice(
5,
customer,
d(2026, 3, 1),
d(2026, 3, 31),
vec![line(Decimal::MAX)],
5,
)
.unwrap();
l.replay_invoice_payment(5, -Decimal::ONE, 10).unwrap();
assert!(too_large(l.get_invoice(5).unwrap().balance()));
assert!(too_large(l.ar_aging(d(2026, 6, 1))));
assert!(too_large(l.invoice_state(4, d(2026, 6, 1))));
// Bills alike.
let vendor = l.add_vendor("Supplier").unwrap();
l.replay_bill(
@@ -359,7 +385,7 @@ fn documents_and_aging_are_exact_or_refused() {
d(2026, 3, 1),
d(2026, 3, 31),
vec![line(Decimal::MAX), line(Decimal::ONE)],
6,
106,
)
.unwrap();
assert!(too_large(l.get_bill(1).unwrap().total()));
+50 -32
View File
@@ -40,12 +40,18 @@ fn usd(cents: i64) -> Money {
}
fn post(l: &mut Ledger, date: NaiveDate, desc: &str, lines: &[(AccountId, Side, i64)]) -> EntryId {
let e = l.create_entry(date, desc);
for &(a, s, cents) in lines {
l.add_line(e, a, s, usd(cents)).unwrap();
}
l.post_entry(e).unwrap();
e
// As replay posts it: these books hold hand lines on receivables or
// payables (1200, 2000), which books an earlier version wrote still
// hold and every report must read; the control guard (rules.md B-38)
// refuses them as new work.
ledger_core::parties::replaying(|| {
let e = l.create_entry(date, desc);
for &(a, s, cents) in lines {
l.add_line(e, a, s, usd(cents)).unwrap();
}
l.post_entry(e).unwrap();
e
})
}
fn draft(l: &mut Ledger, date: NaiveDate, lines: &[(AccountId, Side, i64)]) -> EntryId {
@@ -1784,22 +1790,28 @@ fn build_ordered(gens: &[Gen], scale: i64, order: &[usize], tag: bool) -> Books
let class_a = l.add_class("Alpha").unwrap();
let class_b = l.add_class("Beta").unwrap();
let mut entries = Vec::new();
for g in gens {
let e = l.create_entry(g.date(), "gen");
for (n, (i, side, cents)) in g.legs(scale).into_iter().enumerate() {
l.add_line(e, ids[i], side, usd(cents)).unwrap();
if tag {
let k = match g.classes[n] {
1 => Some(class_a),
2 => Some(class_b),
_ => None,
};
l.set_line_class(e, n, k).unwrap();
// As replay posts it: these books hold hand lines on receivables or
// payables (1200, 2000), which books an earlier version wrote still
// hold and every report must read; the control guard (rules.md B-38)
// refuses them as new work.
ledger_core::parties::replaying(|| {
for g in gens {
let e = l.create_entry(g.date(), "gen");
for (n, (i, side, cents)) in g.legs(scale).into_iter().enumerate() {
l.add_line(e, ids[i], side, usd(cents)).unwrap();
if tag {
let k = match g.classes[n] {
1 => Some(class_a),
2 => Some(class_b),
_ => None,
};
l.set_line_class(e, n, k).unwrap();
}
}
l.post_entry(e).unwrap();
entries.push(e);
}
l.post_entry(e).unwrap();
entries.push(e);
}
});
Books {
l,
ids,
@@ -2000,12 +2012,15 @@ proptest! {
let mut b = build(&gens);
let tb0 = tb_lines(&trial_balance_as_of(&b.l, day(as_of)));
let pl0 = pnl_key(&profit_and_loss_for_period(&b.l, d(2026, 1, 1), day(as_of), None).unwrap());
let e = b.l.create_entry(extra.date(), "extra");
for (i, side, cents) in extra.legs(1) {
b.l.add_line(e, b.ids[i], side, usd(cents)).unwrap();
}
b.l.post_entry(e).unwrap();
b.l.reverse_entry(e, extra.date(), "undo").unwrap();
// As replay posts it (hand lines on 1200 or 2000: see `post`).
ledger_core::parties::replaying(|| {
let e = b.l.create_entry(extra.date(), "extra");
for (i, side, cents) in extra.legs(1) {
b.l.add_line(e, b.ids[i], side, usd(cents)).unwrap();
}
b.l.post_entry(e).unwrap();
b.l.reverse_entry(e, extra.date(), "undo").unwrap();
});
prop_assert_eq!(tb_lines(&trial_balance_as_of(&b.l, day(as_of))), tb0);
let pl1 = profit_and_loss_for_period(&b.l, d(2026, 1, 1), day(as_of), None).unwrap();
prop_assert_eq!(sl_nonzero(&pl1.revenue), pl0.0.into_iter().filter(|x| !x.1.is_zero()).collect::<Vec<_>>());
@@ -2027,13 +2042,16 @@ proptest! {
let gl = gl_key(&general_ledger(&b.l, s0, e0).unwrap());
let cf = cf_key(&cash_flow(&b.l, &cfp).unwrap());
let snap = snapshot(&b.l).unwrap();
for g in &drafts {
let id = b.l.create_entry(g.date(), "draft");
for (n, (i, side, cents)) in g.legs(1).into_iter().enumerate() {
if g.mode == 0 && n == 1 { continue; } // some drafts unbalanced
b.l.add_line(id, b.ids[i], side, usd(cents)).unwrap();
// As replay adds them (hand lines on 1200 or 2000: see `post`).
ledger_core::parties::replaying(|| {
for g in &drafts {
let id = b.l.create_entry(g.date(), "draft");
for (n, (i, side, cents)) in g.legs(1).into_iter().enumerate() {
if g.mode == 0 && n == 1 { continue; } // some drafts unbalanced
b.l.add_line(id, b.ids[i], side, usd(cents)).unwrap();
}
}
}
});
prop_assert_eq!(tb_lines(&trial_balance_as_of(&b.l, e0)), tb);
prop_assert_eq!(pnl_key(&profit_and_loss_for_period(&b.l, s0, e0, None).unwrap()), pl);
prop_assert_eq!(bs_key(&balance_sheet_as_of(&b.l, e0).unwrap()), bs);
+69 -14
View File
@@ -99,14 +99,20 @@ fn bal(l: &Ledger, id: AccountId) -> Decimal {
l.account_balance(id).expect("known account")
}
/// Draft, add lines, post. Panics on any refusal (setup only).
/// Draft, add lines, post. Panics on any refusal (setup only). Posted as
/// replay posts it: these books hold hand lines on receivables or payables
/// (moving a role's balance by hand, B-23's path before documents read
/// their lines), which books an earlier version wrote still hold; the
/// control guard (rules.md B-38) refuses them as new work.
fn post(l: &mut Ledger, date: NaiveDate, lines: &[(AccountId, Side, &str)]) -> EntryId {
let id = l.try_create_entry(date, "test entry").unwrap();
for (a, s, amt) in lines {
l.add_line(id, *a, *s, usd(amt)).unwrap();
}
l.post_entry(id).unwrap();
id
ledger_core::parties::replaying(|| {
let id = l.try_create_entry(date, "test entry").unwrap();
for (a, s, amt) in lines {
l.add_line(id, *a, *s, usd(amt)).unwrap();
}
l.post_entry(id).unwrap();
id
})
}
/// The (code, side, amount) lines of an entry, sorted.
@@ -788,7 +794,7 @@ fn receivables_cannot_move_while_holding_a_balance_but_can_once_moved_out() {
let old = acct(&l, "1200").expect("1200 created by the invoice");
let new = add(&mut l, "1100", "Trade Receivables", AccountType::Asset);
match refuses(&mut l, "receivables", Some(new)) {
LedgerError::RoleHoldsBalance {
LedgerError::DocumentRoleHoldsBalance {
role,
code,
balance,
@@ -798,15 +804,29 @@ fn receivables_cannot_move_while_holding_a_balance_but_can_once_moved_out() {
assert_eq!(code, "1200");
assert_eq!(balance, dec("120.00"));
}
other => panic!("expected RoleHoldsBalance, got {other:?}"),
other => panic!("expected DocumentRoleHoldsBalance, got {other:?}"),
}
// Move the balance with an entry, then the role may move.
// Moving the balance by hand is refused now (the control guard,
// rules.md B-38): until a role's balance moves with its documents
// (plan P4b S7), a receivables role holding a balance stays put.
let e = l.try_create_entry(d(2026, 3, 2), "move").unwrap();
assert!(matches!(
l.add_line(e, old, Side::Credit, usd("120.00")),
Err(LedgerError::UntaggedControlLine { .. })
));
// Books an earlier version wrote can hold such a move, and the
// assignment after it (replayed: today 1100's hand line refuses it,
// RoleAccountHasHandLines): then the documents follow the role.
post(
&mut l,
d(2026, 3, 2),
&[(new, Side::Debit, "120.00"), (old, Side::Credit, "120.00")],
);
l.assign_role("receivables", Some(new)).unwrap();
assert!(matches!(
refuses(&mut l, "receivables", Some(new)),
LedgerError::RoleAccountHasHandLines { .. }
));
ledger_core::parties::replaying(|| l.assign_role("receivables", Some(new))).unwrap();
assert_eq!(l.role_account(&RECEIVABLES), Some(new));
// The open invoice is now controlled by 1100: its payment credits it.
let p = l
@@ -845,6 +865,21 @@ fn every_balance_sheet_role_holds_while_its_account_has_a_balance() {
&format!("Target {i}"),
c.account_type,
);
if c.key == RECEIVABLES.key || c.key == PAYABLES.key {
// No document posted there: the balance is the chart's own,
// so the role moves (B-38); it can't come back to an account
// holding hand lines.
l.assign_role(c.key, Some(target)).unwrap();
assert!(
matches!(
refuses(&mut l, c.key, Some(*cur)),
LedgerError::RoleAccountHasHandLines { .. }
),
"{}",
c.key
);
continue;
}
assert!(
matches!(
refuses(&mut l, c.key, Some(target)),
@@ -877,7 +912,7 @@ fn none_is_refused_while_the_assigned_balance_sheet_account_holds_a_balance() {
.unwrap();
assert!(matches!(
refuses(&mut l, "payables", None),
LedgerError::RoleHoldsBalance { .. }
LedgerError::DocumentRoleHoldsBalance { .. }
));
let _ = cash;
}
@@ -1121,7 +1156,7 @@ fn pool_books() -> (Ledger, Vec<AccountId>) {
}
/// The reasons the spec gives to refuse an assignment, worked from the
/// current books (assign_role SCENARIOS 1–5).
/// current books (assign_role SCENARIOS 1–6).
fn predicted_refusals(
l: &Ledger,
c: &ControlAccount,
@@ -1142,10 +1177,27 @@ fn predicted_refusals(
}
let now = l.role_account(c);
let next = target.map(|a| a.id);
// SCENARIO 6: a document role never moves onto hand lines.
let documents = c.key == RECEIVABLES.key || c.key == PAYABLES.key;
if documents
&& let Some(a) = target
&& next != now
&& l.posted_entries().any(|e| {
e.lines()
.iter()
.enumerate()
.any(|(i, x)| x.account == a.id && l.line_doc(e.id(), i).is_none())
})
{
why.push("handlines");
}
// SCENARIO 4: a document role's balance holds only on its control
// account (assigned there, or holding its documents' lines).
if balance_sheet(c)
&& next != now
&& let Some(cur) = now
&& !bal(l, cur).is_zero()
&& (!documents || l.control_role_of(cur).is_some_and(|r| r.key == c.key))
{
why.push("balance");
}
@@ -1156,7 +1208,10 @@ fn reason(e: &LedgerError) -> &'static str {
match e {
LedgerError::ControlAccountMismatch { .. } => "mismatch",
LedgerError::RoleTaken { .. } => "taken",
LedgerError::RoleHoldsBalance { .. } => "balance",
LedgerError::RoleHoldsBalance { .. } | LedgerError::DocumentRoleHoldsBalance { .. } => {
"balance"
}
LedgerError::RoleAccountHasHandLines { .. } => "handlines",
_ => "other",
}
}
+11 -11
View File
@@ -9,9 +9,9 @@
//! | Jan 2 | owner contributes 10,000 | 1000 Cash | 3000 Capital |
//! | Jan 15 | client pays 2,500 | 1000 Cash | 4000 Revenue |
//! | Jan 20 | rent 800 | 6100 Rent | 1000 Cash |
//! | Feb 3 | software 120 on the card | 6000 Software | 2000 Card |
//! | Feb 3 | software 120 on the card | 6000 Software | 2050 Card |
//! | Feb 10 | client pays 1,000 | 1000 Cash | 4000 Revenue |
//! | Feb 25 | pay the card 120 | 2000 Card | 1000 Cash |
//! | Feb 25 | pay the card 120 | 2050 Card | 1000 Cash |
use chrono::NaiveDate;
use ledger_core::reports::{
@@ -57,7 +57,7 @@ fn books(close_january: bool) -> Books {
.add_account("1000", "Cash", AccountType::Asset, None, false)
.unwrap();
let card = l
.add_account("2000", "Card", AccountType::Liability, None, false)
.add_account("2050", "Card", AccountType::Liability, None, false)
.unwrap();
let capital = l
.add_account("3000", "Capital", AccountType::Equity, None, false)
@@ -160,7 +160,7 @@ fn balance_sheet_is_as_of_the_date() {
// Feb 15: cash 12,700; the card owes 120; earnings 1,700 + 880.
let mid = balance_sheet_as_of(&b.ledger, d(2, 15)).unwrap();
assert_eq!(mid.total_assets, dec(12_700));
assert_eq!(mid.liabilities, vec![line("2000", "Card", 120)]);
assert_eq!(mid.liabilities, vec![line("2050", "Card", 120)]);
assert_eq!(mid.current_earnings, dec(2_580));
assert_eq!(mid.total_liabilities + mid.total_equity, dec(12_700));
@@ -307,7 +307,7 @@ fn general_ledger_runs_balances_by_account() {
let gl = general_ledger(&b.ledger, d(2, 1), d(2, 28)).unwrap();
let codes: Vec<&str> = gl.accounts.iter().map(|a| a.code.as_str()).collect();
// Every account with a beginning balance or February activity, by code.
assert_eq!(codes, ["1000", "2000", "3000", "4000", "6000", "6100"]);
assert_eq!(codes, ["1000", "2050", "3000", "4000", "6000", "6100"]);
let cash = &gl.accounts[0];
assert_eq!(cash.beginning_balance, dec(11_700));
@@ -320,7 +320,7 @@ fn general_ledger_runs_balances_by_account() {
p,
[
(dec(1_000), dec(0), "4000 Revenue", dec(12_700)),
(dec(0), dec(120), "2000 Card", dec(12_580)),
(dec(0), dec(120), "2050 Card", dec(12_580)),
]
);
assert_eq!(cash.ending_balance, dec(12_580));
@@ -354,7 +354,7 @@ fn general_ledger_marks_compound_entries_as_split() {
.add_account("1000", "Cash", AccountType::Asset, None, false)
.unwrap();
let card = l
.add_account("2000", "Card", AccountType::Liability, None, false)
.add_account("2050", "Card", AccountType::Liability, None, false)
.unwrap();
let soft = l
.add_account("6000", "Software", AccountType::Expense, None, false)
@@ -373,7 +373,7 @@ fn general_ledger_marks_compound_entries_as_split() {
// The debit side has two other accounts; each credit has one.
assert_eq!(split_of("6000"), ("-Split-".to_string(), e));
assert_eq!(split_of("1000"), ("6000 Software".to_string(), e));
assert_eq!(split_of("2000"), ("6000 Software".to_string(), e));
assert_eq!(split_of("2050"), ("6000 Software".to_string(), e));
}
/// Two members, 50/50: Alice and Bob. January: Alice puts in 600, Bob 400;
@@ -1087,7 +1087,7 @@ fn cash_flow_labels_say_which_way_each_balance_moved() {
.add_account("1100", "Receivable", AccountType::Asset, None, false)
.unwrap();
let ap = l
.add_account("2000", "Payable", AccountType::Liability, None, false)
.add_account("2010", "Payable", AccountType::Liability, None, false)
.unwrap();
let loan = l
.add_account("2500", "Loan", AccountType::Liability, None, false)
@@ -1144,7 +1144,7 @@ fn cash_flow_labels_say_which_way_each_balance_moved() {
rec(&feb),
[
(s("Increase in 1100 Receivable"), dec(-100)),
(s("Increase in 2000 Payable"), dec(50)),
(s("Increase in 2010 Payable"), dec(50)),
]
);
assert_eq!(
@@ -1167,7 +1167,7 @@ fn cash_flow_labels_say_which_way_each_balance_moved() {
rec(&mar),
[
(s("Decrease in 1100 Receivable"), dec(100)),
(s("Decrease in 2000 Payable"), dec(-50)),
(s("Decrease in 2010 Payable"), dec(-50)),
]
);
assert_eq!(