merge: every reversal is dated on or after its original (D-73; branch t3/reversal-dating-d73, bb5008ed; reviewed)
claims/ledger.md conflicted with the reduced B-9 section: the D-73 pick, Enforced and Checked lines sit above its product rules; the check's place corrected (after the schedule double-post check, not ahead of it) and the citation completed (BS-ledger-16, the Lean model since L-G1). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
e080f761a0
14 files changed
+279
-69
No files matched your search
@@ -1983,6 +1983,47 @@ fn inv4_post_and_reverse_preview_without_confirmed() {
|
||||
assert_eq!(tb["balanced"], true);
|
||||
}
|
||||
|
||||
/// D-73: a reversal is dated on or after its original, for every entry. The
|
||||
/// preview refuses as the post does, naming the dates, and neither journals
|
||||
/// anything; the same day is taken.
|
||||
#[test]
|
||||
fn a_reversal_dated_before_its_entry_is_refused_in_preview_and_post() {
|
||||
let dir = test_dir("rev-dated-before");
|
||||
let toml = books_toml(&dir, "0.00", "");
|
||||
let mut m = Mcp::start(&dir, &toml);
|
||||
m.accounts(BASE_CHART);
|
||||
let e = m.draft(
|
||||
"2026-05-10",
|
||||
"Rent",
|
||||
&[("6000", "debit", "500.00"), ("1000", "credit", "500.00")],
|
||||
);
|
||||
m.attach(Some(e), b"rent receipt");
|
||||
m.post(e).ok("post");
|
||||
let before = m.journal();
|
||||
for confirmed in [None, Some(false), Some(true)] {
|
||||
let mut args = json!({"entry_id": e, "date": "2026-05-09", "description": "early"});
|
||||
if let Some(c) = confirmed {
|
||||
args["confirmed"] = json!(c);
|
||||
}
|
||||
let why = m.refuse("books.reverse_entry", args);
|
||||
assert!(
|
||||
why.contains("can't be dated before it") && why.contains("2026-05-10"),
|
||||
"{why}"
|
||||
);
|
||||
}
|
||||
assert!(m.journal() == before, "a refused reversal wrote");
|
||||
let p = m.ok(
|
||||
"books.reverse_entry",
|
||||
json!({"entry_id": e, "date": "2026-05-10", "description": "same day"}),
|
||||
);
|
||||
assert_eq!(p["status"], "preview", "{p}");
|
||||
m.ok(
|
||||
"books.reverse_entry",
|
||||
json!({"entry_id": e, "date": "2026-05-10", "description": "same day",
|
||||
"confirmed": true}),
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------ invariant 5: receipt policy
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -833,17 +833,13 @@ pub enum LedgerError {
|
||||
#[error("{0}")]
|
||||
DocumentBounds(String),
|
||||
|
||||
/// A reversal of an entry an invoice or bill owns is dated before that
|
||||
/// entry (rules.md B-9, B-38): a correction comes after what it
|
||||
/// corrects.
|
||||
#[error(
|
||||
"entry {entry} belongs to {document} and is dated {original}: its reversal can't be dated before it, on {date}"
|
||||
)]
|
||||
DocumentReversalBeforeOriginal {
|
||||
/// A reversal is dated before the entry it reverses (rules.md B-9,
|
||||
/// D-73): a correction comes after what it corrects, for every kind of
|
||||
/// entry. New commands only; replay never refuses (B-28).
|
||||
#[error("entry {entry} is dated {original}: its reversal can't be dated before it, on {date}")]
|
||||
ReversalBeforeOriginal {
|
||||
/// The entry reversed.
|
||||
entry: u64,
|
||||
/// The document, e.g. "invoice 7".
|
||||
document: String,
|
||||
/// The entry's date.
|
||||
original: chrono::NaiveDate,
|
||||
/// The reversal's date.
|
||||
|
||||
@@ -2236,12 +2236,15 @@ impl Ledger {
|
||||
/// - NEVER recognize one month of a schedule twice
|
||||
/// BECAUSE a reversed month is due again and may have been run
|
||||
/// again (P3 depreciation review R3).
|
||||
/// 6. IF the entry carries a document's lines (an invoice's or a
|
||||
/// bill's own entry, a payment, or a reversal of one) and `date`
|
||||
/// is before the entry's own date:
|
||||
/// - SHOULD refuse (DocumentReversalBeforeOriginal)
|
||||
/// BECAUSE a correction comes after what it corrects (B-9; plan
|
||||
/// P4b.3, "Dating rules").
|
||||
/// 6. IF `date` is before the entry's own date (any kind of entry:
|
||||
/// plain, document, payment, schedule run):
|
||||
/// - SHOULD refuse (ReversalBeforeOriginal)
|
||||
/// - NEVER refuse the same day
|
||||
/// - NEVER refuse on replay
|
||||
/// BECAUSE a correction comes after what it corrects (B-9; owner
|
||||
/// decision D-73, 2026-11-08; plan P4b.3, "Dating rules"). Books
|
||||
/// written before D-73 may hold an earlier-dated reversal and
|
||||
/// reopen as they were (B-28).
|
||||
/// 7. IF reversing it would leave a document it carries owing less
|
||||
/// than nothing or more than its total at some date (a void
|
||||
/// under a payment that stands; re-instating a payment beside
|
||||
@@ -2285,13 +2288,21 @@ impl Ledger {
|
||||
)));
|
||||
}
|
||||
if !crate::parties::is_replaying() {
|
||||
if date < original.date() {
|
||||
return Err(LedgerError::ReversalBeforeOriginal {
|
||||
entry,
|
||||
original: original.date(),
|
||||
date,
|
||||
});
|
||||
}
|
||||
self.check_document_reversal(original, date)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`Self::check_reversal`] SCENARIOS 6 and 7: a reversal of an entry
|
||||
/// carrying documents' lines.
|
||||
/// [`Self::check_reversal`] SCENARIO 7: a reversal of an entry
|
||||
/// carrying documents' lines (the date floor, SCENARIO 6, is checked
|
||||
/// before this runs).
|
||||
fn check_document_reversal(
|
||||
&self,
|
||||
original: &JournalEntry,
|
||||
@@ -2308,16 +2319,8 @@ impl Ledger {
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(&(first, _)) = moves.first() else {
|
||||
if moves.is_empty() {
|
||||
return Ok(());
|
||||
};
|
||||
if date < original.date() {
|
||||
return Err(LedgerError::DocumentReversalBeforeOriginal {
|
||||
entry: original.id(),
|
||||
document: first.to_string(),
|
||||
original: original.date(),
|
||||
date,
|
||||
});
|
||||
}
|
||||
for (doc, by) in moves {
|
||||
self.check_item_bounds(doc, &[(date, by)])?;
|
||||
|
||||
@@ -133,7 +133,12 @@ pub(crate) fn refusal(e: &LedgerError) -> String {
|
||||
LedgerError::DuplicateAccountCode(_) => "code_taken",
|
||||
LedgerError::TaxCategoryRequired { .. } => "tax_category_required",
|
||||
LedgerError::DepreciationPastDisposal(_) => "depreciation_past_disposal",
|
||||
LedgerError::AssetEntryIrreversible(..) => "entry_irreversible",
|
||||
// A reversal dated before its original (D-73) is the examples'
|
||||
// "entry_irreversible" too: bookspec's depreciation example words
|
||||
// the refusal that way, whichever engine check makes it.
|
||||
LedgerError::AssetEntryIrreversible(..) | LedgerError::ReversalBeforeOriginal { .. } => {
|
||||
"entry_irreversible"
|
||||
}
|
||||
LedgerError::AssetAlreadyDisposed(_) => "already_disposed",
|
||||
LedgerError::InvalidDepreciationPeriod(_) => "invalid_depreciation_period",
|
||||
LedgerError::InvalidSchedule(_) => "invalid_schedule",
|
||||
|
||||
@@ -218,7 +218,9 @@ impl Model {
|
||||
return false;
|
||||
};
|
||||
let reversed_already = self.posted.iter().any(|e| e.reversal_of == Some(entry));
|
||||
if reversed_already || orig.closes || self.closed_on(date) {
|
||||
// D-73 (bookspec BS-ledger-5): a correction is dated on or after
|
||||
// what it corrects.
|
||||
if reversed_already || orig.closes || self.closed_on(date) || date < orig.date {
|
||||
return false;
|
||||
}
|
||||
let lines = orig
|
||||
|
||||
@@ -960,11 +960,19 @@ fn a_reinstated_run_counts_and_is_live() {
|
||||
}
|
||||
|
||||
/// A reversal dated before its run: between the two dates the books carry
|
||||
/// −100.00, as the trial balance does (review R2).
|
||||
/// −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.
|
||||
#[test]
|
||||
fn a_reversal_dated_before_its_run_matches_the_trial_balance() {
|
||||
let (mut l, a, id, e) = one_run();
|
||||
l.reverse_entry(e, date(2026, 1, 15), "early").unwrap();
|
||||
assert!(matches!(
|
||||
l.reverse_entry(e, date(2026, 1, 15), "early"),
|
||||
Err(LedgerError::ReversalBeforeOriginal { .. })
|
||||
));
|
||||
l.replay_reverse_entry(e, date(2026, 1, 15), "early")
|
||||
.unwrap();
|
||||
let on = date(2026, 1, 20);
|
||||
assert_eq!(l.accumulated_posted(id, on).unwrap(), d("-100.00"));
|
||||
let tb = ledger_core::trial_balance_as_of(&l, on);
|
||||
|
||||
@@ -510,11 +510,11 @@ fn reversal_before_original_refused_for_documents() {
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
b.l.reverse_entry(pay, d(2026, 1, 19), "early"),
|
||||
Err(LedgerError::DocumentReversalBeforeOriginal { .. })
|
||||
Err(LedgerError::ReversalBeforeOriginal { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
b.l.void_document(DocRef::Invoice(inv), d(2026, 1, 9), "early"),
|
||||
Err(LedgerError::DocumentReversalBeforeOriginal { .. })
|
||||
Err(LedgerError::ReversalBeforeOriginal { .. })
|
||||
));
|
||||
// The same day is fine.
|
||||
b.l.reverse_entry(pay, d(2026, 1, 20), "same day").unwrap();
|
||||
|
||||
@@ -1770,17 +1770,11 @@ impl Store {
|
||||
/// - SHOULD refuse, naming the room left
|
||||
/// - NEVER let accumulated depreciation pass the schedule, or cost
|
||||
/// less salvage.
|
||||
/// 5. IF it is a depreciation run or a schedule month's posting, or a
|
||||
/// reversal in the chain of one, and `date` is before the entry's
|
||||
/// own date:
|
||||
/// - SHOULD refuse
|
||||
/// - NEVER carry a correction at month ends the entry it corrects
|
||||
/// never reached (a run of March reversed on Jan 31 would leave
|
||||
/// January and February with negative depreciation, and a
|
||||
/// disposal in February clearing what they don't carry)
|
||||
/// BECAUSE a correction comes after what it corrects (B-9, Pacioli
|
||||
/// ch. 31: "after you have made this correction"). Commands only:
|
||||
/// a journal an earlier version wrote replays as it was (B-28).
|
||||
/// 5. (the date floor: a reversal dated before the entry it
|
||||
/// reverses is refused for every entry, by `Ledger::check_reversal`
|
||||
/// with `ReversalBeforeOriginal`, D-73; it was this store's check
|
||||
/// for runs and schedule months alone. A journal an earlier
|
||||
/// version wrote replays as it was, B-28.)
|
||||
/// 6. Otherwise: a run of an active asset is un-posted (its month is
|
||||
/// due again, caught up by the next run).
|
||||
/// ```
|
||||
@@ -1797,18 +1791,6 @@ impl Store {
|
||||
.copied()
|
||||
.unwrap_or(entry);
|
||||
let refuse = |why: String| Err(LedgerError::AssetEntryIrreversible(entry, why).into());
|
||||
// SCENARIO 5: the date of the entry reversed (it ends its chain).
|
||||
let dated = self
|
||||
.ledger
|
||||
.get_entry(entry)
|
||||
.map(ledger_core::JournalEntry::date);
|
||||
let before_it = dated.filter(|&d| date < d);
|
||||
if let (Some(on), Some((sid, month))) = (before_it, self.ledger.schedule_posting(top)) {
|
||||
return Err(LedgerError::InvalidSchedule(format!(
|
||||
"entry {entry} (schedule {sid}'s {month}) is dated {on}: a reversal of it can't be dated before it, on {date}"
|
||||
))
|
||||
.into());
|
||||
}
|
||||
let payloads = |t: &str| -> Result<Vec<Value>, StoreError> {
|
||||
let mut stmt = self
|
||||
.conn
|
||||
@@ -1835,11 +1817,6 @@ impl Store {
|
||||
}
|
||||
let asset_id = get_u64(&p, "asset_id")?;
|
||||
let period = get_str(&p, "period")?;
|
||||
if let Some(on) = before_it {
|
||||
return refuse(format!(
|
||||
"it is dated {on}, and a reversal of asset {asset_id}'s depreciation for {period} can't be dated before it, on {date}"
|
||||
));
|
||||
}
|
||||
if self
|
||||
.ledger
|
||||
.get_asset(asset_id)
|
||||
|
||||
@@ -884,6 +884,7 @@ fn a_run_reinstated_after_its_rerun_was_reversed_still_counts() {
|
||||
/// 1,535.71). So is a re-instatement dated before the reversal it reverses,
|
||||
/// and a schedule month's reversal dated before its posting. A reversal on
|
||||
/// the entry's own day is taken. Each refusal journals nothing.
|
||||
/// Since D-73 the refusal is the ledger's for every entry, `ReversalBeforeOriginal`.
|
||||
#[test]
|
||||
fn a_reversal_dated_before_the_entry_it_reverses_is_refused() {
|
||||
let (_dir, mut store) = open_store();
|
||||
@@ -901,10 +902,12 @@ fn a_reversal_dated_before_the_entry_it_reverses_is_refused() {
|
||||
for on in [date(2026, 2, 10), date(2026, 3, 30)] {
|
||||
match store.reverse_entry(mar, on, "backdated") {
|
||||
Err(ledger_store::StoreError::Ledger(
|
||||
ledger_core::LedgerError::AssetEntryIrreversible(e, why),
|
||||
ledger_core::LedgerError::ReversalBeforeOriginal {
|
||||
entry, original, ..
|
||||
},
|
||||
)) => {
|
||||
assert_eq!(e, mar);
|
||||
assert!(why.contains("can't be dated before it"), "{why}");
|
||||
assert_eq!(entry, mar);
|
||||
assert_eq!(original, date(2026, 3, 31));
|
||||
}
|
||||
other => panic!("{on}: {other:?}"),
|
||||
}
|
||||
@@ -917,7 +920,7 @@ fn a_reversal_dated_before_the_entry_it_reverses_is_refused() {
|
||||
assert!(matches!(
|
||||
store.reverse_entry(rev, date(2026, 3, 30), "it was right"),
|
||||
Err(ledger_store::StoreError::Ledger(
|
||||
ledger_core::LedgerError::AssetEntryIrreversible(..)
|
||||
ledger_core::LedgerError::ReversalBeforeOriginal { .. }
|
||||
))
|
||||
));
|
||||
assert_eq!(store.head(), head);
|
||||
@@ -951,7 +954,7 @@ fn a_reversal_dated_before_the_entry_it_reverses_is_refused() {
|
||||
assert!(matches!(
|
||||
store.reverse_entry(feb, date(2026, 1, 31), "backdated"),
|
||||
Err(ledger_store::StoreError::Ledger(
|
||||
ledger_core::LedgerError::InvalidSchedule(_)
|
||||
ledger_core::LedgerError::ReversalBeforeOriginal { .. }
|
||||
))
|
||||
));
|
||||
assert_eq!(store.head(), head);
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
//! A reversal is dated on or after the entry it reverses, for every kind of
|
||||
//! entry (D-73, 2026-11-08; rules.md B-9; bookspec BS-ledger-5): a
|
||||
//! correction comes after what it corrects. A journal an earlier version
|
||||
//! wrote may hold one dated before its original, and it opens as it was
|
||||
//! (B-28: bounds bind new commands, never replay).
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: no new reversal precedes its original; no old one stops a journal
|
||||
//! from opening, or moves a figure.
|
||||
//! SOURCE: docs/spec/rules.md B-9, B-28; plan/served.md D-73.
|
||||
//! ```
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use ledger_core::reports::trial_balance;
|
||||
use ledger_core::{AccountType, Currency, LedgerError, Money, Side};
|
||||
use ledger_store::{JournalWriter, Store, StoreError};
|
||||
use rust_decimal::Decimal;
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
|
||||
struct TestDir(PathBuf);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
type Target = std::path::Path;
|
||||
fn deref(&self) -> &std::path::Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
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-store-revdates-{name}-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
TestDir(dir)
|
||||
}
|
||||
|
||||
fn d(y: i32, m: u32, day: u32) -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(y, m, day).unwrap()
|
||||
}
|
||||
|
||||
fn usd(n: i64) -> Money {
|
||||
Money::new(Decimal::new(n, 2), Currency::USD)
|
||||
}
|
||||
|
||||
/// Books with one plain posted entry: rent paid in cash, 100.00, on
|
||||
/// 2026-03-10. Returns (dir, store, rent, cash, entry).
|
||||
fn books(name: &str) -> (TestDir, Store, u64, u64, u64) {
|
||||
let dir = test_dir(name);
|
||||
let mut s = Store::create(&dir, Currency::USD).unwrap();
|
||||
let rent = s
|
||||
.add_account("6000", "Rent", AccountType::Expense, None, false)
|
||||
.unwrap();
|
||||
let cash = s
|
||||
.add_account("1000", "Cash", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let e = s.create_entry(d(2026, 3, 10), "March rent").unwrap();
|
||||
s.add_line(e, rent, Side::Debit, usd(10_000)).unwrap();
|
||||
s.add_line(e, cash, Side::Credit, usd(10_000)).unwrap();
|
||||
s.post_entry(e).unwrap();
|
||||
(dir, s, rent, cash, e)
|
||||
}
|
||||
|
||||
/// A plain entry's reversal dated before it is refused, by the check the
|
||||
/// preview uses and by the command alike, and nothing is journaled; the
|
||||
/// same day and later are taken.
|
||||
#[test]
|
||||
fn a_plain_entrys_reversal_is_not_dated_before_it() {
|
||||
let (_dir, mut s, rent, cash, e) = books("plain");
|
||||
let head = s.head();
|
||||
let tb = trial_balance(s.ledger());
|
||||
let before = (tb.total_debits, tb.total_credits);
|
||||
for early in [d(2026, 3, 9), d(2026, 1, 1)] {
|
||||
assert!(matches!(
|
||||
s.check_reverse_entry(e, early),
|
||||
Err(StoreError::Ledger(LedgerError::ReversalBeforeOriginal { entry, original, date }))
|
||||
if entry == e && original == d(2026, 3, 10) && date == early
|
||||
));
|
||||
assert!(matches!(
|
||||
s.reverse_entry(e, early, "early"),
|
||||
Err(StoreError::Ledger(
|
||||
LedgerError::ReversalBeforeOriginal { .. }
|
||||
))
|
||||
));
|
||||
}
|
||||
assert_eq!(s.head(), head, "a refused reversal journals nothing");
|
||||
let tb = trial_balance(s.ledger());
|
||||
assert_eq!((tb.total_debits, tb.total_credits), before);
|
||||
assert_eq!(s.ledger().account_movement(rent), Decimal::new(10_000, 2));
|
||||
// The same day is fine, and the books net to nothing.
|
||||
s.check_reverse_entry(e, d(2026, 3, 10)).unwrap();
|
||||
let r = s.reverse_entry(e, d(2026, 3, 10), "same day").unwrap();
|
||||
assert_eq!(s.ledger().account_movement(rent), Decimal::ZERO);
|
||||
assert_eq!(s.ledger().account_movement(cash), Decimal::ZERO);
|
||||
// Reversing the reversal (re-instating) is a correction of it too: it
|
||||
// can't precede the reversal, and may follow it.
|
||||
assert!(matches!(
|
||||
s.reverse_entry(r, d(2026, 3, 9), "early"),
|
||||
Err(StoreError::Ledger(
|
||||
LedgerError::ReversalBeforeOriginal { .. }
|
||||
))
|
||||
));
|
||||
s.reverse_entry(r, d(2026, 3, 11), "later").unwrap();
|
||||
assert_eq!(s.ledger().account_movement(rent), Decimal::new(10_000, 2));
|
||||
}
|
||||
|
||||
/// A journal an earlier version wrote, holding a reversal dated before its
|
||||
/// original, opens exactly as it was: same figures, chain verified, in the
|
||||
/// writer and again after a snapshot-less reopen (B-28).
|
||||
#[test]
|
||||
fn a_journal_with_an_earlier_dated_reversal_opens_as_it_was() {
|
||||
let (dir, s, rent, cash, e) = books("replay");
|
||||
let next = s.ledger().next_entry_id();
|
||||
drop(s);
|
||||
// What the old behaviour journaled: the mirror of the entry, dated
|
||||
// 2026-03-01, nine days before it.
|
||||
let mut w = JournalWriter::open(&dir.join(ledger_store::JOURNAL_FILE)).unwrap();
|
||||
let line = |account: u64, side: &str| json!({"account": account, "side": side, "amount": "100.00", "currency": "USD"});
|
||||
w.append(
|
||||
"entry.reversed",
|
||||
json!({"id": next, "reverses": e, "date": "2026-03-01",
|
||||
"description": "backdated by an earlier version",
|
||||
"lines": [line(rent, "credit"), line(cash, "debit")]}),
|
||||
)
|
||||
.unwrap();
|
||||
drop(w);
|
||||
|
||||
let store = Store::open(&dir).unwrap();
|
||||
store.verify().unwrap();
|
||||
let l = store.ledger();
|
||||
let r = l.get_entry(next).unwrap();
|
||||
assert_eq!(r.date(), d(2026, 3, 1));
|
||||
assert_eq!(r.reversal_of(), Some(e));
|
||||
assert_eq!(l.account_movement(rent), Decimal::ZERO);
|
||||
assert_eq!(l.account_movement(cash), Decimal::ZERO);
|
||||
let tb = trial_balance(l);
|
||||
assert_eq!(tb.total_debits, tb.total_credits);
|
||||
// The old entry stands reversed, and the books still refuse a new
|
||||
// backdated reversal of anything.
|
||||
assert!(!l.in_effect(e));
|
||||
assert!(matches!(
|
||||
store.check_reverse_entry(next, d(2026, 2, 1)),
|
||||
Err(StoreError::Ledger(
|
||||
LedgerError::ReversalBeforeOriginal { .. }
|
||||
))
|
||||
));
|
||||
}
|
||||
Reference in new issue
Block a user