BlogArtificial Intelligence
Process Order Emails with AI: An Architecture Case Study
By Dominik Pototschnig25 min

In this article
A wrong answer in a chat is annoying. A fabricated product in an approved ERP order can cause a real mis-shipment.
That is precisely why robust AI-assisted order processing does not begin with a spectacular prompt. It begins with boundaries: Which email is actually an order? Which customers and products may the model select at all? What must a person review? Under what conditions may anything be written to the ERP? And which personal data leaves which system in the process?
A project for WG Salesmanagement shows how order emails and PDF attachments can be turned into structured, reviewable order proposals. The interesting part is not the individual model call. What matters is the surrounding chain: a Microsoft 365 mailbox, master-data matching, retrieval-assisted candidate search, structured output, downstream validation, human approval, duplicate prevention and Xentral integration.
A note on transparency: the reviewed development snapshot uses the Gemini Developer API. Vertex AI is not yet implemented in this snapshot; it has been prepared as a possible future migration path. The full technical basis and its limitations are set out at the end of this article.
The short answer for decision-makers
Robust AI-assisted order processing is distinguished from a demo by controlled data, validated outputs, limited business impact and measurable operations.
- An order email is unstructured; an ERP order is not. Bridging the two requires more than text recognition.
- The model should not freely generate customer or product numbers. It selects from a controlled candidate set; unknown IDs are removed afterwards.
- RAG does not mean chatting with documents here. Relevant customers and products are retrieved from genuine master data before the model call; Google describes this basic pattern as Retrieval-Augmented Generation.
- A schema checks the form, not automatically the truth. Quantities, units, assignments and business rules require further controls.
- Human-in-the-loop is an operating model, not a button. Exceptions, corrections, responsible people and escalation paths must work in day-to-day operations.
- Vertex AI can support data-protection-compliant processing, but does not automatically make it GDPR-compliant. Under the GDPR, the contract, legal basis, data minimisation, region, deletion and access controls remain specific responsibilities of the operator; Google also documents its own retention cases and required configurations.
Evidence for the project-specific statements: private repository snapshot, commit 3655d58, reviewed on 15 September 2026. This note supports the code path examined, not production operation.
For an SME, the first investment question is therefore not “Which model should we choose?”, but: In which narrowly scoped process can we measure value and risk with real evidence?
The process problem at WG Salesmanagement
WG Salesmanagement describes itself as a sales and consulting partner. In the project examined, one application represents two separate company contexts, each with its assigned mailbox and Xentral access. The second company’s name is not required for the architecture decision and is deliberately not published here.
Orders do not arrive as clean API messages. They arrive as email text, HTML messages or PDFs, often containing tables, customer-specific product descriptions, purchase-order numbers, alternative delivery addresses and units written in different ways. The target system, by contrast, needs unambiguous fields: customer, product, quantity, unit, purchase-order number and, where applicable, delivery information.
This brings two worlds together:
- Input: linguistic, layout-dependent, sometimes incomplete and written by third parties.
- ERP: structured, referential and capable of creating business impact.
A model can interpret this gap well. It should not bear sole responsibility for it. The project approach therefore divides the task into deterministic and probabilistic steps. Anything that can reliably be established from senders, numbers, rules or database queries is resolved before the model becomes involved. The model handles the remaining ambiguity. The application then checks its output again.
This is an important architecture principle: Use AI where interpretation is necessary; use conventional software where a rule can be checked reliably.
How to process order emails with AI: from inbox to ERP proposal
The reviewed development snapshot implements the following flow:
- Email intake: The application retrieves messages from the assigned mailbox via Microsoft Graph. For robust operations, webhooks and delta queries can be combined so that a missed event does not remain a permanent blind spot. Microsoft documents both change notifications and delta queries for messages. The snapshot supports the Graph retrieval path, but not the claim that both safeguards are jointly operated in production.
- Storage: Email content and permitted PDF attachments are assigned to the correct company context and stored without duplicate records.
- Initial resolution: Senders, known contacts, rules and previous corrections provide deterministic clues.
- Candidate search: Customers and products come from the Xentral mirror. Depending on the size of the master-data set, either the entire relevant set or a narrowed selection found through exact, fuzzy-text and semantic search is passed on.
- Extraction: The model receives the email, PDF, context and closed candidate set. It returns a structured object rather than free-form prose.
- Downstream validation: The schema, permitted IDs and minimum business requirements are checked outside the model.
- Decision: A person can compare the original document with the proposal, correct it, reject it or approve it. A separate automated mode is possible, but is disabled by default in the data model.
- ERP hand-off: State, completeness and duplicate checks run before any write operation. Only then can an order be created in Xentral.
Project evidence: private repository snapshot, commit 3655d58, reviewed on 15 September 2026. “Implemented” refers to the code path, not to its production activation or acceptance.
This chain is deliberately longer than a “PDF in, JSON out” demo. Each additional control point addresses a different class of error.
OCR, rules or language model: which approach solves which problem?
Not every order-processing workflow needs a language model. The right solution depends on the variability of the inputs and the potential harm caused by an error.
The following table is a qualitative editorial assessment, not a universally applicable ranking.
| Approach | Well suited when | Typical limitation | Indicative effort |
|---|---|---|---|
| Templates and fixed rules | there are only a few stable formats with unambiguous fields | layout and language variants generate many exceptions | low to medium |
| OCR plus mapping | scanned documents need to be read and known fields transferred | text recognition does not resolve ambiguous customer or product assignments | medium |
| General LLM call | a rapid feasibility test for interpretation is needed | free-form output, hallucinations and missing ERP boundaries | initially low, risky in operation |
The technical choice is not yet a purchasing decision. Whether standard software or a custom solution makes more commercial sense is compared later using the same must-have criteria and total costs.
The most dangerous option is often not “too little AI”, but a persuasive model prototype without a controlled hand-off into the business process.
What RAG actually means in this application
RAG stands for Retrieval-Augmented Generation: before the model is called, relevant information is retrieved from a controlled source and supplied as context. In this project, “retrieval-assisted, closed-set extraction” is the more precise description.
The application searches for candidates through as many as three routes:
- Exact: Do customer, product or other unambiguous numbers match?
- Fuzzy text: Does fuzzy matching find similar names and spellings?
- Semantic: Is the meaning similar even when different words are used?
The semantic route uses embeddings—numerical representations of textual meaning. pgvector makes it possible to compare them directly in PostgreSQL; the project search combines this route with conventional matches.
For smaller data sets, however, the snapshot uses the entire customer or product master rather than a limited result set. This can avoid missing relevant matches, but increases the volume of data transmitted. That matters for both data protection and cost, particularly where customer names and addresses are involved. RAG is not automatically data minimisation.
Project evidence: private repository snapshot, commit 3655d58, reviewed on 15 September 2026. The code does not identify the search thresholds as having been calibrated on production data.
The most important safeguard comes after retrieval: the model may return only IDs from the candidate set supplied to it. If it invents another identifier, the application removes it and lowers the overall confidence. This substantially reduces one dangerous class of error. It does not prove that an allowed candidate is the correct one.
RAG does not prevent prompt injection either. An email comes from outside the organisation and can contain text that looks like an instruction to the model. The project code encapsulates and constrains external text; the OWASP guidance on prompt injection likewise recommends layered controls. The robust boundary is not “The model received strict instructions”, but: After independent checks, what effect can its output still have?
A later provider change also affects search. If the embedding model or its representation space changes, the existing customer, product and correction representations must be regenerated. Otherwise, the search would no longer be comparing like with like.
PDF understanding and structured output are two different tasks
Many order PDFs contain tables. Plain text extraction may find every word while losing the relationship between a row, its quantity and its unit. The reviewed code therefore passes PDFs to the Gemini Developer API as file parts using @ai-sdk/google. The official Google provider for the AI SDK documents this input form. Google’s document-understanding documentation for Vertex AI demonstrates the corresponding platform capability, but is not evidence that the current project already uses Vertex.
The result is then validated against a Zod schema. The AI SDK supports structured output against a specified schema. This ensures that fields, types and the basic shape match what the application expects.
The boundary matters:
- A schema can check whether
quantityis a number. - On its own, it cannot check whether the PDF actually says 12 units rather than 21.
- It can require a customer ID to be represented in the expected form.
- On its own, it cannot prove that this ID belongs to the buyer.
The application therefore combines structural validation with the candidate restriction, minimum requirements and a review interface. “Valid JSON” is an interface property, not a quality verdict on the order.
Project evidence: private repository snapshot, commit 3655d58, reviewed on 15 September 2026.
What a migration to Vertex AI would mean technically
The snapshot uses @ai-sdk/google with an API key. The official Vertex provider for the AI SDK is a separate package and requires Google Cloud authentication as well as project and region details. The existing provider interface reduces the scope of the change, but does not turn the migration into a simple environment-variable update.
Human-in-the-loop: not everything is manual, but every impact is accountable
Human-in-the-loop refers here to an operating mode in which a named person can compare the original document with the AI proposal, correct it and approve it before any business-impacting hand-off.
The assistant places the original message, PDF and extracted fields side by side in a review queue. Customers, products, quantities and other details can be corrected. The processing state remains traceable.
The current code contains two operating modes:
1. Controlled proposal mode
A person reviews and approves the proposal. This mode is suited to the start of a deployment, new senders, unusual documents and cases in which an error could cause significant harm.
2. Conditional automated hand-off
An automated mode that can be enabled separately for each organisation may pass on fully recognised cases above a configurable threshold. High model confidence alone is not enough: the customer and line items must be assigned, plausible quantities must be present, the hallucination guard must not have removed anything, and manual corrections exclude the case from the automated route.
The snapshot does not establish whether this automation is enabled in production. Claiming that “fully automated order processing is in use” would therefore be unsupported. Automation is not an all-or-nothing switch: it must be earned for each risk and case class. The pilot section below explains how to measure shadow operation, supervised approval and a later automation gate.
Project evidence: private repository snapshot, commit 3655d58, reviewed on 15 September 2026. Automation is disabled by default in the data model.
The ERP write path needs more protection than the model call
Xentral is the system of record for customers, products, prices and orders. The application-managed PostgreSQL database mirrors master data for search and stores the application’s own process data. The Xentral API provides resources for this purpose and documents, among other things, creating a sales order via V3.
An approved proposal should still not end as an arbitrary API call. The code examined centralises the write path and checks several conditions before execution:
- a global write switch,
- the correct processing state,
- a complete customer and complete line items,
- master data belonging to the correct organisation,
- an application-level guard against concurrent duplicate processing,
- a remote search for an existing external order identifier,
- traceable status and error values.
Deletion remains blocked in the client. Write operations are not blindly retried automatically. This matters because many ERP APIs do not provide a universal idempotency key, and a timeout does not reveal whether the order was already created before the interruption.
Project evidence: private repository snapshot, commit 3655d58, reviewed on 15 September 2026. Global Xentral write access and automated hand-off are disabled by default.
The manual fallback belongs in the architecture
Operations should have a fallback plan so that order intake can continue when the AI, mailbox retrieval or ERP integration is unavailable. It should include a documented manual-entry route, a named owner and deputy for the exception queue, and a procedure for uncertain write operations: first reconcile in Xentral whether an order was created despite the timeout, then continue deliberately. Open and previously claimed items should be reviewed after a restart. Response and recovery targets should be agreed before the pilot; automation should remain disabled until these routines work reliably.
The lesson is transferable: The more direct the real-world effect, the more deterministic the last mile must be. The model may interpret. Conventional software decides whether, where and how often data is written, based on verifiable states.
Two company contexts, one application: separation is part of the product
The project defines two company contexts with separate mailboxes and separate Xentral access credentials. The application assigns business records to an organisation and verifies current membership on every request. An active organisation ID in a session does not, by itself, count as proof of access. The second company’s name is immaterial to this technical point and remains unpublished.
This may sound like technical hygiene, but it is commercially critical. A missing organisation condition could do more than produce the wrong view. It could mix customer data, product numbers or orders across company contexts.
Among other things, the snapshot supports the existence of:
- organisation-scoped repository access,
- composite uniqueness rules scoped to the organisation,
- separate Xentral credentials for each organisation,
- application-level AES-256-GCM encryption for those Xentral tokens.
It does not establish that every stored email and PDF is additionally encrypted at application level. Hosting, disk encryption, backups, key operations and access logs must also be assessed separately.
Project evidence: private repository snapshot, commit 3655d58, reviewed on 15 September 2026. Code evidence is not a substitute for infrastructure or authorisation testing in the real operating environment.
Data protection when processing order emails with Vertex AI
When executed, the extraction path implemented in the snapshot transmits the sender, subject line, email body, native PDF content, rules or correction context, and customer and product candidates to the Gemini Developer API. Selected product and customer data may also be sent to the same provider for embeddings. The repository review did not establish which production contractual, regional, retention and logging settings actually apply. Before this can be published as a real-world reference, these points must be verified against the running system.
The statement “We use Vertex AI, so the AI is GDPR-compliant” would remain too broad even after a migration. The GDPR assesses a specific processing operation. Under Article 5, relevant requirements include purpose limitation, data minimisation, accuracy, storage limitation and security. Article 28 is relevant to processors; Article 32 to technical and organisational measures. The article “Is local AI the only GDPR-compliant option?” examines the wider infrastructure comparison between local AI and cloud platforms; this article focuses on the specific data flow for order emails.
Vertex AI can provide important building blocks:
- Google provides a Cloud Data Processing Addendum and places its cloud services in context in a GDPR resource.
- Google documents a training restriction: customer data is not used to train or fine-tune managed models without prior permission or instruction.
- The same page also describes retention cases and required configurations, including abuse monitoring, optional request and response logging, and certain grounding features. “Zero Data Retention” is not a phrase that should be adopted without checking the features in use.
- Vertex offers regional and global locations as well as an EU multi-region. The location documentation warns that an endpoint alone does not provide a blanket guarantee of data residency or processing in that region. An operator that needs to control the ML processing region should not select the global endpoint without further assessment.
- Security controls, including data residency, customer-managed encryption keys, VPC Service Controls and Access Transparency, depend on the model and feature; according to the overview, preview models are excluded.
Data-protection check for this specific process
Before a production go-live, at least the following questions should be answered in writing:
- Which fields from the email, PDF, customer master and history are sent to which provider?
- Is the complete customer master genuinely necessary in the prompt, or would narrower retrieval be sufficient?
- Which legal basis and information obligations apply?
- Are data-processing arrangements, subprocessors and transfers documented?
- Which region and endpoint are actually enforced?
- Which provider and application logs exist, and how long are they retained?
- Who may view original documents, proposals and correction histories?
- When are emails, PDFs, vectors and audit data deleted or anonymised?
- How are access, rectification and erasure requests, as well as security incidents, handled?
- Which tests and approvals demonstrate that the documented configuration is actually running?
This is not legal advice. It is the technical evidence list that makes a data-protection assessment concrete in the first place.
When I would assess standard software—and when a custom solution
A custom AI application may make sense when the requirement is not merely to read a document, but to map a specific process between mailbox, master data, rules, review and ERP. It is not automatically the most economical option.
1. Must-have criteria first, vendors second
| Must-have criterion | Evidence required from standard software | Evidence required from a custom solution |
|---|---|---|
| supported mailboxes, PDFs and languages | test with the organisation’s own representative documents | specify as an acceptance test |
| Xentral fields, special rules and duplicate prevention | require a demonstration of the product’s specific functions and limitations | specify the data model, checks and error paths |
| separation of companies and permissions | require evidence of the role model and technical isolation | test organisational boundaries automatically |
| human review and exception handling | demonstrate the review interface, queue and export route | build roles, states and the manual fallback route |
| data protection and data location | assess contract, subprocessors, regions, logs and deletion | provide the same evidence for every service used and for the organisation’s own operations |
| operations and recovery | clarify service scope, support hours and data export | fund responsible staffing, monitoring, backups and recovery |
2. Test the standard solution—or identify an evidenced gap
A standard solution is the obvious first candidate if the organisation’s own documents, Xentral fields, approvals and company contexts are supported by its standard feature set, and lower internal operating effort matters more than bespoke logic. This should be tested with representative documents and genuine exception cases, not merely in a vendor demo.
Custom development should proceed only if this test reveals a material gap, or if organisation-specific rules, correction knowledge and risk-tiered approvals have demonstrable strategic value. “Custom” is not a quality mark; it is an investment that brings its own operating responsibilities.
3. Compare the options using the same business-case calculation
- Current monthly cost: monthly order volume × (processing time + rework time per order in hours) × fully loaded hourly cost + expected monthly cost consequences of errors + fixed monthly process costs.
- TCO of the standard solution: implementation and data cleansing + licences + integrations and updates + internal operations + remaining review, exception and error costs.
- TCO of the custom solution: development and data cleansing + model and infrastructure + integrations and updates + monitoring, backup and on-call cover + data-protection documentation + remaining review, exception and error costs + expected switching costs.
- Comparison: calculate the current process, standard software and custom development over the same period, in the same currency, using the same assumptions for wages, volume, risk and growth.
Only after review time, correction rates and error consequences have been measured in a pilot do assumptions become robust inputs. Low model costs do not automatically make the overall process inexpensive—and higher technical costs do not automatically rule out a viable business case.
A pilot that answers more than “The demo works”
A good pilot needs genuine variability without uncontrolled ERP impact. I would structure it in four steps.
Assign accountability before the start
| Role | Responsibility in the pilot |
|---|---|
| Executive management | budget, acceptable harm from errors and the final investment decision |
| Order-intake process owner | target process, case classes, quality targets and business acceptance |
| Daily reviewer and deputy | review proposals, record corrections and manage the exception queue |
| IT or integration | mailbox, database, Xentral, monitoring, backups and recovery |
| Data-protection owner | data flow, legal basis, contracts, deletion and data-subject processes |
| External implementation partner | technical implementation, testing, documentation and hand-over—not approval of the business risk |
The following allocation is a conservative starting point and must be confirmed by named people before the pilot. Each row has exactly one decision owner; contributions from other roles do not replace that owner.
| Decision gate | Decision owner | Required contribution |
|---|---|---|
| Pilot start | Executive management | the process owner, IT and data protection provide the basis for the decision |
| Activation of automation | Executive management | the process owner demonstrates that the quality gate has been met; IT and data protection confirm their approval points |
| Immediate operational stop | Process owner | the daily reviewer and IT report the trigger and secure the manual route |
| Response to a security incident | IT or security owner | data protection and executive management are involved in accordance with the incident plan |
| Final go or no-go | Executive management | the process owner presents measurements, risks and the TCO comparison |
Step 1: Process and verified target values
- collect representative order types that may lawfully be used,
- minimise sensitive data or replace it with synthetic data for testing,
- define target values for customer, product, quantity, unit and purchase-order number,
- determine the potential harm and stop criteria for errors in each field.
Step 2: Shadow operation
- process emails without writing anything to the ERP,
- compare every model response with the verified target values,
- measure failures and unresolved cases as separate categories,
- classify prompt, retrieval and master-data errors separately.
Step 3: Supervised approval
- review the original document and proposal side by side,
- capture corrections in a structured form,
- measure review time per order,
- deliberately test duplicate, permission and error paths.
Step 4: Investment decision
| Metric | What it answers |
|---|---|
| Share of orders identified correctly | Does the system correctly recognise an incoming order? |
| Customer and product matches per field or line item | Where do business-level matching errors arise? |
| Quantity and unit matches | Is there a risk of incorrect quantities or packaging units? |
| Share of proposals approvable without correction | How much genuine relief is possible? |
| Median and spread of review time | Does work reliably become shorter, or merely different? |
| Erroneous hand-offs and duplicates | Does the business-impacting path remain within the risk boundary? |
| Cost per correctly approvable proposal | How do model, infrastructure and operating costs compare? |
| Age of unresolved exceptions | Does exception handling work in day-to-day operations? |
Targets must not be adjusted retrospectively to fit the outcome. They belong before the pilot.
Decision at the end of Step 4:
- Go: Quality and risk targets have been met, data-protection and operational evidence is complete, and responsible people are named.
- Extend the pilot: Value is visible, but a clearly bounded case class needs more data or better master data.
- Clarify: Contracts, region, deletion, permissions or ERP impact remain unresolved.
- Stop: Critical erroneous hand-offs, an unmanageable exception rate or no robust economic benefit.
The pilot succeeds when it enables a robust decision. That may include a well-founded decision not to automate.
Frequently asked questions
Which data-protection questions arise when order emails are processed in Vertex AI?
Vertex AI is not automatically “GDPR-compliant”. The specific processing operation must meet the GDPR. In particular, the operator remains responsible for the purpose, legal basis, data minimisation, region, retention, access and data-subject processes; Google’s documentation on retention and required configurations must be assessed for the features actually used.
What is RAG in order processing?
In the reviewed private repository snapshot at commit 3655d58, the application retrieves customer and product candidates from genuine master data before extraction. This gives the model operational context and constrains it to a controlled set. The model is not retrained as a result, and errors remain possible. Google describes the general pattern, independently of this specific project, in its RAG architecture overview.
Can AI write orders directly to an ERP?
Technically, yes; Xentral, for example, documents an API for creating sales orders. Whether AI may trigger this path is a risk and operating decision. At a minimum, it should be preceded by state checks, completeness checks, permitted IDs, duplicate prevention, access controls, an audit trail and an emergency stop. Where an error could cause significant harm, a person should approve the order first.
Does structured JSON output prevent hallucinations?
No. Structured output in the AI SDK can bind the shape and data types to a schema. A formally valid customer or product ID can still be wrong in business terms. Controlled candidates, downstream validation and approval proportionate to the risk are still required.
How much does a solution like this cost?
No credible figure is possible without the volume, document lengths, model, match rate, review time, integrations and operating requirements. The decisive figure is not the price of a model call, but the total cost per correctly approvable order.
Conclusion: the model is not the employee—the process is
The WG Sales development snapshot demonstrates a robust direction: unstructured order emails are not translated blindly into an ERP. Master data constrains the selection, structured output creates an interface, conventional checks catch known classes of error, and people retain a controlled decision path.
It is equally transparent about what remains to be proven: production configuration, the migration to Vertex, data-protection approval, data minimisation, measured accuracy and commercial value. Naming these unresolved points does not weaken the project. It distinguishes robust digitalisation from marketing claims.
A sensible next checkpoint: process discovery
Inputs required: monthly order volume, anonymised sample documents or samples that have been legally approved for use, systems involved, current processing and rework time, known consequences of errors and expressly excluded case classes.
Outputs: a process and data-flow map, initial risk list, comparison of the current process, standard software and a custom approach, an evidence-based effort range, and a pilot plan with metrics and stop criteria.
Decision at the checkpoint: no pilot, a test of a standard solution, or a clearly bounded custom pilot. The result is not automatically an implementation engagement.
If you would like to run this checkpoint for your order-intake process, you can book a process discovery meeting. For more implementation context, see AI applications for businesses and digitalisation for SMEs.
Sources and date of review
- WG Salesmanagement: company and service profile
- General Data Protection Regulation, consolidated text
- Google Cloud: GDPR
- Google Cloud Data Processing Addendum
- Vertex AI: zero data retention and documented retention cases
- Vertex AI: locations and endpoints
- Vertex AI: security controls for generative AI
- Google Cloud: document understanding
- Google Cloud: RAG architecture with generative AI
- AI SDK: Google provider
- AI SDK: Google Vertex provider
- AI SDK: structured data generation
- Microsoft Graph: change notifications
- Microsoft Graph: delta query for messages
- Xentral API: introduction
- Xentral API: create a sales order via V3
- pgvector: vector and hybrid search in PostgreSQL
- OWASP: LLM prompt injection prevention
Technical basis: private repository snapshot at commit 3655d58 dated 8 September 2026, reviewed on 15 September 2026. This article describes a development snapshot, not certification or legal advice. Links and provider information were checked on 15 September 2026.
- AI order processing
- order emails
- RAG
- Google Vertex AI
- Xentral
- SMEs
More articles
My Web Stack for SMEs: Static First, Dynamic Where Needed
Why Wogenfels starts SME websites with static Astro, separates dynamic functions through Hono, only prepares persistence, and automates quality checks.
Hermes Agent or n8n? How SMEs Can Build a Controlled AI Employee
Hermes Agent or n8n? See when SMEs should use an agent, a fixed workflow, or a controlled combination of both.
Which AI Models Can Run Locally? Memory, Costs and SME Use Cases
Which AI models can run locally? An SME guide to model size, RAM/VRAM, quantisation, useful tasks, hardware tiers and total cost of ownership.
