feat(arap)!: documents read their figures from standing lines; control accounts
check / check (push) Canceled after 0s
check / check (push) Canceled after 0s
refuse hand entries (P4b S1, part A) Plan P4b (D-45), slice S1, the engine half: rules.md B-38. - ledger-core: every receivables or payables line carries its document (Ledger.line_docs: DocRef, Movement, DocTag), written by the document commands in the step that posts it, derived on replay from the existing document events (the role's account as it stood then; payments by the ordinal rule), copied onto a reversal's mirror. Ledger::stands_on; doc_state / invoice_state / bill_state (total, paid, outstanding, status Open/Partial/Paid/WrittenOff/Void, overdue days) as of any day; ar_aging / ap_aging read them, so reversed payments and voids are right. The control guard (add_line, add_line_fx, post_entry, register_recurring) refuses untagged lines on receivables/payables, exempting a reversal's mirror of a legacy line; replay never refuses. Bounds (kernel::running_bounds, bounds_kept) on payments and reversals; a document reversal never dated before its entry; deposit/payer accounts must be cash-like and hold no role. New API: receive_payment_with / pay_bill_with (PaymentDetails: instrument, reference), void_document / check_void_document, control_check, payments_recorded, standing_payments, replay_reverse_entry. Invoice.amount_paid/status remain only as derived caches for the MCP layer until part B. cashflow bill_splits reads payments from the tags. - ledger-store: journal feature document_standing (D-39 gated) for a payment accepted only because an earlier one was reversed; receive_payment_with / pay_bill_with (instrument journaled as entry.instrument_set, reference in the description), void_document; replay uses replay_reverse_entry; schema 15 drops the projection's amount_paid/status. Fixture p4-arap-before + golden figures written by the version before S1, adjudicated in arap_standing.rs. - ledger-gui: party card, cash "coming up" and company owed totals read doc_state as of today (late from the derived state). - Lean Documents.lean (control_agrees and friends); Kani bounds_check_matches_definition, bounds_kept_is_the_definition_on_books_in_bounds; rules B-38, B-18/B-23 amended; bookspec `older = true` for legacy hand lines; tests that hand-post to 1200/2000 post as replay or renumbered. Review fixes (both reviews of part A): - control_role_of guards only an account the role is assigned to or one holding its documents' lines (a chart's own 1200 Equipment or card at 2000 is free until a document posts there); payment accounts check other roles by holds_role (type-checked). The MCP tests that failed on the guard (oracle_mcp, spec_projects) pass unchanged. - standing_payments leaves out reversals (sorted, deduped); replayed tags match the movement's side; payments_recorded counts every payment event (tagged or not, Ledger.payment_events) and refuses overflow. - The record caches settled (paid + discounted + written off) and owed (Invoice/Bill.owed, never serialized): a void never reads as paid. - assign_role: receivables/payables refuse moving onto an account with untagged lines (RoleAccountHasHandLines) and, on their control account holding a balance, say DocumentRoleHoldsBalance (no hand entry named); B-23 reworded. The reversal-mirror exemption only takes a hand line off (even chain depth); putting it back is refused. - DocStatus Overpaid and Unattached; aging leaves out credit balances; ControlCheck.attention lists out-of-bounds and unattached documents. - stands_on counts a chain in order; indexes (doc_index, doc_accounts, order_pos, reversed_by) keep the derived figures linear. - Viewer reads a post-dated document as of its own date; one state per row. bounds_kept's side-crossing documented as intended. - Tests: ten new spec_documents scenarios, stronger proptests, store proptest arap_props (live = replay = snapshot at every date, closed months), fuzz ops void/payments with details, a GUI post-dated test; Lean Step.assign / Step.release with unattached_zero kept; model limits stated in docs/testing.md and B-38. Review fixes (CPA and engineering lenses): only an assigned role's account or one holding document lines is a control account (a chart's own 1200 asset stays free); a role can't move onto untagged lines or off document lines (Lean Step.assign); a void's cache never reads as paid; no Decimal sum panics; per-document indexes keep figures linear; a replayed tag matches its side; the feature gate counts payment events; a payment's reversal is never listed as standing; an overpaid document has its own status; the viewer keeps post-dated documents. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T3gXMVt7XJPi6ens1or9Dj
This commit is contained in:
54 files changed
+5997
-649
No files matched your search
@@ -383,6 +383,12 @@ struct Event {
|
||||
/// The payment method (an `setup.instruments` label) it was paid with.
|
||||
#[serde(default)]
|
||||
instrument: Option<String>,
|
||||
/// An entry as an earlier version could write it and this version's
|
||||
/// commands refuse: a line by hand on a receivables or payables
|
||||
/// account (the control guard, rules.md B-38). Posted as replay posts
|
||||
/// it, since books that hold it must still read right.
|
||||
#[serde(default)]
|
||||
older: bool,
|
||||
}
|
||||
|
||||
/// A depreciation run of `asset` for `period` ("YYYY-MM"): what is due
|
||||
@@ -1315,6 +1321,10 @@ impl<'a> Books<'a> {
|
||||
"describes its own entries: no description"
|
||||
}
|
||||
);
|
||||
assert!(
|
||||
!e.older || kind == "lines",
|
||||
"{ex} event {n}: older is an entry's lines, as an earlier version wrote them"
|
||||
);
|
||||
assert!(
|
||||
e.payee.is_none() || kind == "lines",
|
||||
"{ex} event {n}: a payee is an entry's: a reversal takes its original's, a bill names its vendor, an invoice its customer, a close and a command have none"
|
||||
@@ -1471,25 +1481,32 @@ impl<'a> Books<'a> {
|
||||
let day = || when.expect("checked: dated");
|
||||
match kind {
|
||||
"lines" => {
|
||||
let entry = self.store.create_entry(day(), description)?;
|
||||
for (i, line) in e.lines.iter().enumerate() {
|
||||
let side = match line.side.as_str() {
|
||||
"debit" => Side::Debit,
|
||||
"credit" => Side::Credit,
|
||||
other => panic!("{what}: side {other:?}"),
|
||||
};
|
||||
let amount = Money::new(money(&line.amount), self.currency);
|
||||
let account = self.id(&line.account);
|
||||
self.store.add_line(entry, account, side, amount)?;
|
||||
// Tagged as books.add_line tags it: after the line.
|
||||
if let Some(p) = &line.project {
|
||||
let class = *self.projects.get(p).unwrap_or_else(|| {
|
||||
panic!("{what}: project {p:?} not in setup.projects")
|
||||
});
|
||||
self.store.set_line_class(entry, i, Some(class))?;
|
||||
let post = |this: &mut Self| -> Result<(), StoreError> {
|
||||
let entry = this.store.create_entry(day(), description)?;
|
||||
for (i, line) in e.lines.iter().enumerate() {
|
||||
let side = match line.side.as_str() {
|
||||
"debit" => Side::Debit,
|
||||
"credit" => Side::Credit,
|
||||
other => panic!("{what}: side {other:?}"),
|
||||
};
|
||||
let amount = Money::new(money(&line.amount), this.currency);
|
||||
let account = this.id(&line.account);
|
||||
this.store.add_line(entry, account, side, amount)?;
|
||||
// Tagged as books.add_line tags it: after the line.
|
||||
if let Some(p) = &line.project {
|
||||
let class = *this.projects.get(p).unwrap_or_else(|| {
|
||||
panic!("{what}: project {p:?} not in setup.projects")
|
||||
});
|
||||
this.store.set_line_class(entry, i, Some(class))?;
|
||||
}
|
||||
}
|
||||
this.store.post_entry(entry)
|
||||
};
|
||||
if e.older {
|
||||
ledger_core::parties::replaying(|| post(self))
|
||||
} else {
|
||||
post(self)
|
||||
}
|
||||
self.store.post_entry(entry)
|
||||
}
|
||||
"reverses" => {
|
||||
let of = e.reverses.expect("checked: a reversal");
|
||||
|
||||
@@ -114,11 +114,17 @@ fn pay(
|
||||
cr: AccountId,
|
||||
amt: &str,
|
||||
) -> EntryId {
|
||||
let e = l.create_entry(date, "payment");
|
||||
let m = Money::new(dec(amt), Currency::USD);
|
||||
l.add_line(e, dr, Side::Debit, m).unwrap();
|
||||
l.add_line(e, cr, Side::Credit, m).unwrap();
|
||||
l.post_entry(e).unwrap();
|
||||
// As replay posts it: money from a vendor on receivables (1200) by
|
||||
// hand, as books an earlier version wrote can hold it; the control
|
||||
// guard (rules.md B-38) refuses that as new work.
|
||||
let e = ledger_core::parties::replaying(|| {
|
||||
let e = l.create_entry(date, "payment");
|
||||
let m = Money::new(dec(amt), Currency::USD);
|
||||
l.add_line(e, dr, Side::Debit, m).unwrap();
|
||||
l.add_line(e, cr, Side::Credit, m).unwrap();
|
||||
l.post_entry(e).unwrap();
|
||||
e
|
||||
});
|
||||
if let Some(v) = vendor {
|
||||
l.set_entry_vendor(e, Some(v)).unwrap();
|
||||
}
|
||||
@@ -2433,11 +2439,15 @@ proptest! {
|
||||
if dr == cr {
|
||||
continue;
|
||||
}
|
||||
let e = l.create_entry(d(2026, month, 10), "generated");
|
||||
let m = Money::new(Decimal::new(i64::from(cents), 2), Currency::USD);
|
||||
l.add_line(e, accounts[dr], Side::Debit, m).unwrap();
|
||||
l.add_line(e, accounts[cr], Side::Credit, m).unwrap();
|
||||
l.post_entry(e).unwrap();
|
||||
// As replay posts it (a hand line on receivables: see `pay`).
|
||||
let e = ledger_core::parties::replaying(|| {
|
||||
let e = l.create_entry(d(2026, month, 10), "generated");
|
||||
let m = Money::new(Decimal::new(i64::from(cents), 2), Currency::USD);
|
||||
l.add_line(e, accounts[dr], Side::Debit, m).unwrap();
|
||||
l.add_line(e, accounts[cr], Side::Credit, m).unwrap();
|
||||
l.post_entry(e).unwrap();
|
||||
e
|
||||
});
|
||||
l.set_entry_vendor(e, Some(vendors[v])).unwrap();
|
||||
if let Some(i) = methods[method % methods.len()] {
|
||||
l.set_entry_instrument(e, Some(i)).unwrap();
|
||||
|
||||
@@ -32,11 +32,17 @@ fn usd(amount: u64) -> Money {
|
||||
/// Post a balanced entry in one call. Panics on programmer error: fixtures
|
||||
/// must be valid by construction.
|
||||
fn post(ledger: &mut Ledger, date: NaiveDate, description: &str, lines: &[(AccountId, Side, u64)]) {
|
||||
let id = ledger.create_entry(date, description);
|
||||
for (account, side, amount) in lines {
|
||||
ledger.add_line(id, *account, *side, usd(*amount)).unwrap();
|
||||
}
|
||||
ledger.post_entry(id).unwrap();
|
||||
// As replay posts it: these books hold hand lines on receivables or
|
||||
// payables (1200, 2000), which books an earlier version wrote still
|
||||
// hold and every report must read; the control guard (rules.md B-38)
|
||||
// refuses them as new work.
|
||||
ledger_core::parties::replaying(|| {
|
||||
let id = ledger.create_entry(date, description);
|
||||
for (account, side, amount) in lines {
|
||||
ledger.add_line(id, *account, *side, usd(*amount)).unwrap();
|
||||
}
|
||||
ledger.post_entry(id).unwrap();
|
||||
})
|
||||
}
|
||||
|
||||
struct Company {
|
||||
@@ -649,21 +655,26 @@ fn random_balanced_journals_preserve_invariants() {
|
||||
c.rent,
|
||||
];
|
||||
|
||||
for i in 0..300u32 {
|
||||
let total = rng.next(100_000) + 100;
|
||||
let nd = (rng.next(3) + 1) as usize;
|
||||
let nc = (rng.next(3) + 1) as usize;
|
||||
let id = ledger.create_entry(date(21), &format!("random {i}"));
|
||||
for part in split_total(&mut rng, total, nd) {
|
||||
let acct = accounts[rng.next(accounts.len() as u64) as usize];
|
||||
ledger.add_line(id, acct, Side::Debit, usd(part)).unwrap();
|
||||
// As replay posts them: random lines land on receivables and
|
||||
// payables by hand, as books an earlier version wrote can hold them
|
||||
// (the control guard, rules.md B-38, refuses them as new work).
|
||||
ledger_core::parties::replaying(|| {
|
||||
for i in 0..300u32 {
|
||||
let total = rng.next(100_000) + 100;
|
||||
let nd = (rng.next(3) + 1) as usize;
|
||||
let nc = (rng.next(3) + 1) as usize;
|
||||
let id = ledger.create_entry(date(21), &format!("random {i}"));
|
||||
for part in split_total(&mut rng, total, nd) {
|
||||
let acct = accounts[rng.next(accounts.len() as u64) as usize];
|
||||
ledger.add_line(id, acct, Side::Debit, usd(part)).unwrap();
|
||||
}
|
||||
for part in split_total(&mut rng, total, nc) {
|
||||
let acct = accounts[rng.next(accounts.len() as u64) as usize];
|
||||
ledger.add_line(id, acct, Side::Credit, usd(part)).unwrap();
|
||||
}
|
||||
ledger.post_entry(id).unwrap();
|
||||
}
|
||||
for part in split_total(&mut rng, total, nc) {
|
||||
let acct = accounts[rng.next(accounts.len() as u64) as usize];
|
||||
ledger.add_line(id, acct, Side::Credit, usd(part)).unwrap();
|
||||
}
|
||||
ledger.post_entry(id).unwrap();
|
||||
}
|
||||
});
|
||||
|
||||
// Every invariant still holds after 300 random balanced entries.
|
||||
let tb = trial_balance(&ledger);
|
||||
@@ -1484,27 +1495,61 @@ fn a_period_ending_inside_a_closed_period_cannot_close() {
|
||||
}
|
||||
|
||||
/// Replay (for journaling stores) rebuilds invoice and bill records
|
||||
/// exactly: ids follow the allocator, payments accumulate, vendors tag
|
||||
/// the entries. A record replayed out of order is refused.
|
||||
/// exactly: ids follow the allocator, each record tags its entry's control
|
||||
/// line and each payment its entry's (rules.md B-38), vendors tag the
|
||||
/// entries. A record replayed out of order is refused.
|
||||
#[test]
|
||||
fn replayed_documents_and_payments_rebuild_the_records() {
|
||||
use ledger_core::DocumentStatus;
|
||||
let mut l = books_with("2000", "Accounts Payable", AccountType::Liability, false);
|
||||
let cash = l.chart().find_by_code("1000").unwrap().id;
|
||||
let ap = l.chart().find_by_code("2000").unwrap().id;
|
||||
let ar = l
|
||||
.add_account(
|
||||
"1200",
|
||||
"Accounts Receivable",
|
||||
AccountType::Asset,
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
let revenue = l
|
||||
.add_account("4000", "Revenue", AccountType::Revenue, None, false)
|
||||
.unwrap();
|
||||
let expense = l
|
||||
.add_account(
|
||||
"6999",
|
||||
"General Expenses",
|
||||
AccountType::Expense,
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
// An entry as replay rebuilds it from its own events.
|
||||
let entry = |l: &mut Ledger, dr, cr, n: u64| {
|
||||
let e = l.create_entry(date(5), "replayed");
|
||||
l.replay_add_line(e, dr, Side::Debit, usd(n)).unwrap();
|
||||
l.replay_add_line(e, cr, Side::Credit, usd(n)).unwrap();
|
||||
l.replay_post_entry(e).unwrap();
|
||||
e
|
||||
};
|
||||
let c = l.add_customer("Acme").unwrap();
|
||||
let v = l.add_vendor("Vend").unwrap();
|
||||
|
||||
let inv = l.next_invoice_id();
|
||||
let e = entry(&mut l, ar, revenue, 100);
|
||||
assert_eq!(
|
||||
l.replay_invoice(inv + 1, c, date(5), date(30), doc(100), 10),
|
||||
l.replay_invoice(inv + 1, c, date(5), date(30), doc(100), e),
|
||||
Err(LedgerError::ReplayIdMismatch(inv + 1, inv))
|
||||
);
|
||||
l.replay_invoice(inv, c, date(5), date(30), doc(100), 10)
|
||||
l.replay_invoice(inv, c, date(5), date(30), doc(100), e)
|
||||
.unwrap();
|
||||
// Each later record replays at the id the allocator now predicts.
|
||||
let mut ids = vec![inv];
|
||||
for entry in [13, 14] {
|
||||
for _ in 0..2 {
|
||||
let next = l.next_invoice_id();
|
||||
l.replay_invoice(next, c, date(5), date(30), doc(1), entry)
|
||||
let e = entry(&mut l, ar, revenue, 1);
|
||||
l.replay_invoice(next, c, date(5), date(30), doc(1), e)
|
||||
.unwrap();
|
||||
ids.push(next);
|
||||
}
|
||||
@@ -1512,38 +1557,52 @@ fn replayed_documents_and_payments_rebuild_the_records() {
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), 3);
|
||||
assert!(ids.iter().all(|&i| l.get_invoice(i).is_some()));
|
||||
l.replay_invoice_payment(inv, Decimal::from(30), 11)
|
||||
.unwrap();
|
||||
l.replay_invoice_payment(inv, Decimal::from(20), 12)
|
||||
.unwrap();
|
||||
for n in [30, 20] {
|
||||
let p = entry(&mut l, cash, ar, n);
|
||||
l.replay_invoice_payment(inv, Decimal::from(n), p).unwrap();
|
||||
assert_eq!(
|
||||
l.line_doc(p, 1).map(|t| t.doc),
|
||||
Some(ledger_core::DocRef::Invoice(inv))
|
||||
);
|
||||
}
|
||||
let i = l.get_invoice(inv).unwrap();
|
||||
assert_eq!(i.amount_paid, Decimal::from(50));
|
||||
assert_eq!(i.balance().unwrap(), Decimal::from(50));
|
||||
assert_eq!(i.status, DocumentStatus::Partial);
|
||||
let st = l.invoice_state(inv, date(31)).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
(st.paid, st.outstanding),
|
||||
(Decimal::from(50), Decimal::from(50))
|
||||
);
|
||||
|
||||
let bill = l.next_bill_id();
|
||||
let e = entry(&mut l, expense, ap, 100);
|
||||
assert_eq!(
|
||||
l.replay_bill(bill + 1, v, date(5), date(30), doc(100), 20),
|
||||
l.replay_bill(bill + 1, v, date(5), date(30), doc(100), e),
|
||||
Err(LedgerError::ReplayIdMismatch(bill + 1, bill))
|
||||
);
|
||||
assert_eq!(l.entry_vendor(20), None);
|
||||
l.replay_bill(bill, v, date(5), date(30), doc(100), 20)
|
||||
assert_eq!(l.entry_vendor(e), None);
|
||||
l.replay_bill(bill, v, date(5), date(30), doc(100), e)
|
||||
.unwrap();
|
||||
assert_eq!(l.entry_vendor(20), Some(v));
|
||||
assert_eq!(l.entry_vendor(e), Some(v));
|
||||
let mut ids = vec![bill];
|
||||
for entry in [23, 24] {
|
||||
for _ in 0..2 {
|
||||
let next = l.next_bill_id();
|
||||
l.replay_bill(next, v, date(5), date(30), doc(1), entry)
|
||||
let e = entry(&mut l, expense, ap, 1);
|
||||
l.replay_bill(next, v, date(5), date(30), doc(1), e)
|
||||
.unwrap();
|
||||
ids.push(next);
|
||||
}
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), 3);
|
||||
l.replay_bill_payment(bill, Decimal::from(30), 21).unwrap();
|
||||
l.replay_bill_payment(bill, Decimal::from(70), 22).unwrap();
|
||||
let mut last = 0;
|
||||
for n in [30, 70] {
|
||||
last = entry(&mut l, ap, cash, n);
|
||||
l.replay_bill_payment(bill, Decimal::from(n), last).unwrap();
|
||||
}
|
||||
let b = l.get_bill(bill).unwrap();
|
||||
assert_eq!(b.amount_paid, Decimal::from(100));
|
||||
assert_eq!(b.status, DocumentStatus::Paid);
|
||||
assert_eq!(l.entry_vendor(22), Some(v));
|
||||
assert_eq!(l.entry_vendor(last), Some(v));
|
||||
}
|
||||
@@ -360,7 +360,10 @@ impl Model {
|
||||
// Commands
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CODES: [&str; 7] = ["1000", "2000", "3000", "3999", "4000", "6000", "1900"];
|
||||
// No 1200 or 2000: a line by hand on a receivables or payables account is
|
||||
// refused (the control guard, rules.md B-38), which this model leaves to
|
||||
// spec_arap.rs.
|
||||
const CODES: [&str; 7] = ["1000", "2100", "3000", "3999", "4000", "6000", "1900"];
|
||||
/// New names: a free one, its own in other capitals and spacing, a
|
||||
/// sibling's (the accounts are named for their codes), blank, nine
|
||||
/// digits, the engine's own name for retained earnings.
|
||||
|
||||
@@ -173,9 +173,10 @@ fn net_for(lines: &[(AccountId, Side, Decimal)], account: AccountId) -> Decimal
|
||||
// ------------------------------------------------- Invoice / Bill methods
|
||||
|
||||
/// Oracle: Invoice doc: total() is "Total of all lines", balance() is
|
||||
/// "Amount still owed" = total - amount_paid.
|
||||
/// "Amount still owed" (its `owed`, derived by the ledger beside
|
||||
/// amount_paid: total - amount_paid while it stands).
|
||||
#[test]
|
||||
fn invoice_total_is_sum_of_lines_and_balance_is_total_minus_paid() {
|
||||
fn invoice_total_is_sum_of_lines_and_balance_is_what_is_owed() {
|
||||
let inv = Invoice {
|
||||
id: 7,
|
||||
customer_id: 1,
|
||||
@@ -183,6 +184,7 @@ fn invoice_total_is_sum_of_lines_and_balance_is_total_minus_paid() {
|
||||
due_date: d(2026, 3, 31),
|
||||
lines: vec![line("a", "100.10"), line("b", "0.05"), line("c", "49.85")],
|
||||
amount_paid: dec("60.00"),
|
||||
owed: dec("90.00"),
|
||||
status: DocumentStatus::Partial,
|
||||
entry_id: 1,
|
||||
};
|
||||
@@ -190,9 +192,9 @@ fn invoice_total_is_sum_of_lines_and_balance_is_total_minus_paid() {
|
||||
assert_eq!(inv.balance().unwrap(), dec("90.00"));
|
||||
}
|
||||
|
||||
/// Oracle: Bill doc: total() is the sum of lines, balance() total - paid.
|
||||
/// Oracle: Bill doc: total() is the sum of lines, balance() what is owed.
|
||||
#[test]
|
||||
fn bill_total_is_sum_of_lines_and_balance_is_total_minus_paid() {
|
||||
fn bill_total_is_sum_of_lines_and_balance_is_what_is_owed() {
|
||||
let bill = Bill {
|
||||
id: 3,
|
||||
vendor_id: 2,
|
||||
@@ -200,6 +202,7 @@ fn bill_total_is_sum_of_lines_and_balance_is_total_minus_paid() {
|
||||
due_date: d(2026, 3, 1),
|
||||
lines: vec![line("x", "19.99"), line("y", "0.01")],
|
||||
amount_paid: dec("20.00"),
|
||||
owed: Decimal::ZERO,
|
||||
status: DocumentStatus::Paid,
|
||||
entry_id: 9,
|
||||
};
|
||||
|
||||
@@ -605,9 +605,10 @@ fn replayed_bases_and_shares_past_the_limit_are_accepted() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A replayed payment is as journaled: no bound but exact arithmetic (a
|
||||
/// paid amount past it is refused, never wrapped). The command's bound is
|
||||
/// the balance (Overpayment).
|
||||
/// A replayed payment is as journaled: no bound (rules.md B-28), and no
|
||||
/// refusal: it tags the line of its entry that carries it, or (an entry
|
||||
/// it doesn't match) nothing. The command's bound is what the invoice
|
||||
/// owes (Overpayment).
|
||||
#[test]
|
||||
fn replayed_payments_are_as_journaled() {
|
||||
let mut b = books();
|
||||
@@ -630,24 +631,19 @@ fn replayed_payments_are_as_journaled() {
|
||||
.receive_payment(invoice, d(2026, 1, 15), too_big(), b.cash),
|
||||
Err(LedgerError::Overpayment(..))
|
||||
));
|
||||
let before = b.ledger.clone();
|
||||
b.ledger
|
||||
.replay_invoice_payment(invoice, too_big(), 98)
|
||||
.unwrap();
|
||||
b.ledger
|
||||
.replay_invoice_payment(invoice, Decimal::MAX - too_big(), 99)
|
||||
.unwrap();
|
||||
// No entry 98 or 99 carries them: nothing is tagged, nothing paid.
|
||||
let doc = ledger_core::DocRef::Invoice(invoice);
|
||||
assert_eq!(b.ledger.doc_lines(doc), before.doc_lines(doc));
|
||||
assert_eq!(
|
||||
b.ledger.get_invoice(invoice).unwrap().amount_paid,
|
||||
Decimal::MAX
|
||||
);
|
||||
assert!(matches!(
|
||||
b.ledger.replay_invoice_payment(invoice, Decimal::ONE, 100),
|
||||
Err(LedgerError::TooLargeToCompute(_))
|
||||
));
|
||||
// Refused before anything changed.
|
||||
assert_eq!(
|
||||
b.ledger.get_invoice(invoice).unwrap().amount_paid,
|
||||
Decimal::MAX
|
||||
b.ledger.get_invoice(invoice).unwrap().balance(),
|
||||
Ok(Decimal::new(10000, 2))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -50,15 +50,21 @@ impl Books {
|
||||
}
|
||||
|
||||
fn post(&mut self, date: NaiveDate, desc: &str, lines: &[(&str, Side, &str)]) -> EntryId {
|
||||
let e = self.l.create_entry(date, desc);
|
||||
for &(code, side, amount) in lines {
|
||||
let a = self.id(code);
|
||||
self.l
|
||||
.add_line(e, a, side, Money::new(x(amount), Currency::USD))
|
||||
.unwrap();
|
||||
}
|
||||
self.l.post_entry(e).unwrap();
|
||||
e
|
||||
// As replay posts it: these books hold hand lines on receivables
|
||||
// or payables (1200, 2000), which books an earlier version wrote
|
||||
// still hold and every report must read; the control guard
|
||||
// (rules.md B-38) refuses them as new work.
|
||||
ledger_core::parties::replaying(|| {
|
||||
let e = self.l.create_entry(date, desc);
|
||||
for &(code, side, amount) in lines {
|
||||
let a = self.id(code);
|
||||
self.l
|
||||
.add_line(e, a, side, Money::new(x(amount), Currency::USD))
|
||||
.unwrap();
|
||||
}
|
||||
self.l.post_entry(e).unwrap();
|
||||
e
|
||||
})
|
||||
}
|
||||
|
||||
fn reverse(&mut self, e: EntryId, date: NaiveDate) -> EntryId {
|
||||
|
||||
@@ -201,10 +201,15 @@ fn reversing_a_tagged_document_takes_its_projects_to_zero() {
|
||||
(t.revenue, t.expenses)
|
||||
};
|
||||
assert_eq!(to_date(&b.l, z), (cents(300_000), cents(120_000)));
|
||||
b.l.receive_payment(inv, d(2026, 3, 20), cents(100_000), b.cash)
|
||||
.unwrap();
|
||||
let pay =
|
||||
b.l.receive_payment(inv, d(2026, 3, 20), cents(100_000), b.cash)
|
||||
.unwrap();
|
||||
assert_eq!(to_date(&b.l, z), (cents(300_000), cents(120_000)));
|
||||
assert_eq!(to_date(&b.l, h), (cents(20_000), Decimal::ZERO));
|
||||
// The payment first: a void waits on the payments that stand (B-38
|
||||
// scenario 3); its reversal moves no project figure either.
|
||||
b.l.reverse_entry(pay, d(2026, 3, 30), "Bounced").unwrap();
|
||||
assert_eq!(to_date(&b.l, z), (cents(300_000), cents(120_000)));
|
||||
for e in [
|
||||
b.l.get_invoice(inv).unwrap().entry_id,
|
||||
b.l.get_bill(bill).unwrap().entry_id,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2468,7 +2468,7 @@ proptest! {
|
||||
let mut l = Ledger::new(Currency::USD);
|
||||
let ids: Vec<_> = [
|
||||
("1000", AccountType::Asset),
|
||||
("2000", AccountType::Liability),
|
||||
("2100", AccountType::Liability),
|
||||
("4000", AccountType::Revenue),
|
||||
("6100", AccountType::Expense),
|
||||
]
|
||||
@@ -2564,7 +2564,7 @@ proptest! {
|
||||
let mut l = Ledger::new(Currency::USD);
|
||||
let ids: Vec<_> = [
|
||||
("1000", AccountType::Asset),
|
||||
("2000", AccountType::Liability),
|
||||
("2100", AccountType::Liability),
|
||||
("4000", AccountType::Revenue),
|
||||
("6100", AccountType::Expense),
|
||||
]
|
||||
|
||||
@@ -28,7 +28,7 @@ fn usd(c: i64) -> Money {
|
||||
Money::new(cents(c), Currency::USD)
|
||||
}
|
||||
|
||||
/// Cash 1000, equipment 1200, revenue 4000, contractors 6000, rent 6200.
|
||||
/// Cash 1000, equipment 1500, revenue 4000, contractors 6000, rent 6200.
|
||||
struct Books {
|
||||
l: Ledger,
|
||||
cash: u64,
|
||||
@@ -42,7 +42,7 @@ fn books() -> Books {
|
||||
let mut l = Ledger::new(Currency::USD);
|
||||
let mut add = |code: &str, t| l.add_account(code, code, t, None, false).unwrap();
|
||||
let cash = add("1000", AccountType::Asset);
|
||||
let equipment = add("1200", AccountType::Asset);
|
||||
let equipment = add("1500", AccountType::Asset);
|
||||
let revenue = add("4000", AccountType::Revenue);
|
||||
let contractors = add("6000", AccountType::Expense);
|
||||
let rent = add("6200", AccountType::Expense);
|
||||
|
||||
@@ -283,22 +283,43 @@ fn a_draft_of_decimals_largest_is_refused_where_summed() {
|
||||
assert!(why.contains("too large to compute"), "{why}");
|
||||
}
|
||||
|
||||
/// A document is restored as journaled: its total and balance are exact,
|
||||
/// or refused past exact arithmetic; aging sums by party, checked.
|
||||
/// A document is restored as journaled: its total is exact, or refused
|
||||
/// past exact arithmetic; what it owes is what the ledger lines tagged
|
||||
/// with it carry (rules.md B-38), exact, whatever the journal held (paid
|
||||
/// above its total included); aging refuses a document whose total it
|
||||
/// can't compute.
|
||||
#[test]
|
||||
fn documents_and_aging_are_exact_or_refused() {
|
||||
let mut l = Ledger::new(Currency::USD);
|
||||
let ar = l
|
||||
.add_account("1200", "Receivables", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let revenue = l
|
||||
.add_account("4000", "Revenue", AccountType::Revenue, None, false)
|
||||
.unwrap();
|
||||
let cash = l
|
||||
.add_account("1000", "Cash", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let customer = l.add_customer("Client").unwrap();
|
||||
let line = |a: Decimal| DocumentLine {
|
||||
description: "x".into(),
|
||||
amount: a,
|
||||
class_id: None,
|
||||
};
|
||||
// An entry as replay rebuilds it: Dr `dr` / Cr `cr` for `a`.
|
||||
let replayed = |l: &mut Ledger, dr, cr, a: Decimal| {
|
||||
let e = l.create_entry(d(2026, 3, 1), "replayed");
|
||||
l.replay_add_line(e, dr, Side::Debit, usd(a)).unwrap();
|
||||
l.replay_add_line(e, cr, Side::Credit, usd(a)).unwrap();
|
||||
l.replay_post_entry(e).unwrap();
|
||||
e
|
||||
};
|
||||
let fine = vec![
|
||||
line(Decimal::new(1, 11)),
|
||||
line("9.99999999999".parse().unwrap()),
|
||||
];
|
||||
l.replay_invoice(1, customer, d(2026, 3, 1), d(2026, 3, 31), fine, 1)
|
||||
let e1 = replayed(&mut l, ar, revenue, Decimal::TEN);
|
||||
l.replay_invoice(1, customer, d(2026, 3, 1), d(2026, 3, 31), fine, e1)
|
||||
.unwrap();
|
||||
let inv = l.get_invoice(1).unwrap();
|
||||
assert_eq!(inv.total(), Ok(Decimal::TEN));
|
||||
@@ -307,8 +328,9 @@ fn documents_and_aging_are_exact_or_refused() {
|
||||
// 62 days past due on June 1st: 61-90.
|
||||
assert_eq!(rows[0].days_90, Decimal::TEN);
|
||||
assert_eq!(rows[0].total(), Ok(Decimal::TEN));
|
||||
// Two documents of half Decimal's largest each: each is exact, the
|
||||
// party's aging bucket is not.
|
||||
// Two documents of half Decimal's largest each, their totals exact; no
|
||||
// line carries them (no entry could), so they owe nothing and age
|
||||
// nowhere.
|
||||
let half = Decimal::MAX / Decimal::TWO;
|
||||
for id in [2, 3] {
|
||||
l.replay_invoice(
|
||||
@@ -317,40 +339,44 @@ fn documents_and_aging_are_exact_or_refused() {
|
||||
d(2026, 3, 1),
|
||||
d(2026, 3, 31),
|
||||
vec![line(half)],
|
||||
id,
|
||||
100 + id,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(l.get_invoice(id).unwrap().total(), Ok(half));
|
||||
let st = l.invoice_state(id, d(2026, 6, 1)).unwrap().unwrap();
|
||||
assert_eq!(st.outstanding, Decimal::ZERO);
|
||||
}
|
||||
assert!(too_large(l.ar_aging(d(2026, 6, 1))));
|
||||
assert_eq!(
|
||||
l.ar_aging(d(2026, 6, 1)).unwrap()[0].total(),
|
||||
Ok(Decimal::TEN)
|
||||
);
|
||||
// Paid more than its total, as journaled: a negative balance, exact.
|
||||
l.replay_invoice_payment(1, Decimal::from(11), 9).unwrap();
|
||||
let p = replayed(&mut l, cash, ar, Decimal::from(11));
|
||||
l.replay_invoice_payment(1, Decimal::from(11), p).unwrap();
|
||||
assert_eq!(l.get_invoice(1).unwrap().balance(), Ok(-Decimal::ONE));
|
||||
// A total of lines that overflow, and its balance.
|
||||
let st = l.invoice_state(1, d(2026, 6, 1)).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
(st.paid, st.outstanding),
|
||||
(Decimal::from(11), -Decimal::ONE)
|
||||
);
|
||||
// A payment event naming an amount no line of its entry carries tags
|
||||
// nothing, and is refused nothing (B-28).
|
||||
l.replay_invoice_payment(1, -Decimal::ONE, p).unwrap();
|
||||
assert_eq!(l.get_invoice(1).unwrap().balance(), Ok(-Decimal::ONE));
|
||||
// A total of lines that overflow, and its balance; aging refuses it.
|
||||
l.replay_invoice(
|
||||
4,
|
||||
customer,
|
||||
d(2026, 3, 1),
|
||||
d(2026, 3, 31),
|
||||
vec![line(Decimal::MAX), line(Decimal::MAX)],
|
||||
4,
|
||||
104,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(too_large(l.get_invoice(4).unwrap().total()));
|
||||
assert!(too_large(l.get_invoice(4).unwrap().balance()));
|
||||
// A balance past exact arithmetic: a total of Decimal's largest paid
|
||||
// a negative amount.
|
||||
l.replay_invoice(
|
||||
5,
|
||||
customer,
|
||||
d(2026, 3, 1),
|
||||
d(2026, 3, 31),
|
||||
vec![line(Decimal::MAX)],
|
||||
5,
|
||||
)
|
||||
.unwrap();
|
||||
l.replay_invoice_payment(5, -Decimal::ONE, 10).unwrap();
|
||||
assert!(too_large(l.get_invoice(5).unwrap().balance()));
|
||||
assert!(too_large(l.ar_aging(d(2026, 6, 1))));
|
||||
assert!(too_large(l.invoice_state(4, d(2026, 6, 1))));
|
||||
// Bills alike.
|
||||
let vendor = l.add_vendor("Supplier").unwrap();
|
||||
l.replay_bill(
|
||||
@@ -359,7 +385,7 @@ fn documents_and_aging_are_exact_or_refused() {
|
||||
d(2026, 3, 1),
|
||||
d(2026, 3, 31),
|
||||
vec![line(Decimal::MAX), line(Decimal::ONE)],
|
||||
6,
|
||||
106,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(too_large(l.get_bill(1).unwrap().total()));
|
||||
|
||||
@@ -40,12 +40,18 @@ fn usd(cents: i64) -> Money {
|
||||
}
|
||||
|
||||
fn post(l: &mut Ledger, date: NaiveDate, desc: &str, lines: &[(AccountId, Side, i64)]) -> EntryId {
|
||||
let e = l.create_entry(date, desc);
|
||||
for &(a, s, cents) in lines {
|
||||
l.add_line(e, a, s, usd(cents)).unwrap();
|
||||
}
|
||||
l.post_entry(e).unwrap();
|
||||
e
|
||||
// As replay posts it: these books hold hand lines on receivables or
|
||||
// payables (1200, 2000), which books an earlier version wrote still
|
||||
// hold and every report must read; the control guard (rules.md B-38)
|
||||
// refuses them as new work.
|
||||
ledger_core::parties::replaying(|| {
|
||||
let e = l.create_entry(date, desc);
|
||||
for &(a, s, cents) in lines {
|
||||
l.add_line(e, a, s, usd(cents)).unwrap();
|
||||
}
|
||||
l.post_entry(e).unwrap();
|
||||
e
|
||||
})
|
||||
}
|
||||
|
||||
fn draft(l: &mut Ledger, date: NaiveDate, lines: &[(AccountId, Side, i64)]) -> EntryId {
|
||||
@@ -1784,22 +1790,28 @@ fn build_ordered(gens: &[Gen], scale: i64, order: &[usize], tag: bool) -> Books
|
||||
let class_a = l.add_class("Alpha").unwrap();
|
||||
let class_b = l.add_class("Beta").unwrap();
|
||||
let mut entries = Vec::new();
|
||||
for g in gens {
|
||||
let e = l.create_entry(g.date(), "gen");
|
||||
for (n, (i, side, cents)) in g.legs(scale).into_iter().enumerate() {
|
||||
l.add_line(e, ids[i], side, usd(cents)).unwrap();
|
||||
if tag {
|
||||
let k = match g.classes[n] {
|
||||
1 => Some(class_a),
|
||||
2 => Some(class_b),
|
||||
_ => None,
|
||||
};
|
||||
l.set_line_class(e, n, k).unwrap();
|
||||
// As replay posts it: these books hold hand lines on receivables or
|
||||
// payables (1200, 2000), which books an earlier version wrote still
|
||||
// hold and every report must read; the control guard (rules.md B-38)
|
||||
// refuses them as new work.
|
||||
ledger_core::parties::replaying(|| {
|
||||
for g in gens {
|
||||
let e = l.create_entry(g.date(), "gen");
|
||||
for (n, (i, side, cents)) in g.legs(scale).into_iter().enumerate() {
|
||||
l.add_line(e, ids[i], side, usd(cents)).unwrap();
|
||||
if tag {
|
||||
let k = match g.classes[n] {
|
||||
1 => Some(class_a),
|
||||
2 => Some(class_b),
|
||||
_ => None,
|
||||
};
|
||||
l.set_line_class(e, n, k).unwrap();
|
||||
}
|
||||
}
|
||||
l.post_entry(e).unwrap();
|
||||
entries.push(e);
|
||||
}
|
||||
l.post_entry(e).unwrap();
|
||||
entries.push(e);
|
||||
}
|
||||
});
|
||||
Books {
|
||||
l,
|
||||
ids,
|
||||
@@ -2000,12 +2012,15 @@ proptest! {
|
||||
let mut b = build(&gens);
|
||||
let tb0 = tb_lines(&trial_balance_as_of(&b.l, day(as_of)));
|
||||
let pl0 = pnl_key(&profit_and_loss_for_period(&b.l, d(2026, 1, 1), day(as_of), None).unwrap());
|
||||
let e = b.l.create_entry(extra.date(), "extra");
|
||||
for (i, side, cents) in extra.legs(1) {
|
||||
b.l.add_line(e, b.ids[i], side, usd(cents)).unwrap();
|
||||
}
|
||||
b.l.post_entry(e).unwrap();
|
||||
b.l.reverse_entry(e, extra.date(), "undo").unwrap();
|
||||
// As replay posts it (hand lines on 1200 or 2000: see `post`).
|
||||
ledger_core::parties::replaying(|| {
|
||||
let e = b.l.create_entry(extra.date(), "extra");
|
||||
for (i, side, cents) in extra.legs(1) {
|
||||
b.l.add_line(e, b.ids[i], side, usd(cents)).unwrap();
|
||||
}
|
||||
b.l.post_entry(e).unwrap();
|
||||
b.l.reverse_entry(e, extra.date(), "undo").unwrap();
|
||||
});
|
||||
prop_assert_eq!(tb_lines(&trial_balance_as_of(&b.l, day(as_of))), tb0);
|
||||
let pl1 = profit_and_loss_for_period(&b.l, d(2026, 1, 1), day(as_of), None).unwrap();
|
||||
prop_assert_eq!(sl_nonzero(&pl1.revenue), pl0.0.into_iter().filter(|x| !x.1.is_zero()).collect::<Vec<_>>());
|
||||
@@ -2027,13 +2042,16 @@ proptest! {
|
||||
let gl = gl_key(&general_ledger(&b.l, s0, e0).unwrap());
|
||||
let cf = cf_key(&cash_flow(&b.l, &cfp).unwrap());
|
||||
let snap = snapshot(&b.l).unwrap();
|
||||
for g in &drafts {
|
||||
let id = b.l.create_entry(g.date(), "draft");
|
||||
for (n, (i, side, cents)) in g.legs(1).into_iter().enumerate() {
|
||||
if g.mode == 0 && n == 1 { continue; } // some drafts unbalanced
|
||||
b.l.add_line(id, b.ids[i], side, usd(cents)).unwrap();
|
||||
// As replay adds them (hand lines on 1200 or 2000: see `post`).
|
||||
ledger_core::parties::replaying(|| {
|
||||
for g in &drafts {
|
||||
let id = b.l.create_entry(g.date(), "draft");
|
||||
for (n, (i, side, cents)) in g.legs(1).into_iter().enumerate() {
|
||||
if g.mode == 0 && n == 1 { continue; } // some drafts unbalanced
|
||||
b.l.add_line(id, b.ids[i], side, usd(cents)).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
prop_assert_eq!(tb_lines(&trial_balance_as_of(&b.l, e0)), tb);
|
||||
prop_assert_eq!(pnl_key(&profit_and_loss_for_period(&b.l, s0, e0, None).unwrap()), pl);
|
||||
prop_assert_eq!(bs_key(&balance_sheet_as_of(&b.l, e0).unwrap()), bs);
|
||||
|
||||
@@ -99,14 +99,20 @@ fn bal(l: &Ledger, id: AccountId) -> Decimal {
|
||||
l.account_balance(id).expect("known account")
|
||||
}
|
||||
|
||||
/// Draft, add lines, post. Panics on any refusal (setup only).
|
||||
/// Draft, add lines, post. Panics on any refusal (setup only). Posted as
|
||||
/// replay posts it: these books hold hand lines on receivables or payables
|
||||
/// (moving a role's balance by hand, B-23's path before documents read
|
||||
/// their lines), which books an earlier version wrote still hold; the
|
||||
/// control guard (rules.md B-38) refuses them as new work.
|
||||
fn post(l: &mut Ledger, date: NaiveDate, lines: &[(AccountId, Side, &str)]) -> EntryId {
|
||||
let id = l.try_create_entry(date, "test entry").unwrap();
|
||||
for (a, s, amt) in lines {
|
||||
l.add_line(id, *a, *s, usd(amt)).unwrap();
|
||||
}
|
||||
l.post_entry(id).unwrap();
|
||||
id
|
||||
ledger_core::parties::replaying(|| {
|
||||
let id = l.try_create_entry(date, "test entry").unwrap();
|
||||
for (a, s, amt) in lines {
|
||||
l.add_line(id, *a, *s, usd(amt)).unwrap();
|
||||
}
|
||||
l.post_entry(id).unwrap();
|
||||
id
|
||||
})
|
||||
}
|
||||
|
||||
/// The (code, side, amount) lines of an entry, sorted.
|
||||
@@ -788,7 +794,7 @@ fn receivables_cannot_move_while_holding_a_balance_but_can_once_moved_out() {
|
||||
let old = acct(&l, "1200").expect("1200 created by the invoice");
|
||||
let new = add(&mut l, "1100", "Trade Receivables", AccountType::Asset);
|
||||
match refuses(&mut l, "receivables", Some(new)) {
|
||||
LedgerError::RoleHoldsBalance {
|
||||
LedgerError::DocumentRoleHoldsBalance {
|
||||
role,
|
||||
code,
|
||||
balance,
|
||||
@@ -798,15 +804,29 @@ fn receivables_cannot_move_while_holding_a_balance_but_can_once_moved_out() {
|
||||
assert_eq!(code, "1200");
|
||||
assert_eq!(balance, dec("120.00"));
|
||||
}
|
||||
other => panic!("expected RoleHoldsBalance, got {other:?}"),
|
||||
other => panic!("expected DocumentRoleHoldsBalance, got {other:?}"),
|
||||
}
|
||||
// Move the balance with an entry, then the role may move.
|
||||
// Moving the balance by hand is refused now (the control guard,
|
||||
// rules.md B-38): until a role's balance moves with its documents
|
||||
// (plan P4b S7), a receivables role holding a balance stays put.
|
||||
let e = l.try_create_entry(d(2026, 3, 2), "move").unwrap();
|
||||
assert!(matches!(
|
||||
l.add_line(e, old, Side::Credit, usd("120.00")),
|
||||
Err(LedgerError::UntaggedControlLine { .. })
|
||||
));
|
||||
// Books an earlier version wrote can hold such a move, and the
|
||||
// assignment after it (replayed: today 1100's hand line refuses it,
|
||||
// RoleAccountHasHandLines): then the documents follow the role.
|
||||
post(
|
||||
&mut l,
|
||||
d(2026, 3, 2),
|
||||
&[(new, Side::Debit, "120.00"), (old, Side::Credit, "120.00")],
|
||||
);
|
||||
l.assign_role("receivables", Some(new)).unwrap();
|
||||
assert!(matches!(
|
||||
refuses(&mut l, "receivables", Some(new)),
|
||||
LedgerError::RoleAccountHasHandLines { .. }
|
||||
));
|
||||
ledger_core::parties::replaying(|| l.assign_role("receivables", Some(new))).unwrap();
|
||||
assert_eq!(l.role_account(&RECEIVABLES), Some(new));
|
||||
// The open invoice is now controlled by 1100: its payment credits it.
|
||||
let p = l
|
||||
@@ -845,6 +865,21 @@ fn every_balance_sheet_role_holds_while_its_account_has_a_balance() {
|
||||
&format!("Target {i}"),
|
||||
c.account_type,
|
||||
);
|
||||
if c.key == RECEIVABLES.key || c.key == PAYABLES.key {
|
||||
// No document posted there: the balance is the chart's own,
|
||||
// so the role moves (B-38); it can't come back to an account
|
||||
// holding hand lines.
|
||||
l.assign_role(c.key, Some(target)).unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
refuses(&mut l, c.key, Some(*cur)),
|
||||
LedgerError::RoleAccountHasHandLines { .. }
|
||||
),
|
||||
"{}",
|
||||
c.key
|
||||
);
|
||||
continue;
|
||||
}
|
||||
assert!(
|
||||
matches!(
|
||||
refuses(&mut l, c.key, Some(target)),
|
||||
@@ -877,7 +912,7 @@ fn none_is_refused_while_the_assigned_balance_sheet_account_holds_a_balance() {
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
refuses(&mut l, "payables", None),
|
||||
LedgerError::RoleHoldsBalance { .. }
|
||||
LedgerError::DocumentRoleHoldsBalance { .. }
|
||||
));
|
||||
let _ = cash;
|
||||
}
|
||||
@@ -1121,7 +1156,7 @@ fn pool_books() -> (Ledger, Vec<AccountId>) {
|
||||
}
|
||||
|
||||
/// The reasons the spec gives to refuse an assignment, worked from the
|
||||
/// current books (assign_role SCENARIOS 1–5).
|
||||
/// current books (assign_role SCENARIOS 1–6).
|
||||
fn predicted_refusals(
|
||||
l: &Ledger,
|
||||
c: &ControlAccount,
|
||||
@@ -1142,10 +1177,27 @@ fn predicted_refusals(
|
||||
}
|
||||
let now = l.role_account(c);
|
||||
let next = target.map(|a| a.id);
|
||||
// SCENARIO 6: a document role never moves onto hand lines.
|
||||
let documents = c.key == RECEIVABLES.key || c.key == PAYABLES.key;
|
||||
if documents
|
||||
&& let Some(a) = target
|
||||
&& next != now
|
||||
&& l.posted_entries().any(|e| {
|
||||
e.lines()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.any(|(i, x)| x.account == a.id && l.line_doc(e.id(), i).is_none())
|
||||
})
|
||||
{
|
||||
why.push("handlines");
|
||||
}
|
||||
// SCENARIO 4: a document role's balance holds only on its control
|
||||
// account (assigned there, or holding its documents' lines).
|
||||
if balance_sheet(c)
|
||||
&& next != now
|
||||
&& let Some(cur) = now
|
||||
&& !bal(l, cur).is_zero()
|
||||
&& (!documents || l.control_role_of(cur).is_some_and(|r| r.key == c.key))
|
||||
{
|
||||
why.push("balance");
|
||||
}
|
||||
@@ -1156,7 +1208,10 @@ fn reason(e: &LedgerError) -> &'static str {
|
||||
match e {
|
||||
LedgerError::ControlAccountMismatch { .. } => "mismatch",
|
||||
LedgerError::RoleTaken { .. } => "taken",
|
||||
LedgerError::RoleHoldsBalance { .. } => "balance",
|
||||
LedgerError::RoleHoldsBalance { .. } | LedgerError::DocumentRoleHoldsBalance { .. } => {
|
||||
"balance"
|
||||
}
|
||||
LedgerError::RoleAccountHasHandLines { .. } => "handlines",
|
||||
_ => "other",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
//! | Jan 2 | owner contributes 10,000 | 1000 Cash | 3000 Capital |
|
||||
//! | Jan 15 | client pays 2,500 | 1000 Cash | 4000 Revenue |
|
||||
//! | Jan 20 | rent 800 | 6100 Rent | 1000 Cash |
|
||||
//! | Feb 3 | software 120 on the card | 6000 Software | 2000 Card |
|
||||
//! | Feb 3 | software 120 on the card | 6000 Software | 2050 Card |
|
||||
//! | Feb 10 | client pays 1,000 | 1000 Cash | 4000 Revenue |
|
||||
//! | Feb 25 | pay the card 120 | 2000 Card | 1000 Cash |
|
||||
//! | Feb 25 | pay the card 120 | 2050 Card | 1000 Cash |
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use ledger_core::reports::{
|
||||
@@ -57,7 +57,7 @@ fn books(close_january: bool) -> Books {
|
||||
.add_account("1000", "Cash", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let card = l
|
||||
.add_account("2000", "Card", AccountType::Liability, None, false)
|
||||
.add_account("2050", "Card", AccountType::Liability, None, false)
|
||||
.unwrap();
|
||||
let capital = l
|
||||
.add_account("3000", "Capital", AccountType::Equity, None, false)
|
||||
@@ -160,7 +160,7 @@ fn balance_sheet_is_as_of_the_date() {
|
||||
// Feb 15: cash 12,700; the card owes 120; earnings 1,700 + 880.
|
||||
let mid = balance_sheet_as_of(&b.ledger, d(2, 15)).unwrap();
|
||||
assert_eq!(mid.total_assets, dec(12_700));
|
||||
assert_eq!(mid.liabilities, vec![line("2000", "Card", 120)]);
|
||||
assert_eq!(mid.liabilities, vec![line("2050", "Card", 120)]);
|
||||
assert_eq!(mid.current_earnings, dec(2_580));
|
||||
assert_eq!(mid.total_liabilities + mid.total_equity, dec(12_700));
|
||||
|
||||
@@ -307,7 +307,7 @@ fn general_ledger_runs_balances_by_account() {
|
||||
let gl = general_ledger(&b.ledger, d(2, 1), d(2, 28)).unwrap();
|
||||
let codes: Vec<&str> = gl.accounts.iter().map(|a| a.code.as_str()).collect();
|
||||
// Every account with a beginning balance or February activity, by code.
|
||||
assert_eq!(codes, ["1000", "2000", "3000", "4000", "6000", "6100"]);
|
||||
assert_eq!(codes, ["1000", "2050", "3000", "4000", "6000", "6100"]);
|
||||
|
||||
let cash = &gl.accounts[0];
|
||||
assert_eq!(cash.beginning_balance, dec(11_700));
|
||||
@@ -320,7 +320,7 @@ fn general_ledger_runs_balances_by_account() {
|
||||
p,
|
||||
[
|
||||
(dec(1_000), dec(0), "4000 Revenue", dec(12_700)),
|
||||
(dec(0), dec(120), "2000 Card", dec(12_580)),
|
||||
(dec(0), dec(120), "2050 Card", dec(12_580)),
|
||||
]
|
||||
);
|
||||
assert_eq!(cash.ending_balance, dec(12_580));
|
||||
@@ -354,7 +354,7 @@ fn general_ledger_marks_compound_entries_as_split() {
|
||||
.add_account("1000", "Cash", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let card = l
|
||||
.add_account("2000", "Card", AccountType::Liability, None, false)
|
||||
.add_account("2050", "Card", AccountType::Liability, None, false)
|
||||
.unwrap();
|
||||
let soft = l
|
||||
.add_account("6000", "Software", AccountType::Expense, None, false)
|
||||
@@ -373,7 +373,7 @@ fn general_ledger_marks_compound_entries_as_split() {
|
||||
// The debit side has two other accounts; each credit has one.
|
||||
assert_eq!(split_of("6000"), ("-Split-".to_string(), e));
|
||||
assert_eq!(split_of("1000"), ("6000 Software".to_string(), e));
|
||||
assert_eq!(split_of("2000"), ("6000 Software".to_string(), e));
|
||||
assert_eq!(split_of("2050"), ("6000 Software".to_string(), e));
|
||||
}
|
||||
|
||||
/// Two members, 50/50: Alice and Bob. January: Alice puts in 600, Bob 400;
|
||||
@@ -1087,7 +1087,7 @@ fn cash_flow_labels_say_which_way_each_balance_moved() {
|
||||
.add_account("1100", "Receivable", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let ap = l
|
||||
.add_account("2000", "Payable", AccountType::Liability, None, false)
|
||||
.add_account("2010", "Payable", AccountType::Liability, None, false)
|
||||
.unwrap();
|
||||
let loan = l
|
||||
.add_account("2500", "Loan", AccountType::Liability, None, false)
|
||||
@@ -1144,7 +1144,7 @@ fn cash_flow_labels_say_which_way_each_balance_moved() {
|
||||
rec(&feb),
|
||||
[
|
||||
(s("Increase in 1100 Receivable"), dec(-100)),
|
||||
(s("Increase in 2000 Payable"), dec(50)),
|
||||
(s("Increase in 2010 Payable"), dec(50)),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -1167,7 +1167,7 @@ fn cash_flow_labels_say_which_way_each_balance_moved() {
|
||||
rec(&mar),
|
||||
[
|
||||
(s("Decrease in 1100 Receivable"), dec(100)),
|
||||
(s("Decrease in 2000 Payable"), dec(-50)),
|
||||
(s("Decrease in 2010 Payable"), dec(-50)),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
|
||||
Reference in new issue
Block a user