Salesforce Flow submits an attached invoice to a published MuleSoft Intelligent Document Processing action, receives the result through a platform event, and creates Invoice__c and InvoiceLine__c records only after a fail-closed gate: execution status, required fields, arithmetic consistency and idempotency on execution ID. Low-confidence or incomplete extractions route to human review in IDP and a Salesforce review task, never written as-is. Covers the Named Credential, External Service import, thresholds, REST test harness, multi-page pitfalls and rollout.
Tags: intelligent-document-processing, idp, salesforce, salesforce-flow, invoice-processing, platform-events, external-services, named-credentials, human-in-the-loop, document-extraction, finance
Invoice Extraction with MuleSoft IDP and Salesforce Flow: Validated Writes and Human Review
Deliverable: A Salesforce-native invoice intake: a user attaches an invoice to an Account, MuleSoft Intelligent Document Processing (IDP) extracts the fields, and a Flow writes an Invoice__c header and InvoiceLine__c rows only when every required field is present, confident and arithmetically consistent. Anything else lands in a human review queue and is never written as-is.
Objective: Invoices arrive as images and PDFs attached to customer or vendor records, and someone re-keys them into Salesforce. That is slow, and the fix people reach for, wiring OCR output straight into a record create, is worse: a misread total or a missing invoice number becomes a clean-looking record that finance later trusts. Working looks like this: extraction runs asynchronously, high-confidence and internally consistent invoices become records automatically, and uncertain ones are routed to a reviewer who confirms or corrects the field before anything is created.
What's Getting Built
- IDP Document Action (MuleSoft IDP, Invoice document type) — extracts header fields and a line-item table, with per-field Visibility, Label, Required and Threshold settings and a reviewer assigned for low-confidence fields · published to Exchange; submit with
POST /api/{apiVersion}/organizations/{orgId}/actions/{actionId}/versions/{actionVersion}/executions, read with GET .../executions/{executionId}
- MuleSoft_IDP_US (Named Credential + External Credential) — authenticated callout from Salesforce to the IDP runtime, provisioned through MuleSoft Services
- External Service
{ExternalServiceName} (generated from the published action) — exposes postDocument and getDocumentActionExecution as Flow actions
- Post Document Flow (record-triggered, Account) — finds the latest attached file and submits it to IDP in
fireAndForget mode
IDPCallback__e (Platform Event) — fields executionId__c, originId__c, origin__c; published by IDP when extraction finishes
- Get Document Flow (platform-event-triggered) — fetches the result, runs the validation gate, then creates
Invoice__c and InvoiceLine__c or creates a review task
Invoice__c / InvoiceLine__c (custom objects) — header (master) and line items (master-detail)
Prerequisites
- Anypoint Platform org with IDP entitlement, permission to author and publish a Document Action, and a Connected App (client credentials) with IDP scopes for scripted testing. Entitlement and Connected App approval are usually the slowest items; request them first.
- Salesforce org with Flow, Platform Events, External Services and MuleSoft Services. Connecting MuleSoft Services (Setup, MuleSoft, Services, choose the control plane for your region) is a manual step that backs the Named Credential.
- A sample set of real invoices from the target process, including at least one with a faint scan, a missing field and a multi-page layout. Do not build against a single clean specimen.
- A reviewer group on the IDP side and a Salesforce queue or user for review tasks, agreed with finance before build.
- A decision on which Salesforce record owns the attachment (this plan uses Account, stored in
BillAccount__c) and which file types are accepted.
- Salesforce CLI (
sf) for deploying metadata, curl and jq for the REST test harness.
Choose your path
- Salesforce-orchestrated (this plan) — Choose this when users already work in Salesforce, volume is modest, and extraction plus the record write fit comfortably in Flow. No Mule code; the integration is configuration.
- Mule-orchestrated — Choose this when invoices arrive from email, SFTP or an ERP, or when validation needs vendor master or PO matching from systems Salesforce cannot reach. A Mule Process API submits to IDP, polls for the result, validates, and calls Salesforce; the same gate and review queue apply.
Architecture
1. Deploy the Salesforce foundation
- Create
Invoice__c with InvoiceNumber__c (Text), InvoiceDate__c (Date), DueDate__c (Date), SubtotalAmount__c, TotalTaxAmount__c, TotalAmountWithTax__c (Currency 16,2) and BillAccount__c (Lookup to Account). Rename the Account child relationship (for example IDP_Invoices) to avoid a collision.
- Create
InvoiceLine__c with Description__c, Quantity__c, UnitPrice__c, LineAmount__c and a master-detail to Invoice__c.
- Add what extraction does not give you but the gate needs:
ExecutionId__c (Text, External ID, unique) on Invoice__c for idempotency.
- Create the
IDPCallback__e platform event with executionId__c, originId__c, origin__c.
- Deploy the Named and External Credential
MuleSoft_IDP_US (Secured Endpoint, URL set to the IDP runtime for your region; the _US suffix is this build's region, so name yours to match your control plane). Keep the extracted fields non-required at the schema level: IDP may return nothing for a field, and the Flow gate, not a database error, should decide what happens next.
2. Author and publish the IDP Document Action
- In the IDP canvas create a Document Action from the Invoice template and upload a representative invoice.
- For each field, set Visibility, Label, Required and Threshold deliberately. Mark invoice number, invoice date, total and tax required; set higher thresholds on money fields than on descriptive ones. A field below its threshold, or a required field not found, is what moves the execution to
MANUAL_VALIDATION_REQUIRED.
- Assign a reviewer so uncertain fields appear as tasks in the IDP task inbox rather than being silently accepted.
- Run, inspect Fields and Tables, then Save and Publish. From the Exchange entry for the published action, record
apiVersion, orgId, actionId and actionVersion from the POST method.
- Import the published action into Salesforce as an External Service through MuleSoft Services, using the
MuleSoft_IDP_US Named Credential and the getDocumentActionExecution operation. This generates the postDocument and getDocumentActionExecution actions and the Apex types the Flows bind to. Flows that reference them cannot deploy before this step.
3. Prove extraction by REST before touching Flow
- Obtain a client-credentials token from the Anypoint control plane (
POST /accounts/api/v2/oauth2/token), submit the file as multipart field file, and poll the execution every 5 seconds up to a bounded number of attempts.
- Treat statuses explicitly:
SUCCEEDED is extractable; MANUAL_VALIDATION_REQUIRED means a reviewer must finish in the IDP task inbox first; FAILED and ERROR are terminal; a timeout is a failure, not "probably fine".
- Keep client ID, secret and action identifiers in an untracked env file or a secrets manager. Never commit them.
4. Build the Post Document Flow
- Record-triggered, after save, on Account. Look up the latest
ContentDocumentLink for the record, then the IsLatest ContentVersion.
- Add an entry decision so only intended accounts and file types are processed. An unconditional trigger resubmits documents every time anyone edits the Account, so also guard on "no
Invoice__c or in-flight submission already exists for this ContentVersion".
- Build the request:
origin = Salesforce, originId = the Account Id, originFileContentId = the ContentVersion Id, originCallbackDestination = IDPCallback__e. Call postDocument with actionId, actionVersion, apiVersion, orgId and mode = fireAndForget. Hold these identifiers in custom metadata or Flow constants, not scattered literals.
- Fire-and-forget keeps the user's save fast; the cost is that failures arrive later. Add a fault path on the action that records the failure on the Account.
5. Build the Get Document Flow with a fail-closed gate
- Trigger on
IDPCallback__e. Capture executionId__c and originId__c, then call getDocumentActionExecution.
- Gate 1, status: proceed only when the execution status is
SUCCEEDED. For MANUAL_VALIDATION_REQUIRED, FAILED, ERROR, an empty pages collection or a null response, create a review task and stop. Never create an invoice from a partial result.
- Gate 2, required fields:
invoiceNumber, invoiceDate, total and tax must be non-null and parse to the target types (Date and Currency). A missing or unparseable value routes to review.
- Gate 3, arithmetic:
subtotal + tax must equal total within a currency tolerance, and the sum of line price values must equal subtotal, after allowing for known adjustment lines (shipping, discounts, line-level tax) that you list explicitly. A mismatch means a misread digit somewhere; route to review with both numbers on the task.
- Gate 4, idempotency: look up
ExecutionId__c first. Platform events can be redelivered, and a duplicate must create nothing.
- Pass: map the header fields (see the sample), set
BillAccount__c from originId__c, create the header, then bulk-create the lines with the new header Id in a single DML.
- Handle multi-page invoices explicitly. Header fields should come from one defined page (usually the first with an invoice number), and line tables from all pages. Assigning page fields inside a loop leaves the last page's values in the record, which silently corrupts totals.
- Review task: assign to the reviewer queue and include the Account, the
executionId and a reason code (STATUS, MISSING_FIELD, ARITHMETIC, FAULT). The reviewer corrects the field in IDP; the resulting SUCCEEDED callback re-enters this flow and passes through the same gate.
6. Security and compliance
- Invoices carry vendor banking, tax and pricing data. Restrict
Invoice__c, InvoiceLine__c and the review queue by permission set; restrict the Named Credential to the integration permission set.
- Credentials live in the External Credential and Connected App; no secret in Flow XML, custom metadata, task text or logs. Scrub identifiers before committing any metadata to source control.
- Log execution ID, status, gate outcome and reason code. Never log full extracted payloads, bank details or file contents.
- Decide retention for attachments and IDP execution history, and whether extracted values count as financial records under your audit regime.
- Confirm the IDP control plane and runtime region matches where invoice data may be processed.
Sample payload — IDP execution result and resulting field mapping
The shape follows the elements the Flow reads: status, pages[].fields.<name>.value and pages[].tables.table1[] rows. Values are placeholders. If your published action's response schema exposes a per-field confidence property, add it to the gate.
{
"executionId": "{executionId}",
"status": "SUCCEEDED",
"pages": [
{
"fields": {
"invoiceNumber": { "value": "{invoice-number}" },
"invoiceDate": { "value": "{yyyy-mm-dd}" },
"dueDate": { "value": "{yyyy-mm-dd}" },
"subtotal": { "value": "{amount}" },
"tax": { "value": "{amount}" },
"total": { "value": "{amount}" }
},
"tables": {
"table1": [
{
"description": { "value": "{item-description}" },
"quantity": { "value": "{qty}" },
"unitPrice": { "value": "{amount}" },
"price": { "value": "{amount}" }
}
]
}
}
]
}
Mapping: invoiceNumber to InvoiceNumber__c; invoiceDate to InvoiceDate__c; dueDate to DueDate__c; subtotal to SubtotalAmount__c; tax to TotalTaxAmount__c; total to TotalAmountWithTax__c; callback originId__c to BillAccount__c. Table rows: description to Description__c, quantity to Quantity__c, unitPrice to UnitPrice__c, price to LineAmount__c.
Deterministic checks
Invoice__c is created only when status is SUCCEEDED, all required fields parse, subtotal + tax = total within tolerance, and line amounts sum to subtotal. Any other result creates a review task and zero invoice records.
- Replaying the same
IDPCallback__e (same executionId__c) creates no second Invoice__c; uniqueness on ExecutionId__c enforces it.
- A null, empty or unparseable IDP response, or a Flow fault on the
getDocumentActionExecution call, routes to review with reason FAULT, never to the create path.
- A
MANUAL_VALIDATION_REQUIRED execution produces no record until the reviewer completes it and a SUCCEEDED callback arrives.
- Flow tests (and Apex tests if you wrap the gate in an invocable) cover each reason code, the duplicate event and the multi-page case, and pass before deployment.
- The REST harness exits nonzero for
FAILED, ERROR and timeout.
Testing and validation
- Happy path: attach a clean invoice to an in-scope Account; confirm the submission, callback, one
Invoice__c and the expected InvoiceLine__c count, and that the header total equals the printed total.
- Low confidence: attach a degraded scan; confirm the execution reaches
MANUAL_VALIDATION_REQUIRED, no invoice exists, the reviewer completes it in IDP, and exactly one invoice appears afterwards.
- Edge case that breaks naive builds: a multi-page invoice where page two carries a page subtotal or a blank header region. Verify header values still come from the intended page and the line table spans both pages.
- Missing required field: remove the invoice number from a test document and confirm a
MISSING_FIELD task and no record.
- Arithmetic: use an invoice where one digit is misread; confirm the gate catches it even though each field looks plausible alone.
- Second edit to an in-scope Account: confirm no resubmission.
- Mapping correctness: compare every created field against the document for a sample of real invoices, not only that the Flow ran.
Phased rollout
Phase 1 — Connect
- Deploy objects, platform event and credentials to a sandbox; connect MuleSoft Services; publish the Document Action; prove extraction with the REST harness on real invoices.
Phase 2 — Map and validate
- Import the External Service, deploy both Flows, tune per-field thresholds against a labelled sample, and measure how many invoices route to review and why. Tighten or relax thresholds from evidence.
Phase 3 — Production
- Deploy through your normal pipeline, run in review-everything mode for a short period, then enable automatic creation. Assign queue ownership, alerting on stuck executions, and a periodic review of gate reason codes.
Success metrics
- Share of invoices created without human touch versus routed to review, split by reason code.
- Field-level correction rate by reviewers, per field, to guide threshold tuning.
- Time from attachment to a usable
Invoice__c, and time spent in the review queue.
- Count of invoices with confirmed errors found after creation (target zero; any is a gate gap).
- Duplicate invoice count and failed or timed-out execution count.
Troubleshooting
- Flows will not deploy — Likely cause: the External Service was not yet imported, so the action and Apex types do not exist. Fix: complete the MuleSoft Services import first, using the exact service name the Flows reference.
- Nothing happens after upload — Likely cause: entry decision not met, no
ContentDocumentLink on the record yet, or the callout failed. Fix: check the Flow interview log and the Named Credential's principal access.
- Callback never arrives — Likely cause: the execution is waiting on a reviewer (
MANUAL_VALIDATION_REQUIRED) or the callback destination name does not match the event. Fix: check the IDP task inbox and the originCallbackDestination value.
- Duplicate invoices — Likely cause: platform event redelivery or an unguarded Account trigger. Fix: unique
ExecutionId__c and the in-flight guard in step 4.
- Wrong totals on multi-page invoices — Likely cause: page fields assigned in a loop so the last page wins. Fix: choose the header page explicitly and sum lines across pages.
- 401 from IDP in the REST harness — Likely cause: Connected App lacks IDP scopes or the wrong control plane region. Fix: recheck scopes and region.