# The six-plus-one verification checks run against every extracted transaction list. import re BALANCE_TOLERANCE = 0.01 _DATE_RE = re.compile(r"(\d{1,2}) (\w{3})(?: (\d{4}))?") _MONTHS = {m: i + 1 for i, m in enumerate( ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] )} def _parse_date(text): """(year, month, day) tuple for sorting/range-checking, or None - the statement's own "DD Mon[ YYYY]" format, not full ISO normalization (good enough for sanity checks; the spec's own date-format-swap suggested fix is Phase 2, not needed here). Year is optional - confirmed for real that some banks (RBC) print only day+month on each transaction row, with the year stated once in the statement's own header rather than repeated per row; a missing year defaults to 0, which keeps same-statement month/day ordering meaningful without pretending to know a year that was never actually printed here.""" m = _DATE_RE.search(text or "") if not m or m.group(2) not in _MONTHS: return None year = int(m.group(3)) if m.group(3) else 0 return (year, _MONTHS[m.group(2)], int(m.group(1))) def check_statement_balance(transactions, opening_balance=None, closing_balance=None): """ Check 1: opening + credits - debits = closing, using FIGURES THE STATEMENT ITSELF PRINTS. For a statement that doesn't cleanly print both (confirmed for real on HSBC - see table_extract.py/ extraction_service.py's own notes), this can't run at all unless the user supplies the missing figure(s) - per the spec's own documented variant (section 7): "statements without printed opening or closing balance: status cannot be Verified; asks the user to enter the missing figure." """ credit_total = round(sum(t["amount"] for t in transactions if t["amount"] and t["amount"] > 0), 2) debit_total = round(sum(t["amount"] for t in transactions if t["amount"] and t["amount"] < 0), 2) # Computed whenever an opening balance is known at all, independent of # whether a closing balance is ALSO known - lets the UI show "this is # what the transactions add up to" even before there's a stated # closing figure to compare it against (see the web app's calculated- # balance readouts under the opening/closing balance inputs). calculated_closing = round(opening_balance + credit_total + debit_total, 2) if opening_balance is not None else None if opening_balance is None or closing_balance is None: return { "name": "statement_balance", "outcome": "not_available", "detail": "No opening and/or closing balance available for this statement - " "enter them to run this check.", "credit_total": credit_total, "debit_total": debit_total, "calculated_closing": calculated_closing, } passed = abs(calculated_closing - closing_balance) < BALANCE_TOLERANCE return { "name": "statement_balance", "outcome": "pass" if passed else "fail", "detail": f"Opening {opening_balance:,.2f} + credits {credit_total:,.2f} + debits {debit_total:,.2f} = " f"{calculated_closing:,.2f}; statement closing balance is {closing_balance:,.2f}" + ("" if passed else f" - off by {round(calculated_closing - closing_balance, 2):,.2f}"), "credit_total": credit_total, "debit_total": debit_total, "calculated_closing": calculated_closing, } def _walk_balance_chain(transactions, direction): """ One pass of the running-balance check in a given listing direction: "backward" for a newest-first statement (HSBC's own convention - balance[i] - amount[i] == balance[i+1]) or "forward" for an oldest-first one (RBC's own convention - balance[i] + amount[i+1] == balance[i+1]). Bridges across any row with no printed balance by carrying a running expected value forward and resyncing whenever a real balance is seen. """ mismatches = [] running = None for i, t in enumerate(transactions): if direction == "forward" and running is not None and t["amount"] is not None: running = round(running + t["amount"], 2) if running is not None and t["balance"] is not None: if abs(running - t["balance"]) > BALANCE_TOLERANCE: mismatches.append({ "index": i, "date": t["date"], "status": t["status"], "expected": running, "actual": t["balance"], }) if t["balance"] is not None: running = t["balance"] if direction == "backward" and running is not None and t["amount"] is not None: running = round(running - t["amount"], 2) return mismatches def check_running_balance(transactions): """ Check 2: for every row with a printed balance, previous balance +/- amount = this balance - bridged across any row with no printed balance (confirmed to happen for real even on a normally-"Posted" row) by carrying a running expected value forward and resyncing whenever a real balance is seen (see the in-app HSBC tool this was first built and debugged in). A statement can list transactions newest-first (HSBC) or oldest- first (RBC) - confirmed for real that assuming one direction universally produces real, spurious chain breaks on the other. Both directions are tried; whichever produces fewer mismatches is almost certainly this statement's own real listing order, so that one's result is used (newest-first wins a tie, since it's the already-proven default and an all-zero-mismatch tie is otherwise unverifiable either way). Unlike the in-app tool, a non-"Posted" status row (e.g. "Cancelled") is NOT dropped before this check runs - per the spec's "never silently correct" rule, it stays in the list, and if its amount breaks the chain, THAT is exactly what gets flagged here instead of being silently resolved by exclusion. """ backward = _walk_balance_chain(transactions, "backward") forward = _walk_balance_chain(transactions, "forward") mismatches = forward if len(forward) < len(backward) else backward return { "name": "running_balance", "outcome": "pass" if not mismatches else "fail", "detail": "Every available running balance follows from the row before it." if not mismatches else f"{len(mismatches)} row(s) break the running-balance chain.", "mismatches": mismatches, } def _ordering_violations(parsed, newest_first): """How many consecutive pairs break a given listing direction - newest_first=True expects non-increasing dates (HSBC's own order), False expects non-decreasing (RBC's own order). Used to auto-detect which direction this statement actually uses, the same approach as check_running_balance's own direction detection.""" violations = [] prev = None for i, (d, t) in enumerate(parsed): if d is None: continue if prev is not None: out_of_order = (d > prev) if newest_first else (d < prev) if out_of_order: violations.append({"index": i, "issue": f"date {t['date']} is out of order"}) prev = d return violations def check_date_sanity(transactions, period_start=None, period_end=None): """ Check 4: every date falls within the statement period (when known) and rows are in a consistent order. A statement can list transactions newest-first (HSBC) or oldest-first (RBC) - both directions are tried and whichever has fewer violations is taken as this statement's own real order (same approach as check_running_balance's direction detection, for the same reason).""" issues = [] parsed = [(_parse_date(t["date"]), t) for t in transactions] for i, (d, t) in enumerate(parsed): if d is None: issues.append({"index": i, "issue": f"unparseable date: {t['date']!r}"}) continue if period_start and d < period_start: issues.append({"index": i, "issue": f"date {t['date']} is before the statement period"}) if period_end and d > period_end: issues.append({"index": i, "issue": f"date {t['date']} is after the statement period"}) newest_first_violations = _ordering_violations(parsed, newest_first=True) oldest_first_violations = _ordering_violations(parsed, newest_first=False) issues.extend( oldest_first_violations if len(oldest_first_violations) < len(newest_first_violations) else newest_first_violations ) return { "name": "date_sanity", "outcome": "pass" if not issues else "needs_review", "detail": "All dates fall within the statement period and are in order." if not issues else f"{len(issues)} date issue(s) found.", "issues": issues, } def check_structure_sanity(transactions): """Check 5: no row with a missing amount, no blank description, no exact duplicate-looking row (same date/amount/description - a real signal for an accidentally double-counted transaction, not proof of one).""" issues = [] seen = {} for i, t in enumerate(transactions): if t["amount"] is None: issues.append({"index": i, "issue": "no amount at all"}) if not t["description"].strip(): issues.append({"index": i, "issue": "blank description"}) key = (t["date"], t["amount"], t["description"]) if key in seen: issues.append({"index": i, "issue": f"looks identical to row {seen[key]} (same date/amount/description)"}) else: seen[key] = i return { "name": "structure_sanity", "outcome": "pass" if not issues else "needs_review", "detail": "No structural issues found." if not issues else f"{len(issues)} structural issue(s) found.", "issues": issues, } def check_page_coverage(page_reports): """Check 6: every page was read. A page where pdfplumber found zero transaction rows at all (not just a Docling miss - see extraction_service.py's "fallback_only" vs a genuinely empty page) is flagged rather than silently assumed to be a cover/notice page.""" empty_pages = [pr["page"] for pr in page_reports if pr["pdfplumber_count"] == 0] return { "name": "page_coverage", "outcome": "pass" if not empty_pages else "needs_review", "detail": "Every page produced transaction rows." if not empty_pages else f"Page(s) {empty_pages} produced no transaction rows - confirm this is expected " "(a cover page or notice) rather than a missed page.", "empty_pages": empty_pages, } def check_engine_agreement(page_reports): """Not one of the spec's six named checks, but the natural output of the dual-engine cross-check design (see extraction_service.py): surfaces pages where Docling found no table at all (lower confidence - pdfplumber's result alone is used) separately from pages where both engines found a table but disagree on count or amounts (true disagreement - never silently resolved).""" fallback_pages = [pr["page"] for pr in page_reports if pr["status"] == "fallback_only"] mismatch_pages = [pr for pr in page_reports if pr["status"] == "mismatch"] if mismatch_pages: outcome = "fail" elif fallback_pages: outcome = "needs_review" else: outcome = "pass" detail_parts = [] if fallback_pages: detail_parts.append(f"Docling did not detect a table on page(s) {fallback_pages} - used pdfplumber alone.") if mismatch_pages: detail_parts.append(f"{len(mismatch_pages)} page(s) have disagreeing counts or amounts between the two extraction engines.") return { "name": "engine_agreement", "outcome": outcome, "detail": " ".join(detail_parts) if detail_parts else "Both extraction engines agree on every page.", "fallback_pages": fallback_pages, "mismatch_pages": [pr["page"] for pr in mismatch_pages], } def check_ocr_source(): """Not one of the spec's six named checks - the OCR-path analog of engine_agreement, which specifically means something about TWO engines agreeing and so can't run at all when only one engine (Docling, via OCR) produced any result (see extraction_service.py's routing). Always needs_review and never pass: this is the product's own acknowledgment that OCR has no second engine checking it, which is also what keeps the overall status in run_all() from ever reaching "Verified" for an OCR-sourced statement, the same way a genuine fail/needs_review outcome from any other check would.""" return { "name": "ocr_source", "outcome": "needs_review", "detail": "This statement was read via OCR - no embedded text layer was found, so " "Docling extracted it alone with no second engine to cross-check against. " "Review the extracted rows against the original image or PDF before relying on them.", } def check_narrative_direction(narrative_direction): """ Not one of the spec's six named checks, but the natural output of deciding each transaction's description-wrapping direction individually (see table_extract.rows_to_transactions / _decide_gap): most rows are settled outright, either by an explicit continuation-label word or by a clearly-closer neighboring transaction. A row flagged here is one where NEITHER applied - no label, and the two neighboring transactions were nearly equidistant - so the direction was still decided, but by a close geometric call worth a human glance rather than silently trusting a near-coin-flip. """ if narrative_direction is None: return {"name": "narrative_direction", "outcome": "pass", "detail": "Not evaluated.", "issues": []} ambiguous = narrative_direction.get("ambiguous_indices", []) # {"index": i} shape, not a plain int list - matches every other # check's own issues/mismatches convention, which is what both the # UI's row-highlighting and the Excel export's flag column key on. issues = [{"index": i, "issue": "description attachment was a close geometric call - worth confirming"} for i in ambiguous] if ambiguous: detail = ( f"{len(ambiguous)} row(s) had no clear signal (no label, nearly equidistant from both " "neighboring transactions) for which transaction their description text belongs to - worth confirming." ) outcome = "needs_review" else: detail = "Every description's attachment direction was decided with a clear signal." outcome = "pass" return {"name": "narrative_direction", "outcome": outcome, "detail": detail, "issues": issues} def run_all(transactions, page_reports, opening_balance=None, closing_balance=None, period_start=None, period_end=None, narrative_direction=None, ocr_only=False): """ Runs every check and derives the overall status: - "Failed": the statement balance check explicitly failed, or the running-balance chain broke, or the two engines actively disagree. - "Needs review": anything else non-passing (missing balance figures, date/structure issues, a page Docling couldn't confirm, a possible mixed narrative-wrapping convention, or an OCR-sourced statement - see check_ocr_source). - "Verified": everything passed. Not reachable when ocr_only=True - check_ocr_source always reports needs_review, by design (see its own docstring): OCR has no second engine to earn "Verified" against. `ocr_only` swaps check_engine_agreement (meaningless with only one engine's result to look at) for check_ocr_source; check_page_coverage still runs unchanged - page_reports' "pdfplumber_count" field holds Docling's own per-page count in this case (see extraction_service._run_ocr_only), and an empty page is just as worth flagging regardless of which engine produced the (lack of) rows. """ results = [ check_statement_balance(transactions, opening_balance, closing_balance), check_running_balance(transactions), check_date_sanity(transactions, period_start, period_end), check_structure_sanity(transactions), check_page_coverage(page_reports), check_ocr_source() if ocr_only else check_engine_agreement(page_reports), check_narrative_direction(narrative_direction), ] outcomes = {r["outcome"] for r in results} if "fail" in outcomes: status = "Failed" elif outcomes - {"pass"}: status = "Needs review" else: status = "Verified" return {"status": status, "checks": results}