bettersight-statement-extra.../backend/services/suggested_fixes_service.py

182 lines
8.6 KiB
Python

# Suggests one-click fixes for running-balance breaks - never applies anything automatically.
"""
Suggested fixes for the review screen (docs/bankstatement.md section 4.1): when a
check fails, test a fixed list of known failure patterns, and for each one that fully
or partially explains the difference, offer a suggested fix with evidence - never
applied automatically, only ever a one-click choice the user accepts or ignores.
Only running_balance mismatches are addressed here - the other three row-flagging
checks (date_sanity/structure_sanity/narrative_direction, see flagCatalogService.js on
the frontend) don't have a comparably mechanical "try a candidate value, see if the
check now passes" test the way a balance figure does.
**"Date format swapped" (the spec's own pattern table) was investigated and found not
to apply to this pipeline's data shape, not silently skipped.** The spec describes
resolving a raw numeric day/month ambiguity (e.g. "03/04" could be 3 April or 4 March).
By the time a transaction reaches this module, its date is already
table_extract.py's own normalized "DD Mon[ YYYY]" text (e.g. "03 Apr 2026") - the month
is a three-letter name, not a number, so there is no day/month ambiguity left to
resolve here; that disambiguation already happened upstream, at extraction time (see
table_extract.py's own column-role detection). What date_sanity actually flags
(unparseable text, out-of-period dates, out-of-order dates) has no mechanical
"candidate value" to test the way a balance figure does either, so none of those get a
suggested fix in this version.
**Tested empirically against a copy of the real transactions, not hand-derived from
check_running_balance's own bridging/direction logic** - applying a candidate value and
re-running the actual, already-proven check is both safer (no risk of the suggestion
engine's own math silently diverging from the real check's) and simpler than
re-deriving which row a bridged, direction-auto-detected mismatch is "really" about.
"""
from copy import deepcopy
from services.checks_service import check_running_balance
# Common OCR digit confusions, each pair tried in both directions.
_OCR_DIGIT_PAIRS = [('0', '8'), ('1', '7'), ('3', '8'), ('5', '6'), ('5', '8'), ('6', '8'), ('6', '9'), ('3', '9')]
def _mismatch_count(transactions):
return len(check_running_balance(transactions)["mismatches"])
def _try_amount(transactions, index, new_amount):
"""The running-balance mismatch count after hypothetically setting
transactions[index]'s own amount to new_amount - never mutates the
caller's own list."""
candidate = deepcopy(transactions)
candidate[index]["amount"] = round(new_amount, 2)
return _mismatch_count(candidate)
def _digit_transpositions(amount):
"""Every value produced by swapping two digits in the amount's own
decimal string - bounded by the string's own digit count (at most a
few dozen pairs for a realistic bank amount), so this is cheap."""
text = f"{abs(amount):.2f}"
sign = -1 if amount < 0 else 1
positions = [i for i, c in enumerate(text) if c.isdigit()]
seen = set()
for a in range(len(positions)):
for b in range(a + 1, len(positions)):
i, j = positions[a], positions[b]
if text[i] == text[j]:
continue
chars = list(text)
chars[i], chars[j] = chars[j], chars[i]
candidate_text = "".join(chars)
if candidate_text in seen:
continue
seen.add(candidate_text)
yield sign * float(candidate_text)
def _ocr_substitutions(amount):
"""Every value produced by substituting one digit for a commonly
OCR-confused counterpart, one substitution at a time."""
text = f"{abs(amount):.2f}"
sign = -1 if amount < 0 else 1
seen = set()
for i, c in enumerate(text):
if not c.isdigit():
continue
for a, b in _OCR_DIGIT_PAIRS:
for frm, to in ((a, b), (b, a)):
if c != frm:
continue
candidate_text = text[:i] + to + text[i + 1:]
if candidate_text in seen:
continue
seen.add(candidate_text)
yield sign * float(candidate_text)
def _evidence(original_count, new_count, row_no, old_value, new_value, reason):
verb = "fully resolves" if new_count == 0 else f"reduces the broken row count from {original_count} to {new_count} -"
return (
f"Changing row {row_no}'s amount from {old_value:,.2f} to {new_value:,.2f} ({reason}) "
f"{verb} the running-balance break."
)
def suggest_fixes(transactions, checks):
"""
One suggestion per resolvable running_balance mismatch, each
{pattern, index, evidence, fix: {field, value}} - "fix" is a plain
instruction the frontend applies on explicit accept, never automatically.
A mismatch recorded at index i can be caused by either that row's own
amount or the PRECEDING row's (check_running_balance's own bridging
logic carries a running figure forward, so the "wrong" value isn't
always the one the mismatch is nominally attached to) - both
candidates are tried, keeping whichever one actually resolves the
chain rather than guessing which is "really" responsible.
Each suggestion carries BOTH `index` (the row the fix actually
APPLIES to) and `flag_index` (the row running_balance's own mismatch
is reported against, i.e. the row the UI actually shows flagged) -
confirmed for real that these two can genuinely differ: correcting
row i's own amount is what the bridging walk's mismatch at row i+1
was really about, so a frontend that only looked up a suggestion by
`index` under the row that LOOKS flagged would never find it, since
the row that's actually wrong often isn't flagged at all.
"""
rb_check = next((c for c in checks if c["name"] == "running_balance"), None)
if not rb_check or not rb_check.get("mismatches"):
return []
original_count = len(rb_check["mismatches"])
suggestions = []
tried_indices = set()
for mismatch in rb_check["mismatches"]:
for idx in (mismatch["index"], mismatch["index"] - 1):
if idx < 0 or idx >= len(transactions) or idx in tried_indices:
continue
tried_indices.add(idx)
row = transactions[idx]
if row.get("amount") is None:
continue
row_no = idx + 1
# Pattern 1 (tried first, per the spec's own pattern table
# order): debit/credit swapped - simplest, most common cause,
# so a row that this already explains isn't also offered a
# digit-level fix for the same break.
new_count = _try_amount(transactions, idx, -row["amount"])
if new_count < original_count:
suggestions.append({
"pattern": "debit_credit_swapped", "index": idx, "flag_index": mismatch["index"],
"evidence": _evidence(original_count, new_count, row_no, row["amount"], -row["amount"], "debit and credit flipped"),
"fix": {"field": "amount", "value": round(-row["amount"], 2)},
})
continue
# Pattern 2: transposed digits.
found = False
for candidate_amount in _digit_transpositions(row["amount"]):
new_count = _try_amount(transactions, idx, candidate_amount)
if new_count < original_count:
suggestions.append({
"pattern": "transposed_digits", "index": idx, "flag_index": mismatch["index"],
"evidence": _evidence(original_count, new_count, row_no, row["amount"], candidate_amount, "two digits transposed"),
"fix": {"field": "amount", "value": round(candidate_amount, 2)},
})
found = True
break
if found:
continue
# Pattern 3: a single OCR-style digit misread.
for candidate_amount in _ocr_substitutions(row["amount"]):
new_count = _try_amount(transactions, idx, candidate_amount)
if new_count < original_count:
suggestions.append({
"pattern": "ocr_digit_misread", "index": idx, "flag_index": mismatch["index"],
"evidence": _evidence(original_count, new_count, row_no, row["amount"], candidate_amount, "a likely misread digit"),
"fix": {"field": "amount", "value": round(candidate_amount, 2)},
})
break
return suggestions