- Supplier invoices are designed for people, not commerce systems.
- An AI extraction service can turn that document into structured fields.
- The client needed invoices received by email or uploaded against an order to enter a controlled review process.
- AI reads the document. It does not become the accounts-payable department.
The client problem
Supplier invoices are designed for people, not commerce systems. One PDF calls the order reference “PO Number”. Another puts it in the footer. Line items use supplier descriptions, taxes appear in different places and a scanned document may contain no machine-readable text at all.
An AI extraction service can turn that document into structured fields. The dangerous shortcut is to let the same probabilistic output choose the order, accept the invoice and trigger payment.
The client needed invoices received by email or uploaded against an order to enter a controlled review process. We built an asynchronous extraction pipeline around Medusa that records the original PDF, asks a specialised document service for a bounded schema, preserves confidence, proposes a seller-scoped order match and leaves acceptance and payment authority with deterministic business rules and people.
AI reads the document. It does not become the accounts-payable department.
The client problem begins with unstructured evidence
A marketplace can know exactly what was ordered and still receive a vendor invoice as a PDF attachment. Before anyone can reconcile it, the system needs ordinary facts:
- invoice number and date;
- vendor identity;
- purchase-order or marketplace order reference;
- property name and address;
- subtotal, tax, shipping and total;
- line descriptions, SKUs, quantities and prices.
Manual entry is slow and repetitive. It also introduces errors at the moment the document should be compared with canonical order and receipt data.
Extraction is therefore valuable. It reduces the cost of making the invoice searchable and reviewable. But the extracted values remain claims made by a document, interpreted by a model. They are not automatically the marketplace's truth.
That distinction shapes the whole architecture.
Keep the original document as the durable source
Every invoice attachment becomes its own source record before extraction starts. The record points to the stored PDF and carries its origin, filename, size, seller context, optional order mapping, review status and extraction lifecycle.
Email messages can contain several PDF attachments, so source identity includes the inbound upload and attachment position. A uniqueness constraint prevents the same attachment from producing duplicate invoice records during retries.
The original file remains available for human review. Structured fields are derived evidence, not a replacement for the document that the supplier actually sent.
This gives operations a stable case file: source, extraction attempt, proposed mapping, reviewer action and eventual invoice use can all be connected without hiding the PDF behind a transient AI response.
Validate the file before sending it to extraction
An .pdf suffix is not enough. The ingestion path reads the stored bytes and applies the platform's PDF validation before uploading them to the extraction provider.
That prevents unrelated or malformed attachments from entering an expensive asynchronous workflow merely because an email labelled them as invoices. File validation and bounded storage are security and cost controls as much as data-quality measures.
If the extraction provider or pipeline configuration is unavailable, the source moves to a failed state with a bounded error instead of remaining indefinitely “in progress”. The document itself is still present, so an operator can retry or waive extraction through an explicit process.
The system remains useful even when automation cannot complete.
Make extraction asynchronous and observable
Invoice parsing may involve OCR, layout analysis and model inference. Keeping an email request or browser upload open until all of that finishes would create fragile timeouts and poor feedback.
We modelled extraction as a lifecycle: not processed, queued, processing, completed, failed or waived. Queuing records the attempt and emits a dedicated event. A subscriber uploads the validated PDF, starts the configured pipeline and stores provider upload and job identifiers.
The provider later reports completion through a verified webhook path. The callback does not blindly trust its metadata: the application checks that the job belongs to the recorded source, ignores repeated webhook IDs and refuses to rewrite a source already completed or waived.
This turns external AI work into a resumable business process rather than a synchronous function call hidden inside invoice creation.
Ask for a narrow invoice schema
The extraction contract names the fields the business can use. It does not accept an arbitrary model-generated object and spread it across the database.
The normaliser searches the provider result for the configured invoice structure, unwraps fields, trims strings and accepts numbers only when they are finite. Line items are mapped into a fixed set of description, SKU, quantity, unit price and extended price.
Unknown or invalid values become null. Optional shipping is absent when it cannot be established. The code does not turn an empty field into zero or invent a vendor name from context.
Confidence travels alongside the values, including per-line-item fields. That makes uncertainty visible to later review rather than compressing every answer into the same apparent certainty.
Let AI propose the order, then apply deterministic eligibility
The model may extract an order number from the PDF. That is useful, but it is not enough to attach the invoice to any order with a similar display ID.
The application first parses the reference into a strict positive numeric display ID. It then searches for an eligible order belonging to the same seller. The query excludes draft orders, requires purchase-order payment terms and excludes orders already validated or paid through the relevant paths.
The match succeeds only when exactly one eligible order is found. Ambiguity produces no automatic mapping.
This is the key trust boundary. AI supplies a candidate identifier from an unstructured document. Deterministic commerce rules decide whether that identifier can refer to one current, unpaid order for the supplier in question.
Preserve manual corrections from late callbacks
Asynchronous jobs create a race with people. An operator may review the source, correct the order mapping or accept the invoice while an earlier extraction attempt is still running.
The completion path therefore checks the current record before applying automated mapping. Email-derived mapping is written only when the source has not been manually mapped and has not already been accepted.
Manual work has precedence. A late callback can still complete the extraction record and store its structured data, but it cannot casually overwrite the decision a reviewer made with more context.
The callback also carries its own identity. Processing the same webhook twice returns the current source rather than repeating side effects. A callback for a different job is ignored.
These controls are easy to miss when AI is demonstrated as a one-shot upload. They become essential in the real operating lifecycle.
Keep review state separate from extraction state
“Extraction completed” means that a service returned a structured result. It does not mean the invoice is correct, accepted or payable.
The source record therefore has a review status separate from extraction status. It can remain pending, be accepted, rejected, marked duplicate or superseded. The record stores who reviewed it and when.
An operator can compare the original PDF, extracted values, confidence and proposed order side by side. If the model failed to find an order, the reviewer can map it manually. If the document is a duplicate, the source can be classified without deleting history.
This separation prevents a common automation mistake: using technical completion as a business decision.
Do not give the extractor payment credentials or commands
The extraction service receives a document and a schema. It does not receive a tool that can mark an order paid, create a bank transfer or approve an invoice.
Payment-related state remains in Medusa and the surrounding procurement workflows. The order match is constrained by seller and payment status. Acceptance is a reviewed transition. Reconciliation can later compare the accepted invoice with order lines, receipts and totals.
This is stronger than adding a sentence to a prompt saying “do not pay”. Prompts guide model behaviour; capability boundaries enforce authority. A component that has no payment command cannot accidentally call one because it misunderstood the document.
When teams introduce AI into financial operations, authority should be minimised in code, not merely requested in natural language.
Send the provider only the document task requires
The same principle applies to data exposure. An extraction provider needs the validated invoice bytes and the schema required to read them. It does not need credentials for Medusa, unrestricted customer history or access to the organisation's other financial records.
Provider job identifiers and usage are stored as provenance, while application logs should avoid reproducing document contents or credentials. Retention and deletion rules can then be defined for the original business record and for the external processor independently.
This narrow exchange makes replacement possible too. If the business later changes document providers, the durable source, normalised invoice contract and review workflow remain inside the platform. Only the extraction adapter changes. The organisation is buying a reading capability, not transferring ownership of its invoice process to a model vendor.
Make failure an ordinary review outcome
Some PDFs will be unreadable. Some jobs will fail. Some documents will omit the order number. A robust workflow does not pretend otherwise.
The source keeps attempt counts, timestamps and a bounded error message. Failed extraction can be retried. Extraction can be explicitly waived with an actor, time and reason when a human can process the invoice without it.
Completed output that cannot produce a unique eligible order remains reviewable instead of being discarded. The human can inspect the document and supply the missing mapping.
This graceful fallback is what makes automation deployable. The system accelerates the ordinary path without blocking the business whenever the probabilistic component is uncertain.
What accounts payable actually gains
The operating sequence becomes clear:
- A supplier sends or uploads a PDF.
- The marketplace creates a durable source record and validates the file.
- A specialised service extracts only the invoice schema asynchronously.
- Normalised values, confidence and provider provenance return to the source.
- A strict seller-scoped query may propose one eligible order.
- A reviewer sees the PDF, extraction and mapping together.
- The reviewer accepts, corrects, rejects or classifies the source.
- Separate procurement rules decide what happens to the accepted invoice.
AI removes transcription work while every consequential decision remains explicit.
Why Medusa is useful for this boundary
Medusa already owns the order, seller relationship, payment type and commerce lifecycle that constrain the invoice. Its event and module system lets us add document ingestion and asynchronous extraction without placing probabilistic logic inside payment code.
We chose that extension boundary because the client's problem was not “use AI”. It was “process supplier invoices faster without weakening financial control”. The model is one replaceable worker in a larger, auditable workflow.
That is how useful AI enters commerce: narrow input, bounded output, deterministic eligibility, human authority and durable provenance.
If invoice PDFs still require repetitive entry, WeAreSouk can design a Medusa extraction and review workflow that uses AI for reading while keeping order mapping, acceptance and payment under control.
