Adam BlansettSenior Full-Stack & AI Engineer
AI Engineering
11 min read
Adam Blansett

Self-Hosted AI Finance Operations: Three-Way Reconciliation, 13-Week Cash Flow, and SOX Audit Chains

Inside the Phase 1 implementation of a self-hosted AI finance operations platform: SHA-256 deduplicated PDF/CSV intake, PO/receipt/invoice 3-way matching, AP/AR settlement gates, 13-week cash scenarios, and immutable SOX logs.

Finance OperationsFastAPIPostgreSQLSOX AuditCash Flow ForecastingOllamaHuman-in-the-Loop

Accounting and finance operations teams rarely lack raw data; they drown in disconnected PDF vendor invoices, warehouse receiving confirmations, ERP purchase orders, and noisy CSV bank statements. Closing the books or updating a 13-week liquidity forecast turns into manual spreadsheet cross-referencing—while uploading financial ledgers and vendor tax IDs to public AI assistants introduces clear confidentiality and SOX control risks.

In the Phase 1 implementation of AI Finance Operations Platform (source on GitHub), the goal was to build a self-hosted Python 3.12 (FastAPI + async SQLAlchemy 2.0 + Alembic + PostgreSQL `pgvector`) backend and 7-view React 18 TypeScript console where deterministic financial controls come first and AI acts strictly as an auditable assistant.

Idempotent Document Ingestion with SHA-256 Duplicate Blocking#

Duplicate vendor bill submissions are one of the simplest ways cash leaks out of accounts payable. Every PDF (parsed via `pypdf`), CSV, and JSON upload arriving at `/api/v1/ingestion/upload` or `/payload` is hashed immediately using SHA-256 over the canonical byte payload. Re-submitting an identical invoice or bank statement returns `HTTP 409 Conflict` before duplicate rows can enter ledger candidate tables.

Three-Way Matching and Controller-Gated AP/AR Settlements#

Once purchase orders, goods receipts, and invoices are normalized, `/api/v1/reconciliation/matches` runs two matching stages:

  • Exact & Tolerance Matching: Links PO numbers, receiving quantities, and invoice line items, immediately surfacing unit-price drift, short-delivery quantity variances, missing goods receipts, and potential duplicate invoice numbers.
  • Semantic Vendor & Memo Normalization (`/api/v1/reconciliation/ap-ar/propose`): Cleans banking prefixes like `ACH DEBIT` or `WIRE TRANSFER`, pairs partial payments or lump settlements against open receivables/payables, and asks the local LLM adapter solely for human-readable variance rationales.
Control Invariant: The reconciliation engine proposes matches—it never auto-posts settled ledger entries. Settlements transition only when an authorized user holding Controller RBAC approves them via signed Bearer tokens or role-validated endpoints.

Rolling 13-Week Cash Flow Forecasting and Scenario Simulation#

Short-term treasury visibility depends on timing rather than accrual totals. `/api/v1/forecasting/cashflow` bins open AR aging collections, scheduled AP vendor disbursements, and recurring payroll or lease commitments into 13 weekly buckets. Controllers can submit interactive stress-test parameters to `POST /api/v1/forecasting/cashflow/scenario`—such as delayed major customer receipts or accelerated supplier prepayments—immediately highlighting weeks where cash drops below minimum safety buffers alongside AI-synthesized variance summaries.

Fail-Fast Startup Checks and Hash-Chained SOX Audit Trails#

Running financial software in production demands zero silent misconfigurations. On startup, `validate_production_security()` aborts boot under `APP_ENV=production` if default development keys or wildcard CORS origins remain present, while pure ASGI security-header middleware hardens every response and `/api/v1/health/ready` verifies database connectivity.

sox_hash_chain.py
def compute_audit_hash(prev_hash: str, actor: str, action: str, payload_json: str, created_at: str) -> str:
    digest_input = f"{prev_hash}|{actor}|{action}|{payload_json}|{created_at}".encode("utf-8")
    return hashlib.sha256(digest_input).hexdigest()

Every expense policy exception check, receipt deduplication finding, IRS/GAAP category evaluation, and approval decision chains into an immutable SHA-256 SOX log under `/api/v1/audit/`. Combined with an offline deterministic `mock` adapter for CI, local Ollama routing, and default outbound PII redaction (`LLM_REDACT_PII_FOR_CLOUD=true`), teams keep sensitive tax and banking identifiers on their own network while shipping verified code across Ruff, Mypy, pytest, Vitest, `npm audit`, and Trivy scans.

Building internal financial automation or reconciling messy ERP data? Learn more about our Full-Stack Engineering and AI Engineering engagements, or book a technical call.

Applied Architecture

Production Case Studies & Capabilities

Explore how these engineering patterns are deployed in production systems and available through client engagements.

Case Study

AI Finance Operations Platform

Open-source Python (FastAPI), async SQLAlchemy 2.0 + PostgreSQL/pgvector, and React 18 finance operations platform featuring SHA-256 deduplicated PDF/CSV/JSON ingestion, three-way PO/receipt/invoice reconciliation, AP/AR settlement matching, 13-week cash flow scenarios, Controller HITL gates, and SHA-256 SOX audit chaining.

Read Case Study
Related Engineering Service

AI Engineering & LLM Integration

Many AI initiatives fail in production due to prompt fragility, high token latency, hallucination risks, and lack of structured evaluation. I bridge the gap between experimental LLM prompts and deterministic software engineering.

Related Engineering Service

Software Architecture & System Design

Fast-moving teams frequently accrue hidden architectural liabilities: tangled domain logic, unmaintainable monoliths, or over-engineered microservices that paralyze development.

Related Engineering Service

Full-Stack Engineering

Companies often struggle with fragile web applications, slow delivery cycles, and disjointed client-server boundaries. I build robust, production-grade applications that scale seamlessly from day one without architectural debt.

Frequently Asked Questions

Why combine deterministic three-way matching rules with AI explanations in finance operations?
Accounting tolerances—unit price variance, short-delivery quantity mismatches, and duplicate invoice hashes—must be deterministic and reproducible across audits. Pairing rule-based ledger matching with local LLM narrative explanations speeds controller triage without ever letting a probabilistic model invent accounting figures.
How does AP/AR memo matching enforce controller human-in-the-loop approval?
Bank feeds often arrive with noisy descriptions such as ACH DEBIT or WIRE TRANSFER truncated by payment processors. Matching logic normalizes memos and proposes invoice settlement candidates with confidence scores, then persists them in a pending queue that only a controller role can approve or reject before ledger state updates.
What protects financial PII and SOX audit records in a self-hosted deployment?
Sensitive vendor tax IDs, bank identifiers, and employee expense notes are processed locally via Ollama by default, while LLM_REDACT_PII_FOR_CLOUD=true strips PII prior to any optional cloud inference. Every state-changing controller action appends to a hash-chained SHA-256 audit table that detects altered records.
Share this technical guide

Need Help Solving This in Your Application?

I partner with founders, executives, and engineering leaders to design architectures, resolve production bottlenecks, and deliver resilient software.

Related Technical Articles