diff --git a/crates/ledger-core/src/evidence.rs b/crates/ledger-core/src/evidence.rs index f03989ea..5fc940bf 100644 --- a/crates/ledger-core/src/evidence.rs +++ b/crates/ledger-core/src/evidence.rs @@ -137,7 +137,11 @@ pub enum Origin { } /// Whether an entry needs evidence before it posts, and why (or why not). -#[derive(Clone, Debug, PartialEq, Eq)] +/// Serialized as `{"decision": "required", "reason": ..}` or +/// `{"decision": "exempt", "source": ..}` (the golden for the evidence +/// gate pins it). +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(tag = "decision", rename_all = "snake_case")] pub enum Requirement { /// The receipt policy covers it: at least one receipt is needed. Required { diff --git a/crates/ledger-store/tests/golden/draft_states_and_evidence_gate.json b/crates/ledger-store/tests/golden/draft_states_and_evidence_gate.json new file mode 100644 index 00000000..6e6255bd --- /dev/null +++ b/crates/ledger-store/tests/golden/draft_states_and_evidence_gate.json @@ -0,0 +1,252 @@ +{ + "drafts_open": [ + { + "entry_id": 2, + "date": "2026-01-10", + "description": "Figma annual plan", + "debits": "40.00", + "state": "awaiting_evidence", + "note": "invoice due from Figma", + "receipts": 0, + "requirement": { + "decision": "required", + "reason": "its debits 40.00 are strictly greater than the 25.00 threshold" + } + }, + { + "entry_id": 3, + "date": "2026-01-11", + "description": "Duplicate hosting invoice", + "debits": "60.00", + "state": "building", + "note": null, + "receipts": 0, + "requirement": { + "decision": "required", + "reason": "its debits 60.00 are strictly greater than the 25.00 threshold" + } + }, + { + "entry_id": 4, + "date": "2026-01-15", + "description": "Office supplies", + "debits": "12.50", + "state": "building", + "note": null, + "receipts": 0, + "requirement": { + "decision": "exempt", + "source": "the receipt policy (policy.evidence.*): under the threshold, or on exempt accounts" + } + }, + { + "entry_id": 5, + "date": "2026-01-20", + "description": "Hosting", + "debits": "100.00", + "state": "building", + "note": null, + "receipts": 1, + "requirement": { + "decision": "required", + "reason": "its debits 100.00 are strictly greater than the 25.00 threshold" + } + } + ], + "gate_refusals": [ + { + "entry_id": 2, + "refused": "receipt_required", + "journal_head_unchanged": true + }, + { + "entry_id": 3, + "refused": "receipt_required", + "journal_head_unchanged": true + } + ], + "posted_entries": [ + { + "entry_id": 1, + "description": "Seed", + "reversal_of": null, + "debits": "500.00", + "receipts": 1, + "requirement": { + "decision": "required", + "reason": "its debits 500.00 are strictly greater than the 25.00 threshold" + } + }, + { + "entry_id": 2, + "description": "Figma annual plan", + "reversal_of": null, + "debits": "40.00", + "receipts": 1, + "requirement": { + "decision": "required", + "reason": "its debits 40.00 are strictly greater than the 25.00 threshold" + } + }, + { + "entry_id": 4, + "description": "Office supplies", + "reversal_of": null, + "debits": "12.50", + "receipts": 0, + "requirement": { + "decision": "exempt", + "source": "the receipt policy (policy.evidence.*): under the threshold, or on exempt accounts" + } + }, + { + "entry_id": 5, + "description": "Hosting", + "reversal_of": null, + "debits": "100.00", + "receipts": 1, + "requirement": { + "decision": "required", + "reason": "its debits 100.00 are strictly greater than the 25.00 threshold" + } + }, + { + "entry_id": 6, + "description": "Reverse hosting (billed in error)", + "reversal_of": 5, + "debits": "100.00", + "receipts": 0, + "requirement": { + "decision": "exempt", + "source": "a reversal: its evidence is its original's (B-43, D-47, D-12)" + } + } + ], + "close_refused_with_draft": { + "refused": "drafts_in_period", + "period_id": 1 + }, + "discard_of_posted_refused": { + "entry_id": 1, + "refused": true + }, + "before_discard": { + "drafts": [ + { + "entry_id": 3, + "date": "2026-01-11", + "description": "Duplicate hosting invoice", + "debits": "60.00", + "state": "building", + "note": null, + "receipts": 0, + "requirement": { + "decision": "required", + "reason": "its debits 60.00 are strictly greater than the 25.00 threshold" + } + } + ], + "next_entry_id": 7, + "trial_balance": { + "lines": [ + { + "code": "1000", + "name": "Cash", + "debit": "447.50", + "credit": "0" + }, + { + "code": "3000", + "name": "Owner's Equity", + "debit": "0", + "credit": "500.00" + }, + { + "code": "6100", + "name": "Software", + "debit": "52.50", + "credit": "0" + } + ], + "total_debits": "500.00", + "total_credits": "500.00" + } + }, + "draft_journal_lines": [ + { + "type": "entry.draft_state_set", + "id": 2, + "state": "awaiting_evidence", + "note": "invoice due from Figma" + }, + { + "type": "entry.draft_discarded", + "id": 3, + "reason": "entered twice" + } + ], + "after_discard": { + "drafts": [], + "next_entry_id": 7, + "trial_balance": { + "lines": [ + { + "code": "1000", + "name": "Cash", + "debit": "447.50", + "credit": "0" + }, + { + "code": "3000", + "name": "Owner's Equity", + "debit": "0", + "credit": "500.00" + }, + { + "code": "6100", + "name": "Software", + "debit": "52.50", + "credit": "0" + } + ], + "total_debits": "500.00", + "total_credits": "500.00" + }, + "trial_balance_equals_before": true + }, + "close_after_discard": { + "closing_entry": 7, + "debits": "52.50", + "receipts": 0, + "requirement": { + "decision": "exempt", + "source": "a period's closing entry: derived from the books (B-43)" + } + }, + "after_close": { + "trial_balance": { + "lines": [ + { + "code": "1000", + "name": "Cash", + "debit": "447.50", + "credit": "0" + }, + { + "code": "3000", + "name": "Owner's Equity", + "debit": "0", + "credit": "500.00" + }, + { + "code": "3999", + "name": "Retained Earnings", + "debit": "52.50", + "credit": "0" + } + ], + "total_debits": "500.00", + "total_credits": "500.00" + } + } +} diff --git a/crates/ledger-store/tests/golden_drafts.rs b/crates/ledger-store/tests/golden_drafts.rs new file mode 100644 index 00000000..14aff4ac --- /dev/null +++ b/crates/ledger-store/tests/golden_drafts.rs @@ -0,0 +1,284 @@ +//! Golden file for draft states, discard and the one evidence gate +//! (`docs/parity.md`: "Draft states and discard" and "One evidence gate"). +//! +//! Rules: `docs/spec/rules.md` B-43 (a draft waits on its evidence; one that +//! will never post can be discarded), D-47 (a reversal needs no receipt of +//! its own), B-12 (a period with an open draft cannot close). +//! +//! It is a `Store` fixture, not a bare `Ledger`, because the gate's second +//! half (is a receipt on file) lives in the store. Every expected value is +//! computed by hand in +//! `plan/golden-worksheets/draft-states-and-evidence-gate.md`. + +use chrono::NaiveDate; +use ledger_core::evidence::requirement; +use ledger_core::reports::trial_balance_as_of; +use ledger_core::{AccountType, Currency, DraftState, Money, Side}; +use ledger_store::{Store, StoreError}; +use rust_decimal::Decimal; +use serde_json::{Value, json}; +use std::path::PathBuf; + +fn jan(day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(2026, 1, day).unwrap() +} + +/// Exact cents: `usd(1250)` is 12.50. +fn usd(cents: i64) -> Money { + Money::new(Decimal::new(cents, 2), Currency::USD) +} + +/// A test's dir, removed when the test ends, pass or panic. +struct TestDir(PathBuf); + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn test_dir(name: &str) -> TestDir { + let dir = std::env::temp_dir().join(format!("wanderbooks-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + TestDir(dir) +} + +/// A draft of `cents` from `debit` to `credit`. +fn draft( + s: &mut Store, + date: NaiveDate, + what: &str, + (debit, credit): (u64, u64), + cents: i64, +) -> u64 { + let id = s.create_entry(date, what).unwrap(); + s.add_line(id, debit, Side::Debit, usd(cents)).unwrap(); + s.add_line(id, credit, Side::Credit, usd(cents)).unwrap(); + id +} + +/// File a receipt (distinct bytes: identical bytes are one file) on `entry`. +fn receipt(s: &mut Store, entry: u64) { + s.attach_receipt( + Some(entry), + "receipt.pdf", + "application/pdf", + format!("%PDF-1.4 receipt for entry {entry}").as_bytes(), + None, + ) + .unwrap(); +} + +/// One draft as the viewer lists it: its state and the gate's decision. +fn draft_record(s: &Store, id: u64) -> Value { + let ledger = s.ledger(); + let e = ledger.get_entry(id).unwrap(); + let note = match e.draft_state() { + DraftState::Building => Value::Null, + DraftState::AwaitingEvidence { note } => json!(note), + }; + json!({ + "entry_id": id, + "date": e.date().to_string(), + "description": e.description(), + "debits": ledger_core::evidence::Policy::entry_debits(e).unwrap().to_string(), + "state": e.draft_state().key(), + "note": note, + "receipts": s.list_attachments(Some(id)).unwrap().len(), + "requirement": serde_json::to_value(requirement(ledger, e, ledger.settings())).unwrap(), + }) +} + +fn drafts(s: &Store) -> Vec { + s.ledger() + .drafts() + .iter() + .map(|e| draft_record(s, e.id())) + .collect() +} + +fn trial_balance(s: &Store) -> Value { + serde_json::to_value(trial_balance_as_of(s.ledger(), jan(31))).unwrap() +} + +/// By-hand worksheet: `plan/golden-worksheets/draft-states-and-evidence-gate.md`. +#[test] +fn golden_draft_states_and_evidence_gate() { + let dir = test_dir("golden-drafts"); + let mut s = Store::create(&dir.0, Currency::USD).unwrap(); + let cash = s + .add_account("1000", "Cash", AccountType::Asset, None, false) + .unwrap(); + let equity = s + .add_account("3000", "Owner's Equity", AccountType::Equity, None, false) + .unwrap(); + let software = s + .add_account("6100", "Software", AccountType::Expense, None, false) + .unwrap(); + + // 1: the seed, with its receipt, posts through the gate. + let seed = draft(&mut s, jan(2), "Seed", (cash, equity), 50_000); + receipt(&mut s, seed); + s.post_entry_checked(seed).unwrap(); + + // 2..5: four drafts. 2 waits for its invoice; 5 already has its receipt. + let figma = draft( + &mut s, + jan(10), + "Figma annual plan", + (software, cash), + 4_000, + ); + let dup = draft( + &mut s, + jan(11), + "Duplicate hosting invoice", + (software, cash), + 6_000, + ); + let supplies = draft(&mut s, jan(15), "Office supplies", (software, cash), 1_250); + let hosting = draft(&mut s, jan(20), "Hosting", (software, cash), 10_000); + assert_eq!((figma, dup, supplies, hosting), (2, 3, 4, 5)); + s.set_draft_state( + figma, + DraftState::AwaitingEvidence { + note: "invoice due from Figma".into(), + }, + ) + .unwrap(); + receipt(&mut s, hosting); + let drafts_open = drafts(&s); + + // The gate refuses 2 and 3 (required, no receipt), journaling nothing. + let mut gate_refusals = Vec::new(); + for id in [figma, dup] { + let head = s.head(); + let refused = match s.post_entry_checked(id) { + Err(StoreError::ReceiptRequired(info)) => { + assert_eq!(info.entry_id, id); + "receipt_required" + } + other => panic!("expected ReceiptRequired, got {other:?}"), + }; + gate_refusals.push(json!({ + "entry_id": id, + "refused": refused, + "journal_head_unchanged": s.head() == head, + })); + } + + // 4 (under the threshold) and 5 (receipt on file) post; 5 is reversed + // with no receipt of its own; 2 posts once its receipt is filed. + s.post_entry_checked(supplies).unwrap(); + s.post_entry_checked(hosting).unwrap(); + let reversal = s + .reverse_entry(hosting, jan(25), "Reverse hosting (billed in error)") + .unwrap(); + assert_eq!(reversal, 6); + receipt(&mut s, figma); + s.post_entry_checked(figma).unwrap(); + + // A period that draft 3 holds open. + let period = s.create_period("2026-01", jan(1), jan(31)).unwrap(); + let close_refused = match s.close_period(period) { + Err(StoreError::Ledger(ledger_core::LedgerError::DraftsInPeriod(p))) => { + json!({"refused": "drafts_in_period", "period_id": p}) + } + other => panic!("expected DraftsInPeriod, got {other:?}"), + }; + // Only a draft can be discarded. + let discard_posted = json!({ + "entry_id": seed, + "refused": s.discard_draft(seed, "oops").is_err(), + }); + + let before_discard = json!({ + "drafts": drafts(&s), + "next_entry_id": s.ledger().next_entry_id(), + "trial_balance": trial_balance(&s), + }); + s.discard_draft(dup, "entered twice").unwrap(); + let after_tb = trial_balance(&s); + let after_discard = json!({ + "drafts": drafts(&s), + "next_entry_id": s.ledger().next_entry_id(), + "trial_balance": after_tb, + "trial_balance_equals_before": after_tb == before_discard["trial_balance"], + }); + + // The close is accepted now. + let closing = s + .close_period(period) + .unwrap() + .expect("a loss is swept, so there is a closing entry"); + let closing_entry = s.ledger().get_entry(closing).unwrap().clone(); + let close_after_discard = json!({ + "closing_entry": closing, + "debits": ledger_core::evidence::Policy::entry_debits(&closing_entry).unwrap().to_string(), + "receipts": s.list_attachments(Some(closing)).unwrap().len(), + "requirement": serde_json::to_value( + requirement(s.ledger(), &closing_entry, s.ledger().settings())).unwrap(), + }); + + // Every entry that posted, as the gate sees it now (not 3: discarded). + let posted_entries: Vec = [seed, figma, supplies, hosting, reversal] + .iter() + .map(|&id| { + let e = s.ledger().get_entry(id).unwrap(); + json!({ + "entry_id": id, + "description": e.description(), + "reversal_of": e.reversal_of(), + "debits": ledger_core::evidence::Policy::entry_debits(e).unwrap().to_string(), + "receipts": s.list_attachments(Some(id)).unwrap().len(), + "requirement": serde_json::to_value( + requirement(s.ledger(), e, s.ledger().settings())).unwrap(), + }) + }) + .collect(); + + // The journal's draft lines: a state and a discard, with their reasons. + let draft_journal_lines: Vec = + std::fs::read_to_string(dir.0.join(ledger_store::JOURNAL_FILE)) + .unwrap() + .lines() + .map(|l| serde_json::from_str::(l).unwrap()) + .filter(|l| { + l["type"] + .as_str() + .is_some_and(|t| t.starts_with("entry.draft_")) + }) + .map(|l| { + let p = &l["payload"]; + match l["type"].as_str().unwrap() { + "entry.draft_state_set" => json!({ + "type": l["type"], "id": p["id"], "state": p["state"], "note": p["note"], + }), + _ => json!({"type": l["type"], "id": p["id"], "reason": p["reason"]}), + } + }) + .collect(); + + s.verify().unwrap(); + let got = json!({ + "drafts_open": drafts_open, + "gate_refusals": gate_refusals, + "posted_entries": posted_entries, + "close_refused_with_draft": close_refused, + "discard_of_posted_refused": discard_posted, + "before_discard": before_discard, + "draft_journal_lines": draft_journal_lines, + "after_discard": after_discard, + "close_after_discard": close_after_discard, + "after_close": {"trial_balance": trial_balance(&s)}, + }); + let want: Value = + serde_json::from_str(include_str!("golden/draft_states_and_evidence_gate.json")).unwrap(); + assert_eq!( + got, + want, + "got:\n{}", + serde_json::to_string_pretty(&got).unwrap() + ); +} diff --git a/plan/golden-worksheets/draft-states-and-evidence-gate.md b/plan/golden-worksheets/draft-states-and-evidence-gate.md new file mode 100644 index 00000000..6cc24893 --- /dev/null +++ b/plan/golden-worksheets/draft-states-and-evidence-gate.md @@ -0,0 +1,129 @@ +# Golden worksheet — draft states, discard, and the one evidence gate + +Rules: `docs/spec/rules.md` B-43 (a draft waits on its evidence; one that +will never post can be discarded), D-47 (a reversal needs no receipt of its +own: its evidence is its original's, D-12), B-12 (a period with an open +draft cannot close), B-9 (corrections are reversing entries). +Golden: `crates/ledger-store/tests/golden/draft_states_and_evidence_gate.json`. +Test: `golden_draft_states_and_evidence_gate` in +`crates/ledger-store/tests/golden_drafts.rs`. + +Parity rows this serves: "Draft states and discard" and "One evidence gate +(`evidence::requirement`)". + +## Fixture + +A new fixture, built like `books_for_drafts` in `store.rs` (cash, equity, +one expense account, a seed posted from a receipt) and extended. It is a +`Store`, not a bare `Ledger`, because the gate's second half (does the entry +have a receipt filed on it) lives in the store. Default settings: receipts +are required strictly above 25.00 (`policy.evidence.threshold`, B-43 and the +owner's ">$25", 2026-10-12). + +Accounts: 1000 Cash (Asset), 3000 Owner's Equity (Equity), 6100 Software +(Expense). Period `2026-01` = 2026-01-01..2026-01-31 (period id 1). + +| # | Date | Description | Lines | Becomes | +|---|------|-------------|-------|---------| +| 1 | 01-02 | Seed | Dr 1000 500.00; Cr 3000 500.00 | receipt filed, posted | +| 2 | 01-10 | Figma annual plan | Dr 6100 40.00; Cr 1000 40.00 | state `awaiting_evidence` "invoice due from Figma"; refused at the gate; later receipt filed, posted | +| 3 | 01-11 | Duplicate hosting invoice | Dr 6100 60.00; Cr 1000 60.00 | `building`; refused at the gate; **discarded** "entered twice" | +| 4 | 01-15 | Office supplies | Dr 6100 12.50; Cr 1000 12.50 | `building`, no receipt, posted (under threshold) | +| 5 | 01-20 | Hosting | Dr 6100 100.00; Cr 1000 100.00 | `building`, receipt filed while still a draft, posted | +| 6 | 01-25 | Reverse hosting (billed in error) | reversal of 5: Dr 1000 100.00; Cr 6100 100.00 | posted at once, **no receipt of its own** | +| 7 | 01-31 | Close period 2026-01 (generated) | see below | the close, accepted once 3 is gone | + +Order of commands (ids are allocated at creation, so this is the id order): +create 1, receipt on 1, post 1; create 2, 3, 4, 5; state of 2; receipt on 5; +list the drafts; try to post 2 and 3 (refused); post 4, 5; reverse 5 (id 6); +receipt on 2, post 2; create the period; try to close (refused: draft 3 +open); try to discard the posted entry 1 (refused); trial balance; discard +3; trial balance; close (id 7); trial balance. + +## Hand computation + +### What the gate requires of each entry (`evidence::requirement`, B-43 INVARIANT 2) + +The decision is a pure function of the entry and the settings: it never asks +whether a receipt exists. Required when debits are strictly greater than +25.00 and the entry has no origin exemption; Exempt otherwise. + +- #1 debits 500.00 > 25.00, hand entry: **Required**. +- #2 debits 40.00 > 25.00: **Required**. +- #3 debits 60.00 > 25.00: **Required**. +- #4 debits 12.50 <= 25.00 (not strictly greater): **Exempt** by the policy. + Not part of a split group: no posted entry shares its date and description. +- #5 debits 100.00 > 25.00: **Required**. +- #6 debits 100.00 > 25.00 would be Required, but it is a reversal: + **Exempt** (D-47, D-12). +- #7 debits 52.50 > 25.00 would be Required, but it is a period's closing + entry: **Exempt** (derived from the books, B-43). + +Whether a receipt is *on file* is a separate count, pinned beside it: +#1 1, #2 0 then 1 (filed before posting), #3 0, #4 0, #5 1, #6 0, #7 0. +The gate therefore refuses #2 and #3 when tried (Required, no receipt) and +lets #4 (Exempt), #5 (Required, has one), and later #2 (receipt filed) post. +A refusal journals nothing: the journal head is unchanged. + +### Draft states (B-43 INVARIANT 3) + +A state is a note: it moves no figure. Only #2 had a state set; #3, #4, #5 +stay at the default `building`. The journal holds exactly two draft lines: +`entry.draft_state_set` for #2 (state `awaiting_evidence`, the note) and +`entry.draft_discarded` for #3 (reason "entered twice"). + +### Trial balance as of 2026-01-31, before the discard (entries 1, 2, 4, 5, 6 posted) + +- 1000 Cash: debit 500.00 (#1); credits 40.00 (#2) + 12.50 (#4) + 100.00 + (#5) = 152.50; debit 100.00 (#6). Net debit 500.00 - 152.50 + 100.00 = + **447.50**. +- 3000 Owner's Equity: credit **500.00**. +- 6100 Software: debits 40.00 + 12.50 + 100.00 = 152.50; credit 100.00 (#6). + Net debit **52.50**. +- Debits 447.50 + 52.50 = **500.00**; credits **500.00**. Balanced. The + accounting equation: assets 447.50 = equity 500.00 - loss 52.50. + +Draft #3 (60.00) is not in any balance: drafts are not in the books. + +### Close with a draft open (B-12) + +The period holds draft #3, so the close is refused (`DraftsInPeriod`, period +1). Drafts #2, #4, #5 have posted, so #3 is the only one holding it open. + +### Discard (B-43 INVARIANT 4) + +#3 is discarded with a reason. Nothing posted moves: the trial balance is +identical to the one before (same numbers, as a boolean in the golden too); +no id is spent (next entry id is 7 both before and after: ids 1-6 were +allocated, 3 stays a hole); the draft list goes from [3] to []. A posted +entry cannot be discarded (#1 refused). + +### Close, accepted (B-12, B-43 INVARIANT 4's last sentence) + +Net income for January = revenue 0 - expense 52.50 = loss 52.50. The +closing entry sweeps 6100 to zero and posts the loss to Retained Earnings +(3999, created by the close): **Dr 3999 52.50; Cr 6100 52.50**, entry id 7. +It is Exempt (origin), no receipt. + +### Trial balance as of 2026-01-31, after the close + +- 1000 Cash debit **447.50** (unchanged). +- 3000 Owner's Equity credit **500.00**. +- 3999 Retained Earnings debit **52.50** (a loss). +- 6100 Software: 52.50 - 52.50 = 0, omitted (a trial balance shows non-zero + balances only). +- Debits 447.50 + 52.50 = **500.00**; credits **500.00**. + +## What the golden pins + +`drafts_open` (the four drafts before the gate is tried), `gate_refusals` +(#2 and #3 refused, journal head unchanged), `posted_entries` (every entry +that posted with its requirement and receipt count, including the reversal +with no receipt of its own and the closing entry), `close_refused_with_draft`, +`discard_of_posted_refused`, `before_discard` / `after_discard` (drafts, next +id, trial balance, equal), `draft_journal_lines`, `close_after_discard`, and +`after_close`. + +The requirement's `reason` / `source` wording is pinned as the code words it +(B-43 INVARIANT 2 fixes the decision and its sources, not the sentence); +a reworded message shows up as a golden diff to be re-read.