Delivered remotely for a business based in Rotterdam, Netherlands. Names withheld by agreement.
Project Overview
Industry: Accounts Payable & Document Capture
Solution scope: An accounts payable invoice ingestion, structured OCR extraction, three-way PO matching, and approval workflow platform built with Python, FastAPI, React, TypeScript, PostgreSQL, Celery, Redis, and AWS S3.
Context: Logistics hubs and distributors process thousands of supplier invoices monthly across email attachments, EDI feeds, and scanned packing slips. Finance clerks spend weeks transcribing VAT numbers, matching freight charges against purchase orders, and chasing email confirmations from dock supervisors. We engineered an automated AP pipeline in Python and React that extracts line-level data with bounding-box provenance, reconciles invoices against POs and receipts in PostgreSQL, and routes exception approvals cleanly.
Accounts Payable Bottlenecks
Manual data entry delayed month-end accruals. Clerks re-typed vendor headers, VAT breakdowns, and freight line items per PDF, creating backlogs before financial closes.
Email approval threads obscured payment liability. Without a centralized sign-off state machine, teams missed early-payment discounts and struggled to answer supplier payment queries.
Unchecked variances leaked margin. Unit-price markups, duplicate billing numbers, and unreceived partial shipments slipped past reviewers when POs lived in separate procurement tools.
Cross-border invoice formats broke rigid scripts. Suppliers used differing decimal separators, multi-page summary tables, and mixed reverse-charge VAT notations that defeated static regex rules.
Architectural Strategy
Preserve immutable originals with full field provenance. Every incoming PDF lands untouched in AWS S3 under a content hash before any transformation runs, and every extracted field stores its exact page number and bounding box so auditors can trace any ledger number back to its visual source.
Combine deterministic normalization with confidence-gated human review. Rather than pretending extraction is infallible, the Python pipeline scores every header and line attribute; high-confidence, variance-free PO matches flow straight through while uncertain fields queue cleanly for keyboard-fast React verification.
Isolate heavy document parsing from interactive APIs. FastAPI validates uploads and serves reviewer queues synchronously, leaving multi-stage OCR, table extraction, and ERP exports to horizontally scalable Celery workers.
Enforce relational financial integrity in PostgreSQL. Vendor masters, PO balances, goods receipts, and invoice allocations lock transactionally so two invoices can never over-consume the same purchase-order quantity.
Core Capabilities
- Multi-channel invoice intake: Automated shared-mailbox polling, drag-and-drop multi-PDF batch splitting, and SFTP vendor drops with instant deduplication.
- Line-item & tax extraction: Captures supplier IBAN/VAT IDs, invoice dates, currency codes, multi-rate tax lines, and detailed SKU or freight line items.
- Configurable 2-way & 3-way PO matching: Evaluates invoice totals against purchase orders and warehouse goods receipts with per-category quantity and price tolerance rules.
- Interactive bounding-box React verifier: Side-by-side PDF viewer highlighting low-confidence fields, keyboard-driven GL coding, and inline variance comparison tables.
- Policy-based approval routing: Multi-step sign-off trees driven by cost center, spend threshold, department head, and variance status with out-of-office delegation.
- Duplicate & fraud anomaly guardrails: Flags recycled invoice numbers, mismatched bank IBANs against vendor master records, and suspicious round-sum entries.
- ERP voucher export & status sync: Generates validated posting payloads and tracks payment-run status back onto the AP dashboard.
Technical Architecture
Python & FastAPI application services. FastAPI handles authenticated REST endpoints, Pydantic validation, upload pre-signing, and approval transitions. Shared Python domain modules normalize locale-specific numbers (1.250,00 vs 1,250.00), VAT rules, and currency conversions consistently across API and workers.
Celery & Redis extraction pipeline. New documents enqueue a directed Celery workflow: PDF split/classify → native text or OCR extraction → vendor master lookup → duplicate & IBAN verification → PO/receipt matching. Redis brokers queues separately for fast interactive uploads versus bulk overnight ERP syncs.
PostgreSQL matching & workflow ledger. PostgreSQL maintains vendors, purchase_orders, goods_receipts, invoices, invoice_lines, and approval_steps. Matching allocations record explicit quantity links between invoice lines and PO lines inside serializable transactions so remaining open PO balances stay exact.
AWS S3 & React workspace. Encrypted S3 buckets retain original files and rendered PNG page previews served via short-lived pre-signed URLs. The React and TypeScript frontend uses canvas overlays to draw field bounding boxes synchronized directly with form focus.
Flow: Email / Upload intake → AWS S3 raw vault → FastAPI & Celery OCR/normalization → PostgreSQL 3-way PO matching → React bounding-box verifier & approval routing → ERP ledger export
Technology Stack
| Category | Technology |
|---|---|
| Backend & ML runtime | Python 3.12 powering document pipelines, extraction normalization, and variance matching logic |
| API framework | FastAPI exposing async ingestion endpoints, Pydantic schema validation, and typed React APIs |
| Verification & ops UI | React and TypeScript delivering side-by-side PDF bounding-box review and approval queues |
| Primary database | PostgreSQL storing vendor masters, purchase orders, goods receipts, extracted invoices, and audit trails |
| Async task workers | Celery workers executing PDF rasterization, OCR inference, duplicate checks, and ERP sync jobs |
| Broker & cache | Redis acting as Celery message broker, result backend, and approval rule cache |
| Document archive | AWS S3 storing immutable original PDFs, page thumbnails, and SHA-256 content fingerprints |
| Ingestion channels | Dedicated IMAP/MIME email listener, bulk drag-and-drop uploader, and SFTP vendor dropbox |
| Observability | Per-document pipeline stage timings, OCR field confidence histograms, and ERP export dead-letter alerts |
Engineering Trade-offs & Solutions
| Challenge | Solution |
|---|---|
| Multi-page PDFs often bundled five separate vendor invoices inside a single email attachment | Added an automated page-boundary classifier in Celery that splits multi-invoice packets into discrete document records before extraction. |
| Scanned thermal receipts and skewed carrier bills produced noisy OCR tables | Coupled preprocessing deskew/contrast normalization with geometric row-clustering heuristics in Python and flagged sub-threshold rows for quick React confirmation. |
| Concurrent clerks opening the same verification queue risked editing identical invoices simultaneously | Added soft claim leases in PostgreSQL with optimistic version checks on save, displaying active reviewer indicators in the React queue. |
| Vendor bank IBAN changes on PDFs created high-severity payment fraud risk | Cross-checked extracted IBANs against locked vendor master records in PostgreSQL and enforced mandatory controller secondary verification on any mismatch. |
| Large multi-hundred-line utility and freight invoices slowed DOM rendering in the browser | Virtualized the React line-item grid and loaded PDF page images lazily on scroll so verification stays responsive on 200-line bills. |
| Downstream ERP endpoints went offline during nightly maintenance windows | Buffered approved exports through an idempotent Celery outbox with retry backoff and clear export-status badges for finance controllers. |
Security & Compliance
Strict segregation of duties. Role policies prevent the same user from creating a purchase order, altering vendor bank details, and approving the final invoice payout, enforcing clean internal financial controls.
Immutable audit & retention trail. Every automated extraction, manual field correction, tolerance override, and approval signature records actor identity, timestamp, and before/after values alongside the immutable S3 source document for statutory tax audits.
Private document delivery. Uploaded invoices live inside private, encrypted S3 buckets accessible only via authenticated FastAPI checks that issue short-lived pre-signed preview URLs.
Performance & Scale
Dedicated worker pools by SLA. Separating single-invoice interactive uploads from bulk SFTP/ERP batch sync queues prevents large month-end supplier drops from delaying clerks actively clearing urgent approvals.
Indexed financial queries. Composite PostgreSQL indexes across (company_id, status, due_date) and (vendor_id, invoice_number) keep aging payables dashboards and duplicate checks snappy as multi-year archives grow.
Operational Outcomes
- Accelerated invoice cycle times: Straight-through PO matches clear automatically while flagged exceptions present exact variance details and PDF highlights in one screen.
- Stronger spend & fraud control: Automated IBAN verification, duplicate blocking, and three-way receipt checks stop overbilling before funds leave the bank.
- Clean month-end accrual visibility: Finance controllers inspect every unapproved, disputed, and ready-to-post invoice in real time rather than hunting through personal inboxes.
- Frictionless ERP reconciliation: Standardized voucher exports carrying GL codes, tax buckets, and linked PO references eliminate manual journal re-entry.