From d1fb512e4bf2bfa645a38ba53cb1538857397bbe Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Tue, 27 Oct 2026 07:19:42 -0600 Subject: [PATCH] feat(arap): record an invoice's sends as invoice.sent (P4b S5) The books never send invoices (A-4), but they must remember that one went out: who sent it, how, to whom, when, whether it was the original or a reminder, and the channel's own reference. That record is a fact of the document's life, not a figure: a send moves no money, so it is one journal line (`invoice.sent`) and no entry, and every derived figure (outstanding, aging, DocState) is exactly as it was. `Ledger::mark_sent` refuses a send on a void invoice (it should never have reached the customer), a send dated before the invoice, no recipients, and any recipient, reference or note that would put a full TIN or control characters into the journal. Open, partial, paid and written-off invoices can be sent (a copy for the customer's records, a reminder). The event is `documents_v2`'s (D-52): an older version refuses the type rather than dropping the record. Replay restores it and the projection keeps it in schema 16's `invoice_sends` table, so live, replay and the viewer agree. The new old-books fixture `p4_s5_before` was written by eeee9658 and opens to the same figures; a hand-written send in `books_written_under_older_rules_still_open` proves an older journal with the new line still opens. Tests: mark_sent_waits_for_documents_v2, sends_replay_and_project, a_send_changes_no_figure, mark_sent_on_void_refused, Op::MarkSent in status_is_a_function_of_journal_and_date, an_older_version_stops_at_invoice_sent. --- crates/ledger-core/src/arap.rs | 50 ++++ crates/ledger-core/src/error.rs | 11 + crates/ledger-core/src/ledger.rs | 102 +++++++ crates/ledger-store/src/format.rs | 1 + crates/ledger-store/src/meta.rs | 57 ++++ crates/ledger-store/src/schema.rs | 19 +- crates/ledger-store/src/store.rs | 55 ++++ crates/ledger-store/tests/arap_props.rs | 33 +++ crates/ledger-store/tests/arap_standing.rs | 191 ++++++++++++- .../fixtures/old-books-writer/Cargo.toml | 2 + .../old-books-writer/src/bin/s5_before.rs | 65 +++++ .../old-books/p4_s5_before/expected.json | 265 ++++++++++++++++++ .../old-books/p4_s5_before/journal.jsonl | 29 ++ crates/ledger-store/tests/format.rs | 83 +++++- crates/ledger-store/tests/store.rs | 17 ++ fuzz/fuzz_targets/fuzz_store_replay.rs | 4 +- 16 files changed, 979 insertions(+), 5 deletions(-) create mode 100644 crates/ledger-store/tests/fixtures/old-books-writer/src/bin/s5_before.rs create mode 100644 crates/ledger-store/tests/fixtures/old-books/p4_s5_before/expected.json create mode 100644 crates/ledger-store/tests/fixtures/old-books/p4_s5_before/journal.jsonl diff --git a/crates/ledger-core/src/arap.rs b/crates/ledger-core/src/arap.rs index cd8ebd5..18102c6 100644 --- a/crates/ledger-core/src/arap.rs +++ b/crates/ledger-core/src/arap.rs @@ -742,6 +742,36 @@ pub enum SentVia { Other(String), } +impl SentVia { + /// Its key as the journal, the tools and the viewer name it: `email`, + /// `mail`, `portal`, `hand`, or `other:NAME` for another channel, + /// named (plan P4b S5). + pub fn key(&self) -> String { + match self { + SentVia::Email => "email".to_string(), + SentVia::Mail => "mail".to_string(), + SentVia::Portal => "portal".to_string(), + SentVia::Hand => "hand".to_string(), + SentVia::Other(name) => format!("other:{name}"), + } + } + + /// [`Self::key`] the other way; `None` for a channel this version + /// doesn't know (a newer version's `sent_via`). + pub fn parse(key: &str) -> Option { + match key { + "email" => Some(SentVia::Email), + "mail" => Some(SentVia::Mail), + "portal" => Some(SentVia::Portal), + "hand" => Some(SentVia::Hand), + other => other + .strip_prefix("other:") + .filter(|name| !name.trim().is_empty()) + .map(|name| SentVia::Other(name.to_string())), + } + } +} + /// Whether a send was the original or a reminder (plan P4b S5). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -752,6 +782,26 @@ pub enum SendKind { Reminder, } +impl SendKind { + /// Its key as the journal, the tools and the viewer name it. + pub fn key(self) -> &'static str { + match self { + SendKind::Original => "original", + SendKind::Reminder => "reminder", + } + } + + /// [`Self::key`] the other way; `None` for a kind this version + /// doesn't know. + pub fn parse(key: &str) -> Option { + match key { + "original" => Some(SendKind::Original), + "reminder" => Some(SendKind::Reminder), + _ => None, + } + } +} + /// One recorded send of an invoice (plan P4b S5): who sent it, how, to /// whom, and the channel's own reference. A send changes no figure. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/ledger-core/src/error.rs b/crates/ledger-core/src/error.rs index 28212b3..55272b5 100644 --- a/crates/ledger-core/src/error.rs +++ b/crates/ledger-core/src/error.rs @@ -778,6 +778,17 @@ pub enum LedgerError { #[error("{0}")] InvalidVoid(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). + #[error("invoice {0} is void: a void invoice was never sent")] + DocumentVoid(u64), + + /// A send was refused: the message says why (no recipients, a date + /// before its invoice, a recipient or reference that breaks the + /// books' text rule). Plan P4b S5. + #[error("{0}")] + InvalidSend(String), + /// Invoice/bill due date is before its date. #[error("due date {0} is before document date")] DueBeforeDate(String), diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index a24a24c..1f1343c 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -5724,6 +5724,108 @@ impl Ledger { Ok(()) } + /// Record that an invoice went out (plan P4b S5): who sent it, how, to + /// whom, when, whether it was the original or a reminder, and the + /// channel's own reference (a message id). The books never send + /// anything themselves (A-4: "Wanderbooks just does books"). + /// + /// ```text + /// GOAL: record a send as a fact of the document's life, without + /// touching a figure: a send moves no money. + /// SOURCE: docs/spec/rules.md B-38 (a document keeps no figure of its + /// own), B-27 (the invoice.sent line, feature documents_v2); + /// plan P4b S5, A-4 (the books record sends; they never send). + /// INVARIANTS: + /// 1. The invoice MUST exist, and a send MUST NOT be dated before it. + /// 2. A void invoice MUST NOT be sent (DocumentVoid): it should never + /// have reached the customer. Open, partial, paid and written-off + /// invoices all may be (a receipt copy, a reminder). + /// 3. `to` MUST hold at least one recipient; every recipient, the + /// reference and the note MUST pass parties::check_text (no full + /// TIN, no control characters, at most 500 characters). + /// 4. A send MUST change no figure: the invoice's DocState is the + /// same before and after, on every date. + /// 5. A refusal MUST leave the books unchanged. + /// SCENARIOS: + /// 1. IF the invoice is unknown, void, dated after the send, has no + /// recipients, or a text breaks the books' rule: SHOULD refuse. + /// ``` + pub fn mark_sent(&mut self, invoice: InvoiceId, sent: arap::Sent) -> Result<(), LedgerError> { + self.atomically(|l| l.mark_sent_steps(invoice, sent)) + } + + /// The steps of [`Self::mark_sent`], run inside [`Self::atomically`]. + fn mark_sent_steps(&mut self, invoice: InvoiceId, sent: arap::Sent) -> Result<(), LedgerError> { + let issued = self + .invoices + .get(&invoice) + .ok_or(LedgerError::UnknownInvoice(invoice))? + .date; + if sent.on < issued { + return Err(LedgerError::InvalidSend(format!( + "invoice {invoice} is dated {issued}: a send can't be dated before it, on {}", + sent.on + ))); + } + // The invoice's state on the day it went out: a void later than the + // send doesn't un-send it, and a void before it does. + let state = self + .doc_state(arap::DocRef::Invoice(invoice), sent.on)? + .ok_or(LedgerError::UnknownInvoice(invoice))?; + match state.status { + arap::DocStatus::Open + | arap::DocStatus::Partial + | arap::DocStatus::Paid + | arap::DocStatus::WrittenOff => {} + arap::DocStatus::Void => return Err(LedgerError::DocumentVoid(invoice)), + arap::DocStatus::Overpaid | arap::DocStatus::Unattached => { + return Err(LedgerError::InvalidSend(format!( + "invoice {invoice} is {status} on {on}: only an open, partial, paid or written-off invoice can be sent", + status = state.status.key(), + on = sent.on + ))); + } + } + if sent.to.is_empty() { + return Err(LedgerError::InvalidSend(format!( + "a send of invoice {invoice} needs at least one recipient" + ))); + } + for to in &sent.to { + crate::parties::check_text("a recipient", to).map_err(LedgerError::InvalidSend)?; + } + if let Some(reference) = &sent.reference { + crate::parties::check_text("the reference", reference) + .map_err(LedgerError::InvalidSend)?; + } + if let Some(note) = &sent.note { + crate::parties::check_text("the note", note).map_err(LedgerError::InvalidSend)?; + } + self.invoices + .get_mut(&invoice) + .expect("checked above") + .sends + .push(sent); + Ok(()) + } + + /// Record a send without checking it: replay support for journaling + /// stores. Nothing is validated on replay (rules.md B-28); the invoice + /// must already have been replayed from its own events. + #[doc(hidden)] + pub fn replay_invoice_sent( + &mut self, + invoice_id: InvoiceId, + sent: arap::Sent, + ) -> Result<(), LedgerError> { + let invoice = self + .invoices + .get_mut(&invoice_id) + .ok_or(LedgerError::UnknownInvoice(invoice_id))?; + invoice.sends.push(sent); + Ok(()) + } + /// Look up an invoice. pub fn get_invoice(&self, id: InvoiceId) -> Option<&Invoice> { self.invoices.get(&id) diff --git a/crates/ledger-store/src/format.rs b/crates/ledger-store/src/format.rs index 500845d..c35b42e 100644 --- a/crates/ledger-store/src/format.rs +++ b/crates/ledger-store/src/format.rs @@ -243,6 +243,7 @@ pub const EVENT_TYPES: &[&str] = &[ "fx.rate_set", "invoice.created", "invoice.payment_received", + "invoice.sent", "instrument.added", FORMAT_SET, "journal.tail_repaired", diff --git a/crates/ledger-store/src/meta.rs b/crates/ledger-store/src/meta.rs index 8205453..225ff92 100644 --- a/crates/ledger-store/src/meta.rs +++ b/crates/ledger-store/src/meta.rs @@ -14,7 +14,9 @@ //! ``` use crate::error::StoreError; +use crate::journal::JournalLine; use chrono::NaiveDate; +use ledger_core::arap::{SendKind, Sent, SentVia}; use ledger_core::conventions::{Approval, ConventionKind, NewConvention, NewDecision, NewOpenItem}; use ledger_core::settings::{Change, Source}; use ledger_core::{ClassId, ProjectFacts, ProjectKind, ProjectStatus}; @@ -361,6 +363,61 @@ pub fn entry_approved_of(p: &Value, seq: u64) -> Result<(u64, Approval), StoreEr )) } +/// A list of strings, each checked (`to` on `invoice.sent`). +fn str_list(p: &Value, event: &str, k: &str) -> Result, StoreError> { + p.get(k) + .and_then(Value::as_array) + .ok_or_else(|| corrupt(event, k))? + .iter() + .map(|v| { + v.as_str() + .map(str::to_string) + .ok_or_else(|| corrupt(event, k)) + }) + .collect() +} + +/// `invoice.sent {invoice_id, on, by, via, to, kind, reference?, note?}` +/// (plan P4b S5): a send is a fact of the document's life and moves no +/// figure. +pub fn invoice_sent(invoice: u64, s: &Sent) -> Value { + let mut o = Map::new(); + o.insert("invoice_id".into(), json!(invoice)); + o.insert("on".into(), json!(s.on.to_string())); + o.insert("by".into(), json!(s.by)); + o.insert("via".into(), json!(s.via.key())); + o.insert("to".into(), json!(s.to)); + o.insert("kind".into(), json!(s.kind.key())); + put(&mut o, "reference", s.reference.clone()); + put(&mut o, "note", s.note.clone()); + Value::Object(o) +} + +/// Read an `invoice.sent`: `(invoice, send)`. A channel or kind this +/// version doesn't know is newer, never corrupt (rules.md B-27). +pub fn invoice_sent_of(line: &JournalLine) -> Result<(u64, Sent), StoreError> { + const E: &str = "invoice.sent"; + let p = &line.payload; + let via = str_of(p, E, "via")?; + let kind = str_of(p, E, "kind")?; + Ok(( + u64_of(p, E, "invoice_id")?, + Sent { + on: date_of(&str_of(p, E, "on")?, E, "on")?, + by: str_of(p, E, "by")?, + via: SentVia::parse(&via).ok_or_else(|| { + crate::format::newer_content(line, format!("the send channel {via:?}")) + })?, + to: str_list(p, E, "to")?, + kind: SendKind::parse(&kind).ok_or_else(|| { + crate::format::newer_content(line, format!("the send kind {kind:?}")) + })?, + reference: opt_str(p, E, "reference")?, + note: opt_str(p, E, "note")?, + }, + )) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ledger-store/src/schema.rs b/crates/ledger-store/src/schema.rs index c885425..c90c065 100644 --- a/crates/ledger-store/src/schema.rs +++ b/crates/ledger-store/src/schema.rs @@ -5,7 +5,7 @@ //! is the current version. /// Current schema version. -pub const SCHEMA_VERSION: u32 = 16; +pub const SCHEMA_VERSION: u32 = 17; /// Migrations, in order. `MIGRATIONS[i]` migrates from version `i` to `i+1`. pub const MIGRATIONS: &[&str] = &[ @@ -417,5 +417,22 @@ ALTER TABLE bills ADD COLUMN received_on TEXT; ALTER TABLE bills ADD COLUMN terms TEXT; ALTER TABLE bills ADD COLUMN memo TEXT; ALTER TABLE bills ADD COLUMN duplicate_reason TEXT; +"#, + r#" +-- v17: sent tracking (plan P4b S5, `invoice.sent`): one row per recorded +-- send of an invoice, in the order journaled. A send moves no figure and +-- no ledger line, so this table is only the projection's copy of the +-- journal's record (parity with replay). `on` and `by` are quoted: `on` +-- is an SQL keyword. +CREATE TABLE IF NOT EXISTS invoice_sends( + invoice_id INTEGER NOT NULL, + "on" TEXT NOT NULL, + "by" TEXT NOT NULL, + via TEXT NOT NULL, + to_json TEXT NOT NULL, + kind TEXT NOT NULL, + reference TEXT NULL, + note TEXT NULL +); "#, ]; diff --git a/crates/ledger-store/src/store.rs b/crates/ledger-store/src/store.rs index 055ff0b..5c6933c 100644 --- a/crates/ledger-store/src/store.rs +++ b/crates/ledger-store/src/store.rs @@ -3698,6 +3698,36 @@ impl Store { self.reverse_entry(target, date, &description) } + /// Record that an invoice went out ([`Ledger::mark_sent`], plan P4b + /// S5): journaled as `invoice.sent` (feature `documents_v2`: an older + /// version refuses the type), then applied to the books. A send moves + /// no figure, so it journals one line and no entry. + /// + /// ```text + /// GOAL: a send is journaled once and replays to the same record, in + /// every version that can read the books. + /// SOURCE: docs/spec/rules.md B-27, B-38; plan P4b S5, A-4. + /// SCENARIOS: + /// 1. IF the engine refuses it (unknown or void invoice, a date + /// before the invoice, no recipients, a text the books won't + /// keep): SHOULD refuse, journaling nothing. + /// 2. IF the books haven't declared documents_v2: SHOULD need the + /// feature, journaling nothing. + /// ``` + pub fn mark_sent( + &mut self, + invoice_id: InvoiceId, + sent: ledger_core::arap::Sent, + ) -> Result<(), StoreError> { + self.ensure_feature(crate::format::DOCUMENTS_V2)?; + self.rehearse(|l| l.mark_sent(invoice_id, sent.clone()))?; + let line = + self.append_journal("invoice.sent", crate::meta::invoice_sent(invoice_id, &sent))?; + self.ledger.mark_sent(invoice_id, sent)?; + apply_line_to_sqlite(&self.conn, &line)?; + Ok(()) + } + // ------------------------------------------------------------------ // Foreign exchange // ------------------------------------------------------------------ @@ -6979,6 +7009,11 @@ fn replay_line( parse_bill_fields(p)?, )?; } + "invoice.sent" => { + // A send moves no figure: it only restores the invoice's sends. + let (invoice_id, sent) = crate::meta::invoice_sent_of(line)?; + ledger.replay_invoice_sent(invoice_id, sent)?; + } "invoice.payment_received" => { // The payment entry was already rebuilt; this only moves the // invoice's paid amount and status. @@ -7961,6 +7996,26 @@ fn apply_line_rows(conn: &Connection, line: &JournalLine) -> Result<(), StoreErr ], )?; } + // A send is a document's own record, not a ledger line (plan P4b + // S5): one row each, for the projection to agree with replay. + "invoice.sent" => { + let to = p + .get("to") + .ok_or_else(|| StoreError::JournalCorrupt("invoice.sent without to".into()))?; + conn.execute( + "INSERT INTO invoice_sends(invoice_id, \"on\", \"by\", via, to_json, kind, reference, note) VALUES (?,?,?,?,?,?,?,?)", + params![ + get_u64(p, "invoice_id")? as i64, + get_str(p, "on")?, + get_str(p, "by")?, + get_str(p, "via")?, + to.to_string(), + get_str(p, "kind")?, + p.get("reference").and_then(|v| v.as_str()), + p.get("note").and_then(|v| v.as_str()), + ], + )?; + } // A payment moves no document row: what a document is paid is read // from the ledger lines tagged with it (schema v15, rules.md B-38). "invoice.payment_received" => {} diff --git a/crates/ledger-store/tests/arap_props.rs b/crates/ledger-store/tests/arap_props.rs index a014f20..89cda5d 100644 --- a/crates/ledger-store/tests/arap_props.rs +++ b/crates/ledger-store/tests/arap_props.rs @@ -64,6 +64,9 @@ enum Op { Reverse(usize, u8), /// Void document `k` on day `n`. Void(usize, u8), + /// Record a send of document `k` (an invoice; a bill is skipped) on + /// day `n`, a reminder after its first send. A send moves no figure. + MarkSent(usize, u8), /// Close month `m` (January to March), in order. Close(u8), /// A hand line on receivables (true) or payables: always refused. @@ -77,6 +80,7 @@ fn arb_op() -> impl Strategy { .prop_map(|(k, n, c, card, r)| Op::Pay(k, n, c, card, r)), 3 => (0usize..40, 0u8..90).prop_map(|(k, n)| Op::Reverse(k, n)), 1 => (0usize..8, 0u8..90).prop_map(|(k, n)| Op::Void(k, n)), + 2 => (0usize..8, 0u8..90).prop_map(|(k, n)| Op::MarkSent(k, n)), 1 => (1u8..4).prop_map(Op::Close), 1 => (any::(), 1i64..10_000).prop_map(|(r, c)| Op::Hand(r, c)), ] @@ -173,6 +177,35 @@ fn run(s: &mut Store, k: &Setup, ops: &[Op], docs: &mut Vec) -> Result<( Op::Void(i, n) => s .void_document(docs[i % docs.len()], day(n), "duplicate") .map(drop), + Op::MarkSent(..) if docs.is_empty() => Ok(()), + Op::MarkSent(i, n) => match docs[i % docs.len()] { + // Bills get no sends: we receive them (plan P4b S5). + DocRef::Bill(_) => Ok(()), + DocRef::Invoice(id) => { + let kind = if s + .ledger() + .get_invoice(id) + .is_some_and(|i| !i.sends.is_empty()) + { + ledger_core::arap::SendKind::Reminder + } else { + ledger_core::arap::SendKind::Original + }; + s.mark_sent( + id, + ledger_core::arap::Sent { + on: day(n), + by: "agent".into(), + via: ledger_core::arap::SentVia::Email, + to: vec!["billing@fernhill.example".into()], + kind, + reference: None, + note: None, + }, + ) + .map(drop) + } + }, Op::Close(m) => { let start = NaiveDate::from_ymd_opt(2026, u32::from(m), 1).unwrap(); let end = start + chrono::Months::new(1) - chrono::Days::new(1); diff --git a/crates/ledger-store/tests/arap_standing.rs b/crates/ledger-store/tests/arap_standing.rs index eec3711..18b4cb5 100644 --- a/crates/ledger-store/tests/arap_standing.rs +++ b/crates/ledger-store/tests/arap_standing.rs @@ -12,8 +12,8 @@ use chrono::NaiveDate; use ledger_core::LedgerError; use ledger_core::arap; -use ledger_core::arap::DocumentLine; -use ledger_core::{AccountType, Currency, Money, Side}; +use ledger_core::arap::{DocumentLine, SendKind, Sent, SentVia}; +use ledger_core::{AccountType, Currency, DocRef, Money, Side}; use ledger_store::{JOURNAL_FILE, Store, StoreError, Subject}; use rust_decimal::Decimal; use serde_json::{Value, json}; @@ -1054,3 +1054,190 @@ fn preview_invoice_and_bill_journal_nothing() { ); s.verify().unwrap(); } + +/// A send, as these tests record one (plan P4b S5, A-4). +fn sent(on: NaiveDate, kind: SendKind, reference: Option<&str>) -> Sent { + Sent { + on, + by: "agent".into(), + via: SentVia::Email, + to: vec!["billing@fernhill.example".into()], + kind, + reference: reference.map(str::to_string), + note: None, + } +} + +/// R-A step 3 (plan P4b S5): `invoice.sent` is `documents_v2`'s, so books +/// that haven't declared it refuse a send, journaling nothing; after the +/// owner's go-ahead it journals, and the reopened books hold it. +#[test] +fn mark_sent_waits_for_documents_v2() { + let dir = test_dir("sent-waits"); + let mut s = Store::create_in_format( + &dir.0, + Currency::USD, + &ledger_store::JournalFormat::default(), + ) + .unwrap(); + let c = s.add_customer("Fernhill Labs").unwrap(); + let inv = s + .create_invoice( + c, + d(2026, 3, 1), + d(2026, 3, 31), + vec![line("Design", 10_000)], + ) + .unwrap(); + let head = s.head(); + let from = journal_len(&dir.0); + let one = sent(d(2026, 3, 2), SendKind::Original, None); + match s.mark_sent(inv, one.clone()) { + Err(StoreError::FormatUpgradePending { need }) => { + assert_eq!(need, "the journal feature documents_v2") + } + other => panic!("expected FormatUpgradePending, got {other:?}"), + } + assert_eq!(s.head(), head, "a refusal journals nothing"); + assert_eq!(journal_len(&dir.0), from); + assert!(s.upgrade_format().unwrap().is_some(), "the go-ahead"); + s.mark_sent(inv, one).unwrap(); + let live = s.ledger().clone(); + drop(s); + let reopened = Store::open(&dir.0).unwrap(); + reopened.verify().unwrap(); + assert!( + live.differs_from(reopened.ledger()).is_empty(), + "{:?}", + live.differs_from(reopened.ledger()) + ); + assert_eq!(reopened.ledger().get_invoice(inv).unwrap().sends.len(), 1); +} + +/// R-A and R-B (plan P4b S5): a send journals one `invoice.sent` line with +/// the whole record, replays into the invoice, and projects into +/// `invoice_sends`; two sends keep their order. +#[test] +fn sends_replay_and_project() { + let dir = test_dir("sent-replay"); + let mut s = Store::create(&dir.0, Currency::USD).unwrap(); + let c = s.add_customer("Fernhill Labs").unwrap(); + let inv = s + .create_invoice( + c, + d(2026, 3, 1), + d(2026, 3, 31), + vec![line("Design", 10_000)], + ) + .unwrap(); + let from = journal_len(&dir.0); + let original = sent(d(2026, 3, 2), SendKind::Original, None); + let reminder = sent(d(2026, 3, 20), SendKind::Reminder, Some("msg-2")); + s.mark_sent(inv, original.clone()).unwrap(); + s.mark_sent(inv, reminder.clone()).unwrap(); + let got = since(&dir.0, from); + assert_eq!(got.len(), 2, "{got:?}"); + assert_eq!(got[0].0, "invoice.sent"); + assert_eq!(got[0].1["invoice_id"], json!(inv)); + assert_eq!(got[0].1["on"], json!("2026-03-02")); + assert_eq!(got[0].1["by"], json!("agent")); + assert_eq!(got[0].1["via"], json!("email")); + assert_eq!(got[0].1["to"], json!(["billing@fernhill.example"])); + assert_eq!(got[0].1["kind"], json!("original")); + assert_eq!(got[0].1.get("reference"), None, "absent, not null"); + assert_eq!(got[1].1["kind"], json!("reminder")); + assert_eq!(got[1].1["reference"], json!("msg-2")); + s.verify().unwrap(); + let live = s.ledger().clone(); + drop(s); + let reopened = Store::open(&dir.0).unwrap(); + reopened.verify().unwrap(); + assert!( + live.differs_from(reopened.ledger()).is_empty(), + "{:?}", + live.differs_from(reopened.ledger()) + ); + assert_eq!( + reopened.ledger().get_invoice(inv).unwrap().sends, + vec![original, reminder] + ); +} + +/// A send changes no figure (plan P4b S5, B-38): on the fixture book an +/// earlier version wrote, every report, every derived document figure and +/// the invoice's whole DocState are the same before and after it. +#[test] +fn a_send_changes_no_figure() { + let dir = fixture("sent-figure"); + let mut s = Store::open(&dir.0).unwrap(); + s.upgrade_format().unwrap(); + let before = ledger_core::reports::snapshot(s.ledger()).unwrap(); + let state_before = s.ledger().invoice_state(1, d(9999, 12, 31)).unwrap(); + let cached_before: Vec<_> = s + .ledger() + .invoices() + .into_iter() + .map(|i| (i.id, i.amount_paid, i.owed, i.status)) + .collect(); + s.mark_sent(1, sent(d(2026, 4, 1), SendKind::Original, None)) + .unwrap(); + assert_eq!( + ledger_core::reports::snapshot(s.ledger()).unwrap(), + before, + "a send moves no report" + ); + assert_eq!( + s.ledger().invoice_state(1, d(9999, 12, 31)).unwrap(), + state_before, + "a send moves no DocState" + ); + assert_eq!( + s.ledger() + .invoices() + .into_iter() + .map(|i| (i.id, i.amount_paid, i.owed, i.status)) + .collect::>(), + cached_before, + "and no derived cache" + ); + assert_eq!( + trial_balance_json(&s), + golden()["trial_balance"], + "the golden's general ledger, a send included" + ); + assert_eq!(s.ledger().get_invoice(1).unwrap().sends.len(), 1); + s.verify().unwrap(); +} + +/// A void invoice is refused a send (plan P4b S5, `DocumentVoid`), +/// journaling nothing; an invoice open on the send's date but voided after +/// it keeps the send that happened first. +#[test] +fn mark_sent_on_void_refused() { + let dir = test_dir("sent-void"); + let mut s = Store::create(&dir.0, Currency::USD).unwrap(); + let c = s.add_customer("Fernhill Labs").unwrap(); + let inv = s + .create_invoice( + c, + d(2026, 3, 1), + d(2026, 3, 31), + vec![line("Design", 10_000)], + ) + .unwrap(); + s.void_document(DocRef::Invoice(inv), d(2026, 3, 10), "duplicate") + .unwrap(); + let head = s.head(); + let from = journal_len(&dir.0); + match s.mark_sent(inv, sent(d(2026, 3, 11), SendKind::Original, None)) { + Err(StoreError::Ledger(LedgerError::DocumentVoid(id))) => assert_eq!(id, inv), + other => panic!("expected DocumentVoid, got {other:?}"), + } + assert_eq!(s.head(), head, "a refusal journals nothing"); + assert_eq!(journal_len(&dir.0), from); + // Dated before the void, the send was a real one: it replays. + s.mark_sent(inv, sent(d(2026, 3, 5), SendKind::Original, None)) + .unwrap(); + assert_eq!(s.ledger().get_invoice(inv).unwrap().sends.len(), 1); + s.verify().unwrap(); +} diff --git a/crates/ledger-store/tests/fixtures/old-books-writer/Cargo.toml b/crates/ledger-store/tests/fixtures/old-books-writer/Cargo.toml index 061f21f..f426613 100644 --- a/crates/ledger-store/tests/fixtures/old-books-writer/Cargo.toml +++ b/crates/ledger-store/tests/fixtures/old-books-writer/Cargo.toml @@ -7,6 +7,8 @@ # cargo run --bin extras -- OUT (the edges of chrono and Decimal) # cargo run --bin extras2 -- OUT (depreciation for 10000-01; 1,044 drafts) # cargo run --bin older -- OUT (x_older_rules, with its JournalWriter) +# cargo run --bin s5_before -- OUT (p4_s5_before: run against eeee9658, +# the revision before P4b S5) # cargo run --bin p2_1099 -- OUT (p2_vendor_1099: P2's 1099 marks, run # against 9c99a0cf, the revision before P3) # cargo run --bin expect -- OUT (expected.json beside each journal) diff --git a/crates/ledger-store/tests/fixtures/old-books-writer/src/bin/s5_before.rs b/crates/ledger-store/tests/fixtures/old-books-writer/src/bin/s5_before.rs new file mode 100644 index 0000000..41ca96e --- /dev/null +++ b/crates/ledger-store/tests/fixtures/old-books-writer/src/bin/s5_before.rs @@ -0,0 +1,65 @@ +//! Writes `p4_s5_before`: books the version before P4b S5 (main eeee9658) +//! wrote through its Store API: a chart, a customer's invoice part paid, +//! and a vendor's bill. No send exists in that version; this version opens +//! the same journal and must report the same figures. +use chrono::NaiveDate; +use ledger_core::{AccountType, Currency, DocRef, DocumentLine, Money, Side}; +use ledger_store::Store; +use rust_decimal::Decimal; +use std::path::PathBuf; + +fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() +} +fn cents(c: i64) -> Decimal { + Decimal::new(c, 2) +} +fn line(what: &str, c: i64) -> DocumentLine { + DocumentLine { + description: what.into(), + amount: cents(c), + class_id: None, + account: None, + quantity: None, + unit_price: None, + } +} + +fn main() { + let root = PathBuf::from(std::env::args().nth(1).unwrap()); + let dir = root.join("p4_s5_before"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Store::create(&dir, Currency::USD).unwrap(); + let bank = s + .add_account("1000", "Bank", AccountType::Asset, None, false) + .unwrap(); + let capital = s + .add_account("3000", "Capital", AccountType::Equity, None, false) + .unwrap(); + let seed = s.create_entry(d(2026, 1, 1), "Opening capital").unwrap(); + let m = Money::new(Decimal::from(1000), Currency::USD); + s.add_line(seed, bank, Side::Debit, m).unwrap(); + s.add_line(seed, capital, Side::Credit, m).unwrap(); + s.post_entry(seed).unwrap(); + let fernhill = s.add_customer("Fernhill Labs").unwrap(); + let vendor = s.add_vendor("Tobin Harlow Supply").unwrap(); + let inv = s + .create_invoice( + fernhill, + d(2026, 2, 1), + d(2026, 3, 3), + vec![line("Design", 120_000)], + ) + .unwrap(); + s.receive_payment(inv, d(2026, 2, 15), cents(40_000), bank) + .unwrap(); + s.create_bill( + vendor, + d(2026, 2, 10), + d(2026, 3, 12), + vec![line("Drafting", 30_000)], + ) + .unwrap(); + println!("WROTE {:?} (invoice {inv}, {:?})", dir, DocRef::Invoice(inv)); +} diff --git a/crates/ledger-store/tests/fixtures/old-books/p4_s5_before/expected.json b/crates/ledger-store/tests/fixtures/old-books/p4_s5_before/expected.json new file mode 100644 index 0000000..7f30b82 --- /dev/null +++ b/crates/ledger-store/tests/fixtures/old-books/p4_s5_before/expected.json @@ -0,0 +1,265 @@ +{ + "assets": [], + "bills": [ + { + "amount_paid": "0", + "date": "2026-02-10", + "due_date": "2026-03-12", + "entry_id": 4, + "id": 1, + "lines": [ + { + "amount": "300.00", + "description": "Drafting" + } + ], + "status": "Open", + "vendor_id": 1 + } + ], + "entries": [ + { + "date": "2026-01-01", + "description": "Opening capital", + "id": 1, + "lines": [ + { + "account": 1, + "amount": { + "amount": "1000", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 2, + "amount": { + "amount": "1000", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + }, + { + "date": "2026-02-01", + "description": "Invoice 1", + "id": 2, + "lines": [ + { + "account": 3, + "amount": { + "amount": "1200.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 4, + "amount": { + "amount": "1200.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + }, + { + "date": "2026-02-15", + "description": "Payment on invoice 1", + "id": 3, + "lines": [ + { + "account": 1, + "amount": { + "amount": "400.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 3, + "amount": { + "amount": "400.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + }, + { + "date": "2026-02-10", + "description": "Bill 1", + "id": 4, + "lines": [ + { + "account": 5, + "amount": { + "amount": "300.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 6, + "amount": { + "amount": "300.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + } + ], + "entry_parties": [ + [ + 2, + [ + { + "party_id": 1, + "share": "derived" + } + ] + ], + [ + 3, + [ + { + "party_id": 1, + "share": "derived" + } + ] + ], + [ + 4, + [ + { + "party_id": 2, + "share": "derived" + } + ] + ] + ], + "invoices": [ + { + "amount_paid": "400.00", + "customer_id": 1, + "date": "2026-02-01", + "due_date": "2026-03-03", + "entry_id": 2, + "id": 1, + "lines": [ + { + "amount": "1200.00", + "description": "Design" + } + ], + "status": "Partial" + } + ], + "payroll_runs": [], + "periods": [], + "recurring": [], + "schedules": [], + "snapshot": { + "Ok": { + "balance_sheet": { + "assets": "2200", + "balanced": true, + "current_earnings": "900", + "equity": "1900", + "liabilities": "300" + }, + "profit_and_loss": { + "expenses": "300", + "net_income": "900", + "revenue": "1200" + }, + "trial_balance": { + "lines": [ + { + "code": "1000", + "credit": "0", + "debit": "1400", + "name": "Bank" + }, + { + "code": "1200", + "credit": "0", + "debit": "800", + "name": "Accounts Receivable" + }, + { + "code": "2000", + "credit": "300", + "debit": "0", + "name": "Accounts Payable" + }, + { + "code": "3000", + "credit": "1000", + "debit": "0", + "name": "Capital" + }, + { + "code": "4000", + "credit": "1200", + "debit": "0", + "name": "Revenue" + }, + { + "code": "6999", + "credit": "0", + "debit": "300", + "name": "General Expenses" + } + ], + "total_credits": "2500", + "total_debits": "2500" + } + } + }, + "verify": { + "Ok": null + } +} diff --git a/crates/ledger-store/tests/fixtures/old-books/p4_s5_before/journal.jsonl b/crates/ledger-store/tests/fixtures/old-books/p4_s5_before/journal.jsonl new file mode 100644 index 0000000..bb854c7 --- /dev/null +++ b/crates/ledger-store/tests/fixtures/old-books/p4_s5_before/journal.jsonl @@ -0,0 +1,29 @@ +{"payload":{"base_currency":"USD"},"prev":"0000000000000000000000000000000000000000000000000000000000000000","seq":1,"ts":"2026-10-27T12:07:38Z","type":"store.created"} +{"payload":{"features":["account_renamed","asset_basis","depreciation_catch_up","disposal_before_service","document_line_projects","document_standing","documents_v2","members_cumulative","month_reposting","party_creditors","payment_instruments","projects","require_tax_category","schedule_convention","tax_categories_gain_exempt","vendor_1099_decisions"],"format":2},"prev":"0bbd745853ef336fa261af81109c83ac2b5c62be3d9243eecbd7d1abc4810afc","seq":2,"ts":"2026-10-27T12:07:38Z","type":"journal.format_set"} +{"payload":{"account_type":"Asset","code":"1000","currency":"USD","id":1,"name":"Bank","parent":null,"placeholder":false},"prev":"5b4b18ca6b1e3e4dd2dd8d2ba522d2ec8ffdf3cd2c10472092983453c5675472","seq":3,"ts":"2026-10-27T12:07:38Z","type":"account.added"} +{"payload":{"account_type":"Equity","code":"3000","currency":"USD","id":2,"name":"Capital","parent":null,"placeholder":false},"prev":"c0ab8146ae450a9204c1f2dd338f49330900ec2c4edd29bda362ce5c73665275","seq":4,"ts":"2026-10-27T12:07:38Z","type":"account.added"} +{"payload":{"date":"2026-01-01","description":"Opening capital","id":1},"prev":"ade211d7ae85ac8a12866d529418cba0785290e559183a0700dd91c95a7d41b0","seq":5,"ts":"2026-10-27T12:07:38Z","type":"entry.created"} +{"payload":{"account":1,"amount":"1000","currency":"USD","id":1,"side":"debit"},"prev":"0b1c4e86907d5b19faed67cba9633120de6726217fec3602930e09cb1c3ac6e1","seq":6,"ts":"2026-10-27T12:07:38Z","type":"entry.line_added"} +{"payload":{"account":2,"amount":"1000","currency":"USD","id":1,"side":"credit"},"prev":"f300e939ff3967ad7b04c781ec6ec0c2790cbfb938a1ad57d8428239f3c05ecb","seq":7,"ts":"2026-10-27T12:07:38Z","type":"entry.line_added"} +{"payload":{"date":"2026-01-01","description":"Opening capital","id":1,"lines":[{"account":1,"amount":"1000","currency":"USD","side":"debit"},{"account":2,"amount":"1000","currency":"USD","side":"credit"}],"reversal_of":null},"prev":"4c31e09e179aa377d03f09ff07298a94f7bcdb5463b9a56e7d9ec1649fa9b859","seq":8,"ts":"2026-10-27T12:07:38Z","type":"entry.posted"} +{"payload":{"id":1,"name":"Fernhill Labs"},"prev":"88a5469ed669976c63355000e7ce6b358bc3d8731527da98f45833ae28cd04f8","seq":9,"ts":"2026-10-27T12:07:38Z","type":"customer.added"} +{"payload":{"id":1,"name":"Tobin Harlow Supply"},"prev":"84f6fd180671d63e367eaa0465867732877995d282996446ed2514e2b164f06d","seq":10,"ts":"2026-10-27T12:07:38Z","type":"vendor.added"} +{"payload":{"account_type":"Asset","code":"1200","currency":"USD","id":3,"name":"Accounts Receivable","parent":null,"placeholder":false},"prev":"af015074dc5235c7efd9df38e447866e46c5d552d049f07ceec7f5cc94655770","seq":11,"ts":"2026-10-27T12:07:38Z","type":"account.added"} +{"payload":{"account_type":"Revenue","code":"4000","currency":"USD","id":4,"name":"Revenue","parent":null,"placeholder":false},"prev":"a17b19e0d8229d378f2cf950079ff6495b21799ecc0b4608de72853d62d5eaf2","seq":12,"ts":"2026-10-27T12:07:39Z","type":"account.added"} +{"payload":{"date":"2026-02-01","description":"Invoice 1","id":2},"prev":"7e1bf5a0142e15f2c4471f6dd413e428586673cdf5ce94d46e40bb951d487423","seq":13,"ts":"2026-10-27T12:07:39Z","type":"entry.created"} +{"payload":{"account":3,"amount":"1200.00","currency":"USD","id":2,"side":"debit"},"prev":"0b0d2bc9815cac0aaf428d114031cd18d6c133cb14aff6e374324b9a973fe50f","seq":14,"ts":"2026-10-27T12:07:39Z","type":"entry.line_added"} +{"payload":{"account":4,"amount":"1200.00","currency":"USD","id":2,"side":"credit"},"prev":"fa319df9f4858df95f47b4035c0f83901674dca7fbc5978b820a8d93bd27e196","seq":15,"ts":"2026-10-27T12:07:39Z","type":"entry.line_added"} +{"payload":{"date":"2026-02-01","description":"Invoice 1","id":2,"lines":[{"account":3,"amount":"1200.00","currency":"USD","side":"debit"},{"account":4,"amount":"1200.00","currency":"USD","side":"credit"}],"reversal_of":null},"prev":"e0cbb496c5116f927a0d2d897c651bf7df706af670d44c468703a81cdbb6a598","seq":16,"ts":"2026-10-27T12:07:39Z","type":"entry.posted"} +{"payload":{"customer_id":1,"date":"2026-02-01","due_date":"2026-03-03","entry_id":2,"id":1,"lines":[{"amount":"1200.00","description":"Design"}]},"prev":"72eee837c1eee71d7b45bc63e840224fe85d4f08f423b7cdadd5431d2e0c730c","seq":17,"ts":"2026-10-27T12:07:39Z","type":"invoice.created"} +{"payload":{"date":"2026-02-15","description":"Payment on invoice 1","id":3},"prev":"915870654047decc4b93972fb04bd76bf8ea65b5710f58a866d3661c0a3c09f5","seq":18,"ts":"2026-10-27T12:07:39Z","type":"entry.created"} +{"payload":{"account":1,"amount":"400.00","currency":"USD","id":3,"side":"debit"},"prev":"433c71f0884859468a8b1e48038b807bc9f910e23e22bd646518913287f5a1d6","seq":19,"ts":"2026-10-27T12:07:39Z","type":"entry.line_added"} +{"payload":{"account":3,"amount":"400.00","currency":"USD","id":3,"side":"credit"},"prev":"86db1b12b1c6585ed1fadbee2543d33e0adede5e9a02f0d36626a6f8acc2179a","seq":20,"ts":"2026-10-27T12:07:39Z","type":"entry.line_added"} +{"payload":{"date":"2026-02-15","description":"Payment on invoice 1","id":3,"lines":[{"account":1,"amount":"400.00","currency":"USD","side":"debit"},{"account":3,"amount":"400.00","currency":"USD","side":"credit"}],"reversal_of":null},"prev":"c4a0a4fb8495af3b43b2b5d5e9602067998028b65d42a301e407f37017d6e6b0","seq":21,"ts":"2026-10-27T12:07:39Z","type":"entry.posted"} +{"payload":{"amount":"400.00","cash_account":1,"date":"2026-02-15","entry_id":3,"invoice_id":1},"prev":"5a29d6bff70696aeb707eb69fac9ceaffb7c5167e10434b23aa18ba9aeb4b8ff","seq":22,"ts":"2026-10-27T12:07:39Z","type":"invoice.payment_received"} +{"payload":{"account_type":"Expense","code":"6999","currency":"USD","id":5,"name":"General Expenses","parent":null,"placeholder":false},"prev":"2dc14a4d6d23f42a34c1172475ac86b9706be79ee17ba9bfd4041fde99c43231","seq":23,"ts":"2026-10-27T12:07:39Z","type":"account.added"} +{"payload":{"account_type":"Liability","code":"2000","currency":"USD","id":6,"name":"Accounts Payable","parent":null,"placeholder":false},"prev":"4a44d6570b6b9e1f3b705b383d41939aab2952d32902ab151f2b4d02ad3c1237","seq":24,"ts":"2026-10-27T12:07:39Z","type":"account.added"} +{"payload":{"date":"2026-02-10","description":"Bill 1","id":4},"prev":"bd11681484634f272371a9245cfabdff52024ffe516380143b650275b9af034a","seq":25,"ts":"2026-10-27T12:07:39Z","type":"entry.created"} +{"payload":{"account":5,"amount":"300.00","currency":"USD","id":4,"side":"debit"},"prev":"3df6859cd10b0f3ec4a50ff2abcfd619291db2c290e3d844399d0434be31754c","seq":26,"ts":"2026-10-27T12:07:39Z","type":"entry.line_added"} +{"payload":{"account":6,"amount":"300.00","currency":"USD","id":4,"side":"credit"},"prev":"86f685ccc47f69411c2cd424017510d10823f05ab3c9018fbf636ff15455b548","seq":27,"ts":"2026-10-27T12:07:39Z","type":"entry.line_added"} +{"payload":{"date":"2026-02-10","description":"Bill 1","id":4,"lines":[{"account":5,"amount":"300.00","currency":"USD","side":"debit"},{"account":6,"amount":"300.00","currency":"USD","side":"credit"}],"reversal_of":null},"prev":"c25fce42aa1755ee4e915191e4903f13874e2ea327bfd915ba39df474a04ca4e","seq":28,"ts":"2026-10-27T12:07:39Z","type":"entry.posted"} +{"payload":{"date":"2026-02-10","due_date":"2026-03-12","entry_id":4,"id":1,"lines":[{"amount":"300.00","description":"Drafting"}],"vendor_id":1},"prev":"55ec1c5c73e4ac37996b917c87d6bc9a841ce1eb43ac57882d2ca9a1fdf4820a","seq":29,"ts":"2026-10-27T12:07:39Z","type":"bill.created"} diff --git a/crates/ledger-store/tests/format.rs b/crates/ledger-store/tests/format.rs index ecc8cf6..608142b 100644 --- a/crates/ledger-store/tests/format.rs +++ b/crates/ledger-store/tests/format.rs @@ -16,8 +16,9 @@ //! ``` use chrono::NaiveDate; +use ledger_core::arap::{DocumentLine, SendKind, Sent, SentVia}; use ledger_core::{AccountType, Currency, Money, Side}; -use ledger_store::format::{EVENT_TYPES, FORMAT_SET, KNOWN_FEATURES}; +use ledger_store::format::{DOCUMENTS_V2, EVENT_TYPES, FORMAT_SET, KNOWN_FEATURES}; use ledger_store::journal::{canonical_json, sha256_hex}; use ledger_store::{ JOURNAL_FILE, JournalFormat, JournalWriter, SUPPORTED_JOURNAL_FORMAT, Snapshot, Store, @@ -1468,3 +1469,83 @@ fn the_replay_fuzzer_writes_every_event_type() { "the replay fuzzer never writes {missing:?}" ); } + +/// Done-when (plan P4b S5): the send event is this version's, it needs +/// `documents_v2`, and the books declare that feature before the first +/// `invoice.sent` line, so a version without it stops at the declaration +/// and reports the books as newer, never corrupt (rules.md B-27). +#[test] +fn an_older_version_stops_at_invoice_sent() { + assert!(EVENT_TYPES.contains(&"invoice.sent")); + let older = JournalFormat { + format: SUPPORTED_JOURNAL_FORMAT, + features: KNOWN_FEATURES + .iter() + .copied() + .filter(|f| *f != DOCUMENTS_V2) + .map(str::to_string) + .collect(), + }; + assert!( + matches!( + older.require_feature(DOCUMENTS_V2), + Err(StoreError::FormatUpgradePending { .. }) + ), + "a reader without documents_v2 waits for it" + ); + let dir = test_dir("sent-gate"); + let mut store = + Store::create_in_format(&dir, Currency::USD, &JournalFormat::default()).unwrap(); + let customer = store.add_customer("Fernhill Labs").unwrap(); + let date = NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(); + let inv = store + .create_invoice( + customer, + date, + date + chrono::Days::new(30), + vec![DocumentLine { + description: "Design".into(), + amount: Decimal::new(10_000, 2), + class_id: None, + account: None, + quantity: None, + unit_price: None, + }], + ) + .unwrap(); + store.upgrade_format().unwrap().expect("the go-ahead"); + store + .mark_sent( + inv, + Sent { + on: date, + by: "agent".into(), + via: SentVia::Email, + to: vec!["billing@fernhill.example".into()], + kind: SendKind::Original, + reference: None, + note: None, + }, + ) + .unwrap(); + let journal = std::fs::read_to_string(dir.join(JOURNAL_FILE)).unwrap(); + let mut declared = false; + let mut sent = false; + for line in journal.lines() { + let v: serde_json::Value = serde_json::from_str(line).unwrap(); + if v["type"] == FORMAT_SET + && v["payload"]["features"] + .as_array() + .is_some_and(|f| f.iter().any(|x| x == DOCUMENTS_V2)) + { + declared = true; + } + if v["type"] == "invoice.sent" { + assert!(declared, "documents_v2 must be declared before the send"); + sent = true; + } + } + assert!(sent); + drop(store); + Store::open(&dir).unwrap().verify().unwrap(); +} diff --git a/crates/ledger-store/tests/store.rs b/crates/ledger-store/tests/store.rs index 412fecc..61b1d2b 100644 --- a/crates/ledger-store/tests/store.rs +++ b/crates/ledger-store/tests/store.rs @@ -1946,6 +1946,15 @@ fn books_written_under_older_rules_still_open() { "memo": "A4 paper", "duplicate_reason": "the vendor sent it twice"}), ) .unwrap(); + // P4b S5's new shape: the record that the invoice went out + // (`invoice.sent`, feature documents_v2). A send moves no figure, so + // the document's figures are the same before and after it. + w.append( + "invoice.sent", + json!({"invoice_id": 1, "on": "2026-04-05", "by": "Avery Quill", "via": "email", + "to": ["billing@fernhill.example"], "kind": "original", "reference": "msg-1"}), + ) + .unwrap(); drop(w); // Opening rebuilds from the journal; it must accept all of it. let _ = std::fs::remove_file(dir.join(ledger_store::db_file())); @@ -2007,6 +2016,14 @@ fn books_written_under_older_rules_still_open() { ); assert_eq!(bill.memo.as_deref(), Some("A4 paper")); assert_eq!(bill.lines[0].account, Some(6)); + // P4b S5's send replays as written, and moves no figure. + let sends = &store.ledger().get_invoice(1).expect("the invoice").sends; + assert_eq!(sends.len(), 1); + assert_eq!(sends[0].on, NaiveDate::from_ymd_opt(2026, 4, 5).unwrap()); + assert_eq!(sends[0].by, "Avery Quill"); + assert_eq!(sends[0].to, ["billing@fernhill.example"]); + assert_eq!(sends[0].kind, ledger_core::arap::SendKind::Original); + assert_eq!(sends[0].reference.as_deref(), Some("msg-1")); } /// The books an earlier wanderbooks wrote, one directory each under diff --git a/fuzz/fuzz_targets/fuzz_store_replay.rs b/fuzz/fuzz_targets/fuzz_store_replay.rs index 3175d3a..8efbe58 100644 --- a/fuzz/fuzz_targets/fuzz_store_replay.rs +++ b/fuzz/fuzz_targets/fuzz_store_replay.rs @@ -27,7 +27,8 @@ const TYPES: &[&str] = &[ "asset.registered", "attachment.withdrawn", "bill.created", "bill.paid", "class.added", "customer.added", "document.filed", "entry.created", "entry.line_added", "entry.line_class_set", "entry.posted", "entry.reversed", "entry.vendor_set", - "fx.rate_set", "invoice.created", "invoice.payment_received", "journal.tail_repaired", + "fx.rate_set", "invoice.created", "invoice.payment_received", "invoice.sent", + "journal.tail_repaired", "line.cleared", "payroll.run", "period.closed", "period.created", "receipt.attached", "receipt.linked", "receipt.unlinked", "recurring.generated", "recurring.registered", "schedule.posted", "schedule.registered", "vendor.1099_set", "vendor.added", @@ -61,6 +62,7 @@ const FIELDS: &[&str] = &[ "rule", "contributor_adjusted_basis", "fmv_at_contribution", "sec704c_method", "tax_basis_723", "depreciable_basis", "built_in_gain_704c", "on", "convention", "status", "party_id", "started_on", "ended_on", "links", "notes", "projects", + "via", "by", "to", "reference", "note", ]; /// Journal features a `journal.format_set` may declare.