HomeCase studiesAutomated Accounts Payable Invoice Capture and Three-Way...

Case study · Rotterdam, Netherlands

Automated Accounts Payable Invoice Capture and Three-Way PO Matching Platform

Accounts Payable & Document Capture

Finance teams processing high volumes of PDF and scanned supplier invoices waste days re-keying line items and chasing email approvals across procurement and warehouse managers. We engineered an accounts payable automation platform using Python, FastAPI, React, PostgreSQL, and Celery to ingest multi-format invoices, extract structured header and line fields, and run automated two-way and three-way purchase-order matching. Low-confidence fields route to a keyboard-driven React verification screen, while approved vouchers export cleanly to downstream ERP ledgers.

Industry
Accounts Payable & Document Capture
Solution
An automated invoice ingestion, OCR extraction, three-way PO matching, and approval routing web platform built with Python, FastAPI, React, PostgreSQL, and Celery.
Platforms
Web & API
Stack
Python · FastAPI · React · TypeScript · PostgreSQL · Celery
Location
Rotterdam, Netherlands · delivered remotely
Role
Engineering, with the team behind for mobile and QA

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.

01 — Questions

asked about this kind of project

How does the Python pipeline handle varied invoice layouts without requiring brittle per-vendor templates?

FastAPI dispatches incoming PDFs to Celery workers that combine native text-layer parsing for digital PDFs with OCR layout analysis for scans. Extracted tokens map through vendor-aware normalization rules—dates, IBANs, VAT IDs, and decimal conventions—returning per-field confidence scores and bounding-box coordinates.

What happens when extracted line items do not match the purchase order or goods receipt?

The matching engine compares invoice quantities, unit prices, and tax totals against PostgreSQL PO and warehouse receipt records using configurable tolerance bands. Clean matches fast-track to approval, whereas price variances or missing receipts route directly to the assigned buyer or warehouse lead with highlighted discrepancies.

How do accounts payable clerks verify uncertain fields quickly in the React interface?

React renders the original invoice page alongside extracted fields using PDF coordinate overlays. Clicking any flagged input zooms straight to the source bounding box, while keyboard shortcuts let clerks confirm or correct totals and GL codes without touching a mouse.

How does the platform catch duplicate vendor invoices sent across different channels?

Every document passes a two-tier duplicate screen: exact SHA-256 file hash detection in AWS S3 to block identical re-uploads, followed by fuzzy composite matching on normalized `(vendor_id, invoice_number, gross_amount, invoice_date)` inside PostgreSQL.

Why separate FastAPI request handling from Celery workers for document processing?

PDF rendering, OCR, and multi-line fuzzy PO matching can take several seconds per multi-page packet. Returning an immediate intake receipt from FastAPI while Celery executes heavy CPU tasks ensures bulk batch uploads never time out browser sessions or block reviewer API calls.

How do human corrections improve future extraction accuracy for recurring suppliers?

When a clerk corrects a misread supplier VAT number, line description, or GL coding in React, PostgreSQL records the delta against that vendor profile so subsequent invoices automatically apply learned vendor-specific aliases and default cost-center mappings.

03 — Similar project?

describe what is different about yours

Build yours.

Tell me what exists, what you need and the deadline. Fixed price for a defined scope, or $55/day (8–9 hours work) with a written plan first.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.