Skip to main content
D2 Automation Systems
Public case study 04
Document OperationsArchitecture prototype

D2 publishes architecture, implementation evidence and evidence boundaries separately so the reader can distinguish demonstrated system design from unverified production outcomes.

Read D2 evidence methodology
n8n Automation Portfolio
Architecture Prototype / AI Automation SystemRole: AI Automation Engineer / Workflow Architect

Selected project 04

AI Document Intelligence & Processing Pipeline

Structured Extraction, Classification, Validation & Operational Routing

A document-operations architecture that converts incoming business files into structured, classified and auditable data before downstream systems are asked to act on them.

n8nGmailGeminiStructured ExtractionSupabasePII RedactionAnomaly DetectionAudit Logging

01 · Business problem

Business documents contain meaning that operational systems cannot consume directly.

Invoices, forms, contracts, receipts, purchase orders and operational attachments often arrive as files or email content. Before they can trigger routing, database updates or reporting, their meaning must be converted into a controlled structured representation.

Unstructured input

Important fields are embedded in prose, labels, tables and attachments.

Operational ambiguity

Departments and owners cannot be assigned consistently from raw files alone.

Governance gap

Without logs and privacy handling, extraction creates another uncontrolled data path.

02 · Core pipeline

Document intake becomes a sequence of explicit processing stages.

The source begins with Gmail-triggered document intake, extracts file content, asks Gemini for typed fields, then applies deterministic categorization, anomaly checks, PII redaction and operational logging.

Incoming Email
Content Extraction
AI Field Extraction
Categorize + Tag
Anomaly Check
PII Redaction
Operational Logs
Database / Analytics

03 · Structured extraction

The first transformation is from document ambiguity to typed data.

The workflow uses n8n's file-content extraction before a Gemini-backed information extractor. The extraction contract names the fields the model is allowed to return instead of passing free-form prose downstream.

Incoming business document

Unstructured attachment / file content

Raw
Meaning is embedded in prose, tables, labels and document layout. Downstream systems cannot safely act on this representation directly.

Typed structured object

Fields · arrays · entities · tables

Structured
{
  "document_type": "…",
  "sender": "…",
  "recipient": "…",
  "date": "…",
  "amount": 0,
  "invoice_number": "…",
  "line_items": [...],
  "entities": [...],
  "relationships": [...],
  "tables": [...]
}
document_typesenderrecipientdateamountinvoice_numberline_itemsentitiesrelationshipstables

The extraction prompt explicitly asks for fields, tables, entities and relationships, and allows unknown attribute values to be omitted rather than invented.

04 · Deterministic vs AI

AI interprets document meaning. Workflow logic controls what happens next.

The architecture separates probabilistic semantic extraction from deterministic operational rules. This keeps department routing, tagging, anomaly thresholds, logging and privacy actions inspectable in workflow code.

AI interpretation

Extract semantic structure

Gemini is used to interpret document text and return named fields such as document type, sender, recipient, date, amount, invoice number, line items, entities, relationships and tables.

Deterministic operations

Route, validate, log and govern

Code nodes classify departments and owners, compute anomaly signals, redact matching PII patterns, route anomaly branches and prepare extraction/GDPR audit records for Supabase.

05 · Classification

Structured fields become operational routing signals.

The source categorization code maps document characteristics and keyword signals into department, process owner, compliance tags and a rule-based confidence value. These are workflow rules, not learned classification metrics.

Finance

CFO

Invoices · receipts · payments

Legal

General Counsel

Contracts · agreements · NDA

HR

HR Director

Resume · employment · offer

Operations

COO

PO · shipping · delivery

General

Document Controller

Uncategorized / review required

The workflow also emits rule-based tags such as ACCOUNTS_PAYABLE, LEGAL_REVIEW, PII_SENSITIVE, GDPR_RELEVANT, PROCUREMENT, LOGISTICS, CONFIDENTIAL and REVIEW_REQUIRED depending on matched conditions.

06 · Anomaly layer

Successful extraction is not the same as trustworthy data.

The source adds a deterministic anomaly engine after categorization. If the anomaly branch fires, a second Gemini-backed extractor produces an explanation, root cause, severity, recommended action and confidence field before anomaly logging.

Statistical amount signal

Flags amounts more than three standard deviations from available batch history when enough values exist.

Required-field check

Checks a configured list of expected fields and raises the anomaly score when fields are missing.

Format checks

Validates date, email and phone patterns when those values are present.

Duplicate signal

Builds a composite document/date/amount/vendor key to find similar records inside the processing set.

Date bounds

Flags dates more than one year in the future or more than ten years in the past.

Amount rules

Flags negative, zero or unusually large values according to explicit prototype thresholds.

Prototype boundary: the anomaly code references fields such as vendor/category that are not part of the primary AI extraction contract, and its configured threshold key does not match the configuration field name. Those contract mismatches would need to be resolved before production use.

07 · PII & governance

Privacy handling is part of the processing path, not a post-processing note.

The workflow includes a recursive regex-based PII redaction engine and a separate GDPR audit-log path. The implementation is useful as an architectural prototype, but it also exposes areas that require stronger production controls.

Recursive PII redaction

The code recursively scans nested strings and arrays for SSN, credit-card, email, phone, passport and driver-license patterns, replacing matches with explicit redaction tokens.

GDPR-oriented audit record

After extraction logging, the workflow prepares audit timestamp, action type, process owner, document type and a PII-redaction indicator for a Supabase GDPR audit table.

Production hardening required

The prototype retains a serialized original-data copy inside PII metadata. A production design should move raw sensitive content into separately protected storage with explicit retention and access controls rather than treating that copy as already secure.

08 · Observability

The workflow defines separate evidence paths for extraction, anomalies, audit and system metrics.

Rather than treating the final structured object as the only output, the source maintains additional records intended to explain what was processed, what looked suspicious and how the system is behaving over time.

Extraction logs

Supabase document_extractions receives timestamp, confidence, processing status and workflow execution context.

Anomaly logs

Anomaly explanations are written to a separate Supabase anomaly_logs path when the anomaly branch is taken.

GDPR audit logs

A distinct Supabase gdpr_audit_logs path records processing/audit metadata.

Dashboard + model metrics

Scheduled branches calculate dashboard telemetry and correction/model metrics; these are metric definitions, not demonstrated achieved results.

Source caveat: the weekly branch is named “Model Retraining,” but the source analyzes user corrections, derives updated parameters/metrics and writes model_metrics; it does not demonstrate an actual model fine-tuning or retraining API call. The case study therefore treats it as a feedback-analysis and model-metrics prototype.

09 · Business applications

A structured document layer can feed many operational workflows.

These are example applications enabled by the architecture, not claims about deployed customers or observed business outcomes.

Accounts payable
Invoice processing
Insurance documents
Logistics paperwork
Contract intake
Customer onboarding
Back-office processing

10 · Engineering principles

Treat document extraction as an operational data contract.

01

Extract once, structure early

02

Do not send raw document ambiguity downstream

03

Keep AI output constrained

04

Separate AI interpretation from deterministic business rules

05

Log every important processing stage

06

Treat privacy as part of architecture

11 · Production roadmap

The prototype already exposes the boundaries a production document platform would need to harden.

The items below are possible next steps. They are not presented as implemented capabilities in the source workflow.

OCR fallback for scanned or image-only documents
Document versioning and lineage
Human verification queues
Confidence scoring by extracted field
Schema versioning and contract enforcement
Vendor-specific extraction policies
Curated evaluation datasets

Final takeaway

“The objective is to turn documents from passive files into structured events that business systems can act on.”

The workflow demonstrates the architecture of that transition: controlled extraction, deterministic classification, anomaly inspection, privacy handling and auditable operational outputs.

Back to portfolio

D2 Automation Systems

Need a system designed around a real operating constraint?

D2 maps the process, source of truth, deterministic rules, failure paths and evidence boundary before recommending the automation scope.