Merge branch 't3/refuse-tax-ids-in-free-text': free text refuses a tax id's shapes; references take nine digits; bank files mask (WB-partner-15)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
e7d5e4b8cd
36 files changed
+4353
-113
No files matched your search
@@ -119,6 +119,11 @@ pub const CODES: &[ledger_core::audit::CodeRow] = &[
|
||||
severity: Severity::Warning,
|
||||
predicate: "two filed attachments, neither withdrawn, hold the same bytes",
|
||||
},
|
||||
ledger_core::audit::CodeRow {
|
||||
code: "tax_id_in_journal",
|
||||
severity: Severity::Warning,
|
||||
predicate: "a journal line's text field holds a number that looks like a tax id (nine digits standing alone, an SSN's 3-2-4 or an EIN's 2-7)",
|
||||
},
|
||||
ledger_core::audit::CodeRow {
|
||||
code: "backup_stale",
|
||||
severity: Severity::Warning,
|
||||
@@ -144,6 +149,84 @@ fn found(code: &'static str, subject: Subject, message: String) -> Finding {
|
||||
}
|
||||
}
|
||||
|
||||
/// How the audit reads one journal field for a tax id.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum TextClass {
|
||||
/// Free words: nine digits standing alone, an SSN's 3-2-4 or an EIN's
|
||||
/// 2-7 are found.
|
||||
Free,
|
||||
/// A reference (a tag, a serial, an invoice number, a file name, an
|
||||
/// account code): only the grouped shapes are found, a bare nine digits
|
||||
/// being a legitimate number there (WB-partner-15).
|
||||
Reference,
|
||||
}
|
||||
|
||||
/// The journal fields that hold words someone wrote (never an id, a digest
|
||||
/// or an amount) and how each is read: what [`Store::integrity_findings`]
|
||||
/// reads for a tax id.
|
||||
const TEXT_KEYS: &[(&str, TextClass)] = &[
|
||||
("description", TextClass::Free),
|
||||
("memo", TextClass::Free),
|
||||
("note", TextClass::Free),
|
||||
("notes", TextClass::Free),
|
||||
("reason", TextClass::Free),
|
||||
("name", TextClass::Free),
|
||||
("label", TextClass::Reference),
|
||||
("title", TextClass::Free),
|
||||
("citation", TextClass::Free),
|
||||
("decided_by", TextClass::Free),
|
||||
("detail", TextClass::Free),
|
||||
("detail_md", TextClass::Free),
|
||||
("resolution", TextClass::Free),
|
||||
("decision_md", TextClass::Free),
|
||||
("body_md", TextClass::Free),
|
||||
("subject", TextClass::Free),
|
||||
("reference", TextClass::Reference),
|
||||
("customer_ref", TextClass::Reference),
|
||||
("vendor_ref", TextClass::Reference),
|
||||
("duplicate_reason", TextClass::Free),
|
||||
("no_party_reason", TextClass::Free),
|
||||
("payee", TextClass::Free),
|
||||
("source", TextClass::Free),
|
||||
("reimbursable_to", TextClass::Free),
|
||||
("file_name", TextClass::Reference),
|
||||
("serial", TextClass::Reference),
|
||||
("tag", TextClass::Reference),
|
||||
("code", TextClass::Reference),
|
||||
("employee_name", TextClass::Free),
|
||||
("display_name", TextClass::Free),
|
||||
("address", TextClass::Free),
|
||||
("contact", TextClass::Free),
|
||||
("kept_at", TextClass::Reference),
|
||||
("approver", TextClass::Free),
|
||||
];
|
||||
|
||||
/// Every text field of `v` named by [`TEXT_KEYS`], as (its key, how it is
|
||||
/// read, its text), at any depth; a list of texts under such a key counts
|
||||
/// each.
|
||||
fn text_fields_in(v: &Value, out: &mut Vec<(String, TextClass, String)>) {
|
||||
match v {
|
||||
Value::Object(m) => {
|
||||
for (k, x) in m {
|
||||
if let Some((_, class)) = TEXT_KEYS.iter().find(|(key, _)| *key == k.as_str()) {
|
||||
match x {
|
||||
Value::String(s) => out.push((k.clone(), *class, s.clone())),
|
||||
Value::Array(a) => out.extend(
|
||||
a.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(|s| (k.clone(), *class, s.to_string())),
|
||||
),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
text_fields_in(x, out);
|
||||
}
|
||||
}
|
||||
Value::Array(a) => a.iter().for_each(|x| text_fields_in(x, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the backups' standing says, one target at a time, for the audit
|
||||
/// (the server reads the standing; the store does not know the backups).
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -304,6 +387,20 @@ pub struct Claim {
|
||||
}
|
||||
|
||||
impl Claim {
|
||||
/// The words a claim keeps (the note, the model's name) hold no tax id
|
||||
/// (BS-partner-2): checked before anything is journaled.
|
||||
fn check(&self) -> Result<(), StoreError> {
|
||||
for (field, text) in [
|
||||
("the note", self.note.as_deref()),
|
||||
("the model", self.method.model.as_deref()),
|
||||
] {
|
||||
if let Some(t) = text {
|
||||
ledger_core::LedgerError::free_text(field, t)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn into_attestation(self, what: Attested) -> Attestation {
|
||||
Attestation {
|
||||
seq: 0,
|
||||
@@ -436,6 +533,51 @@ impl Store {
|
||||
format!("attachments {ids} hold the same bytes ({sha})"),
|
||||
));
|
||||
}
|
||||
out.extend(self.tax_id_findings());
|
||||
out
|
||||
}
|
||||
|
||||
/// The journal lines whose text fields hold what looks like a tax id
|
||||
/// (BS-partner-2): a line an earlier version took, or one a caller
|
||||
/// other than the tools wrote. The books open and replay as they are
|
||||
/// and the journal is never rewritten; the audit says where each one
|
||||
/// is, by line and field, and never what the number is.
|
||||
fn tax_id_findings(&self) -> Vec<Finding> {
|
||||
let rows: Vec<(u64, String, String)> = self
|
||||
.conn
|
||||
.prepare("SELECT seq, type, payload FROM events ORDER BY seq")
|
||||
.and_then(|mut s| {
|
||||
s.query_map([], |r| {
|
||||
Ok((r.get::<_, i64>(0)? as u64, r.get(1)?, r.get(2)?))
|
||||
})?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
for (seq, kind, payload) in rows {
|
||||
let Ok(v) = serde_json::from_str::<Value>(&payload) else {
|
||||
continue;
|
||||
};
|
||||
let mut fields = Vec::new();
|
||||
text_fields_in(&v, &mut fields);
|
||||
for (field, class, text) in fields {
|
||||
let looks = match class {
|
||||
TextClass::Free => ledger_core::settings::holds_printed_tin(&text),
|
||||
TextClass::Reference => {
|
||||
ledger_core::settings::holds_printed_tin_in_reference(&text)
|
||||
}
|
||||
};
|
||||
if looks {
|
||||
out.push(found(
|
||||
"tax_id_in_journal",
|
||||
Subject::Named(format!("journal line {seq}")),
|
||||
format!(
|
||||
"journal line {seq} ({kind}) holds, in its `{field}`, a number that looks like a tax id. The journal is never rewritten and the books open as they are: correct what it describes going forward (reverse the entry and enter it again without the number), and keep the tax id only in the vault (books.set_tin or a W-9, books.set_w9)"
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -624,6 +766,7 @@ impl Store {
|
||||
date: NaiveDate,
|
||||
claim: Claim,
|
||||
) -> Result<Attestation, StoreError> {
|
||||
claim.check()?;
|
||||
self.ensure_feature(crate::format::AUDITS)?;
|
||||
let entry = self
|
||||
.ledger
|
||||
@@ -668,6 +811,7 @@ impl Store {
|
||||
|
||||
/// Record that an entry was reviewed whole (`entry.reviewed`).
|
||||
pub fn review_entry(&mut self, entry_id: u64, claim: Claim) -> Result<Attestation, StoreError> {
|
||||
claim.check()?;
|
||||
self.ensure_feature(crate::format::AUDITS)?;
|
||||
let entry = self
|
||||
.ledger
|
||||
@@ -710,6 +854,7 @@ impl Store {
|
||||
period_id: u64,
|
||||
claim: Claim,
|
||||
) -> Result<(Attestation, AuditRun), StoreError> {
|
||||
claim.check()?;
|
||||
self.ensure_feature(crate::format::AUDITS)?;
|
||||
let run = self.run_for_period(period_id)?;
|
||||
let a = self.journal_attestation(
|
||||
|
||||
@@ -1350,16 +1350,19 @@ impl Store {
|
||||
) -> Result<EntryId, StoreError> {
|
||||
let (default_description, lines) =
|
||||
self.ledger.template_lines(template_id, amount, slots)?;
|
||||
let description = description
|
||||
.map(str::to_string)
|
||||
.or(default_description)
|
||||
.unwrap_or_else(|| {
|
||||
// The caller's words are checked as they come; a description the
|
||||
// template or its convention's title gives is stored text, masked
|
||||
// where an older version let it hold a tax id's shape.
|
||||
let description = description.map(str::to_string).unwrap_or_else(|| {
|
||||
let stored = default_description.unwrap_or_else(|| {
|
||||
self.ledger
|
||||
.conventions()
|
||||
.convention(template_id)
|
||||
.map(|c| c.title.clone())
|
||||
.unwrap_or_default()
|
||||
});
|
||||
ledger_core::settings::mask_printed_tins(&stored).into_owned()
|
||||
});
|
||||
self.rehearse(|l| {
|
||||
let e = l.try_create_entry(date, &description)?;
|
||||
for (account, side, amount) in &lines {
|
||||
@@ -1801,6 +1804,7 @@ impl Store {
|
||||
// Every refusal before the journal: a journaled reversal the engine
|
||||
// then refuses could never be replayed, and the books would not open.
|
||||
self.check_reverse_entry(entry, date)?;
|
||||
LedgerError::free_text("the reversal's description", description)?;
|
||||
let new_id = self.ledger.next_entry_id();
|
||||
let flipped: Vec<Value> = orig.lines().iter().map(flip_line_json).collect();
|
||||
// Reversals journal a single entry.reversed line (no separate
|
||||
@@ -2458,7 +2462,13 @@ impl Store {
|
||||
});
|
||||
}
|
||||
let amount = due.amount;
|
||||
let description = format!("Depreciation — {} — {period}", asset.description);
|
||||
// Composed from the asset's own words, which the books may hold
|
||||
// from before free text was read for a tax id's shape: a number
|
||||
// that reads as one is masked, never refused (WB-partner-15).
|
||||
let description = format!(
|
||||
"Depreciation — {} — {period}",
|
||||
ledger_core::settings::mask_printed_tins(&asset.description)
|
||||
);
|
||||
let money = Money::new(amount, self.base_currency);
|
||||
// Every refusal before the first journaled line: the entry on a
|
||||
// copy (and that it is the period's run, no more and no less:
|
||||
@@ -2884,7 +2894,8 @@ impl Store {
|
||||
(
|
||||
format!(
|
||||
"Depreciation — {} — {} (final)",
|
||||
asset.description, preview.period
|
||||
ledger_core::settings::mask_printed_tins(&asset.description),
|
||||
preview.period
|
||||
),
|
||||
vec![
|
||||
(
|
||||
@@ -2901,7 +2912,11 @@ impl Store {
|
||||
)
|
||||
});
|
||||
let disposal = (
|
||||
format!("Disposal — {} — {}", asset.description, date),
|
||||
format!(
|
||||
"Disposal — {} — {}",
|
||||
ledger_core::settings::mask_printed_tins(&asset.description),
|
||||
date
|
||||
),
|
||||
Self::disposal_lines(
|
||||
&asset,
|
||||
&preview,
|
||||
@@ -3585,8 +3600,14 @@ impl Store {
|
||||
entry_id,
|
||||
"invoice entry diverged from journal"
|
||||
);
|
||||
// The copy's name is composed from the invoice's number (a prefix
|
||||
// the books' settings give, then digits): a number that reads as a
|
||||
// tax id's printed shape is masked, never refused (WB-partner-15).
|
||||
let file_name = match &fields.number {
|
||||
Some(n) => format!("{n}.pdf"),
|
||||
Some(n) => format!(
|
||||
"{}.pdf",
|
||||
ledger_core::settings::mask_printed_tins_in_reference(n)
|
||||
),
|
||||
None => format!("Invoice {live}.pdf"),
|
||||
};
|
||||
// The entry's and the invoice's lines apply first: they were
|
||||
@@ -4172,6 +4193,20 @@ impl Store {
|
||||
));
|
||||
}
|
||||
}
|
||||
// The file's words, as `Self::attach_receipt` reads them, before
|
||||
// the write-off's entry is journaled (a refusal after it would
|
||||
// leave the entry without its evidence).
|
||||
if let WriteOffEvidence::File {
|
||||
file_name,
|
||||
description,
|
||||
..
|
||||
} = evidence
|
||||
{
|
||||
LedgerError::reference_text("the file name", file_name)?;
|
||||
if let Some(d) = description {
|
||||
LedgerError::free_text("the description", d)?;
|
||||
}
|
||||
}
|
||||
if let WriteOffEvidence::File { bytes, .. } = evidence
|
||||
&& let Some(existing) = self.live_attachment_with_sha(&sha256_hex(bytes))?
|
||||
{
|
||||
@@ -4754,6 +4789,10 @@ impl Store {
|
||||
bytes: &[u8],
|
||||
description: Option<&str>,
|
||||
) -> Result<(u64, String, bool), StoreError> {
|
||||
LedgerError::reference_text("the file name", file_name)?;
|
||||
if let Some(d) = description {
|
||||
LedgerError::free_text("the description", d)?;
|
||||
}
|
||||
self.attach(AttachRequest {
|
||||
line_type: "receipt.attached",
|
||||
category: "receipts",
|
||||
@@ -4794,6 +4833,10 @@ impl Store {
|
||||
bytes: &[u8],
|
||||
description: Option<&str>,
|
||||
) -> Result<(u64, String, bool), StoreError> {
|
||||
LedgerError::reference_text("the file name", file_name)?;
|
||||
if let Some(d) = description {
|
||||
LedgerError::free_text("the description", d)?;
|
||||
}
|
||||
self.attach(AttachRequest {
|
||||
line_type: "document.filed",
|
||||
category,
|
||||
@@ -5691,6 +5734,7 @@ impl Store {
|
||||
if reason.is_empty() {
|
||||
return Err(StoreError::ReasonRequired);
|
||||
}
|
||||
LedgerError::free_text("the reason", reason)?;
|
||||
let (entry_id, withdrawn) = self.attachment_state(attachment_id)?;
|
||||
if withdrawn {
|
||||
return Err(StoreError::AttachmentWithdrawn(attachment_id));
|
||||
@@ -5759,6 +5803,7 @@ impl Store {
|
||||
if reason.is_empty() {
|
||||
return Err(StoreError::ReasonRequired);
|
||||
}
|
||||
LedgerError::free_text("the reason", reason)?;
|
||||
self.check_linkable(attachment_id)?;
|
||||
if let Some(sub) = self.attachment_links(attachment_id)?.first() {
|
||||
return Err(StoreError::AlreadyLinked(attachment_id, sub.describe()));
|
||||
@@ -5935,6 +5980,7 @@ impl Store {
|
||||
if reason.is_empty() {
|
||||
return Err(StoreError::ReasonRequired);
|
||||
}
|
||||
LedgerError::free_text("the reason", reason)?;
|
||||
self.attachment_state(attachment_id)?;
|
||||
let linked = self
|
||||
.conn
|
||||
@@ -6064,6 +6110,7 @@ impl Store {
|
||||
if reason.is_empty() {
|
||||
return Err(StoreError::ReasonRequired);
|
||||
}
|
||||
LedgerError::free_text("the reason", reason)?;
|
||||
if self.statement(attachment_id)?.is_none() {
|
||||
return Err(StoreError::InvalidStatement(format!(
|
||||
"attachment {attachment_id} records no statement"
|
||||
@@ -6214,6 +6261,7 @@ impl Store {
|
||||
if reason.is_empty() {
|
||||
return Err(StoreError::ReasonRequired);
|
||||
}
|
||||
LedgerError::free_text("the reason", reason)?;
|
||||
let r = self
|
||||
.reconciliations(None)?
|
||||
.into_iter()
|
||||
@@ -6813,9 +6861,11 @@ impl Store {
|
||||
.conn
|
||||
.prepare("SELECT asset_id, tag FROM asset_tags_log ORDER BY seq")?;
|
||||
let tags = tstmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))?;
|
||||
// History is read, not asked for: a tag or a serial number the books
|
||||
// hold reads back whatever shape it has (BS-entry-4; WB-partner-15).
|
||||
for t in tags {
|
||||
let (id, tag) = t?;
|
||||
ledger.set_asset_tag(id as u64, &tag)?;
|
||||
ledger_core::parties::replaying(|| ledger.set_asset_tag(id as u64, &tag))?;
|
||||
}
|
||||
let mut sstmt = self
|
||||
.conn
|
||||
@@ -6823,7 +6873,7 @@ impl Store {
|
||||
let serials = sstmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))?;
|
||||
for row in serials {
|
||||
let (id, serial) = row?;
|
||||
ledger.set_asset_serial(id as u64, Some(&serial))?;
|
||||
ledger_core::parties::replaying(|| ledger.set_asset_serial(id as u64, Some(&serial)))?;
|
||||
}
|
||||
// Basis records: a pre-P3 one (no value at contribution) as its
|
||||
// event replays, a newer one with its facts.
|
||||
|
||||
@@ -301,6 +301,77 @@ fn stale_head_period_attestation_refused() {
|
||||
s.verify().unwrap();
|
||||
}
|
||||
|
||||
/// BS-partner-2 (WB-partner-15): the store's own texts (a file's name and
|
||||
/// description, the reasons for unlinking, withdrawing and voiding, an
|
||||
/// attestation's note, an entry's description) meet the one free-text check
|
||||
/// before anything is journaled, whoever calls.
|
||||
#[test]
|
||||
fn the_store_refuses_text_that_looks_like_a_tax_id_and_journals_nothing() {
|
||||
use ledger_core::LedgerError;
|
||||
let dir = test_dir("tin-text");
|
||||
let (mut s, fx) = books(&dir, None);
|
||||
let tin = "000-00-0000";
|
||||
let refused = |r: Result<(), StoreError>, what: &str| match r {
|
||||
Err(StoreError::Ledger(LedgerError::FreeTextHoldsTin(why))) => {
|
||||
assert!(!why.contains("0000"), "{what}: never the number: {why}");
|
||||
}
|
||||
other => panic!("{what}: expected a refusal for the tax id, got {other:?}"),
|
||||
};
|
||||
let (att, _, _) = s
|
||||
.attach_receipt(Some(fx.entry), "r.txt", "text/plain", b"paper 40.00", None)
|
||||
.unwrap();
|
||||
let head = s.head();
|
||||
refused(
|
||||
s.attach_receipt(
|
||||
None,
|
||||
"s.txt",
|
||||
"text/plain",
|
||||
b"other",
|
||||
Some(&format!("paid {tin}")),
|
||||
)
|
||||
.map(drop),
|
||||
"a description",
|
||||
);
|
||||
refused(
|
||||
s.attach_receipt(None, &format!("w9 {tin}.txt"), "text/plain", b"other", None)
|
||||
.map(drop),
|
||||
"a file name",
|
||||
);
|
||||
refused(
|
||||
s.file_document(
|
||||
"tax",
|
||||
"t.txt",
|
||||
"text/plain",
|
||||
b"doc",
|
||||
Some(&format!("ein {tin}")),
|
||||
)
|
||||
.map(drop),
|
||||
"a document's description",
|
||||
);
|
||||
refused(
|
||||
s.unlink_receipt(att, &format!("dup {tin}")).map(drop),
|
||||
"an unlink reason",
|
||||
);
|
||||
refused(
|
||||
s.withdraw_attachment(att, &format!("dup {tin}")),
|
||||
"a withdraw reason",
|
||||
);
|
||||
refused(
|
||||
s.create_entry(d(2, 1), &format!("x {tin}")).map(drop),
|
||||
"an entry description",
|
||||
);
|
||||
refused(
|
||||
s.reverse_entry(fx.entry, d(2, 1), &format!("x {tin}"))
|
||||
.map(drop),
|
||||
"a reversal",
|
||||
);
|
||||
let mut c = claim("high");
|
||||
c.note = Some(format!("see {tin}"));
|
||||
refused(s.review_entry(fx.entry, c).map(drop), "an attestation note");
|
||||
assert_eq!(s.head(), head, "a refusal journals nothing");
|
||||
s.verify().unwrap();
|
||||
}
|
||||
|
||||
/// The integrity table: each code seeded alone.
|
||||
#[test]
|
||||
fn integrity_detects_each_seeded_defect() {
|
||||
@@ -362,6 +433,43 @@ fn integrity_detects_each_seeded_defect() {
|
||||
drop(w);
|
||||
Store::open(&dir).unwrap().integrity_findings()
|
||||
}
|
||||
"tax_id_in_journal" => {
|
||||
// A line an earlier version took: its description holds an
|
||||
// SSN's shape. The books open on it all the same, and the
|
||||
// audit says where it is, never what.
|
||||
let next = s.ledger().next_entry_id();
|
||||
drop(s);
|
||||
let mut w = JournalWriter::open(&dir.join(JOURNAL_FILE)).unwrap();
|
||||
w.append(
|
||||
"entry.created",
|
||||
json!({"id": next, "date": "2026-03-01", "description": "paid 000-00-0000 in cash"}),
|
||||
)
|
||||
.unwrap();
|
||||
drop(w);
|
||||
let s = Store::open(&dir).expect("books holding such a line still open");
|
||||
s.verify().expect("and still verify");
|
||||
let found = s.integrity_findings();
|
||||
let f = found
|
||||
.iter()
|
||||
.find(|f| f.code == "tax_id_in_journal")
|
||||
.expect("found");
|
||||
assert!(f.message.contains("`description`"), "{}", f.message);
|
||||
assert!(
|
||||
f.message.contains(&format!(
|
||||
"journal line {}",
|
||||
f.subject.describe().rsplit(' ').next().unwrap()
|
||||
)),
|
||||
"{}",
|
||||
f.message
|
||||
);
|
||||
assert!(
|
||||
!f.message.contains("0000"),
|
||||
"never the number: {}",
|
||||
f.message
|
||||
);
|
||||
assert!(f.message.contains("books.set_tin"), "{}", f.message);
|
||||
found
|
||||
}
|
||||
"access_log_damaged" => {
|
||||
std::fs::write(
|
||||
dir.join("access.jsonl"),
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
//! Text the books already hold is never refused when the program writes it
|
||||
//! again (BS-partner-2, WB-partner-15; BS-entry-4): an asset an earlier
|
||||
//! version took, whose description holds a number that reads as a tax id,
|
||||
//! still depreciates and is still disposed of; the lines the program
|
||||
//! composes from it hold the masked form. And a payment's reference of
|
||||
//! nine digits is kept, shown masked in the entry's description, and is no
|
||||
//! finding of the audit.
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use ledger_core::{AccountType, Currency, Money};
|
||||
use ledger_store::{JOURNAL_FILE, JournalWriter, Store};
|
||||
use rust_decimal::Decimal;
|
||||
use serde_json::json;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn usd(amount: &str) -> Money {
|
||||
Money::new(amount.parse().unwrap(), Currency::USD)
|
||||
}
|
||||
|
||||
fn date(y: i32, m: u32, d: u32) -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
struct Accounts {
|
||||
cost: u64,
|
||||
accum: u64,
|
||||
expense: u64,
|
||||
bank: u64,
|
||||
gain: u64,
|
||||
}
|
||||
|
||||
fn accounts(store: &mut Store) -> Accounts {
|
||||
let mut add = |code: &str, name: &str, t: AccountType| {
|
||||
store.add_account(code, name, t, None, false).unwrap()
|
||||
};
|
||||
Accounts {
|
||||
cost: add("1500", "Equipment", AccountType::Asset),
|
||||
accum: add("1501", "Accumulated Depreciation", AccountType::Asset),
|
||||
expense: add("6100", "Depreciation Expense", AccountType::Expense),
|
||||
bank: add("1000", "Bank", AccountType::Asset),
|
||||
gain: add("4900", "Gain on Disposal", AccountType::Revenue),
|
||||
}
|
||||
}
|
||||
|
||||
/// Books with two assets an earlier version took: one whose description
|
||||
/// holds a bare run of nine digits (a serial number), one an SSN's shape.
|
||||
/// They are written to the journal as that version wrote them: the engine
|
||||
/// refuses such a description now, whoever asks.
|
||||
fn old_books() -> (tempfile::TempDir, Store, Accounts, [u64; 2]) {
|
||||
let dir = tempdir().unwrap();
|
||||
let mut store = Store::create(dir.path(), Currency::USD).unwrap();
|
||||
let a = accounts(&mut store);
|
||||
let first = store.ledger().next_asset_id();
|
||||
drop(store);
|
||||
let mut w = JournalWriter::open(&dir.path().join(JOURNAL_FILE)).unwrap();
|
||||
for (id, description) in [
|
||||
(first, "MacBook SN 000000000"),
|
||||
(first + 1, "Laptop 000-00-0000 kit"),
|
||||
] {
|
||||
w.append(
|
||||
"asset.registered",
|
||||
json!({
|
||||
"id": id,
|
||||
"description": description,
|
||||
"purchase_date": "2026-01-15",
|
||||
"cost": {"amount": "1200.00", "currency": "USD"},
|
||||
"salvage_value": {"amount": "0", "currency": "USD"},
|
||||
"useful_life_months": 12,
|
||||
"method": "straight_line",
|
||||
"cost_account": a.cost,
|
||||
"accum_depr_account": a.accum,
|
||||
"expense_account": a.expense,
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
drop(w);
|
||||
let store = Store::open(dir.path()).expect("books holding such an asset open");
|
||||
store.verify().expect("and verify");
|
||||
(dir, store, a, [first, first + 1])
|
||||
}
|
||||
|
||||
/// An asset whose description holds the shape depreciates: the entry is
|
||||
/// written, its description holds the shape masked, and the books verify.
|
||||
#[test]
|
||||
fn an_old_asset_still_depreciates() {
|
||||
let (_dir, mut store, _, [bare, grouped]) = old_books();
|
||||
let run = store.run_depreciation(bare, "2026-02").unwrap();
|
||||
let entry = store.ledger().get_entry(run.entry_id.unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
entry.description(),
|
||||
"Depreciation — MacBook SN \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000 — 2026-02"
|
||||
);
|
||||
let run = store.run_depreciation(grouped, "2026-02").unwrap();
|
||||
let entry = store.ledger().get_entry(run.entry_id.unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
entry.description(),
|
||||
"Depreciation — Laptop \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 kit — 2026-02"
|
||||
);
|
||||
store.verify().unwrap();
|
||||
}
|
||||
|
||||
/// ... and is disposed of: the final depreciation's entry and the
|
||||
/// disposal's both hold the masked form.
|
||||
#[test]
|
||||
fn an_old_asset_is_still_disposed_of() {
|
||||
let (dir, mut store, a, [bare, grouped]) = old_books();
|
||||
for (id, masked) in [
|
||||
(
|
||||
bare,
|
||||
"MacBook SN \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000",
|
||||
),
|
||||
(
|
||||
grouped,
|
||||
"Laptop \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 kit",
|
||||
),
|
||||
] {
|
||||
store.run_depreciation(id, "2026-02").unwrap();
|
||||
let on = date(2026, 3, 10);
|
||||
let disposal = store
|
||||
.dispose_asset(id, on, usd("100"), a.bank, a.gain)
|
||||
.unwrap();
|
||||
let disposal = store.ledger().get_entry(disposal).unwrap();
|
||||
assert_eq!(
|
||||
disposal.description(),
|
||||
format!("Disposal — {masked} — {on}")
|
||||
);
|
||||
// The final depreciation is the entry just before it.
|
||||
let final_run = store.ledger().get_entry(disposal.id() - 1).unwrap();
|
||||
assert_eq!(
|
||||
final_run.description(),
|
||||
format!("Depreciation — {masked} — 2026-03 (final)")
|
||||
);
|
||||
assert!(matches!(
|
||||
store.ledger().get_asset(id).unwrap().status,
|
||||
ledger_core::AssetStatus::Disposed { .. }
|
||||
));
|
||||
}
|
||||
store.verify().unwrap();
|
||||
// The books open again, as they were written.
|
||||
drop(store);
|
||||
let again = Store::open(dir.path()).unwrap();
|
||||
again.verify().unwrap();
|
||||
assert_eq!(
|
||||
again.ledger().get_asset(bare).unwrap().description,
|
||||
"MacBook SN 000000000"
|
||||
);
|
||||
}
|
||||
|
||||
/// The text of such an asset is not repeated in a line the audit would
|
||||
/// then name: the lines the program wrote hold no number that reads as a
|
||||
/// tax id, so the audit names only the line an earlier version wrote.
|
||||
#[test]
|
||||
fn what_the_program_writes_again_is_no_finding() {
|
||||
let (_dir, mut store, a, [bare, _]) = old_books();
|
||||
store.run_depreciation(bare, "2026-02").unwrap();
|
||||
store
|
||||
.dispose_asset(bare, date(2026, 3, 10), usd("100"), a.bank, a.gain)
|
||||
.unwrap();
|
||||
let found: Vec<String> = store
|
||||
.integrity_findings()
|
||||
.into_iter()
|
||||
.filter(|f| f.code == "tax_id_in_journal")
|
||||
.map(|f| f.message)
|
||||
.collect();
|
||||
// Two lines are the earlier version's (the two assets, whose
|
||||
// description the journal holds as written); none is the program's.
|
||||
assert_eq!(found.len(), 2, "{found:?}");
|
||||
assert!(
|
||||
found.iter().all(|m| m.contains("(asset.registered)")),
|
||||
"{found:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A payment reference of nine digits is a check or confirmation number:
|
||||
/// kept whole as the reference, shown masked in the entry's description,
|
||||
/// and no finding of the audit; a printed tax id is refused before
|
||||
/// anything is journaled.
|
||||
#[test]
|
||||
fn a_nine_digit_payment_reference_is_kept_and_is_no_finding() {
|
||||
let dir = tempdir().unwrap();
|
||||
let mut store = Store::create(dir.path(), Currency::USD).unwrap();
|
||||
let a = accounts(&mut store);
|
||||
let customer = store.add_customer("Acme").unwrap();
|
||||
let invoice = store
|
||||
.create_invoice(
|
||||
customer,
|
||||
date(2026, 3, 1),
|
||||
date(2026, 3, 31),
|
||||
vec![ledger_core::arap::DocumentLine {
|
||||
description: "work".into(),
|
||||
amount: Decimal::from(100),
|
||||
class_id: None,
|
||||
account: None,
|
||||
quantity: None,
|
||||
unit_price: None,
|
||||
}],
|
||||
)
|
||||
.unwrap();
|
||||
let head = store.head();
|
||||
let pay = |store: &mut Store, reference: &str| {
|
||||
store.receive_payment_with(
|
||||
invoice,
|
||||
date(2026, 3, 5),
|
||||
Decimal::from(10),
|
||||
a.bank,
|
||||
&ledger_core::PaymentDetails {
|
||||
instrument: None,
|
||||
reference: Some(reference.into()),
|
||||
},
|
||||
)
|
||||
};
|
||||
assert!(pay(&mut store, "000-00-0000").is_err());
|
||||
assert_eq!(store.head(), head, "a refusal journals nothing");
|
||||
let entry = pay(&mut store, "123456789").unwrap();
|
||||
assert_eq!(
|
||||
store.ledger().get_entry(entry).unwrap().description(),
|
||||
"Payment on invoice 1 (ref \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}6789)"
|
||||
);
|
||||
let found: Vec<String> = store
|
||||
.integrity_findings()
|
||||
.into_iter()
|
||||
.filter(|f| f.code == "tax_id_in_journal")
|
||||
.map(|f| f.message)
|
||||
.collect();
|
||||
assert!(found.is_empty(), "{found:?}");
|
||||
store.verify().unwrap();
|
||||
}
|
||||
|
||||
/// The audit reads each journal field as its class: a reference (a tag, a
|
||||
/// serial, a file name, an invoice number) may be nine digits, free words
|
||||
/// may not, and a printed shape is a finding in either.
|
||||
#[test]
|
||||
fn the_audit_reads_a_reference_as_a_reference() {
|
||||
let dir = tempdir().unwrap();
|
||||
let mut store = Store::create(dir.path(), Currency::USD).unwrap();
|
||||
let a = accounts(&mut store);
|
||||
let asset = store
|
||||
.register_asset(ledger_core::NewAsset {
|
||||
description: "Van".into(),
|
||||
in_service_date: date(2026, 1, 15),
|
||||
cost: usd("1200"),
|
||||
salvage_value: usd("0"),
|
||||
useful_life_months: 12,
|
||||
cost_account: a.cost,
|
||||
accum_depr_account: a.accum,
|
||||
expense_account: a.expense,
|
||||
})
|
||||
.unwrap();
|
||||
let next = store.ledger().next_entry_id();
|
||||
drop(store);
|
||||
let mut w = JournalWriter::open(&dir.path().join(JOURNAL_FILE)).unwrap();
|
||||
// Nine digits as a tag: a reference. As the words of an entry: a finding.
|
||||
w.append(
|
||||
"asset.tagged",
|
||||
json!({"asset_id": asset, "tag": "123456789", "previous_tag": null}),
|
||||
)
|
||||
.unwrap();
|
||||
w.append(
|
||||
"entry.created",
|
||||
json!({"id": next, "date": "2026-03-01", "description": "paid 123456789"}),
|
||||
)
|
||||
.unwrap();
|
||||
// A printed shape in a tag is a finding too.
|
||||
w.append(
|
||||
"asset.tagged",
|
||||
json!({"asset_id": asset, "tag": "T-000-00-0000", "previous_tag": "123456789"}),
|
||||
)
|
||||
.unwrap();
|
||||
drop(w);
|
||||
let store = Store::open(dir.path()).unwrap();
|
||||
store.verify().unwrap();
|
||||
let fields: Vec<String> = store
|
||||
.integrity_findings()
|
||||
.into_iter()
|
||||
.filter(|f| f.code == "tax_id_in_journal")
|
||||
.map(|f| f.message)
|
||||
.collect();
|
||||
assert_eq!(fields.len(), 2, "{fields:?}");
|
||||
assert!(
|
||||
fields[0].contains("(entry.created)") && fields[0].contains("`description`"),
|
||||
"{fields:?}"
|
||||
);
|
||||
assert!(
|
||||
fields[1].contains("(asset.tagged)") && fields[1].contains("`tag`"),
|
||||
"{fields:?}"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user