merge: rule references cite bookspec ids (S-E; reviewed, fixes applied)
Every citation of the retired B-1..B-45 numbering in code, docs and tests now names the rule's bookspec id, the one stable name for it (D-68). docs/spec/rules.md is the index from the old numbers, and docs/spec/claims/ holds what wanderbooks claims for each rule. Thirteen citations in program output and one golden stay as they were: output is a contract and a golden changes only when recomputed by hand, so S-E2 moves them together. A test now holds it: no retired number anywhere outside the index and an exact-count list of the kept ones, and every SOURCE clause in the sources, tests and fuzz targets names a bookspec rule the pinned checker has, a product rule the claims hold, a file that exists, or a declared outside source (pinned in number, so the free-text set cannot grow unseen). The review found unrewritten citations, a mangled range or two, and a user-visible note changed by accident; all fixed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
ec10ef3b77
227 files changed
+2137
-1635
No files matched your search
@@ -93,16 +93,32 @@ property tests, mutation testing, and 11.5M fuzz executions:
|
||||
|
||||
So the bar, for every agent, every change:
|
||||
|
||||
0. **Specs come from authorities, not memory.** Every rule the engine
|
||||
enforces is in `docs/spec/rules.md` with its source: Pacioli for the
|
||||
mechanics of double entry, the IRS (vendored verbatim, public domain)
|
||||
for records, periods, 1099s, capitalization, partnerships, and payroll,
|
||||
FASB's Codification (cited, never copied) for GAAP. A rule no authority
|
||||
states is marked CONVENTION or CHOICE (bookspec's word for a
|
||||
decision), with who decided and when.
|
||||
0. **Specs come from authorities, not memory.** The rules live in
|
||||
bookspec, the definitive accounting specification (D-68):
|
||||
https://git.swaits.com/swaits/bookspec — its `rules/` records are
|
||||
the rule text, rendered for reading in its `spec/rules/` pages and
|
||||
indexed in its `spec/rules-index.md`. Every rule has a bookspec id
|
||||
`BS-<area>-<n>`, and that is the id code and docs cite. Wanderbooks'
|
||||
own layer is `docs/spec/claims/`: for each bookspec rule, the option
|
||||
wanderbooks picks (a CHOICE is picked, never silently decided), where
|
||||
the engine enforces it, which tests check it, and wanderbooks' own
|
||||
product rules `WB-<area>-<n>` (MCP tools, the store, the viewer, the
|
||||
vault), which no authority but this product states.
|
||||
`docs/spec/rules.md` is only the index from the retired B-n
|
||||
numbering to bookspec ids and claims files; do not cite it.
|
||||
Sources rest on authorities: Pacioli for the mechanics of double
|
||||
entry, the IRS (vendored verbatim, public domain, in
|
||||
`docs/spec/sources/`) for records, periods, 1099s, capitalization,
|
||||
partnerships, and payroll, FASB's Codification (cited, never copied)
|
||||
for GAAP. A rule no authority states is marked CONVENTION or CHOICE
|
||||
(bookspec's word for a decision), with who decided and when.
|
||||
Spec blocks in the code (```text GOAL/SOURCE/INVARIANTS/SCENARIOS)
|
||||
carry a `SOURCE:` line. Never write a spec from what the code happens
|
||||
to do, or from what you remember; find the document, or ask.
|
||||
carry a `SOURCE:` line citing a `BS-…` id (a `WB-…` id for a product
|
||||
rule), a vendored source, or the external authority itself.
|
||||
`crates/ledger-core/tests/bookspec/` checks that every `SOURCE:`
|
||||
line names a rule or source that exists. Never write a spec from
|
||||
what the code happens to do, or from what you remember; find the
|
||||
document, or ask.
|
||||
|
||||
1. **Money arithmetic goes in `kernel/`, generic over `Amount`.** If
|
||||
you write a sum, a sign flip, a split, or a rounding plug anywhere
|
||||
@@ -201,7 +217,9 @@ clone, with status. Rules:
|
||||
| `docs/requirements.md` | What the engine must do (R-1…), what is future work |
|
||||
| `docs/architecture.md` | Crate layout, command pattern, dependency rules |
|
||||
| `docs/oracle.md` | How we check correctness: golden files, property tests, fuzzing, cross-checks against other implementations (and who is right) |
|
||||
| `docs/spec/` | The authorities every rule comes from (`rules.md`), with public-domain sources vendored verbatim |
|
||||
| `docs/spec/` | Wanderbooks' layer over bookspec: `claims/` (its picks, enforcement, product rules `WB-…`), `rules.md` (the B-n → bookspec-id index only), `sources/` (public-domain authorities vendored verbatim) |
|
||||
| `docs/spec/claims/` | Wanderbooks' claims on each bookspec rule: the CHOICE picked, where the engine enforces it, which tests check it, and product rules `WB-<area>-<n>` |
|
||||
| https://git.swaits.com/swaits/bookspec | Where the rules live (D-68): `rules/` records, `spec/rules/` reading pages, `spec/rules-index.md`; every rule is `BS-<area>-<n>` |
|
||||
| `docs/verification.md` | The formal proofs: every accounting law, its Kani harness and Lean theorem, what they found |
|
||||
| `docs/parity.md` | Feature catalog and the non-regression floor |
|
||||
| `docs/capability-parity.md` | Parity vs the GSheet+GDrive system + the cutover rule |
|
||||
@@ -209,7 +227,7 @@ clone, with status. Rules:
|
||||
| `docs/receipt-store.md` | Blob store + `ledger-store` SQLite persistence spec |
|
||||
| `docs/testing.md` | Every test layer, each unit's test record, and what P12 must mutate |
|
||||
| `docs/parties-and-attachments.md` | The party directory, roles, the TIN vault, attachments to any subject |
|
||||
| https://git.swaits.com/swaits/bookspec | The formal accounting specification's own repository: README, examples, checker, runner (P13); pinned in `crates/ledger-core/Cargo.toml` |
|
||||
| https://git.swaits.com/swaits/bookspec | Also its README, examples, checker, runner (P13); pinned in `crates/ledger-core/Cargo.toml` |
|
||||
| `deploy/README.md` | Running the books on a machine of your own (P9a) |
|
||||
| `docs/glossary.md` | Debit/credit and friends, for agents new to accounting |
|
||||
| `plan/STATUS.md` | Where the project stands right now |
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
//! Audits and attestations over the wire (plan P8; rules.md B-45, D-9):
|
||||
//! Audits and attestations over the wire (plan P8; BS-ledger-13, D-9):
|
||||
//! a deterministic run and workpaper, claims weighed against the bar when
|
||||
//! asked, the CPA package that waits for a counted audit, and books that
|
||||
//! have not declared `audits`.
|
||||
//!
|
||||
//! Expected behavior comes from `docs/mcp-interface.md` ("Tools — audit
|
||||
//! and attestations") and rules.md B-45. Every call goes through a real
|
||||
//! and attestations") and BS-ledger-13. Every call goes through a real
|
||||
//! books server as an agent reaches it (`common.rs`).
|
||||
|
||||
mod common;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! (common.rs): the preview that writes nothing, the confirm that posts,
|
||||
//! numbers, terms, line accounts, party snapshots and the issued copy filed
|
||||
//! with the invoice (plan/served.md 8.2 P4b S4 item 17; docs/mcp-interface.md
|
||||
//! "Tools — A/R and A/P"; rules.md B-39, B-40; D-55).
|
||||
//! "Tools — A/R and A/P"; BS-arap-3, BS-arap-4; D-55).
|
||||
//!
|
||||
//! Every refusal is checked to leave the journal byte for byte as it was.
|
||||
|
||||
@@ -218,7 +218,7 @@ fn an_invoice_from_issue_to_paid() {
|
||||
}
|
||||
|
||||
/// A bill keeps the vendor's invoice, names its own accounts, and carries
|
||||
/// its terms' discount dates (A-10, A-13; B-39).
|
||||
/// its terms' discount dates (A-10, A-13; BS-arap-3).
|
||||
#[test]
|
||||
fn a_bill_with_its_vendor_invoice_and_terms() {
|
||||
let books = Books::new("documents-bill");
|
||||
@@ -304,7 +304,7 @@ fn a_bill_with_its_vendor_invoice_and_terms() {
|
||||
}
|
||||
|
||||
/// One vendor's invoice number, entered twice: refused unless a reason is
|
||||
/// given, which is journaled with the second bill (B-40).
|
||||
/// given, which is journaled with the second bill (BS-arap-4).
|
||||
#[test]
|
||||
fn duplicate_vendor_invoice_refused() {
|
||||
let books = Books::new("documents-duplicate");
|
||||
@@ -347,7 +347,7 @@ fn duplicate_vendor_invoice_refused() {
|
||||
/// A line's account obeys the document's kind: revenue or a role-free
|
||||
/// liability on an invoice, an expense or a non-cash role-free asset on a
|
||||
/// bill; a role account, cash, a placeholder or none at all is refused
|
||||
/// (A-10, A-11; rules.md B-39).
|
||||
/// (A-10, A-11; BS-arap-3).
|
||||
#[test]
|
||||
fn a_line_account_must_be_allowed() {
|
||||
let books = Books::new("documents-accounts");
|
||||
@@ -927,7 +927,7 @@ mod paying_on_terms {
|
||||
|
||||
/// One deposit settles two invoices of one customer: one entry, one
|
||||
/// receivable line per invoice, each tagged with its own invoice, and the
|
||||
/// output names both documents (B-42 INVARIANTS 1 and 3).
|
||||
/// output names both documents (BS-arap-6 INVARIANTS 1 and 3).
|
||||
#[test]
|
||||
fn one_payment_settles_two_invoices() {
|
||||
let mut s = setup("settle-two");
|
||||
@@ -984,7 +984,7 @@ mod paying_on_terms {
|
||||
}
|
||||
|
||||
/// A discount outside the document's terms needs a reason; with one the
|
||||
/// payment is taken and recorded (B-42 INVARIANT 2; the terms are S4.3's
|
||||
/// payment is taken and recorded (BS-arap-6 INVARIANT 2; the terms are S4.3's
|
||||
/// to journal, so this bill states none).
|
||||
#[test]
|
||||
fn late_discount_needs_a_reason() {
|
||||
@@ -1013,7 +1013,7 @@ mod paying_on_terms {
|
||||
}
|
||||
|
||||
/// A fee posts gross (A-4): the deposit gets the net, the fee its expense,
|
||||
/// and A/R is credited the gross (B-42 INVARIANT 1).
|
||||
/// and A/R is credited the gross (BS-arap-6 INVARIANT 1).
|
||||
#[test]
|
||||
fn a_fee_posts_gross_to_receivables_and_net_to_the_bank() {
|
||||
let mut s = setup("fee-gross");
|
||||
@@ -1075,7 +1075,7 @@ mod paying_on_terms {
|
||||
}
|
||||
|
||||
/// Two bills paid in one entry count once toward 1099s and the party's
|
||||
/// totals (B-42; 8.3.16's multi-document risk).
|
||||
/// totals (BS-arap-6; 8.3.16's multi-document risk).
|
||||
#[test]
|
||||
fn multi_document_payment_counts_once_for_1099_and_party_totals() {
|
||||
let mut s = setup("multi-1099");
|
||||
@@ -1131,7 +1131,7 @@ mod paying_on_terms {
|
||||
|
||||
/// The bills-due list orders by due date and gives the running total
|
||||
/// through each date; the agings' detail rows and their tie-out agree with
|
||||
/// the control check (8.3.10; B-42).
|
||||
/// the control check (8.3.10; BS-arap-6).
|
||||
#[test]
|
||||
fn bills_due_orders_by_due_and_discount() {
|
||||
let mut s = setup("bills-due");
|
||||
@@ -1383,7 +1383,7 @@ mod bad_debts {
|
||||
assert_eq!(check["agrees"], json!(true), "{check}");
|
||||
}
|
||||
|
||||
/// P4b S7: no evidence, no write-off (B-41 INVARIANT 1): the tool refuses
|
||||
/// P4b S7: no evidence, no write-off (BS-arap-5 INVARIANT 1): the tool refuses
|
||||
/// with neither or both, and an attachment already filed is linked
|
||||
/// instead of a new file.
|
||||
#[test]
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! Drafts, the evidence gate and the preview digest over the wire (plan
|
||||
//! P4; rules.md B-43, D-47, D-50): a draft waits for its receipt and
|
||||
//! P4; BS-entry-5, D-47, D-50): a draft waits for its receipt and
|
||||
//! posts when it arrives, a discard unblocks a close, a report and the CPA
|
||||
//! package say when drafts are open, a reversal needs no receipt of its
|
||||
//! own, and every tool with `confirmed` takes the `preview` it returned
|
||||
//! and refuses a stale one.
|
||||
//!
|
||||
//! Expected behavior comes from `docs/mcp-interface.md` ("Tools — drafts",
|
||||
//! "The preview digest") and rules.md B-43. Every call goes through a real
|
||||
//! "The preview digest") and BS-entry-5. Every call goes through a real
|
||||
//! books server as an agent reaches it (`common.rs`).
|
||||
|
||||
mod common;
|
||||
@@ -129,7 +129,7 @@ fn a_draft_waits_for_its_receipt_and_posts() {
|
||||
assert!(listed["drafts"].as_array().unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// B-43: the structured `receipt_required` error is the one the MCP built
|
||||
/// BS-entry-5: the structured `receipt_required` error is the one the MCP built
|
||||
/// before the gate moved into the store.
|
||||
#[test]
|
||||
fn the_gate_moved_and_the_mcp_error_is_unchanged() {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! backfill command.
|
||||
//!
|
||||
//! Expected behavior comes from `docs/mcp-interface.md` ("Tools —
|
||||
//! evidence", "Tools — receipts & documents") and rules.md B-44. Every
|
||||
//! evidence", "Tools — receipts & documents") and BS-ledger-12. Every
|
||||
//! call goes through a real books server as an agent reaches it
|
||||
//! (`common.rs`).
|
||||
|
||||
@@ -318,7 +318,7 @@ fn annotations_and_searches() {
|
||||
assert_eq!(answer_of(&r).unwrap()["status"], "ok");
|
||||
}
|
||||
|
||||
/// Plan P6 step 4 and rules.md B-44 item 5: consolidation never leaves an
|
||||
/// Plan P6 step 4 and BS-ledger-12 item 5: consolidation never leaves an
|
||||
/// entry the receipt policy covers with no evidence.
|
||||
#[test]
|
||||
fn consolidation_never_removes_an_entrys_only_evidence() {
|
||||
|
||||
@@ -844,8 +844,8 @@ fn books_p2_served_cut_over_whole() {
|
||||
"confirmed": true}),
|
||||
),
|
||||
// An invoice carrying documents_v2's fields (terms: P4b S4.4) and
|
||||
// its line naming its project (document_line_projects, rules.md
|
||||
// B-37 item 8).
|
||||
// its line naming its project (document_line_projects,
|
||||
// BS-statement-5 item 8).
|
||||
(
|
||||
"books.create_invoice",
|
||||
json!({"customer": "1", "date": "2026-02-10", "terms": "Net 30",
|
||||
|
||||
@@ -109,12 +109,12 @@ impl Mcp {
|
||||
/// Start (or restart) the server on books an earlier version wrote,
|
||||
/// with the fixture company's settings set as an agent sets them, one
|
||||
/// at a time. Books in a journal format before 2 keep no settings
|
||||
/// until the owner's format upgrade (rules.md B-27, D-39): each change
|
||||
/// until the owner's format upgrade (BS-format-1, D-39): each change
|
||||
/// is refused as `format_upgrade_pending`, and those books are served
|
||||
/// on the defaults (no members, no 1065, no cash accounts), as they
|
||||
/// would be in a data root. Books with periods closed under the
|
||||
/// calendar year keep it (a changed tax year needs the IRS's consent,
|
||||
/// rules.md B-29), whatever their format. Any other answer fails the
|
||||
/// BS-ledger-9), whatever their format. Any other answer fails the
|
||||
/// test when the books are first served (`first`); on a restart,
|
||||
/// after hostile calls that may have changed a setting and closed
|
||||
/// periods under it, the books may refuse a change for what they now
|
||||
@@ -898,7 +898,7 @@ fn hostile_tool_arguments_never_stop_the_server() {
|
||||
|
||||
/// INVARIANT 4: whatever the calls journaled, the books open again. A
|
||||
/// hostile call a command accepts but replay refuses would leave books
|
||||
/// that never reopen (rules.md B-28): the server is restarted on them and
|
||||
/// that never reopen (BS-entry-4): the server is restarted on them and
|
||||
/// must answer books.chart and books.verify.
|
||||
fn reopens(m: Mcp, p: &Places, after: &str) {
|
||||
drop(m);
|
||||
@@ -1449,7 +1449,7 @@ fn reads_of_old_books() -> Vec<(&'static str, Value)> {
|
||||
}
|
||||
|
||||
/// Books an earlier version wrote open, and every tool answers over them
|
||||
/// (rules.md B-28: posted is forever; a figure the books can't compute is
|
||||
/// (BS-entry-4: posted is forever; a figure the books can't compute is
|
||||
/// refused, never a panic). Against each fixture: the reads above, then
|
||||
/// OLD_BOOKS_CASES (default 3) generated calls of every tool; after them
|
||||
/// the server restarts and must open the books again (a call a command
|
||||
|
||||
@@ -1081,7 +1081,7 @@ fn mcp_import_export() {
|
||||
|
||||
// The IIF is plain ASCII text with CR LF line endings, handed over
|
||||
// (D-46); what it writes differently from the books is in warnings
|
||||
// (rules.md B-34).
|
||||
// (BS-format-2).
|
||||
let iif = mcp.call(
|
||||
"books.export",
|
||||
json!({"format": "iif", "report": "journal"}),
|
||||
@@ -1344,7 +1344,7 @@ fn mcp_period_statements() {
|
||||
assert_eq!(feb["net_income"], "-0.50");
|
||||
assert_eq!(feb["expense_accounts"][0]["code"], "6000");
|
||||
assert_eq!(feb["expense_accounts"][0]["amount"], "3.00");
|
||||
// No start (rules.md B-30): the fiscal year that holds the end, to
|
||||
// No start (BS-period-3): the fiscal year that holds the end, to
|
||||
// it. The fiscal year starts 02-01, so January's 4.00 of sales is
|
||||
// last year's, and February's 2.50 is this one's.
|
||||
let ytd = mcp.call("books.profit_and_loss", json!({"end": "2026-02-28"}));
|
||||
@@ -1616,7 +1616,7 @@ fn mcp_partnership_from_template() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Contract (rules.md B-13, D-10; docs/mcp-interface.md close_period and
|
||||
/// Contract (BS-partner-1, D-10; docs/mcp-interface.md close_period and
|
||||
/// list_periods): a close to the members shows each member's running
|
||||
/// split, the same in the preview as once confirmed, and the periods say
|
||||
/// which rule they closed under. Two members at 50% each, hand-computed:
|
||||
@@ -1748,7 +1748,7 @@ fn close_period_shows_each_members_running_split() {
|
||||
assert_eq!(me["members"][1]["ending"], "0.01");
|
||||
}
|
||||
|
||||
/// Contract (rules.md B-13, D-10; docs/mcp-interface.md list_periods and
|
||||
/// Contract (BS-partner-1, D-10; docs/mcp-interface.md list_periods and
|
||||
/// close_period) on books an earlier version wrote: ledger-store's
|
||||
/// old-books fixture x_member_closes (two members at 50%, A with a
|
||||
/// distributions account; three closes untagged, three
|
||||
@@ -2214,7 +2214,7 @@ fn mcp_vendor_1099() {
|
||||
let r = mcp.call("books.vendor_1099", json!({"year": 2026}));
|
||||
assert_eq!(r["vendors"][0]["paid"], "0.00");
|
||||
// A year whose threshold isn't known yet: refused, with what to do
|
||||
// (rules.md B-19). An explicit threshold works.
|
||||
// (BS-1099-1). An explicit threshold works.
|
||||
let why = mcp.call_err("books.vendor_1099", json!({"year": 2027}));
|
||||
for needle in [
|
||||
"only through 2026",
|
||||
@@ -2311,7 +2311,7 @@ fn mcp_receipts_always_required_when_threshold_is_zero() {
|
||||
}
|
||||
|
||||
/// `books.cash_flow` with no accounts passed reads the roles from
|
||||
/// `[books]` in wanderbooks.toml (rules.md B-14): the expense the owners
|
||||
/// `[books]` in wanderbooks.toml (BS-statement-3): the expense the owners
|
||||
/// paid through 2100 is borrowed from them and spent on its date, each
|
||||
/// line with `on_behalf` (D-42, rule 11); repaying the advance is
|
||||
/// financing; a loan to a member is investing; the statement is the direct
|
||||
@@ -2419,7 +2419,7 @@ fn cash_flow_reads_its_account_roles_from_the_books_settings() {
|
||||
}
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 2: roles that contradict the chart are refused,
|
||||
/// BS-statement-3 rule 2: roles that contradict the chart are refused,
|
||||
/// naming the setting and the fix, never a statement on a wrong partition.
|
||||
#[test]
|
||||
fn cash_flow_refuses_contradictory_roles() {
|
||||
@@ -2727,7 +2727,7 @@ fn post_pair(mcp: &mut Mcp, date: &str, dr: &str, cr: &str, amount: &str) -> u64
|
||||
id
|
||||
}
|
||||
|
||||
/// Defect 16 (rules.md B-30): one default period everywhere. On books with
|
||||
/// Defect 16 (BS-period-3): one default period everywhere. On books with
|
||||
/// a July fiscal year and a first entry in the fiscal year before, every
|
||||
/// period report given only an end covers the fiscal year that holds it
|
||||
/// (2025-07-01 through 2026-03-31, never the first entry's day, never
|
||||
@@ -2858,8 +2858,8 @@ fn iif_docnums(iif: &str) -> Vec<u64> {
|
||||
ids
|
||||
}
|
||||
|
||||
/// The default period (rules.md B-30) against the IIF (B-34, D-36) and
|
||||
/// the CPA package (B-33): a general journal asked for without dates is
|
||||
/// The default period (BS-period-3) against the IIF (BS-format-2, D-36) and
|
||||
/// the CPA package (BS-statement-4): a general journal asked for without dates is
|
||||
/// the fiscal year to date, but the IIF is never a period. Without dates
|
||||
/// it holds every posted entry from the first through today, under
|
||||
/// either name of the report, and a start or end is refused; the
|
||||
@@ -2956,7 +2956,7 @@ fn the_default_period_never_shortens_the_iif_or_the_package() {
|
||||
assert_eq!(iif_docnums(&read("general-journal.iif")), every[..3]);
|
||||
}
|
||||
|
||||
/// Defect 15 (rules.md B-31) over the real binary: books.rename_account
|
||||
/// Defect 15 (BS-ledger-10) over the real binary: books.rename_account
|
||||
/// gives an account a new name and nothing else. The chart shows it; a
|
||||
/// past period's P&L export prints it; the general journal's IIF declares
|
||||
/// the account by it; the books verify, the journal grew by the rename
|
||||
@@ -3082,7 +3082,7 @@ fn rename_account_end_to_end_defect_15() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Review R10 (rules.md B-31): on books that name no cash accounts
|
||||
/// Review R10 (BS-ledger-10): on books that name no cash accounts
|
||||
/// (books.cash_accounts unset, so they are picked by name), a rename that
|
||||
/// moves an account into or out of the cash or card accounts says so; one
|
||||
/// that moves nothing says nothing of them. A convention naming the old
|
||||
|
||||
@@ -737,7 +737,7 @@ fn pnl_and_balance_sheet_exports_equal_the_core_statements() {
|
||||
}
|
||||
|
||||
/// Cash flow CSV and JSON equal `ledger_core::cash_flow` for the same
|
||||
/// account roles and members, field for field (rules.md B-14; the JSON is
|
||||
/// account roles and members, field for field (BS-statement-3; the JSON is
|
||||
/// the tool's own answer). Kills: export_cash_flow stubs and its json/csv
|
||||
/// switch, and any field the mapping drops.
|
||||
#[test]
|
||||
@@ -1070,7 +1070,7 @@ fn journal_exports_hold_every_posted_line() {
|
||||
let mut m = Mcp::start(&dir, "1000000.00");
|
||||
|
||||
for report in ["journal", "general_journal"] {
|
||||
// Every date: the journal covers a period (rules.md B-30).
|
||||
// Every date: the journal covers a period (BS-period-3).
|
||||
let csv = m.export_text(
|
||||
json!({"format": "csv", "report": report, "start": "0001-01-01", "end": "9999-12-31"}),
|
||||
);
|
||||
@@ -1419,7 +1419,7 @@ fn xlsx_and_pdf_exports_are_real_files_with_the_books_in_them() {
|
||||
/// (cash accounts BANK, 1200 AR, 2000 AP, a registered asset's accounts
|
||||
/// FIXASSET, the rest by type), then one balanced TRNS/SPL/ENDTRNS block
|
||||
/// per posted entry dated on or before as_of, numbered (DOCNUM) with its
|
||||
/// entry id (rules.md B-33, B-34); plain ASCII text with CR LF, what it
|
||||
/// entry id (BS-statement-4, BS-format-2); plain ASCII text with CR LF, what it
|
||||
/// writes differently (a line break and double quotes, the engine's own em
|
||||
/// dashes) in warnings, grouped. Kills: export_iif's AR and AP comparisons.
|
||||
#[test]
|
||||
@@ -2505,7 +2505,7 @@ fn show_refuses_a_derived_inverted_range_defect_15() {
|
||||
}
|
||||
|
||||
/// Defect 16, repro 1.1.4: books.show sends the dates it names, resolved
|
||||
/// by the one default (rules.md B-30): only an end covers that end's
|
||||
/// by the one default (BS-period-3): only an end covers that end's
|
||||
/// fiscal year to it (2025-01-01 to 2025-06-30, never today's year's
|
||||
/// start); no dates cover today's fiscal year to date (checked against
|
||||
/// the clock read before and after, R14); a report as of a day says "as
|
||||
@@ -3631,7 +3631,7 @@ fn cpa_package_holds_the_year_and_its_evidence() {
|
||||
"tin_last4",
|
||||
],
|
||||
);
|
||||
// Through as_of (rules.md B-33), out of the package's cash account
|
||||
// Through as_of (BS-statement-4), out of the package's cash account
|
||||
// and the settings' financing account (one list each per package).
|
||||
let want = core_1099_through(&ledger, 2025, None, Some(d(END)));
|
||||
assert_eq!(w.len(), want.vendors.len());
|
||||
|
||||
@@ -60,7 +60,7 @@ struct Expected {
|
||||
}
|
||||
|
||||
/// Every figure the tools report on the seam review's books is the
|
||||
/// engine's for the same accounts and dates, on every date (B-33's "the
|
||||
/// engine's for the same accounts and dates, on every date (BS-statement-4's "the
|
||||
/// tool's for the same accounts and through"), and party totals for the
|
||||
/// year are the engine's on both bases.
|
||||
#[test]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! A project's snapshot (rules.md B-37 item 7) in the viewer and from the
|
||||
//! A project's snapshot (BS-statement-5 item 7) in the viewer and from the
|
||||
//! books server, on the same books: `books.project`'s strings are the
|
||||
//! figures the viewer's page draws (its `PageFigures` and `Snap`), to the
|
||||
//! cent, to date, by account, by month with the running net, and for the
|
||||
@@ -208,7 +208,7 @@ fn a_projects_snapshot_is_the_same_in_the_viewer_and_from_the_server() {
|
||||
assert_eq!(period["net"], "-722.22", "a refund and costs, no sale");
|
||||
}
|
||||
|
||||
/// rules.md B-37 item 8: a project's invoiced revenue and billed costs,
|
||||
/// BS-statement-5 item 8: a project's invoiced revenue and billed costs,
|
||||
/// made through the books server's own tools, read the same in the viewer
|
||||
/// (its snapshot, and the invoice's and bill's pages: each line's
|
||||
/// project) and from the server (books.project, books.get_entry).
|
||||
|
||||
@@ -285,7 +285,7 @@ fn books(name: &str) -> Mcp {
|
||||
|
||||
/// [`books`], as P2 left them when `p2`: journal format 2 with none of
|
||||
/// P3's features, books an older version wrote, waiting for their format
|
||||
/// upgrade (rules.md B-27).
|
||||
/// upgrade (BS-format-1).
|
||||
fn books_in(name: &str, p2: bool) -> Mcp {
|
||||
let dir = test_dir(name);
|
||||
if p2 {
|
||||
@@ -610,7 +610,7 @@ fn a_members_method_off_the_financing_accounts_warns() {
|
||||
assert!(out["warnings"].as_array().unwrap().is_empty(), "{out}");
|
||||
}
|
||||
|
||||
/// B-27 and the format-upgrade gate (D-39): books.set_w9 journals the W-9
|
||||
/// BS-format-1 and the format-upgrade gate (D-39): books.set_w9 journals the W-9
|
||||
/// and then the vendor's W-9 flag, a line of the vendor_1099_decisions
|
||||
/// feature, so it asks for the feature before the command's first line,
|
||||
/// never between its lines. In books waiting for their format upgrade
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! Expected behavior comes only from the tool descriptions and parameter /
|
||||
//! result doc comments in `src/server.rs` and `src/types.rs` (the declared
|
||||
//! interface, as `tools/list` serves it), `docs/mcp-interface.md` ("Tools —
|
||||
//! fixed assets"), and `docs/spec/rules.md` B-24. The harness is the
|
||||
//! fixed assets"), and BS-asset-3. The harness is the
|
||||
//! minimal subset of `tests/spec_mcp.rs`: every success validates against
|
||||
//! the tool's `outputSchema`, and every refusal leaves `journal.jsonl`
|
||||
//! byte-identical (server invariant 2: a refused call changes nothing).
|
||||
@@ -441,7 +441,7 @@ fn register_with_a_bad_tag_or_serial_registers_nothing() {
|
||||
assert_eq!(t, "FL-0002");
|
||||
}
|
||||
|
||||
/// A generated tag is never one any asset held (B-24).
|
||||
/// A generated tag is never one any asset held (BS-asset-3).
|
||||
#[test]
|
||||
fn register_never_generates_a_released_tag() {
|
||||
let mut m = books("released");
|
||||
@@ -624,7 +624,7 @@ fn dispose_asset_takes_the_tag_and_the_tag_stays_reserved() {
|
||||
confirm["receipt_attachment_ids"] = json!([doc]);
|
||||
m.ok("books.dispose_asset", confirm);
|
||||
assert_eq!(m.asset(a)["status"], "disposed");
|
||||
// B-24: a disposed asset's tag is never reused.
|
||||
// BS-asset-3: a disposed asset's tag is never reused.
|
||||
m.refuse(
|
||||
"books.label_asset",
|
||||
json!({"asset": b.to_string(), "tag": t}),
|
||||
@@ -815,7 +815,7 @@ fn export_fixed_asset_register_as_of_leaves_out_later_assets() {
|
||||
assert!(!text.contains("LATE-1"), "{text}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------- tax basis (rules.md B-25)
|
||||
// ------------------------------------------------- tax basis (BS-asset-4)
|
||||
//
|
||||
// From the `books.set_asset_tax_basis` and `books.register_asset`
|
||||
// descriptions, `SetAssetTaxBasisParams` / `AssetBasisOut` /
|
||||
@@ -1116,7 +1116,7 @@ fn register_asset_refuses_a_bad_basis_and_registers_nothing() {
|
||||
assert_eq!(m.assets().len(), 1, "nothing registered");
|
||||
}
|
||||
|
||||
// ------------------------------------------- the dates (rules.md B-15)
|
||||
// ------------------------------------------- the dates (BS-asset-1)
|
||||
|
||||
/// purchase_date is an alias for in_service_date for one release, noted.
|
||||
#[test]
|
||||
@@ -1199,7 +1199,7 @@ fn acquired_date_comes_from_the_acquisition_entry() {
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------- posted and scheduled (rules.md B-15 rule 8)
|
||||
// ------------------------------- posted and scheduled (BS-asset-1 rule 8)
|
||||
|
||||
/// Named regression 1 (the brief's reproduction 1, its figures made up): a
|
||||
/// $1,440.00 laptop, 36 months, in service 2026-05-15, nothing run. As of
|
||||
@@ -1501,7 +1501,7 @@ fn dispose_args(x: u64, date: &str, proceeds: &str) -> Value {
|
||||
/// days, 500.00 (the final depreciation); accumulated 5,500.00, book value
|
||||
/// 6,500.00, gain 500.00. Afterwards books.asset_schedule ends there, and
|
||||
/// books.list_assets lists it as gone: not held, every figure 0.00 (it
|
||||
/// left the books with its disposal; rules.md B-15 rule 8). Before P3 the
|
||||
/// left the books with its disposal; BS-asset-1 rule 8). Before P3 the
|
||||
/// schedule showed June 7,000.00, accumulated 12,000.00, book value 0.00.
|
||||
#[test]
|
||||
fn a_disposed_asset_lists_what_it_depreciated_through_its_disposal() {
|
||||
|
||||
@@ -1490,7 +1490,7 @@ enum Op {
|
||||
party: Pick,
|
||||
amount: String,
|
||||
/// The vendor's own invoice number: two bills by one vendor with
|
||||
/// the same number are refused (B-40).
|
||||
/// the same number are refused (BS-arap-4).
|
||||
vendor_ref: String,
|
||||
},
|
||||
PayBill {
|
||||
@@ -2703,7 +2703,7 @@ fn db_digest(path: &Path) -> String {
|
||||
ledger_store::journal::sha256_hex(dump.as_bytes())
|
||||
}
|
||||
|
||||
/// P4b S1 over the real server (rules.md B-38, D-45): a payment carries
|
||||
/// P4b S1 over the real server (BS-arap-2, D-45): a payment carries
|
||||
/// its method and reference and answers with the invoice's derived
|
||||
/// figures; an invoice with a payment standing can't be voided (the
|
||||
/// refusal names the payment); one entered twice is voided and shows as
|
||||
|
||||
@@ -963,7 +963,7 @@ fn party_totals_for_a_customer_a_member_and_a_prepaid() {
|
||||
|
||||
// A prepaid bought with a member's card: an asset, paid through what
|
||||
// the members advanced. That is money when it is a financing account
|
||||
// (rules.md B-35 item 5, P3 defect 24); unlisted, Due to Members is a
|
||||
// (BS-partner-3 item 5, P3 defect 24); unlisted, Due to Members is a
|
||||
// promise like any other liability, counted when the member is paid
|
||||
// back.
|
||||
let prepaid = |m: &mut Mcp| {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//!
|
||||
//! Expected behavior comes only from the tool descriptions and parameter /
|
||||
//! result doc comments in `src/server.rs` and `src/types.rs` (as
|
||||
//! `tools/list` serves them) and rules.md B-35. The harness is the minimal
|
||||
//! `tools/list` serves them) and BS-partner-3. The harness is the minimal
|
||||
//! subset of `tests/spec_mcp.rs` (copied from `tests/spec_parties.rs`):
|
||||
//! every success validates against the tool's `outputSchema`, and every
|
||||
//! refusal leaves `journal.jsonl` byte-identical.
|
||||
@@ -291,7 +291,7 @@ fn books(name: &str) -> Mcp {
|
||||
|
||||
/// [`books`], as P2 left them when `p2`: journal format 2 with none of
|
||||
/// P3's features, books an older version wrote, waiting for their format
|
||||
/// upgrade (rules.md B-27).
|
||||
/// upgrade (BS-format-1).
|
||||
fn books_in(name: &str, p2: bool) -> Mcp {
|
||||
let dir = test_dir(name);
|
||||
if p2 {
|
||||
@@ -380,7 +380,7 @@ fn reverse(m: &mut Mcp, entry: u64, date: &str) -> u64 {
|
||||
.unwrap_or_else(|| panic!("a reversal of {entry}"))
|
||||
}
|
||||
|
||||
/// Defect 14 over the MCP (rules.md B-35): `resolved` is signed as a line
|
||||
/// Defect 14 over the MCP (BS-partner-3): `resolved` is signed as a line
|
||||
/// on the party's own account, with its direction and its money and
|
||||
/// property; a reversal is the exact opposite; party totals take a basis,
|
||||
/// cash by default and echoed, all adding property in kind, so that a
|
||||
@@ -603,7 +603,7 @@ fn defect24_creditor_of_round_trips_and_a_card_fee_is_not_a_payment() {
|
||||
assert_eq!(m.ok("books.verify", json!({}))["status"], "ok");
|
||||
}
|
||||
|
||||
/// rules.md B-27: `books.update_party` asks for the `party_creditors`
|
||||
/// BS-format-1: `books.update_party` asks for the `party_creditors`
|
||||
/// feature before the first line it writes, never between them. In books
|
||||
/// waiting for their format upgrade (P2's), a name change with the first
|
||||
/// creditor is refused whole, journaling nothing (never the notes changed
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Spec-blind tests for the project tools of the books server (rules.md
|
||||
//! B-37), driven through a real `wanderbooks server` as an agent reaches
|
||||
//! Spec-blind tests for the project tools of the books server (
|
||||
//! BS-statement-5), driven through a real `wanderbooks server` as an agent reaches
|
||||
//! it (common.rs).
|
||||
//!
|
||||
//! Expected behavior comes only from the tool descriptions and parameter /
|
||||
@@ -585,7 +585,7 @@ fn project_to_date_counts_lines_before_the_period() {
|
||||
assert_eq!(zeta["to_date"]["net"], "3200.00");
|
||||
}
|
||||
|
||||
/// The snapshot's figures (rules.md B-37 item 7), as the viewer shows
|
||||
/// The snapshot's figures (BS-statement-5 item 7), as the viewer shows
|
||||
/// them: net is the contribution before overhead, margin_pct its share
|
||||
/// of revenue, to_date.by_account the direct costs by category, and each
|
||||
/// month's net_to_date the running net, the last being to_date's.
|
||||
@@ -1202,7 +1202,7 @@ fn l4(
|
||||
)
|
||||
}
|
||||
|
||||
/// rules.md B-37 item 8: each invoice and bill line takes a project (by
|
||||
/// BS-statement-5 item 8: each invoice and bill line takes a project (by
|
||||
/// name or id); the entry's revenue or expense side is one line per
|
||||
/// project, the untagged lines' as one, the receivable or payable line
|
||||
/// and the payments untagged; books.project, profit_and_loss_by_class,
|
||||
@@ -1408,7 +1408,7 @@ fn a_document_for_a_finished_project_says_so() {
|
||||
);
|
||||
}
|
||||
|
||||
/// B-37 items 4 and 8: an invoice line naming an on-spec project is taken
|
||||
/// BS-statement-5 items 4 and 8: an invoice line naming an on-spec project is taken
|
||||
/// and its result asks whether there is now an agreement (a hoped-for
|
||||
/// payment is no receivable); a bill's cost for one is an expense like any
|
||||
/// other, so a bill gets no such note.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Tax categories at account creation, and `policy.require_tax_category`
|
||||
//! (P3, defect 8; rules.md B-32), through a real books server as an
|
||||
//! (P3, defect 8; BS-ledger-11), through a real books server as an
|
||||
//! agent reaches it (common.rs).
|
||||
//!
|
||||
//! ```text
|
||||
@@ -7,7 +7,7 @@
|
||||
//! or the human hears that it doesn't; a company that refuses
|
||||
//! uncategorized accounts gets exactly that, never a refused
|
||||
//! invoice.
|
||||
//! SOURCE: rules.md B-32; plan/served.md P3 defect 8 and "Settled in
|
||||
//! SOURCE: BS-ledger-11; plan/served.md P3 defect 8 and "Settled in
|
||||
//! design" (warn by default, headers exempt).
|
||||
//! ```
|
||||
//!
|
||||
@@ -322,7 +322,7 @@ fn require_tax_category_refuses_defect_8() {
|
||||
assert_eq!(out["warnings"].as_array().unwrap().len(), 2, "{out}");
|
||||
}
|
||||
|
||||
/// rules.md B-31 for new accounts: a name another account under the same
|
||||
/// BS-ledger-10 for new accounts: a name another account under the same
|
||||
/// parent has, ignoring capitals (top-level accounts are siblings too),
|
||||
/// or one holding nine digits in a row, is refused, for books.add_account
|
||||
/// and books.import_chart_csv alike; under another parent the name is
|
||||
@@ -369,7 +369,7 @@ fn a_new_account_named_like_a_sibling_is_refused() {
|
||||
);
|
||||
}
|
||||
|
||||
/// rules.md B-32: a gain on business property (`form_4797_gain_loss`, the
|
||||
/// BS-ledger-11: a gain on business property (`form_4797_gain_loss`, the
|
||||
/// disposal account a refusing company must categorize) is exported apart
|
||||
/// in the tax summary, JSON and CSV alike: at its book amount, with no tax
|
||||
/// amount, and outside income and both nets (Form 4797 figures it from
|
||||
|
||||
@@ -1799,7 +1799,7 @@ fn a_locked_vault_still_builds_the_package() {
|
||||
assert!(w.iter().all(|r| r["tin"].is_empty()));
|
||||
}
|
||||
|
||||
/// B-26 ("No tool output, error, or log holds a full TIN"): a TIN put in
|
||||
/// BS-partner-2 ("No tool output, error, or log holds a full TIN"): a TIN put in
|
||||
/// the wrong field is refused, and the refusal never repeats it, however
|
||||
/// it was written: as a party name, a bare number where a string goes, or
|
||||
/// a share's percent.
|
||||
@@ -1841,7 +1841,7 @@ fn refusals_never_echo_a_tin() {
|
||||
}
|
||||
}
|
||||
|
||||
/// B-26 for resource reads: a refused `resources/read` quotes the URI it
|
||||
/// BS-partner-2 for resource reads: a refused `resources/read` quotes the URI it
|
||||
/// was given, in its message and its data, and never repeats a TIN in it,
|
||||
/// however the URI carries one (a receipt id, a handbook section, an
|
||||
/// unknown path, a digest's `since`).
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! program holds, and books a newer wanderbooks wrote. Oracle: ledger-mcp
|
||||
//! local.rs INVARIANT 3 (every book is tried before the server says it is
|
||||
//! ready; one that won't open is reported with why, on its route and in
|
||||
//! the list, and the others are served) and rules.md B-27 (newer books
|
||||
//! the list, and the others are served) and BS-format-1 (newer books
|
||||
//! are refused as newer, never as corrupt, and left as they are).
|
||||
|
||||
use common::{Home, Server, Wire};
|
||||
@@ -80,7 +80,7 @@ fn a_held_lock_is_refused_not_waited_on_forever() {
|
||||
}
|
||||
|
||||
/// Books written by a newer wanderbooks: the server won't open them, and
|
||||
/// says to update it, not that the books are corrupt (rules.md B-27); it
|
||||
/// says to update it, not that the books are corrupt (BS-format-1); it
|
||||
/// leaves them as they are.
|
||||
#[test]
|
||||
fn newer_books_are_refused_as_newer_not_corrupt() {
|
||||
@@ -90,7 +90,7 @@ fn newer_books_are_refused_as_newer_not_corrupt() {
|
||||
let mut w = ledger_store::JournalWriter::open(&dir.join(ledger_store::JOURNAL_FILE)).unwrap();
|
||||
w.append("journal.format_set", json!({"format": 3, "features": []}))
|
||||
.unwrap();
|
||||
// The next line chains onto it, so its bytes are checked (B-27).
|
||||
// The next line chains onto it, so its bytes are checked (BS-format-1).
|
||||
w.append(
|
||||
"fx.rate_set",
|
||||
json!({"currency": "EUR", "date": "2026-10-01", "rate": "1.10"}),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Files that carry full TINs never enter the books (rules.md B-26;
|
||||
//! Files that carry full TINs never enter the books (BS-partner-2;
|
||||
//! tin_files.rs).
|
||||
//!
|
||||
//! ```text
|
||||
@@ -6,7 +6,7 @@
|
||||
//! (books.get_receipt would hand its bytes to any agent), however it
|
||||
//! comes back: the W-9 books.set_w9 read, books.get_w9's copy, a CPA
|
||||
//! package or a file from one, or text with a TIN in it.
|
||||
//! SOURCE: rules.md B-26; DECISION (P0 review round 2, 2026-10-16).
|
||||
//! SOURCE: BS-partner-2; DECISION (P0 review round 2, 2026-10-16).
|
||||
//! INVARIANTS (oracle):
|
||||
//! 1. Every file the server read or wrote with full TINs is refused by
|
||||
//! every way a file enters the books (books.attach_receipt and
|
||||
|
||||
@@ -95,7 +95,7 @@ impl ReceiptPolicy {
|
||||
}
|
||||
|
||||
/// Total debits of the entry (one side of the balanced entry). A
|
||||
/// draft's lines are as journaled, of any size (rules.md B-28): a total
|
||||
/// draft's lines are as journaled, of any size (BS-entry-4): a total
|
||||
/// past exact arithmetic is refused (TooLargeToCompute), never a panic.
|
||||
pub fn entry_debits(entry: &JournalEntry) -> Result<Decimal, ledger_core::LedgerError> {
|
||||
ledger_core::evidence::Policy::entry_debits(entry)
|
||||
@@ -363,7 +363,7 @@ mod rule_tests {
|
||||
}
|
||||
|
||||
/// A draft an earlier version journaled may hold debits exact
|
||||
/// arithmetic can't sum (rules.md B-28): its total is refused, never a
|
||||
/// arithmetic can't sum (BS-entry-4): its total is refused, never a
|
||||
/// panic, and for the policy it is past any threshold: a receipt is
|
||||
/// required, and it is no part of a split.
|
||||
#[test]
|
||||
|
||||
@@ -59,7 +59,7 @@ impl AccountType {
|
||||
/// The longest name a new account (or a rename) may take, in characters:
|
||||
/// one line that every report prints, as long as the company's own name
|
||||
/// may be ([`crate::settings::MAX_TEXT`]). The command's bound, never
|
||||
/// replay's (rules.md B-28): a journaled name of any length replays.
|
||||
/// replay's (BS-entry-4): a journaled name of any length replays.
|
||||
pub const MAX_ACCOUNT_NAME: usize = crate::settings::MAX_TEXT;
|
||||
|
||||
/// A single account in the chart of accounts.
|
||||
@@ -151,7 +151,7 @@ impl ChartOfAccounts {
|
||||
|
||||
/// Give an account a new name. Only the account must exist: what a
|
||||
/// new name may be is the command's to check
|
||||
/// ([`crate::Ledger::rename_account`]), never replay's (rules.md B-28).
|
||||
/// ([`crate::Ledger::rename_account`]), never replay's (BS-entry-4).
|
||||
pub fn set_name(&mut self, id: AccountId, name: &str) -> Result<(), LedgerError> {
|
||||
let a = self
|
||||
.accounts
|
||||
|
||||
@@ -44,7 +44,7 @@ pub fn interval_start(d: NaiveDate, interval: Interval) -> NaiveDate {
|
||||
/// `[start, end]` split on calendar interval boundaries, first and last
|
||||
/// 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).
|
||||
/// (BS-entry-4: books an earlier version wrote may hold such dates).
|
||||
pub fn intervals(
|
||||
start: NaiveDate,
|
||||
end: NaiveDate,
|
||||
@@ -264,7 +264,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// 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).
|
||||
/// the last interval ends there, never a panic (BS-entry-4).
|
||||
#[test]
|
||||
fn intervals_reach_chronos_last_day() {
|
||||
let y = NaiveDate::MAX.year();
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//! * `receive_payment`: Dr Cash, Cr A/R.
|
||||
//! * `pay_bill`: Dr A/P, Cr Cash.
|
||||
//!
|
||||
//! A document keeps no figure of its own (plan P4b, D-45; rules.md B-38):
|
||||
//! A document keeps no figure of its own (plan P4b, D-45; BS-arap-2):
|
||||
//! every ledger line on a receivables or payables account carries the
|
||||
//! document it belongs to ([`DocTag`]), and what is paid and still owed,
|
||||
//! and the document's status, are read from those lines that stand
|
||||
@@ -29,7 +29,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The most days a payment term may run: ten years, far beyond any trade
|
||||
/// term, and short of the calendar's end for every document date the
|
||||
/// books can hold (B-39).
|
||||
/// books can hold (BS-arap-3).
|
||||
pub const MAX_TERMS_DAYS: u16 = 3_650;
|
||||
|
||||
/// Opaque customer handle.
|
||||
@@ -198,12 +198,12 @@ pub enum DocStatus {
|
||||
Paid,
|
||||
/// Nothing owed, the last of it written off (S7).
|
||||
WrittenOff,
|
||||
/// Its own entry doesn't stand: reversed (B-9), number kept.
|
||||
/// Its own entry doesn't stand: reversed (BS-ledger-5), number kept.
|
||||
Void,
|
||||
/// Less than nothing owed: more paid against it than it is for, a
|
||||
/// credit balance owed back (to the customer on an invoice, by the
|
||||
/// vendor on a bill). Only in books an earlier version left out of
|
||||
/// bounds (B-38 INVARIANT 2); never a receivable or a payable, so
|
||||
/// bounds (BS-arap-2 INVARIANT 2); never a receivable or a payable, so
|
||||
/// never aged.
|
||||
Overpaid,
|
||||
/// Its own entry stands but carries no line tagged with it (an older
|
||||
@@ -263,7 +263,7 @@ pub struct DocState {
|
||||
|
||||
impl DocState {
|
||||
/// It owes less than nothing or more than its total: books an earlier
|
||||
/// version left out of bounds (B-38 INVARIANT 2; plan P4b.14 item 3),
|
||||
/// version left out of bounds (BS-arap-2 INVARIANT 2; plan P4b.14 item 3),
|
||||
/// which the control check lists for attention.
|
||||
pub fn out_of_bounds(&self) -> bool {
|
||||
self.outstanding < Decimal::ZERO || self.outstanding > self.total
|
||||
@@ -275,7 +275,7 @@ impl DocState {
|
||||
/// ```text
|
||||
/// GOAL: one status from the ledger's figures, whatever happened to the
|
||||
/// document, its payments and their reversals.
|
||||
/// SOURCE: docs/spec/rules.md B-38; plan/served.md P4b.3 ("Status as of D");
|
||||
/// SOURCE: BS-arap-2; plan/served.md P4b.3 ("Status as of D");
|
||||
/// ASC 310-10 (a credit balance is not a receivable).
|
||||
/// INVARIANTS:
|
||||
/// 1. Void exactly when its own entry doesn't stand (`origin_stands`
|
||||
@@ -426,7 +426,7 @@ impl PaymentDetails {
|
||||
}
|
||||
}
|
||||
|
||||
/// One document a settlement applies to (plan P4b S6; rules.md B-42): the
|
||||
/// One document a settlement applies to (plan P4b S6; BS-arap-6): the
|
||||
/// cash paid on it, the early-payment discount taken off it, and why a
|
||||
/// discount outside its terms was taken anyway.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -456,7 +456,7 @@ pub struct Fee {
|
||||
pub vendor: Option<VendorId>,
|
||||
}
|
||||
|
||||
/// Everything one settlement needs (plan P4b S6; rules.md B-42): its date,
|
||||
/// Everything one settlement needs (plan P4b S6; BS-arap-6): its date,
|
||||
/// description, deposit account, the party every document belongs to, the
|
||||
/// applications, and the processor's fee when one was withheld.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -484,7 +484,7 @@ pub struct SettleParams {
|
||||
/// when it is a control line ([`Application`]'s payment or discount).
|
||||
pub type SettlementRow = (crate::AccountId, crate::Side, Decimal, Option<DocTag>);
|
||||
|
||||
/// How a document's payment terms count their days (rules.md B-39; plan
|
||||
/// How a document's payment terms count their days (BS-arap-3; plan
|
||||
/// P4b S4.1): from the document's date, from the end of its month, or a
|
||||
/// date the parties agreed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -514,11 +514,11 @@ pub struct EarlyDiscount {
|
||||
}
|
||||
|
||||
/// Payment terms: one due date, and the early-payment discount open
|
||||
/// before it (rules.md B-39; plan P4b S4.1, A-2, A-8).
|
||||
/// before it (BS-arap-3; plan P4b S4.1, A-2, A-8).
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: terms give one due date and one discount date, exactly.
|
||||
/// SOURCE: docs/spec/rules.md B-39; plan/served.md 8.3.13 (B-39);
|
||||
/// SOURCE: BS-arap-3; plan/served.md 8.3.13 (BS-arap-3);
|
||||
/// CONVENTION: standard trade-terms notation; UCC §2-310(a) for
|
||||
/// goods; for services, the contract.
|
||||
/// INVARIANTS:
|
||||
@@ -976,7 +976,7 @@ pub struct DocumentLine {
|
||||
/// Line amount (positive).
|
||||
pub amount: Decimal,
|
||||
/// The project (a class) the line's revenue or cost belongs to, if
|
||||
/// any (rules.md B-37): the posted entry's revenue or expense line for
|
||||
/// any (BS-statement-5): the posted entry's revenue or expense line for
|
||||
/// it carries the tag; the receivable or payable line never does.
|
||||
/// Documents journaled before the `document_line_projects` feature
|
||||
/// have none.
|
||||
@@ -1035,7 +1035,7 @@ pub struct Invoice {
|
||||
pub entry_id: u64,
|
||||
/// The number it was issued under ("INV-0007"), from
|
||||
/// [`crate::Ledger::next_invoice_number`]; stored at issue, never
|
||||
/// recomputed, kept by a void (A-2, B-40). None on a legacy invoice:
|
||||
/// recomputed, kept by a void (A-2, BS-arap-4). None on a legacy invoice:
|
||||
/// it is shown as "Invoice {id}" and never counted.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub number: Option<String>,
|
||||
@@ -1061,7 +1061,7 @@ pub struct Invoice {
|
||||
|
||||
/// 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
|
||||
/// line as written (BS-entry-4), 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> {
|
||||
crate::kernel::total_of(lines, |l| l.amount)
|
||||
@@ -1082,9 +1082,9 @@ pub type DocumentPartKey = (Option<crate::AccountId>, Option<crate::ClassId>);
|
||||
/// GOAL: a document's lines post to their accounts and count toward their
|
||||
/// projects, and a document whose lines name neither posts exactly
|
||||
/// as before.
|
||||
/// SOURCE: docs/spec/rules.md B-37 item 3 (job costing: the revenue and
|
||||
/// SOURCE: BS-statement-5 item 3 (job costing: the revenue and
|
||||
/// direct costs identified with one job) and item 8 (an
|
||||
/// invoice's or bill's line names its project); B-39 and plan
|
||||
/// invoice's or bill's line names its project); BS-arap-3 and plan
|
||||
/// P4b S4.1 A-10 (every bill line names its account).
|
||||
/// INVARIANTS:
|
||||
/// 1. The parts sum to the document's total (conservation), and each
|
||||
@@ -1166,7 +1166,7 @@ pub struct Bill {
|
||||
/// The auto-posted journal entry.
|
||||
pub entry_id: u64,
|
||||
/// The vendor's own invoice number, when given: what a duplicate
|
||||
/// check reads (B-40; [`crate::Ledger::check_vendor_ref`]).
|
||||
/// check reads (BS-arap-4; [`crate::Ledger::check_vendor_ref`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub vendor_ref: Option<String>,
|
||||
/// The day we received the bill, when it differs from its date.
|
||||
@@ -1198,7 +1198,7 @@ impl Bill {
|
||||
/// Validate document lines: at least one, all positive amounts, each in a
|
||||
/// journal line's range, and a quantity and unit price that multiply to
|
||||
/// the amount exactly (plan P4b S4.1). For new documents; replay restores
|
||||
/// them as journaled (rules.md B-28).
|
||||
/// them as journaled (BS-entry-4).
|
||||
pub fn validate_lines(lines: &[DocumentLine]) -> Result<(), LedgerError> {
|
||||
if lines.is_empty() {
|
||||
return Err(LedgerError::EmptyDocumentLines);
|
||||
@@ -1251,7 +1251,7 @@ pub fn validate_lines(lines: &[DocumentLine]) -> Result<(), LedgerError> {
|
||||
|
||||
/// 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).
|
||||
/// documents; replay restores them as journaled (BS-entry-4).
|
||||
pub fn validate_due_date(date: NaiveDate, due_date: NaiveDate) -> Result<(), LedgerError> {
|
||||
crate::calendar::check(date)?;
|
||||
crate::calendar::check(due_date)?;
|
||||
@@ -1354,7 +1354,7 @@ pub struct AgingDocument {
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: say how overdue a balance is, as of a date.
|
||||
/// SOURCE: docs/spec/rules.md B-18 (bucket edges: CONVENTION, ASC
|
||||
/// SOURCE: BS-arap-1 (bucket edges: CONVENTION, ASC
|
||||
/// 326-20-55-38 illustrative; due today is Current: DECISION,
|
||||
/// owner 2026-10-13).
|
||||
/// INVARIANTS:
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
//! — and postings go through the normal entry machinery, so every
|
||||
//! accounting invariant holds.
|
||||
//!
|
||||
//! Two figures of accumulated depreciation, never confused (rules.md B-15 rule 8):
|
||||
//! Two figures of accumulated depreciation, never confused (BS-asset-1 rule 8):
|
||||
//! what the schedule says is due through a date
|
||||
//! ([`accumulated_scheduled_through`]) and what the books carry, the runs
|
||||
//! posted and not reversed ([`crate::Ledger::accumulated_posted`]). Book
|
||||
@@ -72,7 +72,7 @@ pub struct Asset {
|
||||
pub id: AssetId,
|
||||
/// What it is, e.g. "2023 Sprinter van".
|
||||
pub description: String,
|
||||
/// The day it was placed in service: depreciation starts here (B-15).
|
||||
/// The day it was placed in service: depreciation starts here (BS-asset-1).
|
||||
/// The day the company acquired it is its acquisition entry's
|
||||
/// ([`crate::Ledger::asset_acquired_date`]), never later than this.
|
||||
#[serde(rename = "purchase_date")]
|
||||
@@ -274,7 +274,7 @@ pub struct AssetBasis {
|
||||
/// The §704(c) method chosen for it, if chosen (contributions only).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub sec704c_method: Option<Sec704cMethod>,
|
||||
/// Who gave the facts, when, and on what (rules.md B-29).
|
||||
/// Who gave the facts, when, and on what (BS-ledger-9).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<crate::settings::Source>,
|
||||
}
|
||||
@@ -334,7 +334,7 @@ impl AssetBasis {
|
||||
}
|
||||
|
||||
/// The checks every journaled `asset.basis_set` passed, which replay
|
||||
/// applies (rules.md B-28): the facts fit the rule and none is
|
||||
/// applies (BS-entry-4): the facts fit the rule and none is
|
||||
/// negative. No bound on size or places.
|
||||
pub fn check_journaled(&self) -> Result<(), String> {
|
||||
if self.rule == BasisRule::Purchase {
|
||||
@@ -365,7 +365,7 @@ impl AssetBasis {
|
||||
/// written (the rule through 2026-10-16), for a record with no value
|
||||
/// at contribution: a purchase takes no contributor basis; a
|
||||
/// contribution needs one, non-negative, in cents at most. Replay of
|
||||
/// that event applies exactly these (rules.md B-28).
|
||||
/// that event applies exactly these (BS-entry-4).
|
||||
pub fn check_legacy_journaled(&self) -> Result<(), String> {
|
||||
use BasisRule::*;
|
||||
match (self.rule, self.contributor_adjusted_basis) {
|
||||
@@ -610,7 +610,7 @@ struct MonthLine {
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: how much of an asset's cost has been used up, month by month.
|
||||
/// SOURCE: docs/spec/rules.md B-15 (straight line; salvage never
|
||||
/// SOURCE: BS-asset-1 (straight line; salvage never
|
||||
/// depreciated; partial months by days; ASC 360-10-35-4: cost less
|
||||
/// salvage over the useful life "in a systematic and rational
|
||||
/// manner", as equitably as possible to the periods served);
|
||||
@@ -642,7 +642,7 @@ struct MonthLine {
|
||||
/// either side of one).
|
||||
/// 7. NEVER panics: a figure that can't be computed (a life past
|
||||
/// chrono's last day, amounts past exact arithmetic) is refused
|
||||
/// (rules.md B-28).
|
||||
/// (BS-entry-4).
|
||||
/// SCENARIOS:
|
||||
/// 1. IF $12,000 over 12 months from Jan 1, through Jun 15:
|
||||
/// - SHOULD end with June at 500.00 (15 of 30 days), accumulated
|
||||
@@ -743,7 +743,7 @@ fn schedule_months(asset: &Asset, through: NaiveDate) -> Result<Vec<MonthLine>,
|
||||
/// (inclusive), exact to the minor unit ([`depreciation_schedule`]): the
|
||||
/// tools' `accumulated_scheduled_through`. What the books carry is
|
||||
/// [`crate::Ledger::accumulated_posted`]; the two agree once every month
|
||||
/// due is posted (rules.md B-15 rule 8).
|
||||
/// due is posted (BS-asset-1 rule 8).
|
||||
pub fn accumulated_scheduled_through(
|
||||
asset: &Asset,
|
||||
as_of: NaiveDate,
|
||||
@@ -758,7 +758,7 @@ pub fn accumulated_scheduled_through(
|
||||
/// the schedule's own book value (as [`ScheduleLine::book_value`]), never
|
||||
/// what the books carry, which is cost less
|
||||
/// [`crate::Ledger::accumulated_posted`] (the register's and the tools'
|
||||
/// `book_value`, rules.md B-24).
|
||||
/// `book_value`, BS-asset-3).
|
||||
pub fn scheduled_book_value(asset: &Asset, as_of: NaiveDate) -> Result<Decimal, LedgerError> {
|
||||
asset
|
||||
.cost
|
||||
@@ -795,9 +795,9 @@ pub struct PostedRun {
|
||||
/// GOAL: the catch-up rule reads the books as they stood at each month
|
||||
/// end: a run reversed after its month ended still carried that
|
||||
/// month, so running the month again would carry it twice.
|
||||
/// SOURCE: docs/spec/rules.md B-9 (a mistake is corrected by an opposite
|
||||
/// entry, dated when it is made), B-10 (reversing the reversal
|
||||
/// re-instates), B-15 (the catch-up rule).
|
||||
/// SOURCE: BS-ledger-5 (a mistake is corrected by an opposite
|
||||
/// entry, dated when it is made), BS-ledger-6 (reversing the reversal
|
||||
/// re-instates), BS-asset-1 (the catch-up rule).
|
||||
/// INVARIANTS:
|
||||
/// 1. Through any month's end, the effects sum to what the runs' entries
|
||||
/// and their reversals dated on or before it carry in the asset's
|
||||
@@ -1010,7 +1010,7 @@ fn cumulatives(
|
||||
/// SOURCE: plan/served.md P3 "Settled in design" (2026-10-20): a month of
|
||||
/// depreciation skipped is caught up in the month the run is made
|
||||
/// (an immaterial miss; a material one is restated, ASC 250, a
|
||||
/// correction for a human and the CPA); docs/spec/rules.md B-15.
|
||||
/// correction for a human and the CPA); BS-asset-1.
|
||||
/// INVARIANTS:
|
||||
/// 1. amount = catch_up_room for the month: kernel::catch_up over the
|
||||
/// month ends M from this month's through the latest month an effect
|
||||
@@ -1124,11 +1124,11 @@ pub struct DisposalAmounts {
|
||||
|
||||
/// Whether an asset can be disposed of for `proceeds`: it is active and
|
||||
/// the proceeds aren't negative. The checks every journaled
|
||||
/// disposal passed, so replaying one never depends on a figure (rules.md
|
||||
/// B-28). The date's floor, the day the company acquired the asset, needs
|
||||
/// disposal passed, so replaying one never depends on a figure (
|
||||
/// BS-entry-4). The date's floor, the day the company acquired the asset, needs
|
||||
/// its acquisition entry, so the ledger checks it for new disposals only
|
||||
/// (`Ledger::dispose_asset`): a disposal may fall on the in-service date
|
||||
/// (one day held, accrual being inclusive, B-15), or before it once the
|
||||
/// (one day held, accrual being inclusive, BS-asset-1), or before it once the
|
||||
/// asset is acquired (nothing accrued yet).
|
||||
pub fn check_disposal(asset: &Asset, proceeds: Money) -> Result<(), LedgerError> {
|
||||
if asset.status != AssetStatus::Active {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The audit's statements checks (plan P8; rules.md B-45): the books,
|
||||
//! The audit's statements checks (plan P8; BS-ledger-13): the books,
|
||||
//! read as an auditor would, through a date, as a list of findings.
|
||||
//!
|
||||
//! ```text
|
||||
@@ -7,8 +7,10 @@
|
||||
//! reproducible and its workpaper hashes the same twice.
|
||||
//! SOURCE: IRS Pub. 583 (records that support entries); Rev. Proc. 98-25
|
||||
//! §5.01 (the relationship between the records and the books must
|
||||
//! be demonstrable); docs/spec/rules.md B-6 to B-14 (the
|
||||
//! statements), B-38 (control accounts), B-43 (evidence);
|
||||
//! be demonstrable); BS-statement-1, BS-statement-2, BS-ledger-4, BS-ledger-5,
|
||||
//! BS-ledger-6, BS-period-1, BS-period-2, BS-partner-1 and
|
||||
//! BS-statement-3 (the statements), BS-arap-2 (control accounts),
|
||||
//! BS-entry-5 (evidence);
|
||||
//! DECISION D-9 (the audit and its bar), D-53 (a run, not a job).
|
||||
//! INVARIANTS:
|
||||
//! 1. Pure: reads the ledger and the facts [`AuditInput`] hands in,
|
||||
@@ -668,7 +670,7 @@ fn settings_problems(problems: &[String]) -> Vec<Finding> {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Scope, method and the attestation bar (rules.md B-45; D-9)
|
||||
// Scope, method and the attestation bar (BS-ledger-13; D-9)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// What an audit covers.
|
||||
@@ -761,7 +763,7 @@ impl Effort {
|
||||
}
|
||||
|
||||
/// How an attestation was made, as the client says (self-reported: the
|
||||
/// books record the claim, never prove it; rules.md B-45).
|
||||
/// books record the claim, never prove it; BS-ledger-13).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
|
||||
pub struct Method {
|
||||
/// The model that checked, as it names itself.
|
||||
|
||||
@@ -94,7 +94,7 @@ pub(crate) fn fiscal_year_unclamped(md: (u32, u32), d: NaiveDate) -> (NaiveDate,
|
||||
/// the CPA package's year, and every default period derive from.
|
||||
/// SOURCE: IRS Pub. 538 (docs/spec/sources/irs-periods-and-methods.md):
|
||||
/// "A tax year is an annual accounting period for keeping records
|
||||
/// and reporting income and expenses"; rules.md B-28 (no date
|
||||
/// and reporting income and expenses"; BS-entry-4 (no date
|
||||
/// outside the calendar).
|
||||
/// INVARIANTS:
|
||||
/// 1. For d in the calendar: FIRST_DAY <= result <= d, and d is before
|
||||
@@ -108,7 +108,7 @@ pub fn fiscal_year_start_on(md: (u32, u32), d: NaiveDate) -> NaiveDate {
|
||||
fiscal_year_start_unclamped(md, d).max(FIRST_DAY)
|
||||
}
|
||||
|
||||
/// What an omitted date means, by the kind of report (rules.md B-30): the
|
||||
/// What an omitted date means, by the kind of report (BS-period-3): the
|
||||
/// text every tool description and date parameter shows, so none can say
|
||||
/// other than [`PeriodDefaults`] does.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -152,13 +152,13 @@ pub const YEAR_DOC: &str =
|
||||
"Calendar year. Omitted: this calendar year (1099s and party totals count by calendar year).";
|
||||
|
||||
/// The defaults an omitted date takes, today, under the company's fiscal
|
||||
/// year: the one rule (rules.md B-30) the report tools, the viewer and
|
||||
/// year: the one rule (BS-period-3) the report tools, the viewer and
|
||||
/// the tool descriptions share. Built by [`period_defaults`].
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: one meaning for "no dates", everywhere: a report asked for
|
||||
/// without dates covers this fiscal year so far.
|
||||
/// SOURCE: rules.md B-30; IRS Pub. 538 ("an annual accounting period for
|
||||
/// SOURCE: BS-period-3; IRS Pub. 538 ("an annual accounting period for
|
||||
/// keeping records and reporting income and expenses"); 26 U.S.C.
|
||||
/// §6041(a) ("in any calendar year") and §6041A(a)(2) ("during
|
||||
/// such calendar year") for the calendar-year counts; DECISION
|
||||
@@ -251,7 +251,7 @@ impl PeriodDefaults {
|
||||
|
||||
/// 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
|
||||
/// chrono can't hold) has its 31 days too (BS-entry-4: a schedule an
|
||||
/// earlier version accepted is computed, never a panic).
|
||||
pub fn days_in_month(year: i32, month: u32) -> u32 {
|
||||
match month {
|
||||
@@ -290,7 +290,7 @@ pub struct SpanPart {
|
||||
/// ```text
|
||||
/// GOAL: cut a span of days (an asset's life, a schedule's coverage) into
|
||||
/// the calendar months it touches, for proration by days.
|
||||
/// SOURCE: docs/spec/rules.md B-15, B-16; kernel::prorate_by_days.
|
||||
/// SOURCE: BS-asset-1, BS-prepaid-1; kernel::prorate_by_days.
|
||||
/// INVARIANTS:
|
||||
/// 1. The parts' days sum to the span's days; every part has 1 to its
|
||||
/// month's days (a valid kernel::MonthPart), and only the last is
|
||||
@@ -567,7 +567,7 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The descriptions say what the resolver does (B-30), in the words
|
||||
/// The descriptions say what the resolver does (BS-period-3), in the words
|
||||
/// every tool shows.
|
||||
#[test]
|
||||
fn the_descriptions_name_the_rule() {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The statement of cash flows (rules.md B-14), by the direct method: each
|
||||
//! The statement of cash flows (BS-statement-3), by the direct method: each
|
||||
//! entry that moved cash, in the section of the accounts it settled, gross;
|
||||
//! the reconciliation of net income to operating cash as a separate
|
||||
//! schedule; and the investing and financing activities no cash settled,
|
||||
@@ -77,7 +77,7 @@ pub enum OperatingClass {
|
||||
/// (e) Interest paid.
|
||||
InterestPaid,
|
||||
/// (f) Income taxes paid. No tax category marks an entity-level income
|
||||
/// tax yet, so nothing is filed here (rules.md B-14 rule 5).
|
||||
/// tax yet, so nothing is filed here (BS-statement-3 rule 5).
|
||||
IncomeTaxesPaid,
|
||||
/// (g) Other operating cash payments.
|
||||
OtherPayments,
|
||||
@@ -178,7 +178,7 @@ pub struct CashFlowLine {
|
||||
/// The cash, + in.
|
||||
pub amount: Decimal,
|
||||
/// Of `amount`, what a member or a lender paid or received for the
|
||||
/// company with no cash account moving (rules.md B-14 rule 11, D-42):
|
||||
/// company with no cash account moving (BS-statement-3 rule 11, D-42):
|
||||
/// a constructive receipt or payment. Zero for most lines.
|
||||
pub on_behalf: Decimal,
|
||||
/// Codes of this kind's accounts the entry moved, sorted.
|
||||
@@ -295,7 +295,7 @@ pub struct OperatingReconciliation {
|
||||
pub net_cash_from_operating: Decimal,
|
||||
}
|
||||
|
||||
/// The footing check (rules.md B-14 rule 9).
|
||||
/// The footing check (BS-statement-3 rule 9).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CashFlowFooting {
|
||||
/// Operating + investing + financing.
|
||||
@@ -344,7 +344,7 @@ pub struct CashFlowWarning {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// The statement of cash flows, direct method (rules.md B-14).
|
||||
/// The statement of cash flows, direct method (BS-statement-3).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CashFlowStatement {
|
||||
/// Period start, inclusive.
|
||||
@@ -440,7 +440,7 @@ pub enum RoleList {
|
||||
Investing,
|
||||
}
|
||||
|
||||
/// A contradiction among the cash flow account roles (rules.md B-14 rule
|
||||
/// A contradiction among the cash flow account roles (BS-statement-3 rule
|
||||
/// 2): the statement refuses rather than guess.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum RoleProblem {
|
||||
@@ -546,7 +546,7 @@ impl RoleProblem {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every contradiction among the cash flow account roles (rules.md B-14
|
||||
/// Every contradiction among the cash flow account roles (BS-statement-3
|
||||
/// rule 2), in a fixed order. Codes the chart lacks are the caller's to
|
||||
/// report. The one check behind both the statement's refusal and the
|
||||
/// settings' problems, so the two never drift apart.
|
||||
@@ -554,7 +554,7 @@ impl RoleProblem {
|
||||
/// ```text
|
||||
/// GOAL: the statement's account roles partition the chart, so every
|
||||
/// account is in exactly one section.
|
||||
/// SOURCE: rules.md B-14 rule 2 (ASC 230-10-45-10: every cash receipt and
|
||||
/// SOURCE: BS-statement-3 rule 2 (ASC 230-10-45-10: every cash receipt and
|
||||
/// payment is investing, financing or operating).
|
||||
/// INVARIANTS:
|
||||
/// 1. Cash and investing accounts MUST be assets; financing accounts
|
||||
@@ -639,7 +639,7 @@ pub fn role_problems(
|
||||
out
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 9, on its own so the check is tested directly (it
|
||||
/// BS-statement-3 rule 9, on its own so the check is tested directly (it
|
||||
/// cannot fail on posted entries): the sections sum to the change in
|
||||
/// cash, or nothing is produced.
|
||||
pub fn foot(sections_sum: Decimal, net_change: Decimal) -> Result<CashFlowFooting, LedgerError> {
|
||||
@@ -977,8 +977,8 @@ impl<'a> Roles<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The liabilities that hold distributions declared by `end` (rules.md
|
||||
/// B-14 rule 2), among the accounts `open` leaves to be placed: each
|
||||
/// The liabilities that hold distributions declared by `end` (
|
||||
/// BS-statement-3 rule 2), among the accounts `open` leaves to be placed: each
|
||||
/// credited, in the posted entries dated on or before `end` (closes and
|
||||
/// reversals aside), only by entries whose debits are all to equity (Dr
|
||||
/// Distributions / Cr Distributions Payable; a corporation's Dr Retained
|
||||
@@ -1031,7 +1031,7 @@ type KindOrder = (u8, u8, String);
|
||||
/// so the payment is an investing outflow (ASC 230-10-45-13(c)). A bill
|
||||
/// posts to the general-expenses control today, so this is empty until a
|
||||
/// bill can carry an equipment line (P4b S4). A bill's payments are the
|
||||
/// entries whose payables line carries it (rules.md B-38).
|
||||
/// entries whose payables line carries it (BS-arap-2).
|
||||
#[derive(Default)]
|
||||
struct BillSplits {
|
||||
/// By (entry, line index): the investing part of that payables line,
|
||||
@@ -1741,15 +1741,15 @@ fn codes<'p>(
|
||||
Ok(out.into_iter().collect())
|
||||
}
|
||||
|
||||
/// The statement of cash flows for a period, direct method (rules.md
|
||||
/// B-14).
|
||||
/// The statement of cash flows for a period, direct method (
|
||||
/// BS-statement-3).
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: the statement of cash flows for a period: each entry's cash by
|
||||
/// section and kind, the noncash investing and financing activities,
|
||||
/// and net income reconciled to operating cash; footing exactly or
|
||||
/// not at all.
|
||||
/// SOURCE: rules.md B-14 (ASC 230-10-10-1 cash receipts and payments;
|
||||
/// SOURCE: BS-statement-3 (ASC 230-10-10-1 cash receipts and payments;
|
||||
/// 45-4, 45-5 what cash is; 45-7, 45-26 gross; 45-10 the three
|
||||
/// sections; 45-12 to 45-17 what each holds; 45-24 reconciles
|
||||
/// beginning and ending cash; 45-25 the
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! on drafts only; posted entries are immutable, so their classes are frozen.
|
||||
//!
|
||||
//! A class is also a project: the class with its facts ([`ProjectFacts`]:
|
||||
//! what it is, where it stands, who it is for; rules.md B-37). Every class
|
||||
//! what it is, where it stands, who it is for; BS-statement-5). Every class
|
||||
//! is one; a class an earlier version wrote has the default facts.
|
||||
|
||||
use chrono::NaiveDate;
|
||||
@@ -28,7 +28,7 @@ pub struct Class {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// Where a project stands (rules.md B-37).
|
||||
/// Where a project stands (BS-statement-5).
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
|
||||
)]
|
||||
@@ -85,7 +85,7 @@ impl ProjectStatus {
|
||||
}
|
||||
}
|
||||
|
||||
/// What kind of work a project is (rules.md B-37): it decides the
|
||||
/// What kind of work a project is (BS-statement-5): it decides the
|
||||
/// accounting questions its costs raise.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub enum ProjectKind {
|
||||
@@ -141,7 +141,7 @@ pub const MAX_LINKS: usize = 8;
|
||||
/// One link: one line of text ([`crate::settings::line_text`]'s length
|
||||
/// and control-character rules) with no full TIN as a web address holds
|
||||
/// one ([`crate::settings::holds_printed_tin_in_link`]: a printed SSN or
|
||||
/// EIN is refused, a store listing's `id284882215` is not; rules.md B-26).
|
||||
/// EIN is refused, a store listing's `id284882215` is not; BS-partner-2).
|
||||
fn link_text(l: &str) -> Result<String, String> {
|
||||
use crate::settings::{MAX_TEXT, holds_printed_tin_in_link, line_text};
|
||||
// line_text's TIN rule is a plain text's, so it sees the link with
|
||||
@@ -167,13 +167,13 @@ fn link_text(l: &str) -> Result<String, String> {
|
||||
/// GOAL: say what a project is, where it stands and who it is for, in
|
||||
/// the few facts a job cost sheet carries, without a project
|
||||
/// manager's sprawl (no budgets, estimates or percent complete).
|
||||
/// SOURCE: docs/spec/rules.md B-37; DECISION (owner, 2026-10-21: "Projects
|
||||
/// SOURCE: BS-statement-5; DECISION (owner, 2026-10-21: "Projects
|
||||
/// are entities too and can have name, description, whatever
|
||||
/// other metadata"); job-order costing (a job cost sheet: the
|
||||
/// job, its customer, its dates).
|
||||
/// INVARIANTS:
|
||||
/// 1. No field holds a full taxpayer identification number
|
||||
/// (settings::line_text / long_text, rules.md B-26).
|
||||
/// (settings::line_text / long_text, BS-partner-2).
|
||||
/// 2. ended_on only when the project is finished or abandoned, and
|
||||
/// never before started_on.
|
||||
/// 3. The party, if any, is in the directory (archived allowed).
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
//! 4. Decision and open-item ids are allocated in order and journaled;
|
||||
//! a decision supersedes at most one live decision; an item resolves
|
||||
//! once.
|
||||
//! 5. Replay takes what was journaled (rules.md B-28): text limits and
|
||||
//! 5. Replay takes what was journaled (BS-entry-4): text limits and
|
||||
//! chart checks are for new commands only.
|
||||
//! 6. No text holds a full TIN (settings INVARIANT 4).
|
||||
//! ```
|
||||
@@ -273,7 +273,7 @@ pub struct NewDecision {
|
||||
pub supersedes: Option<u64>,
|
||||
/// The rule or document it rests on, if any.
|
||||
pub citation: Option<String>,
|
||||
/// The projects (classes) it is about, if any (rules.md B-37).
|
||||
/// The projects (classes) it is about, if any (BS-statement-5).
|
||||
pub projects: Vec<crate::ClassId>,
|
||||
}
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ pub enum LedgerError {
|
||||
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).
|
||||
/// units): no one can pay a fraction of a cent (BS-ledger-1).
|
||||
#[error(
|
||||
"amount {amount} {currency} has more than {places} decimal places; round it to the {currency} minor unit first"
|
||||
)]
|
||||
@@ -505,7 +505,7 @@ pub enum LedgerError {
|
||||
end: String,
|
||||
},
|
||||
|
||||
/// The statement of cash flows would not foot (rules.md B-14 rule 9):
|
||||
/// The statement of cash flows would not foot (BS-statement-3 rule 9):
|
||||
/// an engine error, never output. It cannot happen on balanced books
|
||||
/// (Lean `cashflow_sections_sum_to_cash_change`); if it does, the
|
||||
/// engine is wrong, and nothing is shown rather than a wrong figure.
|
||||
@@ -523,13 +523,13 @@ pub enum LedgerError {
|
||||
},
|
||||
|
||||
/// The cash flow statement's account roles (cash, financing, investing)
|
||||
/// contradict each other or the chart (rules.md B-14 rule 2). The text
|
||||
/// contradict each other or the chart (BS-statement-3 rule 2). The text
|
||||
/// names the setting and says what to change.
|
||||
#[error("cash flow account roles: {0}")]
|
||||
CashFlowRoles(String),
|
||||
|
||||
/// A report period given only a start, after today: an omitted end is
|
||||
/// today (rules.md B-30), so the period would end before it starts.
|
||||
/// today (BS-period-3), so the period would end before it starts.
|
||||
#[error(
|
||||
"invalid date range: start {start} is after the end, which defaults to today ({today}): pass end"
|
||||
)]
|
||||
@@ -608,12 +608,12 @@ pub enum LedgerError {
|
||||
|
||||
/// A document line's quantity and unit price don't multiply to its
|
||||
/// amount, or only one of the two is given: the engine never rounds
|
||||
/// one (plan P4b S4.1; rules.md B-39).
|
||||
/// one (plan P4b S4.1; BS-arap-3).
|
||||
#[error("{0}")]
|
||||
LineArithmetic(String),
|
||||
|
||||
/// A document line is on an account that kind of document can't post
|
||||
/// to (plan P4b S4.1, A-10; rules.md B-39): a role account, a cash
|
||||
/// to (plan P4b S4.1, A-10; BS-arap-3): a role account, a cash
|
||||
/// account, or a type the document's side doesn't take.
|
||||
#[error("account {code} \"{name}\" cannot take {kind} line: {why}")]
|
||||
DocumentLineAccount {
|
||||
@@ -628,8 +628,8 @@ pub enum LedgerError {
|
||||
},
|
||||
|
||||
/// A vendor's invoice number (normalized) already names a standing
|
||||
/// bill of that vendor, and no duplicate reason was given (rules.md
|
||||
/// B-40).
|
||||
/// bill of that vendor, and no duplicate reason was given (
|
||||
/// BS-arap-4).
|
||||
#[error(
|
||||
"vendor invoice number '{vendor_ref}' is already on another standing bill of this vendor; \
|
||||
give duplicate_reason when it really is a second bill"
|
||||
@@ -642,7 +642,7 @@ pub enum LedgerError {
|
||||
},
|
||||
|
||||
/// An invoice number already names an invoice: numbers are never
|
||||
/// reused (rules.md B-40, A-2).
|
||||
/// reused (BS-arap-4, A-2).
|
||||
#[error("invoice number '{0}' is already used; numbers are never reused")]
|
||||
DuplicateInvoiceNumber(String),
|
||||
|
||||
@@ -654,7 +654,7 @@ pub enum LedgerError {
|
||||
|
||||
/// An early-payment discount needs net days to be open before: it
|
||||
/// can't be given with due-on-receipt, end-of-month or custom terms
|
||||
/// (rules.md B-39).
|
||||
/// (BS-arap-3).
|
||||
#[error(
|
||||
"an early-payment discount needs net terms with a fixed number of days; it can't be given with due-on-receipt, end-of-month or custom terms"
|
||||
)]
|
||||
@@ -662,7 +662,7 @@ pub enum LedgerError {
|
||||
|
||||
/// `invoicing.first_number` asked to move after a numbered invoice
|
||||
/// exists: the series has begun, and a number is never reused or
|
||||
/// renumbered (rules.md B-40, A-2). The store's check lands with the
|
||||
/// renumbered (BS-arap-4, A-2). The store's check lands with the
|
||||
/// invoice numbers it reads (P4b S4.3).
|
||||
#[error(
|
||||
"invoicing.first_number is locked: a numbered invoice already exists, so the series has begun and its numbers are never reused"
|
||||
@@ -695,13 +695,13 @@ pub enum LedgerError {
|
||||
SettlementMixedKinds(String),
|
||||
|
||||
/// A settlement's documents don't all belong to the one party it
|
||||
/// names (rules.md B-42 INVARIANT 1).
|
||||
/// names (BS-arap-6 INVARIANT 1).
|
||||
#[error("{0} is not {1}'s: a settlement covers one party only")]
|
||||
SettlementPartiesDiffer(String, u64),
|
||||
|
||||
/// A discount needs a reason: none is stated in the document's terms,
|
||||
/// or it is larger than its terms allow, or it is taken after the
|
||||
/// discount date (rules.md B-42 INVARIANT 2).
|
||||
/// discount date (BS-arap-6 INVARIANT 2).
|
||||
#[error(
|
||||
"{doc}: the discount of {discount} needs a reason ({because}); pass discount_reason with the payment"
|
||||
)]
|
||||
@@ -751,7 +751,7 @@ pub enum LedgerError {
|
||||
|
||||
/// A settlement's figures can't be exact: the cash and discounts
|
||||
/// don't cover the applications, or the fee leaves a negative deposit
|
||||
/// (rules.md B-42 INVARIANT 1).
|
||||
/// (BS-arap-6 INVARIANT 1).
|
||||
#[error("{0}")]
|
||||
InvalidSettlement(String),
|
||||
|
||||
@@ -761,7 +761,7 @@ pub enum LedgerError {
|
||||
InvalidPayment(String),
|
||||
|
||||
/// Receivables or payables can't move while their account holds a
|
||||
/// balance (rules.md B-23, B-38): that balance is the documents', and
|
||||
/// balance (BS-ledger-8, BS-arap-2): that balance is the documents', and
|
||||
/// a hand entry moving it is refused by the control guard; it moves
|
||||
/// with its documents (plan P4b S7).
|
||||
#[error(
|
||||
@@ -781,7 +781,7 @@ pub enum LedgerError {
|
||||
},
|
||||
|
||||
/// Receivables or payables can't move to an account holding lines
|
||||
/// that are no document's (rules.md B-38 INVARIANT 1): they would
|
||||
/// that are no document's (BS-arap-2 INVARIANT 1): they would
|
||||
/// become hand lines on a control account.
|
||||
#[error(
|
||||
"account {code} \"{name}\" holds lines no invoice or bill carries (entry {entry} first), \
|
||||
@@ -814,7 +814,7 @@ pub enum LedgerError {
|
||||
},
|
||||
|
||||
/// A line on a receivables or payables control account carries no
|
||||
/// document (rules.md B-23, B-38): the control account must always
|
||||
/// document (BS-ledger-8, BS-arap-2): the control account must always
|
||||
/// equal its documents, so only the document commands post there.
|
||||
#[error(
|
||||
"account {account} is a control account (its balance is its invoices or bills): {at} can't be posted there by hand. Use books.create_invoice, books.receive_payment, books.create_bill or books.pay_bill; to void a document, books.reverse_entry of its entry"
|
||||
@@ -828,14 +828,14 @@ pub enum LedgerError {
|
||||
},
|
||||
|
||||
/// A reversal or payment would leave a document owing less than nothing
|
||||
/// or more than its total at some date (rules.md B-38 INVARIANT 2): the
|
||||
/// or more than its total at some date (BS-arap-2 INVARIANT 2): the
|
||||
/// message says which document, when, and what to reverse first.
|
||||
#[error("{0}")]
|
||||
DocumentBounds(String),
|
||||
|
||||
/// A reversal is dated before the entry it reverses (rules.md B-9,
|
||||
/// A reversal is dated before the entry it reverses (BS-ledger-5,
|
||||
/// D-73): a correction comes after what it corrects, for every kind of
|
||||
/// entry. New commands only; replay never refuses (B-28).
|
||||
/// entry. New commands only; replay never refuses (BS-entry-4).
|
||||
#[error("entry {entry} is dated {original}: its reversal can't be dated before it, on {date}")]
|
||||
ReversalBeforeOriginal {
|
||||
/// The entry reversed.
|
||||
@@ -852,12 +852,12 @@ pub enum LedgerError {
|
||||
|
||||
/// A draft's state or discard was refused: the message says why (a
|
||||
/// note or reason that breaks the books' text rule, no reason given).
|
||||
/// Plan P4, rules.md B-43.
|
||||
/// Plan P4, BS-entry-5.
|
||||
#[error("{0}")]
|
||||
InvalidDraft(String),
|
||||
|
||||
/// A void invoice can't be recorded as sent: it was never a document
|
||||
/// the customer should have received (plan P4b S5, B-38).
|
||||
/// the customer should have received (plan P4b S5, BS-arap-2).
|
||||
#[error("invoice {0} is void: a void invoice was never sent")]
|
||||
DocumentVoid(u64),
|
||||
|
||||
@@ -866,8 +866,8 @@ pub enum LedgerError {
|
||||
/// books' text rule). Plan P4b S5.
|
||||
#[error("{0}")]
|
||||
InvalidSend(String),
|
||||
/// A bad debt can't be written off on cash-basis books (rules.md
|
||||
/// B-41 INVARIANT 3; IRC §166(a); Treas. Reg. §1.166-1(e)): the
|
||||
/// A bad debt can't be written off on cash-basis books (
|
||||
/// BS-arap-5 INVARIANT 3; IRC §166(a); Treas. Reg. §1.166-1(e)): the
|
||||
/// invoice was never counted as income, so there is no basis to
|
||||
/// deduct.
|
||||
#[error(
|
||||
@@ -937,11 +937,11 @@ pub enum LedgerError {
|
||||
UnknownClass(u32),
|
||||
|
||||
/// Another class (project) already has this name, ignoring capitals
|
||||
/// (rules.md B-37).
|
||||
/// (BS-statement-5).
|
||||
#[error("a project named {0:?} already exists: names are unique, ignoring capitals")]
|
||||
DuplicateClassName(String),
|
||||
|
||||
/// A project's facts the books can't take (rules.md B-37): the reason.
|
||||
/// A project's facts the books can't take (BS-statement-5): the reason.
|
||||
#[error("{0}")]
|
||||
InvalidProject(String),
|
||||
|
||||
|
||||
@@ -121,7 +121,7 @@ impl Annotation {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The evidence gate (plan P4, I-5, D-47; rules.md B-43)
|
||||
// The evidence gate (plan P4, I-5, D-47; BS-entry-5)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// What posted an entry that the ledger's own state doesn't otherwise say:
|
||||
@@ -196,7 +196,7 @@ impl Policy {
|
||||
}
|
||||
|
||||
/// Total debits of the entry (one side of the balanced entry). A
|
||||
/// draft's lines are as journaled, of any size (rules.md B-28): a
|
||||
/// draft's lines are as journaled, of any size (BS-entry-4): a
|
||||
/// total past exact arithmetic is refused (TooLargeToCompute), never
|
||||
/// a panic.
|
||||
pub fn entry_debits(entry: &JournalEntry) -> Result<Decimal, LedgerError> {
|
||||
@@ -355,14 +355,14 @@ impl Policy {
|
||||
}
|
||||
|
||||
/// Whether `entry` needs evidence before it posts: the one function that
|
||||
/// decides (plan P4 step 2, I-5, D-47; rules.md B-43). The store's gate,
|
||||
/// decides (plan P4 step 2, I-5, D-47; BS-entry-5). The store's gate,
|
||||
/// the server's previews and digest, the viewer and Needs attention all
|
||||
/// call it.
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: one answer, from what the ledger knows, to "does this entry need
|
||||
/// a receipt".
|
||||
/// SOURCE: docs/spec/rules.md B-43; IRS Pub. 583 (supporting documents);
|
||||
/// SOURCE: BS-entry-5; IRS Pub. 583 (supporting documents);
|
||||
/// DECISION D-47 (a reversal's evidence is its original's, D-12);
|
||||
/// DECISION (owner: the threshold, strictly greater than, 2026-10-12).
|
||||
/// INVARIANTS:
|
||||
|
||||
@@ -84,7 +84,7 @@ impl Form1099 {
|
||||
|
||||
/// Why a vendor gets no 1099: the kind of payee no return is required
|
||||
/// for. Each has its authority ([`ExemptReason::citation`],
|
||||
/// sources/irs-1099-payment-method.md); a decision adds the facts in
|
||||
/// docs/spec/sources/irs-1099-payment-method.md); a decision adds the facts in
|
||||
/// words.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -383,14 +383,14 @@ pub fn apply_decision(decisions: &mut Vec<Dated1099>, new: Dated1099) -> Applied
|
||||
}
|
||||
|
||||
/// The checks a new 1099 decision passes before it is recorded (replay
|
||||
/// skips them: rules.md B-28): the decision ([`Decision1099::check`]),
|
||||
/// skips them: BS-entry-4): the decision ([`Decision1099::check`]),
|
||||
/// its source, its date in the books' calendar, and that a dated decision
|
||||
/// records a change. Returns what recording it would do.
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: no dated decision silently leaves the vendor's earlier payments
|
||||
/// undecided.
|
||||
/// SOURCE: DECISION D-40 (owner, 2026-10-20); docs/spec/rules.md B-19.
|
||||
/// SOURCE: DECISION D-40 (owner, 2026-10-20); BS-1099-1.
|
||||
/// SCENARIOS:
|
||||
/// 1. IF `new` is dated, would be recorded, and no decision other than
|
||||
/// undetermined is in force at any time before its date: SHOULD
|
||||
@@ -428,10 +428,10 @@ pub fn check_new_decision(decisions: &[Dated1099], new: &Dated1099) -> Result<Ap
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: the dollar amount at which a vendor's payments become reportable.
|
||||
/// SOURCE: docs/spec/rules.md B-19 (26 U.S.C. §6041(a), (h), §6041A(a)(2),
|
||||
/// SOURCE: BS-1099-1 (26 U.S.C. §6041(a), (h), §6041A(a)(2),
|
||||
/// Pub. L. 119-21 §70433(f): payments made after December 31,
|
||||
/// 2025; sources/irs-1099-thresholds.md,
|
||||
/// sources/irs-1099-payment-method.md).
|
||||
/// 2025; docs/spec/sources/irs-1099-thresholds.md,
|
||||
/// docs/spec/sources/irs-1099-payment-method.md).
|
||||
/// SCENARIOS:
|
||||
/// 1. IF `year` <= 2025: SHOULD be $600.
|
||||
/// 2. IF `year` == 2026: SHOULD be $2,000.
|
||||
@@ -604,7 +604,7 @@ pub struct PaymentAccounts {
|
||||
/// GOAL: a payment line's role comes from what the books record, and a
|
||||
/// line whose method isn't recorded is never presumed a card's
|
||||
/// unless only a card pays through its account.
|
||||
/// SOURCE: docs/spec/rules.md B-19 (P3 review R2); DECISION D-40 (a bank
|
||||
/// SOURCE: BS-1099-1 (P3 review R2); DECISION D-40 (a bank
|
||||
/// payment with no method recorded counts).
|
||||
/// INVARIANTS (first match wins):
|
||||
/// 1. Cash: one of the books' cash accounts.
|
||||
@@ -868,15 +868,15 @@ fn bounds(
|
||||
/// settings), entries dated after `through` left out.
|
||||
///
|
||||
/// ```text
|
||||
/// SOURCE: docs/spec/rules.md B-19 (26 U.S.C. §6041(a): payments made in
|
||||
/// SOURCE: BS-1099-1 (26 U.S.C. §6041(a): payments made in
|
||||
/// the year; Treas. Reg. §1.6041-1(a)(1)(iv): card and network
|
||||
/// payments go on Form 1099-K; §1.6041-1(e)(1): the company is the
|
||||
/// payor when a member pays its bill; §1.6041-3: payees no return
|
||||
/// is required for; sources/irs-1099-payment-method.md);
|
||||
/// is required for; docs/spec/sources/irs-1099-payment-method.md);
|
||||
/// crate::shares (an entry with several parties, each with their
|
||||
/// share; DECISION, owner, 2026-10-15); DECISION D-40 (owner,
|
||||
/// 2026-10-20: dated decisions; a bank payment with no method
|
||||
/// recorded counts); B-33 (a worksheet as of a day).
|
||||
/// recorded counts); BS-statement-4 (a worksheet as of a day).
|
||||
/// DEFINITIONS:
|
||||
/// buckets(e): kernel::payment_bucket per line (role from `sources` and
|
||||
/// the instruments' accounts; tag from Ledger::entry_instrument),
|
||||
@@ -888,7 +888,7 @@ fn bounds(
|
||||
/// sources.financing), what the shares resolve against (the MCP server
|
||||
/// checks them with the same).
|
||||
/// target(e): crate::shares::target(e, money).amount: what the shares
|
||||
/// split (rules.md B-35); a reversal's is its original's negated.
|
||||
/// split (BS-partner-3); a reversal's is its original's negated.
|
||||
/// INVARIANTS:
|
||||
/// 1. Refuses when `sources.cash` is empty (name the books' cash
|
||||
/// accounts; never every asset: P3 review R5), and, with no
|
||||
@@ -899,7 +899,7 @@ fn bounds(
|
||||
/// makes a worksheet as of a day: the payments from January 1
|
||||
/// through it (§6041(a) and §6041A(a)(2) count what is paid "in any
|
||||
/// calendar year"; a CPA package as of June 30 shows the year to
|
||||
/// date, rules.md B-33).
|
||||
/// date, BS-statement-4).
|
||||
/// 3. An entry naming at most one party: the vendor's amounts are
|
||||
/// buckets(e).
|
||||
/// 4. An entry naming several parties (one of them the vendor's party,
|
||||
|
||||
@@ -15,10 +15,10 @@
|
||||
//! ```text
|
||||
//! GOAL: every payment's method is recorded once, plainly, so the 1099
|
||||
//! worksheet never guesses whether a payment was by card.
|
||||
//! SOURCE: docs/spec/rules.md B-19 (Treas. Reg. §1.6041-1(a)(1)(iv),
|
||||
//! SOURCE: BS-1099-1 (Treas. Reg. §1.6041-1(a)(1)(iv),
|
||||
//! §1.6050W-1(b)(1), (b)(3), (c)(3); Instructions for Form 1099-K:
|
||||
//! automated clearing houses are not payment networks;
|
||||
//! sources/irs-1099-payment-method.md); plan/served.md 4.9, 5.2.
|
||||
//! docs/spec/sources/irs-1099-payment-method.md); plan/served.md 4.9, 5.2.
|
||||
//! INVARIANTS:
|
||||
//! 1. A label is one line, at most settings::MAX_TEXT characters, holds
|
||||
//! no full TIN, and is unique among instruments (ignoring case and
|
||||
|
||||
@@ -24,8 +24,8 @@ pub enum EntryStatus {
|
||||
}
|
||||
|
||||
/// Where a draft entry stands (plan P4, `drafts_v2`): still being built,
|
||||
/// or finished and waiting on the document that supports it (rules.md
|
||||
/// B-43). Meaningful while the entry is a draft; a posted entry keeps
|
||||
/// or finished and waiting on the document that supports it (
|
||||
/// BS-entry-5). Meaningful while the entry is a draft; a posted entry keeps
|
||||
/// the state it had and nothing reads it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum DraftState {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! beginning capital, contributions (cash and property separately),
|
||||
//! their share of income, distributions, ending capital.
|
||||
//! SOURCE: Form 1065 Schedule K-1 instructions, Item L ("Partner's capital
|
||||
//! account analysis", on the partnership's books); B-13;
|
||||
//! account analysis", on the partnership's books); BS-partner-1;
|
||||
//! DECISION (owner, 2026-10-15): the CPA package carries a K-1
|
||||
//! worksheet per member.
|
||||
//! INVARIANTS:
|
||||
@@ -37,7 +37,7 @@
|
||||
//! (kernel::apportion, ties to the earlier member): each takes at
|
||||
//! most its own credit, and the split depends on the order the
|
||||
//! members are given only for a tied leftover cent (never on line
|
||||
//! order). Joint property is joint (B-13's
|
||||
//! order). Joint property is joint (BS-partner-1's
|
||||
//! shares, the house convention that joint funds are 50/50).
|
||||
//! 5. k1_detail's lines explain each row: per member, its cash lines
|
||||
//! sum to contributions_cash, its property lines to
|
||||
@@ -434,7 +434,7 @@ mod tests {
|
||||
(a, Side::Credit, "1000"),
|
||||
]);
|
||||
// A hand line on receivables: only books an earlier version wrote
|
||||
// hold one now (the control guard, rules.md B-38), so replayed.
|
||||
// hold one now (the control guard, BS-arap-2), so replayed.
|
||||
crate::parties::replaying(|| post(&[(ar, Side::Debit, "200"), (b, Side::Credit, "200")]));
|
||||
post(&[(exp, Side::Debit, "50"), (b, Side::Credit, "50")]);
|
||||
let members = [
|
||||
|
||||
@@ -27,7 +27,7 @@ pub trait Amount: Copy + Ord {
|
||||
fn from_u32(n: u32) -> Option<Self>;
|
||||
/// `self * rhs`, or `None` when it cannot be represented exactly.
|
||||
///
|
||||
/// A quantity times a unit price (a document line, B-39) is the one
|
||||
/// A quantity times a unit price (a document line, BS-arap-3) is the one
|
||||
/// use: it never rounds.
|
||||
fn checked_mul(self, rhs: Self) -> Option<Self>;
|
||||
/// `self / rhs` exactly, or `None` when `rhs` is zero or the quotient
|
||||
@@ -38,8 +38,8 @@ pub trait Amount: Copy + Ord {
|
||||
/// [`Decimal`] dollars), ties away from zero; never a negative zero.
|
||||
/// `None` when `rhs` is zero or the quotient cannot be represented.
|
||||
///
|
||||
/// The one use is a tax category's deductible amount (rules.md B-32,
|
||||
/// B-21), whose shares are added exactly and rounded once, never
|
||||
/// The one use is a tax category's deductible amount (BS-ledger-11,
|
||||
/// BS-entry-3), whose shares are added exactly and rounded once, never
|
||||
/// share by share.
|
||||
fn checked_div_round_cent(self, rhs: Self) -> Option<Self>;
|
||||
/// `self` rounded to a whole multiple of `step`, in `mode`; `None`
|
||||
@@ -330,7 +330,7 @@ pub fn net<T: Amount>(lines: impl IntoIterator<Item = (Side, T)>) -> Option<T> {
|
||||
/// ```text
|
||||
/// GOAL: an early-payment discount never takes more than its percentage
|
||||
/// says, in exact money.
|
||||
/// SOURCE: docs/spec/rules.md B-39 INVARIANT 2, B-42; plan/served.md
|
||||
/// SOURCE: BS-arap-3 INVARIANT 2, BS-arap-6; plan/served.md
|
||||
/// 8.3.13; CHOICE: the gross method, A-8 (the discount is
|
||||
/// booked when taken, never estimated).
|
||||
/// INVARIANTS:
|
||||
@@ -360,14 +360,14 @@ pub struct Settlement<T> {
|
||||
pub deposit: T,
|
||||
}
|
||||
|
||||
/// The arithmetic of a settlement (rules.md B-42; plan P4b S6): each
|
||||
/// The arithmetic of a settlement (BS-arap-6; plan P4b S6): each
|
||||
/// document's cash and discount, and the processor's fee withheld from the
|
||||
/// cash that reaches the bank.
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: a settlement is exact: what the documents are settled by is the
|
||||
/// cash plus the discounts, and the deposit is the cash less the fee.
|
||||
/// SOURCE: docs/spec/rules.md B-42; plan/served.md 8.3.6, 8.3.13 (B-42);
|
||||
/// SOURCE: BS-arap-6; plan/served.md 8.3.6, 8.3.13 (BS-arap-6);
|
||||
/// CONVENTION; DECISION: the gross method (A-8) and the fee's
|
||||
/// gross presentation (A-4).
|
||||
/// INVARIANTS:
|
||||
@@ -412,7 +412,7 @@ pub fn settle<T: Amount>(cash: &[T], discounts: &[T], fee: T) -> Option<Settleme
|
||||
/// ```text
|
||||
/// GOAL: a line's quantity times its unit price is the amount it posts,
|
||||
/// to the last decimal place.
|
||||
/// SOURCE: docs/spec/rules.md B-39; plan/served.md 8.3.4 ("kernel::
|
||||
/// SOURCE: BS-arap-3; plan/served.md 8.3.4 ("kernel::
|
||||
/// line_amount(q, u) == amount exactly").
|
||||
/// INVARIANTS:
|
||||
/// 1. Some(p) gives p = quantity x unit_price exactly.
|
||||
@@ -431,8 +431,8 @@ pub fn line_amount<T: Amount>(quantity: T, unit_price: T) -> Option<T> {
|
||||
/// ```text
|
||||
/// GOAL: a category's deductible amount is its exact shares added and
|
||||
/// rounded once, never a sum of rounded shares.
|
||||
/// SOURCE: docs/spec/rules.md B-32 (CHOICE: owner, 2026-11-07, D-67) and
|
||||
/// B-21 (Form 1065 instructions: "include cents when adding the
|
||||
/// SOURCE: BS-ledger-11 (CHOICE: owner, 2026-11-07, D-67) and
|
||||
/// BS-entry-3 (Form 1065 instructions: "include cents when adding the
|
||||
/// amounts and round off only the total"); plan/served.md 10.1.
|
||||
/// INVARIANTS:
|
||||
/// 1. On Some(a), a is the exact sum S = Σ(book_i × percent_i ÷ 100)
|
||||
@@ -579,7 +579,7 @@ pub fn credit_line<T: Amount>(credit: T) -> Option<(Side, T)> {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 1099 payments: where each payment line goes (rules.md B-19)
|
||||
// 1099 payments: where each payment line goes (BS-1099-1)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A line's role in a payment to a vendor, from its account.
|
||||
@@ -646,11 +646,11 @@ impl Bucket {
|
||||
/// GOAL: every payment line to a vendor counts toward its 1099, is a card
|
||||
/// or payment-network payment (Form 1099-K), or is unknown; never
|
||||
/// guessed.
|
||||
/// SOURCE: docs/spec/rules.md B-19 (Treas. Reg. §1.6041-1(a)(1)(iv): a
|
||||
/// SOURCE: BS-1099-1 (Treas. Reg. §1.6041-1(a)(1)(iv): a
|
||||
/// transaction reportable under §6050W is not reported under
|
||||
/// §6041; §1.6041-1(e)(1): a member writing a check at the
|
||||
/// company's direction doesn't make the member the payor;
|
||||
/// sources/irs-1099-payment-method.md); DECISION D-40 (owner,
|
||||
/// docs/spec/sources/irs-1099-payment-method.md); DECISION D-40 (owner,
|
||||
/// 2026-10-20: a bank payment with no method recorded counts).
|
||||
/// INVARIANTS (first match wins):
|
||||
/// 1. The tag names this line's account: Card for a card or network,
|
||||
@@ -693,7 +693,7 @@ pub fn split_payment<T: Amount>(lines: &[(Option<Bucket>, Side, T)]) -> Option<[
|
||||
/// ```text
|
||||
/// GOAL: a card bill paid from the bank, a member reimbursed, or a loan
|
||||
/// paid down never counts toward a vendor's 1099.
|
||||
/// SOURCE: docs/spec/rules.md B-19 (26 U.S.C. §6041(a): payments made to
|
||||
/// SOURCE: BS-1099-1 (26 U.S.C. §6041(a): payments made to
|
||||
/// the payee; P3 review R1, 2026-10-20).
|
||||
/// INVARIANTS:
|
||||
/// 1. The buckets' sum P is kept exactly.
|
||||
@@ -758,8 +758,8 @@ pub fn plug_last<T: Amount>(whole: T, parts: &mut [T]) -> Option<()> {
|
||||
/// ```text
|
||||
/// GOAL: split a whole into parts, each a whole number of units where
|
||||
/// possible, summing to the whole exactly, without favoring anyone.
|
||||
/// SOURCE: docs/spec/rules.md B-13 (shares: 26 U.S.C. §704(a); cent
|
||||
/// rounding: DECISION, owner 2026-10-13), B-21 (exact totals).
|
||||
/// SOURCE: BS-partner-1 (shares: 26 U.S.C. §704(a); cent
|
||||
/// rounding: DECISION, owner 2026-10-13), BS-entry-3 (exact totals).
|
||||
/// INVARIANTS:
|
||||
/// 1. MUST make the parts sum to `whole` exactly.
|
||||
/// 2. MUST change each part by zero or one unit (the first in order
|
||||
@@ -835,7 +835,7 @@ pub fn apportion<T: Amount>(whole: T, parts: &mut [T], remainders: &[T], unit: T
|
||||
/// ```text
|
||||
/// GOAL: members' running totals that never drift a unit from their
|
||||
/// exact shares, whatever earlier closes did.
|
||||
/// SOURCE: docs/spec/rules.md B-13 (shares: 26 U.S.C. §704(a); capital
|
||||
/// SOURCE: BS-partner-1 (shares: 26 U.S.C. §704(a); capital
|
||||
/// accounts carry the allocations: Treas. Reg.
|
||||
/// §1.704-1(b)(2)(iv)(b); cent rounding: DECISION, owner
|
||||
/// 2026-10-13; counted from the first close: D-10, 2026-10-16).
|
||||
@@ -880,7 +880,7 @@ pub fn apportion_cumulative<T: Amount>(
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Where a line falls on the statement of cash flows (rules.md B-14 rule
|
||||
/// Where a line falls on the statement of cash flows (BS-statement-3 rule
|
||||
/// 2): a cash account, or one of the three sections.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub enum Flow {
|
||||
@@ -895,8 +895,8 @@ pub enum Flow {
|
||||
}
|
||||
|
||||
impl Flow {
|
||||
/// The three sections, in the order cash is applied to them (rules.md
|
||||
/// B-14 rule 3): operating, investing, financing.
|
||||
/// The three sections, in the order cash is applied to them (
|
||||
/// BS-statement-3 rule 3): operating, investing, financing.
|
||||
pub const SECTIONS: [Flow; 3] = [Flow::Operating, Flow::Investing, Flow::Financing];
|
||||
}
|
||||
|
||||
@@ -938,7 +938,7 @@ pub fn take<T: Amount>(remaining: T, movement: T) -> Option<T> {
|
||||
/// ```text
|
||||
/// GOAL: split an entry's cash among the parts it settled, without
|
||||
/// inventing or losing any.
|
||||
/// SOURCE: rules.md B-14 rule 3 (ASC 230-10-50-5: only the cash portion
|
||||
/// SOURCE: BS-statement-3 rule 3 (ASC 230-10-50-5: only the cash portion
|
||||
/// of a part-cash transaction is a cash flow; the order is a
|
||||
/// CONVENTION, the ASC is silent).
|
||||
/// INVARIANTS:
|
||||
@@ -965,7 +965,7 @@ pub fn apply_cash<T: Amount>(cash: T, movements: &[T], applied: &mut [T]) -> Opt
|
||||
(remaining == T::ZERO).then_some(())
|
||||
}
|
||||
|
||||
/// An entry's cash flows (rules.md B-14 rule 3): the net movement of its
|
||||
/// An entry's cash flows (BS-statement-3 rule 3): the net movement of its
|
||||
/// cash lines, applied to the sections moving against it in the order
|
||||
/// operating, investing, financing, each up to its own movement; what is
|
||||
/// left of a section's movement is the part no cash settled. `None` when
|
||||
@@ -1036,7 +1036,7 @@ fn credits_and_debits<T: Amount>(movements: &[T]) -> Option<(T, T)> {
|
||||
}
|
||||
|
||||
/// Which way money a member or a lender handled for the company went
|
||||
/// (rules.md B-14 rule 11, D-42).
|
||||
/// (BS-statement-3 rule 11, D-42).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum OnBehalf {
|
||||
/// Paid for the company: sources credited (borrowed, contributed)
|
||||
@@ -1058,8 +1058,8 @@ impl OnBehalf {
|
||||
}
|
||||
|
||||
/// What a member or a lender paid, or received, for the company with no
|
||||
/// cash account moving: a constructive receipt and disbursement (rules.md
|
||||
/// B-14 rule 11, D-42). `sources` are what is left unsettled of the
|
||||
/// cash account moving: a constructive receipt and disbursement (
|
||||
/// BS-statement-3 rule 11, D-42). `sources` are what is left unsettled of the
|
||||
/// entry's kinds that can pay or receive for the company (a financing
|
||||
/// liability, a member's equity), `uses` of the kinds they can pay or
|
||||
/// receive for, each debit-positive. [`OnBehalf::Paid`]: `amount =
|
||||
@@ -1075,7 +1075,7 @@ impl OnBehalf {
|
||||
/// GOAL: show money a member or lender handled for the company as the
|
||||
/// company's own, borrowed (or contributed) and spent, without
|
||||
/// inventing or losing a cent.
|
||||
/// SOURCE: rules.md B-14 rule 11 (D-42; ASC 230 is silent, PwC Viewpoint
|
||||
/// SOURCE: BS-statement-3 rule 11 (D-42; ASC 230 is silent, PwC Viewpoint
|
||||
/// FSP 6.9.3.1, Deloitte DART Roadmap 7.2, BDO Blueprint 3.4).
|
||||
/// INVARIANTS:
|
||||
/// 1. The parts net to zero: Σ from + Σ to = 0, so the entry's cash
|
||||
@@ -1108,7 +1108,7 @@ pub fn constructive<T: Amount>(
|
||||
}
|
||||
|
||||
/// How much of an entry is an exchange inside investing and financing
|
||||
/// that no cash settled (rules.md B-14 rule 7, ASC 230-10-50-4: debt
|
||||
/// that no cash settled (BS-statement-3 rule 7, ASC 230-10-50-4: debt
|
||||
/// converted to equity, one asset traded for another). `debits` and
|
||||
/// `credits` are the net debits and net credits of the entry's investing
|
||||
/// and financing balance-sheet accounts (each account netted first; both
|
||||
@@ -1123,7 +1123,7 @@ pub fn exchanged<T: Amount>(debits: T, credits: T, inflow: T, outflow: T) -> Opt
|
||||
Some(d.min(c).max(T::ZERO))
|
||||
}
|
||||
|
||||
/// Which way an entry moved value with its parties (rules.md B-35).
|
||||
/// Which way an entry moved value with its parties (BS-partner-3).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Direction {
|
||||
/// The company paid the party, or gave it value: a line on the
|
||||
@@ -1172,7 +1172,7 @@ impl Direction {
|
||||
}
|
||||
|
||||
/// What an entry's parties split, and what of it counts in their totals
|
||||
/// (rules.md B-35).
|
||||
/// (BS-partner-3).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PartyTarget<T> {
|
||||
/// The whole, signed as a line on the parties' own account would be
|
||||
@@ -1216,7 +1216,7 @@ fn least<T: Amount>(a: T, b: T) -> T {
|
||||
if a < b { a } else { b }
|
||||
}
|
||||
|
||||
/// What an entry's parties split and what of it counts (rules.md B-35
|
||||
/// What an entry's parties split and what of it counts (BS-partner-3
|
||||
/// item 3, every case but a close and a reversal, which the caller
|
||||
/// handles: a close is its parties' own-account movement with direction
|
||||
/// neither, a reversal is [`reverse_target`] of its original's).
|
||||
@@ -1227,7 +1227,7 @@ fn least<T: Amount>(a: T, b: T) -> T {
|
||||
/// money or as property, so a property contribution and its
|
||||
/// reversal never read alike, and a promise is never counted as if
|
||||
/// it were paid.
|
||||
/// SOURCE: rules.md B-35 (B-2 signs; DECISION, owner, 2026-10-20: a
|
||||
/// SOURCE: BS-partner-3 (BS-entry-2 signs; DECISION, owner, 2026-10-20: a
|
||||
/// member's entry counts what moved their capital, money is cash,
|
||||
/// cards, the members' financing and loans, and a liability credit
|
||||
/// never counts as paying that liability's own creditor; Helvering
|
||||
@@ -1321,7 +1321,7 @@ pub fn party_target<T: Amount>(
|
||||
})
|
||||
}
|
||||
|
||||
/// A reversal's target from its original's (rules.md B-35 item 3; B-9: a
|
||||
/// A reversal's target from its original's (BS-partner-3 item 3; BS-ledger-5: a
|
||||
/// correction is the opposite entry): every amount negated (never to a
|
||||
/// negative zero), paid and received swapped. An involution. `None` past
|
||||
/// the type's range.
|
||||
@@ -1495,10 +1495,10 @@ fn round_to_unit<T: Units>(num: T, den: T, unit: T) -> Option<T> {
|
||||
/// GOAL: how much of a total a span of days has used up by a given day,
|
||||
/// each day of a month bearing the same share, the whole total
|
||||
/// reached on the span's last day and never before.
|
||||
/// SOURCE: docs/spec/rules.md B-15 (straight line, partial months by days;
|
||||
/// SOURCE: BS-asset-1 (straight line, partial months by days;
|
||||
/// ASC 360-10-35-4: "systematic and rational", as equitably as
|
||||
/// possible to the periods served), B-16 (daily schedules, D-11),
|
||||
/// B-21 (exact totals).
|
||||
/// possible to the periods served), BS-prepaid-1 (daily schedules, D-11),
|
||||
/// BS-entry-3 (exact totals).
|
||||
/// INVARIANTS (W = months × MONTH_L, m = part.month_days, d = part.days):
|
||||
/// 1. Not the last part: round(total × (before + k × MONTH_L / m) / W):
|
||||
/// the monthly rate total/months times the days held over the days
|
||||
@@ -1520,8 +1520,8 @@ fn round_to_unit<T: Units>(num: T, den: T, unit: T) -> Option<T> {
|
||||
/// W), or any product overflows:
|
||||
/// - SHOULD return None
|
||||
/// - NEVER panic
|
||||
/// BECAUSE a figure the books can't compute is refused (rules.md
|
||||
/// B-28), and symbolic parts are not a calendar.
|
||||
/// BECAUSE a figure the books can't compute is refused (
|
||||
/// BS-entry-4), and symbolic parts are not a calendar.
|
||||
/// 2. IF 12,000.00 over 12 months from Jan 1, through Dec 15 (the last
|
||||
/// part, 31 days, before = 11 months):
|
||||
/// - SHOULD be 11,000.00 + 1,000.00 × 15/31 = 11,483.87
|
||||
@@ -1584,7 +1584,7 @@ pub fn prorated_through<T: Units>(
|
||||
/// ```text
|
||||
/// GOAL: one month's posting of a span spread by day (depreciation,
|
||||
/// daily prepaid and deferred-revenue schedules).
|
||||
/// SOURCE: docs/spec/rules.md B-15, B-16 (D-11), B-21; plan/served.md P3
|
||||
/// SOURCE: BS-asset-1, BS-prepaid-1 (D-11), BS-entry-3; plan/served.md P3
|
||||
/// defect 9 (one shared prorate_by_days, Kani: parts sum to the
|
||||
/// total, each is days × rate within one unit, the last absorbs
|
||||
/// the remainder).
|
||||
@@ -1651,7 +1651,7 @@ pub fn prorate_by_days<T: Units>(
|
||||
/// SOURCE: plan/served.md P3 "Settled in design" (2026-10-20): a month of
|
||||
/// depreciation skipped is caught up in the month the run is made
|
||||
/// (an immaterial miss; a material one is restated, ASC 250);
|
||||
/// docs/spec/rules.md B-15.
|
||||
/// BS-asset-1.
|
||||
/// INVARIANTS:
|
||||
/// 1. The result is >= 0.
|
||||
/// 2. Whenever every posted[i] <= scheduled[i], posted[i] + result <=
|
||||
@@ -1707,7 +1707,7 @@ pub fn catch_ups<T: Amount>(scheduled: &[T], posted: &[T], out: &mut [T]) -> Opt
|
||||
/// ```text
|
||||
/// GOAL: a disposal clears exactly what the schedule says was used up
|
||||
/// through its day, whatever the runs posted.
|
||||
/// SOURCE: docs/spec/rules.md B-15 (a disposed asset depreciates through
|
||||
/// SOURCE: BS-asset-1 (a disposed asset depreciates through
|
||||
/// its disposal day); Ledger::dispose_asset INVARIANT 1 (gain =
|
||||
/// proceeds − book value at the disposal date).
|
||||
/// ```
|
||||
@@ -1737,7 +1737,7 @@ pub struct BasisFigures<T> {
|
||||
/// ```text
|
||||
/// GOAL: the three tax figures of an asset, each named for what it is,
|
||||
/// from one function the register, the tools and the viewer share.
|
||||
/// SOURCE: docs/spec/rules.md B-25: IRC §1012(a) (cost); IRC §723 (the
|
||||
/// SOURCE: BS-asset-4: IRC §1012(a) (cost); IRC §723 (the
|
||||
/// contributor's adjusted basis carries over); Treas. Reg.
|
||||
/// §1.168(i)-4(b)(1) (property converted from personal use: "the
|
||||
/// lesser of its fair market value or its adjusted depreciable
|
||||
@@ -1782,12 +1782,12 @@ pub fn basis_figures<T: Amount>(
|
||||
}
|
||||
|
||||
/// A project's unrecovered cost from its tagged revenue and expenses to
|
||||
/// date: what it would take to be repaid in full (rules.md B-37 item 4).
|
||||
/// date: what it would take to be repaid in full (BS-statement-5 item 4).
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: the "if repaid" figure of work done on spec, from one function
|
||||
/// the tools, the viewer and bookspec share.
|
||||
/// SOURCE: docs/spec/rules.md B-37 item 4 (ASC 450-30-25-1: a hoped-for
|
||||
/// SOURCE: BS-statement-5 item 4 (ASC 450-30-25-1: a hoped-for
|
||||
/// payment is a gain contingency, never recorded before it is
|
||||
/// received; so this is a figure, never a receivable).
|
||||
/// INVARIANTS:
|
||||
@@ -1826,7 +1826,7 @@ pub enum Bounds {
|
||||
/// ```text
|
||||
/// GOAL: one definition of "a document is never overpaid and never owes
|
||||
/// more than it is for", at every date, not only at the end.
|
||||
/// SOURCE: docs/spec/rules.md B-38 INVARIANT 2 (0 <= outstanding(d, D)
|
||||
/// SOURCE: BS-arap-2 INVARIANT 2 (0 <= outstanding(d, D)
|
||||
/// <= total(d) at every D); plan/served.md P4b.3 (Bounds).
|
||||
/// INVARIANTS:
|
||||
/// 1. Within exactly when every prefix sum of `deltas` is within
|
||||
@@ -1873,7 +1873,7 @@ fn out_of_bounds<T: Amount>(total: T, running: T) -> Option<(T, bool)> {
|
||||
/// GOAL: a command never puts a document out of bounds, yet books an
|
||||
/// earlier version left out of bounds (a void under a payment that
|
||||
/// stands) take the step that mends them.
|
||||
/// SOURCE: docs/spec/rules.md B-38 INVARIANT 2, B-28 (replay accepts what
|
||||
/// SOURCE: BS-arap-2 INVARIANT 2, BS-entry-4 (replay accepts what
|
||||
/// was written; the bound is the commands'); plan/served.md
|
||||
/// P4b.14 item 3 (the remedy: reverse the payment).
|
||||
/// INVARIANTS:
|
||||
@@ -1918,7 +1918,7 @@ pub fn bounds_kept<T: Amount>(total: T, before: &[T], after: &[T]) -> Bounds {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// rules.md B-14 rule 3, by hand. Equipment 1,000 for 300 cash and a
|
||||
/// BS-statement-3 rule 3, by hand. Equipment 1,000 for 300 cash and a
|
||||
/// 700 note: investing takes the 300, the note's 700 and the rest of
|
||||
/// the equipment's are the noncash part.
|
||||
#[test]
|
||||
@@ -1964,7 +1964,7 @@ mod tests {
|
||||
assert_eq!(apply_cash(10, &[-3], &mut out), None);
|
||||
}
|
||||
|
||||
/// The exchange measure (rules.md B-14 rule 7) on the review's
|
||||
/// The exchange measure (BS-statement-3 rule 7) on the review's
|
||||
/// hand-checked cases.
|
||||
#[test]
|
||||
fn exchanged_matches_the_hand_checked_cases() {
|
||||
@@ -1986,7 +1986,7 @@ mod tests {
|
||||
assert_eq!(exchanged(1000i64, 1000, 1000, 1000), Some(0));
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 11 (D-42), by hand.
|
||||
/// BS-statement-3 rule 11 (D-42), by hand.
|
||||
#[test]
|
||||
fn constructive_pays_and_receives_for_the_company() {
|
||||
use OnBehalf::{Paid, Received};
|
||||
@@ -2339,7 +2339,7 @@ mod tests {
|
||||
assert!(!i64::MIN.in_line_range());
|
||||
}
|
||||
|
||||
/// B-9: a reversal flips every side and keeps accounts and amounts, so
|
||||
/// BS-ledger-5: a reversal flips every side and keeps accounts and amounts, so
|
||||
/// with the original it nets every account to zero.
|
||||
#[test]
|
||||
fn a_reversal_flips_every_line_and_nets_to_zero() {
|
||||
|
||||
@@ -54,7 +54,7 @@ use rust_decimal::Decimal;
|
||||
/// from ISO 4217), and its CHOICE BS-ledger-14
|
||||
/// "book-in-the-smallest-unit" (the owner, 2026-10-13: book in
|
||||
/// the smallest unit, half away from zero); wanderbooks
|
||||
/// docs/spec/claims/ledger.md B-3 states the same pick. The
|
||||
/// docs/spec/claims/ledger.md BS-ledger-1 states the same pick. The
|
||||
/// rounding itself is kernel::round_step (BS-ledger-1,
|
||||
/// BS-entry-3); owner decision D-69 (the laws live once, in
|
||||
/// bookspec's Lean).
|
||||
@@ -102,7 +102,7 @@ pub fn fx_booked<T: Amount>(foreign: T, rate: T, step: T, mode: Rounding) -> Opt
|
||||
/// [`fx_booked`] at a currency's minor unit, on `Decimal`: the spelling
|
||||
/// `Ledger::add_line_fx` books through. A currency ISO 4217 gives no
|
||||
/// minor unit (gold, SDRs) books the exact product, as `round_minor`
|
||||
/// has always done (B-3). The result's scale is the pre-kernel
|
||||
/// has always done (BS-ledger-1). The result's scale is the pre-kernel
|
||||
/// computation's: `round_places` keeps an amount already at or under
|
||||
/// the minor places unchanged, and otherwise carries exactly the minor
|
||||
/// places (a booked 1.50 prints "1.50", never "1.5000").
|
||||
|
||||
@@ -8,58 +8,58 @@
|
||||
//! laws it implements hold for books of any size. See
|
||||
//! `docs/verification.md` for which proof covers which law.
|
||||
//!
|
||||
//! The laws, in the order they appear (each traced to its authority in
|
||||
//! `docs/spec/rules.md`):
|
||||
//! The laws, in the order they appear (each traced to its bookspec rule
|
||||
//! and to wanderbooks' claim in `docs/spec/claims/`):
|
||||
//!
|
||||
//! * a line's signed amount is `+amount` for a debit, `-amount` for a credit
|
||||
//! (B-2);
|
||||
//! (BS-entry-2);
|
||||
//! * an entry is acceptable when it has two or more lines, every amount is
|
||||
//! positive and in range, and its debits equal its credits exactly (B-1,
|
||||
//! B-2, B-21);
|
||||
//! * an acceptable entry nets to zero, account by account summed (B-1);
|
||||
//! positive and in range, and its debits equal its credits exactly (BS-entry-1,
|
||||
//! BS-entry-2, BS-entry-3);
|
||||
//! * an acceptable entry nets to zero, account by account summed (BS-entry-1);
|
||||
//! * a reversal flips every side, so it is acceptable exactly when the
|
||||
//! original is, and the two together net every account to zero (B-9);
|
||||
//! original is, and the two together net every account to zero (BS-ledger-5);
|
||||
//! * an account's balance is its movement read on its normal side, so the
|
||||
//! balances satisfy the accounting equation whenever movements net to
|
||||
//! zero (B-5, B-7);
|
||||
//! zero (BS-ledger-3, BS-statement-2);
|
||||
//! * a trial balance puts each movement in exactly one column, so its
|
||||
//! columns differ by the net of all movements (B-6);
|
||||
//! * a closing line zeroes the account it closes (B-11);
|
||||
//! columns differ by the net of all movements (BS-statement-1);
|
||||
//! * a closing line zeroes the account it closes (BS-period-1);
|
||||
//! * a payment to a vendor splits, line by line, into what counts toward
|
||||
//! its 1099, what a card or payment network paid, and what is unknown,
|
||||
//! and money moved between the company's own sources nets out (B-19);
|
||||
//! and money moved between the company's own sources nets out (BS-1099-1);
|
||||
//! * an early-payment discount never exceeds its stated percentage of the
|
||||
//! total, and a document line's amount is exactly its quantity times its
|
||||
//! unit price, neither rounded (B-39);
|
||||
//! unit price, neither rounded (BS-arap-3);
|
||||
//! * an allocation's parts sum to the whole, to the last unit, by largest
|
||||
//! remainder (B-13);
|
||||
//! remainder (BS-partner-1);
|
||||
//! * a cumulative allocation hands out exactly the new amount, and leaves
|
||||
//! each running total one allocation of everything allocated, so it never
|
||||
//! drifts a unit from its exact share (B-13);
|
||||
//! drifts a unit from its exact share (BS-partner-1);
|
||||
//! * an entry's cash is applied to the sections of the statement of cash
|
||||
//! flows moving against it, in a fixed order, each up to its own
|
||||
//! movement: the parts sum to the entry's cash, what no cash settled sums
|
||||
//! to zero, and a reversal's parts are the original's negated (B-14);
|
||||
//! to zero, and a reversal's parts are the original's negated (BS-statement-3);
|
||||
//! * what a member or lender paid or received for the company, with no
|
||||
//! cash account moving, is split among the kinds it settled, netting to
|
||||
//! zero, and mirrored by a reversal (B-14 rule 11);
|
||||
//! zero, and mirrored by a reversal (BS-statement-3 rule 11);
|
||||
//! * a party's part of an entry is signed as a line on the party's own
|
||||
//! account would be, a reversal's is its original's negated, and what of
|
||||
//! it counts as money or as property never exceeds it (B-35);
|
||||
//! * a span prorated by days (depreciation, B-15; daily schedules, B-16)
|
||||
//! it counts as money or as property never exceeds it (BS-partner-3);
|
||||
//! * a span prorated by days (depreciation, BS-asset-1; daily schedules, BS-prepaid-1)
|
||||
//! splits into parts that sum to its total, each but the last its days
|
||||
//! times the monthly rate within one unit, the last the remainder;
|
||||
//! * a catch-up run brings the books to the schedule without ever carrying
|
||||
//! more than it says at a month end already posted (B-15), and a
|
||||
//! more than it says at a month end already posted (BS-asset-1), and a
|
||||
//! disposal trues what the books carry up or down to the schedule;
|
||||
//! * an asset's basis figures follow from its basis rule and facts: the
|
||||
//! §723 basis is the contributor's adjusted basis, the depreciable basis
|
||||
//! the cost, that basis, or the lesser of it and fair market value, and
|
||||
//! the §704(c) built-in gain is fair market value less the §723 basis
|
||||
//! (B-25);
|
||||
//! (BS-asset-4);
|
||||
//! * a tax category's deductible amount adds its accounts' exact shares and
|
||||
//! rounds once to the cent, half away from zero, never share by share
|
||||
//! (B-32, B-21).
|
||||
//! (BS-ledger-11, BS-entry-3).
|
||||
//!
|
||||
//! The kernel is a module directory so each kernel-sweep unit adds its
|
||||
//! arithmetic in a file of its own (`fx`, `round`, `allocate`, `total`,
|
||||
|
||||
@@ -14,7 +14,7 @@ use rust_decimal::Decimal;
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Rounding {
|
||||
/// Nearest multiple; an exact half rounds away from zero
|
||||
/// (2.5 -> 3, -2.5 -> -3). The FX booking rule (B-3).
|
||||
/// (2.5 -> 3, -2.5 -> -3). The FX booking rule (BS-ledger-1).
|
||||
HalfAwayFromZero,
|
||||
/// Nearest multiple; an exact half rounds to the even multiple
|
||||
/// (2.5 -> 2, 3.5 -> 4). Rust's `Decimal::round_dp`.
|
||||
@@ -30,12 +30,12 @@ pub enum Rounding {
|
||||
/// ```text
|
||||
/// GOAL: one rounding primitive: money is rounded to a whole multiple of a
|
||||
/// unit, once, with the mode named at the call.
|
||||
/// SOURCE: docs/spec/claims/ledger.md B-3 (a ledger in one money holds no
|
||||
/// SOURCE: docs/spec/claims/ledger.md BS-ledger-1 (a ledger in one money holds no
|
||||
/// fractions of its smallest unit; FX books the base currency's
|
||||
/// minor unit, half away from zero), claims/entry.md B-21 (exact
|
||||
/// minor unit, half away from zero), docs/spec/claims/entry.md BS-entry-3 (exact
|
||||
/// amounts in the books; round only where a rule says to), and
|
||||
/// claims/ledger.md B-32; the call sites' own rules (B-13, B-14,
|
||||
/// B-15, B-16, B-19, B-35, B-36, B-37); owner decision D-69 (the
|
||||
/// docs/spec/claims/ledger.md BS-ledger-11; the call sites' own rules (BS-partner-1, BS-statement-3,
|
||||
/// BS-asset-1, BS-prepaid-1, BS-1099-1, BS-partner-3, BS-partner-4, BS-statement-5); owner decision D-69 (the
|
||||
/// laws live once, in bookspec's Lean).
|
||||
/// INVARIANTS:
|
||||
/// 1. Some(r) is a whole multiple of step: r = n x step for an integer
|
||||
@@ -96,7 +96,7 @@ pub fn round_places(amount: Decimal, places: u32, mode: Rounding) -> Option<Deci
|
||||
/// `amount` rounded to whole `currency` minor units in `mode`: cents for
|
||||
/// USD, whole yen for JPY, thousandths for KWD. A currency ISO 4217 gives
|
||||
/// no minor unit (gold, SDRs) is returned exactly, as the FX booking rule
|
||||
/// has always done (B-3).
|
||||
/// has always done (BS-ledger-1).
|
||||
pub fn round_minor(amount: Decimal, currency: Currency, mode: Rounding) -> Option<Decimal> {
|
||||
match currency.minor_units() {
|
||||
Some(places) => round_places(amount, places, mode),
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! The sum of a collection of money figures, in one place. A raw `Decimal`
|
||||
//! `+`, `+=` or `.sum()` panics at `Decimal::MAX`; these return `None`
|
||||
//! instead, so the caller can refuse with `TooLargeToCompute` and never
|
||||
//! crash a book (rules.md B-28: a replayed journal line is accepted "of
|
||||
//! crash a book (BS-entry-4: a replayed journal line is accepted "of
|
||||
//! any size", so a restored figure is the realistic path to the edge).
|
||||
//! The signed sum of `(Side, amount)` lines is [`super::net`] and the pair
|
||||
//! of columns [`super::totals`]; they were here first and stay the one
|
||||
@@ -17,8 +17,8 @@ use super::Amount;
|
||||
/// ```text
|
||||
/// GOAL: a book's or report's total is the exact sum of its figures, or
|
||||
/// refused; no total is ever rounded, wrapped or a crash.
|
||||
/// SOURCE: docs/spec/rules.md B-21 (amounts are exact; rounding is
|
||||
/// confined to returns), B-28 (replayed lines are accepted "of any
|
||||
/// SOURCE: BS-entry-3 (amounts are exact; rounding is
|
||||
/// confined to returns), BS-entry-4 (replayed lines are accepted "of any
|
||||
/// size"; no input may reach a panic); bookspec BS-entry-3,
|
||||
/// BS-entry-4; CONVENTION.
|
||||
/// INVARIANTS:
|
||||
@@ -49,7 +49,7 @@ pub fn total<T: Amount>(values: impl IntoIterator<Item = T>) -> Option<T> {
|
||||
/// ```text
|
||||
/// GOAL: the sum of a mapped field (a row's amount, a member's share) is
|
||||
/// the exact sum of the mapping, or refused.
|
||||
/// SOURCE: docs/spec/rules.md B-21, B-28; bookspec BS-entry-3,
|
||||
/// SOURCE: BS-entry-3, BS-entry-4; bookspec BS-entry-3,
|
||||
/// BS-entry-4; CONVENTION.
|
||||
/// INVARIANTS:
|
||||
/// 1. total_of(items, f) = total(f(item) for item in items), exactly.
|
||||
@@ -69,7 +69,7 @@ pub fn total_of<T: Amount, I>(
|
||||
/// ```text
|
||||
/// GOAL: the sum of a derived figure (a column's contributions less its
|
||||
/// distributions) is exact, or refused.
|
||||
/// SOURCE: docs/spec/rules.md B-21, B-28; bookspec BS-entry-3,
|
||||
/// SOURCE: BS-entry-3, BS-entry-4; bookspec BS-entry-3,
|
||||
/// BS-entry-4; CONVENTION.
|
||||
/// INVARIANTS:
|
||||
/// 1. total_try(items, f) = Some(Σ f(item)) exactly when every f(item)
|
||||
|
||||
+168
-168
File diff suppressed because it is too large.
Load diff
@@ -63,7 +63,7 @@ impl Currency {
|
||||
/// code ISO 4217 gives none (gold, SDRs), the most a line may carry
|
||||
/// (kernel::MAX_LINE_SCALE). Every posted amount is then a whole number
|
||||
/// of the unit split to, so no member's running share is ever a unit
|
||||
/// from exact (rules.md B-13); split to cents, a finer amount's
|
||||
/// from exact (BS-partner-1); split to cents, a finer amount's
|
||||
/// leftover fraction would all go to one member.
|
||||
pub fn allocation_places(&self) -> u32 {
|
||||
self.minor_units().unwrap_or(crate::kernel::MAX_LINE_SCALE)
|
||||
@@ -156,7 +156,7 @@ impl Money {
|
||||
/// The exact sum of some figures ([`crate::kernel::total`]), or
|
||||
/// `TooLargeToCompute` naming `what` when a running sum cannot be held:
|
||||
/// the engine's way to total a column without a raw `.sum()` that would
|
||||
/// panic at `Decimal::MAX` (rules.md B-21, B-28).
|
||||
/// panic at `Decimal::MAX` (BS-entry-3, BS-entry-4).
|
||||
pub fn sum_exact(
|
||||
values: impl IntoIterator<Item = Decimal>,
|
||||
what: &str,
|
||||
@@ -213,8 +213,8 @@ impl fmt::Debug for Money {
|
||||
/// GOAL: depreciation and daily schedules round to the currency's own
|
||||
/// smallest unit (cents, whole yen, thousandths of a dinar), never a
|
||||
/// fixed two places.
|
||||
/// SOURCE: docs/spec/rules.md B-3 (no fraction of the minor unit; ISO 4217,
|
||||
/// sources/iso-4217.md).
|
||||
/// SOURCE: BS-ledger-1 (no fraction of the minor unit; ISO 4217,
|
||||
/// docs/spec/sources/iso-4217.md).
|
||||
/// INVARIANTS:
|
||||
/// 1. amount = units × 10^-scale exactly; unit = 10^(scale − minor).
|
||||
/// 2. A currency with no minor unit (gold, SDRs) counts as two places.
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
//! not placeholders, payables or payroll withholdings: what the
|
||||
//! company owes that party itself on (a card's issuer, a loan's
|
||||
//! lender, a member for what the members advanced). A credit to one
|
||||
//! never counts as paying that party (rules.md B-35; DECISION, owner,
|
||||
//! never counts as paying that party (BS-partner-3; DECISION, owner,
|
||||
//! 2026-10-20).
|
||||
//! ```
|
||||
|
||||
@@ -305,7 +305,7 @@ impl Party {
|
||||
/// GOAL: one answer to "which TIN is on file for them?" wherever the
|
||||
/// books show a last four (defect 11: the directory showed a
|
||||
/// member's as missing because it read W-9 facts only).
|
||||
/// SOURCE: rules.md B-26 (Treas. Reg. §301.6109-4(a): a truncated TIN
|
||||
/// SOURCE: BS-partner-2 (Treas. Reg. §301.6109-4(a): a truncated TIN
|
||||
/// shows its last four); INVARIANT 2a (DECISION, owner,
|
||||
/// 2026-10-15: the two never disagree, so either answers).
|
||||
/// SCENARIOS:
|
||||
@@ -321,7 +321,7 @@ impl Party {
|
||||
/// ```
|
||||
pub fn tin_last4(&self) -> Option<&str> {
|
||||
// Exactly four digits or nothing, however the facts were built
|
||||
// (the setters check it; this never shows more, B-26).
|
||||
// (the setters check it; this never shows more, BS-partner-2).
|
||||
let four = |s: &str| s.len() == 4 && s.chars().all(|c| c.is_ascii_digit());
|
||||
self.tin
|
||||
.as_ref()
|
||||
@@ -596,9 +596,9 @@ std::thread_local! {
|
||||
/// ```text
|
||||
/// GOAL: books an earlier version wrote open, forever, however a later
|
||||
/// version widens what reads as a full TIN.
|
||||
/// SOURCE: rules.md B-28 ("Replay accepts every line an earlier version
|
||||
/// SOURCE: BS-entry-4 ("Replay accepts every line an earlier version
|
||||
/// accepted": the bounds are the commands', never replay's);
|
||||
/// B-26 (no full TIN in the books).
|
||||
/// BS-partner-2 (no full TIN in the books).
|
||||
/// INVARIANTS:
|
||||
/// 1. Within it, a text is refused only if P2's detector
|
||||
/// ([`journaled_tin_runs`]) refuses it: every name, reason and fact
|
||||
@@ -625,8 +625,8 @@ pub fn replaying<T>(f: impl FnOnce() -> T) -> T {
|
||||
|
||||
/// Whether a journaled line is being replayed now ([`replaying`]): the
|
||||
/// rules a later version added that refuse new work (the control guard,
|
||||
/// a document's bounds, rules.md B-38) never refuse a line an earlier
|
||||
/// version accepted (B-28).
|
||||
/// a document's bounds, BS-arap-2) never refuse a line an earlier
|
||||
/// version accepted (BS-entry-4).
|
||||
pub fn is_replaying() -> bool {
|
||||
REPLAYING.with(std::cell::Cell::get)
|
||||
}
|
||||
@@ -681,7 +681,7 @@ fn journaled_tin_runs(chars: &[char]) -> Vec<(usize, usize)> {
|
||||
|
||||
/// `text` with every run [`has_full_tin`] finds masked: each of its
|
||||
/// digits becomes `•`, separators kept. For refusals that quote what they
|
||||
/// were given, so no error echoes a full TIN (docs/spec/rules.md B-26).
|
||||
/// were given, so no error echoes a full TIN (BS-partner-2).
|
||||
pub fn redact_full_tins(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
let mut chars: Vec<char> = text.chars().collect();
|
||||
let runs = full_tin_runs(&chars);
|
||||
@@ -828,7 +828,7 @@ impl PartyField {
|
||||
];
|
||||
|
||||
/// Whether `field` is a field this version knows. A `party.updated`
|
||||
/// naming another was written by a newer version (rules.md B-27).
|
||||
/// naming another was written by a newer version (BS-format-1).
|
||||
pub fn known_field(field: &str) -> bool {
|
||||
Self::FIELDS.contains(&field)
|
||||
}
|
||||
@@ -850,7 +850,7 @@ impl PartyField {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of a party's totals to report (rules.md B-35 item 4). Not the
|
||||
/// Which of a party's totals to report (BS-partner-3 item 4). Not the
|
||||
/// books' accounting method (`books.accounting_basis`): party totals count
|
||||
/// what moved, whichever method the books keep.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
@@ -928,7 +928,7 @@ impl Activity {
|
||||
}
|
||||
}
|
||||
|
||||
/// The accounts [`entry_flow`] reads money from (rules.md B-35, defect
|
||||
/// The accounts [`entry_flow`] reads money from (BS-partner-3, defect
|
||||
/// 24): the cash accounts (every asset account but receivables when none
|
||||
/// are given), and the money liabilities: the cards ([`card_accounts`]),
|
||||
/// what the members advanced and loans (`books.financing_accounts`).
|
||||
@@ -949,8 +949,8 @@ impl MoneyAccounts {
|
||||
/// what the company owes a party itself never counts as paying it (a
|
||||
/// fee charged on its own card, interest added to its own loan,
|
||||
/// equipment bought on its own note, a distribution still owed to a
|
||||
/// member), and a debit to it is what the money paid for (rules.md
|
||||
/// B-35; DECISION, owner, 2026-10-20).
|
||||
/// member), and a debit to it is what the money paid for (
|
||||
/// BS-partner-3; DECISION, owner, 2026-10-20).
|
||||
pub fn for_parties(
|
||||
&self,
|
||||
ledger: &crate::Ledger,
|
||||
@@ -981,8 +981,8 @@ impl MoneyAccounts {
|
||||
/// ```text
|
||||
/// GOAL: a card is known from what the books record, and a promise (a
|
||||
/// gift card sold) or a member's own card is never the company's.
|
||||
/// SOURCE: rules.md B-35 item 5 (DECISION, owner, 2026-10-20: money is
|
||||
/// cash, cards, the members' financing and loans), B-19 (payment
|
||||
/// SOURCE: BS-partner-3 item 5 (DECISION, owner, 2026-10-20: money is
|
||||
/// cash, cards, the members' financing and loans), BS-1099-1 (payment
|
||||
/// methods, plan P3 defect 12).
|
||||
/// INVARIANTS:
|
||||
/// 1. When the books record a business-card payment method: exactly
|
||||
@@ -1148,7 +1148,7 @@ pub fn entry_flow(
|
||||
) -> 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
|
||||
// A draft's lines are as journaled, of any size (BS-entry-4): every
|
||||
// sum is checked, and one past exact arithmetic is refused.
|
||||
let too_large =
|
||||
|| crate::LedgerError::TooLargeToCompute(format!("entry {}'s money flow", entry.id()));
|
||||
@@ -1256,14 +1256,14 @@ pub fn entry_flow(
|
||||
|
||||
/// The money an entry moved with the parties it names, and what for,
|
||||
/// read as party figures read it: a reversal's is exactly its original's
|
||||
/// negated (B-9), never re-read from its own lines; and a liability owed
|
||||
/// negated (BS-ledger-5), never re-read from its own lines; and a liability owed
|
||||
/// to a party named is not money for the entry
|
||||
/// ([`MoneyAccounts::for_parties`]).
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: what a party's entry paid for, right for reversals too.
|
||||
/// SOURCE: rules.md B-9 ("a mistake is corrected by an opposite entry"),
|
||||
/// B-35.
|
||||
/// SOURCE: BS-ledger-5 ("a mistake is corrected by an opposite entry"),
|
||||
/// BS-partner-3.
|
||||
/// INVARIANTS:
|
||||
/// 1. An entry reversing none: entry_flow of its lines, with
|
||||
/// money.for_parties(the parties of `shares`).
|
||||
@@ -1327,8 +1327,8 @@ pub fn activity(
|
||||
/// get from them?" for the MCP server and the viewer alike, right
|
||||
/// when an entry was with several parties, for property as well as
|
||||
/// money, and for reversals.
|
||||
/// SOURCE: docs/parties-and-attachments.md (Parties, Shares); rules.md
|
||||
/// B-35 (DECISION, owner, 2026-10-15 and 2026-10-20).
|
||||
/// SOURCE: docs/parties-and-attachments.md (Parties, Shares);
|
||||
/// BS-partner-3 (DECISION, owner, 2026-10-15 and 2026-10-20).
|
||||
/// INVARIANTS:
|
||||
/// 1. entries: every entry Ledger::entry_parties names the party in
|
||||
/// (hand tags, vendor tags, bills and their payments, invoices and
|
||||
@@ -1376,7 +1376,7 @@ pub fn activity_with(
|
||||
}
|
||||
let shares = ledger.entry_parties(id);
|
||||
// The target first: an entry that counts nothing is never
|
||||
// unresolved for shares that don't fit it (rules.md B-35 item 4).
|
||||
// unresolved for shares that don't fit it (BS-partner-3 item 4).
|
||||
let Ok(t) = crate::shares::target(ledger, id, shares, money) else {
|
||||
a.unresolved.insert(id);
|
||||
continue;
|
||||
|
||||
@@ -86,7 +86,7 @@ pub type PayoutPlanLine = (AccountId, Side, Decimal, Option<ClassId>);
|
||||
/// collected; fees debit expense accounts), and the payout reconciles to
|
||||
/// the cent.
|
||||
/// A zero deposit (fees and adjustments ate the sales exactly) has no
|
||||
/// deposit line: every planned line is positive (B-2, docs/spec/rules.md).
|
||||
/// deposit line: every planned line is positive (BS-entry-2).
|
||||
pub fn payout_plan(
|
||||
payout: &Payout,
|
||||
chart: &ChartOfAccounts,
|
||||
|
||||
@@ -50,7 +50,7 @@ impl PayrollLine {
|
||||
/// Gross minus all employee withholdings and deductions. Must be >= 0:
|
||||
/// 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).
|
||||
/// restored as journaled (BS-entry-4).
|
||||
pub fn net_pay(&self) -> Result<Decimal, LedgerError> {
|
||||
[
|
||||
self.federal_withholding,
|
||||
@@ -133,7 +133,7 @@ pub fn validate_payroll_lines(lines: &[PayrollLine]) -> Result<(), LedgerError>
|
||||
/// 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).
|
||||
/// restores a run as journaled (BS-entry-4).
|
||||
pub fn check_payroll_ranges(lines: &[PayrollLine]) -> Result<(), LedgerError> {
|
||||
for line in lines {
|
||||
for amount in [
|
||||
|
||||
@@ -56,7 +56,7 @@ pub enum CloseTo {
|
||||
/// gives a member their share of everything closed to the members so
|
||||
/// far, to the currency's minor unit, less what earlier closes gave
|
||||
/// them, so no member is ever a minor unit from their exact share
|
||||
/// (rules.md B-13; D-10). What new closes are made with; the books
|
||||
/// (BS-partner-1; D-10). What new closes are made with; the books
|
||||
/// journal it as [`CloseTo::MembersCumulative`].
|
||||
Members(Vec<MemberClose>),
|
||||
/// [`CloseTo::Members`] as journaled: the count of members closes
|
||||
@@ -130,7 +130,7 @@ pub fn allocate(
|
||||
|
||||
/// [`allocate`], refusing with `TooLargeToCompute` instead of panicking
|
||||
/// when a share of `amount` is beyond exact arithmetic (a replayed close
|
||||
/// carries a journaled amount of any size, rules.md B-28). The same split,
|
||||
/// carries a journaled amount of any size, BS-entry-4). The same split,
|
||||
/// to the cent, for every amount [`allocate`] accepts.
|
||||
pub fn try_allocate(
|
||||
amount: rust_decimal::Decimal,
|
||||
@@ -177,7 +177,7 @@ pub fn allocate_last_absorbs(
|
||||
|
||||
/// [`allocate_last_absorbs`], refusing with `TooLargeToCompute` instead of
|
||||
/// panicking when `amount × share` or the plug is beyond exact arithmetic
|
||||
/// (replay of a legacy close with a huge journaled amount, rules.md B-28).
|
||||
/// (replay of a legacy close with a huge journaled amount, BS-entry-4).
|
||||
/// The same split, to the cent, for every amount [`allocate_last_absorbs`]
|
||||
/// accepts: this is the frozen rule, only its overflow now an error.
|
||||
pub fn try_allocate_last_absorbs(
|
||||
@@ -205,22 +205,22 @@ pub fn try_allocate_last_absorbs(
|
||||
/// ([`crate::Currency::allocation_places`]) instead of cents, less what
|
||||
/// earlier closes gave each member (`given`, in the order of `shares`).
|
||||
/// Each member's running total is then one split of the running total
|
||||
/// (rules.md B-13; [`crate::kernel::apportion_cumulative`]). A loss is
|
||||
/// (BS-partner-1; [`crate::kernel::apportion_cumulative`]). A loss is
|
||||
/// the negation of the same gain: it splits |total| against `given`
|
||||
/// negated, then negates.
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: no member's running share of earnings is ever a minor unit from
|
||||
/// their exact share, whatever earlier closes gave them.
|
||||
/// SOURCE: docs/spec/rules.md B-13 (26 U.S.C. §704(a); Treas. Reg.
|
||||
/// SOURCE: BS-partner-1 (26 U.S.C. §704(a); Treas. Reg.
|
||||
/// §1.704-1(b)(2)(iv)(b); largest remainder: DECISION, owner
|
||||
/// 2026-10-13; from the first close: D-10); B-3 (the minor unit).
|
||||
/// 2026-10-13; from the first close: D-10); BS-ledger-1 (the minor unit).
|
||||
/// INVARIANTS:
|
||||
/// 1. The parts MUST sum to total − Σ given exactly.
|
||||
/// 2. given[i] + part[i] MUST be member i's largest-remainder split of
|
||||
/// total to `places` (ties to the earlier member): one split.
|
||||
/// 3. So when total is a whole number of units of `places` (every posted
|
||||
/// line is at its currency's allocation_places: its minor unit, B-3,
|
||||
/// line is at its currency's allocation_places: its minor unit, BS-ledger-1,
|
||||
/// or for a currency without one the finest a line carries),
|
||||
/// |given[i] + part[i] − total × share[i]| is under one unit (Lean
|
||||
/// allocW_drift, cumulative_drift; Kani
|
||||
@@ -326,7 +326,7 @@ pub struct Period {
|
||||
/// What a close under the run rule ([`CloseTo::MembersRun`], journaled
|
||||
/// `"cumulative"`) allocated, once closed that way. Only those closes
|
||||
/// have one: its serialized form is what earlier versions wrote, and
|
||||
/// stays so (rules.md B-28). Every members close's split, under any
|
||||
/// stays so (BS-entry-4). Every members close's split, under any
|
||||
/// rule, is [`Period::members_closed`].
|
||||
#[serde(default)]
|
||||
pub member_close: Option<MemberCloseRecord>,
|
||||
@@ -415,7 +415,7 @@ 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).
|
||||
/// checks only the order (BS-entry-4).
|
||||
pub fn validate_period_range(start: NaiveDate, end: NaiveDate) -> Result<(), LedgerError> {
|
||||
crate::calendar::check(start)?;
|
||||
crate::calendar::check(end)?;
|
||||
|
||||
@@ -460,7 +460,7 @@ fn closing_entry_balances() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 1099 payments (rules.md B-19)
|
||||
// 1099 payments (BS-1099-1)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn any_role() -> kernel::PayRole {
|
||||
@@ -485,7 +485,7 @@ fn any_tag() -> kernel::Tag {
|
||||
}
|
||||
}
|
||||
|
||||
/// `kernel::payment_bucket` is the B-19 table, all 16 cases: a tag naming
|
||||
/// `kernel::payment_bucket` is the BS-1099-1 table, all 16 cases: a tag naming
|
||||
/// the line's account decides (card or network: Card; otherwise Counts);
|
||||
/// else the role does, and with no tag naming its account a financing line
|
||||
/// never counts and a card account's line is always Card.
|
||||
@@ -726,7 +726,7 @@ fn apportion_cumulative_is_exact() {
|
||||
/// `cumulative_drift` carry any weights and any amounts).
|
||||
const DRIFT: i64 = 1 << 12;
|
||||
|
||||
/// **Bounded drift** (rules.md B-13) for members with these integer
|
||||
/// **Bounded drift** (BS-partner-1) for members with these integer
|
||||
/// weights (shares w_i / W, W their sum): a cumulative members close,
|
||||
/// modelled as `periods::allocate_cumulative` runs it at whole minor units
|
||||
/// (unit 1), hands out exactly its net, and leaves every member's running
|
||||
@@ -968,7 +968,7 @@ fn apply_cash_mirrors() {
|
||||
/// An accepted entry always has cash flows, and they explain its cash
|
||||
/// exactly: the sections' cash sums to the entry's cash, and what no cash
|
||||
/// settled (each section's movement plus its cash) sums to zero
|
||||
/// (rules.md B-14 rules 3 and 9: the statement foots, entry by entry).
|
||||
/// (BS-statement-3 rules 3 and 9: the statement foots, entry by entry).
|
||||
#[kani::proof]
|
||||
#[kani::unwind(5)]
|
||||
fn entry_flows_sum_to_cash() {
|
||||
@@ -1043,7 +1043,7 @@ fn entry_flows_are_bounded() {
|
||||
|
||||
/// A reversal's cash flows are its original's, negated, part by part:
|
||||
/// what lets an entry and its reversal in one period drop out of the
|
||||
/// statement together (rules.md B-14 rule 6). End to end, on entries of
|
||||
/// statement together (BS-statement-3 rule 6). End to end, on entries of
|
||||
/// up to two lines: at three (`NF`) one run went past half an hour at
|
||||
/// four jobs on a busy machine (2026-10-21), so three lines are proved in
|
||||
/// two halves, `entry_movements_of_a_reversal_mirror` and
|
||||
@@ -1227,8 +1227,8 @@ fn any_way() -> kernel::OnBehalf {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a member or a lender paid or received for the company (rules.md
|
||||
/// B-14 rule 11, D-42) invents and loses nothing: the parts net to zero,
|
||||
/// What a member or a lender paid or received for the company (
|
||||
/// BS-statement-3 rule 11, D-42) invents and loses nothing: the parts net to zero,
|
||||
/// so an entry's flows still sum to its cash; each part settles its own
|
||||
/// movement toward zero, never past it; and as much is settled as can be.
|
||||
#[kani::proof]
|
||||
@@ -1276,7 +1276,7 @@ fn constructive_nets_to_zero() {
|
||||
|
||||
/// The other way, minus the sources and minus the uses give minus the
|
||||
/// parts: a reversal of a payment made on the company's behalf mirrors it
|
||||
/// (rules.md B-14 rule 6), so the two drop out together.
|
||||
/// (BS-statement-3 rule 6), so the two drop out together.
|
||||
#[kani::proof]
|
||||
#[kani::unwind(4)]
|
||||
fn constructive_mirrors() {
|
||||
@@ -1300,7 +1300,7 @@ fn constructive_mirrors() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// A party's part of an entry (rules.md B-35)
|
||||
// A party's part of an entry (BS-partner-3)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// The inputs `kernel::party_target` reads, any in range: a capital
|
||||
@@ -1320,7 +1320,7 @@ fn any_party_inputs() -> (Option<(i64, i64)>, i64, i64, i64) {
|
||||
(capital, any_amount(), any_amount(), debits)
|
||||
}
|
||||
|
||||
/// B-35 items 1-4: the direction is the sign of what counts (paid above
|
||||
/// BS-partner-3 items 1-4: the direction is the sign of what counts (paid above
|
||||
/// zero, received below), neither exactly when nothing counts; cash and
|
||||
/// in kind each carry the whole's sign and together never exceed it; a
|
||||
/// money target is all cash; a contribution counts all of itself; a
|
||||
@@ -1374,7 +1374,7 @@ fn party_target_direction_is_its_sign() {
|
||||
);
|
||||
}
|
||||
|
||||
/// B-35 item 3 and B-9: the target is odd. Negating the lines negates the
|
||||
/// BS-partner-3 item 3 and BS-ledger-5: the target is odd. Negating the lines negates the
|
||||
/// capital movement, the money net and the own-account movement, and the
|
||||
/// property comes from the other side, so it keeps its size: the result
|
||||
/// is the original's reverse_target, whenever it isn't the debits fallback
|
||||
@@ -1409,7 +1409,7 @@ fn party_target_is_odd() {
|
||||
);
|
||||
}
|
||||
|
||||
/// B-9: reversing a reversal gives the original back, and reverse_target
|
||||
/// BS-ledger-5: reversing a reversal gives the original back, and reverse_target
|
||||
/// never panics: past the range it refuses.
|
||||
#[kani::proof]
|
||||
fn reverse_target_is_an_involution() {
|
||||
@@ -1438,7 +1438,7 @@ fn reverse_target_is_an_involution() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Proration by days (depreciation, B-15; daily schedules, B-16)
|
||||
// Proration by days (depreciation, BS-asset-1; daily schedules, BS-prepaid-1)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Most month parts the proration harnesses explore.
|
||||
@@ -1687,7 +1687,7 @@ fn prorated_through_refuses_malformed_input() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Catching up and truing up (B-15)
|
||||
// Catching up and truing up (BS-asset-1)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A catch-up run posts max(0, min gap), never negative, and never carries
|
||||
@@ -1753,7 +1753,7 @@ fn true_up_reaches_the_target() {
|
||||
kani::cover!(down > 0, "depreciation past the day, credited back");
|
||||
}
|
||||
|
||||
/// `kernel::basis_figures` (rules.md B-25), for every rule and every
|
||||
/// `kernel::basis_figures` (BS-asset-4), for every rule and every
|
||||
/// cost, adjusted basis and value within the bounds: a purchase
|
||||
/// depreciates from cost with no §723 basis or built-in gain; a
|
||||
/// contribution's §723 basis is the adjusted basis and its built-in gain
|
||||
@@ -1797,7 +1797,7 @@ fn basis_figures_laws() {
|
||||
);
|
||||
}
|
||||
|
||||
/// `kernel::unrecovered_cost` (rules.md B-37 item 4), for every revenue
|
||||
/// `kernel::unrecovered_cost` (BS-statement-5 item 4), for every revenue
|
||||
/// and expense a line could carry: never below zero; the shortfall when
|
||||
/// expenses exceed revenue, else zero; never above max(expenses, 0) when
|
||||
/// revenue isn't negative (expenses may be negative: a reimbursement
|
||||
@@ -1819,7 +1819,7 @@ fn unrecovered_cost_laws() {
|
||||
kani::cover!(u == 0 && revenue > expenses, "repaid, and more");
|
||||
}
|
||||
|
||||
/// `kernel::running_bounds` (rules.md B-38 INVARIANT 2; the bounds every
|
||||
/// `kernel::running_bounds` (BS-arap-2 INVARIANT 2; the bounds every
|
||||
/// document command and reversal checks), for every total and every
|
||||
/// sequence of up to `N` dated movements a line could carry: it says
|
||||
/// Within exactly when every running balance is in `0 ..= total`, and
|
||||
@@ -1859,7 +1859,7 @@ fn bounds_check_matches_definition() {
|
||||
}
|
||||
|
||||
/// `kernel::bounds_kept` (the check every document command and reversal
|
||||
/// runs, rules.md B-38 INVARIANT 2): on books in bounds at every date it
|
||||
/// runs, BS-arap-2 INVARIANT 2): on books in bounds at every date it
|
||||
/// is the definition (`running_bounds` of the books after the step); and
|
||||
/// whenever it says Within, no running balance after the step is further
|
||||
/// outside `0 ..= total` than before it, so a step that mends books an
|
||||
@@ -1996,7 +1996,7 @@ fn line_amount_is_exact() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tax categories (B-32)
|
||||
// Tax categories (BS-ledger-11)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// `n / 100` rounded half away from zero: the reference for the one
|
||||
@@ -2013,7 +2013,7 @@ fn round_cent(n: i64) -> Option<i64> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `kernel::deductible_amount` (rules.md B-32, B-21; CHOICE, owner
|
||||
/// `kernel::deductible_amount` (BS-ledger-11, BS-entry-3; CHOICE, owner
|
||||
/// 2026-11-07, D-67) over up to three accounts in exact range: the exact
|
||||
/// sum of the shares (`book × percent ÷ 100`) rounded once to the nearest
|
||||
/// cent, ties away from zero; never the sum of per-account roundings; and
|
||||
|
||||
@@ -47,7 +47,7 @@ impl TrialBalance {
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: the trial balance over every posted entry (see trial_balance_as_of).
|
||||
/// SOURCE: docs/spec/rules.md B-6; R-7.
|
||||
/// SOURCE: BS-statement-1; R-7.
|
||||
/// INVARIANTS:
|
||||
/// 1. MUST equal trial_balance_as_of on or after the last entry's date.
|
||||
/// 2. MUST balance (total debits == total credits).
|
||||
@@ -63,7 +63,7 @@ pub fn trial_balance(ledger: &Ledger) -> TrialBalance {
|
||||
/// ```text
|
||||
/// GOAL: every account's balance, in a debit or a credit column, from the
|
||||
/// posted entries dated on or before `as_of`.
|
||||
/// SOURCE: docs/spec/rules.md B-6 (Pacioli ch. 36; IRS Pub. 583); R-7, R-9b.
|
||||
/// SOURCE: BS-statement-1 (Pacioli ch. 36; IRS Pub. 583); R-7, R-9b.
|
||||
/// INVARIANTS:
|
||||
/// 1. MUST have total debits equal total credits, for any books built
|
||||
/// through the Ledger commands.
|
||||
@@ -191,7 +191,7 @@ pub struct ClassProfitAndLoss {
|
||||
/// ```text
|
||||
/// GOAL: a profit and loss per class (department, location, job), plus the
|
||||
/// unclassified lines.
|
||||
/// SOURCE: docs/spec/rules.md B-14; R-? Tracking classes.
|
||||
/// SOURCE: BS-statement-3; R-? Tracking classes.
|
||||
/// INVARIANTS:
|
||||
/// 1. The per-class P&Ls (with unclassified) MUST sum to the whole P&L,
|
||||
/// account by account (conservation).
|
||||
@@ -452,7 +452,7 @@ fn statement_lines(
|
||||
/// ```text
|
||||
/// GOAL: revenue, expenses, and net income for the entries dated from
|
||||
/// `start` through `end` (both inclusive), optionally one class's lines.
|
||||
/// SOURCE: docs/spec/rules.md B-14, B-11; R-9.
|
||||
/// SOURCE: BS-statement-3, BS-period-1; R-9.
|
||||
/// INVARIANTS:
|
||||
/// 1. MUST count only revenue and expense accounts, a line per account
|
||||
/// with its normal-side amount, and net income = revenue - expenses.
|
||||
@@ -533,7 +533,7 @@ fn profit_and_loss_counted(
|
||||
))
|
||||
}
|
||||
|
||||
/// A project's figures (rules.md B-37 item 3): the period's statement and
|
||||
/// A project's figures (BS-statement-5 item 3): the period's statement and
|
||||
/// months, and its figures to date.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ProjectFigures {
|
||||
@@ -563,7 +563,7 @@ impl ProjectFigures {
|
||||
}
|
||||
|
||||
/// A project's figures to date: every posted revenue and expense line
|
||||
/// tagged to it through `through`, whatever its dates (rules.md B-37).
|
||||
/// tagged to it through `through`, whatever its dates (BS-statement-5).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ProjectToDate {
|
||||
/// The last day counted.
|
||||
@@ -592,7 +592,7 @@ pub struct ProjectToDate {
|
||||
|
||||
impl ProjectToDate {
|
||||
/// Revenue less expenses: the project's contribution before overhead
|
||||
/// (rules.md B-37 item 7), since only its own tagged lines count.
|
||||
/// (BS-statement-5 item 7), since only its own tagged lines count.
|
||||
pub fn net(&self) -> Decimal {
|
||||
self.revenue - self.expenses
|
||||
}
|
||||
@@ -611,11 +611,11 @@ impl ProjectToDate {
|
||||
}
|
||||
|
||||
/// Contribution as a percent of revenue, to one place (half to even), or
|
||||
/// `None` without revenue to divide by (rules.md B-37 item 7).
|
||||
/// `None` without revenue to divide by (BS-statement-5 item 7).
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: one margin the tools and the viewer print alike.
|
||||
/// SOURCE: docs/spec/rules.md B-37 item 7 (revenue less the costs traced
|
||||
/// SOURCE: BS-statement-5 item 7 (revenue less the costs traced
|
||||
/// to the project, fixed and variable alike: Garrison's segment
|
||||
/// margin, as a ratio; not Horngren's variable-cost contribution
|
||||
/// margin; a presentation choice, not GAAP).
|
||||
@@ -650,7 +650,7 @@ pub const PROJECT_MONTHS: u32 = 240;
|
||||
/// ```text
|
||||
/// GOAL: what a project earned and cost, from one function the tools, the
|
||||
/// viewer and bookspec share, so their figures never drift.
|
||||
/// SOURCE: docs/spec/rules.md B-37 item 3 (job costing), B-11, B-14.
|
||||
/// SOURCE: BS-statement-5 item 3 (job costing), BS-period-1, BS-statement-3.
|
||||
/// INVARIANTS:
|
||||
/// 1. MUST be profit_and_loss_for_period with the project's class: only
|
||||
/// revenue and expense lines tagged to it, closing entries left out.
|
||||
@@ -748,7 +748,7 @@ pub fn project_to_date(
|
||||
/// Every entry with a line tagged to the project (drafts included),
|
||||
/// newest first (by date, then id), with its project amount: its tagged
|
||||
/// revenue lines less its tagged expense lines, each on its normal side.
|
||||
/// A tagged balance-sheet line counts zero (rules.md B-37 item 3).
|
||||
/// A tagged balance-sheet line counts zero (BS-statement-5 item 3).
|
||||
pub fn project_entries(ledger: &Ledger, id: ClassId) -> Vec<(crate::EntryId, Decimal)> {
|
||||
let mut out: Vec<(NaiveDate, crate::EntryId, Decimal)> = Vec::new();
|
||||
for eid in 1..ledger.next_entry_id() {
|
||||
@@ -796,7 +796,7 @@ pub fn project_entries(ledger: &Ledger, id: ClassId) -> Vec<(crate::EntryId, Dec
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: assets, liabilities, and equity as of a date, a line per account.
|
||||
/// SOURCE: docs/spec/rules.md B-7 (CON 8 ¶E62), B-11; R-8.
|
||||
/// SOURCE: BS-statement-2 (CON 8 ¶E62), BS-period-1; R-8.
|
||||
/// INVARIANTS:
|
||||
/// 1. MUST balance: assets = liabilities + equity + current earnings,
|
||||
/// exactly.
|
||||
@@ -917,7 +917,7 @@ pub struct GeneralLedger {
|
||||
/// ```text
|
||||
/// GOAL: every posting from `start` through `end`, by account in code
|
||||
/// order, with running balances.
|
||||
/// SOURCE: docs/spec/rules.md B-6; R-9a (the QuickBooks general ledger).
|
||||
/// SOURCE: BS-statement-1; R-9a (the QuickBooks general ledger).
|
||||
/// INVARIANTS:
|
||||
/// 1. Each account MUST show its beginning balance (entries before
|
||||
/// `start`), every posting in the range in date order, and an ending
|
||||
@@ -1147,8 +1147,8 @@ pub fn cancelled_in_span(
|
||||
/// GOAL: each member's capital roll-forward for a partnership over a
|
||||
/// period: beginning, contributions, allocated net income, distributions,
|
||||
/// ending; with a total.
|
||||
/// SOURCE: docs/spec/rules.md B-13 (26 U.S.C. §704(a); Treas. Reg.
|
||||
/// §1.704-1(b)(2)(iv)(b); Form 1065 Schedule M-2; D-38), B-11;
|
||||
/// SOURCE: BS-partner-1 (26 U.S.C. §704(a); Treas. Reg.
|
||||
/// §1.704-1(b)(2)(iv)(b); Form 1065 Schedule M-2; D-38), BS-period-1;
|
||||
/// R-9c.
|
||||
/// INVARIANTS:
|
||||
/// 1. Each row MUST roll forward exactly: beginning + contributions +
|
||||
@@ -1182,7 +1182,7 @@ pub fn cancelled_in_span(
|
||||
/// 5. An entry dated `start` is period activity, not beginning capital.
|
||||
/// 6. An entry and its reversal both dated in the span cancel
|
||||
/// ([`cancelled_in_span`]): neither is a contribution or a
|
||||
/// distribution, since the correction undoes the original (B-9: "it
|
||||
/// distribution, since the correction undoes the original (BS-ledger-5: "it
|
||||
/// is just as if you had written nothing"). A reversal whose original
|
||||
/// is outside the span counts by side, like any entry.
|
||||
/// SCENARIOS:
|
||||
@@ -1501,7 +1501,7 @@ pub fn snapshot(ledger: &Ledger) -> Result<serde_json::Value, LedgerError> {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cash flow statement (direct method, rules.md B-14): see `crate::cashflow`.
|
||||
// Cash flow statement (direct method, BS-statement-3): see `crate::cashflow`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub use crate::cashflow::{
|
||||
@@ -1700,8 +1700,8 @@ pub fn register_row(
|
||||
/// GOAL: one list of everything the company owns as a fixed asset: what,
|
||||
/// which label, cost, depreciation due and posted, book value, tax
|
||||
/// figures, and whether the books agree.
|
||||
/// SOURCE: docs/spec/rules.md B-15 (depreciation), B-24 (the register
|
||||
/// reconciles to the books), B-25 (tax figures beside book);
|
||||
/// SOURCE: BS-asset-1 (depreciation), BS-asset-3 (the register
|
||||
/// reconciles to the books), BS-asset-4 (tax figures beside book);
|
||||
/// DECISION (owner, 2026-10-15): a fully featured asset register.
|
||||
/// INVARIANTS:
|
||||
/// 1. Rows: the assets acquired on or before as_of
|
||||
@@ -1726,7 +1726,7 @@ pub fn register_row(
|
||||
/// 5. Each row's tax fields are the asset's (Asset::basis_figures),
|
||||
/// never re-derived here.
|
||||
/// 6. NEVER panics: a contributor basis is as journaled, of any size
|
||||
/// (rules.md B-28), and a total past exact arithmetic, or a schedule
|
||||
/// (BS-entry-4), and a total past exact arithmetic, or a schedule
|
||||
/// that can't be computed, is refused (TooLargeToCompute,
|
||||
/// DateOutOfRange).
|
||||
/// ```
|
||||
|
||||
@@ -30,7 +30,8 @@ use chrono::NaiveDate;
|
||||
pub struct DatedRule {
|
||||
/// Plain name, e.g. "1099 reporting threshold".
|
||||
pub name: &'static str,
|
||||
/// Its entry in docs/spec/rules.md, e.g. "B-19".
|
||||
/// Its bookspec rule id, e.g. "BS-1099-1" (indexed in docs/spec/rules.md;
|
||||
/// wanderbooks' claim is in docs/spec/claims/1099.md).
|
||||
pub catalog: &'static str,
|
||||
/// The vendored official text it comes from (a path in this repo,
|
||||
/// for the people who update the rule).
|
||||
@@ -61,11 +62,11 @@ impl DatedRule {
|
||||
}
|
||||
}
|
||||
|
||||
/// The 1099-NEC / 1099-MISC reporting threshold (rules.md B-19): $600 for
|
||||
/// The 1099-NEC / 1099-MISC reporting threshold (BS-1099-1): $600 for
|
||||
/// payments through 2025, $2,000 in 2026, then indexed for inflation.
|
||||
pub const THRESHOLD_1099: DatedRule = DatedRule {
|
||||
name: "1099 reporting threshold",
|
||||
catalog: "B-19",
|
||||
catalog: "BS-1099-1",
|
||||
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,
|
||||
|
||||
@@ -47,7 +47,7 @@ pub enum ScheduleKind {
|
||||
/// How a schedule spreads its total over the time it covers.
|
||||
///
|
||||
/// ```text
|
||||
/// SOURCE: docs/spec/rules.md B-16; plan/served.md D-11 (new schedules
|
||||
/// SOURCE: BS-prepaid-1; plan/served.md D-11 (new schedules
|
||||
/// daily, "matching depreciation"; existing ones stay
|
||||
/// monthly_even), D-37 (owner, 2026-10-20: confirmed; an
|
||||
/// equal-months schedule starts on the 1st of a month, for
|
||||
@@ -173,7 +173,7 @@ pub const EXACT_LIMIT: Decimal =
|
||||
/// 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).
|
||||
/// (BS-entry-4). `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
|
||||
@@ -232,7 +232,7 @@ pub fn amortization_plan(
|
||||
/// ```text
|
||||
/// GOAL: recognize a prepaid expense, or earn deferred revenue, as each
|
||||
/// day it covers passes.
|
||||
/// SOURCE: docs/spec/rules.md B-16 (ASC 606-10-25-23: revenue as the
|
||||
/// SOURCE: BS-prepaid-1 (ASC 606-10-25-23: revenue as the
|
||||
/// obligation is satisfied; ASC 340-10-05-4: a prepaid is used up
|
||||
/// over the time it covers); plan/served.md D-11, D-37.
|
||||
/// INVARIANTS:
|
||||
@@ -381,7 +381,7 @@ fn month_first(d: NaiveDate) -> NaiveDate {
|
||||
/// [`validate_schedule`] without the total's range and minor-unit checks
|
||||
/// 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).
|
||||
/// replaying journals written before them (BS-entry-4).
|
||||
pub fn validate_schedule_shape(
|
||||
new: &NewSchedule,
|
||||
chart: &ChartOfAccounts,
|
||||
@@ -585,7 +585,7 @@ pub fn validate_recurring(new: &NewRecurring, chart: &ChartOfAccounts) -> Result
|
||||
/// 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
|
||||
/// Replay applies exactly these (BS-entry-4). Sums too large for exact
|
||||
/// arithmetic are refused (TooLargeToCompute), never a panic.
|
||||
pub fn validate_recurring_journaled(
|
||||
new: &NewRecurring,
|
||||
@@ -668,7 +668,7 @@ mod tests {
|
||||
|
||||
/// 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).
|
||||
/// refused where it can't, never a panic (BS-entry-4).
|
||||
#[test]
|
||||
fn plans_at_the_edges_are_computed_or_refused() {
|
||||
assert_eq!(month_end(NaiveDate::MAX), NaiveDate::MAX);
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//! sees the same way.
|
||||
//! SOURCE: plan/served.md I-3 (the journal holds all books state) and 5.3
|
||||
//! (setting keys); the validators carried over from
|
||||
//! ledger-config's wanderbooks.toml parser, whose SOURCE lines
|
||||
//! the `crates/ledger-config/src/lib.rs` parser (`parse`), whose SOURCE lines
|
||||
//! they keep (IRS Pub. 538, Treas. Reg. §301.7701-3, IRC §704(a)).
|
||||
//! INVARIANTS:
|
||||
//! 1. Only keys in KEYS exist; a value is checked by its key's kind
|
||||
@@ -22,7 +22,7 @@
|
||||
//! must hold together ([`Settings::check_whole`]), or none is made.
|
||||
//! 3. Replay takes any value of the right shape ([`shape`]): a check a
|
||||
//! later version tightens never makes older books unreadable
|
||||
//! (rules.md B-28).
|
||||
//! (BS-entry-4).
|
||||
//! 4. A setting never holds a full TIN, except the company's own EIN
|
||||
//! (`company.ein`, decided 2026-10-16, D-5): nine digits standing
|
||||
//! alone, bare or printed the way an SSN or EIN is (3-2-4 or 2-7,
|
||||
@@ -142,7 +142,7 @@ pub enum Kind {
|
||||
/// A positive whole number (a day count, the first invoice number).
|
||||
Count,
|
||||
/// Payment terms, in their one canonical spelling ([`crate::Terms`],
|
||||
/// rules.md B-39).
|
||||
/// BS-arap-3).
|
||||
Terms,
|
||||
/// Payment methods (A-3): a list of `{kind, label, lines, link?, qr?}`.
|
||||
PaymentMethods,
|
||||
@@ -633,7 +633,7 @@ impl Company {
|
||||
}
|
||||
|
||||
/// `policy.require_tax_category`: whether a revenue or expense account
|
||||
/// must map to a line of the return (rules.md B-32; DECISION, owner,
|
||||
/// must map to a line of the return (BS-ledger-11; DECISION, owner,
|
||||
/// 2026-10-20: warn by default; a company may refuse).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum TaxCategoryPolicy {
|
||||
@@ -723,7 +723,7 @@ pub fn holds_printed_tin(text: &str) -> bool {
|
||||
/// EIN (2-7) forms count as there, but a bare run of nine digits joined
|
||||
/// to a letter or to the URL punctuation `/ = ? & #` does not: it is an
|
||||
/// id in a path or query (an app store listing's `id284882215`), not a
|
||||
/// TIN someone wrote down (rules.md B-26).
|
||||
/// TIN someone wrote down (BS-partner-2).
|
||||
pub fn holds_printed_tin_in_link(text: &str) -> bool {
|
||||
printed_tin(text, true)
|
||||
}
|
||||
@@ -1936,7 +1936,7 @@ mod tests {
|
||||
assert_eq!(s.get("company.name").unwrap().seq, 7);
|
||||
}
|
||||
|
||||
/// policy.require_tax_category (rules.md B-32): warn or refuse, one
|
||||
/// policy.require_tax_category (BS-ledger-11): warn or refuse, one
|
||||
/// spelling each ("required" and "require" are refuse), nothing else
|
||||
/// ("off" is no value: the warning is the floor); unset is warn.
|
||||
#[test]
|
||||
|
||||
@@ -18,11 +18,11 @@
|
||||
//! transaction is with both members, each with their share, and
|
||||
//! shares can be apportioned explicitly ("do you allow for
|
||||
//! controlled apportioning?" Yes). docs/parties-and-attachments.md
|
||||
//! "Shares". rules.md B-35 (the sign, direction and money of a
|
||||
//! "Shares". BS-partner-3 (the sign, direction and money of a
|
||||
//! part; DECISION, owner, 2026-10-20: a member's entry counts what
|
||||
//! moved their capital).
|
||||
//! DEFINITIONS:
|
||||
//! target (target(), rules.md B-35 item 3): what the shares split,
|
||||
//! target (target(), BS-partner-3 item 3): what the shares split,
|
||||
//! signed debit-positive as a line on the parties' own account would
|
||||
//! be (positive: the company paid or gave; negative: it received),
|
||||
//! with its direction (paid, received, neither) and what of it moved
|
||||
@@ -188,7 +188,7 @@ pub struct PartyMember {
|
||||
///
|
||||
/// 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).
|
||||
/// checks only [`check_shares_journaled`] (BS-entry-4).
|
||||
pub fn check_shares(shares: &[PartyShare], known: impl Fn(PartyId) -> bool) -> Result<(), String> {
|
||||
check_shares_journaled(shares, known)?;
|
||||
for s in shares {
|
||||
@@ -207,7 +207,7 @@ pub fn check_shares(shares: &[PartyShare], known: impl Fn(PartyId) -> bool) -> R
|
||||
/// 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).
|
||||
/// version wrote always open (BS-entry-4).
|
||||
pub fn check_shares_journaled(
|
||||
shares: &[PartyShare],
|
||||
known: impl Fn(PartyId) -> bool,
|
||||
@@ -304,7 +304,7 @@ fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option<Vec<Decimal>>
|
||||
}
|
||||
|
||||
/// What an entry's shares split, and what of it counts (the module's
|
||||
/// DEFINITIONS: target; rules.md B-35).
|
||||
/// DEFINITIONS: target; BS-partner-3).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Target {
|
||||
/// The whole, signed debit-positive as a line on the parties' own
|
||||
@@ -318,7 +318,7 @@ pub struct Target {
|
||||
pub in_kind: Decimal,
|
||||
/// Which side the parts count on in a party's totals: the direction
|
||||
/// of the entry's root original (itself, unless it is a reversal), so
|
||||
/// a reversal nets what it reverses (B-35 item 4).
|
||||
/// a reversal nets what it reverses (BS-partner-3 item 4).
|
||||
pub counts_as: Direction,
|
||||
}
|
||||
|
||||
@@ -356,7 +356,7 @@ impl Resolved {
|
||||
/// checked; they cover the whole reversal chain (Ledger::set_entry_parties
|
||||
/// INVARIANT 5). Refused (TooLargeToCompute), never a panic, when a sum is
|
||||
/// past exact arithmetic: a draft's lines are as journaled, of any size
|
||||
/// (rules.md B-28).
|
||||
/// (BS-entry-4).
|
||||
pub fn target(
|
||||
ledger: &Ledger,
|
||||
id: EntryId,
|
||||
|
||||
@@ -400,7 +400,7 @@ pub fn check_category(
|
||||
/// no postings, so nothing of its own reaches the return).
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: the accounts a tax category is for (rules.md B-32).
|
||||
/// GOAL: the accounts a tax category is for (BS-ledger-11).
|
||||
/// SOURCE: IRS Pub. 583, "Your books must show your gross income, as well
|
||||
/// as your deductions and credits"; Rev. Proc. 98-25 §5.01, a
|
||||
/// relationship between "the amounts ... by account and the
|
||||
@@ -540,7 +540,7 @@ struct CategoryBuild {
|
||||
/// Build the tax summary for `[start, end]`, closing entries excluded (like
|
||||
/// the P&L). Each category's deductible amount is the exact sum of its
|
||||
/// accounts' shares (book × deductible percent ÷ 100), rounded once to
|
||||
/// the cent, half away from zero (B-21: "round off only the total"); the
|
||||
/// the cent, half away from zero (BS-entry-3: "round off only the total"); the
|
||||
/// book amounts stay exact. The share arithmetic is
|
||||
/// [`crate::kernel::deductible_amount`], so Kani proves the one rounding.
|
||||
pub fn tax_summary(
|
||||
|
||||
@@ -72,7 +72,7 @@
|
||||
//! 2. IF a fixed asset is in service during the span:
|
||||
//! - SHOULD leave the tax net income open, with the book depreciation
|
||||
//! posted in the span
|
||||
//! BECAUSE tax depreciation is the CPA's (rules.md B-15, B-25).
|
||||
//! BECAUSE tax depreciation is the CPA's (BS-asset-1, BS-asset-4).
|
||||
//! 3. IF nothing but cash comes in and goes out:
|
||||
//! - SHOULD still leave the tax net income open, the book share known
|
||||
//! BECAUSE income "as figured for tax purposes" is the return's.
|
||||
@@ -89,9 +89,9 @@ use rust_decimal::Decimal;
|
||||
/// `[start, end]`: its lines on the asset's depreciation expense account,
|
||||
/// debit-positive (the depreciation still due through the disposal day,
|
||||
/// or, negative, what the month's run posted past it, credited back:
|
||||
/// rules.md B-15 rule 5). With the runs
|
||||
/// BS-asset-1 rule 5). With the runs
|
||||
/// (`Ledger::depreciation_posted_between`) it is the asset's depreciation
|
||||
/// expense in the span, the P&L's and the cash flow's (B-14 rule 8).
|
||||
/// expense in the span, the P&L's and the cash flow's (BS-statement-3 rule 8).
|
||||
/// The disposal entry is the posted entry dated the disposal day that
|
||||
/// credits the asset's cost account by its cost (`Store::dispose_asset`
|
||||
/// posts it so).
|
||||
@@ -215,7 +215,7 @@ pub enum Open {
|
||||
pub enum Note {
|
||||
/// Property contributed in `entry` to a prepaid account (the balance
|
||||
/// account of a prepaid-expense schedule: a service contract the
|
||||
/// member handed over, B-13) with no fixed asset for it: its §723
|
||||
/// member handed over, BS-partner-1) with no fixed asset for it: its §723
|
||||
/// basis is taken as its book amount, this member's share `book`
|
||||
/// (DECISION, P3 review 2026-10-21: the contract's carryover basis is
|
||||
/// what the books recorded for it; the CPA to confirm).
|
||||
@@ -342,7 +342,7 @@ fn too_large() -> LedgerError {
|
||||
}
|
||||
|
||||
/// A running split of amounts among members, one split at a time, each
|
||||
/// by its own weights (B-36, the odd cent as D-38 settles it): each
|
||||
/// by its own weights (BS-partner-4, the odd cent as D-38 settles it): each
|
||||
/// member's running total is rounded afresh from their exact running
|
||||
/// total, so it never drifts a cent from it, and tied cents don't pile up
|
||||
/// on one member. The worksheet keeps one per set of members with weight
|
||||
@@ -354,8 +354,8 @@ fn too_large() -> LedgerError {
|
||||
/// distributed is a cent or more from their exact share, however
|
||||
/// many entries it is summed over; three equal odd-cent properties
|
||||
/// contributed 50/50 leave the members one cent apart, never three.
|
||||
/// SOURCE: rules.md B-36 (shared within each entry as its book value is),
|
||||
/// B-13 (cent rounding by largest remainder: DECISION, owner
|
||||
/// SOURCE: BS-partner-4 (shared within each entry as its book value is),
|
||||
/// BS-partner-1 (cent rounding by largest remainder: DECISION, owner
|
||||
/// 2026-10-13); DECISION D-38 (owner, 2026-10-20: odd cents
|
||||
/// everywhere alike, cumulative largest remainder), here for the
|
||||
/// tax basis by the owner's ask, 2026-10-22 (kernel::
|
||||
@@ -552,7 +552,7 @@ impl RunningSplit {
|
||||
/// it is rounded to the cent ([`RunningSplit`] INVARIANT 4).
|
||||
const EXACT_PLACES: u32 = 10;
|
||||
|
||||
/// The four amounts an entry's members share (B-36): the property's
|
||||
/// The four amounts an entry's members share (BS-partner-4): the property's
|
||||
/// built-in gain, its property without a basis, its prepaid at book (each
|
||||
/// by the members' property in it) and the property it distributes (by
|
||||
/// what each took).
|
||||
@@ -632,14 +632,14 @@ fn entry_wholes(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Every entry's parts of the amounts it splits (B-36 with D-38), from
|
||||
/// Every entry's parts of the amounts it splits (BS-partner-4 with D-38), from
|
||||
/// the books' first entry through `end`, whatever span the worksheet is
|
||||
/// asked for, so an entry's cents are the same in every span it is in.
|
||||
///
|
||||
/// ```text
|
||||
/// GOAL: odd cents that run (RunningSplit) and never touch a member who
|
||||
/// has no part in the entry, nor change with the span asked for.
|
||||
/// SOURCE: rules.md B-36; DECISION D-38; Form 1065 Item L (a partner's
|
||||
/// SOURCE: BS-partner-4; DECISION D-38; Form 1065 Item L (a partner's
|
||||
/// capital contributed is the basis of the property that partner
|
||||
/// contributed).
|
||||
/// INVARIANTS:
|
||||
|
||||
@@ -296,7 +296,7 @@ fn schedule_through_purchase_date_covers_one_day() {
|
||||
|
||||
#[test]
|
||||
fn van_schedule_is_the_hand_computed_one() {
|
||||
// Rank 1, computed by hand (rules.md B-15), replacing an unreviewed
|
||||
// Rank 1, computed by hand (BS-asset-1), replacing an unreviewed
|
||||
// golden file (2026-10-13; every row of the old file was checked
|
||||
// against this computation first, and matched).
|
||||
// $60,000 over 60 months is $1,000 a month. Bought 2026-01-15: January
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The audit's statements checks (plan P8; rules.md B-45): one test per
|
||||
//! The audit's statements checks (plan P8; BS-ledger-13): one test per
|
||||
//! finding code, each seeding exactly the defect the code names.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
@@ -281,7 +281,7 @@ impl<'a> Books<'a> {
|
||||
s.rounding
|
||||
);
|
||||
// The engine splits a close among the members by largest
|
||||
// remainder (rules.md B-13): an example closing to the members
|
||||
// remainder (BS-partner-1): an example closing to the members
|
||||
// says so.
|
||||
assert!(
|
||||
s.rounding == "largest-remainder"
|
||||
|
||||
@@ -16,7 +16,7 @@ pub(crate) fn account_type(a: &AccountSpec, id: &str) -> AccountType {
|
||||
}
|
||||
|
||||
/// The period `[from, to]` a period query covers, each date omitted
|
||||
/// resolved by the one rule (rules.md B-30) on `setup.today`; panics on
|
||||
/// resolved by the one rule (BS-period-3) on `setup.today`; panics on
|
||||
/// `as_of`, on an omitted date without `setup.today`, and on a period the
|
||||
/// rule refuses.
|
||||
pub(crate) fn period(ex: &Example, x: &Expect) -> (NaiveDate, NaiveDate) {
|
||||
@@ -55,8 +55,8 @@ pub(crate) fn resolved_q_period(
|
||||
defaults(ex, &q.name).statement(from, to)
|
||||
}
|
||||
|
||||
/// The day an as-of query is made as of (omitted: `setup.today`, rules.md
|
||||
/// B-30); panics on `from` or `to`.
|
||||
/// The day an as-of query is made as of (omitted: `setup.today`,
|
||||
/// BS-period-3); panics on `from` or `to`.
|
||||
pub(crate) fn day(ex: &Example, x: &Expect) -> NaiveDate {
|
||||
let q = x.query();
|
||||
resolved_q_day(ex, &q).unwrap_or_else(|e| panic!("{}: {}: {e}", ex.id, x.query))
|
||||
@@ -83,12 +83,12 @@ pub(crate) trait Pipe: Sized {
|
||||
}
|
||||
}
|
||||
impl<T> Pipe for T {}
|
||||
/// What an omitted date means for `ex` (rules.md B-30): its fiscal year
|
||||
/// What an omitted date means for `ex` (BS-period-3): its fiscal year
|
||||
/// on `setup.today`, which `query` needs.
|
||||
pub(crate) fn defaults(ex: &Example, query: &str) -> PeriodDefaults {
|
||||
let today = ex.setup.today.as_deref().unwrap_or_else(|| {
|
||||
panic!(
|
||||
"{}: {query} omits a date: setup.today says what it means (rules.md B-30)",
|
||||
"{}: {query} omits a date: setup.today says what it means (BS-period-3)",
|
||||
ex.id
|
||||
)
|
||||
});
|
||||
|
||||
@@ -411,7 +411,7 @@ impl Books<'_> {
|
||||
};
|
||||
// Each write-off's own notice: identical bytes would be one
|
||||
// record (plan P6 step 4), and a receipt evidences one entry
|
||||
// (B-38), so a second write-off with the first's letter is
|
||||
// (BS-arap-2), so a second write-off with the first's letter is
|
||||
// refused before anything is journaled.
|
||||
let letter = format!(
|
||||
"%PDF-1.4\nFinal demand for invoice {invoice}: {}\n%%EOF\n",
|
||||
|
||||
@@ -218,7 +218,7 @@ pub(crate) fn a_members_close_declared_with_another_rounding_is_refused() {
|
||||
});
|
||||
}
|
||||
|
||||
/// A period's dates are the rule's (rules.md B-30): an example saying the
|
||||
/// A period's dates are the rule's (BS-period-3): an example saying the
|
||||
/// fiscal year to date starts on January 1 under a July fiscal year fails.
|
||||
#[test]
|
||||
#[should_panic(expected = "period from")]
|
||||
@@ -560,7 +560,7 @@ pub(crate) fn a_members_reconciliation_shows_every_cause() {
|
||||
}
|
||||
|
||||
/// A project named twice in `setup.projects` is refused (names are
|
||||
/// unique, rules.md B-37).
|
||||
/// unique, BS-statement-5).
|
||||
#[test]
|
||||
#[should_panic(expected = "a project named")]
|
||||
pub(crate) fn a_project_named_twice_is_refused() {
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
|
||||
pub(crate) use std::borrow::Borrow;
|
||||
pub(crate) use std::collections::{BTreeMap, BTreeSet};
|
||||
pub(crate) use std::path::Path;
|
||||
pub(crate) use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) use chrono::{Datelike, NaiveDate};
|
||||
pub(crate) use ledger_core::calendar::{PeriodDefaults, period_defaults};
|
||||
@@ -93,4 +93,5 @@ mod pin;
|
||||
mod queries;
|
||||
mod rules_md;
|
||||
mod run;
|
||||
mod source_refs;
|
||||
mod sources;
|
||||
@@ -225,7 +225,7 @@ impl Books<'_> {
|
||||
/// Check one `run` expectation: what the `run_depreciation` event `event`
|
||||
/// posted (`amount`: zero when nothing was due, or the month already had
|
||||
/// its run) and, of it, what it caught up beyond its own month's
|
||||
/// depreciation (`caught_up`), both listed (rules.md B-15).
|
||||
/// depreciation (`caught_up`), both listed (BS-asset-1).
|
||||
pub(crate) fn check_run(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
undated(ex, x);
|
||||
@@ -256,7 +256,7 @@ pub(crate) fn check_run(b: &Books<'_>, x: &Expect) {
|
||||
}
|
||||
|
||||
/// Check one `disposal` expectation: what the disposal of `asset` took, as
|
||||
/// the engine computed it when posting it (rules.md B-15), every figure
|
||||
/// the engine computed it when posting it (BS-asset-1), every figure
|
||||
/// listed: `final_depreciation` (posted in its own entry before the
|
||||
/// disposal), `catch_up_depreciation` and `excess_depreciation` (charged,
|
||||
/// and credited back, in the disposal entry), `accumulated` (cleared),
|
||||
@@ -288,7 +288,7 @@ pub(crate) fn check_disposal(b: &Books<'_>, x: &Expect) {
|
||||
}
|
||||
|
||||
/// Check one `depreciation_schedule` expectation: the schedule of `asset`
|
||||
/// through `as_of` (rules.md B-15), each month named (`"YYYY-MM"`) its
|
||||
/// through `as_of` (BS-asset-1), each month named (`"YYYY-MM"`) its
|
||||
/// depreciation, 0.00 for a month the schedule doesn't reach;
|
||||
/// `accumulated` and `book_value` through `as_of`; the example names the
|
||||
/// figures it shows.
|
||||
@@ -326,7 +326,7 @@ pub(crate) fn check_depreciation_schedule(b: &Books<'_>, x: &Expect) {
|
||||
|
||||
/// Check one `schedule_plan` expectation: what the schedule's plan
|
||||
/// recognizes at each month end named (`"YYYY-MM-DD"`, 0.00 at a month end
|
||||
/// the plan doesn't post), and `total`, all it recognizes (rules.md B-16);
|
||||
/// the plan doesn't post), and `total`, all it recognizes (BS-prepaid-1);
|
||||
/// the example names the figures it shows.
|
||||
pub(crate) fn check_schedule_plan(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
@@ -364,7 +364,7 @@ pub(crate) fn check_schedule_plan(b: &Books<'_>, x: &Expect) {
|
||||
}
|
||||
|
||||
/// Check one `register_row` expectation: the asset's row of the fixed
|
||||
/// asset register as of `as_of` (rules.md B-15 rules 7 and 8, B-24):
|
||||
/// asset register as of `as_of` (BS-asset-1 rules 7 and 8, BS-asset-3):
|
||||
/// `acquired` and `in_service` (`YYYY-MM-DD`), `cost`,
|
||||
/// `accumulated_scheduled` (the schedule's), `accumulated_posted` (what
|
||||
/// the books carry), `unposted` (the one less the other), `book_value`
|
||||
@@ -403,7 +403,7 @@ pub(crate) fn check_register_row(b: &Books<'_>, x: &Expect) {
|
||||
}
|
||||
|
||||
/// Check one `register_totals` expectation: the fixed asset register's
|
||||
/// totals as of `as_of`, over the assets held (rules.md B-24, B-25):
|
||||
/// totals as of `as_of`, over the assets held (BS-asset-3, BS-asset-4):
|
||||
/// `total_cost`, `total_accumulated_scheduled`, `total_accumulated_posted`,
|
||||
/// `total_book_value`, `total_depreciable_basis`, `total_tax_basis_723`,
|
||||
/// `missing_basis` (how many held have none), and how it reconciles to
|
||||
@@ -440,7 +440,7 @@ pub(crate) fn check_register_totals(b: &Books<'_>, x: &Expect) {
|
||||
}
|
||||
|
||||
/// Check one `asset_basis` expectation: the asset's basis facts and the
|
||||
/// tax figures they give (rules.md B-25): `rule`,
|
||||
/// tax figures they give (BS-asset-4): `rule`,
|
||||
/// `contributor_adjusted_basis`, `fmv_at_contribution`, `tax_basis_723`,
|
||||
/// `depreciable_basis`, `built_in_gain_704c` (a loss negative), each
|
||||
/// `"none"` where the asset has none (a purchase's §723 basis), and
|
||||
|
||||
@@ -76,7 +76,7 @@ pub(crate) fn every_balance(l: &Ledger) -> Vec<(String, Decimal, Decimal)> {
|
||||
}
|
||||
|
||||
/// Try one command on a copy of the books, as the books' own command does
|
||||
/// it (the engine's checks, then the policy's: rules.md B-31, B-32), and
|
||||
/// it (the engine's checks, then the policy's: BS-ledger-10, BS-ledger-11), and
|
||||
/// check it is accepted or refused for the reason given.
|
||||
pub(crate) fn check_command(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
let mut copy = l.clone();
|
||||
@@ -88,7 +88,7 @@ pub(crate) fn check_command(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| panic!("{}: rename_account gives the name", ex.id));
|
||||
copy.rename_account(account, name).inspect(|()| {
|
||||
// A rename changes the label, nothing else (rules.md B-31).
|
||||
// A rename changes the label, nothing else (BS-ledger-10).
|
||||
assert_eq!(
|
||||
copy.chart().get(account).unwrap().name,
|
||||
name.trim(),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::*;
|
||||
|
||||
/// Check one `period` expectation: the period a period report asked with
|
||||
/// these dates covers, by the one rule (rules.md B-30), as `from` and
|
||||
/// these dates covers, by the one rule (BS-period-3), as `from` and
|
||||
/// `to`; or the rule's refusal.
|
||||
pub(crate) fn check_period(ex: &Example, x: &Expect) {
|
||||
match (resolved_period(ex, x), &x.refused) {
|
||||
@@ -20,7 +20,7 @@ pub(crate) fn check_period(ex: &Example, x: &Expect) {
|
||||
}
|
||||
|
||||
/// Check one `day` expectation: the day a report as of a day is made as
|
||||
/// of (rules.md B-30), as `as_of`.
|
||||
/// of (BS-period-3), as `as_of`.
|
||||
pub(crate) fn check_day(ex: &Example, x: &Expect) {
|
||||
exactly(ex, x, &["as_of".to_string()].into());
|
||||
let want = date(&x.figures(&ex.id)["as_of"], &ex.id);
|
||||
@@ -28,7 +28,7 @@ pub(crate) fn check_day(ex: &Example, x: &Expect) {
|
||||
}
|
||||
|
||||
/// Check one `calendar_year` expectation: the year a calendar-year count
|
||||
/// (1099s, party totals) asked without one counts (rules.md B-30).
|
||||
/// (1099s, party totals) asked without one counts (BS-period-3).
|
||||
pub(crate) fn check_calendar_year(ex: &Example, x: &Expect) {
|
||||
assert!(
|
||||
x.from.is_none() && x.to.is_none() && x.as_of.is_none(),
|
||||
@@ -49,8 +49,8 @@ pub(crate) fn check_calendar_year(ex: &Example, x: &Expect) {
|
||||
|
||||
/// Check one `account_names` expectation: each account's name, by code,
|
||||
/// as the chart holds it and every report prints it (the trial balance
|
||||
/// and the profit and loss, over every date: past periods too, rules.md
|
||||
/// B-31); every account listed.
|
||||
/// and the profit and loss, over every date: past periods too,
|
||||
/// BS-ledger-10); every account listed.
|
||||
pub(crate) fn check_account_names(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
assert!(
|
||||
x.from.is_none() && x.to.is_none() && x.as_of.is_none(),
|
||||
@@ -83,7 +83,7 @@ pub(crate) fn check_account_names(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
|
||||
/// Check one `uncategorized_accounts` expectation: every account that
|
||||
/// maps to a line of the return and has no tax category, with activity or
|
||||
/// not, as `"<code> <name>"`, by code (rules.md B-32).
|
||||
/// not, as `"<code> <name>"`, by code (BS-ledger-11).
|
||||
pub(crate) fn check_uncategorized_accounts(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
assert!(
|
||||
x.from.is_none() && x.to.is_none() && x.as_of.is_none(),
|
||||
|
||||
@@ -192,13 +192,13 @@ impl Books<'_> {
|
||||
/// The 1099 report a `vendor_1099_paid` or `vendor_1099` expectation
|
||||
/// asks for: the calendar year of `to`, from January 1 through `to`, out
|
||||
/// of the cash and financing accounts, an entry's shares resolved with
|
||||
/// the members who are parties (rules.md B-19, B-33).
|
||||
/// the members who are parties (BS-1099-1, BS-statement-4).
|
||||
pub(crate) fn report_1099(
|
||||
b: &Books<'_>,
|
||||
x: &Expect,
|
||||
) -> (NaiveDate, NaiveDate, ledger_core::Vendor1099Report) {
|
||||
let (ex, l) = (b.ex, b.l());
|
||||
// A calendar-year count, never the fiscal default (rules.md B-30):
|
||||
// A calendar-year count, never the fiscal default (BS-period-3):
|
||||
// both dates given.
|
||||
assert!(
|
||||
x.from.is_some() && x.to.is_some(),
|
||||
@@ -231,7 +231,7 @@ pub(crate) fn report_1099(
|
||||
|
||||
/// Check one `vendor_1099_paid` expectation: each payee's payments that
|
||||
/// count toward its 1099 ([`report_1099`]), a payment card's left out,
|
||||
/// every payee listed (rules.md B-19, B-33).
|
||||
/// every payee listed (BS-1099-1, BS-statement-4).
|
||||
pub(crate) fn check_vendor_1099_paid(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
let (from, to, r) = report_1099(b, x);
|
||||
@@ -254,7 +254,7 @@ pub(crate) fn check_vendor_1099_paid(b: &Books<'_>, x: &Expect) {
|
||||
/// applied, and what was `paid` (counts toward its 1099),
|
||||
/// `excluded_card` (a card or payment network's, Form 1099-K),
|
||||
/// `undetermined` (its payment method not recorded) and `not_reportable`
|
||||
/// (paid while decided not reportable); every one given (rules.md B-19).
|
||||
/// (paid while decided not reportable); every one given (BS-1099-1).
|
||||
pub(crate) fn check_vendor_1099(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
let name = x
|
||||
@@ -299,7 +299,7 @@ pub(crate) fn check_vendor_1099(b: &Books<'_>, x: &Expect) {
|
||||
|
||||
/// The money party shares resolve against: the cash accounts (every
|
||||
/// asset account but receivables when none are named), the cards and the
|
||||
/// financing accounts (rules.md B-35 item 5).
|
||||
/// financing accounts (BS-partner-3 item 5).
|
||||
pub(crate) fn party_money(ex: &Example, l: &Ledger) -> MoneyAccounts {
|
||||
ledger_core::parties::money_accounts(
|
||||
l,
|
||||
@@ -320,7 +320,7 @@ pub(crate) fn expect_party(b: &Books<'_>, x: &Expect) -> PartyId {
|
||||
}
|
||||
|
||||
/// Check one `party_part` expectation: entry N's part for the party
|
||||
/// (rules.md B-35): `resolved`, signed as a line on the party's own
|
||||
/// (BS-partner-3): `resolved`, signed as a line on the party's own
|
||||
/// account (debit-positive: paid or given positive, received negative),
|
||||
/// the entry's `direction` (`paid`, `received` or `neither`), and what
|
||||
/// of it moved as money (`cash`) and as property (`in_kind`); every one
|
||||
@@ -368,7 +368,7 @@ pub(crate) fn check_party_part(b: &Books<'_>, x: &Expect) {
|
||||
/// Check one `party_totals` expectation: what was `paid` to and
|
||||
/// `received` from the party from `from` through `to` on `basis` (`cash`:
|
||||
/// money; `all`: money and property in kind), each entry's part on its
|
||||
/// root original's side (rules.md B-35 item 4); both given.
|
||||
/// root original's side (BS-partner-3 item 4); both given.
|
||||
pub(crate) fn check_party_totals(b: &Books<'_>, x: &Expect) {
|
||||
let (ex, l) = (b.ex, b.l());
|
||||
assert!(
|
||||
@@ -421,8 +421,8 @@ pub(crate) fn check_party_totals(b: &Books<'_>, x: &Expect) {
|
||||
);
|
||||
}
|
||||
|
||||
/// Check one `project` expectation (rules.md B-37): the project's
|
||||
/// `revenue`, `expenses` and `net` for the period (B-30 resolving omitted
|
||||
/// Check one `project` expectation (BS-statement-5): the project's
|
||||
/// `revenue`, `expenses` and `net` for the period (BS-period-3 resolving omitted
|
||||
/// dates), the same `to_date` (every tagged line through `to`), and its
|
||||
/// `unrecovered_cost` (`"none"` unless it is on spec); every one given.
|
||||
/// Through ledger_core::project_figures, as the tools and the viewer.
|
||||
@@ -474,7 +474,7 @@ pub(crate) fn check_project(b: &Books<'_>, x: &Expect) {
|
||||
|
||||
/// Check one `party_tin_last4` expectation: the last four of the party's
|
||||
/// TIN the books keep (its TIN facts', else its W-9's; `""` for none:
|
||||
/// rules.md B-26).
|
||||
/// BS-partner-2).
|
||||
pub(crate) fn check_party_tin_last4(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
assert!(
|
||||
|
||||
@@ -389,7 +389,7 @@ pub(crate) fn check_cash_flow(b: &Books<'_>, x: &Expect) {
|
||||
|
||||
/// Check one `trial_balance` expectation: each account's balance as of
|
||||
/// the day, debits less credits (a credit balance negative), every
|
||||
/// account listed (rules.md B-6, B-33).
|
||||
/// account listed (BS-statement-1, BS-statement-4).
|
||||
pub(crate) fn check_trial_balance(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
let as_of = day(ex, x);
|
||||
let tb = trial_balance_as_of(l, as_of);
|
||||
@@ -411,7 +411,7 @@ pub(crate) fn check_trial_balance(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
/// Check one `profit_and_loss` expectation: each revenue and expense
|
||||
/// account's activity over the period on its normal side, closing entries
|
||||
/// left out, and `net_income`, revenue less expenses; every revenue and
|
||||
/// expense account listed (rules.md B-14, B-33).
|
||||
/// expense account listed (BS-statement-3, BS-statement-4).
|
||||
pub(crate) fn check_profit_and_loss(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
let (start, end) = period(ex, x);
|
||||
let pl = profit_and_loss_for_period(l, start, end, None)
|
||||
@@ -506,8 +506,8 @@ pub(crate) fn check_balances(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
/// Check one `members_equity` expectation: the statement of changes in
|
||||
/// members' equity over the period, `"<member>.<column>"` for the columns
|
||||
/// `beginning`, `contributions`, `net_income`, `distributions`, `other`
|
||||
/// and `ending`; the figures named are the example's choice (rules.md
|
||||
/// B-13).
|
||||
/// and `ending`; the figures named are the example's choice (
|
||||
/// BS-partner-1).
|
||||
pub(crate) fn check_members_equity(
|
||||
ex: &Example,
|
||||
l: &Ledger,
|
||||
|
||||
@@ -92,8 +92,8 @@ impl Books<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `k1` expectation: the K-1 worksheet over the period (rules.md
|
||||
/// B-13; Schedule K-1 Item L), `"<member>.<column>"` for the columns
|
||||
/// Check one `k1` expectation: the K-1 worksheet over the period (
|
||||
/// BS-partner-1; Schedule K-1 Item L), `"<member>.<column>"` for the columns
|
||||
/// `beginning`, `contributions_cash`, `contributions_property`,
|
||||
/// `net_income`, `distributions`, `other` and `ending`; the figures named
|
||||
/// are the example's choice. It needs `cash_accounts` (what is money
|
||||
@@ -136,7 +136,7 @@ pub(crate) fn check_k1(ex: &Example, l: &Ledger, members: &[MemberCapital], x: &
|
||||
}
|
||||
}
|
||||
|
||||
/// The tax-basis capital worksheet for `[from, to]` (rules.md B-36), a
|
||||
/// The tax-basis capital worksheet for `[from, to]` (BS-partner-4), a
|
||||
/// row a member, as `k1` reads the book one: it needs the members and
|
||||
/// their shares, and `cash_accounts`.
|
||||
pub(crate) fn tax_capital_rows(b: &Books<'_>, x: &Expect, what: &str) -> Vec<TaxCapitalRow> {
|
||||
@@ -158,7 +158,7 @@ pub(crate) fn tax_capital_rows(b: &Books<'_>, x: &Expect, what: &str) -> Vec<Tax
|
||||
|
||||
/// Check one `k1_tax_basis` expectation: each member's capital account
|
||||
/// for `[from, to]` on the tax basis, as Schedule K-1 Item L reports it
|
||||
/// (rules.md B-36), `"<member>.<line>"` for the lines `beginning`,
|
||||
/// (BS-partner-4), `"<member>.<line>"` for the lines `beginning`,
|
||||
/// `contributions_cash`, `contributions_property`, `net_income`, `other`,
|
||||
/// `distributions` and `ending`, beside `k1`'s book figures; a line the
|
||||
/// books can't know is `"open"`, with what they know so far as
|
||||
@@ -201,8 +201,8 @@ pub(crate) const RECONCILING_CAUSES: [&str; 5] = [
|
||||
];
|
||||
|
||||
/// Check one `k1_reconciliation` expectation: each member's book capital
|
||||
/// less tax-basis capital at the end of `[from, to]`, by cause (rules.md
|
||||
/// B-36), `"<member>.<cause>"` for `beginning`, `built_in_gain_704c`
|
||||
/// less tax-basis capital at the end of `[from, to]`, by cause (
|
||||
/// BS-partner-4), `"<member>.<cause>"` for `beginning`, `built_in_gain_704c`
|
||||
/// (their share of the §704(c) gain or loss at contribution),
|
||||
/// `property_without_basis`, `property_distributed` and `total`: the
|
||||
/// example names the members it shows, each with every cause.
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
//! The source-citation checks (unit S-E, tightened in review).
|
||||
//!
|
||||
//! Every spec block's source clause -- the line that introduces it plus
|
||||
//! its continuation lines in the same comment block, up to the next
|
||||
//! blank comment line or the next uppercase heading -- names a rule or
|
||||
//! a source that exists: a bookspec id the pinned bookspec has, a
|
||||
//! product-rule id in `docs/spec/claims/`, a repo path that exists, a
|
||||
//! code reference that names a real item, or a declared external or
|
||||
//! free-text citation. Path-like and code-reference tokens are checked
|
||||
//! even when a rule id is also cited; they never fall through to the
|
||||
//! free-text branch. Clauses that pass only through the free-text
|
||||
//! branch are counted, and that count is a floor-style constant: it
|
||||
//! changes only on purpose, in the same commit as the constant.
|
||||
//!
|
||||
//! The second check flags any retired rule number (the old wanderbooks
|
||||
//! numbering, a word-boundary capital letter, hyphen and a number from
|
||||
//! 1 to 45) in every tracked text file, outside the excluded index and
|
||||
//! claims files. A deliberately kept occurrence is allow-listed below
|
||||
//! with its exact count per file; the count failing in either
|
||||
//! direction means the list changes only on purpose. Scanning the
|
||||
//! whole file text, not line by line, also catches a reference wrapped
|
||||
//! across lines, filename at the end of one line and the number at the
|
||||
//! start of the next behind a comment prefix.
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn repo_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
|
||||
}
|
||||
|
||||
fn collect_rs(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
collect_rs(&path, out);
|
||||
} else if path.extension().is_some_and(|e| e == "rs") {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_all(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if name == "target" || name == ".git" {
|
||||
continue;
|
||||
}
|
||||
if path.is_dir() {
|
||||
collect_all(&path, out);
|
||||
} else {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids in `text` that start with `prefix`, each cut at the first
|
||||
/// character that cannot be in an id.
|
||||
fn ids_in(text: &str, prefix: &str) -> Vec<String> {
|
||||
let mut ids = Vec::new();
|
||||
let mut rest = text;
|
||||
while let Some(at) = rest.find(prefix) {
|
||||
let tail: String = rest[at..]
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
|
||||
.collect();
|
||||
let body = &tail[prefix.len()..];
|
||||
if body
|
||||
.rsplit('-')
|
||||
.next()
|
||||
.is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()))
|
||||
&& body.contains('-')
|
||||
{
|
||||
ids.push(tail);
|
||||
}
|
||||
rest = &rest[at + prefix.len()..];
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
const EXTERNAL: &[&str] = &[
|
||||
"U.S.C.",
|
||||
"§",
|
||||
"ASC ",
|
||||
"IRS",
|
||||
"Pub.",
|
||||
"Form ",
|
||||
"Treas.",
|
||||
"Rev. Proc.",
|
||||
"IRC",
|
||||
"ISO 4217",
|
||||
"Unicode",
|
||||
"Pacioli",
|
||||
"Instructions for",
|
||||
"RFC ",
|
||||
];
|
||||
|
||||
/// The number of source clauses checked must stay at or above this.
|
||||
const CHECKED_FLOOR: usize = 300;
|
||||
/// Clauses passing only through the declared or external free-text
|
||||
/// branch. Edit this constant, on purpose, in the same commit that
|
||||
/// changes the count.
|
||||
const FREE_TEXT_COUNT: usize = 56;
|
||||
|
||||
fn strip_comment(line: &str) -> Option<String> {
|
||||
let t = line.trim_start();
|
||||
t.strip_prefix("//!")
|
||||
.or_else(|| t.strip_prefix("///"))
|
||||
.or_else(|| t.strip_prefix("//"))
|
||||
.map(|rest| rest.trim().to_string())
|
||||
}
|
||||
|
||||
fn is_heading(content: &str) -> bool {
|
||||
let Some((head, _)) = content.split_once(':') else {
|
||||
return false;
|
||||
};
|
||||
!head.is_empty()
|
||||
&& head.len() <= 32
|
||||
&& head.chars().filter(|c| c.is_ascii_uppercase()).count() >= 2
|
||||
&& head
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || " _-/()".contains(c))
|
||||
}
|
||||
|
||||
fn clean_token(token: &str) -> String {
|
||||
token
|
||||
.trim_start_matches(['`', '"', '\'', '(', '[', '{'])
|
||||
.trim_end_matches(['`', '"', '\'', ')', ']', '}', ',', ';', ':', '.'])
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn is_path_like(token: &str) -> bool {
|
||||
[".md", ".rs", ".toml", ".json"]
|
||||
.iter()
|
||||
.any(|e| token.ends_with(e))
|
||||
}
|
||||
|
||||
struct ClauseCtx<'a> {
|
||||
root: &'a Path,
|
||||
bs_ids: &'a BTreeSet<String>,
|
||||
wb_ids: &'a BTreeSet<String>,
|
||||
identifiers: &'a BTreeSet<String>,
|
||||
basenames: &'a BTreeSet<String>,
|
||||
}
|
||||
|
||||
fn check_clause(clause: &str, ctx: &ClauseCtx<'_>, bad: &mut Vec<String>, at: &str) -> bool {
|
||||
// Returns true when the clause passes only through the free-text branch.
|
||||
let Some(text) = clause.split("SOURCE:").nth(1) else {
|
||||
return false;
|
||||
};
|
||||
let mut errors: Vec<String> = Vec::new();
|
||||
let mut cited = false;
|
||||
for id in ids_in(text, "BS-") {
|
||||
cited = true;
|
||||
if !ctx.bs_ids.contains(&id) {
|
||||
errors.push(format!("unknown bookspec id {id}"));
|
||||
}
|
||||
}
|
||||
for id in ids_in(text, "WB-") {
|
||||
cited = true;
|
||||
if !ctx.wb_ids.contains(&id) {
|
||||
errors.push(format!("unknown product rule {id}"));
|
||||
}
|
||||
}
|
||||
let mut has_path = false;
|
||||
let mut has_ref = false;
|
||||
for raw in text.split_whitespace() {
|
||||
let token = clean_token(raw);
|
||||
if token.contains("://") {
|
||||
continue;
|
||||
}
|
||||
if is_path_like(&token) {
|
||||
let exists = if token.contains('/') {
|
||||
ctx.root.join(&token).exists()
|
||||
} else {
|
||||
ctx.basenames.contains(&token)
|
||||
};
|
||||
if exists {
|
||||
has_path = true;
|
||||
} else {
|
||||
errors.push(format!("path {token} does not exist"));
|
||||
}
|
||||
}
|
||||
if token.contains("::") {
|
||||
let first = token.split("::").next().unwrap_or("");
|
||||
if first == "crate" || first.starts_with("ledger_") {
|
||||
let last = token.rsplit("::").next().unwrap_or("");
|
||||
let ident: String = last
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
|
||||
.collect();
|
||||
if ctx.identifiers.contains(&ident) {
|
||||
has_ref = true;
|
||||
} else {
|
||||
errors.push(format!("code reference {token} names nothing real"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !errors.is_empty() {
|
||||
for e in errors {
|
||||
bad.push(format!("{at}: {e}"));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if cited || has_path || has_ref {
|
||||
return false;
|
||||
}
|
||||
if EXTERNAL.iter().any(|m| text.contains(m)) {
|
||||
return true;
|
||||
}
|
||||
let declared = text.contains("DECISION")
|
||||
|| text.contains("CONVENTION")
|
||||
|| text.contains("CHOICE")
|
||||
|| text.contains("::")
|
||||
|| text.contains("plan ")
|
||||
|| text.contains("plan/")
|
||||
|| text.contains("server.rs")
|
||||
|| text.contains("the module's rule")
|
||||
|| text.contains("the books.")
|
||||
|| text.contains("owner")
|
||||
|| text
|
||||
.split(|c: char| !c.is_ascii_alphanumeric() && c != '-')
|
||||
.any(|t| {
|
||||
(t.starts_with("R-")
|
||||
|| t.starts_with("D-")
|
||||
|| t.starts_with("I-")
|
||||
|| t.starts_with("A-"))
|
||||
&& t.len() > 2
|
||||
&& t[2..].chars().next().is_some_and(|c| c.is_ascii_digit())
|
||||
&& t[2..].chars().all(|c| c.is_ascii_alphanumeric())
|
||||
});
|
||||
if declared {
|
||||
return true;
|
||||
}
|
||||
bad.push(format!(
|
||||
"{at}: source clause cites no rule or source that exists"
|
||||
));
|
||||
false
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub(crate) fn every_source_line_cites_an_existing_rule_or_source() {
|
||||
let root = repo_root();
|
||||
let bs_ids: BTreeSet<String> = bookspec_checker::rules()
|
||||
.iter()
|
||||
.map(|r| r.id.to_string())
|
||||
.collect();
|
||||
assert!(!bs_ids.is_empty(), "the pinned bookspec has rules");
|
||||
|
||||
let claims_dir = root.join("docs/spec/claims");
|
||||
let mut wb_ids = BTreeSet::new();
|
||||
for entry in std::fs::read_dir(&claims_dir).expect("docs/spec/claims") {
|
||||
let path = entry.expect("a claims entry").path();
|
||||
if path.extension().is_some_and(|e| e == "md") {
|
||||
let text = std::fs::read_to_string(&path).expect("a claims file");
|
||||
wb_ids.extend(ids_in(&text, "WB-"));
|
||||
}
|
||||
}
|
||||
assert!(!wb_ids.is_empty(), "the claims files hold product rules");
|
||||
|
||||
// Identifiers declared anywhere under crates/, and file basenames
|
||||
// anywhere in the repo, for the path and code-reference checks.
|
||||
let mut crate_files = Vec::new();
|
||||
collect_all(&root.join("crates"), &mut crate_files);
|
||||
let mut identifiers = BTreeSet::new();
|
||||
for path in crate_files
|
||||
.iter()
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "rs"))
|
||||
{
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
continue;
|
||||
};
|
||||
let words: Vec<&str> = text
|
||||
.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
|
||||
.filter(|w| !w.is_empty())
|
||||
.collect();
|
||||
for pair in words.windows(2) {
|
||||
if matches!(
|
||||
pair[0],
|
||||
"fn" | "struct" | "enum" | "mod" | "const" | "type" | "trait"
|
||||
) {
|
||||
identifiers.insert(pair[1].to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut all_files = Vec::new();
|
||||
collect_all(&root, &mut all_files);
|
||||
let basenames: BTreeSet<String> = all_files
|
||||
.iter()
|
||||
.filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
|
||||
.collect();
|
||||
|
||||
let mut files = Vec::new();
|
||||
for crate_dir in std::fs::read_dir(root.join("crates")).expect("crates") {
|
||||
let base = crate_dir.expect("a crate").path();
|
||||
for sub in ["src", "tests"] {
|
||||
let dir = base.join(sub);
|
||||
if dir.is_dir() {
|
||||
collect_rs(&dir, &mut files);
|
||||
}
|
||||
}
|
||||
}
|
||||
let fuzz_dir = root.join("fuzz");
|
||||
if fuzz_dir.is_dir() {
|
||||
collect_rs(&fuzz_dir, &mut files);
|
||||
}
|
||||
files.sort();
|
||||
assert!(!files.is_empty(), "crates and fuzz hold sources");
|
||||
|
||||
let mut bad = Vec::new();
|
||||
let mut checked = 0usize;
|
||||
let mut free_text = 0usize;
|
||||
for path in &files {
|
||||
let text = std::fs::read_to_string(path).expect("a source file");
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let mut i = 0usize;
|
||||
while i < lines.len() {
|
||||
let Some(content) = strip_comment(lines[i]) else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
if !content.contains("SOURCE:") {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
checked += 1;
|
||||
let at = format!("{}:{}", path.display(), i + 1);
|
||||
let mut clause = content.clone();
|
||||
let mut j = i + 1;
|
||||
while j < lines.len() {
|
||||
let Some(next) = strip_comment(lines[j]) else {
|
||||
break;
|
||||
};
|
||||
if next.is_empty() || is_heading(&next) || next.contains("SOURCE:") {
|
||||
break;
|
||||
}
|
||||
clause.push(' ');
|
||||
clause.push_str(&next);
|
||||
j += 1;
|
||||
}
|
||||
let ctx = ClauseCtx {
|
||||
root: &root,
|
||||
bs_ids: &bs_ids,
|
||||
wb_ids: &wb_ids,
|
||||
identifiers: &identifiers,
|
||||
basenames: &basenames,
|
||||
};
|
||||
if check_clause(&clause, &ctx, &mut bad, &at) {
|
||||
free_text += 1;
|
||||
}
|
||||
i = j.max(i + 1);
|
||||
}
|
||||
}
|
||||
println!("source clauses checked: {checked}");
|
||||
println!("source clauses passing only through the free-text branch: {free_text}");
|
||||
assert!(
|
||||
checked >= CHECKED_FLOOR,
|
||||
"source clauses were found ({checked})"
|
||||
);
|
||||
assert_eq!(
|
||||
free_text, FREE_TEXT_COUNT,
|
||||
"free-text source clauses changed on purpose only: edit FREE_TEXT_COUNT in the same commit"
|
||||
);
|
||||
assert!(
|
||||
bad.is_empty(),
|
||||
"every source clause cites a rule or source that exists:\n{}",
|
||||
bad.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
fn retired_count(text: &str) -> usize {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let mut count = 0usize;
|
||||
let mut i = 0usize;
|
||||
while i < chars.len() {
|
||||
if chars[i] == 'B'
|
||||
&& (i == 0 || !(chars[i - 1].is_alphanumeric() || chars[i - 1] == '_'))
|
||||
&& chars.get(i + 1) == Some(&'-')
|
||||
{
|
||||
let mut j = i + 2;
|
||||
let mut value = 0usize;
|
||||
let mut digits = 0usize;
|
||||
while j < chars.len() && chars[j].is_ascii_digit() {
|
||||
value = value * 10 + chars[j].to_digit(10).unwrap_or(0) as usize;
|
||||
digits += 1;
|
||||
j += 1;
|
||||
}
|
||||
if digits > 0 && (1..=45).contains(&value) {
|
||||
count += 1;
|
||||
}
|
||||
i = j.max(i + 1);
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub(crate) fn no_retired_rule_reference_remains() {
|
||||
let root = repo_root();
|
||||
// Deliberately kept occurrences: path and exact count. Any change
|
||||
// in either direction edits this list, on purpose, in that commit.
|
||||
let allow: &[(&str, usize)] = &[
|
||||
// Kept: user-visible evidence-source strings in program output.
|
||||
("crates/ledger-core/src/ledger.rs", 8),
|
||||
// Kept: goldens are hand-verified expected output.
|
||||
(
|
||||
"crates/ledger-store/tests/golden/draft_states_and_evidence_gate.json",
|
||||
2,
|
||||
),
|
||||
// Kept: user-visible CPA package text in program output.
|
||||
("crates/ledger-package/src/package.rs", 1),
|
||||
// Kept: user-visible tool description text in program output.
|
||||
("crates/ledger-mcp/src/tools/settlements.rs", 1),
|
||||
// Kept: user-visible on-screen contribution note.
|
||||
("crates/ledger-gui/src/pages/projects.rs", 1),
|
||||
];
|
||||
let output = std::process::Command::new("git")
|
||||
.args(["ls-files", "-z"])
|
||||
.current_dir(&root)
|
||||
.output()
|
||||
.expect("git ls-files");
|
||||
assert!(output.status.success(), "git ls-files succeeds");
|
||||
let listing = String::from_utf8_lossy(&output.stdout);
|
||||
let mut bad = Vec::new();
|
||||
let mut seen_allow: BTreeSet<&str> = BTreeSet::new();
|
||||
for rel in listing.split('\0').filter(|s| !s.is_empty()) {
|
||||
if rel.starts_with("plan/")
|
||||
|| rel == "docs/spec/rules.md"
|
||||
|| rel.starts_with("docs/spec/claims/")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let path = root.join(rel);
|
||||
let Ok(text) = std::fs::read_to_string(&path) else {
|
||||
continue;
|
||||
};
|
||||
if text.contains('\0') {
|
||||
continue;
|
||||
}
|
||||
// Whole-text scan: a reference wrapped across a newline and a
|
||||
// comment prefix is still one occurrence of the number.
|
||||
let count = retired_count(&text);
|
||||
if count == 0 {
|
||||
continue;
|
||||
}
|
||||
match allow.iter().find(|(p, _)| *p == rel) {
|
||||
Some((_, expected)) => {
|
||||
seen_allow.insert(rel);
|
||||
if count != *expected {
|
||||
bad.push(format!(
|
||||
"{rel}: {count} kept occurrences, allow-list says {expected}"
|
||||
));
|
||||
}
|
||||
}
|
||||
None => bad.push(format!("{rel}: {count} retired rule reference(s)")),
|
||||
}
|
||||
}
|
||||
for (p, _) in allow {
|
||||
if !seen_allow.contains(p) {
|
||||
bad.push(format!(
|
||||
"{p}: allow-listed file has no kept occurrence left"
|
||||
));
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
bad.is_empty(),
|
||||
"no retired rule reference remains outside the map files and the allow-list:\n{}",
|
||||
bad.join("\n")
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Totals past exact arithmetic are refused, never a panic (kernel sweep
|
||||
//! unit K-U4; rules.md B-21, B-28).
|
||||
//! unit K-U4; BS-entry-3, BS-entry-4).
|
||||
//!
|
||||
//! A replayed journal line is accepted "of any size", so a restored
|
||||
//! figure can sit at `Decimal::MAX`; every sum the engine makes of such
|
||||
|
||||
@@ -116,7 +116,7 @@ fn pay(
|
||||
) -> EntryId {
|
||||
// As replay posts it: money from a vendor on receivables (1200) by
|
||||
// hand, as books an earlier version wrote can hold it; the control
|
||||
// guard (rules.md B-38) refuses that as new work.
|
||||
// guard (BS-arap-2) refuses that as new work.
|
||||
let e = ledger_core::parties::replaying(|| {
|
||||
let e = l.create_entry(date, "payment");
|
||||
let m = Money::new(dec(amt), Currency::USD);
|
||||
@@ -219,7 +219,7 @@ fn cash_paid_per_vendor_and_who_is_reportable() {
|
||||
#[test]
|
||||
fn years_and_thresholds() {
|
||||
let l = books();
|
||||
// SOURCE: rules.md B-19 (sources/irs-1099-thresholds.md; Pub. L.
|
||||
// SOURCE: BS-1099-1 (docs/spec/sources/irs-1099-thresholds.md; Pub. L.
|
||||
// 119-21 §70433(f): payments made after December 31, 2025).
|
||||
assert_eq!(default_threshold(2025), Ok(dec("600")));
|
||||
assert_eq!(default_threshold(2026), Ok(dec("2000")));
|
||||
@@ -805,7 +805,7 @@ fn a_debit_card_payment_from_the_bank_is_excluded_when_tagged() {
|
||||
assert_eq!((v.paid, v.excluded_card), (dec("300.00"), dec("1200.00")));
|
||||
}
|
||||
|
||||
/// Never guessed (B-19): only a company card's account presumes a card.
|
||||
/// Never guessed (BS-1099-1): only a company card's account presumes a card.
|
||||
/// The members' account 2100, left out of the financing accounts, carries
|
||||
/// a member's card; a platform's balance 1050 carries a payment platform.
|
||||
/// Each also pays by check or friends-and-family transfer (counting), so
|
||||
@@ -1511,7 +1511,7 @@ fn an_undated_old_decision_is_in_force_from_the_beginning() {
|
||||
assert!(b.decision_needed);
|
||||
}
|
||||
|
||||
/// kernel::payment_bucket, every one of its 16 cases against the B-19
|
||||
/// kernel::payment_bucket, every one of its 16 cases against the BS-1099-1
|
||||
/// table (a complete check, not a sample).
|
||||
#[test]
|
||||
fn payment_bucket_is_the_table_in_all_16_cases() {
|
||||
@@ -2317,7 +2317,7 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
/// rules.md B-35 item 9: party totals and the 1099 worksheet never
|
||||
/// BS-partner-3 item 9: party totals and the 1099 worksheet never
|
||||
/// contradict. For books whose cash accounts are named, whose company
|
||||
/// card is recorded as a business-card payment method (or that have
|
||||
/// no card at all: without the method, 2050's name says nothing, so
|
||||
@@ -2521,12 +2521,12 @@ fn card_accounts_are_the_company_cards_liabilities() {
|
||||
/// plan/golden-worksheets/1099-worksheet.md before this test was run.
|
||||
/// 2025 and 2026 together pin the year boundary: Dana's 300.00 on
|
||||
/// 2025-12-30 counts in 2025 only, and the threshold moves from 600 to
|
||||
/// 2,000 (rules.md B-19).
|
||||
/// 2,000 (BS-1099-1).
|
||||
#[test]
|
||||
fn golden_1099_worksheet() {
|
||||
let mut l = books();
|
||||
// Record the card (worksheet, "With the card recorded"): Sam's 5,000
|
||||
// is then a card payment, excluded and listed (B-19). books() leaves
|
||||
// is then a card payment, excluded and listed (BS-1099-1). books() leaves
|
||||
// it unrecorded, and other tests rely on that.
|
||||
let card = l.chart().find_by_code("2100").unwrap().id;
|
||||
l.add_instrument(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The audit workpaper's findings for one small book, hand-verified
|
||||
//! (rules.md B-45; plan/golden-worksheets/audit-workpaper.md).
|
||||
//! (BS-ledger-13; plan/golden-worksheets/audit-workpaper.md).
|
||||
//!
|
||||
//! The fixture is a bank, prepaid insurance, capital, two revenue and two
|
||||
//! expense accounts, a 12-month prepaid plan, and a vendor paid from the
|
||||
|
||||
@@ -34,7 +34,7 @@ fn post(ledger: &mut Ledger, date: NaiveDate, description: &str, lines: &[(Accou
|
||||
// As replay posts it: this fixture holds hand lines on the receivable
|
||||
// and payable control accounts (1200, 2000), which books an earlier
|
||||
// version wrote still hold and every report must read; the control
|
||||
// guard (rules.md B-38) refuses them as new work.
|
||||
// guard (BS-arap-2) refuses them as new work.
|
||||
ledger_core::parties::replaying(|| {
|
||||
let id = ledger.create_entry(date, description);
|
||||
for (account, side, amount) in lines {
|
||||
|
||||
@@ -34,7 +34,7 @@ fn usd(amount: u64) -> Money {
|
||||
fn post(ledger: &mut Ledger, date: NaiveDate, description: &str, lines: &[(AccountId, Side, u64)]) {
|
||||
// As replay posts it: these books hold hand lines on receivables or
|
||||
// payables (1200, 2000), which books an earlier version wrote still
|
||||
// hold and every report must read; the control guard (rules.md B-38)
|
||||
// hold and every report must read; the control guard (BS-arap-2)
|
||||
// refuses them as new work.
|
||||
ledger_core::parties::replaying(|| {
|
||||
let id = ledger.create_entry(date, description);
|
||||
@@ -213,7 +213,7 @@ fn out_of_range_amount_is_rejected() {
|
||||
// Big enough to overflow a sum: an error, never a panic, as soon as
|
||||
// the line is added (a draft is summed before it posts: its debits,
|
||||
// its parties' shares; P0 review round 3, S1). Replayed as an earlier
|
||||
// version wrote it (rules.md B-28): accepted into its draft, whose
|
||||
// version wrote it (BS-entry-4): accepted into its draft, whose
|
||||
// post refuses it, never a panic.
|
||||
let id = ledger.create_entry(date(21), "Too big");
|
||||
let old = ledger.create_entry(date(21), "Too big, journaled before the bound");
|
||||
@@ -268,7 +268,7 @@ fn out_of_range_amount_is_rejected() {
|
||||
);
|
||||
}
|
||||
|
||||
/// B-3 (DECISION, owner 2026-10-13: a ledger in one money holds no
|
||||
/// BS-ledger-1 (DECISION, owner 2026-10-13: a ledger in one money holds no
|
||||
/// fractions of its smallest unit). Regression: a payroll run posted
|
||||
/// $65.27794 (found by the store's refusal property in CI, 2026-10-13).
|
||||
#[test]
|
||||
@@ -392,7 +392,7 @@ fn foreign_currency_line_is_rejected() {
|
||||
);
|
||||
}
|
||||
|
||||
/// R-1 / B-3: one currency throughout an entry. Even when every line
|
||||
/// R-1 / BS-ledger-1: one currency throughout an entry. Even when every line
|
||||
/// matches its own account's currency (a chart the ledger never builds
|
||||
/// today, R-5), an entry mixing currencies is refused.
|
||||
#[test]
|
||||
@@ -657,7 +657,7 @@ fn random_balanced_journals_preserve_invariants() {
|
||||
|
||||
// As replay posts them: random lines land on receivables and
|
||||
// payables by hand, as books an earlier version wrote can hold them
|
||||
// (the control guard, rules.md B-38, refuses them as new work).
|
||||
// (the control guard, BS-arap-2, refuses them as new work).
|
||||
ledger_core::parties::replaying(|| {
|
||||
for i in 0..300u32 {
|
||||
let total = rng.next(100_000) + 100;
|
||||
@@ -755,7 +755,7 @@ fn entry_movements_sum_to_zero() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cash flow statement (direct method, rules.md B-14).
|
||||
// Cash flow statement (direct method, BS-statement-3).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
use ledger_core::NewAsset;
|
||||
@@ -797,8 +797,8 @@ fn cash_flow_reconciles_to_change_in_cash() {
|
||||
assert!(r.lines.iter().all(|l| l.label != "Depreciation"));
|
||||
|
||||
// Operating, by the direct method: collected 1,500 (class (a)); paid
|
||||
// 2,500 for equipment (not a registered asset: operating, rules.md
|
||||
// B-14 rule 12's limits) and 800 rent (class (d)) = -1,800. Reconciled:
|
||||
// 2,500 for equipment (not a registered asset: operating,
|
||||
// BS-statement-3 rule 12's limits) and 800 rent (class (d)) = -1,800. Reconciled:
|
||||
// 3,200 net income - 2,500 increase in AR (4,000 billed - 1,500
|
||||
// collected) - 2,500 increase in equipment = -1,800.
|
||||
// Financing: +10,000 owner contribution. Sum = 8,200. Reconciles.
|
||||
@@ -974,7 +974,7 @@ fn cash_flow_with_registered_asset_and_disposal() {
|
||||
// payroll, and closes to accounts it finds by code. When an account with
|
||||
// that code exists but is the wrong kind, it refuses, says why, and changes
|
||||
// nothing, rather than posting to it or forcing the chart into its
|
||||
// numbering. SOURCE: rules.md B-4 (the elements), DECISION.
|
||||
// numbering. SOURCE: BS-ledger-2 (the elements), DECISION.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn books_with(code: &str, name: &str, t: AccountType, placeholder: bool) -> Ledger {
|
||||
@@ -1110,7 +1110,7 @@ fn a_close_refuses_a_3999_that_is_not_equity() {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A child account subdivides its parent, so it is the same kind of
|
||||
/// account. SOURCE: rules.md B-4; DECISION (owner, 2026-10-13).
|
||||
/// account. SOURCE: BS-ledger-2; DECISION (owner, 2026-10-13).
|
||||
#[test]
|
||||
fn a_child_account_has_its_parents_type() {
|
||||
let mut l = Ledger::new(Currency::USD);
|
||||
@@ -1168,7 +1168,7 @@ fn periods_nest_but_never_partially_overlap() {
|
||||
}
|
||||
|
||||
/// A line names a real, postable account when it is added, not only when
|
||||
/// the entry posts. DECISION (owner, 2026-10-13); rules.md B-1.
|
||||
/// the entry posts. DECISION (owner, 2026-10-13); BS-entry-1.
|
||||
#[test]
|
||||
fn a_line_on_an_unknown_or_placeholder_account_is_refused_when_added() {
|
||||
let c = fixture_company();
|
||||
@@ -1202,7 +1202,7 @@ fn a_line_on_an_unknown_or_placeholder_account_is_refused_when_added() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Spec (rules.md B-3; DECISION, owner 2026-10-13, after the GnuCash
|
||||
/// Spec (BS-ledger-1; DECISION, owner 2026-10-13, after the GnuCash
|
||||
/// cross-check): a foreign line is booked in the base currency's smallest
|
||||
/// unit, half away from zero; the foreign original is kept.
|
||||
#[test]
|
||||
@@ -1392,7 +1392,7 @@ fn reconciling_a_card_reads_its_normal_side_and_includes_the_statement_date() {
|
||||
assert_eq!(outstanding, vec![date(21), date(25)]);
|
||||
}
|
||||
|
||||
/// B-11: closing to retained earnings with nothing to close but a swept
|
||||
/// BS-period-1: closing to retained earnings with nothing to close but a swept
|
||||
/// account's balance still sweeps it.
|
||||
#[test]
|
||||
fn a_close_sweeps_dividends_even_without_income() {
|
||||
@@ -1473,7 +1473,7 @@ fn a_last_absorbs_close_gives_the_rounding_to_the_last_member() {
|
||||
assert_eq!(got, vec![cents(32), cents(32), cents(41)]);
|
||||
}
|
||||
|
||||
/// B-12: a period whose closing date already lies in a closed period
|
||||
/// BS-period-2: a period whose closing date already lies in a closed period
|
||||
/// can't close; the refusal names that period.
|
||||
#[test]
|
||||
fn a_period_ending_inside_a_closed_period_cannot_close() {
|
||||
@@ -1499,7 +1499,7 @@ fn a_period_ending_inside_a_closed_period_cannot_close() {
|
||||
|
||||
/// Replay (for journaling stores) rebuilds invoice and bill records
|
||||
/// exactly: ids follow the allocator, each record tags its entry's control
|
||||
/// line and each payment its entry's (rules.md B-38), vendors tag the
|
||||
/// line and each payment its entry's (BS-arap-2), vendors tag the
|
||||
/// entries. A record replayed out of order is refused.
|
||||
#[test]
|
||||
fn replayed_documents_and_payments_rebuild_the_records() {
|
||||
@@ -1611,10 +1611,10 @@ fn replayed_documents_and_payments_rebuild_the_records() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Drafts: a state, and a way out (plan P4, rules.md B-43).
|
||||
// Drafts: a state, and a way out (plan P4, BS-entry-5).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Spec (rules.md B-43; Lean `Step.discard` and `hdrafts`): a period with
|
||||
/// Spec (BS-entry-5; Lean `Step.discard` and `hdrafts`): a period with
|
||||
/// an open draft can't close; once the draft is discarded it can, and
|
||||
/// nothing posted moved: balances, order and ids are as they were.
|
||||
#[test]
|
||||
|
||||
@@ -133,7 +133,7 @@ proptest! {
|
||||
prop_assert_eq!(ri, kernel::reversal(&to_dec(&lines)));
|
||||
}
|
||||
|
||||
/// The 1099 kernel (rules.md B-19): a payment split into its buckets,
|
||||
/// The 1099 kernel (BS-1099-1): a payment split into its buckets,
|
||||
/// and netted, the same at both types.
|
||||
#[test]
|
||||
fn payment_buckets_agree(lines in arb_lines()) {
|
||||
@@ -277,7 +277,7 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 3: the statement of cash flows' per-entry split
|
||||
/// BS-statement-3 rule 3: the statement of cash flows' per-entry split
|
||||
/// (`kernel::entry_flows`, Kani `entry_flows_*`) is the same at both
|
||||
/// instantiations, on balanced and unbalanced lines alike.
|
||||
#[test]
|
||||
@@ -324,7 +324,7 @@ proptest! {
|
||||
);
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 11: `kernel::constructive` (what a member or
|
||||
/// BS-statement-3 rule 11: `kernel::constructive` (what a member or
|
||||
/// lender paid or received for the company; Kani
|
||||
/// `constructive_nets_to_zero`, `constructive_mirrors`) agrees at both
|
||||
/// instantiations.
|
||||
@@ -347,7 +347,7 @@ proptest! {
|
||||
prop_assert_eq!(ti.into_iter().map(dec).collect::<Vec<_>>(), td);
|
||||
}
|
||||
|
||||
/// rules.md B-35: a party's target, and a reversal's, are the same on
|
||||
/// BS-partner-3: a party's target, and a reversal's, are the same on
|
||||
/// i64 cents and on Decimal.
|
||||
#[test]
|
||||
fn party_target_agrees(
|
||||
@@ -565,7 +565,7 @@ proptest! {
|
||||
prop_assert_eq!(narrow.map(|n| Decimal::new(n, 4)), wide);
|
||||
}
|
||||
|
||||
/// The tax summary's one rounding (rules.md B-32, B-21):
|
||||
/// The tax summary's one rounding (BS-ledger-11, BS-entry-3):
|
||||
/// `kernel::deductible_amount` at i64 cents (what Kani
|
||||
/// `deductible_amount_rounds_once` proved) and at Decimal dollars
|
||||
/// agree on the same accounts, and the Decimal result keeps the laws:
|
||||
|
||||
@@ -361,7 +361,7 @@ fn round_places_keeps_the_old_scale() {
|
||||
}
|
||||
|
||||
/// `round_minor` picks the currency's own unit; a currency with none is
|
||||
/// returned exactly (the FX rule, B-3).
|
||||
/// returned exactly (the FX rule, BS-ledger-1).
|
||||
#[test]
|
||||
fn round_minor_follows_the_currency() {
|
||||
use ledger_core::Currency;
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! transcribed into the simplest Rust that has the same observable
|
||||
//! behavior: a list of accounts, a list of drafts, an append-only list of
|
||||
//! posted entries, a list of periods, and loops. It is written from the
|
||||
//! spec (rules.md, the Ledger doc comments), not from ledger.rs.
|
||||
//! spec (bookspec's rules and `docs/spec/claims/`, the Ledger doc
|
||||
//! comments), not from ledger.rs.
|
||||
//!
|
||||
//! Random command sequences, weighted toward commands that interact (post
|
||||
//! a draft, reverse a posted entry, close a period with drafts in it,
|
||||
@@ -55,7 +56,7 @@ struct MPeriod {
|
||||
struct Model {
|
||||
/// (id, code, type, placeholder, name). The name is outside the Lean
|
||||
/// model (its chart is code and type): kept here so the two agree on
|
||||
/// renames' refusals, and a rename moves nothing else (rules.md B-31).
|
||||
/// renames' refusals, and a rename moves nothing else (BS-ledger-10).
|
||||
accounts: Vec<(u64, String, AccountType, bool, String)>,
|
||||
drafts: Vec<MEntry>,
|
||||
posted: Vec<MEntry>,
|
||||
@@ -122,7 +123,7 @@ impl Model {
|
||||
self.next_account += 1;
|
||||
}
|
||||
|
||||
/// rules.md B-31: a name is free for `account` (None: a new one) when
|
||||
/// BS-ledger-10: a name is free for `account` (None: a new one) when
|
||||
/// it isn't blank, holds no nine digits in a row, and no other account
|
||||
/// (all are top-level here, so all are siblings) has it, ignoring
|
||||
/// capitals and surrounding space.
|
||||
@@ -140,7 +141,7 @@ impl Model {
|
||||
.any(|a| Some(a.0) != account && a.4.trim().to_lowercase() == key)
|
||||
}
|
||||
|
||||
/// rules.md B-31: rename an account that exists to a free name other
|
||||
/// BS-ledger-10: rename an account that exists to a free name other
|
||||
/// than its own; only the name changes.
|
||||
fn rename(&mut self, id: u64, name: &str) -> bool {
|
||||
let Some(i) = self.accounts.iter().position(|a| a.0 == id) else {
|
||||
@@ -363,7 +364,7 @@ impl Model {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// No 1200 or 2000: a line by hand on a receivables or payables account is
|
||||
// refused (the control guard, rules.md B-38), which this model leaves to
|
||||
// refused (the control guard, BS-arap-2), which this model leaves to
|
||||
// spec_arap.rs.
|
||||
const CODES: [&str; 7] = ["1000", "2100", "3000", "3999", "4000", "6000", "1900"];
|
||||
/// New names: a free one, its own in other capitals and spacing, a
|
||||
@@ -400,7 +401,7 @@ enum Cmd {
|
||||
Reverse(usize, u32),
|
||||
CreatePeriod(u32, u32),
|
||||
Close(usize),
|
||||
/// Rename an account (rules.md B-31): `Step.record` in the Lean model,
|
||||
/// Rename an account (BS-ledger-10): `Step.record` in the Lean model,
|
||||
/// whose chart has no names.
|
||||
Rename(usize, usize),
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The odd cent (P3 defect 17; rules.md B-13; D-10, D-38): members closes
|
||||
//! The odd cent (P3 defect 17; BS-partner-1; D-10, D-38): members closes
|
||||
//! split earnings cumulatively, each member's share of everything closed
|
||||
//! to these members and shares so far less what earlier closes gave them,
|
||||
//! and the statement of members' equity, the K-1 worksheet and the viewer
|
||||
@@ -358,7 +358,7 @@ fn a_true_up_rides_on_a_distribution_sweep() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Where a count starts: a set of members and shares (B-13; §706(d))
|
||||
// Where a count starts: a set of members and shares (BS-partner-1; §706(d))
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A reorder of the members is not a change: [A, B] closes January's cent
|
||||
@@ -509,7 +509,7 @@ fn a_journaled_start_other_than_the_derived_one_is_refused() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The minor unit (B-3): whole yen, thousandths of a dinar
|
||||
// The minor unit (BS-ledger-1): whole yen, thousandths of a dinar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// P3 brief item 6: a yen book closes to its members in whole yen. 101
|
||||
@@ -577,7 +577,7 @@ fn a_dinar_book_closes_to_members_in_thousandths() {
|
||||
/// A currency ISO 4217 gives no minor unit (gold, XAU) splits to the finest
|
||||
/// amount a line may carry (kernel::MAX_LINE_SCALE places), so every amount
|
||||
/// is a whole number of the unit it splits to and no member is ever one
|
||||
/// from exact (B-13's precondition). 0.019 at 33.33% / 33.33% / 33.34% is
|
||||
/// from exact (BS-partner-1's precondition). 0.019 at 33.33% / 33.33% / 33.34% is
|
||||
/// exactly 0.0063327 / 0.0063327 / 0.0063346: each member takes theirs.
|
||||
/// Split to cents instead, the floors (0.00 each) left 0.019, a cent and
|
||||
/// 0.009 of one, all of it to the largest remainder: C 0.019, A and B
|
||||
@@ -835,7 +835,7 @@ fn nth_month(i: usize) -> (i32, u32) {
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(512))]
|
||||
|
||||
/// Oracle: rules.md B-13 and close INVARIANT 6, hand-stated: after
|
||||
/// Oracle: BS-partner-1 and close INVARIANT 6, hand-stated: after
|
||||
/// any history (closes under the legacy rules, then months closed to
|
||||
/// the members in either order, to retained earnings, or left open),
|
||||
/// every members close hands out exactly its net; once a cumulative
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
//! pinned container (bookspec's `gnucash/oracle/`, image
|
||||
//! `bookspec-gnucash-oracle`), and compares every account's
|
||||
//! balance at month ends and random dates, exactly. A difference is a
|
||||
//! finding to adjudicate from principles (rules.md), never a reason to
|
||||
//! finding to adjudicate from principles (bookspec's rules and
|
||||
//! `docs/spec/claims/`), never a reason to
|
||||
//! change wanderbooks to match.
|
||||
//!
|
||||
//! Needs Docker: `just oracle` builds the image and runs this.
|
||||
@@ -283,7 +284,7 @@ fn balances_match_gnucash_on_generated_books() {
|
||||
);
|
||||
assert!(
|
||||
diffs.is_empty(),
|
||||
"{} difference(s) with GnuCash; adjudicate each from rules.md:\n{}",
|
||||
"{} difference(s) with GnuCash; adjudicate each from bookspec's rules (docs/spec/claims/):\n{}",
|
||||
diffs.len(),
|
||||
diffs.join("\n")
|
||||
);
|
||||
|
||||
@@ -389,7 +389,7 @@ proptest! {
|
||||
|
||||
/// A fiscal year start as the books may hold one: any month and day 2001
|
||||
/// has (a new setting is the first of a month; replay takes any day every
|
||||
/// year has, rules.md B-28).
|
||||
/// year has, BS-entry-4).
|
||||
fn arb_fiscal_start() -> impl Strategy<Value = (u32, u32)> {
|
||||
(1u32..=12, 1u32..=31).prop_filter("a day 2001 has", |&(m, d)| {
|
||||
NaiveDate::from_ymd_opt(2001, m, d).is_some()
|
||||
@@ -411,7 +411,7 @@ fn arb_calendar_day() -> impl Strategy<Value = NaiveDate> {
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(5000))]
|
||||
|
||||
/// rules.md B-30, PeriodDefaults INVARIANTS 1-5, for every fiscal
|
||||
/// BS-period-3, PeriodDefaults INVARIANTS 1-5, for every fiscal
|
||||
/// year start the books hold, every today in the calendar, and every
|
||||
/// mix of given and omitted dates: the resolved dates are the given
|
||||
/// ones or the defaults, never swapped; Err exactly when the resolved
|
||||
@@ -596,7 +596,7 @@ mod p3 {
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(500))]
|
||||
|
||||
/// depreciation_schedule INVARIANT 5 (rules.md B-15; defect 22): accumulated depreciation never falls,
|
||||
/// depreciation_schedule INVARIANT 5 (BS-asset-1; defect 22): accumulated depreciation never falls,
|
||||
/// never exceeds cost − salvage, is 0 before the in-service date and
|
||||
/// cost − salvage from the life's last day on; each schedule's lines
|
||||
/// sum to its accumulated and none is negative. Sampled through: every
|
||||
@@ -680,7 +680,7 @@ proptest! {
|
||||
prop_assert_eq!(scheduled_book_value(a, on).unwrap(), want.book_value);
|
||||
}
|
||||
|
||||
/// B-15 rule 3 (defect 22), against arithmetic written here: through
|
||||
/// BS-asset-1 rule 3 (defect 22), against arithmetic written here: through
|
||||
/// any day k of the life's final month (its d days), accumulated is C +
|
||||
/// (D − C) × k / d rounded half up to the cent, C the exact charge of
|
||||
/// the months before (D × each month's days held over its days, over
|
||||
@@ -719,7 +719,7 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
/// B-15 rule 4 (depreciation_schedule INVARIANT 6; P3 depreciation brief 2.3, R1, R8): through every
|
||||
/// BS-asset-1 rule 4 (depreciation_schedule INVARIANT 6; P3 depreciation brief 2.3, R1, R8): through every
|
||||
/// month end of the life, the schedule is the pre-P3 running total
|
||||
/// (USD, a two-place currency), except where the exact cumulative is a
|
||||
/// half-cent tie, which the old 28-digit Decimal quotients could round
|
||||
@@ -895,8 +895,8 @@ fn arb_basis_rule() -> impl Strategy<Value = ledger_core::BasisRule> {
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(5000))]
|
||||
|
||||
/// kernel::basis_figures INVARIANTS 1-4 on Decimal money (rules.md
|
||||
/// B-25): a purchase depreciates from cost and has no §723 basis or
|
||||
/// kernel::basis_figures INVARIANTS 1-4 on Decimal money (
|
||||
/// BS-asset-4): a purchase depreciates from cost and has no §723 basis or
|
||||
/// built-in gain; a contribution's §723 basis is the adjusted basis,
|
||||
/// its built-in gain fair market value less that basis, negative
|
||||
/// exactly when the basis exceeds the value; carryover depreciates
|
||||
@@ -937,7 +937,7 @@ proptest! {
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(256))]
|
||||
|
||||
/// rules.md B-37 item 3: for any tags and any period, the projects'
|
||||
/// BS-statement-5 item 3: for any tags and any period, the projects'
|
||||
/// figures plus the untagged lines' are the period's profit and loss
|
||||
/// (no line counted twice or lost), each through
|
||||
/// ledger_core::project_figures.
|
||||
@@ -1002,7 +1002,7 @@ proptest! {
|
||||
prop_assert_eq!(exp_sum + untagged_exp, all.total_expenses);
|
||||
}
|
||||
|
||||
/// rules.md B-37 item 7: the snapshot's contribution is
|
||||
/// BS-statement-5 item 7: the snapshot's contribution is
|
||||
/// project_to_date's net, revenue less direct costs, whatever the
|
||||
/// tags and sides (a refund debits revenue, a reimbursement credits an
|
||||
/// expense below zero): the accounts sum to the totals, each month's
|
||||
@@ -1091,7 +1091,7 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
/// rules.md B-37 item 3: project_entries codes its own signs, so the
|
||||
/// BS-statement-5 item 3: project_entries codes its own signs, so the
|
||||
/// posted entries' project amounts must sum to project_to_date's net
|
||||
/// (with no entry dated after the day), whatever the tags, the sides,
|
||||
/// a tagged balance-sheet line, or drafts beside them.
|
||||
@@ -1145,7 +1145,7 @@ proptest! {
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(2000))]
|
||||
|
||||
/// rules.md B-26 (P7): a TIN is found and masked however its groups
|
||||
/// BS-partner-2 (P7): a TIN is found and masked however its groups
|
||||
/// are separated — a hyphen, a dot, a comma, a parenthesis, a slash,
|
||||
/// an underscore, or any run of spaces — and what merely looks like
|
||||
/// one is not: an amount's thousands separators (1,234,567.89 is
|
||||
@@ -1154,7 +1154,7 @@ proptest! {
|
||||
/// setting's kind (company.duns), never a party field. The ACH payment
|
||||
/// methods' lines get the same exemption in P4b S4's Kind; until then
|
||||
/// the filing scan's narrow shapes keep a bank export's routing
|
||||
/// numbers out of the rule (rules.md B-26).
|
||||
/// numbers out of the rule (BS-partner-2).
|
||||
#[test]
|
||||
fn tin_shapes_with_any_separator_are_found(
|
||||
sep in prop::sample::select(vec![
|
||||
|
||||
@@ -239,7 +239,7 @@ fn recurring_entries_generate_drafts_never_posts() {
|
||||
let _ = b.revenue;
|
||||
}
|
||||
|
||||
/// Regression (B-12, found by the store's refusal property on
|
||||
/// Regression (BS-period-2, found by the store's refusal property on
|
||||
/// 2026-10-13): a recurring occurrence dated in a closed period is
|
||||
/// refused, leaves nothing behind, and is reported as needing a human.
|
||||
#[test]
|
||||
@@ -825,7 +825,7 @@ fn plan_values(plan: Vec<(NaiveDate, Decimal)>) -> Vec<serde_json::Value> {
|
||||
/// A year of prepaid insurance at 100.00 a month (three months posted,
|
||||
/// 900.00 left) and three months of deferred revenue at 333.33, 333.33,
|
||||
/// 333.34 (the last period takes the rounding, so the three sum to
|
||||
/// 1,000.00 exactly: rules.md B-16).
|
||||
/// 1,000.00 exactly: BS-prepaid-1).
|
||||
#[test]
|
||||
fn golden_amortization_plans() {
|
||||
let mut b = books();
|
||||
|
||||
@@ -458,7 +458,7 @@ fn counts_are_positive_whole_numbers() {
|
||||
}
|
||||
|
||||
/// `Kind::Terms`: canonicalized through [`ledger_core::Terms`], so two
|
||||
/// spellings of one agreement are one value (rules.md B-39).
|
||||
/// spellings of one agreement are one value (BS-arap-3).
|
||||
#[test]
|
||||
fn terms_keep_one_canonical_spelling() {
|
||||
let terms = |s: &str| checked("invoicing.default_terms", json!(s));
|
||||
@@ -575,7 +575,7 @@ fn contact_details_are_in_the_company_profile() {
|
||||
|
||||
/// Replay checks the new kinds by shape, never by a later version's
|
||||
/// bounds: a count is a positive whole number, terms any string, and a
|
||||
/// method list of objects with their fields (rules.md B-28).
|
||||
/// method list of objects with their fields (BS-entry-4).
|
||||
#[test]
|
||||
fn replay_shapes_the_new_kinds() {
|
||||
let count = key("invoicing.unsent_days").unwrap();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! Oracles are the spec blocks in the `ledger-core` interface (doc comments
|
||||
//! on `Ledger::create_invoice`, `create_bill`, `receive_payment`, `pay_bill`,
|
||||
//! `arap::aging_bucket`, the `ControlAccount` / `ControlAccountMismatch`
|
||||
//! docs) and `docs/spec/rules.md` B-18. Expected values are computed by hand
|
||||
//! docs) and BS-arap-1. Expected values are computed by hand
|
||||
//! from those, never from the code under test.
|
||||
|
||||
use std::str::FromStr;
|
||||
@@ -124,7 +124,7 @@ fn fingerprint(l: &Ledger) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// Expected bucket index from rules.md B-18, written independently:
|
||||
/// Expected bucket index from BS-arap-1, written independently:
|
||||
/// 0 Current (on or before due), 1: 1-30, 2: 31-60, 3: 61-90, 4: 90+.
|
||||
fn expected_bucket(due: NaiveDate, as_of: NaiveDate) -> usize {
|
||||
let days = (as_of - due).num_days();
|
||||
@@ -288,7 +288,7 @@ fn derive_status_examples() {
|
||||
|
||||
// ------------------------------------------------------------ aging_bucket
|
||||
|
||||
/// Oracle: aging_bucket SCENARIO 1 and B-18 DECISION: due today is Current.
|
||||
/// Oracle: aging_bucket SCENARIO 1 and BS-arap-1 DECISION: due today is Current.
|
||||
#[test]
|
||||
fn aging_due_today_is_current() {
|
||||
let r = aging_bucket(d(2026, 10, 13), d(2026, 10, 13), dec("42.00"));
|
||||
@@ -307,7 +307,7 @@ fn aging_not_yet_due_is_current() {
|
||||
}
|
||||
|
||||
/// Oracle: aging_bucket SCENARIOS 2-5 at each edge (1, 30, 31, 60, 61, 90,
|
||||
/// 91 days past due), B-18.
|
||||
/// 91 days past due), BS-arap-1.
|
||||
#[test]
|
||||
fn aging_boundaries_by_days_past_due() {
|
||||
let due = d(2026, 1, 1);
|
||||
@@ -795,7 +795,7 @@ fn receive_payment_partial_then_full() {
|
||||
}
|
||||
|
||||
/// Oracle: receive_payment SCENARIO 1 (amount not positive) — refusal leaves
|
||||
/// the books unchanged (B-8 general refusal rule, as for post_entry).
|
||||
/// the books unchanged (BS-ledger-4 general refusal rule, as for post_entry).
|
||||
#[test]
|
||||
fn receive_payment_refuses_non_positive_amount() {
|
||||
let (mut l, cash) = books();
|
||||
@@ -984,7 +984,7 @@ fn pay_bill_refuses_bad_amounts_books_unchanged() {
|
||||
// ------------------------------------------------------------------ aging
|
||||
|
||||
/// Oracle: ar_aging doc (one row per customer with an outstanding balance,
|
||||
/// bucketed by days past due) and B-18 buckets; fully paid customers get no
|
||||
/// bucketed by days past due) and BS-arap-1 buckets; fully paid customers get no
|
||||
/// row.
|
||||
///
|
||||
/// ASSUMED: rows carry the customer's name and their order is unspecified
|
||||
@@ -1040,7 +1040,7 @@ fn ar_aging_example() {
|
||||
}
|
||||
|
||||
/// Oracle: ap_aging doc (one row per vendor with an outstanding balance) and
|
||||
/// B-18 (1-30 and 61-90 buckets).
|
||||
/// BS-arap-1 (1-30 and 61-90 buckets).
|
||||
#[test]
|
||||
fn ap_aging_example() {
|
||||
let (mut l, cash) = books();
|
||||
@@ -1124,7 +1124,7 @@ proptest! {
|
||||
/// unchanged); DocumentStatus docs (status law); Invoice::balance doc;
|
||||
/// conservation (1200 balance = sum of open invoice balances, 4000 =
|
||||
/// sum of invoice totals, cash = sum received, since every movement on
|
||||
/// them comes through invoices and payments); ar_aging doc + B-18
|
||||
/// them comes through invoices and payments); ar_aging doc + BS-arap-1
|
||||
/// (each open balance in exactly one bucket; buckets sum to open
|
||||
/// balances; due today is Current).
|
||||
#[test]
|
||||
@@ -1215,7 +1215,7 @@ proptest! {
|
||||
/// Oracles: pay_bill INVARIANTS 1-2 and SCENARIO 1; DocumentStatus docs;
|
||||
/// Bill::balance doc; conservation (2000 = sum of open bill balances,
|
||||
/// 6999 = sum of bill totals, cash = -sum paid); every payment entry
|
||||
/// tagged with its vendor; ap_aging doc + B-18.
|
||||
/// tagged with its vendor; ap_aging doc + BS-arap-1.
|
||||
#[test]
|
||||
fn prop_bills_and_payments_conserve(
|
||||
docs in proptest::collection::vec(doc_strategy(), 1..6),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Spec-derived tests for an asset's basis facts and tax figures
|
||||
//! (rules.md B-25), its two dates and its two accumulated figures
|
||||
//! (rules.md B-15, B-24): `BasisRule`, `Sec704cMethod`, `AssetBasis`
|
||||
//! (BS-asset-4), its two dates and its two accumulated figures
|
||||
//! (BS-asset-1, BS-asset-3): `BasisRule`, `Sec704cMethod`, `AssetBasis`
|
||||
//! (`check`, `check_journaled`, `check_legacy_journaled`),
|
||||
//! `Ledger::set_asset_basis` / `replay_set_asset_basis` /
|
||||
//! `replay_set_asset_tax_basis`, `Asset::basis_figures`,
|
||||
@@ -942,7 +942,7 @@ fn posted_follows_the_entries_dates() {
|
||||
assert_eq!(l.live_depreciation_run(id, "2026-01"), None);
|
||||
}
|
||||
|
||||
/// A reversal of the reversal reinstates the run (B-9), and the run counts
|
||||
/// A reversal of the reversal reinstates the run (BS-ledger-5), and the run counts
|
||||
/// again: the month is not due twice (review R2).
|
||||
#[test]
|
||||
fn a_reinstated_run_counts_and_is_live() {
|
||||
@@ -963,7 +963,7 @@ fn a_reinstated_run_counts_and_is_live() {
|
||||
/// −100.00, as the trial balance does (review R2). No command can write one
|
||||
/// any more (D-73: a reversal is dated on or after its original, so
|
||||
/// `reverse_entry` refuses it), but a journal an earlier version wrote holds
|
||||
/// them and replays as it was (B-28): this test replays one.
|
||||
/// them and replays as it was (BS-entry-4): this test replays one.
|
||||
#[test]
|
||||
fn a_reversal_dated_before_its_run_matches_the_trial_balance() {
|
||||
let (mut l, a, id, e) = one_run();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Spec-derived tests for asset tags and serial numbers (rules.md B-24) and
|
||||
//! Spec-derived tests for asset tags and serial numbers (BS-asset-3) and
|
||||
//! the fixed asset register (`reports::fixed_asset_register`).
|
||||
//!
|
||||
//! Every expected value comes from the written specification: the doc
|
||||
@@ -6,7 +6,7 @@
|
||||
//! `assets::check_asset_tag`, `assets::check_serial`, `assets::tag_key`,
|
||||
//! `Ledger::set_asset_tag`, `check_asset_tag_for`, `set_asset_serial`,
|
||||
//! `asset_by_tag`, `next_asset_tag`, `fixed_asset_register` and
|
||||
//! `AssetRegister`, and `docs/spec/rules.md` B-15 and B-24. Depreciation
|
||||
//! `AssetRegister`, and BS-asset-1 and BS-asset-3. Depreciation
|
||||
//! amounts are worked by hand (straight line, whole months) or, for
|
||||
//! mid-month dates, taken from the already-tested building block
|
||||
//! `accumulated_scheduled_through`. Nothing is read back from the code under
|
||||
@@ -160,7 +160,7 @@ fn check_asset_tag_accepts_the_documented_forms() {
|
||||
assert!(check_asset_tag(&longest).is_ok());
|
||||
}
|
||||
|
||||
/// B-24 says 1–32 characters: the constant agrees with the rule.
|
||||
/// BS-asset-3 says 1–32 characters: the constant agrees with the rule.
|
||||
#[test]
|
||||
fn max_asset_tag_len_is_32_per_b24() {
|
||||
assert_eq!(MAX_ASSET_TAG_LEN, 32);
|
||||
@@ -608,7 +608,7 @@ fn serial_ok(s: &str) -> bool {
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(256))]
|
||||
|
||||
/// B-24 / set_asset_tag INVARIANTS 1-3 and set_asset_serial SCENARIO 1
|
||||
/// BS-asset-3 / set_asset_tag INVARIANTS 1-3 and set_asset_serial SCENARIO 1
|
||||
/// over random command sequences, against a model built from the spec.
|
||||
#[test]
|
||||
fn prop_tag_commands_keep_the_invariants(cmds in proptest::collection::vec(arb_cmd(), 1..40)) {
|
||||
@@ -1088,7 +1088,7 @@ fn register_of_no_assets_is_empty() {
|
||||
/// 1,000.00 and June's 10/30: 5,333.33 scheduled. Before P3 the disposed
|
||||
/// schedule ended in a plug, so the register showed 12,000.00 and 0.00.
|
||||
/// The same in the life's final month: on 2026-12-15, 11,483.87. Book
|
||||
/// value is cost less what the books carry (defect 13, rules.md B-15 rule
|
||||
/// value is cost less what the books carry (defect 13, BS-asset-1 rule
|
||||
/// 8): the fixture's runs, January to March, 3,000.00, so 9,000.00.
|
||||
#[test]
|
||||
fn register_as_of_a_day_before_a_same_month_disposal_is_prorated() {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Spec-derived tests for fixed assets (depreciation, disposal) and payroll.
|
||||
//!
|
||||
//! Every expected value here is a literal worked by hand from the written
|
||||
//! specification (the interface doc comments, `docs/spec/rules.md` B-15 and
|
||||
//! B-22, and IRS Pub. 15 in `docs/spec/sources/irs-payroll.md`), or a law the
|
||||
//! specification (the interface doc comments, BS-asset-1 and
|
||||
//! BS-asset-2, and IRS Pub. 15 in `docs/spec/sources/irs-payroll.md`), or a law the
|
||||
//! specification states. Nothing is read back from the code under test and
|
||||
//! then asserted.
|
||||
|
||||
@@ -274,7 +274,7 @@ const PLAN_CASH: AccountId = 100;
|
||||
|
||||
// ------------------------------------------------- depreciation schedule
|
||||
|
||||
/// Oracle: B-15 straight line, (cost − salvage) / life = 12000 / 12 = 1000.00
|
||||
/// Oracle: BS-asset-1 straight line, (cost − salvage) / life = 12000 / 12 = 1000.00
|
||||
/// per full month; a purchase on the 1st makes every month full.
|
||||
#[test]
|
||||
fn full_months_each_take_one_twelfth_b15() {
|
||||
@@ -316,7 +316,7 @@ fn schedule_clamps_to_end_of_life() {
|
||||
assert_eq!(s.last().unwrap().book_value, d("0.00"));
|
||||
}
|
||||
|
||||
/// Oracle: B-15 partial months prorated by days; monthly 620/2 = 310.00.
|
||||
/// Oracle: BS-asset-1 partial months prorated by days; monthly 620/2 = 310.00.
|
||||
/// Bought 2026-01-15: Jan holds 15..31 = 17/31 → 170.00; Feb full 310.00;
|
||||
/// life ends 2026-03-15 so Mar holds 1..14 = 14/31 → 140.00. 17/31 + 14/31
|
||||
/// = one full month, and the total is exactly 620.00.
|
||||
@@ -368,7 +368,7 @@ fn last_month_trues_up_unequal_month_lengths_b15() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Oracle: B-15 "salvage never depreciated": cost 5000, salvage 1000, life 4
|
||||
/// Oracle: BS-asset-1 "salvage never depreciated": cost 5000, salvage 1000, life 4
|
||||
/// → 1000.00/month, book value stops at 1000.00 forever.
|
||||
#[test]
|
||||
fn salvage_value_is_never_depreciated_b15() {
|
||||
@@ -387,7 +387,7 @@ fn salvage_value_is_never_depreciated_b15() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Oracle: B-21/interface "exact cents … never a penny off": 1000.00 over 3
|
||||
/// Oracle: BS-entry-3/interface "exact cents … never a penny off": 1000.00 over 3
|
||||
/// months cannot split evenly; months are 333.33 or 333.34 and sum to
|
||||
/// exactly 1000.00.
|
||||
#[test]
|
||||
@@ -567,7 +567,7 @@ fn defect22_a_disposed_assets_schedule_stops_at_its_disposal_day() {
|
||||
/// cumulative 100,000 × m / 12, rounded half up to the yen (8,333.33 →
|
||||
/// 8,333; 16,666.67 → 16,667; 25,000; ...), so months alternate 8,333 and
|
||||
/// 8,334 and sum to 100,000. Every one is whole yen, so it can post (an
|
||||
/// entry refuses a fraction of the minor unit, B-3).
|
||||
/// entry refuses a fraction of the minor unit, BS-ledger-1).
|
||||
#[test]
|
||||
fn jpy_depreciation_posts_whole_yen() {
|
||||
let mut a = asset("100000", "0", 12, date(2026, 1, 1));
|
||||
@@ -667,7 +667,7 @@ fn disposal_loss_is_negative() {
|
||||
assert_eq!(scrap.gain_loss, d("-6000.00"));
|
||||
}
|
||||
|
||||
/// Oracle: B-15 + gain law: after full life, book value = salvage 1000.00,
|
||||
/// Oracle: BS-asset-1 + gain law: after full life, book value = salvage 1000.00,
|
||||
/// selling for 1000.00 is neither gain nor loss.
|
||||
#[test]
|
||||
fn disposal_after_full_life_at_salvage_is_break_even() {
|
||||
@@ -742,7 +742,7 @@ fn assert_asset_refused(new: NewAsset, l: &mut Ledger, check: impl Fn(&LedgerErr
|
||||
}
|
||||
|
||||
/// Oracle: register_asset SCENARIO 1 "description is blank: SHOULD refuse";
|
||||
/// refusal leaves the books unchanged (B-8 / post_entry INVARIANT 3 spirit).
|
||||
/// refusal leaves the books unchanged (BS-ledger-4 / post_entry INVARIANT 3 spirit).
|
||||
#[test]
|
||||
fn register_asset_refuses_empty_description() {
|
||||
let (mut l, a) = fixture();
|
||||
@@ -1226,7 +1226,7 @@ fn run_payroll_refuses_zero_gross() {
|
||||
}
|
||||
|
||||
/// Oracle: validate_payroll/run_payroll take a cash account; an unknown one
|
||||
/// cannot be credited (B-1 / R-1 "no unknown accounts").
|
||||
/// cannot be credited (BS-entry-1 / R-1 "no unknown accounts").
|
||||
///
|
||||
/// ASSUMED: the refusal comes before posting; variant unspecified.
|
||||
#[test]
|
||||
@@ -1251,7 +1251,7 @@ fn run_payroll_refuses_wrong_type_control_account() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Oracle: B-12 "a closed period takes no new postings"; remit doc "rejects
|
||||
/// Oracle: BS-period-2 "a closed period takes no new postings"; remit doc "rejects
|
||||
/// dates in closed periods".
|
||||
#[test]
|
||||
fn payroll_and_remit_refuse_closed_period() {
|
||||
@@ -1312,7 +1312,7 @@ fn period_end(p: &str) -> NaiveDate {
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(256))]
|
||||
|
||||
/// Oracle: B-15 laws — a full schedule sums to exactly cost − salvage;
|
||||
/// Oracle: BS-asset-1 laws — a full schedule sums to exactly cost − salvage;
|
||||
/// amounts are non-negative whole cents; accumulated is the running sum
|
||||
/// and non-decreasing; book value = cost − accumulated, never rises, never
|
||||
/// below salvage, ends at salvage; months are consecutive from the
|
||||
@@ -1367,7 +1367,7 @@ proptest! {
|
||||
prop_assert_eq!(scheduled_book_value(&a, before).unwrap(), a.cost.amount);
|
||||
}
|
||||
|
||||
/// Oracle: B-15 partial months by days + interface "the last month absorbs
|
||||
/// Oracle: BS-asset-1 partial months by days + interface "the last month absorbs
|
||||
/// the drift". When (cost − salvage) / life is a whole number of cents M
|
||||
/// and the purchase is after the 1st, the middle months are each exactly
|
||||
/// M and the partial first and last months together are exactly M.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! (ledger_core::calendar), and what can't be computed exactly is refused,
|
||||
//! never wrapped or panicked on (P0 review round 3, finding S1: a panic
|
||||
//! stops the books server). The bounds are the commands' only: replay
|
||||
//! accepts every line an earlier version accepted (rules.md B-28, posted
|
||||
//! accepts every line an earlier version accepted (BS-entry-4, posted
|
||||
//! is forever; P0 review round 4), so each bound here has its pair, a
|
||||
//! replay of an old line past it, accepted.
|
||||
//!
|
||||
@@ -13,8 +13,10 @@
|
||||
//! ledger unchanged; a replayed line an earlier version wrote past
|
||||
//! the same bound is accepted exactly as written.
|
||||
//! SOURCE: DECISION (P0 review round 3, 2026-10-16, S1; round 4,
|
||||
//! 2026-10-17); kernel.rs MAX_LINE_AMOUNT (rules.md: a line over a
|
||||
//! quadrillion is a mistake); calendar.rs (four-digit years).
|
||||
//! 2026-10-17); `crates/ledger-core/src/kernel/entries.rs`
|
||||
//! MAX_LINE_AMOUNT (BS-entry-4: a line over a
|
||||
//! quadrillion is a mistake); `crates/ledger-core/src/calendar.rs`
|
||||
//! (four-digit years).
|
||||
//! ```
|
||||
|
||||
use chrono::{Datelike, NaiveDate};
|
||||
@@ -617,7 +619,7 @@ fn replayed_bases_and_shares_past_the_limit_are_accepted() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A replayed payment is as journaled: no bound (rules.md B-28), and no
|
||||
/// A replayed payment is as journaled: no bound (BS-entry-4), and no
|
||||
/// refusal: it tags the line of its entry that carries it, or (an entry
|
||||
/// it doesn't match) nothing. The command's bound is what the invoice
|
||||
/// owes (Overpayment).
|
||||
@@ -719,7 +721,7 @@ fn disposal_proceeds_and_dates_are_bounded() {
|
||||
// Replay keeps what every version checked: no disposal twice, no
|
||||
// negative proceeds. The date floor (the acquired date, P3) is a
|
||||
// command's: replay accepts a disposal before it, which every earlier
|
||||
// version's commands refused anyway (rules.md B-28: replay accepts
|
||||
// version's commands refused anyway (BS-entry-4: replay accepts
|
||||
// more, never less).
|
||||
assert_eq!(
|
||||
b.ledger
|
||||
@@ -744,12 +746,12 @@ fn disposal_proceeds_and_dates_are_bounded() {
|
||||
}
|
||||
|
||||
/// D-75 (owner, 2026-11-08): a new line's foreign amount and its rate take
|
||||
/// at most ten decimal places each, as a base amount does (B-28), so the
|
||||
/// at most ten decimal places each, as a base amount does (BS-entry-4), so the
|
||||
/// product is exact (at most twenty places, under Decimal's 28) and the
|
||||
/// booked amount is rounded once. Found by the K-U1 review: a 26-place
|
||||
/// foreign amount times 0.005 books 0.01 though the exact product is under
|
||||
/// half a cent, because Decimal rounded the product to 28 places first.
|
||||
/// Replay is exempt (B-28): an older line keeps its figures.
|
||||
/// Replay is exempt (BS-entry-4): an older line keeps its figures.
|
||||
#[test]
|
||||
fn a_foreign_amount_and_a_rate_take_at_most_ten_places() {
|
||||
let dec = |s: &str| s.parse::<Decimal>().unwrap();
|
||||
@@ -963,7 +965,7 @@ fn new_asset(
|
||||
}
|
||||
}
|
||||
|
||||
/// B-3 (P3): a new asset's cost and salvage are in the currency's minor
|
||||
/// BS-ledger-1 (P3): a new asset's cost and salvage are in the currency's minor
|
||||
/// unit (every depreciation and disposal line derives from them, and a
|
||||
/// line finer than a cent never posts). Its replay pair: an asset an
|
||||
/// earlier version took in tenths of a cent opens, and its schedule is
|
||||
@@ -998,7 +1000,7 @@ fn an_asset_cost_finer_than_a_cent_is_refused() {
|
||||
assert_eq!(s[11].accumulated, "1200.005".parse::<Decimal>().unwrap());
|
||||
}
|
||||
|
||||
/// B-28 (P3: lives past 9999, plan/served.md defect 22): a new asset's
|
||||
/// BS-entry-4 (P3: lives past 9999, plan/served.md defect 22): a new asset's
|
||||
/// last day of depreciation is at most 9999-12-31, the calendar's last
|
||||
/// day, so every month of its life is one the books can post. A life
|
||||
/// ending on that day is taken (P0 bounded the life's exclusive end, one
|
||||
@@ -1040,7 +1042,7 @@ fn a_life_ending_after_it_is_refused() {
|
||||
}
|
||||
}
|
||||
|
||||
/// B-28 (P3): a daily schedule's last day is in the calendar: one month
|
||||
/// BS-entry-4 (P3): a daily schedule's last day is in the calendar: one month
|
||||
/// from 9999-12-15 covers through 10000-01-14, refused; one month from
|
||||
/// 9999-12-01 ends on 9999-12-31, taken. Replay takes either.
|
||||
#[test]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The statement of cash flows (rules.md B-14), from the rule and its
|
||||
//! The statement of cash flows (BS-statement-3), from the rule and its
|
||||
//! sources, never from the implementation.
|
||||
//!
|
||||
//! Every expected figure is worked by hand in the test's doc comment from
|
||||
@@ -53,7 +53,7 @@ impl Books {
|
||||
// As replay posts it: these books hold hand lines on receivables
|
||||
// or payables (1200, 2000), which books an earlier version wrote
|
||||
// still hold and every report must read; the control guard
|
||||
// (rules.md B-38) refuses them as new work.
|
||||
// (BS-arap-2) refuses them as new work.
|
||||
ledger_core::parties::replaying(|| {
|
||||
let e = self.l.create_entry(date, desc);
|
||||
for &(code, side, amount) in lines {
|
||||
@@ -168,7 +168,7 @@ fn s(t: &str) -> String {
|
||||
t.to_string()
|
||||
}
|
||||
|
||||
/// The laws every statement keeps (rules.md B-14 rules 8 and 9): each
|
||||
/// The laws every statement keeps (BS-statement-3 rules 8 and 9): each
|
||||
/// section is its lines, and its kinds; the sections are the change in
|
||||
/// cash; net income and the reconciling items are operating.
|
||||
fn foots(cf: &CashFlowStatement) {
|
||||
@@ -205,7 +205,7 @@ fn no_distribution(cf: &CashFlowStatement) {
|
||||
/// The minimal reproduction of defect 1. Property contributed (Dr
|
||||
/// Equipment 2,340 / Cr Capital), the asset registered, the entry reversed
|
||||
/// the same day. No cash moved, and the entry and its reversal cancel
|
||||
/// (rules.md B-14 rules 1, 6): every section 0.00, no lines, no
|
||||
/// (BS-statement-3 rules 1, 6): every section 0.00, no lines, no
|
||||
/// disclosures, footing 0 / 0 / 0. Before the fix: investing −2,340.00
|
||||
/// against a change in cash of 0.00 (the reversal's credit to the
|
||||
/// equipment account belonged to no section).
|
||||
@@ -276,7 +276,7 @@ fn defect1_reversed_contributions_foot_regression() {
|
||||
/// | 22 | 03-20 | reverses #9 | | |
|
||||
/// | 23 | 03-30 | API credits on the card | 6300 42.75 | 2050 |
|
||||
///
|
||||
/// By hand, the year to 2026-03-31 (rules.md B-14; D-42 for what the
|
||||
/// By hand, the year to 2026-03-31 (BS-statement-3; D-42 for what the
|
||||
/// members paid):
|
||||
/// - Operating: the members paid #1 85.00, #2 12.97, #3 99.00, #6 7.49,
|
||||
/// #21 216.40, #7 129.00 and #20 46.38 (the prepaid domain) for the
|
||||
@@ -876,7 +876,7 @@ fn a_property_contribution_is_a_noncash_disclosure() {
|
||||
assert_eq!(n.label, format!("Laptop contributed (#{e})"));
|
||||
}
|
||||
|
||||
/// D-42, rules.md B-14 rule 11 (ASC 230 is silent on a payment a third
|
||||
/// D-42, BS-statement-3 rule 11 (ASC 230 is silent on a payment a third
|
||||
/// party makes on the entity's behalf; PwC FSP 6.9.3.1, DART Roadmap 7.2
|
||||
/// and BDO Blueprint 3.4 present it by substance, as constructive receipt
|
||||
/// and disbursement). An expense a member pays personally (Dr Supplies
|
||||
@@ -1011,7 +1011,7 @@ fn equipment_a_lender_paid_for_is_borrowed_and_invested() {
|
||||
assert_eq!(cf.net_change_in_cash, x("-500.00"));
|
||||
}
|
||||
|
||||
/// The expense-to-capital case (rules.md B-14 rule 11): a member pays a
|
||||
/// The expense-to-capital case (BS-statement-3 rule 11): a member pays a
|
||||
/// vendor for the company and the books credit the member's capital (Dr
|
||||
/// Supplies 80 / Cr Capital — Member A), no cash. The member paid cash to
|
||||
/// a third party on the company's behalf, as through 2100; only the form
|
||||
@@ -1150,7 +1150,7 @@ fn equipment_on_the_sellers_credit_stays_noncash_and_flagged() {
|
||||
assert!(w.message.contains("borrowed and spent"), "{}", w.message);
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 6 with rule 11: a payment a member made for the
|
||||
/// BS-statement-3 rule 6 with rule 11: a payment a member made for the
|
||||
/// company and its reversal, both in February, drop out together (their
|
||||
/// flows, constructive cash included, are exact negatives: Kani
|
||||
/// `constructive_mirrors`); no line, no disclosure, no total moves. The
|
||||
@@ -1351,7 +1351,7 @@ fn interest_and_guaranteed_payments_charged_to_a_creditor_stay_noncash() {
|
||||
);
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 6 (B-9: a correction undoes what it corrects): an
|
||||
/// BS-statement-3 rule 6 (BS-ledger-5: a correction undoes what it corrects): an
|
||||
/// entry and its reversal both in the period drop out of every line and
|
||||
/// disclosure, and no total moves (their flows are exact negatives, Kani
|
||||
/// `entry_flows_of_a_reversal_mirror`).
|
||||
@@ -1390,7 +1390,7 @@ fn an_entry_and_its_reversal_in_the_period_drop_out() {
|
||||
assert_eq!(cf.net_change_in_cash, before.net_change_in_cash);
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 6: a reversal shown alone (its original in an
|
||||
/// BS-statement-3 rule 6: a reversal shown alone (its original in an
|
||||
/// earlier period) is labelled "Reversal of #N — <N's description>" and
|
||||
/// listed under its original's kind, never as a distribution (D1-c).
|
||||
#[test]
|
||||
@@ -1414,7 +1414,7 @@ fn a_reversal_alone_is_labelled_reversal_of() {
|
||||
no_distribution(&cf);
|
||||
}
|
||||
|
||||
/// rules.md B-14 rules 4 and 6: a reversal takes its chain root's
|
||||
/// BS-statement-3 rules 4 and 6: a reversal takes its chain root's
|
||||
/// sections, class and kind, with its own sign. Reversing January's cash
|
||||
/// sale at a 300 gain in February: investing −500 under "Proceeds from
|
||||
/// sales of property and equipment", G +300 (the gain, reversed, is still
|
||||
@@ -1766,7 +1766,7 @@ fn operating_classes_follow_asc_230_10_45_25() {
|
||||
|
||||
/// ASC 230-10-45-28(b): depreciation is an item of net income with no
|
||||
/// cash effect, a reconciling item; it is not an investing or financing
|
||||
/// activity, so nothing is disclosed (rules.md B-14 rule 7).
|
||||
/// activity, so nothing is disclosed (BS-statement-3 rule 7).
|
||||
#[test]
|
||||
fn depreciation_is_reconciling_not_disclosed() {
|
||||
let mut b = funded();
|
||||
@@ -1862,7 +1862,7 @@ fn operating_reconciliation_ties_to_operating_cash() {
|
||||
);
|
||||
}
|
||||
|
||||
/// rules.md B-11 and B-14 rule 10: a period close moves earnings into
|
||||
/// BS-period-1 and BS-statement-3 rule 10: a period close moves earnings into
|
||||
/// equity; it earns and spends nothing, so it is never in the statement.
|
||||
#[test]
|
||||
fn closing_entries_never_appear() {
|
||||
@@ -1881,7 +1881,7 @@ fn closing_entries_never_appear() {
|
||||
assert!(!text.contains(&format!("entry: {close},")));
|
||||
}
|
||||
|
||||
/// The period is [start, end] inclusive (rules.md B-14 rule 1): a
|
||||
/// The period is [start, end] inclusive (BS-statement-3 rule 1): a
|
||||
/// contribution on the start date is a flow, not opening cash.
|
||||
#[test]
|
||||
fn cash_flow_starts_counting_on_the_start_date() {
|
||||
@@ -1921,7 +1921,7 @@ fn a_transfer_between_cash_accounts_is_not_a_flow() {
|
||||
assert!(cf.noncash_disclosures.is_empty());
|
||||
}
|
||||
|
||||
/// Review round 2, footing in odd shapes (rules.md B-14 rules 1, 6, 9,
|
||||
/// Review round 2, footing in odd shapes (BS-statement-3 rules 1, 6, 9,
|
||||
/// 11), by hand:
|
||||
/// - two cash accounts in one entry, a transfer less its fee (Dr Savings
|
||||
/// 99, Dr Supplies 1 / Cr Cash 100): only the net, −1, moves cash,
|
||||
@@ -2035,7 +2035,7 @@ fn a_note_received_for_equipment_is_disclosed() {
|
||||
/// ASC 230-10-50-4: a trade-in. A new vehicle (2,000, on 1520) for the
|
||||
/// old equipment (cost 1,000 on 1500, accumulated 800, gain 300) and
|
||||
/// 1,500 cash: investing −1,500 and an exchange of 500 disclosed. Within
|
||||
/// one cost account a trade-in nets away (a limit B-14 records).
|
||||
/// one cost account a trade-in nets away (a limit BS-statement-3 records).
|
||||
#[test]
|
||||
fn a_trade_in_is_disclosed() {
|
||||
let mut b = funded();
|
||||
@@ -2216,7 +2216,7 @@ fn financing_lists_each_members_contributions_and_distributions() {
|
||||
/// ASC 230-10-45-25 requires interest received (b) and interest paid (e)
|
||||
/// "at a minimum" apart from the other classes, so an entry's operating
|
||||
/// cash is classed kind by kind: its interest lines are (b) or (e)
|
||||
/// whatever else it settles, the rest by its structure (rules.md B-14
|
||||
/// whatever else it settles, the rest by its structure (BS-statement-3
|
||||
/// rule 5). By hand:
|
||||
/// - a payment of 900 on a loan the settings leave operating, with 100
|
||||
/// interest (Dr 2500 900, Dr 6200 100 / Cr cash 1,000): (d) −900 and
|
||||
@@ -2547,7 +2547,7 @@ fn a_reversed_bill_payment_leaves_the_purchase_unpaid() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Role refusals (rules.md B-14 rule 2) and the footing check (rule 9).
|
||||
// Role refusals (BS-statement-3 rule 2) and the footing check (rule 9).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn refused(b: &Books, cash: &[&str], financing: &[&str], investing: &[&str]) -> String {
|
||||
@@ -2617,7 +2617,7 @@ fn a_registered_asset_account_cannot_be_cash() {
|
||||
assert!(m.contains("a registered fixed asset's account"), "{m}");
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 9: any difference between the sections and the
|
||||
/// BS-statement-3 rule 9: any difference between the sections and the
|
||||
/// change in cash is an engine error, never a statement.
|
||||
#[test]
|
||||
fn foot_refuses_any_difference() {
|
||||
@@ -2638,7 +2638,7 @@ fn foot_refuses_any_difference() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Properties over random books (rules.md B-14; plan P3: 5,000 cases).
|
||||
// Properties over random books (BS-statement-3; plan P3: 5,000 cases).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
mod random {
|
||||
@@ -3011,7 +3011,7 @@ use random::*;
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(cases()))]
|
||||
|
||||
/// rules.md B-14 over random books, reversals of reversals included:
|
||||
/// BS-statement-3 over random books, reversals of reversals included:
|
||||
/// 1. the sections sum to the change in cash, which is the model's;
|
||||
/// 2. each section is its lines and its kinds, and 3. net income and
|
||||
/// the reconciling items are operating (`foots`);
|
||||
@@ -3244,7 +3244,7 @@ fn a_disposals_depreciation_credit_back_is_depreciation() {
|
||||
assert_eq!(cf.cash_from_investing, x("975.00"));
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 5 (the P3 cutover review's open point 2): ASC
|
||||
/// BS-statement-3 rule 5 (the P3 cutover review's open point 2): ASC
|
||||
/// 230-10-45-17(c), "Cash payments to governments for taxes, duties,
|
||||
/// fines, and other fees or penalties", is not 45-17(b)'s "Cash payments
|
||||
/// to other suppliers and employees": a state's filing fee booked to an
|
||||
@@ -3316,7 +3316,7 @@ fn a_payment_to_a_government_is_other_operating() {
|
||||
assert_eq!((line.class, line.amount), (Some(OtherPayments), x("75.00")));
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 5: the payee decides on any account, and the tax
|
||||
/// BS-statement-3 rule 5: the payee decides on any account, and the tax
|
||||
/// category still does without one: a license on `taxes_licenses` with no
|
||||
/// party is (g). An entry naming a government and a supplier together
|
||||
/// (half each) is split by their shares, as ASC 230-10-45-22 has each
|
||||
@@ -3371,7 +3371,7 @@ fn a_government_payee_moves_a_fee_on_any_account() {
|
||||
assert_eq!(classes(&cf, shared), [(OtherPayments, x("-100.00"))]);
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 5: a split by shares that leaves an odd cent rounds
|
||||
/// BS-statement-3 rule 5: a split by shares that leaves an odd cent rounds
|
||||
/// the government's part half to even, the supplier's the rest, so the
|
||||
/// line still sums to the payment; its reversal next month mirrors it to
|
||||
/// the cent. Fixed amounts split as given.
|
||||
@@ -3450,7 +3450,7 @@ fn a_shared_government_payment_splits_to_the_cent() {
|
||||
);
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 5: a reversal takes its original's payee, so the
|
||||
/// BS-statement-3 rule 5: a reversal takes its original's payee, so the
|
||||
/// pair always lands in one class and nets. A state's fee paid in
|
||||
/// February and reversed in March: (g) both. The books keep a reversal
|
||||
/// chain's parties one (Ledger::set_entry_parties INVARIANT 5): tagging
|
||||
@@ -3500,7 +3500,7 @@ fn a_reversal_takes_its_originals_payee() {
|
||||
assert_eq!(classes(&b), both(ToSuppliersAndEmployees));
|
||||
}
|
||||
|
||||
/// rules.md B-14 rules 5 and 11: a payment shared between a state and an
|
||||
/// BS-statement-3 rules 5 and 11: a payment shared between a state and an
|
||||
/// agent that a member paid personally (Dr 6000 137.00 / Cr 2100, the
|
||||
/// members' financing account) is borrowed and spent, and its spending is
|
||||
/// split by the parties' shares as a bank payment's is, the part no bank
|
||||
@@ -3577,7 +3577,7 @@ fn a_shared_government_payment_a_member_paid_splits_both_ways() {
|
||||
assert_eq!(cf.net_change_in_cash, Decimal::ZERO);
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 5 (CONVENTION): payroll keeps its structure. Taxes
|
||||
/// BS-statement-3 rule 5 (CONVENTION): payroll keeps its structure. Taxes
|
||||
/// withheld from employees and remitted to the tax agency are the
|
||||
/// employees' pay (45-17(b), "Cash payments to other suppliers and
|
||||
/// employees"), and the payroll payables mix them with the employer's
|
||||
@@ -3636,7 +3636,7 @@ fn a_payroll_remittance_to_a_tax_agency_stays_pay() {
|
||||
assert_eq!(class(employer), Some(OtherPayments));
|
||||
}
|
||||
|
||||
/// rules.md B-14 rule 5: a government selling goods or services is a
|
||||
/// BS-statement-3 rule 5: a government selling goods or services is a
|
||||
/// supplier (45-17(b), "for other goods or services"), not 45-17(c)'s
|
||||
/// taxes, fees or penalties: the post office named with the `vendor`
|
||||
/// role, postage stays (d). The roles decide, so a post office given the
|
||||
@@ -3664,7 +3664,7 @@ fn a_government_selling_services_is_a_supplier() {
|
||||
}
|
||||
|
||||
/// A bill whose line is equipment, paid later: the payment's cash is
|
||||
/// investing, through the bill's split (D-35; rules.md B-14), not
|
||||
/// investing, through the bill's split (D-35; BS-statement-3), not
|
||||
/// operating. Plan P4b S6 keeps this true when the bill is paid as part
|
||||
/// of a settlement.
|
||||
#[test]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! An invoice's or bill's lines name their projects (rules.md B-37 item
|
||||
//! An invoice's or bill's lines name their projects (BS-statement-5 item
|
||||
//! 8): the posted entry's revenue or expense side is one line per project,
|
||||
//! the untagged lines' as one; the receivable or payable line, and the
|
||||
//! payments, never take one.
|
||||
@@ -6,9 +6,9 @@
|
||||
//! ```text
|
||||
//! GOAL: a client project's invoiced revenue and a contractor's billed
|
||||
//! cost count toward the project, every other figure as before.
|
||||
//! SOURCE: docs/spec/rules.md B-37 items 3 and 8 (job costing), B-14 (the
|
||||
//! projects with the untagged lines partition the P&L), B-19 and
|
||||
//! B-35 (1099 and party figures follow the money, not the tags).
|
||||
//! SOURCE: BS-statement-5 items 3 and 8 (job costing), BS-statement-3 (the
|
||||
//! projects with the untagged lines partition the P&L), BS-1099-1 and
|
||||
//! BS-partner-3 (1099 and party figures follow the money, not the tags).
|
||||
//! ```
|
||||
|
||||
use chrono::NaiveDate;
|
||||
@@ -170,7 +170,7 @@ fn a_bills_cost_is_one_line_per_project_and_the_payable_none() {
|
||||
}
|
||||
|
||||
/// Reversing a tagged invoice's or bill's entry carries each line's
|
||||
/// project to the reversal (B-37 item 3: each line on its normal side), so
|
||||
/// project to the reversal (BS-statement-5 item 3: each line on its normal side), so
|
||||
/// every project nets back to zero; a partial payment, cash against the
|
||||
/// receivable, moves no project figure.
|
||||
#[test]
|
||||
@@ -209,7 +209,7 @@ fn reversing_a_tagged_document_takes_its_projects_to_zero() {
|
||||
.unwrap();
|
||||
assert_eq!(to_date(&b.l, z), (cents(300_000), cents(120_000)));
|
||||
assert_eq!(to_date(&b.l, h), (cents(20_000), Decimal::ZERO));
|
||||
// The payment first: a void waits on the payments that stand (B-38
|
||||
// The payment first: a void waits on the payments that stand (BS-arap-2
|
||||
// scenario 3); its reversal moves no project figure either.
|
||||
b.l.reverse_entry(pay, d(2026, 3, 30), "Bounced").unwrap();
|
||||
assert_eq!(to_date(&b.l, z), (cents(300_000), cents(120_000)));
|
||||
@@ -294,7 +294,7 @@ fn a_line_naming_an_unknown_project_is_refused_whole() {
|
||||
assert!(b.l.differs_from(&before).is_empty(), "nothing changed");
|
||||
}
|
||||
|
||||
/// Finished and abandoned projects still take a document's lines (B-37
|
||||
/// Finished and abandoned projects still take a document's lines (BS-statement-5
|
||||
/// item 5: a late cost, a final invoice).
|
||||
#[test]
|
||||
fn a_finished_project_still_takes_an_invoice() {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! Documents read their figures from the ledger lines tagged with them
|
||||
//! (rules.md B-38; plan P4b S1, D-45): one test per scenario of the
|
||||
//! B-38 spec block, then the properties.
|
||||
//! (BS-arap-2; plan P4b S1, D-45): one test per scenario of the
|
||||
//! BS-arap-2 spec block, then the properties.
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: invoices and bills are the subledgers of the receivables and
|
||||
//! payables control accounts; every figure about a document is read
|
||||
//! from the ledger lines tagged with it.
|
||||
//! SOURCE: docs/spec/rules.md B-8, B-9, B-10, B-18, B-23, B-28, B-38;
|
||||
//! SOURCE: BS-ledger-4, BS-ledger-5, BS-ledger-6, BS-arap-1, BS-ledger-8, BS-entry-4, BS-arap-2;
|
||||
//! ASC 310-10, ASC 405-20-40-1, ASC 606-10-45-4.
|
||||
//! ```
|
||||
|
||||
@@ -109,7 +109,7 @@ impl Books {
|
||||
self.l.chart().find_by_code(code).unwrap().id
|
||||
}
|
||||
|
||||
/// Every control account's tie-out holds: no difference (B-38
|
||||
/// Every control account's tie-out holds: no difference (BS-arap-2
|
||||
/// INVARIANT 1).
|
||||
fn ties(&self, on: NaiveDate) {
|
||||
for c in self.l.control_check(on).unwrap() {
|
||||
@@ -186,7 +186,7 @@ fn a_voided_invoice_never_ages() {
|
||||
Err(LedgerError::InvalidVoid(why)) => assert!(why.contains(&r.to_string()), "{why}"),
|
||||
other => panic!("expected InvalidVoid, got {other:?}"),
|
||||
}
|
||||
// Reversing the void re-instates it (B-10); voiding again reverses
|
||||
// Reversing the void re-instates it (BS-ledger-6); voiding again reverses
|
||||
// that reversal, the end of the chain.
|
||||
let back = b.l.reverse_entry(r, d(2026, 2, 7), "Re-instate").unwrap();
|
||||
assert_eq!(
|
||||
@@ -500,7 +500,7 @@ fn deposit_account_must_be_cash_like() {
|
||||
}
|
||||
|
||||
/// A reversal of an entry a document owns is never dated before it
|
||||
/// (B-9; P4b.3, "Dating rules").
|
||||
/// (BS-ledger-5; P4b.3, "Dating rules").
|
||||
#[test]
|
||||
fn reversal_before_original_refused_for_documents() {
|
||||
let mut b = books();
|
||||
@@ -1067,7 +1067,7 @@ fn out_of_bounds_documents_are_listed_not_aged() {
|
||||
|
||||
/// Reversing a legacy hand line takes it off; reversing that reversal
|
||||
/// would put it back, and is refused: no command adds an untagged control
|
||||
/// line (B-38 INVARIANT 1 and item 3; first review of S1).
|
||||
/// line (BS-arap-2 INVARIANT 1 and item 3; first review of S1).
|
||||
#[test]
|
||||
fn putting_back_a_removed_hand_line_is_refused() {
|
||||
let mut b = books();
|
||||
@@ -1201,10 +1201,10 @@ fn a_chain_counts_in_order() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Write-offs (plan P4b S7; rules.md B-41)
|
||||
// Write-offs (plan P4b S7; BS-arap-5)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// B-38 SCENARIO 7 and B-41 INVARIANT 1: half of an invoice paid, the rest
|
||||
/// BS-arap-2 SCENARIO 7 and BS-arap-5 INVARIANT 1: half of an invoice paid, the rest
|
||||
/// written off, reads Written off with 50 paid and 50 written off, and
|
||||
/// receivables falls by the write-off alone.
|
||||
#[test]
|
||||
@@ -1261,7 +1261,7 @@ fn half_paid_rest_written_off_is_written_off() {
|
||||
assert!(check.iter().all(|c| c.difference.is_zero()));
|
||||
}
|
||||
|
||||
/// B-41 INVARIANT 3: a cash-basis company never counted the invoice as
|
||||
/// BS-arap-5 INVARIANT 3: a cash-basis company never counted the invoice as
|
||||
/// income, so it has no basis to deduct (IRC §166; Treas. Reg.
|
||||
/// §1.166-1(e)).
|
||||
#[test]
|
||||
@@ -1308,7 +1308,7 @@ fn write_off_refused_on_cash_basis() {
|
||||
);
|
||||
}
|
||||
|
||||
/// B-41 INVARIANT 1: at most what is owed, a partial write-off allowed
|
||||
/// BS-arap-5 INVARIANT 1: at most what is owed, a partial write-off allowed
|
||||
/// (Treas. Reg. §1.166-3(a)); more is refused, naming what is owed, and
|
||||
/// nothing changes.
|
||||
#[test]
|
||||
@@ -1351,7 +1351,7 @@ fn write_off_above_outstanding_refused() {
|
||||
assert_eq!((st.paid, st.written_off), (cents(4_000), cents(6_000)));
|
||||
}
|
||||
|
||||
/// D-49's same-year recovery, and B-41 INVARIANT 2: reversing the
|
||||
/// D-49's same-year recovery, and BS-arap-5 INVARIANT 2: reversing the
|
||||
/// write-off re-instates the debt (it is not a new movement), and the
|
||||
/// payment then recorded settles it; a recovery is income, never a
|
||||
/// payment event.
|
||||
@@ -1502,7 +1502,7 @@ fn days(b: &Books) -> Vec<NaiveDate> {
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(256))]
|
||||
|
||||
/// B-38 INVARIANTS 1, 2 and 6 over random histories of creates,
|
||||
/// BS-arap-2 INVARIANTS 1, 2 and 6 over random histories of creates,
|
||||
/// payments, voids, reversals of any entry and refused hand lines: at
|
||||
/// every date the control accounts equal their documents (no
|
||||
/// difference, nothing unattached: no command adds a hand line), each
|
||||
@@ -1538,7 +1538,7 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
/// B-38 INVARIANT 5: the aging as of a day partitions what the
|
||||
/// BS-arap-2 INVARIANT 5: the aging as of a day partitions what the
|
||||
/// documents owe then (in books these commands write, none owes less
|
||||
/// than nothing). INVARIANT 4 (Store, replay and Snapshot agree) is
|
||||
/// ledger-store's `status_is_a_function_of_journal_and_date`.
|
||||
@@ -1562,7 +1562,7 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
/// B-38 INVARIANT 3: reversing a tagged entry moves its documents by
|
||||
/// BS-arap-2 INVARIANT 3: reversing a tagged entry moves its documents by
|
||||
/// exactly the opposite of the entry's own tagged lines from the
|
||||
/// reversal's day (read from the entry reversed, not from the mirror,
|
||||
/// so a mirror that lost its tag is caught); reversing that reversal
|
||||
@@ -1637,7 +1637,7 @@ fn doc_line(
|
||||
}
|
||||
}
|
||||
|
||||
/// B-39 SCENARIOS: Net 30, Net 15 EOM, a leap day, due on receipt, a
|
||||
/// BS-arap-3 SCENARIOS: Net 30, Net 15 EOM, a leap day, due on receipt, a
|
||||
/// custom date, and the 9999-12 bound refused instead of panicking.
|
||||
#[test]
|
||||
fn terms_derive_due_dates() {
|
||||
@@ -1671,7 +1671,7 @@ fn terms_derive_due_dates() {
|
||||
assert!(Terms::new(TermsKind::NetEom(3_651), None).is_err());
|
||||
}
|
||||
|
||||
/// B-39 INVARIANT 2: the discount's bound, its date, and the terms that
|
||||
/// BS-arap-3 INVARIANT 2: the discount's bound, its date, and the terms that
|
||||
/// cannot carry one.
|
||||
#[test]
|
||||
fn discount_bounds_and_late_reason() {
|
||||
@@ -1741,7 +1741,7 @@ fn discount_bounds_and_late_reason() {
|
||||
assert_eq!(kernel::discount_max(cents(-1), 200), None);
|
||||
}
|
||||
|
||||
/// B-39 INVARIANT 3: the canonical spellings read back as they print.
|
||||
/// BS-arap-3 INVARIANT 3: the canonical spellings read back as they print.
|
||||
#[test]
|
||||
fn terms_describe_and_parse_round_trip() {
|
||||
for text in [
|
||||
@@ -1899,7 +1899,7 @@ fn qty_times_price_must_equal_amount() {
|
||||
));
|
||||
}
|
||||
|
||||
/// B-39 line accounts: an invoice takes revenue or deferred revenue; a
|
||||
/// BS-arap-3 line accounts: an invoice takes revenue or deferred revenue; a
|
||||
/// bill takes an expense or a non-cash asset; roles, cash and headers are
|
||||
/// refused (plan P4b S4.1, A-10).
|
||||
#[test]
|
||||
@@ -1959,7 +1959,7 @@ fn document_line_account_refuses_roles_cash_and_placeholders() {
|
||||
assert_eq!(b.l.next_bill_id(), before);
|
||||
}
|
||||
|
||||
/// A-2, B-40: numbers run, a void keeps its number, legacy invoices are
|
||||
/// A-2, BS-arap-4: numbers run, a void keeps its number, legacy invoices are
|
||||
/// not counted, and a number is never reused.
|
||||
#[test]
|
||||
fn numbers_run_and_voids_keep_theirs() {
|
||||
@@ -2033,7 +2033,7 @@ fn numbers_run_and_voids_keep_theirs() {
|
||||
);
|
||||
}
|
||||
|
||||
/// B-40: four digits, wider past 9,999, never truncated.
|
||||
/// BS-arap-4: four digits, wider past 9,999, never truncated.
|
||||
#[test]
|
||||
fn number_widens_past_9999() {
|
||||
let mut b = books();
|
||||
@@ -2053,7 +2053,7 @@ fn number_widens_past_9999() {
|
||||
assert_eq!(b.l.next_invoice_number("INV-", 9_999), "INV-10000");
|
||||
}
|
||||
|
||||
/// B-40: a vendor's invoice number names one standing bill; case, spaces
|
||||
/// BS-arap-4: a vendor's invoice number names one standing bill; case, spaces
|
||||
/// and hyphens are ignored; a duplicate needs a reason (plan P4b S4.1).
|
||||
#[test]
|
||||
fn duplicate_vendor_ref_refused_unless_a_reason_is_given() {
|
||||
@@ -2124,13 +2124,13 @@ fn duplicate_vendor_ref_refused_unless_a_reason_is_given() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// P4b S6: paying on terms (rules.md B-42)
|
||||
// P4b S6: paying on terms (BS-arap-6)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A bill on "2/10 net 30", paid within the discount window: the gross
|
||||
/// method's entry is Dr A/P the full amount, Cr purchase discounts what
|
||||
/// was taken, Cr the bank the rest; the bill reads paid and discounted.
|
||||
/// A discount larger than the terms allow needs a reason (B-42).
|
||||
/// A discount larger than the terms allow needs a reason (BS-arap-6).
|
||||
#[test]
|
||||
fn bill_on_terms_with_discount() {
|
||||
use ledger_core::{Application, DocRef, SettleParams};
|
||||
@@ -2231,7 +2231,7 @@ fn bill_on_terms_with_discount() {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// A discount taken after the discount date needs a reason (B-42
|
||||
/// A discount taken after the discount date needs a reason (BS-arap-6
|
||||
/// INVARIANT 2); a bill with an asset or prepaid line refuses one with the
|
||||
/// D-49 remedy, and none of the refusals changes the books.
|
||||
#[test]
|
||||
@@ -2379,7 +2379,7 @@ fn a_fee_posts_gross_to_receivables_and_net_to_the_bank() {
|
||||
|
||||
/// A payment that settles more than one document names its lines in
|
||||
/// application order, and two applications on one document are refused:
|
||||
/// each document's bound is one bound (B-42 INVARIANTS 1 and 2).
|
||||
/// each document's bound is one bound (BS-arap-6 INVARIANTS 1 and 2).
|
||||
#[test]
|
||||
fn a_settlement_names_its_lines_and_refuses_a_document_twice() {
|
||||
use ledger_core::{Application, DocRef, SettleParams};
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Spec-derived tests for the `Ledger` command surface.
|
||||
//!
|
||||
//! Written from the spec blocks (GOAL / SOURCE / INVARIANTS / SCENARIOS) in
|
||||
//! the public interface and from `docs/spec/rules.md`, never from the
|
||||
//! the public interface and from bookspec's rules (wanderbooks' claims
|
||||
//! in `docs/spec/claims/`), never from the
|
||||
//! implementation. Every expected value is a literal computed by hand from
|
||||
//! the spec, or a law (a model kept by the test itself). A test whose name
|
||||
//! does not already say its oracle says it in its doc comment.
|
||||
@@ -130,7 +131,7 @@ fn try_post(
|
||||
}
|
||||
|
||||
/// [`try_post`] through the replay path, which books written before the
|
||||
/// minor-unit rule (B-3, 2026-10-13) still take: for the kernel's own
|
||||
/// minor-unit rule (BS-ledger-1, 2026-10-13) still take: for the kernel's own
|
||||
/// limits below a cent.
|
||||
fn try_replay_post(
|
||||
l: &mut Ledger,
|
||||
@@ -245,7 +246,7 @@ fn tb_has_code(l: &Ledger, as_of: NaiveDate, code: &str) -> bool {
|
||||
// add_account
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Oracle: R-4 / B-4: an added account is findable by its code with exactly
|
||||
/// Oracle: R-4 / BS-ledger-2: an added account is findable by its code with exactly
|
||||
/// the type, parent, and placeholder flag it was given.
|
||||
#[test]
|
||||
fn an_added_account_is_registered_under_its_code() {
|
||||
@@ -339,7 +340,7 @@ fn a_refused_account_never_uses_up_an_id() {
|
||||
assert_eq!(id, announced);
|
||||
}
|
||||
|
||||
/// Oracle: add_account SCENARIO 3 (B-4 DECISION): a child of another type is
|
||||
/// Oracle: add_account SCENARIO 3 (BS-ledger-2 DECISION): a child of another type is
|
||||
/// refused with ParentTypeMismatch and NEVER added.
|
||||
#[test]
|
||||
fn a_child_account_has_its_parents_type() {
|
||||
@@ -390,7 +391,7 @@ fn a_new_draft_gets_the_next_id_one_past_the_last() {
|
||||
assert!(e.lines().is_empty());
|
||||
}
|
||||
|
||||
/// Oracle: try_create_entry SCENARIO 1 (B-12): a date inside a closed period,
|
||||
/// Oracle: try_create_entry SCENARIO 1 (BS-period-2): a date inside a closed period,
|
||||
/// first and last day included, is refused with ClosedPeriod and creates
|
||||
/// nothing; the day after the period is accepted.
|
||||
#[test]
|
||||
@@ -444,7 +445,7 @@ fn lines_are_kept_in_the_order_added() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Oracle: B-1 DECISION (owner, 2026-10-13): a line on an unknown account
|
||||
/// Oracle: BS-entry-1 DECISION (owner, 2026-10-13): a line on an unknown account
|
||||
/// is refused when added (UnknownAccount), not only at post.
|
||||
#[test]
|
||||
fn a_line_on_an_unknown_account_is_refused_when_added() {
|
||||
@@ -458,7 +459,7 @@ fn a_line_on_an_unknown_account_is_refused_when_added() {
|
||||
assert_eq!(observe(&b.l), before);
|
||||
}
|
||||
|
||||
/// Oracle: B-1 DECISION / R-4: a line on a placeholder account is refused
|
||||
/// Oracle: BS-entry-1 DECISION / R-4: a line on a placeholder account is refused
|
||||
/// when added (PlaceholderAccount).
|
||||
#[test]
|
||||
fn a_line_on_a_placeholder_account_is_refused_when_added() {
|
||||
@@ -473,7 +474,7 @@ fn a_line_on_a_placeholder_account_is_refused_when_added() {
|
||||
assert_eq!(observe(&b.l), before);
|
||||
}
|
||||
|
||||
/// Oracle: B-3 / R-5 and the add_line doc: a foreign-currency amount is
|
||||
/// Oracle: BS-ledger-1 / R-5 and the add_line doc: a foreign-currency amount is
|
||||
/// refused, never converted (CurrencyMismatch).
|
||||
#[test]
|
||||
fn a_foreign_currency_line_is_refused_not_converted() {
|
||||
@@ -493,7 +494,7 @@ fn a_foreign_currency_line_is_refused_not_converted() {
|
||||
assert_eq!(observe(&b.l), before);
|
||||
}
|
||||
|
||||
/// Oracle: R-3 / B-8 and the PostedEntryImmutable doc ("add lines"): a posted
|
||||
/// Oracle: R-3 / BS-ledger-4 and the PostedEntryImmutable doc ("add lines"): a posted
|
||||
/// entry takes no more lines.
|
||||
#[test]
|
||||
fn a_posted_entry_takes_no_more_lines() {
|
||||
@@ -523,7 +524,7 @@ fn a_line_on_an_unknown_entry_is_refused() {
|
||||
assert_eq!(observe(&b.l), before);
|
||||
}
|
||||
|
||||
/// Oracle: B-3 (ASC 830-20-30-1) and the add_line_fx doc: base = foreign ×
|
||||
/// Oracle: BS-ledger-1 (ASC 830-20-30-1) and the add_line_fx doc: base = foreign ×
|
||||
/// rate (100 EUR × 1.10 = 110.00 USD), the original kept; the entry then
|
||||
/// balances in base currency.
|
||||
#[test]
|
||||
@@ -569,7 +570,7 @@ fn a_non_positive_fx_rate_is_refused() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Oracle: rules.md B-3 "Checked: fx_overflow_is_an_error" and B-21 (exact
|
||||
/// Oracle: BS-ledger-1 "Checked: fx_overflow_is_an_error" and BS-entry-3 (exact
|
||||
/// amounts): a product that can't be represented is refused, never rounded
|
||||
/// or wrapped.
|
||||
#[test]
|
||||
@@ -584,7 +585,7 @@ fn fx_overflow_is_an_error() {
|
||||
assert_eq!(observe(&b.l), before);
|
||||
}
|
||||
|
||||
/// Oracle: B-1 DECISION applies to add_line_fx too: unknown account refused
|
||||
/// Oracle: BS-entry-1 DECISION applies to add_line_fx too: unknown account refused
|
||||
/// when added.
|
||||
#[test]
|
||||
fn a_foreign_line_on_an_unknown_account_is_refused_when_added() {
|
||||
@@ -598,7 +599,7 @@ fn a_foreign_line_on_an_unknown_account_is_refused_when_added() {
|
||||
assert_eq!(observe(&b.l), before);
|
||||
}
|
||||
|
||||
/// Oracle: B-3 + line range (AmountOutOfRange: at most one quadrillion):
|
||||
/// Oracle: BS-ledger-1 + line range (AmountOutOfRange: at most one quadrillion):
|
||||
/// a foreign line converting to 2,000,000,000,000,000 USD never posts.
|
||||
#[test]
|
||||
fn a_foreign_line_beyond_line_range_never_posts() {
|
||||
@@ -631,7 +632,7 @@ fn posting_an_unknown_entry_is_refused() {
|
||||
assert_eq!(observe(&b.l), before);
|
||||
}
|
||||
|
||||
/// Oracle: post_entry SCENARIO 2 (B-8): a posted entry is never posted
|
||||
/// Oracle: post_entry SCENARIO 2 (BS-ledger-4): a posted entry is never posted
|
||||
/// twice (EntryAlreadyPosted), the log unchanged.
|
||||
#[test]
|
||||
fn a_posted_entry_is_never_posted_twice() {
|
||||
@@ -647,7 +648,7 @@ fn a_posted_entry_is_never_posted_twice() {
|
||||
assert_eq!(b.l.posted_entries().count(), 1);
|
||||
}
|
||||
|
||||
/// Oracle: post_entry SCENARIO 3 (B-12): an entry dated in a closed period
|
||||
/// Oracle: post_entry SCENARIO 3 (BS-period-2): an entry dated in a closed period
|
||||
/// is refused (ClosedPeriod), even one drafted through the unchecked
|
||||
/// constructor.
|
||||
#[test]
|
||||
@@ -670,7 +671,7 @@ fn an_entry_dated_in_a_closed_period_never_posts() {
|
||||
assert_eq!(observe(&b.l), before);
|
||||
}
|
||||
|
||||
/// Oracle: R-1/B-1: fewer than two lines is refused (TooFewLines), for zero
|
||||
/// Oracle: R-1/BS-entry-1: fewer than two lines is refused (TooFewLines), for zero
|
||||
/// lines and for one.
|
||||
#[test]
|
||||
fn an_entry_with_fewer_than_two_lines_never_posts() {
|
||||
@@ -690,7 +691,7 @@ fn an_entry_with_fewer_than_two_lines_never_posts() {
|
||||
assert_eq!(b.l.posted_entries().count(), 0);
|
||||
}
|
||||
|
||||
/// Oracle: R-1/B-1 (no epsilon): 100.00 against 99.99 is refused with the
|
||||
/// Oracle: R-1/BS-entry-1 (no epsilon): 100.00 against 99.99 is refused with the
|
||||
/// offending totals.
|
||||
#[test]
|
||||
fn an_unbalanced_entry_is_refused_with_its_totals() {
|
||||
@@ -744,7 +745,7 @@ fn exact_decimal_sums_balance() {
|
||||
assert_eq!(r, None);
|
||||
}
|
||||
|
||||
/// Oracle: R-6 / B-2: a zero-amount line is refused (ZeroAmountLine).
|
||||
/// Oracle: R-6 / BS-entry-2: a zero-amount line is refused (ZeroAmountLine).
|
||||
#[test]
|
||||
fn a_zero_amount_line_never_posts() {
|
||||
let mut b = books();
|
||||
@@ -761,7 +762,7 @@ fn a_zero_amount_line_never_posts() {
|
||||
assert_eq!(b.l.posted_entries().count(), 0);
|
||||
}
|
||||
|
||||
/// Oracle: B-2: a negative amount is refused (NegativeAmountLine): the side
|
||||
/// Oracle: BS-entry-2: a negative amount is refused (NegativeAmountLine): the side
|
||||
/// says the direction.
|
||||
#[test]
|
||||
fn a_negative_amount_line_never_posts() {
|
||||
@@ -799,7 +800,7 @@ fn line_range_is_one_quadrillion_and_ten_places() {
|
||||
ok(&mut b, "1000000000000000.01"),
|
||||
Some(LedgerError::AmountOutOfRange)
|
||||
);
|
||||
// Below a cent, new work is refused first (B-3); replayed books meet
|
||||
// Below a cent, new work is refused first (BS-ledger-1); replayed books meet
|
||||
// the kernel's ten-place limit.
|
||||
assert!(matches!(
|
||||
ok(&mut b, "0.0000000001"),
|
||||
@@ -886,7 +887,7 @@ fn the_log_is_in_posting_order() {
|
||||
// check_reversal / reverse_entry
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Oracle: B-9 (Pacioli's storno): the reversal has the same lines with
|
||||
/// Oracle: BS-ledger-5 (Pacioli's storno): the reversal has the same lines with
|
||||
/// sides flipped, is posted, dated as asked, linked by `reversal_of`, and
|
||||
/// returns every balance to what it was.
|
||||
#[test]
|
||||
@@ -917,12 +918,12 @@ fn a_reversal_mirrors_the_original_and_cancels_it() {
|
||||
for a in [b.exp, b.cash, b.card] {
|
||||
assert_eq!(b.l.account_balance(a).unwrap(), Decimal::ZERO);
|
||||
}
|
||||
// The original is untouched (B-8): never erased.
|
||||
// The original is untouched (BS-ledger-4): never erased.
|
||||
assert_eq!(b.l.get_entry(e).unwrap().status(), EntryStatus::Posted);
|
||||
assert_eq!(b.l.posted_entries().count(), 2);
|
||||
}
|
||||
|
||||
/// Oracle: B-10 / check_reversal SCENARIO 2: an entry is reversed at most
|
||||
/// Oracle: BS-ledger-6 / check_reversal SCENARIO 2: an entry is reversed at most
|
||||
/// once (EntryAlreadyReversed(entry, by)); reversing the reversal is allowed
|
||||
/// and re-instates it, and does not reopen the original.
|
||||
#[test]
|
||||
@@ -986,7 +987,7 @@ fn only_posted_entries_are_reversed() {
|
||||
assert_eq!(observe(&b.l), before);
|
||||
}
|
||||
|
||||
/// Oracle: B-10 / check_reversal SCENARIO 3: a closing entry is never
|
||||
/// Oracle: BS-ledger-6 / check_reversal SCENARIO 3: a closing entry is never
|
||||
/// reversed (ClosingEntryIrreversible), even dated in an open period.
|
||||
#[test]
|
||||
fn a_closing_entry_is_never_reversed() {
|
||||
@@ -1015,7 +1016,7 @@ fn a_closing_entry_is_never_reversed() {
|
||||
assert_eq!(observe(&b.l), before);
|
||||
}
|
||||
|
||||
/// Oracle: check_reversal SCENARIO 4 (B-12): a reversal dated in a closed
|
||||
/// Oracle: check_reversal SCENARIO 4 (BS-period-2): a reversal dated in a closed
|
||||
/// period is refused (ClosedPeriod); dated after it, accepted.
|
||||
#[test]
|
||||
fn a_reversal_is_never_dated_in_a_closed_period() {
|
||||
@@ -1184,7 +1185,7 @@ fn assert_balanced(l: &Ledger, id: EntryId) {
|
||||
assert_eq!(dr, cr, "closing entry must balance");
|
||||
}
|
||||
|
||||
/// Oracle: close INVARIANTS 1-3 and B-11: closing to retained earnings
|
||||
/// Oracle: close INVARIANTS 1-3 and BS-period-1: closing to retained earnings
|
||||
/// zeroes revenue and expense as of Jan 31, credits 3999 (created, equity)
|
||||
/// with exactly the net 700.00, is dated Jan 31, balances, locks the
|
||||
/// period, and leaves February's 50.00 sale untouched.
|
||||
@@ -1296,7 +1297,7 @@ fn a_period_with_drafts_never_closes() {
|
||||
assert_eq!(observe(&b.l), before);
|
||||
}
|
||||
|
||||
/// Oracle: close SCENARIO 3 (B-12): closing out of order is refused
|
||||
/// Oracle: close SCENARIO 3 (BS-period-2): closing out of order is refused
|
||||
/// (CloseOutOfOrder(id, later)).
|
||||
#[test]
|
||||
fn periods_close_in_order() {
|
||||
@@ -1443,7 +1444,7 @@ fn members(shares: &[(AccountId, &str, Option<AccountId>)]) -> CloseTo {
|
||||
)
|
||||
}
|
||||
|
||||
/// Oracle: B-13 / AGENTS.md (50/50): net 700.00 splits 350.00 / 350.00; each
|
||||
/// Oracle: BS-partner-1 / AGENTS.md (50/50): net 700.00 splits 350.00 / 350.00; each
|
||||
/// member's distributions close into their own capital.
|
||||
#[test]
|
||||
fn a_partnership_close_splits_by_share() {
|
||||
@@ -1488,7 +1489,7 @@ fn net_books(net: &str) -> (Books, PeriodId, AccountId) {
|
||||
(b, jan, cap_c)
|
||||
}
|
||||
|
||||
/// Oracle: B-13 DECISION (largest remainder, ties to the earlier member),
|
||||
/// Oracle: BS-partner-1 DECISION (largest remainder, ties to the earlier member),
|
||||
/// hand-computed: 1.05 at 0.3/0.3/0.4 is exactly 0.315/0.315/0.42; rounded
|
||||
/// down 0.31/0.31/0.42 leaves one cent, remainders .005/.005/0 tie, so the
|
||||
/// first member gets it: 0.32/0.31/0.42. (The retired last-absorbs rule
|
||||
@@ -1507,7 +1508,7 @@ fn members_split_by_largest_remainder_ties_to_the_earlier() {
|
||||
assert_eq!(b.l.account_balance(cap_c).unwrap(), dec("0.42"));
|
||||
}
|
||||
|
||||
/// Oracle: B-13 / kernel::apportion INVARIANT 3, hand-computed: 0.07 at
|
||||
/// Oracle: BS-partner-1 / kernel::apportion INVARIANT 3, hand-computed: 0.07 at
|
||||
/// 0.2/0.3/0.5 is exactly 0.014/0.021/0.035; rounded down 0.01/0.02/0.03
|
||||
/// (sum 0.06), remainders .004/.001/.005, so the largest remainder (the
|
||||
/// third) gets the cent: 0.01/0.02/0.04, wherever it sits in the list.
|
||||
@@ -1736,7 +1737,7 @@ fn only_a_posted_line_can_clear() {
|
||||
// account_balance
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Oracle: account_balance INVARIANT 1 / B-5 and trial balance SCENARIO 2:
|
||||
/// Oracle: account_balance INVARIANT 1 / BS-ledger-3 and trial balance SCENARIO 2:
|
||||
/// asset debited 100 and credited 30 is 70; credit-normal accounts read
|
||||
/// credits minus debits; a contra balance is negative.
|
||||
#[test]
|
||||
@@ -1818,7 +1819,7 @@ fn the_balance_of_an_unknown_account_is_refused() {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Oracle: set_line_class GOAL: a draft line is tagged (and cleared with
|
||||
/// None); SCENARIO 1 (B-8): a posted line NEVER changes; SCENARIO 2: an
|
||||
/// None); SCENARIO 1 (BS-ledger-4): a posted line NEVER changes; SCENARIO 2: an
|
||||
/// unknown line or class is refused.
|
||||
#[test]
|
||||
fn only_draft_lines_take_a_class() {
|
||||
@@ -2287,7 +2288,7 @@ proptest! {
|
||||
prop_assert_eq!(observe_but_account_ids(&f.b.l), before, "command {} changed the books ({:?})", k, r);
|
||||
}
|
||||
|
||||
/// Oracle: B-1/B-6 and post_entry INVARIANT 2 against the test's own
|
||||
/// Oracle: BS-entry-1/BS-statement-1 and post_entry INVARIANT 2 against the test's own
|
||||
/// model: every balanced random entry posts, the log is exactly the
|
||||
/// posting sequence, earlier entries never change, every balance equals
|
||||
/// the model on its normal side, and the trial balance balances.
|
||||
@@ -2314,7 +2315,7 @@ proptest! {
|
||||
prop_assert!(trial_balance(&b.l).balanced());
|
||||
}
|
||||
|
||||
/// Oracle: close INVARIANTS 1-4 and B-13 against the test's own model,
|
||||
/// Oracle: close INVARIANTS 1-4 and BS-partner-1 against the test's own model,
|
||||
/// for random books closed 50/50 to members at Jan 31: revenue and
|
||||
/// expense are zero as of Jan 31; what remains is exactly February and
|
||||
/// March; the members' credits sum to January's net with A taking the
|
||||
@@ -2551,7 +2552,7 @@ fn renumber_refusals_leave_the_books_unchanged() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Ledger::rename_account (P3, defect 15; rules.md B-31).
|
||||
// Ledger::rename_account (P3, defect 15; BS-ledger-10).
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
proptest! {
|
||||
@@ -2721,7 +2722,7 @@ fn a_closed_period_or_a_role_never_blocks_a_rename() {
|
||||
assert_eq!(l.role_account(&ledger_core::GENERAL_EXPENSES), Some(b.exp));
|
||||
}
|
||||
|
||||
/// rename_account INVARIANT 3 (rules.md B-28's pair): replay takes a
|
||||
/// rename_account INVARIANT 3 (BS-entry-4's pair): replay takes a
|
||||
/// journaled name the command now refuses (blank, a sibling's, nine
|
||||
/// digits, unchanged) for an account that exists, and refuses only an
|
||||
/// unknown account.
|
||||
@@ -2738,7 +2739,7 @@ fn a_journaled_rename_replays_past_the_command_rules() {
|
||||
);
|
||||
}
|
||||
|
||||
/// add_account SCENARIOS 5-6 (rules.md B-31): a new account named like a
|
||||
/// add_account SCENARIOS 5-6 (BS-ledger-10): a new account named like a
|
||||
/// sibling (ignoring capitals and surrounding space; top-level accounts
|
||||
/// are siblings) or holding a run of nine digits is refused, using up no
|
||||
/// id; under another parent the name is free. Replay takes them all, and
|
||||
@@ -2838,12 +2839,12 @@ fn a_rename_reason_is_bounded_text_without_a_tin() {
|
||||
assert!(Ledger::check_rename_reason(&"x".repeat(2_000)).is_ok());
|
||||
}
|
||||
|
||||
/// add_account SCENARIOS 7-8 and rename_account SCENARIO 6 (rules.md
|
||||
/// B-31): a new name is one line of at most MAX_ACCOUNT_NAME characters,
|
||||
/// add_account SCENARIOS 7-8 and rename_account SCENARIO 6 (
|
||||
/// BS-ledger-10): a new name is one line of at most MAX_ACCOUNT_NAME characters,
|
||||
/// kept trimmed, by a new account and a rename alike: 200 characters are
|
||||
/// taken, 201 refused, and so is a line break, a tab or another control
|
||||
/// character; surrounding space is dropped the same way on both paths.
|
||||
/// Replay takes any journaled name (B-28).
|
||||
/// Replay takes any journaled name (BS-entry-4).
|
||||
#[test]
|
||||
fn a_new_name_is_one_trimmed_line_of_bounded_length() {
|
||||
use ledger_core::account::MAX_ACCOUNT_NAME;
|
||||
|
||||
@@ -232,7 +232,7 @@ fn redact_full_tins_masks_every_full_tin() {
|
||||
}
|
||||
|
||||
/// Oracle: `check_text` refuses what `has_full_tin` finds, so a purge
|
||||
/// reason or note quoting the old number with dots is refused (B-26: no
|
||||
/// reason or note quoting the old number with dots is refused (BS-partner-2: no
|
||||
/// party field may hold a nine-digit number).
|
||||
#[test]
|
||||
fn check_text_refuses_a_dotted_tin() {
|
||||
@@ -1461,7 +1461,7 @@ fn entry_flow_takes_across_in_order_until_used_up() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Oracle: shares::target DEFINITIONS, case 3 (rules.md B-35): members
|
||||
/// Oracle: shares::target DEFINITIONS, case 3 (BS-partner-3): members
|
||||
/// named on an entry moving no money split what moved equity, E (here
|
||||
/// −4.00 of a draft not yet balanced), received, in kind (the equipment's
|
||||
/// 10.00, at most |E|); case 5: with a party named who isn't a member,
|
||||
@@ -1860,7 +1860,7 @@ mod shares {
|
||||
assert_eq!(paid_received(&b, b.mo), (Decimal::ZERO, d("100.00")));
|
||||
}
|
||||
|
||||
/// SCENARIO 3 (defect 14, rules.md B-35): property contributed moves
|
||||
/// SCENARIO 3 (defect 14, BS-partner-3): property contributed moves
|
||||
/// no money; each member's part is what moved their capital, signed
|
||||
/// as their own account shows it: received, in kind. Basis cash
|
||||
/// counts nothing; basis all counts it. (Before P3 this read +500.00
|
||||
@@ -1919,7 +1919,7 @@ mod shares {
|
||||
assert_eq!((a.paid, a.received), (Decimal::ZERO, Decimal::ZERO));
|
||||
}
|
||||
|
||||
/// rules.md B-35 item 3 (capital first): a members' entry counts what
|
||||
/// BS-partner-3 item 3 (capital first): a members' entry counts what
|
||||
/// moved their capital, not other money on it: 300.00 in, 200.00 of it
|
||||
/// Tobin's capital and 100.00 an expense refunded, is Tobin's 200.00
|
||||
/// received (cash) and nothing of Morgan's. (Before P3 the 300.00 net
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
//! P3 defects 14, 24 and 11: a party's part of an entry, a party's
|
||||
//! totals, and the directory's TIN last four.
|
||||
//!
|
||||
//! Oracles: rules.md B-35 (a party's part, signed as a line on its own
|
||||
//! Oracles: BS-partner-3 (a party's part, signed as a line on its own
|
||||
//! account, with its direction and its money and property; party totals
|
||||
//! on basis cash or all; a member's entry counts what moved their capital;
|
||||
//! money is cash, cards, the members' financing and loans; a liability
|
||||
//! credit never counts as paying that liability's own creditor), B-9 (a
|
||||
//! correction is the opposite entry), B-13 and the K-1 worksheet (k1
|
||||
//! INVARIANT 3: what is property), B-26 (a TIN's last four), and the spec
|
||||
//! credit never counts as paying that liability's own creditor), BS-ledger-5 (a
|
||||
//! correction is the opposite entry), BS-partner-1 and the K-1 worksheet (k1
|
||||
//! INVARIANT 3: what is property), BS-partner-2 (a TIN's last four), and the spec
|
||||
//! blocks of `ledger_core::shares`, `ledger_core::parties` (`flow`,
|
||||
//! `activity_with`, `Party::tin_last4`) and `ledger_core::kernel`
|
||||
//! (`party_target`, `reverse_target`). Every expected value is worked by
|
||||
@@ -257,7 +257,7 @@ fn part(party: PartyId, amount: &str, cash: &str, in_kind: &str) -> Part {
|
||||
use Side::{Credit as Cr, Debit as Dr};
|
||||
|
||||
/// The audit's reproduction (F36, F37), anonymized, with what each row
|
||||
/// should say (rules.md B-35): `resolved` signed as a line on the party's
|
||||
/// should say (BS-partner-3): `resolved` signed as a line on the party's
|
||||
/// own account, a direction, and what of it was money or property; a
|
||||
/// reversal the exact opposite of what it reverses; totals on both bases,
|
||||
/// labelled.
|
||||
@@ -550,7 +550,7 @@ fn defect14_shares_take_the_partys_side_and_reversals_flip() {
|
||||
);
|
||||
}
|
||||
|
||||
/// B-35 item 4: on the member-only entries, basis all is the statement of
|
||||
/// BS-partner-3 item 4: on the member-only entries, basis all is the statement of
|
||||
/// members' equity (contributions and distributions, the same dates), and
|
||||
/// basis cash is the K-1 worksheet's cash contributions.
|
||||
#[test]
|
||||
@@ -655,7 +655,7 @@ fn defect24_an_accrual_through_another_liability_counts_once() {
|
||||
assert_eq!(b.totals(c, Basis::All), (Decimal::ZERO, d("1200.00")));
|
||||
}
|
||||
|
||||
/// Defect 24 and B-35 item 6: a credit to what the company owes a party
|
||||
/// Defect 24 and BS-partner-3 item 6: a credit to what the company owes a party
|
||||
/// itself never counts as paying it. A fee on the issuer's own card is a
|
||||
/// bill from the issuer (counted when the card is paid); a distribution
|
||||
/// still owed to a member counts when it is paid; equipment bought on the
|
||||
@@ -749,7 +749,7 @@ fn defect24_a_credit_to_a_partys_own_liability_never_pays_it() {
|
||||
assert_eq!(b.totals(m, Basis::All), (Decimal::ZERO, d("800.00")));
|
||||
}
|
||||
|
||||
/// The known limit B-35 states (and the tool text says): when the
|
||||
/// The known limit BS-partner-3 states (and the tool text says): when the
|
||||
/// members aren't named the creditors of their financing account, a
|
||||
/// distribution declared through it counts when declared and again when
|
||||
/// paid. Pinned so a change to it is seen.
|
||||
@@ -778,7 +778,7 @@ fn a_distribution_owed_counts_twice_until_the_members_are_named_its_creditors()
|
||||
/// again when paid (400.00); now it counts nothing until it is paid, then
|
||||
/// 200.00, once, on both bases (Helvering v. Price; party_target
|
||||
/// INVARIANT 2). The statement of members' equity counts it when declared:
|
||||
/// party totals catch up when it is paid (B-35 item 4's conditions).
|
||||
/// party totals catch up when it is paid (BS-partner-3 item 4's conditions).
|
||||
#[test]
|
||||
fn defect24_a_distribution_declared_to_a_payable_counts_once_when_paid() {
|
||||
let mut b = books();
|
||||
@@ -829,7 +829,7 @@ fn defect24_a_distribution_declared_to_a_payable_counts_once_when_paid() {
|
||||
assert_eq!(b.totals(t, Basis::Cash), (d("300.00"), Decimal::ZERO));
|
||||
}
|
||||
|
||||
/// B-35 item 3: a distribution's cash is the money it paid and its in
|
||||
/// BS-partner-3 item 3: a distribution's cash is the money it paid and its in
|
||||
/// kind the property it gave. Equipment carried at 1,000.00 less 300.00
|
||||
/// depreciated, and 100.00 in cash, distributed: 100.00 cash and 700.00
|
||||
/// in kind (it read 800.00 in kind and no cash, the equipment's cost
|
||||
@@ -868,7 +868,7 @@ fn a_distribution_of_money_and_depreciated_property_splits_by_what_moved() {
|
||||
assert_eq!(b.resolved(gain).1, vec![part(t, "900.00", "0", "900.00")]);
|
||||
}
|
||||
|
||||
/// Defect 24 and the card rule (B-35 item 5): a gift card the company
|
||||
/// Defect 24 and the card rule (BS-partner-3 item 5): a gift card the company
|
||||
/// sold is deferred revenue, a promise, though its account's name says
|
||||
/// "card". It counted as received when sold and again when redeemed
|
||||
/// (200.00); now once, when the money came in. A card the company pays
|
||||
@@ -892,7 +892,7 @@ fn defect24_a_gift_card_sold_is_received_once() {
|
||||
assert_eq!(b.totals(c, Basis::All), (Decimal::ZERO, d("100.00")));
|
||||
}
|
||||
|
||||
/// B-35 item 5 and `parties::card_accounts` INVARIANTS 1-4: one rule for
|
||||
/// BS-partner-3 item 5 and `parties::card_accounts` INVARIANTS 1-4: one rule for
|
||||
/// what a card is. Before any business card is recorded, the liabilities
|
||||
/// whose names say "card" but not "gift" (2050 Business Card; never 2410
|
||||
/// Gift Card Liability), less a member's card's account; once one is
|
||||
@@ -958,7 +958,7 @@ fn a_card_is_a_recorded_business_card_else_a_liability_named_card() {
|
||||
assert_eq!(b.resolved(on_2050).0.direction, Direction::Neither);
|
||||
}
|
||||
|
||||
/// B-35 item 3, case 3: E is the movement of equity other than retained
|
||||
/// BS-partner-3 item 3, case 3: E is the movement of equity other than retained
|
||||
/// earnings, so a members' entry reads as the statement of members' equity
|
||||
/// reads it. Retained earnings given up for equipment moves no member's
|
||||
/// capital: neither, as the statement shows no distribution. Retained
|
||||
@@ -1035,7 +1035,7 @@ fn a_refund_is_received_from_the_vendor() {
|
||||
assert_eq!(b.totals(v, Basis::Cash), (d("100.00"), d("20.00")));
|
||||
}
|
||||
|
||||
/// B-35 item 3 (capital first): a mixed contribution is split into money
|
||||
/// BS-partner-3 item 3 (capital first): a mixed contribution is split into money
|
||||
/// and property exactly as the K-1 worksheet splits it (its SCENARIO 3),
|
||||
/// whichever member the shares list first; an expense a member pays
|
||||
/// straight to capital is cash, as on the K-1 (k1 INVARIANT 3); a debt
|
||||
@@ -1168,7 +1168,7 @@ fn a_members_entry_keeps_its_reading_after_they_leave() {
|
||||
);
|
||||
}
|
||||
|
||||
/// B-35 item 3, case 1: a period's closing entry moves nothing with
|
||||
/// BS-partner-3 item 3, case 1: a period's closing entry moves nothing with
|
||||
/// anyone: direction neither, its members' part their income allocated
|
||||
/// (credited to their capital: negative), counted in no total.
|
||||
#[test]
|
||||
@@ -1343,7 +1343,7 @@ fn defect11_a_partys_tin_last4_is_its_tin_facts_else_its_w9s() {
|
||||
assert_eq!(by_hand.tin_last4(), None);
|
||||
}
|
||||
|
||||
/// The kernel's B-35 cases, by hand (party_target INVARIANTS 1-6) and
|
||||
/// The kernel's BS-partner-3 cases, by hand (party_target INVARIANTS 1-6) and
|
||||
/// reverse_target an involution.
|
||||
#[test]
|
||||
fn party_target_cases_by_hand() {
|
||||
@@ -1661,7 +1661,7 @@ proptest! {
|
||||
/// account converted to capital, some through their distributions
|
||||
/// accounts, some declared to distributions payable and paid later,
|
||||
/// and reverse some of it later in the year. For each member, over
|
||||
/// every span from the year's start to any date (B-35 item 4's
|
||||
/// every span from the year's start to any date (BS-partner-3 item 4's
|
||||
/// conditions hold: a reversal in such a span always has its original
|
||||
/// in it): basis all is the statement of members' equity's
|
||||
/// contributions and distributions, but for a distribution declared
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Projects (rules.md B-37): a class with its facts; its figures are the
|
||||
//! Projects (BS-statement-5): a class with its facts; its figures are the
|
||||
//! revenue and expense lines tagged to it.
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: a project's record holds only what its rules allow, and its
|
||||
//! figures are exactly its tagged lines, from one function.
|
||||
//! SOURCE: docs/spec/rules.md B-37 (job costing; ASC 450-30-25-1 and
|
||||
//! 340-40-25-5 for on-spec work), B-11 (closes left out).
|
||||
//! SOURCE: BS-statement-5 (job costing; ASC 450-30-25-1 and
|
||||
//! 340-40-25-5 for on-spec work), BS-period-1 (closes left out).
|
||||
//! ```
|
||||
|
||||
use chrono::NaiveDate;
|
||||
@@ -534,7 +534,7 @@ fn a_reversal_nets_a_project_to_zero() {
|
||||
let entries = project_entries(&b.l, c);
|
||||
assert_eq!(entries, vec![(r, cents(180_000)), (e, cents(-180_000))]);
|
||||
// Nothing left on an account, but two lines tagged: it breaks even,
|
||||
// it isn't untagged (rules.md B-37 item 7).
|
||||
// it isn't untagged (BS-statement-5 item 7).
|
||||
assert!(t.expenses_by_account.is_empty());
|
||||
assert_eq!((t.revenue_lines, t.expenses_lines), (0, 2));
|
||||
assert!(t.any_tagged());
|
||||
@@ -652,7 +652,7 @@ fn differs_from_names_projects() {
|
||||
assert_eq!(a.l.differs_from(&before), vec!["projects"]);
|
||||
}
|
||||
|
||||
/// rules.md B-37 item 7: the margin is the contribution's share of
|
||||
/// BS-statement-5 item 7: the margin is the contribution's share of
|
||||
/// revenue, one place, half to even, and none without revenue.
|
||||
#[test]
|
||||
fn contribution_margin_is_one_place_and_none_without_revenue() {
|
||||
@@ -671,7 +671,7 @@ fn contribution_margin_is_one_place_and_none_without_revenue() {
|
||||
assert_eq!(pct(Decimal::MAX, cents(1)), None, "never panics");
|
||||
}
|
||||
|
||||
/// rules.md B-37 item 7: each month's net to date opens on the lines
|
||||
/// BS-statement-5 item 7: each month's net to date opens on the lines
|
||||
/// before the months (a deposit last year) and ends on the net to date;
|
||||
/// a reimbursement credited above its cost leaves the expense below zero.
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Figures derived from what replay accepts: computed exactly where exact
|
||||
//! arithmetic and chrono's calendar reach, refused (TooLargeToCompute,
|
||||
//! DateOutOfRange) where they don't, never a panic (rules.md B-28; P0
|
||||
//! DateOutOfRange) where they don't, never a panic (BS-entry-4; P0
|
||||
//! review round 4, 2026-10-17).
|
||||
//!
|
||||
//! ```text
|
||||
@@ -243,8 +243,8 @@ fn a_draft_of_decimals_largest_is_refused_where_summed() {
|
||||
assert!(why.contains("too large to compute"), "{why}");
|
||||
assert_eq!(l.post_entry(e).unwrap_err(), LedgerError::AmountOutOfRange);
|
||||
}
|
||||
// A member's capital moved past exact arithmetic (rules.md B-35, case
|
||||
// 3, B-28): the target is refused, never a panic.
|
||||
// A member's capital moved past exact arithmetic (BS-partner-3, case
|
||||
// 3, BS-entry-4): the target is refused, never a panic.
|
||||
let e = l.create_entry(d(2026, 3, 1), "huge capital");
|
||||
for _ in 0..2 {
|
||||
l.replay_add_line(e, cash, Side::Debit, usd(Decimal::MAX))
|
||||
@@ -285,7 +285,7 @@ fn a_draft_of_decimals_largest_is_refused_where_summed() {
|
||||
|
||||
/// A document is restored as journaled: its total is exact, or refused
|
||||
/// past exact arithmetic; what it owes is what the ledger lines tagged
|
||||
/// with it carry (rules.md B-38), exact, whatever the journal held (paid
|
||||
/// with it carry (BS-arap-2), exact, whatever the journal held (paid
|
||||
/// above its total included); aging refuses a document whose total it
|
||||
/// can't compute.
|
||||
#[test]
|
||||
@@ -363,7 +363,7 @@ fn documents_and_aging_are_exact_or_refused() {
|
||||
(Decimal::from(11), -Decimal::ONE)
|
||||
);
|
||||
// A payment event naming an amount no line of its entry carries tags
|
||||
// nothing, and is refused nothing (B-28).
|
||||
// nothing, and is refused nothing (BS-entry-4).
|
||||
l.replay_invoice_payment(1, -Decimal::ONE, p).unwrap();
|
||||
assert_eq!(l.get_invoice(1).unwrap().balance(), Ok(-Decimal::ONE));
|
||||
// A total of lines that overflow, and its balance; aging refuses it.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Spec-derived tests for the reports (`reports.rs`).
|
||||
//!
|
||||
//! Written from the spec blocks (GOAL / SOURCE / INVARIANTS / SCENARIOS) and
|
||||
//! `docs/spec/rules.md` / `docs/requirements.md` only, never from the
|
||||
//! bookspec's rules and wanderbooks' claims in `docs/spec/claims/` /
|
||||
//! `docs/requirements.md` only, never from the
|
||||
//! implementation. Every expected value is either a literal computed by hand
|
||||
//! from the spec or a law (property) that pins the answer without calling the
|
||||
//! function under test to compute it. Where the random-book tests need a
|
||||
@@ -42,7 +43,7 @@ fn usd(cents: i64) -> Money {
|
||||
fn post(l: &mut Ledger, date: NaiveDate, desc: &str, lines: &[(AccountId, Side, i64)]) -> EntryId {
|
||||
// As replay posts it: these books hold hand lines on receivables or
|
||||
// payables (1200, 2000), which books an earlier version wrote still
|
||||
// hold and every report must read; the control guard (rules.md B-38)
|
||||
// hold and every report must read; the control guard (BS-arap-2)
|
||||
// refuses them as new work.
|
||||
ledger_core::parties::replaying(|| {
|
||||
let e = l.create_entry(date, desc);
|
||||
@@ -1115,7 +1116,7 @@ fn me_unexplained_equity_change_goes_in_other() {
|
||||
/// 50.00).
|
||||
///
|
||||
/// ASSUMED: a closing entry's credit to a member's capital account is not
|
||||
/// reported as a contribution (B-11: a close moves earnings), so January's
|
||||
/// reported as a contribution (BS-period-1: a close moves earnings), so January's
|
||||
/// statement shows contributions 1000 / 0, income 50.01 / 50.00.
|
||||
#[test]
|
||||
fn me_after_members_close_does_not_count_close_as_contribution() {
|
||||
@@ -1473,7 +1474,7 @@ fn cf_undesignated_liability_is_operating() {
|
||||
assert_eq!(cf.net_change_in_cash, c(58000));
|
||||
}
|
||||
|
||||
/// Oracle: CF INVARIANT 5 / B-14 — closing entries never counted: after
|
||||
/// Oracle: CF INVARIANT 5 / BS-statement-3 — closing entries never counted: after
|
||||
/// closing February into retained earnings the February statement is
|
||||
/// unchanged (NI still 400, 3999 not in financing).
|
||||
#[test]
|
||||
@@ -1792,7 +1793,7 @@ fn build_ordered(gens: &[Gen], scale: i64, order: &[usize], tag: bool) -> Books
|
||||
let mut entries = Vec::new();
|
||||
// As replay posts it: these books hold hand lines on receivables or
|
||||
// payables (1200, 2000), which books an earlier version wrote still
|
||||
// hold and every report must read; the control guard (rules.md B-38)
|
||||
// hold and every report must read; the control guard (BS-arap-2)
|
||||
// refuses them as new work.
|
||||
ledger_core::parties::replaying(|| {
|
||||
for g in gens {
|
||||
@@ -1931,7 +1932,7 @@ fn opt_month() -> impl Strategy<Value = Option<u32>> {
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(64))]
|
||||
|
||||
/// Oracle: TB INVARIANT 1 / B-6 — total debits equal total credits, and
|
||||
/// Oracle: TB INVARIANT 1 / BS-statement-1 — total debits equal total credits, and
|
||||
/// each total is its column's sum, for any as-of date, with or without a
|
||||
/// close.
|
||||
#[test]
|
||||
@@ -2005,7 +2006,7 @@ proptest! {
|
||||
prop_assert_eq!(many.total_debits, one.total_debits * kk);
|
||||
}
|
||||
|
||||
/// Oracle: B-9 metamorphic — adding an entry and its reversal (same
|
||||
/// Oracle: BS-ledger-5 metamorphic — adding an entry and its reversal (same
|
||||
/// date) leaves TB and P&L unchanged at every date.
|
||||
#[test]
|
||||
fn prop_entry_plus_reversal_leaves_tb_and_pnl_unchanged(gens in arb_books(), extra in arb_gen(), as_of in 0u32..365) {
|
||||
@@ -2222,7 +2223,7 @@ proptest! {
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(64))]
|
||||
|
||||
/// Oracle: BS INVARIANT 1 / B-7 — assets = liabilities + equity (with
|
||||
/// Oracle: BS INVARIANT 1 / BS-statement-2 — assets = liabilities + equity (with
|
||||
/// current earnings), exactly; totals are line sums; never a revenue or
|
||||
/// expense line; with or without a close (RE or members).
|
||||
#[test]
|
||||
@@ -2503,7 +2504,7 @@ proptest! {
|
||||
/// Oracle: CF INVARIANT 2 against an independent model — financing is
|
||||
/// the cash part of the equity and designated-debt movements: each
|
||||
/// entry's cash applied to the sections moving against it, operating,
|
||||
/// investing, financing, each up to its own movement (rules.md B-14
|
||||
/// investing, financing, each up to its own movement (BS-statement-3
|
||||
/// rule 3), then to the kinds within each section in their order;
|
||||
/// plus what the loan or a member's capital paid or received for the
|
||||
/// company (rule 11, D-42): the loan pays for operating lines (the
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! (receivables, revenue, payables, general expense, retained earnings, the
|
||||
//! seven payroll accounts) assigned to the chart's own accounts.
|
||||
//!
|
||||
//! Oracles are `docs/spec/rules.md` B-4 (the five elements) and B-23
|
||||
//! Oracles are BS-ledger-2 (the five elements) and BS-ledger-8
|
||||
//! (control roles), the spec block on `Ledger::assign_role`, the doc
|
||||
//! comments of `Ledger::role_account`, `role_assignment`,
|
||||
//! `check_assign_role`, `control_account`, `ControlAccount::key`, the spec
|
||||
@@ -48,7 +48,7 @@ fn line(desc: &str, amount: &str) -> DocumentLine {
|
||||
}
|
||||
}
|
||||
|
||||
/// The thirteen role keys, as the spec lists them (B-23, B-41's
|
||||
/// The thirteen role keys, as the spec lists them (BS-ledger-8, BS-arap-5's
|
||||
/// bad_debts, and `UnknownRole`).
|
||||
const KEYS: [&str; 13] = [
|
||||
"receivables",
|
||||
@@ -106,9 +106,9 @@ fn bal(l: &Ledger, id: AccountId) -> Decimal {
|
||||
|
||||
/// Draft, add lines, post. Panics on any refusal (setup only). Posted as
|
||||
/// replay posts it: these books hold hand lines on receivables or payables
|
||||
/// (moving a role's balance by hand, B-23's path before documents read
|
||||
/// (moving a role's balance by hand, BS-ledger-8's path before documents read
|
||||
/// their lines), which books an earlier version wrote still hold; the
|
||||
/// control guard (rules.md B-38) refuses them as new work.
|
||||
/// control guard (BS-arap-2) refuses them as new work.
|
||||
fn post(l: &mut Ledger, date: NaiveDate, lines: &[(AccountId, Side, &str)]) -> EntryId {
|
||||
ledger_core::parties::replaying(|| {
|
||||
let id = l.try_create_entry(date, "test entry").unwrap();
|
||||
@@ -250,7 +250,7 @@ fn alice() -> PayrollLine {
|
||||
|
||||
// ------------------------------------------------------------ the roles
|
||||
|
||||
/// Oracle: B-23 (and B-41 for bad_debts) names the roles and their default
|
||||
/// Oracle: BS-ledger-8 (and BS-arap-5 for bad_debts) names the roles and their default
|
||||
/// codes; `control_account` finds a role by its `key`; `UnknownRole` lists
|
||||
/// the thirteen keys.
|
||||
#[test]
|
||||
@@ -601,7 +601,7 @@ fn an_unknown_account_is_refused() {
|
||||
|
||||
// ----------------------------------------- SCENARIO 2: type / placeholder
|
||||
|
||||
/// Oracle: SCENARIO 2 + INVARIANT 3 + B-4: every role refuses an account of
|
||||
/// Oracle: SCENARIO 2 + INVARIANT 3 + BS-ledger-2: every role refuses an account of
|
||||
/// each other type with ControlAccountMismatch naming the account, the
|
||||
/// role, the type needed and the type found.
|
||||
#[test]
|
||||
@@ -688,7 +688,7 @@ fn none_is_refused_when_the_default_code_holds_a_wrong_typed_account() {
|
||||
}
|
||||
|
||||
// The role assigned elsewhere, then 1200 taken by a wrong type (an
|
||||
// assignment frees the code, B-23 / check_renumber_account): None is
|
||||
// assignment frees the code, BS-ledger-8 / check_renumber_account): None is
|
||||
// refused, and the assignment stays.
|
||||
let (mut l, _) = books();
|
||||
let ar = add(&mut l, "1100", "Trade Receivables", AccountType::Asset);
|
||||
@@ -784,7 +784,7 @@ fn none_is_refused_when_its_codes_account_fills_another_role() {
|
||||
|
||||
// --------------------------------------------- SCENARIO 4: balances move
|
||||
|
||||
/// Oracle: SCENARIO 4 + B-23 ("moves only when its account holds no
|
||||
/// Oracle: SCENARIO 4 + BS-ledger-8 ("moves only when its account holds no
|
||||
/// balance, so the bookkeeper first moves the balance with an entry").
|
||||
#[test]
|
||||
fn receivables_cannot_move_while_holding_a_balance_but_can_once_moved_out() {
|
||||
@@ -814,7 +814,7 @@ fn receivables_cannot_move_while_holding_a_balance_but_can_once_moved_out() {
|
||||
other => panic!("expected DocumentRoleHoldsBalance, got {other:?}"),
|
||||
}
|
||||
// Moving the balance by hand is refused now (the control guard,
|
||||
// rules.md B-38): until a role's balance moves with its documents
|
||||
// BS-arap-2): until a role's balance moves with its documents
|
||||
// (plan P4b S7), a receivables role holding a balance stays put.
|
||||
let e = l.try_create_entry(d(2026, 3, 2), "move").unwrap();
|
||||
assert!(matches!(
|
||||
@@ -874,7 +874,7 @@ fn every_balance_sheet_role_holds_while_its_account_has_a_balance() {
|
||||
);
|
||||
if c.key == RECEIVABLES.key || c.key == PAYABLES.key {
|
||||
// No document posted there: the balance is the chart's own,
|
||||
// so the role moves (B-38); it can't come back to an account
|
||||
// so the role moves (BS-arap-2); it can't come back to an account
|
||||
// holding hand lines.
|
||||
l.assign_role(c.key, Some(target)).unwrap();
|
||||
assert!(
|
||||
@@ -924,7 +924,7 @@ fn none_is_refused_while_the_assigned_balance_sheet_account_holds_a_balance() {
|
||||
let _ = cash;
|
||||
}
|
||||
|
||||
/// Oracle: SCENARIO 4 "Revenue and expense roles move freely"; B-23
|
||||
/// Oracle: SCENARIO 4 "Revenue and expense roles move freely"; BS-ledger-8
|
||||
/// "earlier postings stay where they are"; INVARIANT 4.
|
||||
#[test]
|
||||
fn revenue_and_expense_roles_move_even_with_a_balance() {
|
||||
@@ -1048,7 +1048,7 @@ fn check_assign_role_agrees_and_does_not_mutate() {
|
||||
|
||||
// ------------------------------------------- renumbering and the codes
|
||||
|
||||
/// Oracle: B-23 + check_renumber_account ("an assigned role frees its
|
||||
/// Oracle: BS-ledger-8 + check_renumber_account ("an assigned role frees its
|
||||
/// code"); renumber_account SCENARIO 2 for an unassigned role's code.
|
||||
#[test]
|
||||
fn an_assigned_role_frees_its_code_for_renumbering() {
|
||||
|
||||
@@ -547,11 +547,11 @@ fn statement_json(
|
||||
/// The golden: every number in `golden/members_equity_two_member.json` was
|
||||
/// computed by hand, from the entries, in
|
||||
/// `plan/golden-worksheets/members_equity_two_member.md`, before the engine's
|
||||
/// output was looked at. Rules: B-13 (capital account = contributions +
|
||||
/// output was looked at. Rules: BS-partner-1 (capital account = contributions +
|
||||
/// allocated income − distributions; cent rounding by largest remainder, the
|
||||
/// odd cent to the member listed first; unclosed earnings split cumulatively)
|
||||
/// and B-7 (the Total ties to balance-sheet equity). The same numbers hold
|
||||
/// whether or not January is closed (B-13: a member's capital on a date never
|
||||
/// and BS-statement-2 (the Total ties to balance-sheet equity). The same numbers hold
|
||||
/// whether or not January is closed (BS-partner-1: a member's capital on a date never
|
||||
/// moves when its period closes).
|
||||
#[test]
|
||||
fn golden_members_equity_two_member() {
|
||||
@@ -1102,7 +1102,7 @@ fn cf_params(start: NaiveDate, end: NaiveDate, cash: AccountId) -> CashFlowParam
|
||||
}
|
||||
|
||||
fn reconciles(cf: &ledger_core::CashFlowStatement) {
|
||||
// B-14 / cash_flow INVARIANT 4: the three sections sum to the change in
|
||||
// BS-statement-3 / cash_flow INVARIANT 4: the three sections sum to the change in
|
||||
// cash, exactly, and net income and its reconciling items to operating.
|
||||
assert_eq!(
|
||||
cf.cash_from_operations + cf.cash_from_investing + cf.cash_from_financing,
|
||||
@@ -1444,7 +1444,7 @@ fn lines(ls: &[ledger_core::reports::CashFlowLine]) -> Vec<(String, Decimal)> {
|
||||
/// amounts borrowed"): borrowing and repayment are separate lines, one
|
||||
/// per entry, borrowing first (each lender's, by code), then repayments.
|
||||
/// The software the owner paid personally is borrowed from the owner and
|
||||
/// spent on its date (rules.md B-14 rule 11, D-42: constructive receipt
|
||||
/// spent on its date (BS-statement-3 rule 11, D-42: constructive receipt
|
||||
/// and disbursement). Financing: +100 + 1,000 − 100 − 400 = 600; nothing
|
||||
/// is disclosed.
|
||||
#[test]
|
||||
@@ -1487,7 +1487,7 @@ fn a_loan_the_entity_makes_is_investing_gross() {
|
||||
assert_eq!(cf.cash_from_investing, dec(-300));
|
||||
}
|
||||
|
||||
/// Oracle: D-42 (rules.md B-14 rule 11; ASC 230 is silent on a payment
|
||||
/// Oracle: D-42 (BS-statement-3 rule 11; ASC 230 is silent on a payment
|
||||
/// made on the entity's behalf, PwC FSP 6.9.3.1 and DART Roadmap 7.2
|
||||
/// present it as constructive receipt and disbursement). The owner paying
|
||||
/// software personally is cash the company borrowed (financing +100) and
|
||||
@@ -1691,7 +1691,7 @@ mod cumulative_closes {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Oracle: rules.md B-13 (cumulative closes; docs/testing.md #12),
|
||||
/// Oracle: BS-partner-1 (cumulative closes; docs/testing.md #12),
|
||||
/// hand-computed. Closing each cent on its own gives the earlier member
|
||||
/// every tie: A 0.03, B 0.00 after three months. Cumulatively: after
|
||||
/// month 1 the run's 0.01 splits A 0.01 / B 0; after month 2, 0.02
|
||||
@@ -1723,7 +1723,7 @@ mod cumulative_closes {
|
||||
}
|
||||
|
||||
proptest::proptest! {
|
||||
/// Oracle: rules.md B-13, cumulative closes. For any run of monthly
|
||||
/// Oracle: BS-partner-1, cumulative closes. For any run of monthly
|
||||
/// profits and losses closed into three members at 33.33% /
|
||||
/// 33.33% / 33.34%, each member's total from the run is within one
|
||||
/// cent of their exact share of everything closed.
|
||||
@@ -1782,7 +1782,7 @@ mod cumulative_closes {
|
||||
assert_eq!((a, b), (cents("0.02"), cents("0")));
|
||||
}
|
||||
|
||||
/// The rule since P3 (rules.md B-13, D-10): a close to retained
|
||||
/// The rule since P3 (BS-partner-1, D-10): a close to retained
|
||||
/// earnings allocates nothing to the members and is skipped, so March's
|
||||
/// members close continues January's count: the running 0.02 splits
|
||||
/// 0.01 / 0.01, and March gives B the cent.
|
||||
|
||||
@@ -165,7 +165,7 @@ fn by_value(v: &mut serde_json::Value) {
|
||||
/// The golden: every number in `golden/tax_summary_form_1065.json` was
|
||||
/// computed by hand, from the fixture's entries, in
|
||||
/// `plan/golden-worksheets/tax_summary_form_1065.md`, before the engine's
|
||||
/// output was looked at. Rules: B-32 and `sources/irs-tax-lines.md` (the
|
||||
/// output was looked at. Rules: BS-ledger-11 and `sources/irs-tax-lines.md` (the
|
||||
/// category-to-line map; a contra-income expense account reduces receipts;
|
||||
/// meals at 50% from the Schedule C line 24b instructions, so 333.33 is
|
||||
/// 166.665, the cent half away from zero, 166.67; fines and penalties at 0%
|
||||
@@ -228,7 +228,7 @@ fn category_books(category: &str, specs: &[(&str, &str, Option<&str>)]) -> Ledge
|
||||
l
|
||||
}
|
||||
|
||||
/// CHOICE (owner, 2026-11-07; rules.md B-32, B-21): a category rounds
|
||||
/// CHOICE (owner, 2026-11-07; BS-ledger-11, BS-entry-3): a category rounds
|
||||
/// once, on its total. Two Meals accounts of 1.01 at 50%: each share is
|
||||
/// exactly 0.505, so rounding per account would give 0.51 + 0.51 = 1.02;
|
||||
/// the exact sum 1.01 rounds once to 1.01. Book stays exact: 2.02.
|
||||
@@ -441,8 +441,8 @@ fn a_sole_proprietor_cannot_deduct_a_gift_on_schedule_c() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Which accounts need a category, and the policy (P3, defect 8; rules.md
|
||||
// B-32).
|
||||
// Which accounts need a category, and the policy (P3, defect 8;
|
||||
// BS-ledger-11).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn set_policy(l: &mut Ledger, value: &str) {
|
||||
@@ -634,11 +634,11 @@ fn under_refuse_a_needed_category_is_never_cleared() {
|
||||
Err(LedgerError::UnknownAccount(999))
|
||||
);
|
||||
// The engine's own set_account_tax (which replay calls) never checks
|
||||
// the policy (rules.md B-28): a journaled clear replays.
|
||||
// the policy (BS-entry-4): a journaled clear replays.
|
||||
l.set_account_tax(software, None, None).unwrap();
|
||||
}
|
||||
|
||||
/// rules.md B-32 (review R3): every account a tool can require has a
|
||||
/// BS-ledger-11 (review R3): every account a tool can require has a
|
||||
/// category that fits it on every return: a disposal's gain or loss
|
||||
/// account (revenue or expense: Form 4797), tax-exempt income on the
|
||||
/// entity returns, and each control role's account.
|
||||
|
||||
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user