feat(core): one detector for free text, with Unicode separators, masking and words
holds_printed_tin now reads the Unicode dashes, dots, spaces and numerals between an SSN's 3-2-4 or an EIN's 2-7 groups (a replay keeps reading the narrow form, BS-entry-4). mask_printed_tins keeps the last four digits of each number found; check_free_text and tin_refusal give the one refusal in words: which field, that it looks like a tax id, where a tax id goes (books.set_tin or a W-9), never the number. Property tests: every grouping with every listed separator is found, nine digits alone are found, ten or more digits, invoice and phone numbers, amounts and dates pass. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
a9fec9ee27
commit
ff58b055ce
2 files changed
+354
-25
No files matched your search
@@ -714,9 +714,31 @@ pub fn decimal(s: &str) -> Option<Decimal> {
|
||||
/// 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); full-width digits count as digits.
|
||||
/// around it), whatever Unicode form the dash, dot, space or digit takes
|
||||
/// (full-width, Arabic-Indic, no-break space, en space, ...).
|
||||
///
|
||||
/// ```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), docs/spec/claims/partner.md.
|
||||
/// 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.
|
||||
/// 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).
|
||||
/// SCENARIOS:
|
||||
/// 1. IF a memo says `paid 000-00-0000`: SHOULD be found.
|
||||
/// 2. IF it says `inv 2026-11-0042`: SHOULD NOT be.
|
||||
/// ```
|
||||
pub fn holds_printed_tin(text: &str) -> bool {
|
||||
printed_tin(text, false)
|
||||
!printed_tin_spans(text, false).1.is_empty()
|
||||
}
|
||||
|
||||
/// [`holds_printed_tin`] for a web address: the printed SSN (3-2-4) and
|
||||
@@ -725,34 +747,99 @@ 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(text, true)
|
||||
!printed_tin_spans(text, true).1.is_empty()
|
||||
}
|
||||
|
||||
/// [`holds_printed_tin`], with a link's bare runs let through when `link`.
|
||||
fn printed_tin(text: &str, link: bool) -> bool {
|
||||
// Full-width digits read as the digits they are.
|
||||
let c: Vec<char> = text
|
||||
.chars()
|
||||
.map(|ch| match ch {
|
||||
'\u{ff10}'..='\u{ff19}' => char::from_digit(ch as u32 - 0xff10, 10).unwrap_or(ch),
|
||||
_ => ch,
|
||||
})
|
||||
.collect();
|
||||
let digit = |i: usize| c.get(i).is_some_and(char::is_ascii_digit);
|
||||
let dash = |ch: char| matches!(ch, '-' | '\u{2010}'..='\u{2015}' | '\u{2212}' | '.');
|
||||
/// `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.
|
||||
pub fn mask_printed_tins(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
let (mut chars, spans) = printed_tin_spans(text, false);
|
||||
if spans.is_empty() {
|
||||
return std::borrow::Cow::Borrowed(text);
|
||||
}
|
||||
for (from, to) in spans {
|
||||
let digits: Vec<usize> = (from..to).filter(|&i| chars[i].is_numeric()).collect();
|
||||
let keep = digits.len().saturating_sub(4);
|
||||
for &i in &digits[..keep] {
|
||||
chars[i] = '\u{2022}';
|
||||
}
|
||||
}
|
||||
std::borrow::Cow::Owned(chars.into_iter().collect())
|
||||
}
|
||||
|
||||
/// How many numbers [`holds_printed_tin`] finds in `text`.
|
||||
pub fn count_printed_tins(text: &str) -> usize {
|
||||
printed_tin_spans(text, false).1.len()
|
||||
}
|
||||
|
||||
/// A character that stands for a digit: ASCII, full-width, or any other
|
||||
/// script's numeral (outside a replay, which reads ASCII and full-width
|
||||
/// only).
|
||||
fn digit_like(ch: char, extended: bool) -> bool {
|
||||
ch.is_ascii_digit()
|
||||
|| matches!(ch, '\u{ff10}'..='\u{ff19}')
|
||||
|| (extended && ch.is_numeric())
|
||||
}
|
||||
|
||||
/// A space between a TIN's groups: the plain one, and outside a replay
|
||||
/// the tab and every Unicode space separator.
|
||||
fn tin_space(ch: char, extended: bool) -> bool {
|
||||
ch == ' '
|
||||
|| (extended
|
||||
&& matches!(
|
||||
ch,
|
||||
'\t' | '\u{a0}'
|
||||
| '\u{1680}'
|
||||
| '\u{2000}'..='\u{200a}'
|
||||
| '\u{202f}'
|
||||
| '\u{205f}'
|
||||
| '\u{3000}'
|
||||
))
|
||||
}
|
||||
|
||||
/// A dash or dot between a TIN's groups: the hyphen, the dashes U+2010 to
|
||||
/// U+2015, the minus sign and the dot, and outside a replay every other
|
||||
/// Unicode dash and dot form.
|
||||
fn tin_dash(ch: char, extended: bool) -> bool {
|
||||
matches!(ch, '-' | '\u{2010}'..='\u{2015}' | '\u{2212}' | '.')
|
||||
|| (extended
|
||||
&& matches!(
|
||||
ch,
|
||||
'\u{58a}'
|
||||
| '\u{1806}'
|
||||
| '\u{2024}'
|
||||
| '\u{2043}'
|
||||
| '\u{2e3a}'
|
||||
| '\u{2e3b}'
|
||||
| '\u{fe58}'
|
||||
| '\u{fe63}'
|
||||
| '\u{ff0d}'
|
||||
| '\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)>) {
|
||||
let extended = !crate::parties::is_replaying();
|
||||
let c: Vec<char> = text.chars().collect();
|
||||
let digit = |i: usize| c.get(i).is_some_and(|&ch| digit_like(ch, extended));
|
||||
// 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> {
|
||||
let mut j = i;
|
||||
while c.get(j) == Some(&' ') {
|
||||
while c.get(j).is_some_and(|&ch| tin_space(ch, extended)) {
|
||||
j += 1;
|
||||
}
|
||||
let mut dashes = 0;
|
||||
while c.get(j).copied().is_some_and(dash) {
|
||||
while c.get(j).is_some_and(|&ch| tin_dash(ch, extended)) {
|
||||
j += 1;
|
||||
dashes += 1;
|
||||
}
|
||||
while c.get(j) == Some(&' ') {
|
||||
while c.get(j).is_some_and(|&ch| tin_space(ch, extended)) {
|
||||
j += 1;
|
||||
}
|
||||
let spaces = j - i - dashes;
|
||||
@@ -777,23 +864,59 @@ fn printed_tin(text: &str, link: bool) -> bool {
|
||||
i.and_then(|i| c.get(i))
|
||||
.is_some_and(|ch| ch.is_alphabetic() || matches!(ch, '/' | '=' | '?' | '&' | '#'))
|
||||
};
|
||||
(0..c.len()).any(|at| {
|
||||
(at == 0 || !digit(at - 1))
|
||||
&& [&[9][..], &[3, 2, 4][..], &[2, 7][..]].iter().any(|g| {
|
||||
groups_at(at, g).is_some_and(|end| {
|
||||
let mut spans = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < c.len() {
|
||||
if at > 0 && digit(at - 1) {
|
||||
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))))
|
||||
})
|
||||
})
|
||||
})
|
||||
});
|
||||
match found {
|
||||
Some(end) => {
|
||||
spans.push((at, end));
|
||||
at = end;
|
||||
}
|
||||
None => at += 1,
|
||||
}
|
||||
}
|
||||
(c, spans)
|
||||
}
|
||||
|
||||
/// What a refusal says of a field that looks like it holds a tax id
|
||||
/// (BS-partner-2): which field, why, where a tax id goes instead. Never
|
||||
/// the number.
|
||||
pub fn tin_refusal(field: &str) -> String {
|
||||
format!(
|
||||
"{field} looks like it holds a tax id (a full SSN or EIN: nine digits, bare or written 3-2-4 or 2-7), so nothing was changed. Tax ids are stored only with books.set_tin or a W-9 (books.set_w9), never in a name, note or description; to mention a number, write only its last four digits"
|
||||
)
|
||||
}
|
||||
|
||||
/// Free text (a memo, a note, a reason, a description, a name) that may be
|
||||
/// kept: it must not look like a tax id ([`holds_printed_tin`]). Returns
|
||||
/// why not, in [`tin_refusal`]'s words. Never refuses during a replay
|
||||
/// ([`crate::parties::replaying`]): the journal holds what it holds, and
|
||||
/// books an earlier version wrote open (BS-entry-4).
|
||||
pub fn check_free_text(field: &str, text: &str) -> Result<(), String> {
|
||||
if !crate::parties::is_replaying() && holds_printed_tin(text) {
|
||||
return Err(tin_refusal(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn no_tin(what: &str, s: &str) -> Result<(), String> {
|
||||
if holds_printed_tin(s) {
|
||||
return Err(format!(
|
||||
"{what} holds a number that reads as a full SSN or EIN (nine digits, bare or printed 3-2-4 or 2-7): a full TIN goes only into the vault (books.set_tin), the company's EIN into company.ein and its D-U-N-S number into company.duns; for any other nine-digit number, write its last four"
|
||||
"{what} holds a number that reads as a full SSN or EIN (nine digits, bare or 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), the company's EIN into company.ein and its D-U-N-S number into company.duns; for any other nine-digit number, write its last four"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
//! Free text never holds a tax id (BS-partner-2): the one detector free
|
||||
//! text meets (`ledger_core::settings::holds_printed_tin`), the masking a
|
||||
//! bank's description gets, and the engine commands that take free text.
|
||||
//!
|
||||
//! Oracle: the owner's decision of 2026-11-21 (docs/spec/claims/partner.md,
|
||||
//! the CHOICE on BS-partner-2): free text refuses what looks like a tax id,
|
||||
//! that is nine digits standing alone, an SSN's 3-2-4 and an EIN's 2-7, with
|
||||
//! any dash, dot or space between the groups; it lets an invoice number, a
|
||||
//! phone number, an order number, a reference of ten digits or more, an
|
||||
//! amount and a date through. The fake ids are `000-00-0000` and
|
||||
//! `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,
|
||||
};
|
||||
use proptest::prelude::*;
|
||||
|
||||
/// Every separator the detector reads between a TIN's groups.
|
||||
const SEPARATORS: &[&str] = &[
|
||||
"-",
|
||||
"\u{2010}",
|
||||
"\u{2011}",
|
||||
"\u{2012}",
|
||||
"\u{2013}",
|
||||
"\u{2014}",
|
||||
"\u{2015}",
|
||||
"\u{2212}",
|
||||
"\u{fe58}",
|
||||
"\u{fe63}",
|
||||
"\u{ff0d}",
|
||||
".",
|
||||
"\u{ff0e}",
|
||||
" ",
|
||||
" ",
|
||||
"\t",
|
||||
"\u{a0}",
|
||||
"\u{2002}",
|
||||
"\u{2003}",
|
||||
"\u{2009}",
|
||||
"\u{202f}",
|
||||
"\u{3000}",
|
||||
" - ",
|
||||
" \u{2013} ",
|
||||
"\u{a0}\u{2014}\u{a0}",
|
||||
];
|
||||
|
||||
/// Text around a number that has no digit at its edge.
|
||||
const CONTEXTS: &[(&str, &str)] = &[
|
||||
("", ""),
|
||||
("paid ", ""),
|
||||
("", " paid"),
|
||||
("SSN ", "."),
|
||||
("(", ")"),
|
||||
("ref: ", ", thanks"),
|
||||
("a\u{e9}", "z"),
|
||||
];
|
||||
|
||||
fn digits(n: usize) -> impl Strategy<Value = String> {
|
||||
prop::collection::vec(0u8..10, n)
|
||||
.prop_map(|d| d.into_iter().map(|x| char::from(b'0' + x)).collect())
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(512))]
|
||||
|
||||
/// Every 3-2-4 grouping with any listed separator is found.
|
||||
#[test]
|
||||
fn every_ssn_grouping_is_found(
|
||||
a in digits(3), b in digits(2), c in digits(4),
|
||||
s1 in 0..SEPARATORS.len(), s2 in 0..SEPARATORS.len(), ctx in 0..CONTEXTS.len(),
|
||||
) {
|
||||
let text = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, SEPARATORS[s1], SEPARATORS[s2], CONTEXTS[ctx].1);
|
||||
prop_assert!(holds_printed_tin(&text), "{text:?}");
|
||||
}
|
||||
|
||||
/// Every 2-7 grouping with any listed separator is found.
|
||||
#[test]
|
||||
fn every_ein_grouping_is_found(
|
||||
a in digits(2), b in digits(7), s in 0..SEPARATORS.len(), ctx in 0..CONTEXTS.len(),
|
||||
) {
|
||||
let text = format!("{}{a}{}{b}{}", CONTEXTS[ctx].0, SEPARATORS[s], CONTEXTS[ctx].1);
|
||||
prop_assert!(holds_printed_tin(&text), "{text:?}");
|
||||
}
|
||||
|
||||
/// Nine digits standing alone are found.
|
||||
#[test]
|
||||
fn nine_digits_alone_are_found(a in digits(9), ctx in 0..CONTEXTS.len()) {
|
||||
let text = format!("{}{a}{}", CONTEXTS[ctx].0, CONTEXTS[ctx].1);
|
||||
prop_assert!(holds_printed_tin(&text), "{text:?}");
|
||||
}
|
||||
|
||||
/// Ten digits or more are a reference, never a tax id: one digit more
|
||||
/// before, after or inside a shape takes it out of the reading.
|
||||
#[test]
|
||||
fn ten_or_more_digits_are_a_reference(a in digits(10), extra in 0usize..6, ctx in 0..CONTEXTS.len()) {
|
||||
let tail: String = "7".repeat(extra);
|
||||
let text = format!("{}{a}{tail}{}", CONTEXTS[ctx].0, CONTEXTS[ctx].1);
|
||||
prop_assert!(!holds_printed_tin(&text), "{text:?}");
|
||||
}
|
||||
|
||||
/// Masking leaves nothing for the detector to find, keeps the last four
|
||||
/// digits of each number and its length, and changes nothing else.
|
||||
#[test]
|
||||
fn masking_keeps_the_last_four_and_the_rest(
|
||||
a in digits(3), b in digits(2), c in digits(4), s1 in 0..SEPARATORS.len(),
|
||||
s2 in 0..SEPARATORS.len(), ctx in 0..CONTEXTS.len(),
|
||||
) {
|
||||
let text = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, SEPARATORS[s1], SEPARATORS[s2], CONTEXTS[ctx].1);
|
||||
let masked = mask_printed_tins(&text).into_owned();
|
||||
prop_assert!(!holds_printed_tin(&masked), "{masked:?}");
|
||||
prop_assert_eq!(masked.chars().count(), text.chars().count());
|
||||
prop_assert_eq!(count_printed_tins(&text), 1);
|
||||
let expect = format!("{}\u{2022}\u{2022}\u{2022}{}\u{2022}\u{2022}{}{c}{}", CONTEXTS[ctx].0, SEPARATORS[s1], SEPARATORS[s2], CONTEXTS[ctx].1);
|
||||
prop_assert_eq!(masked, expect);
|
||||
}
|
||||
}
|
||||
|
||||
/// What must go through: the allow-list of the owner's table.
|
||||
#[test]
|
||||
fn the_allow_list_passes() {
|
||||
for fine in [
|
||||
// invoice numbers
|
||||
"INV-2026-11-0042",
|
||||
"2026-11-0042",
|
||||
"invoice 2026-0042",
|
||||
"INV 20261121",
|
||||
// phone numbers
|
||||
"801-555-0142",
|
||||
"(801) 555-0142",
|
||||
"+1 801 555 0142",
|
||||
"+44 20 7946 0958",
|
||||
// order numbers
|
||||
"ORD-48213-7",
|
||||
"order 4821-3377-12",
|
||||
"PO 12-345",
|
||||
// references of ten digits or more
|
||||
"1234567890",
|
||||
"REF 202611210042",
|
||||
"000000000000",
|
||||
"12345678901234567890",
|
||||
// amounts
|
||||
"$1,234,567.89",
|
||||
"1,234,567",
|
||||
"$12,345,678.00",
|
||||
"USD 1 234 567,89",
|
||||
// dates
|
||||
"2026-11-21",
|
||||
"11/21/2026",
|
||||
"21.11.2026",
|
||||
"2026-11-21T10:30:00Z",
|
||||
// plain words
|
||||
"Office rent, November",
|
||||
"",
|
||||
] {
|
||||
assert!(!holds_printed_tin(fine), "{fine:?} must pass");
|
||||
assert!(check_free_text("memo", fine).is_ok(), "{fine:?} must pass");
|
||||
}
|
||||
}
|
||||
|
||||
/// What must be found, written out: the shapes with the fake ids.
|
||||
#[test]
|
||||
fn the_shapes_are_found() {
|
||||
for caught in [
|
||||
"000-00-0000",
|
||||
"00-0000000",
|
||||
"000000000",
|
||||
"tin 000 00 0000",
|
||||
"ein 00 0000000",
|
||||
"000\u{2013}00\u{2013}0000",
|
||||
"000\u{a0}00\u{a0}0000",
|
||||
"\u{ff10}\u{ff10}\u{ff10}-\u{ff10}\u{ff10}-\u{ff10}\u{ff10}\u{ff10}\u{ff10}",
|
||||
"\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.",
|
||||
] {
|
||||
assert!(holds_printed_tin(caught), "{caught:?} must be found");
|
||||
let why = check_free_text("the memo", caught).unwrap_err();
|
||||
assert!(why.starts_with("the memo looks like it holds a tax id"), "{why}");
|
||||
assert!(why.contains("books.set_tin"), "{why}");
|
||||
assert!(why.contains("W-9"), "{why}");
|
||||
assert!(!why.contains("0000"), "a refusal never repeats the number: {why}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two numbers in one text are two finds, each masked to its last four.
|
||||
#[test]
|
||||
fn masking_masks_each_number() {
|
||||
let text = "ACH 000-00-0000 and ref 00-0000000, then 1234567890";
|
||||
assert_eq!(count_printed_tins(text), 2);
|
||||
assert_eq!(
|
||||
mask_printed_tins(text),
|
||||
"ACH \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 and ref \u{2022}\u{2022}-\u{2022}\u{2022}\u{2022}0000, then 1234567890"
|
||||
);
|
||||
// Nothing to mask: the text comes back as it was.
|
||||
assert!(matches!(
|
||||
mask_printed_tins("Whole Foods #1234"),
|
||||
std::borrow::Cow::Borrowed(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_refusal_names_the_field_and_never_a_number() {
|
||||
let why = tin_refusal("books.add_class name");
|
||||
assert!(why.starts_with("books.add_class name looks like it holds a tax id"));
|
||||
assert!(why.contains("books.set_tin") && why.contains("books.set_w9"));
|
||||
}
|
||||
Reference in new issue
Block a user