News Case study

Case study

B2B Sales Management: Order Processing with Agentic AI

In the fast-paced world of wholesale distribution, managing incoming B2B purchase orders can quickly become a bottleneck. Discover how Dataflos engineered InfloAI to handle multi-channel order processing with agentic AI for Caroline Gardner.

Published 9 min read

Screenshot
Inflo - Purchase Order Review Queue

Case Overview: Order Processing with Agentic AI

In wholesale distribution, the inbox is a bottleneck. Purchase orders arrive as structured PDFs, half-typed emails, scanned photos, vendor-portal CSVs, and .msg files with cryptic WingDings attachments.

Each one ends up in the same place: a sales coordinator typing line items into Sage 200 by hand.

That was the daily reality at Caroline Gardner, a UK greeting card and stationery wholesaler with hunderds of accounts, a sprawling product catalogue, and a multi-tier pricing model — Order processing with agentic AI was a natural exploration course for them.

Their Sales team was spending hours each day re-keying orders arriving by email as text, excel, pdf, and jpeg.

Dataflos built InfloAI to fix this: a deterministic, self-healing agentic application that ingests purchase orders and self-bills from any channel, resolves them against Sage 200's master data, and produces import-ready CSVs, all with a human firmly in the loop for the genuinely ambiguous cases.

30%orders arriving by email in unstructured formats
~90%straight-through processing on known formats
70%+orders processed cleanly with no hand-keying

The Challenge: Untangling Multi-Channel Chaos

Caroline Gardner's order workflow had 4 compounding problems:

  • Unstructured, disparate formats: Roughly 30% of orders arrived by email — PDFs, raw email bodies, embedded photos, vendor-portal exports.
  • Vague, customer-specific language: Customers have their own unit of measurement. Orders might routinely say "6 cards" when the customer meant "6 packs of 36 cards"; SKUs were abbreviated, mislabelled, or written using the buyer's internal codes rather than CG's.
  • Layered pricing logic: A single line could resolve through any of 3 tiers — a customer specific price list, a product-group discount, or the standard list; with 166 group discount rules across 3,616 customers and 18,872 products.
  • An unforgiving target system: Sage 200's import expects latin-1-encoded CSVs in two precise shapes — a 49-column soheader and a 20-column sodetail — with uppercase account refs, valid analysis codes, and YYYYMMDD dates. One malformed row rejects the whole batch.

The Solution: InFloAI Architecture

We built InfloAI on a strict 3 layer separation — deterministic Python tools, LLM-powered agents, and a routing orchestrator — with a Next.js + FastAPI review surface on top.

Screenshot
Intelligent automated aggregation, parsing, and loading
1. The Orchestrator

The orchestrator is the central traffic controller.

When a file arrives, from Microsoft Graph polling an Outlook mailbox, a manual upload through the dashboard, or a watched folder — it runs a deterministic 6-step pipeline:

  1. 01parse
  2. 02extract
  3. 03apply learned overrides
  4. 04resolve customer + SKUs
  5. 05normalise quantities
  6. 06price
  7. 07verify

Every step is independently testable, and every agent call is captured in a PipelineTrace for after-the-fact debugging.

2. Specialised Sub-Agents (powered by Claude Sonnet 4.6)

Rather than a single monolithic prompt, we deployed a team of focused sub-agents:

Extractor Agent
Turns unstructured text or images into a canonical ExtractedPO JSON schema. Prompt rules disambiguate buy-from blocks from agent blocks, and supplier vs. buyer-internal SKU columns.
Lookup Agent
Fuzzy-matches customer names and SKUs against Sage's master data using rapidfuzz, with confidence-banded escalation to Azure AI Search for semantic recall.
Quantity Agent
Converts vague UOM ("2 cases", "a dozen") into accurate single-unit multiples using each product's pack-size metadata.
Verifier Agent
Runs the three-tier pricing waterfall, flags variances, detects duplicates, and assigns a per-line confidence score. Below threshold goes to review queue. Above is ready to export.
Learner Agent
Turns user corrections into permanent, scoped overrides. Writes are atomic (lock + temp + rename) so a crash mid-save can never corrupt the override store.
Explorer Agent
A conversational agent that operators can ask questions of ("why did this PO go to review?", "did we ever ship this customer with this SKU before?"), wired into the same tools the deterministic pipeline uses.
3. Resilient Document Parsing

PDFs are the challenging part of B2B order ingestion. We built a 4 tier fallback parser:

  1. 01PyMuPDF
  2. 02Docling
  3. 03Azure Document Intelligence
  4. 04Claude Vision
  1. PyMuPDF for clean, text-layer PDFs.
  2. Docling for structured tables.
  3. Azure Document Intelligence (prebuilt-invoice) for complex layouts.
  4. Claude Vision for scanned photos and corrupted files.

When all 4 fail, the orchestrator now returns an attribution-rich error — which parser failed, how, and what the operator should check on the host — rather than a generic "no text found" string. This was the difference between a 30 minute root-cause hunt and a 30 second one during a recent AVD parser-stack outage.

4. Sage 200 Reject Prevention

Sage's import is unforgiving. A single lowercase SKU, a stray space in an account ref, or a missing analysis code rejects the whole batch. We added three layers of defence:

  • Writer boundary normalisation — account refs and SKUs are uppercased and stripped at the edge of the system, not buried in business logic.
  • Pre-flight validator — every CSV is checked against the customer master, product master, analysis-code rules, and structural shape before it is written to disk.
  • Validation failure routing — when pre-flight fails, the order is reverted to review with each individual defect surfaced as a flag, so the operator gets a checklist rather than a stack trace.
5. Failed-Ingest Visibility

Earlier versions had a quiet failure mode: if extraction crashed (encrypted PDF, parser regression, model rate-limit), the email was marked-as-read and the failure lived only in a log file.

We changed the contract: every email that arrives at SageFlow becomes a queue row, even when extraction fails.

The operator sees a "Ingest failed" pill, the original source file, and a "delete and retry" path — no AVD log access required.

The Tech Stack & Tooling Decisions

InfloAI Traces
InfloAI Agent Tracing

Production-grade agentic AI is mostly an exercise in saying "no" to abstractions.

Here's what we picked, and why.

Custom SDK wrapper over a framework

We built a thin wrapper around the Anthropic Python SDK rather than adopting LangChain or LlamaIndex for the agent loop. Off-the-shelf frameworks obscure prompt mechanics, making it hard to debug why an agent made a decision. A custom wrapper gives us deterministic control over prompt injection, tool schemas, history compaction, and streaming. We use LangSmith for observability, but never for execution.

Skills, not super-prompts

Our first iteration tried to teach the LLM all of CG's pricing logic in the system prompt. Predictably, it hallucinated prices on edge cases. We stripped the business logic out of the prompt and into deterministic Python "Skills" (ProductResolutionSkill, QuantityNormalizationSkill, SelfBillDetectionSkill, OverrideApplicationSkill). The LLM now decides when to call a skill; the skill decides what the answer is. Hallucinated prices went to zero.

Hybrid persistence: Azure Table + local-first fallbacks

The audit trail and override store live in Azure Table Storage, authenticated via zero-secret Managed Identities — a hard requirement from the client's IT security team. But every persistent component also has a local-JSON fallback path, so the entire app runs on a developer laptop with nothing but an ANTHROPIC_API_KEY. We don't make engineers stand up Azure to fix a bug.

Single-origin production deployment

The new UI is Next.js 15 + Tailwind v3 (App Router, React 19, server components for the SSR shell) talking to a FastAPI backend over a single origin. In dev they run on separate ports; in production, FastAPI serves the static Next bundle. No CORS in prod, no SPA-rebuild-on-every-deploy, one systemd service to monitor. Authentication is JWT in an HttpOnly cookie, with a CSRF double-submit token on every mutation.

Server-Sent Events for live work

Long-running operations — processing a 12-page PDF, streaming an Explorer chat response, broadcasting a new pipeline trace — all push to the UI over SSE, with loop.call_soon_threadsafe fan-out from worker threads into FastAPI's StreamingResponse. No WebSockets, no polling. The 6-step process pipeline shows up in the UI as it happens; the agent chat streams tokens as they arrive.

Optimistic locking, not last-write-wins

Two reviewers can sit on the same order without conflict — until they both try to save. We use If-Match headers carrying an ISO8601 ETag against last_modified; a stale write returns 409 with the current state in the body, and the UI surfaces a "Reload / Keep my edits" banner rather than silently overwriting someone else's work.

Human In The Loop

The New Review Surface

The original Inflo shipped with a Streamlit dashboard.

It got us to MVP fast, but as users grew — multiple concurrent reviewers, a need for spreadsheet style line editing, keyboard driven navigation — Streamlit's single session model started to bite.

We rebuilt the front end on Next.js without touching the orchestrator.

Inflo - Order Details
Human in a loop review and approval.

The new dashboard surfaces:

Three queue views
Inbox cards, dense Smart Table, and Lane view (Ready / Review / Blocked / Duplicate) — switchable instantly, persisted per user.
Sticky inspector pane
A 408 px right-rail that follows the queue, showing confidence breakdown, issues, and one-click Approve / Approve and Export / Preview CSV / Mark as Reviewed actions.
Order detail with split view
The original PDF or email pinned on the left, an editable spreadsheet of line items on the right with Excel-style cell navigation, locked-price glyphs, and live total recomputation.
Live process page
Drop a file or pick from examples; watch the 6-step pipeline tick through in real time over SSE; expand the agent reasoning panel to see exactly what the Extractor / Lookup / Verifier agents did.
Traces page
Every PipelineTrace and AgentTrace, with waterfall timing bars (green / yellow / red) and a live SSE feed of new traces as they're recorded.
Agent chat with palette
Token-streamed conversation with the Explorer agent (tool-call pills render as the agent calls into the deterministic skills), and a global Cmd-K command palette for navigation, search across customers / products / orders, and quick actions.
Settings consolidation
Sage path config, manual Outlook poll, override management, and account profile, all in one place. Path validation classifies UNC vs. drive-letter vs. local on startup so reviewers don't silently lose connectivity to the share.

The result is a surface that scales to the whole team and stays out of their way: keyboard-driven for power users, click-driven for casual ones, and instrumented end-to-end so the engineering team can see exactly what every agent is doing.

The Impact

InfloAI replaced a manual, per order keyboarding workflow with a deterministic pipeline that the team can trust and audit.

Key wins:

  1. Hours back per day

    Sales coordinators no longer hand-key the 70%+ of orders that arrive cleanly. They review exceptions instead of typing line items.

  2. ~90% straight-through processing

    On known formats. Confidence-banded routing means the genuinely ambiguous cases — and only those — reach a human.

  3. Self-healing on user corrections

    Every manual fix becomes a permanent override. The same mistake never lands in the queue twice.

  4. Hard-to-corrupt persistence

    Atomic writes everywhere state is touched (lock + .tmp + rename). A crash mid-save leaves the previous file intact.

  5. Reject-resistant exports

    The pre-flight validator has caught lowercase SKUs, missing analysis codes, and account refs that don't exist in the customer master — before writing to the data-exchange folder. Sage rejections dropped to near-zero.

  6. Operational visibility

    Every email becomes a queue row, every parser failure carries attribution, every agent call carries a trace. The engineering team has stopped debugging from log files.

  7. Zero-secret enterprise security

    Deployed natively on the client's Azure VM using Managed Identities. No hardcoded credentials, no secret rotation pain, full data sovereignty.

What's Next for SageFlow

InfloAI

With the Next.js + FastAPI cutover complete and the Sage import path hardened, the roadmap turns to depth:

  • Cross-format learning — generalising the Learner Agent so an override learned on a PDF transfers to the same customer's CSV format.
  • Self-bill reconciliation — extending the same pipeline to inbound self-bills, where the customer is telling CG what they owe rather than what they want.
  • Active dashboards — turning the Traces page into an SLO surface (parser success rate, model latency, queue clearance time) so operations can spot drift before users feel it.
  • Wider rollout — packaging the architecture for other Sage-200 wholesalers facing the same multi-format intake problem.

Eliminate manual data entry from your operations

Looking to streamline your operational workflows with Agentic AI? Contact the Dataflos team today to explore how bespoke AI automation can transform your business.

Book a 30 minute audit