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/FL-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:
1 parent
9f9f00ed9a
commit
8693d5a3f5
161 files changed
+18938
-1110
No files matched your search
@@ -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)
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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)> {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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))?;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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>(),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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, \
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)?
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user