MCP: short connect text, a handbook, tool annotations, safe local imports

- The 13K-character instructions (clients cut them short) become a
  connect text of at most 1,400 characters whose first 512 stand alone,
  plus books.handbook and books://handbook/{section}: the old guidance by
  section, with no helper commands, home paths, pull requests or
  file-reading suggestions (tool_text_lint).
- Every tool has a title and read-only/destructive hints; no
  requiresUserInteraction anywhere (owner decision 2026-10-16).
- books.import_local_file reads only regular files inside the import
  roots (the downloads folder by default, or --import-root), never the
  data dir, books dir, vault or the key's folder, no symlink escapes or
  hard links, and the file opened must be the file checked.
- The store lock is a tokio mutex taken off the runtime threads.
- get_info refreshes settings first; a bare books://digest reads.

Review fixes (P0 review, 2026-10-16):
- Fail closed: a tokio mutex never poisons and spawn_blocking caught the
  panic, so after a panic mid-mutation the server kept serving a Store
  behind its journal. A panic (the task, or while holding the store)
  now stops the shared store; every later request on every session is
  refused with a plain message; a restart re-verifies the journal. The
  join error goes through redact_refusal and never carries the panic's
  text.
- books.set_w9 w9_file_path read any path (a link named w9.pdf to the
  vault key was stored and get_w9 wrote it out): it now goes through the
  import roots' lockdown, its type judged on the canonical path.
- Sealed even inside a root: the key file in force, where a linked one
  leads, both folders, and the default key folder whatever the settings
  say. Refusals check the roots first, so outside them every path gets
  one message (no probing what exists); inside, other books-dir files say
  to copy them out first.
- The open is O_NOFOLLOW | O_NONBLOCK (a pipe swapped in after the check
  can't hang a thread) and must match the checked file's device and
  inode. New dependency: libc (unix only), for those two open flags,
  which std doesn't name.
- Default import roots are the downloads folder only (the plan); files
  with full TINs (get_w9, vendor_1099 include_tins, the CPA package with
  TINs) are never written into an import root, and the server refuses to
  import any file it wrote with TINs (by SHA-256).
- set_tin and set_w9 overwrite vault records: destructive_hint = true;
  annotations_complete pins the key tools' hints. The read-only hint is
  checked in behaviour on every spec_mcp call (journal and data-dir files
  unchanged).
- Text: the connect text names the settings file as the one local file
  to edit, says every entry balances on real accounts and names its
  party, says invoice/bill/payment/payroll tools post unchecked, rewords
  the exemptions, and shows the company name as one plain line; the
  handbook takes section "all", lists its ids in the schema and says to
  read contract first; books.settings drops the config.json path and no
  error names the data dir or the key file. tool_text_lint covers the
  whole tool JSON and resources and bans git/commit/WL-0001; tool
  descriptions over 700 characters are pinned to today's eight (P5).
- digest: an empty since= is bare; the default date is pinned on every
  day of a month.

Round-2 review fixes (2026-10-16):
- TIN files (B-26): the in-memory, per-session set of TIN-file hashes
  became one registry beside the vault (vault/tin-files.sha256, hashes
  only), shared by every session and every later server. It holds the
  W-9 set_w9 reads (recorded as read), get_w9 copies, 1099 worksheets
  with TINs, CPA packages with TINs and each file in one that holds a
  TIN; a file is recorded before it is written, and a failure refuses.
  import_local_file, attach_receipt and file_document (base64 was never
  checked) refuse a recorded file, and a text file (by type, name, or
  UTF-8/UTF-16 decoding) holding a full TIN. Not caught: an altered
  binary copy; the docs say so (P2/P7 remove the path tools).
- The text check is narrow (owner/engineer decision, 2026-10-16: bank
  exports are filed for reconciliation, and has_full_tin's "nine digits
  however separated" refused their routing numbers, long references and
  dates run into amounts). Text is refused when it holds (a) a TIN the
  vault holds for a party, anywhere, as nine digits, 3-2-4 joined by
  hyphens, spaces or dots, or 2-7 joined by a hyphen or space, compared
  on the server against the decrypted vault and never returned or
  logged (a vault that can't be opened leaves (b)); or (b) a stand-alone
  printed SSN (123-45-6789) or EIN (12-3456789) shape: no digit, and no
  hyphen or dot followed by a digit, beside it. Full-width digits and
  Unicode hyphens and spaces read as ASCII. has_full_tin still guards
  refusals and results (redact_refusal). Known limit, for P7: a refusal
  under (a) tells the agent a text it chose holds a vault TIN.
  New dependency: zeroize in ledger-mcp (already in the workspace
  through ledger-vault, same major version), so the vault's TINs decoded
  for the scan are wiped from memory on drop as the vault's own are.
- Mutation testing of the final P0 diff (docs/testing.md): tests for
  each law a survivor broke (handbook titles, a dropped default root, a
  .jpg W-9, the waker, the walk's folder flags against a link and a
  pipe, the 40-link limit, save paths refused as such, the package
  marking only its TIN files, a registry that can't be read, text types,
  the short receipt rule's counts and a 12-character code). Simpler
  code where only a race could tell: inspect places an existing path by
  canonicalize itself (no second comparison), read_checked's read limit
  is its one size check, openat fails on -1 as specified. The 25 MiB
  upload test removes its 50 MB of books however it ends.
- The GUI's stale-rule prompt no longer says to open a pull request: it
  asks the agent to find the figure from the rule's official authority,
  confirm it with the human, pass it explicitly, and tell the human so it
  can be reported upstream (as the handbook says); a lib test pins it and
  bans files, git, GitHub and pull requests from every attention prompt.
- Import roots (local_files.rs INVARIANT 0): XDG_DOWNLOAD_DIR="$HOME/"
  made $HOME (or /) the root. No root may be /, the home folder or hold
  it, or hold the books, data dir, vault or a key: a named one stops the
  server at startup, a default one is dropped; the default falls back to
  ~/Downloads only if that is a real folder other than $HOME; with no
  root, an import says so.
- The read is a component walk from / with openat(O_NOFOLLOW |
  O_DIRECTORY) per folder and O_NOFOLLOW | O_NONBLOCK for the file, so a
  folder swapped for a link after the check fails; no step may land on a
  protected inode (one renamed into a root); dev/ino and nlink stay. No
  /proc. Portable to macOS. (libc's openat, two small unsafe blocks.)
- One refusal for missing, dangling and outside paths: resolved()
  follows every link, dangling ones too, so a link's target existing or
  not no longer changes the answer.
- Sealing: the key files (in force, default) and their targets always;
  their folders only when not $HOME, not a root, not holding a root; and
  ~/.config/wanderbooks whatever XDG_CONFIG_HOME says.
- Agent text (I-12): RuleNotKnown names the authority (IRS, with its
  address) and says to tell the human, never a repo path, PR or GitHub;
  the digest's stale_rules drop the repo catalog and path for it; vault,
  outside-books, STOPPED and local-file refusals name no git, path or
  flag. tool_text_lint bans docs/, .md, /home, data dir, --data-dir,
  --import-root, vault.key, .jsonl, sqlite, .gitignore, github, pull
  request, and also lints every error template (scanned from source),
  built error texts, and the server's refusal constants.
- The receipt rule told (ReceiptPolicy::rule) is the one enforced: the
  exact threshold in the base currency (no "$", no rounding), required
  and exempt accounts, reversals exempt; the connect text fits 1,400
  characters by dropping reasons, then codes, never the rule.
- The connect text follows the parties setting; "offer books.digest"
  everywhere. shown_name drops Unicode format characters (bidi, zero
  width).
- read_only_tools_change_nothing compares file contents, the database
  by every row, the vault and the settings file (raw database bytes did
  not change either; rows are the stable comparison).
- import_local_file takes the name and type from the canonical path;
  the digest's journal repair says when the tail was set aside, not the
  journal's file name; "version-history messages" back in the TIN rule;
  openWorldHint false on every tool, pinned in annotations_complete.
- Outside the MCP crate, for the same texts: ledger-core's DatedRule
  gains `authority` (the statute or publication with its address) and
  RuleNotKnown carries it; ledger-store's "sqlite error" reads "database
  error"; ledger-config's ReceiptPolicy::rule takes the base currency.
  New dev-dependency: rusqlite in ledger-mcp (already in the workspace,
  same version and features as ledger-store), to read the database's
  rows in read_only_tools_change_nothing.
- The filing scan is no TIN oracle (tin_files.rs INVARIANT 4): text
  holding more than two TIN-shaped numbers (any rendering rule (a)
  reads) that end in a known TIN's last four (the books' TIN and W-9
  facts, via known_tin_last4, before the vault is opened; then the
  vault's own) is refused with TIN_PROBE, the same words whether or not
  one is the vault's TIN; only one or two candidates are compared
  against the vault. Tests: unit
  text_probing_for_a_tin_is_refused_alike_whether_or_not_it_holds_it,
  one_or_two_candidates_are_compared_against_the_vault; over HTTP
  text_probing_for_a_tin_is_refused_alike_by_every_filing_tool.

Plan: plan/served.md P0, section 6 "Immediate hole (P0)", 4.1, 4.3, 4.9.

Review round 3. S1: a panic stops the server for every session, so no
input may reach one. Dates are four-digit years (new ledger_core::
calendar, 0001-01-01..9999-12-31): the MCP's parse_date is strict
YYYY-MM-DD, periods are bounded, last_day_of_month returns a refusal
(server and store); schedules, assets, recurring entries, periods,
documents, disposals and entries refuse dates outside the calendar, and
replay refuses such journal dates. Every amount a command takes is at
most a line's (draft lines by size, document lines, payouts, payroll,
statements, shares, tax basis, proceeds, recurring templates), on
replay too, so sums are exact; the 1099 vendor part and the K-1
property share use checked products (TooLargeToCompute); a recurring
run makes at most 1,000 drafts. tests/hostile_args.rs drives every tool
with schema-derived hostile arguments and every resource with generated
URIs, asserting the server never stops; the audit's panics are pinned.
S2: a `.` or `..` path name is refused as NO_SUCH_FILE up front. S3:
NUL-interleaved UTF-16 without a byte-order mark is scanned both ways.
S4: resource-read refusals are TIN-redacted. S5: set_w9 records its W-9
only once the call passes every check, just before the vault write.
S8: idempotentHint only on verify, run_depreciation, run_schedules,
run_recurring, set_party_roles (a repeat leaves journal and vault
alone; spec_vault checks every candidate twice); every tool's hints
pinned in one table. C1: books.settings lists receipt_required_accounts
and receipt_exempt_accounts uncut. C2: the default company name reads
"a new company". C3: the parties rule names no-party reasons. C4/C5:
the handbook names the settings file only as books.settings' books_toml,
and restores "check books.digest and offer it". C6: an import root
inside the books, data dir or vault is refused at startup. The lint
catches `just` however it ends and where the books are;
digest_resource_bare_reads reads the server's month.

Review round 4 (2026-10-17): round 3's bounds ran in replay too, so
journals main wrote and reopened (an entry dated 0000-06-01 or
+10000-01-01, a draft line of 2e15, an asset ending past 9999, a basis
or share past the line limit, sub-cent document and payroll lines) no
longer opened. Posted is forever: the bounds are the commands' only.
- Replay applies main's rule exactly: parse_date takes any date chrono
  reads; replay_add_line(_fx) has no size bound (add_line/add_line_fx
  do); replay_register_asset/correct_asset (chrono overflow only),
  replay_set_asset_tax_basis (check_journaled), replay_set_entry_parties
  (check_shares_journaled), replay_register_recurring
  (validate_recurring_journaled), replay_register_schedule (months 1 to
  600), replay_create_period (order only), replay_dispose_asset, and no
  line, date, payment or payroll range checks in replay_invoice/bill,
  their payments and replay_payroll_run.
- Derived figures over such books refuse (TooLargeToCompute,
  DateOutOfRange), never panic: amortization plans, depreciation into
  chrono's last month (and the true-up for lives past 9999), intervals,
  document totals and aging, net pay and payroll plans, money flows and
  share resolution, the asset register, receipt-policy debits; the MCP
  tools and the viewer show what can't be computed.
- tests/fixtures/old-books: the review's 13 journals, its control and 15
  more edges, written by main's Store API with main's figures
  (expected.json); every one opens in the writer and the viewer to those
  figures, every derived figure computes or refuses, every MCP tool and
  GUI page answers; hostile_args restarts the server after each
  property; each bound has a command/replay test pair.

Final review: a schedule's plan refuses a total of 10^26 or more
(TooLargeToCompute) instead of letting Decimal round its cents silently,
and a null `remaining` in the schedule output is always explained by
plan_error. Replay is unaffected: no journaled schedule month can belong
to a total that large (the line limit bounds every posted month).

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-17 09:25:00 -06:00
1 parent aec55b8d12
commit b22a034746
161 files changed
+18938 -1110

No files matched your search

+43 -2
View File
@@ -36,11 +36,15 @@ impl Interval {
/// The first day of the calendar interval containing `d`.
pub fn interval_start(d: NaiveDate, interval: Interval) -> NaiveDate {
let month0 = (d.month0() / interval.months()) * interval.months();
// The first of a month of `d`'s own year: every year chrono holds has
// all twelve.
NaiveDate::from_ymd_opt(d.year(), month0 + 1, 1).expect("valid")
}
/// `[start, end]` split on calendar interval boundaries, first and last
/// pieces clipped to the range. Empty when `end < start`.
/// pieces clipped to the range. Empty when `end < start`. Never panics:
/// an interval that would end past chrono's last day ends at `end`
/// (rules.md B-28: books an earlier version wrote may hold such dates).
pub fn intervals(
start: NaiveDate,
end: NaiveDate,
@@ -49,7 +53,11 @@ pub fn intervals(
let mut out = Vec::new();
let mut from = interval_start(start, interval);
while from <= end {
let next = from + Months::new(interval.months());
let Some(next) = from.checked_add_months(Months::new(interval.months())) else {
// The interval holding chrono's last day: nothing after it.
out.push((from.max(start), end));
break;
};
let to = (next - Days::new(1)).min(end);
out.push((from.max(start), to));
from = next;
@@ -242,4 +250,37 @@ mod tests {
);
assert!(intervals(d(2026, 2, 1), d(2026, 1, 1), Interval::Month).is_empty());
}
/// At chrono's last day (books an earlier version wrote may hold it):
/// the last interval ends there, never a panic (rules.md B-28).
#[test]
fn intervals_reach_chronos_last_day() {
let y = NaiveDate::MAX.year();
assert_eq!(
intervals(d(y, 11, 20), NaiveDate::MAX, Interval::Month),
[(d(y, 11, 20), d(y, 11, 30)), (d(y, 12, 1), NaiveDate::MAX)]
);
assert_eq!(
intervals(d(y, 2, 2), NaiveDate::MAX, Interval::Year),
[(d(y, 2, 2), NaiveDate::MAX)]
);
assert_eq!(
intervals(d(y, 12, 31), NaiveDate::MAX, Interval::Quarter),
[(NaiveDate::MAX, NaiveDate::MAX)]
);
assert_eq!(
intervals(
NaiveDate::MIN,
d(NaiveDate::MIN.year(), 2, 3),
Interval::Month
),
[
(NaiveDate::MIN, d(NaiveDate::MIN.year(), 1, 31)),
(
d(NaiveDate::MIN.year(), 2, 1),
d(NaiveDate::MIN.year(), 2, 3)
),
]
);
}
}
+82 -18
View File
@@ -93,15 +93,37 @@ pub struct Invoice {
pub entry_id: u64,
}
/// The sum of a document's lines; refused (TooLargeToCompute), never a
/// panic, past exact arithmetic. A document is restored from its journal
/// line as written (rules.md B-28), so its lines are bounded only by what
/// the version that wrote it checked.
pub fn document_total(lines: &[DocumentLine], what: &str) -> Result<Decimal, LedgerError> {
lines
.iter()
.try_fold(Decimal::ZERO, |sum, l| sum.checked_add(l.amount))
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{what}'s total")))
}
/// 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.
pub fn total(&self) -> Decimal {
self.lines.iter().map(|l| l.amount).sum()
/// Total of all lines ([`document_total`]).
pub fn total(&self) -> Result<Decimal, LedgerError> {
document_total(&self.lines, &format!("invoice {}", self.id))
}
/// Amount still owed.
pub fn balance(&self) -> Decimal {
self.total() - self.amount_paid
pub fn balance(&self) -> Result<Decimal, LedgerError> {
document_balance(
self.total()?,
self.amount_paid,
&format!("invoice {}", self.id),
)
}
}
@@ -127,18 +149,24 @@ pub struct Bill {
}
impl Bill {
/// Total of all lines.
pub fn total(&self) -> Decimal {
self.lines.iter().map(|l| l.amount).sum()
/// Total of all lines ([`document_total`]).
pub fn total(&self) -> Result<Decimal, LedgerError> {
document_total(&self.lines, &format!("bill {}", self.id))
}
/// Amount still owed.
pub fn balance(&self) -> Decimal {
self.total() - self.amount_paid
pub fn balance(&self) -> Result<Decimal, LedgerError> {
document_balance(
self.total()?,
self.amount_paid,
&format!("bill {}", self.id),
)
}
}
/// Validate document lines: at least one, all positive amounts.
/// Validate document lines: at least one, all positive amounts, each in a
/// journal line's range. For new documents; replay restores them as
/// journaled (rules.md B-28).
pub fn validate_lines(lines: &[DocumentLine]) -> Result<(), LedgerError> {
if lines.is_empty() {
return Err(LedgerError::EmptyDocumentLines);
@@ -147,12 +175,24 @@ pub fn validate_lines(lines: &[DocumentLine]) -> Result<(), LedgerError> {
if line.amount <= Decimal::ZERO {
return Err(LedgerError::InvalidDocumentLineAmount(line.amount));
}
// No larger than a journal line may be (kernel::MAX_LINE_AMOUNT):
// the document's total is summed from them (P0 review round 3, S1).
if !crate::kernel::Amount::in_line_range(line.amount) {
return Err(LedgerError::ValueOutOfRange(format!(
"document line amount {}",
line.amount
)));
}
}
Ok(())
}
/// Validate that due date is not before the document date.
/// Validate that due date is not before the document date, and both are
/// in the calendar the books keep (P0 review round 3, S1). For new
/// documents; replay restores them as journaled (rules.md B-28).
pub fn validate_due_date(date: NaiveDate, due_date: NaiveDate) -> Result<(), LedgerError> {
crate::calendar::check(date)?;
crate::calendar::check(due_date)?;
if due_date < date {
return Err(LedgerError::DueBeforeDate(due_date.to_string()));
}
@@ -188,9 +228,33 @@ pub struct AgingRow {
}
impl AgingRow {
/// Total outstanding.
pub fn total(&self) -> Decimal {
self.current + self.days_30 + self.days_60 + self.days_90 + self.days_90_plus
/// Total outstanding; refused past exact arithmetic.
pub fn total(&self) -> Result<Decimal, LedgerError> {
[self.days_30, self.days_60, self.days_90, self.days_90_plus]
.into_iter()
.try_fold(self.current, Decimal::checked_add)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{}'s aging total", self.name)))
}
/// Add `other`'s buckets to this row's; refused past exact arithmetic.
pub(crate) fn add(&mut self, other: &AgingRow) -> Result<(), LedgerError> {
let too_large = || LedgerError::TooLargeToCompute(format!("{}'s aging", self.name));
let sum = |a: Decimal, b: Decimal| a.checked_add(b).ok_or_else(too_large);
let (current, days_30, days_60, days_90, days_90_plus) = (
sum(self.current, other.current)?,
sum(self.days_30, other.days_30)?,
sum(self.days_60, other.days_60)?,
sum(self.days_90, other.days_90)?,
sum(self.days_90_plus, other.days_90_plus)?,
);
(
self.current,
self.days_30,
self.days_60,
self.days_90,
self.days_90_plus,
) = (current, days_30, days_60, days_90, days_90_plus);
Ok(())
}
}
@@ -271,7 +335,7 @@ mod tests {
)
.unwrap();
let invoice = l.get_invoice(inv).unwrap();
assert_eq!(invoice.total(), "1000.00".parse().unwrap());
assert_eq!(invoice.total().unwrap(), "1000.00".parse().unwrap());
assert_eq!(invoice.status, DocumentStatus::Open);
// A/R has a debit balance of 1000.
@@ -289,7 +353,7 @@ mod tests {
.unwrap();
let invoice = l.get_invoice(inv).unwrap();
assert_eq!(invoice.status, DocumentStatus::Partial);
assert_eq!(invoice.balance(), "600.00".parse().unwrap());
assert_eq!(invoice.balance().unwrap(), "600.00".parse().unwrap());
// Full payment.
l.receive_payment(
@@ -449,7 +513,7 @@ mod tests {
)
.unwrap();
let as_of = NaiveDate::from_ymd_opt(2026, 10, 1).unwrap();
let aging = l.ar_aging(as_of);
let aging = l.ar_aging(as_of).unwrap();
assert_eq!(aging.len(), 1);
assert_eq!(aging[0].current, "100".parse().unwrap());
assert_eq!(aging[0].days_60, "200".parse().unwrap());
+44 -17
View File
@@ -155,9 +155,24 @@ pub struct TaxBasis {
impl TaxBasis {
/// Whether the record fits its rule: Cost takes no contributor basis;
/// Carryover and PersonalUseConversion require a non-negative one in
/// cents at most. Returns why not. Needs no asset, so a caller can check
/// before registering one.
/// cents at most, and no larger than a cost may be
/// (kernel::MAX_LINE_AMOUNT: the register sums them; P0 review round 3,
/// S1). Returns why not. Needs no asset, so a caller can check before
/// registering one. Replay checks only [`Self::check_journaled`].
pub fn check(&self) -> Result<(), String> {
self.check_journaled()?;
match self.contributor_basis {
Some(b) if b > crate::kernel::MAX_LINE_AMOUNT => {
Err("a basis is at most 1000000000000000".into())
}
_ => Ok(()),
}
}
/// The checks every journaled `asset.tax_basis_set` passed when it was
/// written (the rule through 2026-10-16): [`Self::check`] without the
/// upper bound. Replay applies exactly these (rules.md B-28).
pub fn check_journaled(&self) -> Result<(), String> {
use TaxBasisRule::*;
match (self.rule, self.contributor_basis) {
(Cost, Some(_)) => {
@@ -307,14 +322,23 @@ pub struct ScheduleLine {
pub book_value: Decimal,
}
/// The days in a month of a year chrono holds, without stepping to the
/// next month, so chrono's last month (December 262142, whose next month
/// chrono can't hold) has its 31 days too (rules.md B-28: a schedule an
/// earlier version accepted is computed, never a panic).
fn days_in_month(year: i32, month: u32) -> u32 {
let first = NaiveDate::from_ymd_opt(year, month, 1).expect("valid month");
let next = if month == 12 {
NaiveDate::from_ymd_opt(year + 1, 1, 1).expect("valid month")
} else {
NaiveDate::from_ymd_opt(year, month + 1, 1).expect("valid month")
};
(next - first).num_days() as u32
match month {
2 if NaiveDate::from_ymd_opt(year, 2, 29).is_some() => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
/// The first day of the month after `month_start`'s, or `None` past
/// chrono's last day (the month containing NaiveDate::MAX).
fn next_month_start(month_start: NaiveDate) -> Option<NaiveDate> {
month_start.checked_add_months(Months::new(1))
}
/// The last day depreciation accrues: purchase + life, or disposal, whichever
@@ -378,18 +402,18 @@ pub fn depreciation_schedule(asset: &Asset, through: NaiveDate) -> Vec<ScheduleL
let mut accumulated_rounded = Decimal::ZERO;
// Walk calendar months from the purchase month.
let (mut year, mut month) = (asset.purchase_date.year(), asset.purchase_date.month());
loop {
let month_start = NaiveDate::from_ymd_opt(year, month, 1).expect("valid month");
// Past chrono's last month there is no month to walk, and nothing left
// to accrue: accrual_end is at most NaiveDate::MAX.
while let Some(month_start) = NaiveDate::from_ymd_opt(year, month, 1) {
if month_start >= accrual_end {
break;
}
let dim = days_in_month(year, month);
let month_end_excl = month_start
.checked_add_months(Months::new(1))
.expect("month arithmetic");
// Days held this month: overlap of [purchase_date, accrual_end) with the month.
// Days held this month: overlap of [purchase_date, accrual_end) with
// the month. In chrono's last month there is no next month to end
// at, and accrual_end (at most NaiveDate::MAX) is the bound.
let held_start = asset.purchase_date.max(month_start);
let held_end = accrual_end.min(month_end_excl);
let held_end = next_month_start(month_start).map_or(accrual_end, |n| accrual_end.min(n));
let days_held = (held_end - held_start).num_days().max(0) as u32;
if days_held > 0 {
let exact = monthly_rate * Decimal::from(days_held) / Decimal::from(dim);
@@ -416,9 +440,12 @@ pub fn depreciation_schedule(asset: &Asset, through: NaiveDate) -> Vec<ScheduleL
// absorb any month-length drift so the lifetime total is exactly
// (cost − salvage). The drift is bounded by a fraction of one month's
// charge, so the final month stays positive.
// The final month named as the lines name theirs: chrono's "%Y" signs
// a year past 9999 ("+10004"), and the lines don't, so books an
// earlier version wrote with such a life true up too (rules.md B-28).
if let Some(last) = out.last_mut()
&& let Some(day_before_end) = end.pred_opt()
&& last.period == day_before_end.format("%Y-%m").to_string()
&& last.period == format!("{:04}-{:02}", day_before_end.year(), day_before_end.month())
{
let plug = depreciable - accumulated_rounded;
last.amount += plug;
+82
View File
@@ -0,0 +1,82 @@
//! The calendar the books keep: four-digit years, 0001-01-01 through
//! 9999-12-31.
//!
//! ```text
//! GOAL: no date the books hold, or derive (a schedule's last month, an
//! asset's last day of depreciation, a fiscal year's end), is one
//! date arithmetic can't reach, or one a report can't print.
//! SOURCE: CONVENTION: ISO 8601's basic calendar dates have four-digit
//! years (0000-9999; year 0 is no Gregorian year, so 0001 is the
//! first), as do the spreadsheet and PDF formats the books export
//! to; DECISION (P0 review round 3, 2026-10-16, finding S1): a date
//! outside them is refused, never a crash.
//! INVARIANTS:
//! 1. in_calendar(d) iff FIRST_DAY <= d <= LAST_DAY.
//! 2. Every date from the calendar plus a year or 600 months less than
//! ten thousand years is a date chrono represents (its range is about
//! +-262,000 years), so arithmetic on calendar dates never overflows.
//! ```
use crate::LedgerError;
use chrono::NaiveDate;
/// The first day the books keep.
pub const FIRST_DAY: NaiveDate = match NaiveDate::from_ymd_opt(1, 1, 1) {
Some(d) => d,
None => panic!("0001-01-01 is a date"),
};
/// The last day the books keep.
pub const LAST_DAY: NaiveDate = match NaiveDate::from_ymd_opt(9999, 12, 31) {
Some(d) => d,
None => panic!("9999-12-31 is a date"),
};
/// Whether `d` is in the calendar the books keep (INVARIANT 1).
pub fn in_calendar(d: NaiveDate) -> bool {
(FIRST_DAY..=LAST_DAY).contains(&d)
}
/// `d`, if it is in the calendar; else [`LedgerError::DateOutOfRange`].
pub fn check(d: NaiveDate) -> Result<NaiveDate, LedgerError> {
if in_calendar(d) {
Ok(d)
} else {
Err(LedgerError::DateOutOfRange(d))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_calendar_is_four_digit_years() {
assert!(in_calendar(FIRST_DAY));
assert!(in_calendar(LAST_DAY));
assert!(!in_calendar(FIRST_DAY.pred_opt().unwrap()));
assert!(!in_calendar(LAST_DAY.succ_opt().unwrap()));
assert!(!in_calendar(NaiveDate::MAX));
assert!(!in_calendar(NaiveDate::MIN));
assert_eq!(FIRST_DAY.to_string(), "0001-01-01");
assert_eq!(LAST_DAY.to_string(), "9999-12-31");
assert_eq!(check(LAST_DAY), Ok(LAST_DAY));
assert_eq!(
check(NaiveDate::MAX),
Err(LedgerError::DateOutOfRange(NaiveDate::MAX))
);
}
/// INVARIANT 2: the arithmetic the books do on calendar dates (a year
/// on, 600 months on, a day back) stays inside chrono's range.
#[test]
fn arithmetic_on_calendar_dates_never_overflows() {
for d in [FIRST_DAY, LAST_DAY] {
assert!(d.checked_add_months(chrono::Months::new(600)).is_some());
assert!(d.checked_sub_months(chrono::Months::new(600)).is_some());
assert!(NaiveDate::from_ymd_opt(chrono::Datelike::year(&d) + 1, 1, 1).is_some());
assert!(NaiveDate::from_ymd_opt(chrono::Datelike::year(&d) - 1, 12, 31).is_some());
assert!(d.pred_opt().is_some() && d.succ_opt().is_some());
}
}
}
+24 -7
View File
@@ -35,6 +35,23 @@ pub enum LedgerError {
#[error("journal line amount is out of range (at most 1000000000000000, ten decimal places)")]
AmountOutOfRange,
/// A date outside the calendar the books keep (`crate::calendar`):
/// four-digit years, 0001-01-01 through 9999-12-31.
#[error("date {0} is outside the calendar the books keep (0001-01-01 through 9999-12-31)")]
DateOutOfRange(chrono::NaiveDate),
/// An amount other than a journal line's (a document line, a payout, a
/// payroll figure, a statement balance, a share, a basis) larger than
/// one quadrillion or with more than ten decimal places: a mistake, and
/// one that could overflow exact arithmetic.
#[error("{0} is out of range (at most 1000000000000000, ten decimal places)")]
ValueOutOfRange(String),
/// A figure the books derive (a sum, or a share of one) too large for
/// exact arithmetic: refused, never rounded or wrapped.
#[error("{0} is too large to compute exactly")]
TooLargeToCompute(String),
/// An amount finer than its currency's smallest unit (ISO 4217 minor
/// units): no one can pay a fraction of a cent (rules.md B-3).
#[error(
@@ -205,13 +222,13 @@ pub enum LedgerError {
/// A rule set by law (a dollar threshold, a rate) isn't known to
/// wanderbooks for the year asked; the engine never guesses (see
/// [`crate::rules`]).
/// [`crate::rules`]). The text names the authority, never this repo:
/// it reaches agents.
#[error(
"wanderbooks knows the {rule} only through {known_through}, not for {year}. \
Find the {year} figure from the official source (see {spec}) or ask the books' \
owner or CPA, and pass it explicitly. Then update the rule for everyone: open a \
pull request (or at least an issue) at https://github.com/swaits/wanderbooks with \
the new value and its official source."
Find the {year} figure from the official source, {authority}, or ask the books' \
owner or CPA, and pass it explicitly. Then tell the human the figure and where \
it came from, so the rule can be updated for everyone."
)]
RuleNotKnown {
/// The rule's plain name.
@@ -220,8 +237,8 @@ pub enum LedgerError {
year: i32,
/// The last year the rule is known for.
known_through: i32,
/// The vendored official source of the rule.
spec: String,
/// The official source of the rule (`DatedRule::authority`).
authority: String,
},
/// A child account subdivides its parent, so it must be the same type
+48 -8
View File
@@ -81,7 +81,7 @@ pub fn default_threshold(year: i32) -> Result<Decimal, LedgerError> {
rule: rule.name.to_string(),
year,
known_through: rule.known_through,
spec: rule.source.to_string(),
authority: rule.authority.to_string(),
});
}
Ok(if year <= 2025 {
@@ -190,14 +190,24 @@ fn payment(ledger: &Ledger, entry: &crate::JournalEntry, sources: &PaymentAccoun
/// The vendor's part of `payment` when the entry names several parties:
/// its resolved share scaled from the share target to the payment (the
/// SCENARIOS of [`vendor_1099_report_with_members`], INVARIANT 3).
fn vendor_part(payment: Decimal, share: Decimal, target: Decimal) -> Decimal {
/// Refused, never wrapped or rounded early, when payment × share is
/// beyond exact arithmetic (both near the line limit; P0 review round 3,
/// S1).
fn vendor_part(payment: Decimal, share: Decimal, target: Decimal) -> Result<Decimal, LedgerError> {
if payment == target {
share
Ok(share)
} else if target.is_zero() {
Decimal::ZERO
Ok(Decimal::ZERO)
} else {
(payment * share / target)
.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointAwayFromZero)
let scaled = payment
.checked_mul(share)
.and_then(|x| x.checked_div(target))
.ok_or_else(|| {
LedgerError::TooLargeToCompute(format!(
"a vendor's share ({share}) of a payment of {payment}"
))
})?;
Ok(scaled.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointAwayFromZero))
}
}
@@ -281,7 +291,7 @@ pub fn vendor_1099_report_with_members(
Ok(parts) => {
match parts.into_iter().find(|(p, _)| Some(*p) == party) {
Some((_, share)) => {
vendor_part(cash, share, crate::shares::share_target(entry, &money))
vendor_part(cash, share, crate::shares::share_target(entry, &money)?)?
}
// Tagged by hand with a vendor none of the parties
// is: nothing to scale by, so the whole payment.
@@ -297,7 +307,10 @@ pub fn vendor_1099_report_with_members(
}
}
};
*paid.entry(vendor).or_default() += amount;
let total = paid.entry(vendor).or_default();
*total = total.checked_add(amount).ok_or_else(|| {
LedgerError::TooLargeToCompute("a vendor's payments for the year".into())
})?;
}
let mut vendors: Vec<Vendor1099Line> = ledger
.list_vendors()
@@ -328,3 +341,30 @@ pub fn vendor_1099_report_with_members(
unresolved,
})
}
#[cfg(test)]
mod tests {
use super::*;
/// vendor_part: the vendor's share scaled from the share target to the
/// payment, exactly, rounded to the cent; refused, never a panic, when
/// payment x share is past exact arithmetic (P0 review round 3, S1).
#[test]
fn a_vendor_part_is_scaled_exactly_or_refused() {
let d = |s: &str| s.parse::<Decimal>().unwrap();
assert_eq!(vendor_part(d("100"), d("40"), d("100")), Ok(d("40")));
assert_eq!(vendor_part(d("50"), d("40"), d("100")), Ok(d("20")));
assert_eq!(vendor_part(d("1"), d("1"), d("3")), Ok(d("0.33")));
assert_eq!(vendor_part(d("2"), d("1"), d("3")), Ok(d("0.67")));
assert_eq!(vendor_part(d("5"), d("1"), d("0")), Ok(Decimal::ZERO));
let near = d("450000000000000");
assert!(matches!(
vendor_part(near * d("2"), near, near - d("1")),
Err(LedgerError::TooLargeToCompute(_))
));
assert!(matches!(
vendor_part(Decimal::MAX, Decimal::MAX, d("1")),
Err(LedgerError::TooLargeToCompute(_))
));
}
}
+38 -10
View File
@@ -219,7 +219,7 @@ pub fn k1_detail(
.iter()
.map(|m| sum(e, Side::Credit, m.capital_account))
.collect();
let takes = share_property(pool, &credits);
let takes = share_property(pool, &credits)?;
for (i, m) in members.iter().enumerate() {
let (credit, take) = (credits[i], takes[i]);
if !(credit - take).is_zero() {
@@ -276,16 +276,27 @@ pub fn k1_detail(
/// (INVARIANT 4): at most their total credit, in proportion to each
/// credit, rounded toward zero to the cent, the leftover cents by largest
/// remainder. Each part is at most its own credit.
fn share_property(pool: Decimal, credits: &[Decimal]) -> Vec<Decimal> {
/// Refused when whole × credit is beyond exact arithmetic (credits near
/// the line limit; P0 review round 3, S1).
fn share_property(pool: Decimal, credits: &[Decimal]) -> Result<Vec<Decimal>, LedgerError> {
use rust_decimal::RoundingStrategy::ToZero;
let total: Decimal = credits.iter().sum();
let too_large =
|| LedgerError::TooLargeToCompute("a member's share of contributed property".into());
let total = credits
.iter()
.try_fold(Decimal::ZERO, |t, c| t.checked_add(*c))
.ok_or_else(too_large)?;
let whole = pool.min(total);
if whole <= Decimal::ZERO || total <= Decimal::ZERO {
return vec![Decimal::ZERO; credits.len()];
return Ok(vec![Decimal::ZERO; credits.len()]);
}
// whole × credit is exact; ÷ total is exact whenever the share is a
// whole number of cents, so truncating never loses a cent it is owed.
let exact: Vec<Decimal> = credits.iter().map(|c| whole * c / total).collect();
let exact: Vec<Decimal> = credits
.iter()
.map(|c| whole.checked_mul(*c).and_then(|x| x.checked_div(total)))
.collect::<Option<_>>()
.ok_or_else(too_large)?;
let mut parts: Vec<Decimal> = exact
.iter()
.map(|x| x.round_dp_with_strategy(2, ToZero))
@@ -293,7 +304,7 @@ fn share_property(pool: Decimal, credits: &[Decimal]) -> Vec<Decimal> {
let remainders: Vec<Decimal> = exact.iter().zip(&parts).map(|(x, p)| x - p).collect();
crate::kernel::apportion(whole, &mut parts, &remainders, Decimal::new(1, 2))
.expect("each part is short by under a cent, so the shortfall is under a cent per member");
parts
Ok(parts)
}
/// The party a member (by name, as in wanderbooks.toml) is in the
@@ -829,22 +840,39 @@ mod tests {
flipped.reverse();
assert_eq!(split(&bk, &flipped), vec![each, each]);
assert_eq!(
share_property(d("401"), &[d("750"), d("250")]),
share_property(d("401"), &[d("750"), d("250")]).unwrap(),
vec![d("300.75"), d("100.25")]
);
assert_eq!(
share_property(d("0.01"), &[d("5"), d("5")]),
share_property(d("0.01"), &[d("5"), d("5")]).unwrap(),
vec![d("0.01"), d("0.00")]
);
// More property than credit (part financed): at most the credits.
assert_eq!(
share_property(d("900"), &[d("300"), d("100")]),
share_property(d("900"), &[d("300"), d("100")]).unwrap(),
vec![d("300"), d("100")]
);
assert_eq!(
share_property(d("50"), &[d("0"), d("0")]),
share_property(d("50"), &[d("0"), d("0")]).unwrap(),
vec![d("0"), d("0")]
);
// Credits near the line limit: whole x credit is past exact
// arithmetic, so the split is refused, never a panic (P0 review
// round 3, S1); at a quarter of it, it still splits exactly.
let near = d("900000000000000");
assert!(matches!(
share_property(near, &[near, near]),
Err(LedgerError::TooLargeToCompute(_))
));
assert!(matches!(
share_property(near, &[Decimal::MAX, Decimal::MAX]),
Err(LedgerError::TooLargeToCompute(_))
));
let quarter = d("250000000000");
assert_eq!(
share_property(quarter, &[quarter, quarter]).unwrap(),
vec![d("125000000000"), d("125000000000")]
);
}
/// member_party doc: the party of that name with the member role only.
+326 -55
View File
@@ -378,7 +378,8 @@ impl Ledger {
.schedules
.get(&id)
.ok_or_else(|| LedgerError::InvalidSchedule(format!("unknown schedule {id}")))?;
let (date, amount) = schedules::amortization_plan(s.total.amount, s.start, s.months)
let (date, amount) = s
.plan()?
.into_iter()
.find(|(d, _)| *d == month_end)
.ok_or_else(|| {
@@ -439,6 +440,23 @@ impl Ledger {
/// Register a recurring entry. Returns its id.
pub fn register_recurring(&mut self, new: NewRecurring) -> Result<RecurringId, LedgerError> {
schedules::validate_recurring(&new, &self.chart)?;
self.insert_recurring(new)
}
/// [`Self::register_recurring`] with the checks every journaled
/// `recurring.registered` passed when it was written
/// (schedules::validate_recurring_journaled), for replay only
/// (rules.md B-28). Never for new work.
pub fn replay_register_recurring(
&mut self,
new: NewRecurring,
) -> Result<RecurringId, LedgerError> {
schedules::validate_recurring_journaled(&new, &self.chart)?;
self.insert_recurring(new)
}
/// Put a checked recurring entry in under the next id.
fn insert_recurring(&mut self, new: NewRecurring) -> Result<RecurringId, LedgerError> {
let id = self.next_recurring_id;
self.next_recurring_id += 1;
self.recurring.insert(
@@ -515,7 +533,9 @@ impl Ledger {
let (description, lines) = (r.description.clone(), r.lines.clone());
let entry = self.create_entry(date, &description);
for (account, side, money) in lines {
if let Err(e) = self.add_line(entry, account, side, money) {
// The template's lines as journaled: no size bound (rules.md
// B-28); a draft too large to post is refused at its post.
if let Err(e) = self.add_line_journaled(entry, account, side, money, false) {
self.entries.remove(&entry);
self.next_entry_id = entry;
return Err(e);
@@ -1028,6 +1048,8 @@ impl Ledger {
/// GOAL: start a draft entry for new work.
/// SOURCE: docs/spec/rules.md B-12; Lean invariant Inv.draftsOpen.
/// SCENARIOS:
/// 0. IF the date is outside the calendar the books keep
/// (crate::calendar): SHOULD refuse (DateOutOfRange).
/// 1. IF the date falls in a closed period:
/// - SHOULD refuse (ClosedPeriod)
/// - NEVER create a draft there
@@ -1039,6 +1061,7 @@ impl Ledger {
date: NaiveDate,
description: &str,
) -> Result<EntryId, LedgerError> {
crate::calendar::check(date)?;
if let Some(pid) = self.closed_period_containing(date) {
return Err(LedgerError::ClosedPeriod(pid, date.to_string()));
}
@@ -1075,9 +1098,30 @@ impl Ledger {
account: AccountId,
side: Side,
amount: Money,
) -> Result<(), LedgerError> {
self.add_line_journaled(entry, account, side, amount, true)
}
/// [`Self::add_line`]'s checks: the account, the minor unit, and (when
/// `bounded`, for new work) the size. A draft line larger than any
/// posting could carry is refused when it is added, not only at the
/// post (P0 review round 3, S1); a recurring entry's draft is generated
/// with the checks its template passed when it was journaled
/// (`bounded` false), so a journaled `recurring.generated` always
/// replays (rules.md B-28).
fn add_line_journaled(
&mut self,
entry: EntryId,
account: AccountId,
side: Side,
amount: Money,
bounded: bool,
) -> Result<(), LedgerError> {
self.check_line_account(account)?;
check_minor_units(amount)?;
if bounded {
check_line_size(amount.amount)?;
}
self.replay_add_line(entry, account, side, amount)
}
@@ -1094,8 +1138,10 @@ impl Ledger {
Ok(())
}
/// [`Self::add_line`] without the account check added on 2026-10-13,
/// for replaying journals written before it. Never for new work.
/// [`Self::add_line`] without the account check added on 2026-10-13 or
/// the size bound added in P0, for replaying journals written before
/// them (rules.md B-28): a draft line replays as journaled, and its post
/// refuses it if it is out of range. Never for new work.
pub fn replay_add_line(
&mut self,
entry: EntryId,
@@ -1179,6 +1225,7 @@ impl Ledger {
if base_amount <= Decimal::ZERO {
return Err(LedgerError::InvalidFxRate(fx_rate));
}
check_line_size(base_amount)?;
self.replay_add_line_fx(
entry,
account,
@@ -1190,9 +1237,9 @@ impl Ledger {
}
/// A foreign-currency line exactly as a journal recorded it: the base
/// amount as booked (rounded or not, by the rule of its day) and the
/// foreign original. For replay only; new work uses
/// [`Self::add_line_fx`].
/// amount as booked (rounded or not, by the rule of its day, and of any
/// size: the bound is the command's, rules.md B-28) and the foreign
/// original. For replay only; new work uses [`Self::add_line_fx`].
pub fn replay_add_line_fx(
&mut self,
entry: EntryId,
@@ -1405,7 +1452,26 @@ impl Ledger {
/// Pure pre-validation for [`Self::register_asset`]: every check that
/// does not mutate, so journaling stores can validate before journaling.
/// [`Self::validate_new_asset_journaled`], and both ends of the life
/// inside the calendar the books keep (crate::calendar): a life that
/// runs past 9999-12-31 is refused like one past chrono's last day (P0
/// review round 3, S1).
pub fn validate_new_asset(&self, new: &NewAsset) -> Result<(), LedgerError> {
self.check_new_asset(new, true)
}
/// The checks every journaled `asset.registered` and `asset.corrected`
/// passed when it was written (the rule through 2026-10-16):
/// [`Self::validate_new_asset`] without the calendar bound, the end of
/// the life only representable. Replay applies exactly these
/// (rules.md B-28).
pub fn validate_new_asset_journaled(&self, new: &NewAsset) -> Result<(), LedgerError> {
self.check_new_asset(new, false)
}
/// The checks of [`Self::validate_new_asset`] (`strict`) or
/// [`Self::validate_new_asset_journaled`], in one order.
fn check_new_asset(&self, new: &NewAsset, strict: bool) -> Result<(), LedgerError> {
if new.description.trim().is_empty() {
return Err(LedgerError::EmptyAssetDescription);
}
@@ -1437,12 +1503,15 @@ impl Ledger {
}
// The schedule walks every month of the asset's life; a purchase
// date near the end of the calendar would overflow date arithmetic
// (and hang or panic the schedule). Reject it up front.
if new
// (and hang or panic the schedule). Reject it up front. New ones
// keep both ends inside the calendar the books keep.
if strict {
crate::calendar::check(new.purchase_date)?;
}
let end = new
.purchase_date
.checked_add_months(Months::new(new.useful_life_months))
.is_none()
{
.checked_add_months(Months::new(new.useful_life_months));
if !end.is_some_and(|end| !strict || crate::calendar::in_calendar(end)) {
return Err(LedgerError::AssetDateOverflow);
}
assets::validate_asset_accounts(
@@ -1468,6 +1537,20 @@ impl Ledger {
/// ```
pub fn register_asset(&mut self, new: NewAsset) -> Result<AssetId, LedgerError> {
self.validate_new_asset(&new)?;
self.insert_asset(new)
}
/// [`Self::register_asset`] with the checks every journaled
/// `asset.registered` passed when it was written
/// ([`Self::validate_new_asset_journaled`]), for replay only (rules.md
/// B-28). Never for new work.
pub fn replay_register_asset(&mut self, new: NewAsset) -> Result<AssetId, LedgerError> {
self.validate_new_asset_journaled(&new)?;
self.insert_asset(new)
}
/// Put a checked asset on the register under the next id.
fn insert_asset(&mut self, new: NewAsset) -> Result<AssetId, LedgerError> {
let id = self.next_asset_id;
self.next_asset_id += 1;
self.assets.insert(
@@ -1744,6 +1827,25 @@ impl Ledger {
Ok(())
}
/// [`Self::set_asset_tax_basis`] with the checks every journaled
/// `asset.tax_basis_set` passed when it was written
/// (TaxBasis::check_journaled: no upper bound), for replay only
/// (rules.md B-28). Never for new work.
pub fn replay_set_asset_tax_basis(
&mut self,
id: AssetId,
tax: assets::TaxBasis,
) -> Result<(), LedgerError> {
let asset = self
.assets
.get_mut(&id)
.ok_or(LedgerError::UnknownAsset(id))?;
tax.check_journaled()
.map_err(LedgerError::InvalidTaxBasis)?;
asset.tax = Some(tax);
Ok(())
}
/// The validation behind [`Self::set_asset_tax_basis`].
pub fn check_asset_tax_basis(
&self,
@@ -1778,12 +1880,32 @@ impl Ledger {
fix: assets::AssetCorrection,
) -> Result<(), LedgerError> {
self.check_correct_asset(id, &fix)?;
self.apply_asset_correction(id, fix);
Ok(())
}
/// [`Self::correct_asset`] with the checks every journaled
/// `asset.corrected` passed when it was written
/// ([`Self::validate_new_asset_journaled`]), for replay only (rules.md
/// B-28). Never for new work.
pub fn replay_correct_asset(
&mut self,
id: AssetId,
fix: assets::AssetCorrection,
) -> Result<(), LedgerError> {
let corrected = self.corrected_asset(id, &fix)?;
self.validate_new_asset_journaled(&corrected)?;
self.apply_asset_correction(id, fix);
Ok(())
}
/// Write checked corrected figures onto the asset.
fn apply_asset_correction(&mut self, id: AssetId, fix: assets::AssetCorrection) {
let a = self.assets.get_mut(&id).expect("checked");
a.cost = fix.cost;
a.salvage_value = fix.salvage_value;
a.useful_life_months = fix.useful_life_months;
a.purchase_date = fix.purchase_date;
Ok(())
}
/// The validation behind [`Self::correct_asset`].
@@ -1792,11 +1914,21 @@ impl Ledger {
id: AssetId,
fix: &assets::AssetCorrection,
) -> Result<(), LedgerError> {
self.validate_new_asset(&self.corrected_asset(id, fix)?)
}
/// The active asset `id` as `fix` would leave it, as a registration to
/// check.
fn corrected_asset(
&self,
id: AssetId,
fix: &assets::AssetCorrection,
) -> Result<NewAsset, LedgerError> {
let a = self.assets.get(&id).ok_or(LedgerError::UnknownAsset(id))?;
if a.status != AssetStatus::Active {
return Err(LedgerError::AssetAlreadyDisposed(id));
}
self.validate_new_asset(&NewAsset {
Ok(NewAsset {
description: a.description.clone(),
purchase_date: fix.purchase_date,
cost: fix.cost,
@@ -1845,6 +1977,37 @@ impl Ledger {
id: AssetId,
date: NaiveDate,
proceeds: Money,
) -> Result<(), LedgerError> {
self.check_dispose_asset(id, date, proceeds, true)?;
self.assets.get_mut(&id).expect("asset exists").status =
AssetStatus::Disposed { date, proceeds };
Ok(())
}
/// [`Self::dispose_asset`] with the checks every journaled
/// `asset.disposed` passed when it was written (no bound on the
/// proceeds or the date beyond the disposal's own), for replay only
/// (rules.md B-28). Never for new work.
pub fn replay_dispose_asset(
&mut self,
id: AssetId,
date: NaiveDate,
proceeds: Money,
) -> Result<(), LedgerError> {
self.check_dispose_asset(id, date, proceeds, false)?;
self.assets.get_mut(&id).expect("asset exists").status =
AssetStatus::Disposed { date, proceeds };
Ok(())
}
/// The checks of [`Self::dispose_asset`] (`strict`) or
/// [`Self::replay_dispose_asset`].
fn check_dispose_asset(
&self,
id: AssetId,
date: NaiveDate,
proceeds: Money,
strict: bool,
) -> Result<(), LedgerError> {
if proceeds.currency != self.base_currency {
return Err(LedgerError::CurrencyMismatch {
@@ -1855,8 +2018,14 @@ impl Ledger {
let asset = self.assets.get(&id).ok_or(LedgerError::UnknownAsset(id))?;
// Pure math validates activeness, proceeds sign, and date order.
crate::disposal_amounts(asset, date, proceeds)?;
self.assets.get_mut(&id).expect("asset exists").status =
AssetStatus::Disposed { date, proceeds };
if strict {
// Proceeds are a line of the disposal entry, and its date one
// the books keep (P0 review round 3, S1).
if !kernel::Amount::in_line_range(proceeds.amount) {
return Err(LedgerError::AmountOutOfRange);
}
crate::calendar::check(date)?;
}
Ok(())
}
@@ -1909,14 +2078,16 @@ impl Ledger {
}
/// [`Self::create_period`] without the nesting rule added on
/// 2026-10-13, for replaying journals written before it.
/// 2026-10-13 or the calendar bound added in P0 (only the order is
/// checked, periods::validate_period_order), for replaying journals
/// written before them (rules.md B-28).
pub fn replay_create_period(
&mut self,
name: &str,
start: NaiveDate,
end: NaiveDate,
) -> Result<PeriodId, LedgerError> {
periods::validate_period_range(start, end)?;
periods::validate_period_order(start, end)?;
let id = self.next_period_id;
self.next_period_id += 1;
self.periods.insert(
@@ -3116,6 +3287,35 @@ impl Ledger {
shares: &[crate::PartyShare],
) -> Result<(), LedgerError> {
let vendor = self.check_set_entry_parties(entry, shares)?;
self.apply_entry_parties(entry, shares, vendor);
Ok(())
}
/// [`Self::set_entry_parties`] with the checks every journaled
/// `entry.parties_set` passed when it was written
/// (crate::shares::check_shares_journaled: no upper bound on an
/// amount), for replay only (rules.md B-28). Never for new work.
pub fn replay_set_entry_parties(
&mut self,
entry: EntryId,
shares: &[crate::PartyShare],
) -> Result<(), LedgerError> {
if !self.entries.contains_key(&entry) {
return Err(LedgerError::UnknownEntry(entry));
}
let vendor = self.party_shares_vendor(shares, false)?;
self.apply_entry_parties(entry, shares, vendor);
Ok(())
}
/// Record checked shares on the entry's reversal chain
/// ([`Self::set_entry_parties`] INVARIANTS 2-5).
fn apply_entry_parties(
&mut self,
entry: EntryId,
shares: &[crate::PartyShare],
vendor: Option<VendorId>,
) {
for e in self.reversal_chain(entry) {
if shares.is_empty() {
self.entry_parties.remove(&e);
@@ -3133,7 +3333,6 @@ impl Ledger {
}
}
}
Ok(())
}
/// The validation behind [`Self::set_entry_parties`]: returns the
@@ -3155,12 +3354,27 @@ impl Ledger {
pub fn check_party_shares(
&self,
shares: &[crate::PartyShare],
) -> Result<Option<VendorId>, LedgerError> {
self.party_shares_vendor(shares, true)
}
/// [`Self::check_party_shares`], with crate::shares::check_shares when
/// `strict` (new work) or check_shares_journaled (replay).
fn party_shares_vendor(
&self,
shares: &[crate::PartyShare],
strict: bool,
) -> Result<Option<VendorId>, LedgerError> {
if let Some(s) = shares.iter().find(|s| !self.parties.contains_key(&s.party)) {
return Err(LedgerError::UnknownParty(s.party));
}
crate::shares::check_shares(shares, |p| self.parties.contains_key(&p))
.map_err(LedgerError::InvalidParty)?;
let known = |p| self.parties.contains_key(&p);
if strict {
crate::shares::check_shares(shares, known)
} else {
crate::shares::check_shares_journaled(shares, known)
}
.map_err(LedgerError::InvalidParty)?;
let vendors: Vec<(crate::PartyId, VendorId)> = shares
.iter()
.filter_map(|s| self.parties[&s.party].vendor.map(|v| (s.party, v)))
@@ -3551,7 +3765,8 @@ impl Ledger {
.get(&invoice_id)
.ok_or(LedgerError::UnknownInvoice(invoice_id))?
.clone();
let balance = invoice.balance();
let total = invoice.total()?;
let balance = invoice.balance()?;
if amount > balance {
return Err(LedgerError::Overpayment(amount, balance));
}
@@ -3574,8 +3789,9 @@ impl Ledger {
self.add_line(entry, ar, Side::Credit, money)?;
self.post_entry(entry)?;
let inv = self.invoices.get_mut(&invoice_id).expect("invoice exists");
// At most the balance: the sum is at most the total.
inv.amount_paid += amount;
inv.status = arap::derive_status(inv.amount_paid, inv.total());
inv.status = arap::derive_status(inv.amount_paid, total);
let customer = inv.customer_id;
self.invoice_payments
.entry(invoice_id)
@@ -3627,7 +3843,8 @@ impl Ledger {
.get(&bill_id)
.ok_or(LedgerError::UnknownBill(bill_id))?
.clone();
let balance = bill.balance();
let total = bill.total()?;
let balance = bill.balance()?;
if amount > balance {
return Err(LedgerError::Overpayment(amount, balance));
}
@@ -3651,7 +3868,7 @@ impl Ledger {
self.post_entry(entry)?;
let b = self.bills.get_mut(&bill_id).expect("bill exists");
b.amount_paid += amount;
b.status = arap::derive_status(b.amount_paid, b.total());
b.status = arap::derive_status(b.amount_paid, total);
self.bill_payments
.entry(bill_id)
.or_default()
@@ -3678,6 +3895,9 @@ impl Ledger {
if id != self.next_invoice_id {
return Err(LedgerError::ReplayIdMismatch(id, self.next_invoice_id));
}
// Restored exactly as journaled: replay checks no line or date
// (none did when it was written; rules.md B-28). Figures derived
// from them (the total, aging) refuse what they can't compute.
self.next_invoice_id += 1;
self.invoices.insert(
id,
@@ -3711,6 +3931,9 @@ impl Ledger {
if id != self.next_bill_id {
return Err(LedgerError::ReplayIdMismatch(id, self.next_bill_id));
}
// Restored exactly as journaled: replay checks no line or date
// (none did when it was written; rules.md B-28). Figures derived
// from them (the total, aging) refuse what they can't compute.
self.next_bill_id += 1;
self.bills.insert(
id,
@@ -3745,12 +3968,18 @@ impl Ledger {
.invoices
.get_mut(&invoice_id)
.ok_or(LedgerError::UnknownInvoice(invoice_id))?;
inv.amount_paid += amount;
// No bound on a journaled payment (rules.md B-28); a sum past exact
// arithmetic is refused, never wrapped, before anything changes.
let total = inv.total()?;
inv.amount_paid = inv
.amount_paid
.checked_add(amount)
.ok_or_else(|| LedgerError::TooLargeToCompute("the invoice's paid amount".into()))?;
self.invoice_payments
.entry(invoice_id)
.or_default()
.push((entry_id, amount));
inv.status = arap::derive_status(inv.amount_paid, inv.total());
inv.status = arap::derive_status(inv.amount_paid, total);
let customer = inv.customer_id;
self.tag_customer(entry_id, customer);
Ok(())
@@ -3769,8 +3998,14 @@ impl Ledger {
.bills
.get_mut(&bill_id)
.ok_or(LedgerError::UnknownBill(bill_id))?;
bill.amount_paid += amount;
bill.status = arap::derive_status(bill.amount_paid, bill.total());
// No bound on a journaled payment (rules.md B-28); a sum past exact
// arithmetic is refused, never wrapped, before anything changes.
let total = bill.total()?;
bill.amount_paid = bill
.amount_paid
.checked_add(amount)
.ok_or_else(|| LedgerError::TooLargeToCompute("the bill's paid amount".into()))?;
bill.status = arap::derive_status(bill.amount_paid, total);
self.bill_payments
.entry(bill_id)
.or_default()
@@ -3781,8 +4016,10 @@ impl Ledger {
}
/// A/R aging as of a date: one row per customer with an outstanding
/// balance, bucketed by days past due.
pub fn ar_aging(&self, as_of: NaiveDate) -> Vec<AgingRow> {
/// balance, bucketed by days past due. Refused (TooLargeToCompute),
/// never a panic, when a sum is past exact arithmetic: documents are
/// restored as journaled (rules.md B-28).
pub fn ar_aging(&self, as_of: NaiveDate) -> Result<Vec<AgingRow>, LedgerError> {
let mut by_customer: HashMap<CustomerId, AgingRow> = HashMap::new();
for inv in self.invoices.values() {
// Only what existed by `as_of`: issued by then, less payments
@@ -3790,7 +4027,10 @@ impl Ledger {
if inv.date > as_of {
continue;
}
let balance = inv.total() - self.paid_by(self.invoice_payments.get(&inv.id), as_of);
let paid = self.paid_by(self.invoice_payments.get(&inv.id), as_of)?;
let balance = inv.total()?.checked_sub(paid).ok_or_else(|| {
LedgerError::TooLargeToCompute(format!("invoice {}'s balance", inv.id))
})?;
if balance.is_zero() {
continue;
}
@@ -3809,38 +4049,42 @@ impl Ledger {
days_90: Decimal::ZERO,
days_90_plus: Decimal::ZERO,
});
entry.current += row.current;
entry.days_30 += row.days_30;
entry.days_60 += row.days_60;
entry.days_90 += row.days_90;
entry.days_90_plus += row.days_90_plus;
entry.add(&row)?;
}
let mut rows: Vec<AgingRow> = by_customer.into_values().collect();
rows.sort_by(|a, b| a.name.cmp(&b.name));
rows
Ok(rows)
}
/// What a document's payments add up to through `as_of`: payments are
/// posted entries, dated.
fn paid_by(&self, payments: Option<&Vec<(EntryId, Decimal)>>, as_of: NaiveDate) -> Decimal {
fn paid_by(
&self,
payments: Option<&Vec<(EntryId, Decimal)>>,
as_of: NaiveDate,
) -> Result<Decimal, LedgerError> {
payments
.into_iter()
.flatten()
.filter(|(e, _)| self.get_entry(*e).is_some_and(|e| e.date() <= as_of))
.map(|(_, amount)| *amount)
.sum()
.try_fold(Decimal::ZERO, |sum, (_, amount)| sum.checked_add(*amount))
.ok_or_else(|| LedgerError::TooLargeToCompute("a document's payments".into()))
}
/// A/P aging as of a date: one row per vendor with an outstanding
/// balance, bucketed by days past due.
pub fn ap_aging(&self, as_of: NaiveDate) -> Vec<AgingRow> {
/// balance, bucketed by days past due; refused as
/// [`Self::ar_aging`] is.
pub fn ap_aging(&self, as_of: NaiveDate) -> Result<Vec<AgingRow>, LedgerError> {
let mut by_vendor: HashMap<VendorId, AgingRow> = HashMap::new();
for bill in self.bills.values() {
// Only what existed by `as_of` (see `ar_aging`).
if bill.date > as_of {
continue;
}
let balance = bill.total() - self.paid_by(self.bill_payments.get(&bill.id), as_of);
let paid = self.paid_by(self.bill_payments.get(&bill.id), as_of)?;
let balance = bill.total()?.checked_sub(paid).ok_or_else(|| {
LedgerError::TooLargeToCompute(format!("bill {}'s balance", bill.id))
})?;
if balance.is_zero() {
continue;
}
@@ -3857,15 +4101,11 @@ impl Ledger {
days_90: Decimal::ZERO,
days_90_plus: Decimal::ZERO,
});
entry.current += row.current;
entry.days_30 += row.days_30;
entry.days_60 += row.days_60;
entry.days_90 += row.days_90;
entry.days_90_plus += row.days_90_plus;
entry.add(&row)?;
}
let mut rows: Vec<AgingRow> = by_vendor.into_values().collect();
rows.sort_by(|a, b| a.name.cmp(&b.name));
rows
Ok(rows)
}
// ------------------------------------------------------------------
@@ -3942,6 +4182,13 @@ impl Ledger {
.chart
.get(account)
.ok_or(LedgerError::UnknownAccount(account))?;
// A statement says what an account holds: no more than a line may
// move, so the difference is exact (P0 review round 3, S1).
if !kernel::Amount::in_line_range(statement_balance) {
return Err(LedgerError::ValueOutOfRange(format!(
"statement balance {statement_balance}"
)));
}
let normal = acct.account_type.normal_side();
let mut book = Decimal::ZERO;
let mut cleared = Decimal::ZERO;
@@ -3987,7 +4234,9 @@ impl Ledger {
cleared
},
statement_balance,
difference: cleared - statement_balance,
difference: cleared.checked_sub(statement_balance).ok_or_else(|| {
LedgerError::TooLargeToCompute("the reconciliation's difference".into())
})?,
uncleared_lines,
})
}
@@ -4162,7 +4411,7 @@ impl Ledger {
let accounts = self.payroll_accounts();
let entry = self.try_create_entry(date, &format!("Payroll {date}"))?;
for (account, side, amount) in
payroll_entry_plan(&lines, accounts, cash_account, self.base_currency)
payroll_entry_plan(&lines, accounts, cash_account, self.base_currency)?
{
self.add_line(entry, account, side, amount)?;
}
@@ -4192,11 +4441,21 @@ impl Ledger {
) -> Result<(), LedgerError> {
let mut paid: Vec<(crate::PartyId, Decimal)> = Vec::new();
let mut unnamed = false;
for l in lines.iter().filter(|l| !l.net_pay().is_zero()) {
for l in lines {
// A run is restored as journaled (rules.md B-28): its figures
// are checked, and a net past exact arithmetic refused.
let net = l.net_pay()?;
if net.is_zero() {
continue;
}
match l.employee {
Some(p) => match paid.iter_mut().find(|(x, _)| *x == p) {
Some((_, v)) => *v += l.net_pay(),
None => paid.push((p, l.net_pay())),
Some((_, v)) => {
*v = v.checked_add(net).ok_or_else(|| {
LedgerError::TooLargeToCompute(format!("party {p}'s net pay"))
})?
}
None => paid.push((p, net)),
},
None => unnamed = true,
}
@@ -4320,6 +4579,8 @@ impl Ledger {
if id != self.next_payroll_run_id {
return Err(LedgerError::ReplayIdMismatch(id, self.next_payroll_run_id));
}
// Restored exactly as journaled: the run's figures are checked by
// the command, not by replay (rules.md B-28).
self.next_payroll_run_id += 1;
if self.entries.contains_key(&entry_id) {
self.name_payroll_parties(entry_id, &lines)?;
@@ -4442,6 +4703,16 @@ pub(crate) fn check_minor_units(amount: Money) -> Result<(), LedgerError> {
}
}
/// Refuse a new line larger than any posting could carry
/// (kernel::MAX_LINE_AMOUNT; P0 review round 3, S1). Only the size: the
/// minor unit is check_minor_units', and the post checks the full range.
fn check_line_size(amount: Decimal) -> Result<(), LedgerError> {
if amount.abs() > kernel::MAX_LINE_AMOUNT {
return Err(LedgerError::AmountOutOfRange);
}
Ok(())
}
/// A members close's (capital account, share) list, in order: what a run
/// of cumulative closes must share.
fn member_key(members: &[periods::MemberClose]) -> Vec<(AccountId, Decimal)> {
+1
View File
@@ -20,6 +20,7 @@ pub mod account;
pub mod analysis;
pub mod arap;
pub mod assets;
pub mod calendar;
pub mod classes;
pub mod error;
pub mod form1099;
+41 -20
View File
@@ -552,9 +552,18 @@ pub struct EntryFlow {
/// 2100), or a loan paying it off (Dr 2050 / Cr loan): net is the
/// amount, what for is the card, as if paid from the bank.
/// ```
pub fn entry_flow(entry: &crate::JournalEntry, money: &MoneyAccounts) -> EntryFlow {
pub fn entry_flow(
entry: &crate::JournalEntry,
money: &MoneyAccounts,
) -> Result<EntryFlow, crate::LedgerError> {
use crate::Side;
use rust_decimal::Decimal;
// A draft's lines are as journaled, of any size (rules.md B-28): every
// sum is checked, and one past exact arithmetic is refused.
let too_large =
|| crate::LedgerError::TooLargeToCompute(format!("entry {}'s money flow", entry.id()));
let plus = |a: Decimal, b: Decimal| a.checked_add(b).ok_or_else(too_large);
let minus = |a: Decimal, b: Decimal| a.checked_sub(b).ok_or_else(too_large);
let (mut cash_cr, mut cash_dr, mut liab_cr, mut liab_dr) =
(Decimal::ZERO, Decimal::ZERO, Decimal::ZERO, Decimal::ZERO);
for l in entry.lines() {
@@ -564,10 +573,10 @@ pub fn entry_flow(entry: &crate::JournalEntry, money: &MoneyAccounts) -> EntryFl
money.liabilities.contains(&l.account),
l.side,
) {
(true, _, Side::Credit) => cash_cr += a,
(true, _, Side::Debit) => cash_dr += a,
(false, true, Side::Credit) => liab_cr += a,
(false, true, Side::Debit) => liab_dr += a,
(true, _, Side::Credit) => cash_cr = plus(cash_cr, a)?,
(true, _, Side::Debit) => cash_dr = plus(cash_dr, a)?,
(false, true, Side::Credit) => liab_cr = plus(liab_cr, a)?,
(false, true, Side::Debit) => liab_dr = plus(liab_dr, a)?,
_ => {}
}
}
@@ -581,13 +590,16 @@ pub fn entry_flow(entry: &crate::JournalEntry, money: &MoneyAccounts) -> EntryFl
let add = |by: &mut std::collections::BTreeMap<crate::AccountId, Decimal>,
order: &mut Vec<crate::AccountId>,
account: crate::AccountId,
part: Decimal| {
part: Decimal|
-> Result<(), crate::LedgerError> {
if !part.is_zero() {
if !by.contains_key(&account) {
order.push(account);
}
*by.entry(account).or_default() += part;
let sum = by.entry(account).or_default();
*sum = plus(*sum, part)?;
}
Ok(())
};
for l in entry.lines() {
let a = l.amount.amount;
@@ -607,7 +619,7 @@ pub fn entry_flow(entry: &crate::JournalEntry, money: &MoneyAccounts) -> EntryFl
}
};
match left.iter_mut().find(|(x, _)| *x == l.account) {
Some((_, v)) => *v += rest,
Some((_, v)) => *v = plus(*v, rest)?,
None => left.push((l.account, rest)),
}
part
@@ -617,36 +629,39 @@ pub fn entry_flow(entry: &crate::JournalEntry, money: &MoneyAccounts) -> EntryFl
Side::Credit => -a,
}
};
add(&mut by, &mut order, l.account, part);
add(&mut by, &mut order, l.account, part)?;
}
let owed_down: Decimal = left
let owed_down = left
.iter()
.map(|(_, v)| *v)
.filter(|v| *v > Decimal::ZERO)
.sum();
let owed_up: Decimal = -left
.try_fold(Decimal::ZERO, &plus)?;
let owed_up = -left
.iter()
.map(|(_, v)| *v)
.filter(|v| *v < Decimal::ZERO)
.sum::<Decimal>();
.try_fold(Decimal::ZERO, &plus)?;
let across = owed_down.min(owed_up);
let mut across_left = across;
for (account, v) in left {
if v > Decimal::ZERO && !across_left.is_zero() {
let take = v.min(across_left);
across_left -= take;
add(&mut by, &mut order, account, take);
add(&mut by, &mut order, account, take)?;
}
}
let net = (cash_cr - cash_dr) + (liab_cr - liab_dr) + down - up + across;
EntryFlow {
let net = plus(
plus(minus(cash_cr, cash_dr)?, minus(liab_cr, liab_dr)?)?,
plus(minus(down, up)?, across)?,
)?;
Ok(EntryFlow {
net,
what_for: order
.into_iter()
.map(|a| (a, by[&a]))
.filter(|(_, v)| !v.is_zero())
.collect(),
}
})
}
/// One party's entries, and the money paid to and received from it in
@@ -702,7 +717,9 @@ pub fn activity_with(
.filter(|&id| ledger.entry_names_party(id, party))
.collect();
let money = money_accounts(ledger, cash);
let net_out = |e: &crate::JournalEntry| entry_flow(e, &money).net;
// A posted entry's lines are in a line's range, so its flow computes;
// one that doesn't counts nothing and is listed as unresolved.
let net_out = |e: &crate::JournalEntry| entry_flow(e, &money).map(|f| f.net);
let (mut paid, mut received) = (Decimal::ZERO, Decimal::ZERO);
let mut unresolved = BTreeSet::new();
for &id in &entries {
@@ -712,7 +729,10 @@ pub fn activity_with(
if e.status() != crate::EntryStatus::Posted || e.date() < start || e.date() > end {
continue;
}
let net = net_out(e);
let Ok(net) = net_out(e) else {
unresolved.insert(id);
continue;
};
if net.is_zero() {
continue;
}
@@ -732,7 +752,8 @@ pub fn activity_with(
.reversal_chain(id)
.first()
.and_then(|&root| ledger.get_entry(root))
.map_or(net, net_out),
.map_or(Ok(net), net_out)
.unwrap_or(net),
None => net,
};
if side > Decimal::ZERO {
+14
View File
@@ -126,8 +126,22 @@ pub fn payout_plan(
a.code
)));
}
// No larger than a journal line may be: the payout's totals are
// sums of them (P0 review round 3, S1).
if !crate::kernel::Amount::in_line_range(amount) {
return Err(LedgerError::ValueOutOfRange(format!(
"{role} amount {amount} on {}",
a.code
)));
}
Ok(())
};
if !crate::kernel::Amount::in_line_range(payout.deposit) {
return Err(LedgerError::ValueOutOfRange(format!(
"deposit {}",
payout.deposit
)));
}
let deposit_account = chart
.get(payout.deposit_account)
.ok_or(LedgerError::UnknownAccount(payout.deposit_account))?;
+63 -23
View File
@@ -48,14 +48,20 @@ pub struct PayrollLine {
impl PayrollLine {
/// Gross minus all employee withholdings and deductions. Must be >= 0:
/// you cannot withhold more than the employee earned.
pub fn net_pay(&self) -> Decimal {
self.gross_pay
- self.federal_withholding
- self.state_withholding
- self.ss_employee
- self.medicare_employee
- self.other_deductions
/// you cannot withhold more than the employee earned. Refused
/// (TooLargeToCompute), never a panic, past exact arithmetic: a run is
/// restored as journaled (rules.md B-28).
pub fn net_pay(&self) -> Result<Decimal, LedgerError> {
[
self.federal_withholding,
self.state_withholding,
self.ss_employee,
self.medicare_employee,
self.other_deductions,
]
.into_iter()
.try_fold(self.gross_pay, Decimal::checked_sub)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{}'s net pay", self.employee_name)))
}
}
@@ -116,13 +122,40 @@ pub fn validate_payroll_lines(lines: &[PayrollLine]) -> Result<(), LedgerError>
return Err(LedgerError::NegativePayrollAmount(amount));
}
}
if line.net_pay() < Decimal::ZERO {
check_payroll_ranges(std::slice::from_ref(line))?;
if line.net_pay()? < Decimal::ZERO {
return Err(LedgerError::NegativeNetPay(line.employee_name.clone()));
}
}
Ok(())
}
/// Every amount of every line no larger than a journal line may be
/// (kernel::MAX_LINE_AMOUNT, ten decimal places), so net pay and the run's
/// totals are exact (P0 review round 3, S1). For new runs only: replay
/// restores a run as journaled (rules.md B-28).
pub fn check_payroll_ranges(lines: &[PayrollLine]) -> Result<(), LedgerError> {
for line in lines {
for amount in [
line.gross_pay,
line.federal_withholding,
line.state_withholding,
line.ss_employee,
line.medicare_employee,
line.ss_employer,
line.medicare_employer,
line.other_deductions,
] {
if !crate::kernel::Amount::in_line_range(amount) {
return Err(LedgerError::ValueOutOfRange(format!(
"payroll amount {amount}"
)));
}
}
}
Ok(())
}
/// The auto-posted payroll entry's lines, in posting order: Dr 6100 gross,
/// Dr 6110 the employer FICA share, Cr 2110–2150 the payables, Cr cash net
/// pay. Zero totals are skipped — the engine rejects zero-amount lines.
@@ -131,21 +164,28 @@ pub fn validate_payroll_lines(lines: &[PayrollLine]) -> Result<(), LedgerError>
/// journaled entry and the posted entry are built from the same math. The
/// plan always balances: debits are gross + employer FICA, credits are the
/// payables + net, and net is defined as gross minus employee withholdings.
/// Refused (TooLargeToCompute) when a total is past exact arithmetic.
pub fn payroll_entry_plan(
lines: &[PayrollLine],
accounts: PayrollAccounts,
cash_account: AccountId,
base: Currency,
) -> Vec<(AccountId, Side, Money)> {
let sum = |f: fn(&PayrollLine) -> Decimal| lines.iter().map(f).sum::<Decimal>();
let gross = sum(|l| l.gross_pay);
let employer = sum(|l| l.ss_employer + l.medicare_employer);
let federal = sum(|l| l.federal_withholding);
let state = sum(|l| l.state_withholding);
let ss = sum(|l| l.ss_employee + l.ss_employer);
let medicare = sum(|l| l.medicare_employee + l.medicare_employer);
let other = sum(|l| l.other_deductions);
let net = sum(|l| l.net_pay());
) -> Result<Vec<(AccountId, Side, Money)>, LedgerError> {
let too_large = || LedgerError::TooLargeToCompute("the payroll run's totals".into());
let sum = |f: &dyn Fn(&PayrollLine) -> Option<Decimal>| {
lines
.iter()
.try_fold(Decimal::ZERO, |t, l| t.checked_add(f(l)?))
.ok_or_else(too_large)
};
let gross = sum(&|l| Some(l.gross_pay))?;
let employer = sum(&|l| l.ss_employer.checked_add(l.medicare_employer))?;
let federal = sum(&|l| Some(l.federal_withholding))?;
let state = sum(&|l| Some(l.state_withholding))?;
let ss = sum(&|l| l.ss_employee.checked_add(l.ss_employer))?;
let medicare = sum(&|l| l.medicare_employee.checked_add(l.medicare_employer))?;
let other = sum(&|l| Some(l.other_deductions))?;
let net = sum(&|l| l.net_pay().ok())?;
let mut plan = Vec::new();
let mut push = |account: AccountId, side: Side, amount: Decimal| {
if !amount.is_zero() {
@@ -160,7 +200,7 @@ pub fn payroll_entry_plan(
push(accounts.medicare_payable, Side::Credit, medicare);
push(accounts.other_payable, Side::Credit, other);
push(cash_account, Side::Credit, net);
plan
Ok(plan)
}
/// The remittance entry's lines: Dr each payable with a non-zero balance,
@@ -222,7 +262,7 @@ mod tests {
fn net_pay_math() {
let l = line("Ada");
// 5000 - 750 - 250 - 310 - 72.50 - 100 = 3517.50
assert_eq!(l.net_pay(), d(351_750));
assert_eq!(l.net_pay().unwrap(), d(351_750));
}
#[test]
@@ -236,7 +276,7 @@ mod tests {
);
let mut over = line("Cat");
over.other_deductions = d(99_999_999);
assert!(over.net_pay() < Decimal::ZERO);
assert!(over.net_pay().unwrap() < Decimal::ZERO);
assert_eq!(
validate_payroll_lines(std::slice::from_ref(&over)),
Err(LedgerError::NegativeNetPay("Cat".to_string()))
@@ -260,7 +300,7 @@ mod tests {
let mut l = line("Ada");
l.state_withholding = Decimal::ZERO;
l.other_deductions = Decimal::ZERO;
let plan = payroll_entry_plan(&[l], accounts, cash, Currency::USD);
let plan = payroll_entry_plan(&[l], accounts, cash, Currency::USD).unwrap();
assert_eq!(plan.len(), 6); // gross, employer tax, fed, ss, medicare, cash
let mut debits = Decimal::ZERO;
let mut credits = Decimal::ZERO;
+11
View File
@@ -168,7 +168,18 @@ impl Period {
}
/// Validate a period's date range before creation.
/// [`validate_period_order`], and both ends inside the calendar the books
/// keep (crate::calendar; P0 review round 3, S1). For new periods; replay
/// checks only the order (rules.md B-28).
pub fn validate_period_range(start: NaiveDate, end: NaiveDate) -> Result<(), LedgerError> {
crate::calendar::check(start)?;
crate::calendar::check(end)?;
validate_period_order(start, end)
}
/// The check every journaled `period.created` passed when it was written
/// (the rule through 2026-10-16): the end is not before the start.
pub fn validate_period_order(start: NaiveDate, end: NaiveDate) -> Result<(), LedgerError> {
if end < start {
return Err(LedgerError::InvalidPeriodRange {
start: start.to_string(),
+21 -6
View File
@@ -1673,8 +1673,15 @@ impl AssetRegister {
/// depreciation accounts of the registered assets, so
/// unposted_depreciation and unregistered_cost are zero exactly when
/// register and books agree.
/// 6. NEVER panics: a contributor basis is as journaled, of any size
/// (rules.md B-28), and a total past exact arithmetic is refused
/// (TooLargeToCompute).
/// ```
pub fn fixed_asset_register(ledger: &Ledger, as_of: NaiveDate) -> AssetRegister {
pub fn fixed_asset_register(
ledger: &Ledger,
as_of: NaiveDate,
) -> Result<AssetRegister, LedgerError> {
let too_large = |what: &str| LedgerError::TooLargeToCompute(format!("the register's {what}"));
use crate::AssetStatus;
let mut rows = Vec::new();
let (mut cost, mut accumulated) = (Decimal::ZERO, Decimal::ZERO);
@@ -1699,10 +1706,18 @@ pub fn fixed_asset_register(ledger: &Ledger, as_of: NaiveDate) -> AssetRegister
crate::assets::accumulated_depreciation(a, as_of)
};
if disposed.is_none() {
cost += a.cost.amount;
accumulated += acc;
cost = cost
.checked_add(a.cost.amount)
.ok_or_else(|| too_large("cost"))?;
accumulated = accumulated
.checked_add(acc)
.ok_or_else(|| too_large("accumulated depreciation"))?;
match a.tax_basis() {
Some(t) => tax_total += t,
Some(t) => {
tax_total = tax_total
.checked_add(t)
.ok_or_else(|| too_large("tax basis"))?
}
None => tax_missing += 1,
}
}
@@ -1740,7 +1755,7 @@ pub fn fixed_asset_register(ledger: &Ledger, as_of: NaiveDate) -> AssetRegister
.map(|l| l.debit - l.credit)
.unwrap_or(Decimal::ZERO)
};
AssetRegister {
Ok(AssetRegister {
as_of,
rows,
total_cost: cost,
@@ -1750,5 +1765,5 @@ pub fn fixed_asset_register(ledger: &Ledger, as_of: NaiveDate) -> AssetRegister
missing_tax_basis: tax_missing,
ledger_cost: cost_accounts.iter().map(|&id| net(id)).sum(),
ledger_accumulated: -accum_accounts.iter().map(|&id| net(id)).sum::<Decimal>(),
}
})
}
+7 -1
View File
@@ -32,8 +32,13 @@ pub struct DatedRule {
pub name: &'static str,
/// Its entry in docs/spec/rules.md, e.g. "B-19".
pub catalog: &'static str,
/// The vendored official text it comes from.
/// The vendored official text it comes from (a path in this repo,
/// for the people who update the rule).
pub source: &'static str,
/// The authority itself, as an agent or a human can find it: the
/// statute or publication, with its official address. What every
/// agent-facing text names, never the repo's copy.
pub authority: &'static str,
/// The last year wanderbooks knows the rule for.
pub known_through: i32,
/// When to look again, as (year, month, day): the day the next value
@@ -62,6 +67,7 @@ pub const THRESHOLD_1099: DatedRule = DatedRule {
name: "1099 reporting threshold",
catalog: "B-19",
source: "docs/spec/sources/irs-1099-thresholds.md",
authority: "26 U.S.C. §6041(a) and (h) and the IRS's yearly figure in the Instructions for Forms 1099-MISC and 1099-NEC (https://www.irs.gov/instructions/i1099mec)",
known_through: 2026,
review: (2026, 11, 1),
review_why: "26 U.S.C. §6041(h) indexes the threshold for calendar years after 2026, \
+188 -29
View File
@@ -81,38 +81,91 @@ pub struct NewSchedule {
pub pl_account: AccountId,
}
/// The last day of `d`'s month.
/// The last day of `d`'s month: in chrono's last month (December 262142),
/// NaiveDate::MAX, never a panic.
pub fn month_end(d: NaiveDate) -> NaiveDate {
let first = NaiveDate::from_ymd_opt(d.year(), d.month(), 1).expect("valid");
first + Months::new(1) - Days::new(1)
d.with_day(1)
.and_then(|first| first.checked_add_months(Months::new(1)))
.and_then(|next| next.checked_sub_days(Days::new(1)))
.unwrap_or(NaiveDate::MAX)
}
/// The smallest total whose plan isn't computed exactly in cents (10^26):
/// 26 integer digits and 2 decimals fill Decimal's 28 significant digits.
pub const EXACT_LIMIT: Decimal =
Decimal::from_parts(0xe400_0000, 0xdcc8_0cd2, 0x0052_b7d2, false, 0);
/// The schedule's monthly postings: (month-end date, amount). Equal
/// amounts to the cent, the last month absorbing rounding, so they sum to
/// the total exactly.
///
/// ```text
/// INVARIANTS:
/// 1. The amounts sum to `total` exactly; all but the last are equal.
/// 2. NEVER panics: a schedule an earlier version journaled whose months
/// run past chrono's last day is refused with DateOutOfRange, and one
/// whose amounts exact arithmetic can't hold with TooLargeToCompute
/// (rules.md B-28). `months` is at least 1 (validate_schedule_shape).
/// 3. NEVER rounds silently: a total of EXACT_LIMIT or more is refused
/// with TooLargeToCompute. Below it every amount in cents, and every
/// sum of them (none exceeds the total), fits Decimal's 28 significant
/// digits, so INVARIANT 1 holds exactly; at it, Decimal's checked
/// operations round instead of failing.
/// ```
///
/// Replay is unaffected: a posted schedule month passed the line limit
/// (kernel::MAX_LINE_AMOUNT), so no journaled schedule.posted belongs to a
/// schedule with a total anywhere near EXACT_LIMIT.
pub fn amortization_plan(
total: Decimal,
start: NaiveDate,
months: u32,
) -> Vec<(NaiveDate, Decimal)> {
let each = (total / Decimal::from(months)).round_dp(2);
let first = NaiveDate::from_ymd_opt(start.year(), start.month(), 1).expect("valid");
) -> Result<Vec<(NaiveDate, Decimal)>, LedgerError> {
let too_large = || LedgerError::TooLargeToCompute(format!("a {months}-month plan of {total}"));
if total.abs() >= EXACT_LIMIT {
return Err(too_large());
}
let each = total
.checked_div(Decimal::from(months))
.ok_or_else(too_large)?
.round_dp(2);
let first = start
.with_day(1)
.ok_or(LedgerError::DateOutOfRange(start))?;
(0..months)
.map(|i| {
let date = month_end(first + Months::new(i));
let month = first
.checked_add_months(Months::new(i))
.ok_or(LedgerError::DateOutOfRange(start))?;
let amount = if i + 1 == months {
total - each * Decimal::from(months - 1)
each.checked_mul(Decimal::from(months - 1))
.and_then(|before| total.checked_sub(before))
.ok_or_else(too_large)?
} else {
each
};
(date, amount)
Ok((month_end(month), amount))
})
.collect()
}
/// Validate a new schedule against the chart.
/// Validate a new schedule against the chart: [`validate_schedule_shape`],
/// the total in range and in cents, and its first and last months inside
/// the calendar the books keep (crate::calendar; P0 review round 3, S1),
/// so every month end of the plan is a date.
pub fn validate_schedule(new: &NewSchedule, chart: &ChartOfAccounts) -> Result<(), LedgerError> {
validate_schedule_shape(new, chart)?;
crate::calendar::check(new.start)?;
if !new
.start
.checked_add_months(Months::new(new.months - 1))
.is_some_and(crate::calendar::in_calendar)
{
return Err(LedgerError::InvalidSchedule(format!(
"{} months from {} run past 9999-12-31, the last day the books keep",
new.months, new.start
)));
}
// Every month's posting derives from the total: one no line could
// carry, or finer than a cent, is refused here, not at a month end
// (found by the store's refusal property, 2026-10-13).
@@ -123,7 +176,9 @@ pub fn validate_schedule(new: &NewSchedule, chart: &ChartOfAccounts) -> Result<(
}
/// [`validate_schedule`] without the total's range and minor-unit checks
/// added on 2026-10-13, for replaying journals written before them.
/// added on 2026-10-13 or the calendar bound added in P0: the checks every
/// journaled `schedule.registered` passed when it was written, for
/// replaying journals written before them (rules.md B-28).
pub fn validate_schedule_shape(
new: &NewSchedule,
chart: &ChartOfAccounts,
@@ -166,21 +221,31 @@ impl AmortizationSchedule {
}
}
/// Months due through `through` and not yet posted.
pub fn due(&self, through: NaiveDate) -> Vec<(NaiveDate, Decimal)> {
/// Its monthly postings ([`amortization_plan`]); refused, never a
/// panic, for one that can't be computed.
pub fn plan(&self) -> Result<Vec<(NaiveDate, Decimal)>, LedgerError> {
amortization_plan(self.total.amount, self.start, self.months)
.into_iter()
.filter(|(d, _)| *d <= through && !self.posted.contains(d))
.collect()
}
/// The amount not yet recognized.
pub fn remaining(&self) -> Decimal {
amortization_plan(self.total.amount, self.start, self.months)
/// Months due through `through` and not yet posted.
pub fn due(&self, through: NaiveDate) -> Result<Vec<(NaiveDate, Decimal)>, LedgerError> {
Ok(self
.plan()?
.into_iter()
.filter(|(d, _)| *d <= through && !self.posted.contains(d))
.collect())
}
/// The amount not yet recognized: the sum of the plan's unposted
/// months.
pub fn remaining(&self) -> Result<Decimal, LedgerError> {
self.plan()?
.into_iter()
.filter(|(d, _)| !self.posted.contains(d))
.map(|(_, a)| a)
.sum()
.try_fold(Decimal::ZERO, |sum, (_, a)| sum.checked_add(a))
.ok_or_else(|| {
LedgerError::TooLargeToCompute(format!("schedule {}'s remaining amount", self.id))
})
}
}
@@ -256,9 +321,36 @@ pub struct NewRecurring {
pub end: Option<NaiveDate>,
}
/// Validate a new recurring entry: at least two lines, positive amounts,
/// postable accounts, balanced, and an end not before the start.
/// Validate a new recurring entry: [`validate_recurring_journaled`], its
/// dates inside the calendar the books keep, and no line larger than a
/// journal line may be (P0 review round 3, S1).
pub fn validate_recurring(new: &NewRecurring, chart: &ChartOfAccounts) -> Result<(), LedgerError> {
// The size first: a line past the limit is out of range, whatever its
// sum would be.
if new
.lines
.iter()
.any(|(_, _, money)| money.amount > crate::kernel::MAX_LINE_AMOUNT)
{
return Err(LedgerError::AmountOutOfRange);
}
validate_recurring_journaled(new, chart)?;
crate::calendar::check(new.start)?;
if let Some(end) = new.end {
crate::calendar::check(end)?;
}
Ok(())
}
/// The checks every journaled `recurring.registered` passed when it was
/// written (the rule through 2026-10-16): at least two lines, positive
/// amounts, postable accounts, balanced, and an end not before the start.
/// Replay applies exactly these (rules.md B-28). Sums too large for exact
/// arithmetic are refused (TooLargeToCompute), never a panic.
pub fn validate_recurring_journaled(
new: &NewRecurring,
chart: &ChartOfAccounts,
) -> Result<(), LedgerError> {
let bad = |m: String| Err(LedgerError::InvalidSchedule(m));
if new.description.trim().is_empty() {
return bad("description is required".into());
@@ -283,10 +375,13 @@ pub fn validate_recurring(new: &NewRecurring, chart: &ChartOfAccounts) -> Result
money.amount
));
}
match side {
Side::Debit => debits += money.amount,
Side::Credit => credits += money.amount,
}
let total = match side {
Side::Debit => &mut debits,
Side::Credit => &mut credits,
};
*total = total
.checked_add(money.amount)
.ok_or_else(|| LedgerError::TooLargeToCompute("the recurring entry's total".into()))?;
}
if debits != credits {
return bad(format!(
@@ -317,7 +412,7 @@ mod tests {
#[test]
fn plans_sum_exactly_and_land_on_month_ends() {
let plan = amortization_plan(Decimal::new(100_000, 2), d(2026, 11, 15), 3);
let plan = amortization_plan(Decimal::new(100_000, 2), d(2026, 11, 15), 3).unwrap();
// 1,000.00 / 3 = 333.33, 333.33, 333.34.
assert_eq!(
plan,
@@ -327,10 +422,74 @@ mod tests {
(d(2027, 1, 31), Decimal::new(33_334, 2)),
]
);
let leap = amortization_plan(Decimal::new(1200, 0), d(2028, 2, 1), 1);
let leap = amortization_plan(Decimal::new(1200, 0), d(2028, 2, 1), 1).unwrap();
assert_eq!(leap, [(d(2028, 2, 29), Decimal::new(1200, 0))]);
}
/// A schedule an earlier version journaled, at chrono's last month or
/// with Decimal's largest total: its plan is computed where it can be,
/// refused where it can't, never a panic (rules.md B-28).
#[test]
fn plans_at_the_edges_are_computed_or_refused() {
assert_eq!(month_end(NaiveDate::MAX), NaiveDate::MAX);
assert_eq!(month_end(d(262_142, 12, 1)), NaiveDate::MAX);
assert_eq!(month_end(d(262_142, 11, 5)), d(262_142, 11, 30));
assert_eq!(month_end(NaiveDate::MIN), d(NaiveDate::MIN.year(), 1, 31));
// The last month chrono holds is a month of the plan.
assert_eq!(
amortization_plan(Decimal::new(300, 0), d(262_142, 11, 9), 2).unwrap(),
[
(d(262_142, 11, 30), Decimal::new(150, 0)),
(NaiveDate::MAX, Decimal::new(150, 0)),
]
);
// One month further is none.
assert_eq!(
amortization_plan(Decimal::new(300, 0), d(262_142, 11, 9), 3),
Err(LedgerError::DateOutOfRange(d(262_142, 11, 9)))
);
// Past the line limit (replay takes any positive total): exact, the
// last month the remainder, right up to just under EXACT_LIMIT.
for big in ["2000000000000000.00", "99999999999999999999999999.99"] {
let big: Decimal = big.parse().unwrap();
let plan = amortization_plan(big, d(2026, 1, 1), 600).unwrap();
assert_eq!(plan.len(), 600);
assert_eq!(
plan.iter()
.try_fold(Decimal::ZERO, |s, (_, a)| s.checked_add(*a)),
Some(big)
);
}
// At EXACT_LIMIT and beyond, Decimal would round: refused, never
// rounded (INVARIANT 3), in either sign.
assert_eq!(
EXACT_LIMIT,
Decimal::from_i128_with_scale(10_i128.pow(26), 0)
);
for total in [EXACT_LIMIT, -EXACT_LIMIT, Decimal::MAX, Decimal::MIN] {
assert!(matches!(
amortization_plan(total, d(2026, 1, 1), 600),
Err(LedgerError::TooLargeToCompute(_))
));
}
let s = AmortizationSchedule {
id: 1,
description: "edge".into(),
kind: ScheduleKind::PrepaidExpense,
total: Money::new(Decimal::new(300, 0), crate::Currency::USD),
start: d(262_142, 11, 9),
months: 3,
balance_account: 1,
pl_account: 2,
posted: BTreeSet::new(),
};
assert!(s.due(NaiveDate::MAX).is_err());
assert!(s.remaining().is_err());
let s = AmortizationSchedule { months: 2, ..s };
assert_eq!(s.due(NaiveDate::MAX).unwrap().len(), 2);
assert_eq!(s.remaining(), Ok(Decimal::new(300, 0)));
}
#[test]
fn monthly_occurrences_do_not_drift() {
let f = Frequency::Monthly;
+76 -27
View File
@@ -119,7 +119,33 @@ pub struct PartyMember {
/// The structural checks on an entry's shares (the module's INVARIANTS 1–4;
/// 5 needs the directory and is [`crate::Ledger::check_set_entry_parties`]'s).
/// `known` says whether a party is in the directory. Returns why not.
///
/// For new shares: [`check_shares_journaled`], and no amount larger than a
/// line may be (kernel::MAX_LINE_AMOUNT; P0 review round 3, S1). Replay
/// checks only [`check_shares_journaled`] (rules.md B-28).
pub fn check_shares(shares: &[PartyShare], known: impl Fn(PartyId) -> bool) -> Result<(), String> {
check_shares_journaled(shares, known)?;
for s in shares {
if let Share::Amount(a) = s.share
&& a > crate::kernel::MAX_LINE_AMOUNT
{
return Err(format!(
"party {}'s amount {a} is larger than any entry may move (at most 1000000000000000)",
s.party
));
}
}
Ok(())
}
/// The checks every journaled `entry.parties_set` passed when it was
/// written (the rule through 2026-10-16): [`check_shares`] without the
/// amount's upper bound. Replay applies exactly these, so books an earlier
/// version wrote always open (rules.md B-28).
pub fn check_shares_journaled(
shares: &[PartyShare],
known: impl Fn(PartyId) -> bool,
) -> Result<(), String> {
let mut seen = std::collections::BTreeSet::new();
for s in shares {
if !known(s.party) {
@@ -178,35 +204,59 @@ pub fn check_shares(shares: &[PartyShare], known: impl Fn(PartyId) -> bool) -> R
/// What the shares are split over: the entry's flow net, else its total
/// debits (the module's DEFINITIONS).
pub fn share_target(entry: &JournalEntry, money: &crate::parties::MoneyAccounts) -> Decimal {
let net = crate::parties::entry_flow(entry, money).net;
/// Refused (TooLargeToCompute), never a panic, when a sum is past exact
/// arithmetic: a draft's lines and an entry's shares are as journaled, of
/// any size (rules.md B-28).
pub fn share_target(
entry: &JournalEntry,
money: &crate::parties::MoneyAccounts,
) -> Result<Decimal, crate::LedgerError> {
let net = crate::parties::entry_flow(entry, money)?.net;
if net.is_zero() {
entry
.lines()
.iter()
.filter(|l| l.side == Side::Debit)
.map(|l| l.amount.amount)
.sum()
.try_fold(Decimal::ZERO, |s, l| s.checked_add(l.amount.amount))
.ok_or_else(|| too_large(format!("entry {}'s debits", entry.id())))
} else {
net
Ok(net)
}
}
/// The refusal of a sum past exact arithmetic.
fn too_large(what: String) -> crate::LedgerError {
crate::LedgerError::TooLargeToCompute(what)
}
/// The sum of `values`, or None past exact arithmetic.
fn checked_sum(values: impl IntoIterator<Item = Decimal>) -> Option<Decimal> {
values
.into_iter()
.try_fold(Decimal::ZERO, |s, v| s.checked_add(v))
}
/// Split `magnitude` (non-negative) by `weights` (positive, any sum): each
/// part rounded toward zero to the cent, the cents left over to the first.
fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Vec<Decimal> {
/// None when a product or sum is past exact arithmetic.
fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option<Vec<Decimal>> {
use rust_decimal::RoundingStrategy::ToZero;
let total: Decimal = weights.iter().copied().sum();
let total = checked_sum(weights.iter().copied())?;
if weights.is_empty() || total.is_zero() {
return vec![Decimal::ZERO; weights.len()];
return Some(vec![Decimal::ZERO; weights.len()]);
}
let mut parts: Vec<Decimal> = weights
.iter()
.map(|w| (magnitude * w / total).round_dp_with_strategy(2, ToZero))
.collect();
let left = magnitude - parts.iter().copied().sum::<Decimal>();
parts[0] += left;
parts
.map(|w| {
magnitude
.checked_mul(*w)
.and_then(|x| x.checked_div(total))
.map(|x| x.round_dp_with_strategy(2, ToZero))
})
.collect::<Option<_>>()?;
let left = magnitude.checked_sub(checked_sum(parts.iter().copied())?)?;
parts[0] = parts[0].checked_add(left)?;
Some(parts)
}
/// Each party's exact part of what `entry` moved (the module's INVARIANTS
@@ -218,7 +268,8 @@ pub fn resolve(
money: &crate::parties::MoneyAccounts,
members: &[PartyMember],
) -> Result<Vec<(PartyId, Decimal)>, String> {
let target = share_target(entry, money);
let target = share_target(entry, money).map_err(|e| e.to_string())?;
let past_exact = || too_large(format!("entry {}'s shares", entry.id())).to_string();
let magnitude = target.abs();
let signed = |v: Decimal| if target.is_sign_negative() { -v } else { v };
let Some(first) = shares.first() else {
@@ -233,7 +284,7 @@ pub fn resolve(
_ => Decimal::ZERO,
})
.collect();
let sum: Decimal = amounts.iter().copied().sum();
let sum = checked_sum(amounts.iter().copied()).ok_or_else(past_exact)?;
if sum != magnitude {
return Err(format!(
"the parties' amounts sum to {sum}, but entry {} moved {magnitude}",
@@ -250,7 +301,7 @@ pub fn resolve(
_ => Decimal::ZERO,
})
.collect();
split_first(magnitude, &weights)
split_first(magnitude, &weights).ok_or_else(past_exact)?
}
Share::Derived if shares.len() == 1 => vec![magnitude],
Share::Derived => {
@@ -274,19 +325,17 @@ pub fn resolve(
let parts: Vec<Decimal> = named
.iter()
.map(|m| {
entry
.lines()
.iter()
.filter(|l| on(m, l.account))
.map(|l| match l.side {
checked_sum(entry.lines().iter().filter(|l| on(m, l.account)).map(|l| {
match l.side {
Side::Credit => l.amount.amount,
Side::Debit => -l.amount.amount,
})
.sum::<Decimal>()
.abs()
}
}))
.map(|s| s.abs())
})
.collect();
let sum: Decimal = parts.iter().copied().sum();
.collect::<Option<_>>()
.ok_or_else(past_exact)?;
let sum = checked_sum(parts.iter().copied()).ok_or_else(past_exact)?;
if sum != magnitude {
return Err(format!(
"the members' capital lines on entry {} come to {sum}, but it moved {magnitude}: give each member an amount",
@@ -302,7 +351,7 @@ pub fn resolve(
.into(),
);
}
split_first(magnitude, &weights)
split_first(magnitude, &weights).ok_or_else(past_exact)?
}
}
};
+31 -1
View File
@@ -231,7 +231,37 @@ fn registration_rejects_date_overflow() {
expense_account: expense,
})
.unwrap_err();
assert!(matches!(err, ledger_core::LedgerError::AssetDateOverflow));
assert!(matches!(
err,
ledger_core::LedgerError::DateOutOfRange(d) if d == NaiveDate::MAX
));
// Inside the calendar the books keep (ledger_core::calendar), but a
// life that runs past its last day: refused too, whatever chrono
// could still reach (P0 review round 3, S1).
let new = |date: NaiveDate, months: u32| NewAsset {
description: "Late machine".to_string(),
purchase_date: date,
cost: usd("1000"),
salvage_value: usd("0"),
useful_life_months: months,
cost_account: cost,
accum_depr_account: accum,
expense_account: expense,
};
let d = |y, m, day| NaiveDate::from_ymd_opt(y, m, day).unwrap();
for (date, months) in [
(d(9999, 6, 1), 12),
(d(9999, 12, 31), 1),
(d(2026, 1, 1), u32::MAX),
] {
assert!(matches!(
ledger.register_asset(new(date, months)).unwrap_err(),
ledger_core::LedgerError::AssetDateOverflow
));
}
// A life that ends on the calendar's last day is kept.
ledger.register_asset(new(d(9999, 11, 30), 1)).unwrap();
ledger.register_asset(new(d(1, 1, 1), 12)).unwrap();
}
#[test]
+8 -3
View File
@@ -158,7 +158,7 @@ fn an_unknown_year_threshold_is_never_guessed() {
rule,
year,
known_through,
spec,
authority,
} = &err
else {
panic!("expected RuleNotKnown, got {err:?}");
@@ -167,16 +167,21 @@ fn an_unknown_year_threshold_is_never_guessed() {
(rule.as_str(), *year, *known_through),
("1099 reporting threshold", 2027, 2026)
);
assert!(spec.ends_with("irs-1099-thresholds.md"), "{spec}");
assert!(authority.contains("https://www.irs.gov/"), "{authority}");
let why = err.to_string();
for needle in [
"2027",
"official source",
"CPA",
"github.com/swaits/wanderbooks",
"irs.gov",
"tell the human",
] {
assert!(why.contains(needle), "missing {needle:?} in: {why}");
}
// It reaches agents: it names the authority, never this repo.
for never in ["github", "pull request", "docs/", ".md"] {
assert!(!why.to_lowercase().contains(never), "{never:?} in: {why}");
}
let l = books();
assert!(matches!(
vendor_1099_report(&l, 2027, None),
+39 -7
View File
@@ -196,20 +196,52 @@ fn negative_amount_line_is_rejected() {
);
}
fn kernel_max() -> Decimal {
ledger_core::kernel::MAX_LINE_AMOUNT
}
#[test]
fn out_of_range_amount_is_rejected() {
let c = fixture_company();
let mut ledger = c.ledger;
// Big enough to overflow a sum: an error, never a panic.
// Big enough to overflow a sum: an error, never a panic, as soon as
// the line is added (a draft is summed before it posts: its debits,
// its parties' shares; P0 review round 3, S1). Replayed as an earlier
// version wrote it (rules.md B-28): accepted into its draft, whose
// post refuses it, never a panic.
let id = ledger.create_entry(date(21), "Too big");
let big = Money::new(Decimal::MAX, Currency::USD);
ledger.add_line(id, c.cash, Side::Debit, big).unwrap();
ledger.add_line(id, c.cash, Side::Debit, big).unwrap();
ledger.add_line(id, c.equity, Side::Credit, big).unwrap();
let old = ledger.create_entry(date(21), "Too big, journaled before the bound");
for amount in [
Decimal::MAX,
Decimal::MIN,
kernel_max() + Decimal::new(1, 2),
] {
let big = Money::new(amount, Currency::USD);
assert_eq!(
ledger.add_line(id, c.cash, Side::Debit, big).unwrap_err(),
LedgerError::AmountOutOfRange
);
ledger
.replay_add_line(old, c.cash, Side::Debit, big)
.unwrap();
}
let max_usd = Money::new(Decimal::MAX, Currency::USD);
ledger
.replay_add_line(old, c.equity, Side::Credit, max_usd)
.unwrap();
assert_eq!(
ledger.post_entry(id).unwrap_err(),
ledger.post_entry(old).unwrap_err(),
LedgerError::AmountOutOfRange
);
assert_eq!(
ledger.replay_post_entry(old).unwrap_err(),
LedgerError::AmountOutOfRange
);
// The largest line goes in, and posts.
let max = Money::new(kernel_max(), Currency::USD);
ledger.add_line(id, c.cash, Side::Debit, max).unwrap();
ledger.add_line(id, c.equity, Side::Credit, max).unwrap();
ledger.post_entry(id).unwrap();
// Too precise: refused as soon as it is added (finer than a cent)...
let id = ledger.create_entry(date(21), "Too precise");
let tiny = Money::new("0.00000000001".parse().unwrap(), Currency::USD);
@@ -1426,7 +1458,7 @@ fn replayed_documents_and_payments_rebuild_the_records() {
.unwrap();
let i = l.get_invoice(inv).unwrap();
assert_eq!(i.amount_paid, Decimal::from(50));
assert_eq!(i.balance(), Decimal::from(50));
assert_eq!(i.balance().unwrap(), Decimal::from(50));
assert_eq!(i.status, DocumentStatus::Partial);
let bill = l.next_bill_id();
+12 -4
View File
@@ -75,7 +75,7 @@ fn a_prepaid_expense_is_expensed_month_by_month() {
})
.unwrap();
// Through May: March, April, May, at month end, 100 each.
let due: Vec<_> = b.l.get_schedule(id).unwrap().due(d(5, 31));
let due: Vec<_> = b.l.get_schedule(id).unwrap().due(d(5, 31)).unwrap();
assert_eq!(
due,
[
@@ -88,14 +88,21 @@ fn a_prepaid_expense_is_expensed_month_by_month() {
b.l.post_schedule_month(id, month).unwrap();
}
assert!(
b.l.get_schedule(id).unwrap().due(d(5, 31)).is_empty(),
b.l.get_schedule(id)
.unwrap()
.due(d(5, 31))
.unwrap()
.is_empty(),
"idempotent"
);
assert!(matches!(
b.l.post_schedule_month(id, d(4, 30)),
Err(LedgerError::InvalidSchedule(_))
));
assert_eq!(b.l.get_schedule(id).unwrap().remaining(), dec("900"));
assert_eq!(
b.l.get_schedule(id).unwrap().remaining().unwrap(),
dec("900")
);
let bs = balance_sheet_as_of(&b.l, d(5, 31)).unwrap();
let prepaid = bs.assets.iter().find(|a| a.code == "1300").unwrap();
assert_eq!(prepaid.amount, dec("900"));
@@ -123,11 +130,12 @@ fn deferred_revenue_is_earned_to_the_cent() {
b.l.get_schedule(id)
.unwrap()
.due(d(12, 31))
.unwrap()
.into_iter()
.map(|(_, a)| a)
.collect();
assert_eq!(plan, [dec("333.33"), dec("333.33"), dec("333.34")]);
for (m, _) in b.l.get_schedule(id).unwrap().due(d(12, 31)) {
for (m, _) in b.l.get_schedule(id).unwrap().due(d(12, 31)).unwrap() {
b.l.post_schedule_month(id, m).unwrap();
}
let pl = profit_and_loss_for_period(&b.l, d(1, 1), d(3, 31), None).unwrap();
+27 -26
View File
@@ -185,8 +185,8 @@ fn invoice_total_is_sum_of_lines_and_balance_is_total_minus_paid() {
status: DocumentStatus::Partial,
entry_id: 1,
};
assert_eq!(inv.total(), dec("150.00"));
assert_eq!(inv.balance(), dec("90.00"));
assert_eq!(inv.total().unwrap(), dec("150.00"));
assert_eq!(inv.balance().unwrap(), dec("90.00"));
}
/// Oracle: Bill doc: total() is the sum of lines, balance() total - paid.
@@ -202,8 +202,8 @@ fn bill_total_is_sum_of_lines_and_balance_is_total_minus_paid() {
status: DocumentStatus::Paid,
entry_id: 9,
};
assert_eq!(bill.total(), dec("20.00"));
assert_eq!(bill.balance(), Decimal::ZERO);
assert_eq!(bill.total().unwrap(), dec("20.00"));
assert_eq!(bill.balance().unwrap(), Decimal::ZERO);
}
// ------------------------------------------------------ pure validators
@@ -285,7 +285,7 @@ fn aging_due_today_is_current() {
fn aging_not_yet_due_is_current() {
let r = aging_bucket(d(2026, 12, 31), d(2026, 10, 13), dec("5"));
assert_eq!(r.current, dec("5"));
assert_eq!(r.total(), dec("5"));
assert_eq!(r.total().unwrap(), dec("5"));
}
/// Oracle: aging_bucket SCENARIOS 2-5 at each edge (1, 30, 31, 60, 61, 90,
@@ -322,7 +322,7 @@ fn aging_row_total_sums_buckets() {
days_90: dec("4"),
days_90_plus: dec("0.25"),
};
assert_eq!(r.total(), dec("10.75"));
assert_eq!(r.total().unwrap(), dec("10.75"));
}
proptest! {
@@ -343,7 +343,7 @@ proptest! {
let mut want = [Decimal::ZERO; 5];
want[expected_bucket(due, as_of)] = balance;
prop_assert_eq!(b, want);
prop_assert_eq!(r.total(), balance);
prop_assert_eq!(r.total().unwrap(), balance);
}
/// Oracle: aging_bucket INVARIANT 2: never moves to a younger bucket as
@@ -451,10 +451,10 @@ fn create_invoice_posts_dr_receivables_cr_revenue_for_the_line_sum() {
let inv = l.get_invoice(id).unwrap().clone();
assert_eq!(inv.customer_id, c);
assert_eq!(inv.total(), dec("1234.56"));
assert_eq!(inv.total().unwrap(), dec("1234.56"));
assert_eq!(inv.amount_paid, Decimal::ZERO);
assert_eq!(inv.status, DocumentStatus::Open);
assert_eq!(inv.balance(), dec("1234.56"));
assert_eq!(inv.balance().unwrap(), dec("1234.56"));
let e = l.get_entry(inv.entry_id).unwrap();
assert_eq!(e.status(), EntryStatus::Posted);
@@ -755,7 +755,7 @@ fn receive_payment_partial_then_full() {
let inv = l.get_invoice(id).unwrap();
assert_eq!(inv.amount_paid, dec("100.00"));
assert_eq!(inv.status, DocumentStatus::Partial);
assert_eq!(inv.balance(), dec("200.00"));
assert_eq!(inv.balance().unwrap(), dec("200.00"));
assert_eq!(bal(&l, "1200"), dec("200.00"));
assert_eq!(bal(&l, "1000"), dec("100.00"));
@@ -764,7 +764,7 @@ fn receive_payment_partial_then_full() {
let inv = l.get_invoice(id).unwrap();
assert_eq!(inv.amount_paid, dec("300.00"));
assert_eq!(inv.status, DocumentStatus::Paid);
assert_eq!(inv.balance(), Decimal::ZERO);
assert_eq!(inv.balance().unwrap(), Decimal::ZERO);
assert_eq!(bal(&l, "1200"), Decimal::ZERO);
assert_eq!(bal(&l, "1000"), dec("300.00"));
}
@@ -860,7 +860,7 @@ fn create_bill_posts_dr_general_expenses_cr_payables_tagged() {
let bill = l.get_bill(id).unwrap().clone();
assert_eq!(bill.vendor_id, v);
assert_eq!(bill.total(), dec("49.50"));
assert_eq!(bill.total().unwrap(), dec("49.50"));
assert_eq!(bill.amount_paid, Decimal::ZERO);
assert_eq!(bill.status, DocumentStatus::Open);
@@ -926,7 +926,7 @@ fn pay_bill_partial_then_full() {
l.pay_bill(id, d(2026, 4, 6), dec("50.00"), cash).unwrap();
let b = l.get_bill(id).unwrap();
assert_eq!(b.status, DocumentStatus::Paid);
assert_eq!(b.balance(), Decimal::ZERO);
assert_eq!(b.balance().unwrap(), Decimal::ZERO);
assert_eq!(bal(&l, "2000"), Decimal::ZERO);
assert_eq!(bal(&l, "1000"), dec("-80.00"));
}
@@ -999,7 +999,7 @@ fn ar_aging_example() {
l.receive_payment(i4, d(2026, 9, 2), dec("7"), cash)
.unwrap();
let mut rows = l.ar_aging(as_of);
let mut rows = l.ar_aging(as_of).unwrap();
rows.sort_by(|x, y| x.name.cmp(&y.name));
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].name, "Acme");
@@ -1040,7 +1040,7 @@ fn ap_aging_example() {
.create_bill(w, d(2026, 9, 1), d(2026, 9, 30), vec![line("c", "5")])
.unwrap();
l.pay_bill(pb, d(2026, 9, 5), dec("5"), cash).unwrap();
let rows = l.ap_aging(as_of);
let rows = l.ap_aging(as_of).unwrap();
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].name, "Hosting");
assert_eq!(
@@ -1145,12 +1145,12 @@ proptest! {
let mut open_sum = Decimal::ZERO;
for (i, id) in ids.iter().enumerate() {
let inv = l.get_invoice(*id).unwrap();
prop_assert_eq!(inv.total(), totals[i]);
prop_assert_eq!(inv.total().unwrap(), totals[i]);
prop_assert_eq!(inv.amount_paid, expect_paid[i]);
prop_assert_eq!(inv.balance(), totals[i] - expect_paid[i]);
prop_assert!(inv.balance() >= Decimal::ZERO);
prop_assert_eq!(inv.balance().unwrap(), totals[i] - expect_paid[i]);
prop_assert!(inv.balance().unwrap() >= Decimal::ZERO);
prop_assert_eq!(inv.status, status_law(expect_paid[i], totals[i]));
open_sum += inv.balance();
open_sum += inv.balance().unwrap();
}
prop_assert_eq!(bal(&l, "1200"), open_sum);
prop_assert_eq!(bal(&l, "4000"), totals.iter().copied().sum::<Decimal>());
@@ -1159,7 +1159,7 @@ proptest! {
// Aging as of a date spanning every bucket edge in turn.
for as_of_off in [0i64, 1, 30, 31, 60, 61, 90, 91, 200] {
let as_of = base + Duration::days(as_of_off);
let rows = l.ar_aging(as_of);
let rows = l.ar_aging(as_of).unwrap();
let mut want: std::collections::BTreeMap<String, [Decimal; 5]> = Default::default();
for (i, doc) in docs.iter().enumerate() {
// Payments (dated base + 5) count only once made: aging
@@ -1177,7 +1177,7 @@ proptest! {
rows.iter().map(|r| (r.name.clone(), buckets(r))).collect();
prop_assert_eq!(rows.len(), got.len(), "one row per customer");
prop_assert_eq!(&got, &want);
let row_sum: Decimal = rows.iter().map(|r| r.total()).sum();
let row_sum: Decimal = rows.iter().map(|r| r.total().unwrap()).sum();
let want_sum: Decimal = want.values().flatten().copied().sum();
prop_assert_eq!(row_sum, want_sum);
}
@@ -1236,11 +1236,11 @@ proptest! {
let mut open_sum = Decimal::ZERO;
for (i, id) in ids.iter().enumerate() {
let b = l.get_bill(*id).unwrap();
prop_assert_eq!(b.total(), totals[i]);
prop_assert_eq!(b.total().unwrap(), totals[i]);
prop_assert_eq!(b.amount_paid, expect_paid[i]);
prop_assert_eq!(b.balance(), totals[i] - expect_paid[i]);
prop_assert_eq!(b.balance().unwrap(), totals[i] - expect_paid[i]);
prop_assert_eq!(b.status, status_law(expect_paid[i], totals[i]));
open_sum += b.balance();
open_sum += b.balance().unwrap();
}
prop_assert_eq!(bal(&l, "2000"), open_sum);
prop_assert_eq!(bal(&l, "6999"), totals.iter().copied().sum::<Decimal>());
@@ -1248,7 +1248,7 @@ proptest! {
for as_of_off in [0i64, 15, 45, 75, 120] {
let as_of = base + Duration::days(as_of_off);
let rows = l.ap_aging(as_of);
let rows = l.ap_aging(as_of).unwrap();
let mut want: std::collections::BTreeMap<String, [Decimal; 5]> = Default::default();
for (i, doc) in docs.iter().enumerate() {
// Payments (dated base + 3) count only once made.
@@ -1321,6 +1321,7 @@ fn aging_as_of_a_date_sees_only_what_existed_then() {
.unwrap();
let total = |as_of| -> Decimal {
l.ar_aging(as_of)
.unwrap()
.iter()
.map(|r| buckets(r).iter().copied().sum::<Decimal>())
.sum()
@@ -1332,5 +1333,5 @@ fn aging_as_of_a_date_sees_only_what_existed_then() {
// Mar 15: both.
assert_eq!(total(d(2026, 3, 15)), dec("700.00"));
// Before anything was issued: nothing.
assert!(l.ar_aging(d(2025, 12, 31)).is_empty());
assert!(l.ar_aging(d(2025, 12, 31)).unwrap().is_empty());
}
+15 -15
View File
@@ -780,7 +780,7 @@ fn register_agrees_with_the_books_when_depreciation_is_posted() {
let (mut l, _, laptop, server) = register_fixture();
l.set_asset_tag(laptop, "WL-0001").unwrap();
l.set_asset_serial(laptop, Some("C02XG0FDJGH5")).unwrap();
let r = fixed_asset_register(&l, date(2026, 3, 31));
let r = fixed_asset_register(&l, date(2026, 3, 31)).unwrap();
assert_eq!(r.as_of, date(2026, 3, 31));
assert_eq!(r.rows.len(), 2);
// INVARIANT 1: registration order.
@@ -817,7 +817,7 @@ fn register_agrees_with_the_books_when_depreciation_is_posted() {
#[test]
fn register_shows_unposted_depreciation() {
let (l, _, _, _) = register_fixture();
let r = fixed_asset_register(&l, date(2026, 4, 30));
let r = fixed_asset_register(&l, date(2026, 4, 30)).unwrap();
assert_eq!(r.total_accumulated, d("4400.00"));
assert_eq!(r.ledger_accumulated, d("3300.00"));
assert_eq!(r.unposted_depreciation(), d("1100.00"));
@@ -830,7 +830,7 @@ fn register_shows_unposted_depreciation() {
fn register_shows_overposted_depreciation_as_negative() {
let (mut l, a, _, _) = register_fixture();
depreciate(&mut l, &a, a.accum, date(2026, 3, 31), "50.00");
let r = fixed_asset_register(&l, date(2026, 3, 31));
let r = fixed_asset_register(&l, date(2026, 3, 31)).unwrap();
assert_eq!(r.ledger_accumulated, d("3350.00"));
assert_eq!(r.unposted_depreciation(), d("-50.00"));
}
@@ -839,7 +839,7 @@ fn register_shows_overposted_depreciation_as_negative() {
#[test]
fn register_ledger_balances_are_as_of_the_date() {
let (l, _, _, _) = register_fixture();
let r = fixed_asset_register(&l, date(2026, 2, 28));
let r = fixed_asset_register(&l, date(2026, 2, 28)).unwrap();
assert_eq!(r.total_accumulated, d("2200.00"));
assert_eq!(r.ledger_accumulated, d("2200.00"));
assert_eq!(r.ledger_cost, d("14400.00"));
@@ -852,7 +852,7 @@ fn register_ledger_balances_are_as_of_the_date() {
fn register_accumulated_mid_month_follows_the_schedule() {
let (l, _, laptop, server) = register_fixture();
let on = date(2026, 5, 17);
let r = fixed_asset_register(&l, on);
let r = fixed_asset_register(&l, on).unwrap();
let la = accumulated_depreciation(l.get_asset(laptop).unwrap(), on);
let sa = accumulated_depreciation(l.get_asset(server).unwrap(), on);
assert_eq!(r.rows[0].accumulated, la);
@@ -867,7 +867,7 @@ fn register_accumulated_mid_month_follows_the_schedule() {
fn register_shows_unregistered_cost() {
let (mut l, a, _, _) = register_fixture();
buy(&mut l, &a, a.equipment, date(2026, 2, 10), "500.00");
let r = fixed_asset_register(&l, date(2026, 3, 31));
let r = fixed_asset_register(&l, date(2026, 3, 31)).unwrap();
assert_eq!(r.ledger_cost, d("14900.00"));
assert_eq!(r.total_cost, d("14400.00"));
assert_eq!(r.unregistered_cost(), d("500.00"));
@@ -875,7 +875,7 @@ fn register_shows_unregistered_cost() {
let (mut l2, a2) = fixture();
l2.register_asset(equipment(&a2, "Unpaid", "800.00", 8, date(2026, 1, 1)))
.unwrap();
let r2 = fixed_asset_register(&l2, date(2026, 1, 31));
let r2 = fixed_asset_register(&l2, date(2026, 1, 31)).unwrap();
assert_eq!(r2.ledger_cost, Decimal::ZERO);
assert_eq!(r2.unregistered_cost(), d("-800.00"));
assert_eq!(r2.unposted_depreciation(), d("100.00"));
@@ -889,11 +889,11 @@ fn register_leaves_out_assets_not_yet_in_service() {
let chair = l
.register_asset(equipment(&a, "Chair", "600.00", 6, date(2026, 6, 1)))
.unwrap();
let r = fixed_asset_register(&l, date(2026, 5, 31));
let r = fixed_asset_register(&l, date(2026, 5, 31)).unwrap();
let ids: Vec<AssetId> = r.rows.iter().map(|x| x.asset_id).collect();
assert_eq!(ids, vec![laptop, server]);
assert_eq!(r.ledger_cost, d("14400.00"));
let r = fixed_asset_register(&l, date(2026, 6, 1));
let r = fixed_asset_register(&l, date(2026, 6, 1)).unwrap();
let ids: Vec<AssetId> = r.rows.iter().map(|x| x.asset_id).collect();
assert_eq!(ids, vec![laptop, server, chair]);
assert_eq!(
@@ -901,7 +901,7 @@ fn register_leaves_out_assets_not_yet_in_service() {
accumulated_depreciation(l.get_asset(chair).unwrap(), date(2026, 6, 1))
);
// Before anything: empty and zero.
let r = fixed_asset_register(&l, date(2025, 12, 31));
let r = fixed_asset_register(&l, date(2025, 12, 31)).unwrap();
assert!(r.rows.is_empty());
assert_eq!(r.total_cost, Decimal::ZERO);
assert_eq!(r.total_accumulated, Decimal::ZERO);
@@ -934,7 +934,7 @@ fn register_shows_a_disposed_asset_outside_the_totals() {
let (mut l, a, laptop, server) = register_fixture();
l.set_asset_tag(server, "WL-0002").unwrap();
dispose_server(&mut l, &a, server);
let r = fixed_asset_register(&l, date(2026, 6, 30));
let r = fixed_asset_register(&l, date(2026, 6, 30)).unwrap();
assert_eq!(r.rows.len(), 2, "a disposed asset still has a row");
let s = r.rows.iter().find(|x| x.asset_id == server).unwrap();
assert_eq!(s.disposed, Some((date(2026, 6, 30), d("2000.00"))));
@@ -959,7 +959,7 @@ fn register_shows_a_disposed_asset_outside_the_totals() {
fn register_before_the_disposal_date_shows_the_asset_held() {
let (mut l, a, _, server) = register_fixture();
dispose_server(&mut l, &a, server);
let r = fixed_asset_register(&l, date(2026, 5, 31));
let r = fixed_asset_register(&l, date(2026, 5, 31)).unwrap();
let s = r.rows.iter().find(|x| x.asset_id == server).unwrap();
assert_eq!(s.disposed, None);
assert_eq!(s.accumulated, d("500.00"));
@@ -992,7 +992,7 @@ fn register_sums_the_gl_over_distinct_asset_accounts() {
for m in 1..=3 {
depreciate(&mut l, &a, a.vehicles_accum, month_end(m), "500.00");
}
let r = fixed_asset_register(&l, date(2026, 3, 31));
let r = fixed_asset_register(&l, date(2026, 3, 31)).unwrap();
assert_eq!(r.rows[2].salvage, d("6000.00"));
assert_eq!(r.rows[2].accumulated, d("1500.00"));
assert_eq!(r.rows[2].book_value, d("34500.00"));
@@ -1013,7 +1013,7 @@ fn register_ignores_accounts_no_asset_uses() {
// Vehicles bought but never registered under 1520: not one of the
// registered assets' accounts.
buy(&mut l, &a, a.vehicles, date(2026, 1, 1), "9000.00");
let r = fixed_asset_register(&l, date(2026, 3, 31));
let r = fixed_asset_register(&l, date(2026, 3, 31)).unwrap();
assert_eq!(r.ledger_cost, d("14400.00"));
assert_eq!(r.unregistered_cost(), Decimal::ZERO);
}
@@ -1022,7 +1022,7 @@ fn register_ignores_accounts_no_asset_uses() {
#[test]
fn register_of_no_assets_is_empty() {
let (l, _) = fixture();
let r = fixed_asset_register(&l, date(2026, 12, 31));
let r = fixed_asset_register(&l, date(2026, 12, 31)).unwrap();
assert!(r.rows.is_empty());
assert_eq!(r.ledger_cost, Decimal::ZERO);
assert_eq!(r.ledger_accumulated, Decimal::ZERO);
@@ -710,8 +710,8 @@ fn dispose_asset_refuses_bad_disposals_unchanged() {
/// shares are not withheld from the employee).
#[test]
fn net_pay_is_gross_minus_employee_withholdings() {
assert_eq!(alice().net_pay(), d("3567.50"));
assert_eq!(bob().net_pay(), d("1697.00"));
assert_eq!(alice().net_pay().unwrap(), d("3567.50"));
assert_eq!(bob().net_pay().unwrap(), d("1697.00"));
}
/// Oracle: validate_payroll_lines doc "non-empty".
@@ -762,7 +762,7 @@ fn validate_lines_refuses_negative_net_pay() {
fn validate_lines_accepts_zero_net_pay() {
let mut ln = alice();
ln.other_deductions = d("3767.50");
assert_eq!(ln.net_pay(), d("0"));
assert_eq!(ln.net_pay().unwrap(), d("0"));
assert_eq!(validate_payroll_lines(&[ln]), Ok(()));
}
@@ -772,7 +772,7 @@ fn validate_lines_accepts_zero_net_pay() {
/// Cr cash 3567.50. Debits = credits = 5382.50.
#[test]
fn entry_plan_matches_hand_worked_entry() {
let plan = payroll_entry_plan(&[alice()], PA, PLAN_CASH, Currency::USD);
let plan = payroll_entry_plan(&[alice()], PA, PLAN_CASH, Currency::USD).unwrap();
let got: Vec<(AccountId, Side, Money)> = plan;
let want = [
(1, Side::Debit, usd("5000.00")),
@@ -797,7 +797,7 @@ fn entry_plan_matches_hand_worked_entry() {
/// withholding and no other deductions, so no 2120 or 2150 line.
#[test]
fn entry_plan_skips_zero_totals() {
let plan = payroll_entry_plan(&[bob()], PA, PLAN_CASH, Currency::USD);
let plan = payroll_entry_plan(&[bob()], PA, PLAN_CASH, Currency::USD).unwrap();
assert!(plan.iter().all(|(_, _, m)| !m.amount.is_zero()));
assert!(
plan.iter()
@@ -1232,14 +1232,14 @@ proptest! {
#[test]
fn prop_entry_plan_laws(lines in prop::collection::vec(arb_line(), 1..5)) {
prop_assert_eq!(validate_payroll_lines(&lines), Ok(()));
let plan = payroll_entry_plan(&lines, PA, PLAN_CASH, Currency::USD);
let plan = payroll_entry_plan(&lines, PA, PLAN_CASH, Currency::USD).unwrap();
let (dr, cr) = plan_totals(&plan);
prop_assert_eq!(dr, cr);
prop_assert!(plan.iter().all(|(_, _, m)| m.amount > Decimal::ZERO && m.currency == Currency::USD));
let sum = |f: fn(&PayrollLine) -> Decimal| -> Decimal { lines.iter().map(f).sum() };
for l in &lines {
prop_assert_eq!(
l.net_pay(),
l.net_pay().unwrap(),
l.gross_pay - l.federal_withholding - l.state_withholding
- l.ss_employee - l.medicare_employee - l.other_deductions
);
@@ -1251,7 +1251,7 @@ proptest! {
prop_assert_eq!(plan_sum(&plan, PA.ss_payable, Side::Credit), sum(|l| l.ss_employee + l.ss_employer));
prop_assert_eq!(plan_sum(&plan, PA.medicare_payable, Side::Credit), sum(|l| l.medicare_employee + l.medicare_employer));
prop_assert_eq!(plan_sum(&plan, PA.other_payable, Side::Credit), sum(|l| l.other_deductions));
prop_assert_eq!(plan_sum(&plan, PLAN_CASH, Side::Credit), sum(|l| l.net_pay()));
prop_assert_eq!(plan_sum(&plan, PLAN_CASH, Side::Credit), sum(|l| l.net_pay().unwrap()));
}
/// Oracle: payroll_remit_plan doc "balances by construction": Σ Dr = Cr
@@ -1289,7 +1289,7 @@ proptest! {
let cost: Decimal = lines.iter().map(|x| x.gross_pay + x.ss_employer + x.medicare_employer).sum();
let withheld: Decimal = lines
.iter()
.map(|x| x.gross_pay - x.net_pay() + x.ss_employer + x.medicare_employer)
.map(|x| x.gross_pay - x.net_pay().unwrap() + x.ss_employer + x.medicare_employer)
.sum();
let owed: Decimal = l.payroll_tax_payables().iter().map(|(_, b)| *b).sum();
prop_assert_eq!(owed, withheld);
+792
View File
@@ -0,0 +1,792 @@
//! No command reaches an overflow or a date chrono can't hold: every amount
//! a new command takes is at most a journal line's
//! (kernel::MAX_LINE_AMOUNT), every date is in the calendar the books keep
//! (ledger_core::calendar), and what can't be computed exactly is refused,
//! never wrapped or panicked on (P0 review round 3, finding S1: a panic
//! stops the books server). The bounds are the commands' only: replay
//! accepts every line an earlier version accepted (rules.md B-28, posted
//! is forever; P0 review round 4), so each bound here has its pair, a
//! replay of an old line past it, accepted.
//!
//! ```text
//! GOAL: a command the books can't hold is refused with a reason, the
//! ledger unchanged; a replayed line an earlier version wrote past
//! the same bound is accepted exactly as written.
//! SOURCE: DECISION (P0 review round 3, 2026-10-16, S1; round 4,
//! 2026-10-17); kernel.rs MAX_LINE_AMOUNT (rules.md: a line over a
//! quadrillion is a mistake); calendar.rs (four-digit years).
//! ```
use chrono::{Datelike, NaiveDate};
use ledger_core::kernel::MAX_LINE_AMOUNT;
use ledger_core::{
AccountId, AccountType, Currency, DocumentLine, Frequency, Ledger, LedgerError, Money,
NewRecurring, NewSchedule, PayrollLine, Side,
};
use rust_decimal::Decimal;
fn d(y: i32, m: u32, day: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(y, m, day).unwrap()
}
fn usd(a: Decimal) -> Money {
Money::new(a, Currency::USD)
}
/// One past the largest a line may be.
fn too_big() -> Decimal {
MAX_LINE_AMOUNT + Decimal::new(1, 2)
}
struct Books {
ledger: Ledger,
cash: AccountId,
prepaid: AccountId,
revenue: AccountId,
expense: AccountId,
}
fn books() -> Books {
let mut ledger = Ledger::new(Currency::USD);
let mut add = |code: &str, ty| ledger.add_account(code, code, ty, None, false).unwrap();
let cash = add("1000", AccountType::Asset);
let prepaid = add("1300", AccountType::Asset);
let revenue = add("4000", AccountType::Revenue);
let expense = add("6000", AccountType::Expense);
add("3000", AccountType::Equity);
Books {
ledger,
cash,
prepaid,
revenue,
expense,
}
}
/// A date outside the calendar is refused wherever a command takes one:
/// a draft, a period, a schedule's months, a recurring entry, a document.
#[test]
fn dates_outside_the_calendar_are_refused_everywhere() {
let mut b = books();
for far in [NaiveDate::MAX, NaiveDate::MIN, d(10000, 1, 1), d(0, 12, 31)] {
assert_eq!(
b.ledger.try_create_entry(far, "far").unwrap_err(),
LedgerError::DateOutOfRange(far)
);
assert_eq!(
b.ledger.create_period("far", far, far).unwrap_err(),
LedgerError::DateOutOfRange(far)
);
}
assert_eq!(
b.ledger
.create_period("far", d(2026, 1, 1), d(10000, 1, 1))
.unwrap_err(),
LedgerError::DateOutOfRange(d(10000, 1, 1))
);
b.ledger.try_create_entry(d(1, 1, 1), "first day").unwrap();
b.ledger
.try_create_entry(d(9999, 12, 31), "last day")
.unwrap();
b.ledger
.create_period("last", d(9999, 12, 1), d(9999, 12, 31))
.unwrap();
// A schedule whose months run past the calendar's last day.
let schedule = |start: NaiveDate, months: u32| NewSchedule {
description: "Insurance".into(),
kind: ledger_core::schedules::ScheduleKind::PrepaidExpense,
total: usd(Decimal::new(30000, 2)),
start,
months,
balance_account: b.prepaid,
pl_account: b.expense,
};
for (start, months) in [
(d(9999, 12, 15), 2),
(d(9999, 1, 1), 13),
(NaiveDate::MAX, 1),
(d(0, 6, 1), 1),
] {
assert!(
b.ledger.register_schedule(schedule(start, months)).is_err(),
"{start} + {months}"
);
}
b.ledger
.register_schedule(schedule(d(9999, 1, 1), 12))
.unwrap();
// A recurring entry starting or ending outside it.
let recurring = |start: NaiveDate, end: Option<NaiveDate>| NewRecurring {
description: "Rent".into(),
lines: vec![
(b.expense, Side::Debit, usd(Decimal::ONE)),
(b.cash, Side::Credit, usd(Decimal::ONE)),
],
frequency: Frequency::Monthly,
start,
end,
};
for (start, end) in [
(NaiveDate::MIN, None),
(d(2026, 1, 1), Some(NaiveDate::MAX)),
] {
assert!(matches!(
b.ledger.register_recurring(recurring(start, end)),
Err(LedgerError::DateOutOfRange(_))
));
}
// An invoice due outside it.
let customer = b.ledger.add_customer("Client").unwrap();
let line = vec![DocumentLine {
description: "work".into(),
amount: Decimal::ONE,
}];
assert_eq!(
b.ledger
.create_invoice(customer, d(2026, 1, 1), NaiveDate::MAX, line.clone())
.unwrap_err(),
LedgerError::DateOutOfRange(NaiveDate::MAX)
);
let _ = b.revenue;
}
/// The pairs of dates_outside_the_calendar_are_refused_everywhere: each
/// replay of an old line dated past the calendar is accepted as written.
#[test]
fn replayed_dates_outside_the_calendar_are_accepted() {
let mut b = books();
for far in [NaiveDate::MAX, NaiveDate::MIN, d(10000, 1, 1), d(0, 12, 31)] {
let e = b.ledger.create_entry(far, "far");
assert_eq!(b.ledger.get_entry(e).unwrap().date(), far);
let p = b.ledger.replay_create_period("far", far, far).unwrap();
assert_eq!(b.ledger.get_period(p).unwrap().start, far);
}
// Only the order is checked on replay.
assert!(matches!(
b.ledger
.replay_create_period("backwards", d(2026, 2, 1), d(2026, 1, 1)),
Err(LedgerError::InvalidPeriodRange { .. })
));
let schedule = |start: NaiveDate, months: u32| NewSchedule {
description: "Insurance".into(),
kind: ledger_core::schedules::ScheduleKind::PrepaidExpense,
total: usd(Decimal::new(30000, 2)),
start,
months,
balance_account: b.prepaid,
pl_account: b.expense,
};
for (start, months) in [
(d(9999, 12, 15), 2),
(d(9999, 6, 1), 12),
(NaiveDate::MAX, 1),
(d(0, 6, 1), 1),
] {
let id = b
.ledger
.replay_register_schedule(schedule(start, months))
.unwrap_or_else(|e| panic!("{start} + {months}: {e}"));
assert_eq!(b.ledger.get_schedule(id).unwrap().start, start);
}
// The month bounds are main's: 1 to 600.
assert!(
b.ledger
.replay_register_schedule(schedule(d(2026, 1, 1), 601))
.is_err()
);
let recurring = |start: NaiveDate, end: Option<NaiveDate>| NewRecurring {
description: "Rent".into(),
lines: vec![
(b.expense, Side::Debit, usd(Decimal::ONE)),
(b.cash, Side::Credit, usd(Decimal::ONE)),
],
frequency: Frequency::Monthly,
start,
end,
};
for (start, end) in [
(NaiveDate::MIN, None),
(d(2026, 1, 1), Some(NaiveDate::MAX)),
] {
b.ledger
.replay_register_recurring(recurring(start, end))
.unwrap();
}
let customer = b.ledger.add_customer("Client").unwrap();
let vendor = b.ledger.add_vendor("Supplier").unwrap();
let line = vec![DocumentLine {
description: "work".into(),
amount: Decimal::ONE,
}];
b.ledger
.replay_invoice(1, customer, NaiveDate::MIN, NaiveDate::MAX, line.clone(), 1)
.unwrap();
b.ledger
.replay_bill(1, vendor, d(0, 1, 1), d(10000, 1, 1), line, 1)
.unwrap();
let mut add = |code: &str, ty| b.ledger.add_account(code, code, ty, None, false).unwrap();
let equipment = add("1500", AccountType::Asset);
let accum = add("1501", AccountType::Asset);
let depreciation = add("6100", AccountType::Expense);
let asset = |purchase_date: NaiveDate, useful_life_months: u32| ledger_core::NewAsset {
description: "Late".into(),
purchase_date,
cost: usd(Decimal::new(120000, 2)),
salvage_value: usd(Decimal::ZERO),
useful_life_months,
cost_account: equipment,
accum_depr_account: accum,
expense_account: depreciation,
};
for (date, life) in [
(d(9999, 1, 1), 60),
(d(2026, 1, 1), 120_000),
(d(0, 1, 1), 1),
] {
assert_eq!(
b.ledger.register_asset(asset(date, life)).unwrap_err(),
if date.year() == 0 {
LedgerError::DateOutOfRange(date)
} else {
LedgerError::AssetDateOverflow
}
);
b.ledger.replay_register_asset(asset(date, life)).unwrap();
}
// Replay keeps main's one date rule: the life's end is a date chrono
// holds.
assert_eq!(
b.ledger
.replay_register_asset(asset(d(262_142, 1, 1), 12))
.unwrap_err(),
LedgerError::AssetDateOverflow
);
let id = b
.ledger
.replay_register_asset(asset(d(2026, 1, 1), 12))
.unwrap();
let fix = |purchase_date: NaiveDate| ledger_core::AssetCorrection {
cost: usd(Decimal::new(120000, 2)),
salvage_value: usd(Decimal::ZERO),
useful_life_months: 60,
purchase_date,
};
assert_eq!(
b.ledger.correct_asset(id, fix(d(9999, 1, 1))).unwrap_err(),
LedgerError::AssetDateOverflow
);
b.ledger
.replay_correct_asset(id, fix(d(9999, 1, 1)))
.unwrap();
assert_eq!(b.ledger.get_asset(id).unwrap().purchase_date, d(9999, 1, 1));
// A disposal dated past the calendar.
let proceeds = usd(Decimal::ZERO);
assert_eq!(
b.ledger
.dispose_asset(id, d(10000, 1, 1), proceeds)
.unwrap_err(),
LedgerError::DateOutOfRange(d(10000, 1, 1))
);
b.ledger
.replay_dispose_asset(id, d(10000, 1, 1), proceeds)
.unwrap();
}
/// An amount larger than a line may be is refused wherever a command takes
/// one, so every sum the books make of them is exact.
#[test]
fn amounts_larger_than_a_line_are_refused_everywhere() {
let mut b = books();
let big = too_big();
// A draft line, as it is added; replayed as an older version wrote it.
let e = b.ledger.try_create_entry(d(2026, 1, 1), "big").unwrap();
assert_eq!(
b.ledger
.add_line(e, b.expense, Side::Debit, usd(big))
.unwrap_err(),
LedgerError::AmountOutOfRange
);
for a in [big, Decimal::MAX, -Decimal::MAX] {
b.ledger
.replay_add_line(e, b.expense, Side::Debit, usd(a))
.unwrap();
}
assert_eq!(b.ledger.get_entry(e).unwrap().lines().len(), 3);
// Its post refuses it, never a panic.
assert!(b.ledger.post_entry(e).is_err());
// Document lines, and their replay.
let customer = b.ledger.add_customer("Client").unwrap();
let lines = |a: Decimal| {
vec![
DocumentLine {
description: "a".into(),
amount: a,
},
DocumentLine {
description: "b".into(),
amount: Decimal::ONE,
},
]
};
for a in [big, Decimal::MAX, Decimal::new(1, 11)] {
assert!(matches!(
b.ledger
.create_invoice(customer, d(2026, 1, 1), d(2026, 2, 1), lines(a)),
Err(LedgerError::ValueOutOfRange(_))
));
}
// Replayed as journaled: whatever its lines, a document is restored;
// a total past exact arithmetic is refused where it is computed.
for (id, a) in [(1, big), (2, Decimal::new(1, 11)), (3, Decimal::MAX)] {
b.ledger
.replay_invoice(id, customer, d(2026, 1, 1), d(2026, 2, 1), lines(a), id)
.unwrap();
}
assert_eq!(
b.ledger.get_invoice(2).unwrap().total(),
Ok(Decimal::new(100_000_000_001, 11))
);
assert!(matches!(
b.ledger.get_invoice(3).unwrap().total(),
Err(LedgerError::TooLargeToCompute(_))
));
assert!(matches!(
b.ledger.ar_aging(d(2026, 3, 1)),
Err(LedgerError::TooLargeToCompute(_))
));
// A recurring template's lines.
let recurring = NewRecurring {
description: "x".into(),
lines: vec![
(b.expense, Side::Debit, usd(Decimal::MAX)),
(b.expense, Side::Debit, usd(Decimal::ONE)),
(b.cash, Side::Credit, usd(Decimal::ONE)),
],
frequency: Frequency::Monthly,
start: d(2026, 1, 1),
end: None,
};
assert_eq!(
b.ledger.register_recurring(recurring.clone()).unwrap_err(),
LedgerError::AmountOutOfRange
);
// On replay, one whose debits overflow Decimal is refused (no version
// could have written it: main panicked on it), never a panic; one past
// the line limit that balances is accepted.
assert!(matches!(
b.ledger.replay_register_recurring(recurring),
Err(LedgerError::TooLargeToCompute(_))
));
let half = Decimal::MAX / Decimal::TWO;
b.ledger
.replay_register_recurring(NewRecurring {
description: "x".into(),
lines: vec![
(b.expense, Side::Debit, usd(half)),
(b.cash, Side::Credit, usd(half)),
],
frequency: Frequency::Monthly,
start: d(2026, 1, 1),
end: None,
})
.unwrap();
// Payroll figures, run and replayed.
let payroll = |fed: Decimal, ss: Decimal| PayrollLine {
employee_name: "Dana".into(),
employee: None,
gross_pay: Decimal::ONE,
federal_withholding: fed,
state_withholding: fed,
ss_employee: Decimal::ZERO,
medicare_employee: Decimal::ZERO,
ss_employer: ss,
medicare_employer: Decimal::ONE,
other_deductions: Decimal::ZERO,
};
for line in [
payroll(Decimal::MAX, Decimal::ONE),
payroll(Decimal::ZERO, big),
] {
assert!(matches!(
b.ledger.run_payroll(d(2026, 1, 31), vec![line], b.cash),
Err(LedgerError::ValueOutOfRange(_))
));
}
// Replayed as journaled, sub-cent and past the limit alike; a net
// past exact arithmetic is refused where it is computed.
let fine = payroll(Decimal::new(1, 12), Decimal::ONE);
let huge = payroll(Decimal::ZERO, big);
b.ledger
.replay_payroll_run(1, d(2026, 1, 31), vec![fine, huge], 1)
.unwrap();
let mut over = payroll(Decimal::ZERO, Decimal::ONE);
over.gross_pay = -Decimal::MAX;
over.federal_withholding = Decimal::MAX;
assert!(matches!(
over.net_pay(),
Err(LedgerError::TooLargeToCompute(_))
));
assert!(
ledger_core::payroll::check_payroll_ranges(&[payroll(MAX_LINE_AMOUNT, MAX_LINE_AMOUNT)])
.is_ok()
);
// A statement balance in a reconciliation.
for balance in [-Decimal::MAX, big, -big] {
assert!(matches!(
b.ledger
.reconciliation_report(b.cash, d(2026, 1, 31), balance),
Err(LedgerError::ValueOutOfRange(_))
));
}
let report = b
.ledger
.reconciliation_report(b.cash, d(2026, 1, 31), -MAX_LINE_AMOUNT)
.unwrap();
assert_eq!(report.difference, MAX_LINE_AMOUNT);
// A payout's lines and its deposit.
let payout = |revenue: Decimal, deposit: Decimal| ledger_core::Payout {
deposit_account: b.cash,
deposit,
revenue: vec![ledger_core::PayoutLine {
account: b.revenue,
amount: revenue,
class: None,
}],
fees: vec![],
adjustments: vec![],
};
for p in [payout(big, big), payout(Decimal::ONE, -Decimal::MAX)] {
assert!(matches!(
ledger_core::payout_plan(&p, b.ledger.chart()),
Err(LedgerError::ValueOutOfRange(_))
));
}
assert!(
ledger_core::payout_plan(&payout(MAX_LINE_AMOUNT, MAX_LINE_AMOUNT), b.ledger.chart())
.is_ok()
);
// A contributor's basis.
let basis = |b: Decimal| ledger_core::TaxBasis {
rule: ledger_core::TaxBasisRule::Carryover,
contributor_basis: Some(b),
};
assert!(basis(big).check().is_err());
assert!(basis(MAX_LINE_AMOUNT).check().is_ok());
// On replay: every journaled basis passed check_journaled.
let cents_max = Decimal::MAX.round_dp(2) / Decimal::ONE_HUNDRED;
assert!(basis(big.round_dp(2)).check_journaled().is_ok());
assert!(basis(cents_max.round_dp(2)).check_journaled().is_ok());
assert!(basis(-Decimal::ONE).check_journaled().is_err());
// A party's share of an entry.
let share = |a: Decimal| {
vec![ledger_core::PartyShare {
party: 1,
share: ledger_core::shares::Share::Amount(a),
}]
};
let known = |_| true;
assert!(ledger_core::shares::check_shares(&share(big.round_dp(2)), known).is_err());
assert!(ledger_core::shares::check_shares(&share(MAX_LINE_AMOUNT), known).is_ok());
// On replay: every journaled share passed check_shares_journaled.
assert!(ledger_core::shares::check_shares_journaled(&share(big.round_dp(2)), known).is_ok());
assert!(ledger_core::shares::check_shares_journaled(&share(Decimal::MAX), known).is_ok());
assert!(ledger_core::shares::check_shares_journaled(&share(Decimal::ZERO), known).is_err());
}
/// The ledger-level pairs for a basis and shares: the command refuses past
/// the limit; replay of the old line is accepted, and what it feeds (the
/// register, the shares' resolution) refuses what it can't compute.
#[test]
fn replayed_bases_and_shares_past_the_limit_are_accepted() {
let mut b = books();
let mut add = |code: &str, ty| b.ledger.add_account(code, code, ty, None, false).unwrap();
let equipment = add("1500", AccountType::Asset);
let accum = add("1501", AccountType::Asset);
let depreciation = add("6100", AccountType::Expense);
// Decimal's largest is a whole number of cents, as every version
// required of a basis and a share.
let cents_max = Decimal::MAX;
let basis = ledger_core::TaxBasis {
rule: ledger_core::TaxBasisRule::Carryover,
contributor_basis: Some(cents_max),
};
for _ in 0..2 {
let id = b
.ledger
.register_asset(ledger_core::NewAsset {
description: "Laptop".into(),
purchase_date: d(2026, 1, 1),
cost: usd(Decimal::new(240000, 2)),
salvage_value: usd(Decimal::ZERO),
useful_life_months: 24,
cost_account: equipment,
accum_depr_account: accum,
expense_account: depreciation,
})
.unwrap();
assert!(matches!(
b.ledger.set_asset_tax_basis(id, basis),
Err(LedgerError::InvalidTaxBasis(_))
));
b.ledger.replay_set_asset_tax_basis(id, basis).unwrap();
assert_eq!(b.ledger.get_asset(id).unwrap().tax, Some(basis));
}
assert!(matches!(
ledger_core::fixed_asset_register(&b.ledger, d(2026, 12, 31)),
Err(LedgerError::TooLargeToCompute(_))
));
let a = b
.ledger
.add_party("A", &[ledger_core::Role::Member])
.unwrap();
let c = b
.ledger
.add_party("C", &[ledger_core::Role::Member])
.unwrap();
let e = b.ledger.try_create_entry(d(2026, 3, 1), "rent").unwrap();
b.ledger
.add_line(e, b.expense, Side::Debit, usd(Decimal::TEN))
.unwrap();
b.ledger
.add_line(e, b.cash, Side::Credit, usd(Decimal::TEN))
.unwrap();
b.ledger.post_entry(e).unwrap();
let shares = [a, c].map(|party| ledger_core::PartyShare {
party,
share: ledger_core::shares::Share::Amount(cents_max),
});
assert!(matches!(
b.ledger.set_entry_parties(e, &shares),
Err(LedgerError::InvalidParty(_))
));
b.ledger.replay_set_entry_parties(e, &shares).unwrap();
assert_eq!(b.ledger.entry_parties(e), &shares);
let money = ledger_core::parties::money_accounts(&b.ledger, &[b.cash]);
let why = ledger_core::shares::resolve(b.ledger.get_entry(e).unwrap(), &shares, &money, &[])
.unwrap_err();
assert!(why.contains("too large to compute"), "{why}");
// Replay still checks what every version checked.
assert_eq!(
b.ledger.replay_set_entry_parties(99, &shares).unwrap_err(),
LedgerError::UnknownEntry(99)
);
}
/// 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).
#[test]
fn replayed_payments_are_as_journaled() {
let mut b = books();
let customer = b.ledger.add_customer("Client").unwrap();
let invoice = b
.ledger
.create_invoice(
customer,
d(2026, 1, 1),
d(2026, 2, 1),
vec![DocumentLine {
description: "work".into(),
amount: Decimal::new(10000, 2),
}],
)
.unwrap();
assert!(matches!(
b.ledger
.receive_payment(invoice, d(2026, 1, 15), too_big(), b.cash),
Err(LedgerError::Overpayment(..))
));
b.ledger
.replay_invoice_payment(invoice, too_big(), 98)
.unwrap();
b.ledger
.replay_invoice_payment(invoice, Decimal::MAX - too_big(), 99)
.unwrap();
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
);
}
/// A disposal's proceeds are a line of its entry, and its date a day of
/// the calendar, for a new disposal; a replayed one is as journaled, and
/// its amounts (disposal_amounts, pure) are computed, never a panic.
#[test]
fn disposal_proceeds_and_dates_are_bounded() {
let mut b = books();
let mut add = |code: &str, ty| b.ledger.add_account(code, code, ty, None, false).unwrap();
let equipment = add("1500", AccountType::Asset);
let accum = add("1501", AccountType::Asset);
let depreciation = add("6100", AccountType::Expense);
let laptop = || ledger_core::NewAsset {
description: "Laptop".into(),
purchase_date: d(2026, 1, 1),
cost: usd(Decimal::new(240000, 2)),
salvage_value: usd(Decimal::ZERO),
useful_life_months: 24,
cost_account: equipment,
accum_depr_account: accum,
expense_account: depreciation,
};
let id = b.ledger.register_asset(laptop()).unwrap();
for proceeds in [Decimal::MAX, too_big()] {
assert_eq!(
b.ledger
.dispose_asset(id, d(2026, 6, 30), usd(proceeds))
.unwrap_err(),
LedgerError::AmountOutOfRange
);
let asset = b.ledger.get_asset(id).unwrap().clone();
let amounts = ledger_core::disposal_amounts(&asset, d(2026, 6, 30), usd(proceeds)).unwrap();
assert_eq!(amounts.gain_loss, proceeds - amounts.book_value);
}
assert_eq!(
b.ledger
.dispose_asset(id, NaiveDate::MAX, usd(Decimal::ONE))
.unwrap_err(),
LedgerError::DateOutOfRange(NaiveDate::MAX)
);
// Disposal amounts at chrono's last day: computed.
let asset = b.ledger.get_asset(id).unwrap().clone();
let amounts = ledger_core::disposal_amounts(&asset, NaiveDate::MAX, usd(Decimal::ONE)).unwrap();
assert_eq!(amounts.book_value, Decimal::ZERO);
b.ledger
.dispose_asset(id, d(2026, 6, 30), usd(MAX_LINE_AMOUNT))
.unwrap();
// Replayed past both bounds: accepted as journaled.
let old = b.ledger.register_asset(laptop()).unwrap();
b.ledger
.replay_dispose_asset(old, NaiveDate::MAX, usd(Decimal::MAX))
.unwrap();
assert!(matches!(
b.ledger.get_asset(old).unwrap().status,
ledger_core::AssetStatus::Disposed { date, .. } if date == NaiveDate::MAX
));
// Replay keeps what every version checked: no disposal twice, none
// before the purchase, no negative proceeds.
assert_eq!(
b.ledger
.replay_dispose_asset(old, NaiveDate::MAX, usd(Decimal::ONE))
.unwrap_err(),
LedgerError::AssetAlreadyDisposed(old)
);
let early = b.ledger.register_asset(laptop()).unwrap();
assert!(matches!(
b.ledger
.replay_dispose_asset(early, d(2025, 1, 1), usd(Decimal::ONE)),
Err(LedgerError::DisposalBeforePurchase(_))
));
assert!(matches!(
b.ledger
.replay_dispose_asset(early, d(2026, 2, 1), usd(-Decimal::ONE)),
Err(LedgerError::NegativeProceeds(_))
));
}
/// The bounds are the line limit exactly: a new draft line (base or
/// foreign) and a recurring template's line may be as large as a line, and
/// no larger; a replayed one past it is accepted as journaled.
#[test]
fn the_bound_is_the_line_limit_itself() {
let mut b = books();
let e = b.ledger.try_create_entry(d(2026, 1, 1), "max").unwrap();
for amount in [MAX_LINE_AMOUNT, -MAX_LINE_AMOUNT] {
b.ledger
.add_line(e, b.cash, Side::Debit, usd(amount))
.unwrap();
}
for amount in [too_big().round_dp(2), -too_big().round_dp(2)] {
assert_eq!(
b.ledger
.add_line(e, b.cash, Side::Debit, usd(amount))
.unwrap_err(),
LedgerError::AmountOutOfRange
);
}
// A foreign line: its base amount, foreign x rate, is what's bounded.
b.ledger
.add_line_fx(
e,
b.cash,
Side::Debit,
Currency::EUR,
MAX_LINE_AMOUNT,
Decimal::ONE,
)
.unwrap();
assert_eq!(
b.ledger
.add_line_fx(
e,
b.cash,
Side::Debit,
Currency::EUR,
MAX_LINE_AMOUNT,
Decimal::TWO
)
.unwrap_err(),
LedgerError::AmountOutOfRange
);
// Replayed as an earlier version booked them: past the limit too.
for amount in [too_big(), -too_big(), Decimal::MAX] {
b.ledger
.replay_add_line_fx(
e,
b.cash,
Side::Debit,
usd(amount),
Currency::EUR,
Decimal::ONE,
)
.unwrap();
b.ledger
.replay_add_line(e, b.cash, Side::Debit, usd(amount))
.unwrap();
}
assert_eq!(b.ledger.get_entry(e).unwrap().lines().len(), 9);
let recurring = |a: Decimal| NewRecurring {
description: "max".into(),
lines: vec![
(b.expense, Side::Debit, usd(a)),
(b.cash, Side::Credit, usd(a)),
],
frequency: Frequency::Monthly,
start: d(2026, 1, 1),
end: None,
};
b.ledger
.register_recurring(recurring(MAX_LINE_AMOUNT))
.unwrap();
assert_eq!(
b.ledger
.register_recurring(recurring(too_big()))
.unwrap_err(),
LedgerError::AmountOutOfRange
);
let old = b
.ledger
.replay_register_recurring(recurring(too_big()))
.unwrap();
// Its occurrences generate drafts as journaled; their post refuses.
let draft = b
.ledger
.replay_generate_recurring(old, d(2026, 1, 1))
.unwrap();
assert_eq!(
b.ledger.get_entry(draft).unwrap().lines()[0].amount.amount,
too_big()
);
assert_eq!(
b.ledger.post_entry(draft).unwrap_err(),
LedgerError::AmountOutOfRange
);
}
+194 -2
View File
@@ -17,7 +17,7 @@ use chrono::NaiveDate;
use ledger_core::parties::{check_text, has_full_tin, name_key, redact_full_tins};
use ledger_core::{
AccountId, AccountType, Currency, EntryId, Ledger, Money, Party, PartyField, PartyId,
PayrollLine, Role, Side, W4Facts, W9Facts,
PartyShare, PayrollLine, Role, Side, W4Facts, W9Facts,
};
use proptest::prelude::*;
use rust_decimal::Decimal;
@@ -959,6 +959,78 @@ fn payroll_employee_must_have_the_employee_role() {
assert_eq!(rec.lines[0].employee, Some(alice));
}
/// Oracle: name_payroll_parties doc: a payroll entry names the employees
/// it paid as its parties, each with their net pay (one employee: the whole
/// entry), live and on replay alike; a line naming no employee leaves the
/// entry untagged; a line paying nothing names no one.
#[test]
fn a_payroll_entry_names_the_employees_it_paid() {
let (mut l, fx) = fixture();
let alice = l.add_party("Alice", &[Role::Employee]).unwrap();
let bob = l.add_party("Bob", &[Role::Employee]).unwrap();
let day = date(2026, 2, 27);
let net = d("823.50");
let run = l
.run_payroll(day, vec![pay_line("Alice", Some(alice))], fx.cash)
.unwrap();
let entry = l.get_payroll_run(run).unwrap().entry_id;
assert_eq!(l.entry_parties(entry), &[PartyShare::whole(alice)]);
// Alice twice (her two lines one share) and Bob: exact amounts.
let lines = vec![
pay_line("Alice", Some(alice)),
pay_line("Bob", Some(bob)),
pay_line("Alice", Some(alice)),
];
let run = l.run_payroll(day, lines.clone(), fx.cash).unwrap();
let entry = l.get_payroll_run(run).unwrap().entry_id;
let amounts = |a: Decimal, b: Decimal| {
vec![
PartyShare {
party: alice,
share: ledger_core::Share::Amount(a),
},
PartyShare {
party: bob,
share: ledger_core::Share::Amount(b),
},
]
};
assert_eq!(l.entry_parties(entry), amounts(net + net, net).as_slice());
// The same run replayed names them the same way.
let replayed = l.create_entry(day, "Payroll replayed");
let hosting = l.chart().find_by_code("6050").unwrap().id;
l.add_line(replayed, hosting, Side::Debit, usd("1.00"))
.unwrap();
l.add_line(replayed, fx.cash, Side::Credit, usd("1.00"))
.unwrap();
l.post_entry(replayed).unwrap();
let id = l.next_payroll_run_id();
l.replay_payroll_run(id, day, lines, replayed).unwrap();
assert_eq!(
l.entry_parties(replayed),
amounts(net + net, net).as_slice()
);
// A line naming no employee: the entry is left for the agent to tag.
let run = l
.run_payroll(
day,
vec![pay_line("Alice", Some(alice)), pay_line("Old", None)],
fx.cash,
)
.unwrap();
let entry = l.get_payroll_run(run).unwrap().entry_id;
assert!(l.entry_parties(entry).is_empty());
// A line that pays nothing (all withheld) names no one, so Bob's run
// is his alone.
let mut nothing = pay_line("Old", None);
nothing.federal_withholding = d("923.50");
let run = l
.run_payroll(day, vec![nothing, pay_line("Bob", Some(bob))], fx.cash)
.unwrap();
let entry = l.get_payroll_run(run).unwrap().entry_id;
assert_eq!(l.entry_parties(entry), &[PartyShare::whole(bob)]);
}
// ---------------------------------------------------------------- invariants
/// INVARIANTS 1–4 plus the vendor/party tag sync, over the whole ledger.
@@ -1181,6 +1253,126 @@ fn a_vault_record_hash_with_nine_digits_is_accepted() {
assert_eq!(facts.check(), Ok(()));
}
/// Oracle: parties::entry_flow DEFINITIONS (across): one liability paying
/// down two (a member paying both cards from their own funds): across is
/// taken from the debited liabilities in order of first appearance, each
/// at most what is left of it, until across is used up.
#[test]
fn entry_flow_takes_across_in_order_until_used_up() {
use ledger_core::parties::{entry_flow, money_accounts};
use ledger_core::{AccountType, Currency, Ledger, Money, Side};
let mut l = Ledger::new(Currency::USD);
let mut acct = |code: &str, t| l.add_account(code, code, t, None, false).unwrap();
let bank = acct("1000", AccountType::Asset);
let card_a = acct("2050", AccountType::Liability);
let card_b = acct("2060", AccountType::Liability);
let members = acct("2100", AccountType::Liability);
let capital = acct("3000", AccountType::Equity);
let fees = acct("6000", AccountType::Expense);
let money = money_accounts(&l, &[bank]);
let e = l.create_entry(NaiveDate::from_ymd_opt(2026, 5, 1).unwrap(), "x");
for (a, side, amt) in [
(card_a, Side::Debit, "30.00"),
(card_b, Side::Debit, "20.00"),
(fees, Side::Debit, "5.00"),
(members, Side::Credit, "25.00"),
(bank, Side::Credit, "15.00"),
(capital, Side::Credit, "15.00"),
] {
l.add_line(e, a, side, Money::new(d(amt), Currency::USD))
.unwrap();
}
let f = entry_flow(l.get_entry(e).unwrap(), &money).unwrap();
// down = min(liab_dr 50, cash_cr 15) = 15: card A's first 15. Left:
// card A 15, card B 20, members -25; across = min(35, 25) = 25: card
// A's 15, then 10 of card B's 20, and nothing more.
assert_eq!(f.net, d("30.00"));
assert_eq!(
f.what_for,
vec![
(card_a, d("30.00")),
(fees, d("5.00")),
(capital, d("-15.00")),
(card_b, d("10.00"))
]
);
}
/// Oracle: shares::share_target: an entry moving no money splits over its
/// total debits, whatever its credits (a draft not yet balanced).
#[test]
fn a_share_target_without_money_is_the_debits() {
use ledger_core::parties::money_accounts;
use ledger_core::{AccountType, Currency, Ledger, Money, Side};
let mut l = Ledger::new(Currency::USD);
let bank = l
.add_account("1000", "Bank", AccountType::Asset, None, false)
.unwrap();
let equip = l
.add_account("1500", "Equipment", AccountType::Asset, None, false)
.unwrap();
let capital = l
.add_account("3000", "Capital", AccountType::Equity, None, false)
.unwrap();
let money = money_accounts(&l, &[bank]);
let e = l.create_entry(NaiveDate::from_ymd_opt(2026, 5, 1).unwrap(), "x");
l.add_line(e, equip, Side::Debit, Money::new(d("10.00"), Currency::USD))
.unwrap();
l.add_line(
e,
capital,
Side::Credit,
Money::new(d("4.00"), Currency::USD),
)
.unwrap();
assert_eq!(
ledger_core::shares::share_target(l.get_entry(e).unwrap(), &money),
Ok(d("10.00"))
);
}
/// Oracle: shares::resolve INVARIANT 10: members named on an entry that
/// touches their capital share it by their capital lines, credits less
/// debits.
#[test]
fn derived_member_shares_net_their_capital_lines() {
use ledger_core::parties::money_accounts;
use ledger_core::{AccountType, Currency, Ledger, Money, Side};
let mut l = Ledger::new(Currency::USD);
let mut acct = |code: &str, t| l.add_account(code, code, t, None, false).unwrap();
let bank = acct("1000", AccountType::Asset);
let cap_a = acct("3000", AccountType::Equity);
let cap_b = acct("3001", AccountType::Equity);
let a = l.add_party("A", &[Role::Member]).unwrap();
let b = l.add_party("B", &[Role::Member]).unwrap();
let money = money_accounts(&l, &[bank]);
let member = |party, capital| ledger_core::PartyMember {
party,
share: d("0.5"),
capital,
distributions: None,
};
let members = [member(a, cap_a), member(b, cap_b)];
let e = l.create_entry(NaiveDate::from_ymd_opt(2026, 5, 1).unwrap(), "x");
for (acct, side, amt) in [
(bank, Side::Debit, "100.00"),
(cap_a, Side::Credit, "100.00"),
(cap_a, Side::Debit, "30.00"),
(cap_b, Side::Credit, "30.00"),
] {
l.add_line(e, acct, side, Money::new(d(amt), Currency::USD))
.unwrap();
}
let shares = [PartyShare::whole(a), PartyShare::whole(b)].map(|mut s| {
s.share = ledger_core::Share::Derived;
s
});
assert_eq!(
ledger_core::shares::resolve(l.get_entry(e).unwrap(), &shares, &money, &members),
Ok(vec![(a, d("-70.00")), (b, d("-30.00"))])
);
}
/// Oracle: parties::entry_flow SCENARIOS 1–6, worked by hand; what_for
/// always sums to net.
#[test]
@@ -1211,7 +1403,7 @@ fn entry_flow_scenarios() {
)
.unwrap();
}
let f = entry_flow(l.get_entry(e).unwrap(), &money);
let f = entry_flow(l.get_entry(e).unwrap(), &money).unwrap();
let sum: Decimal = f.what_for.iter().map(|(_, v)| *v).sum();
assert_eq!(sum, f.net, "what_for sums to net: {f:?}");
f
@@ -0,0 +1,412 @@
//! Figures derived from what replay accepts: computed exactly where exact
//! arithmetic and chrono's calendar reach, refused (TooLargeToCompute,
//! DateOutOfRange) where they don't, never a panic (rules.md B-28; P0
//! review round 4, 2026-10-17).
//!
//! ```text
//! GOAL: books an earlier version wrote (a draft line of Decimal's
//! largest, shares and bases past the line limit, a document's lines
//! or a payroll run as journaled, dates at chrono's last day) can be
//! read every way the engine reads books, and the server stays up.
//! SOURCE: DECISION (P0 review round 4: posted is forever; derived
//! computations refuse rather than panic).
//! ```
use chrono::{Datelike, NaiveDate};
use ledger_core::{
AccountType, Currency, DocumentLine, Ledger, LedgerError, Money, NewAsset, PartyShare,
PayrollLine, Side,
};
use rust_decimal::Decimal;
fn d(y: i32, m: u32, day: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(y, m, day).unwrap()
}
fn usd(a: Decimal) -> Money {
Money::new(a, Currency::USD)
}
fn too_large(r: Result<impl std::fmt::Debug, LedgerError>) -> bool {
matches!(r, Err(LedgerError::TooLargeToCompute(_)))
}
/// An asset whose life ends in chrono's last month (an earlier version
/// accepted any life whose end chrono holds): its schedule walks into
/// December 262142, prorates that month by its 31 days, and sums to its
/// cost exactly.
#[test]
fn depreciation_reaches_chronos_last_month() {
let mut l = Ledger::new(Currency::USD);
let mut add = |code: &str, ty| l.add_account(code, code, ty, None, false).unwrap();
let cost_account = add("1500", AccountType::Asset);
let accum = add("1510", AccountType::Asset);
let expense = add("6100", AccountType::Expense);
let y = NaiveDate::MAX.year();
let id = l
.replay_register_asset(NewAsset {
description: "edge".into(),
purchase_date: d(y, 1, 15),
cost: usd(Decimal::new(120000, 2)),
salvage_value: usd(Decimal::ZERO),
useful_life_months: 11,
cost_account,
accum_depr_account: accum,
expense_account: expense,
})
.unwrap();
let a = l.get_asset(id).unwrap();
let full = ledger_core::depreciation_schedule(a, NaiveDate::MAX);
assert_eq!(full.len(), 12);
assert_eq!(full[0].period, format!("{y}-01"));
assert_eq!(full[11].period, format!("{y}-12"));
assert_eq!(full[11].accumulated, Decimal::new(120000, 2));
assert_eq!(
full.iter().map(|l| l.amount).sum::<Decimal>(),
Decimal::new(120000, 2)
);
// Through November: eleven months, December not yet.
let nov = ledger_core::depreciation_schedule(a, d(y, 11, 30));
assert_eq!(nov.len(), 11);
assert!(nov.last().unwrap().accumulated < Decimal::new(120000, 2));
// December is walked without stepping past chrono's last day.
let dec = ledger_core::depreciation_schedule(a, d(y, 12, 10));
assert_eq!(dec.last().unwrap().period, format!("{y}-12"));
assert_eq!(
ledger_core::accumulated_depreciation(a, NaiveDate::MAX),
Decimal::new(120000, 2)
);
assert_eq!(ledger_core::book_value(a, NaiveDate::MAX), Decimal::ZERO);
}
/// An asset whose life runs past 9999 (or starts before year 1) trues up
/// in its final month like any other: its lifetime is exactly its cost.
#[test]
fn a_life_past_9999_trues_up_to_the_cent() {
let mut l = Ledger::new(Currency::USD);
let mut add = |code: &str, ty| l.add_account(code, code, ty, None, false).unwrap();
let cost_account = add("1500", AccountType::Asset);
let accum = add("1510", AccountType::Asset);
let expense = add("6100", AccountType::Expense);
// March 17th to April 17th: a 31-day first month and a 30-day last, so
// the partial months drift and the true-up is needed.
for (start, months) in [
(d(9999, 3, 17), 61),
(d(-10, 3, 17), 61),
(d(9998, 3, 17), 25),
] {
let id = l
.replay_register_asset(NewAsset {
description: "far".into(),
purchase_date: start,
cost: usd(Decimal::new(100_000, 2)),
salvage_value: usd(Decimal::new(1, 2)),
useful_life_months: months,
cost_account,
accum_depr_account: accum,
expense_account: expense,
})
.unwrap();
let a = l.get_asset(id).unwrap();
let s = ledger_core::depreciation_schedule(a, NaiveDate::MAX);
assert_eq!(
s.last().unwrap().accumulated,
Decimal::new(99_999, 2),
"{start} + {months}"
);
assert_eq!(
s.iter().map(|l| l.amount).sum::<Decimal>(),
Decimal::new(99_999, 2),
"{start} + {months}"
);
}
}
/// February has 29 days exactly in the years chrono calls leap, from its
/// first year to its last (year 0 and the negative years included), so a
/// schedule in any of them prorates February rightly.
#[test]
fn february_is_prorated_by_chronos_calendar_in_every_year() {
let mut l = Ledger::new(Currency::USD);
let mut add = |code: &str, ty| l.add_account(code, code, ty, None, false).unwrap();
let cost_account = add("1500", AccountType::Asset);
let accum = add("1510", AccountType::Asset);
let expense = add("6100", AccountType::Expense);
let min = NaiveDate::MIN.year();
let max = NaiveDate::MAX.year();
for year in [
min,
min + 1,
-400,
-100,
-4,
-1,
0,
1,
4,
100,
400,
1900,
2000,
2024,
2026,
max - 1,
max,
] {
let leap = NaiveDate::from_ymd_opt(year, 2, 29).is_some();
// Bought February 1st, two months of life, so February is a whole
// month of it.
let id = l
.replay_register_asset(NewAsset {
description: format!("{year}"),
purchase_date: d(year, 2, 1),
cost: usd(Decimal::from(2900)),
salvage_value: usd(Decimal::ZERO),
useful_life_months: 2,
cost_account,
accum_depr_account: accum,
expense_account: expense,
})
.unwrap();
let a = l.get_asset(id).unwrap();
// Through the 14th: 14 of February's days.
let half = ledger_core::depreciation_schedule(a, d(year, 2, 14));
let days = if leap { 29 } else { 28 };
let want = (Decimal::from(1450) * Decimal::from(14) / Decimal::from(days))
.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointAwayFromZero);
assert_eq!(half.last().unwrap().amount, want, "{year}");
}
}
/// A draft an earlier version journaled with lines of Decimal's largest:
/// its money flow and debits are refused, its shares don't resolve, its
/// post refuses it.
#[test]
fn a_draft_of_decimals_largest_is_refused_where_summed() {
let mut l = Ledger::new(Currency::USD);
let cash = l
.add_account("1000", "Cash", AccountType::Asset, None, false)
.unwrap();
let card = l
.add_account("2050", "Card", AccountType::Liability, None, false)
.unwrap();
let rent = l
.add_account("6000", "Rent", AccountType::Expense, None, false)
.unwrap();
let p = l
.add_party("Acme", &[ledger_core::Role::Contractor])
.unwrap();
let q = l
.add_party("Beta", &[ledger_core::Role::Contractor])
.unwrap();
let money = ledger_core::parties::money_accounts(&l, &[cash]);
for (dr, cr) in [(rent, cash), (rent, card), (card, cash), (cash, card)] {
let e = l.create_entry(d(2026, 3, 1), "huge");
for side in [Side::Debit, Side::Debit] {
l.replay_add_line(e, dr, side, usd(Decimal::MAX)).unwrap();
}
l.replay_add_line(e, cr, Side::Credit, usd(Decimal::MAX))
.unwrap();
l.replay_add_line(e, cr, Side::Credit, usd(Decimal::MAX))
.unwrap();
let entry = l.get_entry(e).unwrap();
assert!(too_large(ledger_core::parties::entry_flow(entry, &money)));
assert!(too_large(ledger_core::shares::share_target(entry, &money)));
let why =
ledger_core::shares::resolve(entry, &[PartyShare::whole(p)], &money, &[]).unwrap_err();
assert!(why.contains("too large to compute"), "{why}");
assert_eq!(l.post_entry(e).unwrap_err(), LedgerError::AmountOutOfRange);
}
// One line of Decimal's largest flows, and its share resolves whole.
let e = l.create_entry(d(2026, 3, 1), "one huge");
l.replay_add_line(e, rent, Side::Debit, usd(Decimal::MAX))
.unwrap();
l.replay_add_line(e, cash, Side::Credit, usd(Decimal::MAX))
.unwrap();
let entry = l.get_entry(e).unwrap();
assert_eq!(
ledger_core::parties::entry_flow(entry, &money).unwrap().net,
Decimal::MAX
);
assert_eq!(
ledger_core::shares::resolve(entry, &[PartyShare::whole(p)], &money, &[]).unwrap(),
[(p, Decimal::MAX)]
);
// A percent of it: the product is past exact arithmetic.
let halves = [p, q].map(|party| PartyShare {
party,
share: ledger_core::shares::Share::Percent(Decimal::from(50)),
});
let why = ledger_core::shares::resolve(entry, &halves, &money, &[]).unwrap_err();
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.
#[test]
fn documents_and_aging_are_exact_or_refused() {
let mut l = Ledger::new(Currency::USD);
let customer = l.add_customer("Client").unwrap();
let line = |a: Decimal| DocumentLine {
description: "x".into(),
amount: a,
};
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)
.unwrap();
let inv = l.get_invoice(1).unwrap();
assert_eq!(inv.total(), Ok(Decimal::TEN));
assert_eq!(inv.balance(), Ok(Decimal::TEN));
let rows = l.ar_aging(d(2026, 6, 1)).unwrap();
// 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.
let half = Decimal::MAX / Decimal::TWO;
for id in [2, 3] {
l.replay_invoice(
id,
customer,
d(2026, 3, 1),
d(2026, 3, 31),
vec![line(half)],
id,
)
.unwrap();
assert_eq!(l.get_invoice(id).unwrap().total(), Ok(half));
}
assert!(too_large(l.ar_aging(d(2026, 6, 1))));
// Paid more than its total, as journaled: a negative balance, exact.
l.replay_invoice_payment(1, Decimal::from(11), 9).unwrap();
assert_eq!(l.get_invoice(1).unwrap().balance(), Ok(-Decimal::ONE));
// A total of lines that overflow, and its balance.
l.replay_invoice(
4,
customer,
d(2026, 3, 1),
d(2026, 3, 31),
vec![line(Decimal::MAX), line(Decimal::MAX)],
4,
)
.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()));
// Bills alike.
let vendor = l.add_vendor("Supplier").unwrap();
l.replay_bill(
1,
vendor,
d(2026, 3, 1),
d(2026, 3, 31),
vec![line(Decimal::MAX), line(Decimal::ONE)],
6,
)
.unwrap();
assert!(too_large(l.get_bill(1).unwrap().total()));
assert!(too_large(l.ap_aging(d(2026, 6, 1))));
let row = ledger_core::AgingRow {
name: "x".into(),
current: Decimal::MAX,
days_30: Decimal::ONE,
days_60: Decimal::ZERO,
days_90: Decimal::ZERO,
days_90_plus: Decimal::ZERO,
};
assert!(too_large(row.total()));
for (i, one) in [
(0, Decimal::ONE),
(1, Decimal::TWO),
(2, Decimal::TEN),
(3, Decimal::ONE_HUNDRED),
(4, Decimal::ONE_THOUSAND),
] {
let mut r = ledger_core::AgingRow {
current: Decimal::ZERO,
..row.clone()
};
r.days_30 = Decimal::ZERO;
match i {
0 => r.current = one,
1 => r.days_30 = one,
2 => r.days_60 = one,
3 => r.days_90 = one,
_ => r.days_90_plus = one,
}
assert_eq!(r.total(), Ok(one), "bucket {i}");
}
}
/// A payroll run restored as journaled: net pay is exact, or refused past
/// exact arithmetic; a run's plan refuses totals it can't hold.
#[test]
fn payroll_figures_are_exact_or_refused() {
let line = |gross: Decimal, fed: Decimal| PayrollLine {
employee_name: "Dana".into(),
employee: None,
gross_pay: gross,
federal_withholding: fed,
state_withholding: Decimal::new(1, 2),
ss_employee: Decimal::new(2, 2),
medicare_employee: Decimal::new(3, 2),
ss_employer: Decimal::ZERO,
medicare_employer: Decimal::ZERO,
other_deductions: Decimal::new(4, 2),
};
assert_eq!(
line(Decimal::from(100), Decimal::new(1, 12)).net_pay(),
Ok("99.899999999999".parse().unwrap())
);
assert!(too_large(line(-Decimal::MAX, Decimal::ONE).net_pay()));
let accounts = ledger_core::payroll::PayrollAccounts {
salary_expense: 1,
payroll_tax_expense: 2,
federal_payable: 3,
state_payable: 4,
ss_payable: 5,
medicare_payable: 6,
other_payable: 7,
};
let big = line(Decimal::MAX, Decimal::ZERO);
assert!(too_large(ledger_core::payroll::payroll_entry_plan(
&[big.clone(), big],
accounts,
8,
Currency::USD
)));
let plan = ledger_core::payroll::payroll_entry_plan(
&[line(Decimal::from(100), Decimal::ONE)],
accounts,
8,
Currency::USD,
)
.unwrap();
let debits: Decimal = plan
.iter()
.filter(|(_, s, _)| *s == Side::Debit)
.map(|(_, _, m)| m.amount)
.sum();
let credits: Decimal = plan
.iter()
.filter(|(_, s, _)| *s == Side::Credit)
.map(|(_, _, m)| m.amount)
.sum();
assert_eq!(debits, Decimal::from(100));
assert_eq!(credits, Decimal::from(100));
}
+9 -9
View File
@@ -489,7 +489,7 @@ fn register_books() -> RegisterBooks {
#[test]
fn register_rows_carry_the_assets_tax_fields() {
let b = register_books();
let r = fixed_asset_register(&b.l, date(2026, 6, 30));
let r = fixed_asset_register(&b.l, date(2026, 6, 30)).unwrap();
assert_eq!(r.rows.len(), 5);
for row in &r.rows {
let a = b.l.get_asset(row.asset_id).unwrap();
@@ -535,12 +535,12 @@ fn register_rows_carry_the_assets_tax_fields() {
#[test]
fn register_tax_totals_cover_held_assets_only() {
let b = register_books();
let r = fixed_asset_register(&b.l, date(2026, 6, 30));
let r = fixed_asset_register(&b.l, date(2026, 6, 30)).unwrap();
// 3000.00 + 650.25 + 1200.00 (the disposed 360.00 left out).
assert_eq!(r.total_tax_basis, d("4850.25"));
assert_eq!(r.missing_tax_basis, 1);
// Before the disposal date the old monitor is still held.
let r = fixed_asset_register(&b.l, date(2026, 2, 28));
let r = fixed_asset_register(&b.l, date(2026, 2, 28)).unwrap();
assert_eq!(r.total_tax_basis, d("5210.25"));
assert_eq!(r.missing_tax_basis, 1);
}
@@ -552,11 +552,11 @@ fn a_disposed_asset_without_a_basis_is_not_missing() {
let x = register(&mut l, &a, "Laptop", "1000.00");
let y = register(&mut l, &a, "Desk", "400.00");
l.dispose_asset(y, date(2026, 3, 31), usd("0.00")).unwrap();
let r = fixed_asset_register(&l, date(2026, 6, 30));
let r = fixed_asset_register(&l, date(2026, 6, 30)).unwrap();
assert_eq!(r.missing_tax_basis, 1);
assert_eq!(r.total_tax_basis, Decimal::ZERO);
set(&mut l, x, TaxBasisRule::Carryover, Some("900.00"));
let r = fixed_asset_register(&l, date(2026, 6, 30));
let r = fixed_asset_register(&l, date(2026, 6, 30)).unwrap();
assert_eq!(r.missing_tax_basis, 0);
assert_eq!(r.total_tax_basis, d("900.00"));
}
@@ -565,7 +565,7 @@ fn a_disposed_asset_without_a_basis_is_not_missing() {
#[test]
fn an_empty_register_has_no_tax_basis() {
let (l, _) = fixture();
let r = fixed_asset_register(&l, date(2026, 6, 30));
let r = fixed_asset_register(&l, date(2026, 6, 30)).unwrap();
assert!(r.rows.is_empty());
assert_eq!(r.total_tax_basis, Decimal::ZERO);
assert_eq!(r.missing_tax_basis, 0);
@@ -576,14 +576,14 @@ fn an_empty_register_has_no_tax_basis() {
fn tax_basis_does_not_move_book_totals() {
let (mut l, a) = fixture();
let x = register(&mut l, &a, "Laptop", "1200.00");
let before = fixed_asset_register(&l, date(2026, 6, 30));
let before = fixed_asset_register(&l, date(2026, 6, 30)).unwrap();
set(
&mut l,
x,
TaxBasisRule::PersonalUseConversion,
Some("2000.00"),
);
let after = fixed_asset_register(&l, date(2026, 6, 30));
let after = fixed_asset_register(&l, date(2026, 6, 30)).unwrap();
assert_eq!(after.total_cost, before.total_cost);
assert_eq!(after.total_accumulated, before.total_accumulated);
assert_eq!(after.total_book_value, before.total_book_value);
@@ -656,7 +656,7 @@ proptest! {
}
}
}
let r = fixed_asset_register(&l, date(2026, 6, 30));
let r = fixed_asset_register(&l, date(2026, 6, 30)).unwrap();
prop_assert_eq!(r.total_tax_basis, expected_total);
prop_assert_eq!(r.missing_tax_basis, expected_missing);
}