fix(core): free text's detector reads a dot, a longer run, a line break and invisible characters, and a reference takes nine digits

A dot joins an SSN's groups only when it joins both (000.00.0000), never an
EIN's: a coordinate such as 47.6062095 is a number, not a tax id. A group
that starts or ends inside a longer run of digits and dashes (a date's day
then its reference, a part number) belongs to that run. A line break reads
as a space and zero-width and soft-hyphen characters are not counted, as the
strict party reading already has it. The reading is one detector with a
parameter: a reference (tag, serial, invoice or payment reference, account
code, label, where a W-9 or W-4 is kept) drops the bare-nine group, since a
serial or a check number is nine digits. The engine now also refuses a
payment's reference (printed shapes) and a discount's reason (free text),
which only the tools' table covered; a payment entry's description, free
text, shows the reference masked. A project's field has an engine-level test.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 16:12:59 -07:00
1 parent 657daf43da
commit dd5f1befd6
8 files changed
+604 -78

No files matched your search

+21 -11
View File
@@ -399,24 +399,32 @@ pub const MAX_REFERENCE_CHARS: usize = 200;
impl PaymentDetails {
/// The payment entry's description: `base`, then the reference when
/// there is one (`base (ref R)`).
/// there is one (`base (ref R)`), with a run of nine digits in it masked
/// to its last four: the reference is kept whole in the payment's own
/// record, and an entry's description is free text, which holds no
/// number that reads as a tax id (WB-partner-15).
pub fn description(&self, base: &str) -> String {
match self.reference.as_deref().map(str::trim) {
Some(r) if !r.is_empty() => format!("{base} (ref {r})"),
Some(r) if !r.is_empty() => {
format!("{base} (ref {})", crate::settings::mask_printed_tins(r))
}
_ => base.to_string(),
}
}
/// Refuse a reference that isn't one line of at most
/// [`MAX_REFERENCE_CHARS`] characters. A blank one is none. (A bank
/// trace number is fifteen digits, so no nine-digit scan here.)
/// [`MAX_REFERENCE_CHARS`] characters, or one that looks like a tax id's
/// printed SSN or EIN (a bare nine digits is a check or confirmation
/// number: a reference's reading, WB-partner-15; not in a replay,
/// BS-entry-4). A blank one is none.
pub fn check(&self) -> Result<(), LedgerError> {
if let Some(r) = &self.reference
&& (r.contains(['\n', '\r']) || r.chars().count() > MAX_REFERENCE_CHARS)
{
return Err(LedgerError::InvalidPayment(format!(
"a payment's reference is one line of at most {MAX_REFERENCE_CHARS} characters"
)));
if let Some(r) = &self.reference {
if r.contains(['\n', '\r']) || r.chars().count() > MAX_REFERENCE_CHARS {
return Err(LedgerError::InvalidPayment(format!(
"a payment's reference is one line of at most {MAX_REFERENCE_CHARS} characters"
)));
}
LedgerError::reference_text("the payment reference", r)?;
}
Ok(())
}
@@ -1263,7 +1271,6 @@ pub fn check_document_text(
duplicate_reason: Option<&str>,
) -> Result<(), LedgerError> {
for (field, text) in [
("the reference", reference),
("the memo", memo),
("the duplicate reason", duplicate_reason),
] {
@@ -1271,6 +1278,9 @@ pub fn check_document_text(
LedgerError::free_text(field, t)?;
}
}
if let Some(t) = reference {
LedgerError::reference_text("the reference", t)?;
}
Ok(())
}
+7
View File
@@ -1008,6 +1008,13 @@ impl LedgerError {
pub fn free_text(field: &str, text: &str) -> Result<(), LedgerError> {
crate::settings::check_free_text(field, text).map_err(LedgerError::FreeTextHoldsTin)
}
/// [`Self::free_text`] for a reference (a tag, a serial, a payment's or
/// an invoice's reference, an account code, a file name): a bare nine
/// digits is allowed ([`crate::settings::check_reference_text`]).
pub fn reference_text(field: &str, text: &str) -> Result<(), LedgerError> {
crate::settings::check_reference_text(field, text).map_err(LedgerError::FreeTextHoldsTin)
}
}
/// The refusal [`LedgerError::TaxCategoryRequired`] gives: what to pass,
+4 -3
View File
@@ -127,10 +127,11 @@ pub struct Instrument {
pub account: AccountId,
}
/// Check a label: one line, at most `MAX_TEXT` characters, no full TIN
/// (INVARIANT 1, all but uniqueness). Returns it trimmed.
/// Check a label: one line, at most `MAX_TEXT` characters, no printed SSN or
/// EIN (INVARIANT 1, all but uniqueness; a label is a reference, so a bare
/// nine digits is allowed, WB-partner-15). Returns it trimmed.
pub fn check_label(label: &str) -> Result<String, String> {
crate::settings::line_text("label", label, crate::settings::MAX_TEXT)
crate::settings::reference_line_text("label", label, crate::settings::MAX_TEXT)
}
/// Check a last four (INVARIANT 2).
+8 -5
View File
@@ -1024,7 +1024,7 @@ impl Ledger {
if code.trim().is_empty() {
return Err(LedgerError::EmptyAccountCode);
}
LedgerError::free_text("the account code", code)?;
LedgerError::reference_text("the account code", code)?;
let name = name.trim();
if name.is_empty() {
return Err(LedgerError::EmptyAccountName);
@@ -1295,7 +1295,7 @@ impl Ledger {
if code.trim().is_empty() {
return Err(LedgerError::EmptyAccountCode);
}
LedgerError::free_text("the account code", code)?;
LedgerError::reference_text("the account code", code)?;
if self.chart.find_by_code(code).is_some() {
return Err(LedgerError::DuplicateAccountCode(code.to_string()));
}
@@ -2773,7 +2773,7 @@ impl Ledger {
tag: tag.to_string(),
why,
})?;
LedgerError::free_text("the asset tag", tag)?;
LedgerError::reference_text("the asset tag", tag)?;
match self.asset_tags.get(&assets::tag_key(tag)) {
Some(&holder) if Some(holder) != id => Err(LedgerError::AssetTagTaken {
tag: tag.to_string(),
@@ -2810,7 +2810,7 @@ impl Ledger {
}
if let Some(s) = serial {
assets::check_serial(s).map_err(LedgerError::InvalidSerial)?;
LedgerError::free_text("the serial number", s)?;
LedgerError::reference_text("the serial number", s)?;
}
Ok(())
}
@@ -6220,7 +6220,7 @@ impl Ledger {
crate::parties::check_text("a recipient", to).map_err(LedgerError::InvalidSend)?;
}
if let Some(reference) = &sent.reference {
crate::parties::check_note("the reference", reference)
crate::parties::check_reference_note("the reference", reference)
.map_err(LedgerError::InvalidSend)?;
}
if let Some(note) = &sent.note {
@@ -6785,6 +6785,9 @@ impl Ledger {
arap::MAX_REFERENCE_CHARS,
));
}
if let Some(reason) = &app.discount_reason {
LedgerError::free_text("the discount reason", reason)?;
}
if app.discount > Decimal::ZERO {
self.check_discount(app, kind, total, doc_date, params.date)?;
}
+19 -5
View File
@@ -416,7 +416,7 @@ fn tin_separator(c: char) -> bool {
/// right-to-left marks and the other directional formatting characters,
/// the word joiner, the byte-order mark, the variation selectors, the tags
/// and the fillers. None is ASCII.
fn tin_invisible(c: char) -> bool {
pub(crate) fn tin_invisible(c: char) -> bool {
matches!(
c,
'\u{AD}'
@@ -720,10 +720,22 @@ pub fn check_text(field: &str, text: &str) -> Result<(), String> {
/// Check a free text field: no tax id's shape (a nine-digit number standing
/// alone, an SSN's 3-2-4, an EIN's 2-7: [`crate::settings::check_free_text`]),
/// at most 500 characters, no control characters except newline. For a
/// memo, a note, a reason or a reference; a party's own fields keep the
/// strict [`check_text`] (BS-partner-2; the owner's choice, 2026-11-21).
/// memo, a note or a reason; a party's own fields keep the strict
/// [`check_text`] (BS-partner-2; the owner's choice, 2026-11-21).
pub fn check_note(field: &str, text: &str) -> Result<(), String> {
crate::settings::check_free_text(field, text)?;
check_note_form(field, text)
}
/// [`check_note`] for a reference (a payment's or a send's reference, a
/// file's location): only the grouped shapes are refused, a bare nine
/// digits is allowed ([`crate::settings::check_reference_text`]).
pub fn check_reference_note(field: &str, text: &str) -> Result<(), String> {
crate::settings::check_reference_text(field, text)?;
check_note_form(field, text)
}
fn check_note_form(field: &str, text: &str) -> Result<(), String> {
if text.chars().count() > 500 {
return Err(format!("{field} is at most 500 characters"));
}
@@ -762,12 +774,14 @@ impl W9Facts {
("entity_type", Some(self.entity_type.as_str())),
("exempt_payee_code", self.exempt_payee_code.as_deref()),
("fatca_code", self.fatca_code.as_deref()),
("kept_at", Some(self.kept_at.as_str())),
] {
if let Some(t) = t {
check_text(f, t)?;
}
}
// Where the paper is kept is a reference (a binder, a portal, a
// file name): a bare nine digits is allowed (WB-partner-15).
check_reference_note("kept_at", &self.kept_at)?;
if let Some(h) = &self.vault_record
&& (h.len() != 64 || !h.chars().all(|c| c.is_ascii_hexdigit()))
{
@@ -786,7 +800,7 @@ impl W4Facts {
if self.kept_at.trim().is_empty() {
return Err("say where the W-4 itself is kept".into());
}
check_text("kept_at", &self.kept_at)
check_reference_note("kept_at", &self.kept_at)
}
}
+163 -41
View File
@@ -713,32 +713,50 @@ pub fn decimal(s: &str) -> Option<Decimal> {
/// Whether `text` holds a number that reads as a full TIN (INVARIANT 4):
/// nine digits standing alone (no digit right before or after), bare or
/// printed the way an SSN (3-2-4) or an EIN (2-7) is, the groups joined by
/// a hyphen or any other dash, a dot, or a space (or a dash with spaces
/// around it), whatever Unicode form the dash, dot, space or digit takes
/// (full-width, Arabic-Indic, no-break space, en space, ...).
/// a hyphen or any other dash, or a space (or a dash with spaces around
/// it), whatever Unicode form the dash, space or digit takes (full-width,
/// Arabic-Indic, no-break space, en space, a line break, ...), with
/// zero-width and soft-hyphen characters not counted. A dot joins an SSN's
/// groups only when it joins both (`000.00.0000`), never an EIN's, so a
/// coordinate (`47.6062095`) is no tax id.
///
/// ```text
/// GOAL: the one test free text meets before it is kept: it refuses what
/// looks like a tax id and nothing else.
/// SOURCE: BS-partner-2 (no full TIN in the books); wanderbooks' CHOICE on
/// it (the owner, 2026-11-21: shapes on free text, strict on party
/// fields, masking on bank imports), WB-partner-15.
/// fields, masking on bank imports; a reference field allows a
/// bare nine digits, decided by the lead the same day within that
/// choice), WB-partner-15.
/// INVARIANTS:
/// 1. Nine digits standing alone, an SSN's 3-2-4 and an EIN's 2-7 are
/// found, with any dash, dot or space (Unicode forms too) between
/// the groups.
/// found, with any dash or space (Unicode forms and line breaks
/// too) between the groups, and a dot between all of an SSN's.
/// 2. An invoice number (`2026-11-0042`), a phone number, an order
/// number, a reference of ten digits or more, an amount with comma
/// groups and a date are not found.
/// 3. During a replay ([`crate::parties::replaying`]) the Unicode forms
/// are not read, so a line an earlier version took still replays
/// (BS-entry-4).
/// groups, a date, a date followed by a reference
/// (`2026-11-21 0001234`) and a decimal (`47.6062095`) are not found.
/// 3. A group that starts or ends inside a longer run of digits and
/// dashes (a digit and a dash before its first digit, or a dash and a
/// digit after its last) is part of that run, not a tax id.
/// 4. During a replay ([`crate::parties::replaying`]) the Unicode forms,
/// line breaks and invisible characters are not read, so a line an
/// earlier version took still replays (BS-entry-4).
/// SCENARIOS:
/// 1. IF a memo says `paid 000-00-0000`: SHOULD be found.
/// 2. IF it says `inv 2026-11-0042`: SHOULD NOT be.
/// 3. IF it says `at 47.6062095`: SHOULD NOT be.
/// ```
pub fn holds_printed_tin(text: &str) -> bool {
!printed_tin_spans(text, false).1.is_empty()
!printed_tin_spans(text, Reading::Free).1.is_empty()
}
/// [`holds_printed_tin`] for a reference (an asset tag, a serial number, an
/// invoice or bill number, a payment reference, an account code, a file
/// name): a bare run of nine digits is a legitimate number there, so only
/// the printed SSN (3-2-4) and EIN (2-7) forms count (WB-partner-15).
pub fn holds_printed_tin_in_reference(text: &str) -> bool {
!printed_tin_spans(text, Reading::Reference).1.is_empty()
}
/// [`holds_printed_tin`] for a web address: the printed SSN (3-2-4) and
@@ -747,16 +765,27 @@ pub fn holds_printed_tin(text: &str) -> bool {
/// id in a path or query (an app store listing's `id284882215`), not a
/// TIN someone wrote down (BS-partner-2).
pub fn holds_printed_tin_in_link(text: &str) -> bool {
!printed_tin_spans(text, true).1.is_empty()
!printed_tin_spans(text, Reading::Link).1.is_empty()
}
/// `text` with every number [`holds_printed_tin`] finds masked down to its
/// last four digits: every other digit becomes `•`, the separators stay
/// (`•••-••-0000`), the form the books show a TIN in everywhere else. For
/// text that is not typed by a person and must be kept (a bank's
/// description of a transaction), never for a refusal's words.
/// description of a transaction, a line the program composes from text the
/// books already hold), never for a refusal's words.
pub fn mask_printed_tins(text: &str) -> std::borrow::Cow<'_, str> {
let (mut chars, spans) = printed_tin_spans(text, false);
mask_spans(text, Reading::Free)
}
/// [`mask_printed_tins`] for a reference ([`holds_printed_tin_in_reference`]):
/// a bare run of nine digits stays.
pub fn mask_printed_tins_in_reference(text: &str) -> std::borrow::Cow<'_, str> {
mask_spans(text, Reading::Reference)
}
fn mask_spans(text: &str, reading: Reading) -> std::borrow::Cow<'_, str> {
let (mut chars, spans) = printed_tin_spans(text, reading);
if spans.is_empty() {
return std::borrow::Cow::Borrowed(text);
}
@@ -772,7 +801,19 @@ pub fn mask_printed_tins(text: &str) -> std::borrow::Cow<'_, str> {
/// How many numbers [`holds_printed_tin`] finds in `text`.
pub fn count_printed_tins(text: &str) -> usize {
printed_tin_spans(text, false).1.len()
printed_tin_spans(text, Reading::Free).1.len()
}
/// What [`printed_tin_spans`] looks for.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Reading {
/// Free text: nine digits alone, an SSN's 3-2-4, an EIN's 2-7.
Free,
/// A reference: the grouped shapes only.
Reference,
/// A web address: free text, but a bare nine digits joined to a letter
/// or URL punctuation is an id in a path.
Link,
}
/// A character that stands for a digit: ASCII, full-width, or any other
@@ -783,13 +824,20 @@ fn digit_like(ch: char, extended: bool) -> bool {
}
/// A space between a TIN's groups: the plain one, and outside a replay
/// the tab and every Unicode space separator.
/// the tab, a line break and every Unicode space separator.
fn tin_space(ch: char, extended: bool) -> bool {
ch == ' '
|| (extended
&& matches!(
ch,
'\t' | '\u{a0}' | '\u{1680}' | '\u{2000}'
'\t' | '\n'
| '\r'
| '\u{85}'
| '\u{2028}'
| '\u{2029}'
| '\u{a0}'
| '\u{1680}'
| '\u{2000}'
..='\u{200a}' | '\u{202f}' | '\u{205f}' | '\u{3000}'
))
}
@@ -815,21 +863,39 @@ fn tin_dash(ch: char, extended: bool) -> bool {
))
}
/// The dots among [`tin_dash`]'s characters.
fn tin_dot(ch: char) -> bool {
matches!(ch, '.' | '\u{2024}' | '\u{ff0e}')
}
/// The characters of `text` and the runs ([from, to) in characters) of it
/// that read as a full TIN, non-overlapping, left to right.
fn printed_tin_spans(text: &str, link: bool) -> (Vec<char>, Vec<(usize, usize)>) {
fn printed_tin_spans(text: &str, reading: Reading) -> (Vec<char>, Vec<(usize, usize)>) {
let extended = !crate::parties::is_replaying();
let c: Vec<char> = text.chars().collect();
let all: Vec<char> = text.chars().collect();
// What is read: outside a replay, the zero-width and soft-hyphen
// characters are not there (`1\u{200B}2` shows as `12`). `seen[i]` is
// where the i-th character read sits in `all`.
let seen: Vec<usize> = (0..all.len())
.filter(|&i| !(extended && crate::parties::tin_invisible(all[i])))
.collect();
let c: Vec<char> = seen.iter().map(|&i| all[i]).collect();
let digit = |i: usize| c.get(i).is_some_and(|&ch| digit_like(ch, extended));
// A hyphen or other dash, the dot not counted.
let hyphen = |i: usize| {
c.get(i)
.is_some_and(|&ch| tin_dash(ch, extended) && !tin_dot(ch))
};
// A joiner at `i`: a dash, dot or space, or a dash with spaces around
// it; returns where the next group starts.
let joiner = |i: usize| -> Option<usize> {
// it; returns where the next group starts, and whether it is a dot.
let joiner = |i: usize| -> Option<(usize, bool)> {
let mut j = i;
while c.get(j).is_some_and(|&ch| tin_space(ch, extended)) {
j += 1;
}
let mut dashes = 0;
let (mut dashes, mut dotted) = (0, false);
while c.get(j).is_some_and(|&ch| tin_dash(ch, extended)) {
dotted |= tin_dot(c[j]);
j += 1;
dashes += 1;
}
@@ -837,13 +903,16 @@ fn printed_tin_spans(text: &str, link: bool) -> (Vec<char>, Vec<(usize, usize)>)
j += 1;
}
let spaces = j - i - dashes;
(j > i && dashes <= 1 && spaces <= 2).then_some(j)
(j > i && dashes <= 1 && spaces <= 2).then_some((j, dotted))
};
let groups_at = |at: usize, groups: &[usize]| -> Option<usize> {
let mut i = at;
// Where `groups` of digits end from `at`, and how many joiners were dots.
let groups_at = |at: usize, groups: &[usize]| -> Option<(usize, usize)> {
let (mut i, mut dots) = (at, 0);
for (n, g) in groups.iter().enumerate() {
if n > 0 {
i = joiner(i)?;
let (next, dotted) = joiner(i)?;
i = next;
dots += usize::from(dotted);
}
for _ in 0..*g {
if !digit(i) {
@@ -852,12 +921,24 @@ fn printed_tin_spans(text: &str, link: bool) -> (Vec<char>, Vec<(usize, usize)>)
i += 1;
}
}
Some(i)
Some((i, dots))
};
let url_joined = |i: Option<usize>| {
i.and_then(|i| c.get(i))
.is_some_and(|ch| ch.is_alphabetic() || matches!(ch, '/' | '=' | '?' | '&' | '#'))
};
// The text before `at` ends in a digit and a dash: the group is the
// tail of a longer number (a date's day, a part number).
let digit_dash_before = |at: usize| at >= 2 && hyphen(at - 1) && digit(at - 2);
// The text from `end` is a dash and a digit: the group is the head of a
// longer number.
let dash_digit_after = |end: usize| hyphen(end) && digit(end + 1);
// A dot with a digit on each side: a decimal point.
let decimal_point = |i: usize| c.get(i) == Some(&'.') && i >= 1 && digit(i - 1) && digit(i + 1);
let shapes: &[&[usize]] = match reading {
Reading::Reference => &[&[3, 2, 4], &[2, 7]],
Reading::Free | Reading::Link => &[&[9], &[3, 2, 4], &[2, 7]],
};
let mut spans = Vec::new();
let mut at = 0;
while at < c.len() {
@@ -865,25 +946,36 @@ fn printed_tin_spans(text: &str, link: bool) -> (Vec<char>, Vec<(usize, usize)>)
at += 1;
continue;
}
let found = [&[9][..], &[3, 2, 4][..], &[2, 7][..]]
.iter()
.find_map(|g| {
groups_at(at, g).filter(|&end| {
!digit(end)
&& !(link
&& g.len() == 1
&& (url_joined(at.checked_sub(1)) || url_joined(Some(end))))
})
});
let found = shapes.iter().find_map(|g| {
let (end, dots) = groups_at(at, g)?;
if digit(end) {
return None;
}
match g.len() {
// Nine digits alone: not a number in a path (a link), not
// the digits of a decimal.
1 => {
let in_a_path = reading == Reading::Link
&& (url_joined(at.checked_sub(1)) || url_joined(Some(end)));
let in_a_decimal = (at >= 1 && decimal_point(at - 1)) || decimal_point(end);
(!in_a_path && !in_a_decimal).then_some(end)
}
// An EIN: never joined by a dot.
2 => (dots == 0 && !digit_dash_before(at) && !dash_digit_after(end)).then_some(end),
// An SSN: dots at both joiners or at neither.
_ => ((dots == 0 || dots == 2) && !digit_dash_before(at) && !dash_digit_after(end))
.then_some(end),
}
});
match found {
Some(end) => {
spans.push((at, end));
spans.push((seen[at], seen[end - 1] + 1));
at = end;
}
None => at += 1,
}
}
(c, spans)
(all, spans)
}
/// What a refusal says of a field that looks like it holds a tax id
@@ -907,6 +999,19 @@ pub fn check_free_text(field: &str, text: &str) -> Result<(), String> {
Ok(())
}
/// A reference (an asset tag, a serial number, an invoice or bill number, a
/// payment reference, an account code, a file name, a label) that may be
/// kept: it must not look like a tax id's *printed* shapes
/// ([`holds_printed_tin_in_reference`]), a bare run of nine digits being a
/// legitimate number there. Returns why not, in [`tin_refusal`]'s words.
/// Never refuses during a replay (BS-entry-4).
pub fn check_reference_text(field: &str, text: &str) -> Result<(), String> {
if !crate::parties::is_replaying() && holds_printed_tin_in_reference(text) {
return Err(tin_refusal(field));
}
Ok(())
}
fn no_tin(what: &str, s: &str) -> Result<(), String> {
if holds_printed_tin(s) {
return Err(format!(
@@ -924,6 +1029,19 @@ pub fn line_text(what: &str, s: &str, max: usize) -> Result<String, String> {
Ok(t)
}
/// [`line_text`] for a reference (a label): one line, with only the printed
/// SSN and EIN shapes refused, a bare nine digits allowed
/// ([`holds_printed_tin_in_reference`]).
pub fn reference_line_text(what: &str, s: &str, max: usize) -> Result<String, String> {
let t = bare_line_text(what, s, max)?;
if holds_printed_tin_in_reference(&t) {
return Err(format!(
"{what} holds a number that reads as a full SSN or EIN (printed 3-2-4 or 2-7): a full TIN goes only into the vault (books.set_tin or a W-9, books.set_w9); for any other number, write it without that grouping"
));
}
Ok(t)
}
/// [`line_text`] without the full-TIN check: for the one place a nine-digit
/// number is legitimate (an `ach` or `wire` payment method's bank-detail
/// line, where it is a routing number: A-3).
@@ -2207,8 +2325,6 @@ mod tests {
"123-45-6789",
"a 12-3456789.",
"(123-45-6789)",
"1-123-45-6789",
"12-3456789-0",
"123\u{2010}45\u{2010}6789",
"123 45 6789",
"SSN 123456789",
@@ -2222,6 +2338,12 @@ mod tests {
"12-34567890",
"1234567890",
"14745117-0160",
// the tail or head of a longer run of digits and dashes
"1-123-45-6789",
"12-3456789-0",
// a decimal, a date and its reference
"47.6062095",
"2026-11-21 0001234",
"801-555-0142",
"2026-10-04",
"100 Example Way, Midvale, UT 84047",
+375 -12
View File
@@ -11,11 +11,13 @@
//! `00-0000000`; no real one appears here.
use ledger_core::settings::{
check_free_text, count_printed_tins, holds_printed_tin, mask_printed_tins, tin_refusal,
check_free_text, check_reference_text, count_printed_tins, holds_printed_tin,
holds_printed_tin_in_reference, mask_printed_tins, mask_printed_tins_in_reference, tin_refusal,
};
use proptest::prelude::*;
/// Every separator the detector reads between a TIN's groups.
/// Every separator the detector reads between a TIN's groups, the dot
/// aside (a dot joins only the three groups of an SSN, both: `DOTS`).
const SEPARATORS: &[&str] = &[
"-",
"\u{2010}",
@@ -28,8 +30,6 @@ const SEPARATORS: &[&str] = &[
"\u{fe58}",
"\u{fe63}",
"\u{ff0d}",
".",
"\u{ff0e}",
" ",
" ",
"\t",
@@ -42,8 +42,14 @@ const SEPARATORS: &[&str] = &[
" - ",
" \u{2013} ",
"\u{a0}\u{2014}\u{a0}",
// a line break reads as a space
"\n",
"\r\n",
];
/// The dots: they join an SSN's groups when they join both of them.
const DOTS: &[&str] = &[".", "\u{ff0e}", "\u{2024}"];
/// Text around a number that has no digit at its edge.
const CONTEXTS: &[(&str, &str)] = &[
("", ""),
@@ -73,6 +79,46 @@ proptest! {
prop_assert!(holds_printed_tin(&text), "{text:?}");
}
/// An SSN written with a dot at both joiners (`000.00.0000`) is found.
#[test]
fn a_dotted_ssn_is_found(
a in digits(3), b in digits(2), c in digits(4),
s1 in 0..DOTS.len(), s2 in 0..DOTS.len(), ctx in 0..CONTEXTS.len(),
) {
let text = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, DOTS[s1], DOTS[s2], CONTEXTS[ctx].1);
prop_assert!(holds_printed_tin(&text), "{text:?}");
}
/// A dot at one joiner only, or between an EIN's groups, is a decimal or
/// a version, not a tax id (a coordinate: `47.6062095`).
#[test]
fn a_dot_alone_is_not_a_joiner(
a in digits(3), b in digits(2), c in digits(4), e in digits(7),
dot in 0..DOTS.len(), sep in 0..SEPARATORS.len(), ctx in 0..CONTEXTS.len(),
) {
let ein = format!("{}{}{}{e}{}", CONTEXTS[ctx].0, &a[..2], DOTS[dot], CONTEXTS[ctx].1);
prop_assert!(!holds_printed_tin(&ein), "{ein:?}");
let first = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, DOTS[dot], SEPARATORS[sep], CONTEXTS[ctx].1);
prop_assert!(!holds_printed_tin(&first), "{first:?}");
let second = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, SEPARATORS[sep], DOTS[dot], CONTEXTS[ctx].1);
prop_assert!(!holds_printed_tin(&second), "{second:?}");
}
/// A date followed by a seven-digit reference is a date and a
/// reference, whatever stands between them, and a decimal with seven
/// digits after its point is a number (`47.6062095`).
#[test]
fn a_date_then_a_reference_and_a_decimal_are_no_tax_id(
y in 1990u32..2100, m in 1u32..13, d in 1u32..29, r in digits(7),
whole in digits(2), sep in 0..4usize, ctx in 0..CONTEXTS.len(),
) {
let between = [" ", "\t", "\n", " "][sep];
let date = format!("{}{y}-{m:02}-{d:02}{between}{r}{}", CONTEXTS[ctx].0, CONTEXTS[ctx].1);
prop_assert!(!holds_printed_tin(&date), "{date:?}");
let decimal = format!("{}{whole}.{r}{}", CONTEXTS[ctx].0, CONTEXTS[ctx].1);
prop_assert!(!holds_printed_tin(&decimal), "{decimal:?}");
}
/// Every 2-7 grouping with any listed separator is found.
#[test]
fn every_ein_grouping_is_found(
@@ -148,6 +194,18 @@ fn the_allow_list_passes() {
"11/21/2026",
"21.11.2026",
"2026-11-21T10:30:00Z",
// decimals: a coordinate, a version, an amount
"47.6062095",
"at 47.6062095, -122.3321",
"17.2345678",
"v 12.3456789",
"$1234567.8901234",
// a date followed by, or inside, a longer number
"2026-11-21 0001234",
"on 2026-11-21 0001234 paid",
"2026-11-0001234",
"55-1234567-001",
"part 5-000-00-0000",
// plain words
"Office rent, November",
"",
@@ -172,6 +230,21 @@ fn the_shapes_are_found() {
"\u{660}\u{660}\u{660}-\u{660}\u{660}-\u{660}\u{660}\u{660}\u{660}",
"pay 00-0000000 now",
"SSN: 000.00.0000.",
// a line break between the groups reads as a space
"000\n00\n0000",
"000\r\n00\r\n0000",
"ein 00\n0000000",
"ein 00\r0000000",
// zero-width and soft-hyphen characters between digits are not there
"000\u{200b}-00-0000",
"0\u{200b}0\u{200c}0\u{200d}-0\u{2060}0-00\u{feff}00",
"00\u{ad}-0000000",
"00-000\u{ad}0\u{ad}000",
"0\u{200b}00000000",
"\u{200b}000000000\u{200b}",
// the text around a number
"words 000-00-0000 words",
"(00-0000000)",
] {
assert!(holds_printed_tin(caught), "{caught:?} must be found");
let why = check_free_text("the memo", caught).unwrap_err();
@@ -188,6 +261,106 @@ fn the_shapes_are_found() {
}
}
/// What the shapes do not take for a tax id: a dot is no joiner but between
/// both groups of an SSN, and a group that is the tail or head of a longer
/// run of digits and dashes belongs to that run.
#[test]
fn a_dot_and_a_longer_run_are_no_tax_id() {
for fine in [
"47.6062095",
"17.2345678",
"12.3456789",
"000.00 0000",
"000 00.0000",
"000.00-0000",
"000-00.0000",
"2026-11-21 0001234",
"2026-11-21\n0001234",
"12-3456789-0",
"1-123-45-6789",
"0000-00-0000000",
"123456789.5",
"0.123456789",
] {
assert!(!holds_printed_tin(fine), "{fine:?} must pass");
assert!(check_free_text("memo", fine).is_ok(), "{fine:?} must pass");
}
// ... while the shapes, with words around them, are still found.
for caught in [
"2026-11-21 paid 00-0000000",
"on 2026-11-21: 000-00-0000",
"47.6062095 and then 00-0000000",
"ref 12-3456789.",
"123456789.",
] {
assert!(holds_printed_tin(caught), "{caught:?} must be found");
}
// The line break and the invisible characters are read only outside a
// replay, as the Unicode forms are (BS-entry-4).
let broken = "000\n00\n0000";
assert!(holds_printed_tin(broken));
ledger_core::parties::replaying(|| {
assert!(!holds_printed_tin(broken));
assert!(!holds_printed_tin("0\u{200b}00000000"));
});
}
/// Letters between digits, and a number split across two fields, are an
/// accident and not a way to hide one: the reading leaves them (WB-partner-15).
#[test]
fn letters_between_digits_are_left_alone() {
for fine in ["000a00b0000", "00-0000 000", "000-00x0000"] {
assert!(!holds_printed_tin(fine), "{fine:?}");
}
}
/// A reference's reading (an asset tag, a serial, an invoice or bill
/// number, a payment reference, an account code, a file name): a bare nine
/// digits is a number there; the printed shapes are still refused.
#[test]
fn a_reference_may_be_nine_digits_but_not_a_printed_tax_id() {
for fine in [
"123456789",
"SN 000000000",
"tag 000000000.",
"000000000",
"INV-2026-11-0042",
"1234567890",
"scan 000000000.pdf",
] {
assert!(!holds_printed_tin_in_reference(fine), "{fine:?}");
assert!(check_reference_text("the tag", fine).is_ok(), "{fine:?}");
assert_eq!(
mask_printed_tins_in_reference(fine),
fine,
"a bare nine digits stays in a reference"
);
}
for caught in [
"000-00-0000",
"00-0000000",
"SN 000 00 0000",
"w9 00\u{2013}0000000.pdf",
"000.00.0000",
"000\n00\n0000",
"0\u{200b}0-0000000",
] {
assert!(holds_printed_tin_in_reference(caught), "{caught:?}");
let why = check_reference_text("the tag", caught).unwrap_err();
assert!(
why.starts_with("the tag looks like it holds a tax id") && !why.contains("0000"),
"{why}"
);
}
// Free text says the same of the same bare run: refused.
assert!(holds_printed_tin("123456789"));
// A mask of a reference keeps its bare run and covers its shapes.
assert_eq!(
mask_printed_tins_in_reference("SN 123456789 / 000-00-0000"),
"SN 123456789 / \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000"
);
}
/// Two numbers in one text are two finds, each masked to its last four.
#[test]
fn masking_masks_each_number() {
@@ -324,16 +497,20 @@ mod engine {
f.l.create_period(&format!("P {TIN}"), day(1), day(31)),
"the period name",
);
// An account code is a reference: its printed shape is refused, a
// bare nine digits is a code (WB-partner-15).
holds_tin(
f.l.add_account(
&TIN.replace('-', ""),
"Odd",
AccountType::Asset,
None,
false,
),
f.l.add_account(TIN, "Odd", AccountType::Asset, None, false),
"the account code",
);
let nine =
f.l.add_account("123456789", "Nine", AccountType::Asset, None, false);
assert!(nine.is_ok(), "{nine:?}");
holds_tin(
f.l.renumber_account(f.cash, "00-0000000"),
"the account code",
);
f.l.renumber_account(f.cash, "000000000").unwrap();
f.l.create_period("2026-03", day(1), day(31)).unwrap();
}
@@ -433,12 +610,31 @@ mod engine {
bill(
&mut f.l,
BillFields {
vendor_ref: Some("000000000".into()),
vendor_ref: Some(TIN.into()),
..Default::default()
},
),
"the reference",
);
// A bare nine digits is a vendor's invoice number, and a customer's
// purchase order: references.
bill(
&mut f.l,
BillFields {
vendor_ref: Some("000000000".into()),
..Default::default()
},
)
.unwrap();
inv(
&mut f.l,
vec![line("ok")],
InvoiceFields {
customer_ref: Some("PO 123456789".into()),
..Default::default()
},
)
.unwrap();
holds_tin(
bill(
&mut f.l,
@@ -469,6 +665,169 @@ mod engine {
.unwrap();
}
/// A payment's reference is the engine's to check, as the tools check
/// it: a printed SSN or EIN is refused, a bare nine digits (a check or
/// a confirmation number) is kept, and the entry's description, which
/// is free text, shows it masked. A discount's reason is free text.
#[test]
fn payments_check_their_reference_and_discount_reason() {
use ledger_core::{Application, DocRef, PaymentDetails, SettleParams};
let mut f = fx();
let c = f.l.add_customer("Acme").unwrap();
let v = f.l.add_vendor("Beta").unwrap();
let invoice =
f.l.create_invoice_with(
c,
day(1),
day(31),
vec![line("work")],
InvoiceFields::default(),
)
.unwrap();
let bill =
f.l.create_bill_with(
v,
day(1),
day(31),
vec![line("parts")],
BillFields::default(),
)
.unwrap();
let pay = |l: &mut Ledger, reference: &str| {
l.receive_payment_with(
invoice,
day(5),
Decimal::from(1),
f.cash,
&PaymentDetails {
instrument: None,
reference: Some(reference.into()),
},
)
};
holds_tin(pay(&mut f.l, TIN), "the payment reference");
holds_tin(pay(&mut f.l, "check 00-0000000"), "the payment reference");
let before = f.l.clone();
holds_tin(
f.l.pay_bill_with(
bill,
day(5),
Decimal::from(1),
f.cash,
&PaymentDetails {
instrument: None,
reference: Some(format!("wire {TIN}")),
},
),
"the payment reference",
);
assert_eq!(f.l, before, "a refusal changes nothing");
// A bare nine digits is a reference ...
let e = pay(&mut f.l, "123456789").unwrap();
// ... and the entry's description, free text, holds it masked.
assert_eq!(
f.l.get_entry(e).unwrap().description(),
"Payment on invoice 1 (ref \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}6789)"
);
// A ten-digit trace number is kept as it is.
let e = pay(&mut f.l, "1234567890").unwrap();
assert_eq!(
f.l.get_entry(e).unwrap().description(),
"Payment on invoice 1 (ref 1234567890)"
);
// The discount reason of a settlement.
let settle = |l: &mut Ledger, why: &str| {
l.settle(SettleParams {
date: day(6),
description: "Payment".into(),
cash_account: f.cash,
party: c,
applications: vec![Application {
doc: DocRef::Invoice(invoice),
cash: Decimal::from(1),
discount: Decimal::ZERO,
discount_reason: Some(why.into()),
}],
fee: None,
instrument: None,
reference: None,
})
};
holds_tin(
settle(&mut f.l, &format!("early {TIN}")),
"the discount reason",
);
settle(&mut f.l, "paid within 10 days, ref 1234567890").unwrap();
// A replay reads none of it.
ledger_core::parties::replaying(|| {
let d = PaymentDetails {
instrument: None,
reference: Some(TIN.into()),
};
d.check().unwrap();
});
}
/// A project's fields are refused by the engine itself, whoever calls
/// (the tools' own check runs before it, and says it first).
#[test]
fn a_project_field_is_refused_by_the_engine() {
use ledger_core::classes::ProjectFacts;
let mut f = fx();
let id = f.l.add_class("Harbor").unwrap();
let facts = |notes: Option<&str>, description: Option<&str>, links: &[&str]| ProjectFacts {
notes: notes.map(Into::into),
description: description.map(Into::into),
links: links.iter().map(|l| (*l).to_string()).collect(),
..Default::default()
};
let engine_refusal = |r: Result<(String, ProjectFacts), LedgerError>, field: &str| match r {
Err(LedgerError::InvalidProject(why)) => {
assert!(why.contains(field), "{why}");
assert!(why.contains("full SSN or EIN"), "{why}");
assert!(!why.contains("0000"), "never the number: {why}");
}
other => panic!("{field}: expected the engine's refusal, got {other:?}"),
};
engine_refusal(
f.l.check_set_project(id, "Harbor", &facts(Some(&format!("ssn {TIN}")), None, &[])),
"notes",
);
engine_refusal(
f.l.check_set_project(id, "Harbor", &facts(None, Some("ein 00-0000000"), &[])),
"description",
);
engine_refusal(
f.l.check_set_project(
id,
"Harbor",
&facts(None, None, &["https://x.test/000-00-0000"]),
),
"link",
);
match f
.l
.set_project(id, &format!("Harbor {TIN}"), facts(None, None, &[]))
{
Err(LedgerError::InvalidProject(why)) => {
assert!(why.contains("full SSN or EIN"), "{why}");
}
other => panic!("the name: {other:?}"),
}
// A reference of ten digits, an invoice number and a store listing's
// id are no tax id.
f.l.set_project(
id,
"Harbor 2026-11-0042",
facts(
Some("ref 1234567890"),
Some("PO 2026-0042"),
&["https://apps.example.com/app/id284882215"],
),
)
.unwrap();
}
/// Assets, schedules, recurring entries and payroll names.
#[test]
fn assets_schedules_and_payroll() {
@@ -498,6 +857,10 @@ mod engine {
);
holds_tin(f.l.set_asset_tag(a, "T-000-00-0000"), "the asset tag");
f.l.set_asset_serial(a, Some("C02XK1ABCDEF")).unwrap();
// A tag and a serial number are references: a bare nine digits
// is one.
f.l.set_asset_serial(a, Some("000000000")).unwrap();
f.l.set_asset_tag(a, "123456789").unwrap();
let sched = |d: &str| NewSchedule {
description: d.into(),
kind: ScheduleKind::PrepaidExpense,
+7 -1
View File
@@ -444,9 +444,15 @@ fn w9_check_refuses_full_tin_in_any_text() {
let mut f = w9("6789");
f.entity_type = "LLC 12-3456789".to_string();
assert!(f.check().is_err());
// Where the paper is kept is a reference, not a name or a detail: its
// printed shapes are refused, and a bare nine digits (a binder's or a
// file's number) is a number there (WB-partner-15).
let mut f = w9("6789");
f.kept_at = "drawer 123-45-6789".to_string();
assert!(f.check().is_err());
let mut f = w9("6789");
f.kept_at = "drawer 123456789".to_string();
assert!(f.check().is_err());
assert!(f.check().is_ok());
let mut f = w9("6789");
f.exempt_payee_code = Some("123-45-6789".to_string());
assert!(f.check().is_err());