AI Invoice Data Extraction: A Validation-First Blueprint
Reading an invoice with a language model is the easy part of invoice automation. The hard part is deciding what to do with what comes back. A model that reads "39.98" as "39.00" produces a perfectly formatted, completely wrong invoice, and if that flows into the accounts system, nobody notices until the books do not balance. The reliable design is validation first: never trust the extracted numbers, recompute them, and send anything that does not add up to a person.
This blueprint covers that second half: checking the extraction, handling money correctly, catching duplicates, and routing every invoice to accepted, needs review or rejected. The extraction call itself is one step in the middle, and it can be any model.
What this article is, and is not
The checking code ran on Laravel 13, PHP 8.3 and MySQL, with 11 automated tests (27 assertions) on made-up invoices. I did not call a model, read a PDF or use real invoice data, so I make no claims about how accurately any model reads invoices, and nothing here is a result from a real business. The fixed rules (the arithmetic, the duplicate key, the thresholds) are examples to adapt: your tax rules, currencies and approval limits will differ.
The flow
invoice (PDF, image, e-mail)
1. get the text (OCR or text extraction: outside this article)
2. ask a model for JSON in a fixed shape (use strict output validation)
3. check it: shape, amounts, arithmetic, plausibility
4. look for a duplicate
5. route: accepted -> post to the accounting system (once, idempotently)
needs_review -> a person compares it with the document
rejected -> unusable output: retry the extraction or send to a person
6. keep the original document, the model output and the reasons (audit trail)
Principle 1: Money is not a float
In PHP, 3 * 0.1 == 0.3 is false, because binary floating point cannot represent 0.1 exactly. An invoice with three lines at 0.10 would fail a check that was written with floats, and one that "passes" with a tolerance can hide a real error. The checker converts every amount to integer cents first and does all arithmetic on integers. It also refuses an amount with more than two decimals instead of rounding it: "48.745" in an invoice is far more likely to be a misread than a rounding detail.
app/Services/Invoices/Money.php
<?php
namespace App\Services\Invoices;
use InvalidArgumentException;
final class Money
{
/**
* Converts "12.50", 12.5 or 12 into integer cents, refusing anything with more than two decimals.
* Doing the arithmetic in integers avoids float errors such as 3 * 0.10 !== 0.30.
*/
public static function toCents(mixed $value): int
{
$text = is_float($value) ? rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.') : trim((string) $value);
if (! preg_match('/^-?\d+(\.\d{1,2})?$/', $text)) {
throw new InvalidArgumentException("Not a valid amount with at most two decimals: {$text}");
}
[$whole, $fraction] = array_pad(explode('.', ltrim($text, '-'), 2), 2, '0');
$cents = ((int) $whole) * 100 + (int) str_pad($fraction, 2, '0');
return str_starts_with($text, '-') ? -$cents : $cents;
}
}
Principle 2: Recompute, never trust
The model reports line totals, a subtotal, tax and a total. The checker recomputes each relationship and compares:
- every line: quantity times unit price equals the line total
- the line totals add up to the subtotal
- subtotal plus tax equals the total
Any mismatch sends the invoice to review, with the reason spelled out so the person knows where to look. Rejecting is reserved for output that is structurally unusable, such as a missing field, an amount with extra decimals or a date that does not exist. A mismatch is different: the extraction may be right and the document itself wrong, which is the person's call.
Principle 3: Plausibility flags are not errors
Some invoices are valid but deserve a look: an unexpected currency, a date in the future or more than two years old, a negative total that may be a credit note, and any total above your automatic approval limit. These go to review too, so a person decides, and the limit is a setting you control.
app/Services/Invoices/CheckResult.php
<?php
namespace App\Services\Invoices;
final class CheckResult
{
/** @param array<int, string> $reasons @param array<string, mixed> $normalized */
public function __construct(
public readonly string $status, // accepted | needs_review | rejected
public readonly array $reasons,
public readonly array $normalized = [],
) {}
}
app/Services/Invoices/InvoiceChecker.php
<?php
namespace App\Services\Invoices;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Validator;
use InvalidArgumentException;
/**
* Checks what a model extracted from an invoice. It never trusts the numbers:
* it recomputes them, and anything that does not add up goes to a person.
*/
class InvoiceChecker
{
public function __construct(
private array $currencies = ['USD', 'EUR', 'GBP'],
private int $reviewAboveCents = 500_000, // amounts over this always get a human look
) {}
public function check(array $data): CheckResult
{
// 1. Shape. Failing here means the output is unusable: reject it.
$v = Validator::make($data, [
'supplier' => ['required', 'string', 'max:200'],
'invoice_number' => ['required', 'string', 'max:100'],
'issue_date' => ['required', 'date_format:Y-m-d'],
'currency' => ['required', 'string', 'size:3'],
'lines' => ['required', 'array', 'min:1'],
'lines.*.description' => ['required', 'string'],
'lines.*.quantity' => ['required', 'numeric'],
'lines.*.unit_price' => ['required'],
'lines.*.total' => ['required'],
'subtotal' => ['required'],
'tax' => ['required'],
'total' => ['required'],
]);
if ($v->fails()) {
return new CheckResult('rejected', $v->errors()->all());
}
// 2. Amounts become integer cents. More than two decimals is a misread, not a rounding detail.
try {
$lines = array_map(fn ($l) => [
'description' => $l['description'],
'quantity' => (float) $l['quantity'],
'unit' => Money::toCents($l['unit_price']),
'total' => Money::toCents($l['total']),
], $data['lines']);
$subtotal = Money::toCents($data['subtotal']);
$tax = Money::toCents($data['tax']);
$total = Money::toCents($data['total']);
} catch (InvalidArgumentException $e) {
return new CheckResult('rejected', [$e->getMessage()]);
}
// 3. Arithmetic. A mismatch usually means a misread digit: a person checks it against the document.
$reasons = [];
foreach ($lines as $i => $line) {
if ((int) round($line['quantity'] * $line['unit']) !== $line['total']) {
$reasons[] = 'Line '.($i + 1).': quantity x unit price does not equal the line total.';
}
}
if (array_sum(array_column($lines, 'total')) !== $subtotal) {
$reasons[] = 'The line totals do not add up to the subtotal.';
}
if ($subtotal + $tax !== $total) {
$reasons[] = 'Subtotal plus tax does not equal the total.';
}
// 4. Plausibility. Soft flags: not wrong, but worth a person's attention.
if (! in_array(strtoupper($data['currency']), $this->currencies, true)) {
$reasons[] = "Unexpected currency: {$data['currency']}.";
}
$date = CarbonImmutable::createFromFormat('Y-m-d', $data['issue_date']);
if ($date === false || $date->format('Y-m-d') !== $data['issue_date']) {
return new CheckResult('rejected', ['The issue date is not a real date.']);
}
if ($date->isFuture()) {
$reasons[] = 'The issue date is in the future.';
}
if ($date->lt(now()->subYears(2))) {
$reasons[] = 'The issue date is more than two years old.';
}
if ($total < 0 || $subtotal < 0) {
$reasons[] = 'Negative amounts: this may be a credit note.';
}
if (abs($total) > $this->reviewAboveCents) {
$reasons[] = 'The total is above the automatic approval limit.';
}
return new CheckResult($reasons === [] ? 'accepted' : 'needs_review', $reasons, [
'supplier_key' => self::supplierKey($data['supplier']),
'invoice_number' => trim($data['invoice_number']),
'total_cents' => $total,
'currency' => strtoupper($data['currency']),
]);
}
public static function supplierKey(string $name): string
{
return trim(preg_replace('/[^a-z0-9]+/', ' ', strtolower($name)));
}
}
Principle 4: Duplicates are normal
Suppliers send the same invoice twice, by e-mail and by post. Pipelines also retry. The intake step looks for an earlier extraction with the same normalised supplier name, invoice number and total in cents, and sends a second copy to review as a possible duplicate instead of accepting it. The supplier name is normalised so that "Northwind Supplies Ltd" and "NORTHWIND supplies ltd." match. The lookup is backed by an index.
app/Services/Invoices/InvoiceIntake.php
<?php
namespace App\Services\Invoices;
use App\Models\InvoiceExtraction;
class InvoiceIntake
{
public function __construct(private InvoiceChecker $checker) {}
/** Checks, detects duplicates, and stores the outcome. Nothing is "accepted" if it might be a second copy. */
public function handle(array $extracted): InvoiceExtraction
{
$result = $this->checker->check($extracted);
$status = $result->status;
$reasons = $result->reasons;
if ($status !== 'rejected') {
$original = InvoiceExtraction::query()
->where('supplier_key', $result->normalized['supplier_key'])
->where('invoice_number', $result->normalized['invoice_number'])
->where('total_cents', $result->normalized['total_cents'])
->whereIn('status', ['accepted', 'needs_review'])
->orderBy('id')
->first();
if ($original) {
$status = 'needs_review';
$reasons[] = "Possible duplicate of extraction #{$original->id}.";
}
}
return InvoiceExtraction::create([
'status' => $status,
'payload' => $extracted,
'reasons' => $reasons ?: null,
] + $result->normalized);
}
}
database/migrations/..._create_invoice_extractions_table.php (up)
Schema::create('invoice_extractions', function (Blueprint $table) {
$table->id();
$table->string('status', 20)->index(); // accepted, needs_review, rejected
$table->string('supplier_key', 120)->nullable(); // normalised supplier name
$table->string('invoice_number', 100)->nullable();
$table->bigInteger('total_cents')->nullable(); // money as integers
$table->string('currency', 3)->nullable();
$table->json('payload'); // what the model returned
$table->json('reasons')->nullable(); // why it needs a person
$table->timestamps();
// Name the index yourself: the generated name is longer than MySQL's 64-character limit.
$table->index(['supplier_key', 'invoice_number', 'total_cents'], 'invoice_duplicate_lookup');
});
One practical trap: Laravel generates the index name from the table and column names, and for a composite index on three long column names that name exceeded MySQL's limit of 64 characters, so the migration failed. Name such an index yourself, as above. I also keep the original model output (payload) and the reasons in the table, because when a person corrects an invoice later you want to know what the model said.
What the checker did on made-up invoices
| Input | Result | Reasons given |
|---|
| A clean invoice | accepted | none |
| One digit misread: a line total of 39.00 instead of 39.98 | needs review | "Line 2: quantity x unit price does not equal the line total." and "The line totals do not add up to the subtotal." |
| Total changed from 48.74 to 49.74 | needs review | "Subtotal plus tax does not equal the total." |
| Tax given as 8.455 | rejected | "Not a valid amount with at most two decimals: 8.455" |
| Invoice number missing | rejected | "The invoice number field is required." |
| The same invoice a second time, different capitalisation of the supplier | needs review | "Possible duplicate of extraction #1." |
Note the first row of that list: the same document read correctly passes straight through, so the review queue is for the exceptions. If most invoices land in review, the extraction or the rules need work. If almost none do, check that your thresholds are not too loose.
Tests that pin the behaviour down
- A correct invoice is accepted with exact cent values.
- Three lines at 0.10 add up exactly, and the test also demonstrates that the float comparison fails.
- A wrong line total, subtotal or total goes to review with a specific reason.
- A missing field, an amount with more than two decimals and an impossible date are rejected.
- An unexpected currency, a future date and a total above the limit are all reported together.
- A negative total is flagged as a possible credit note.
- A second copy of an invoice with different formatting is flagged as a duplicate.
- Rejected output is stored with its reasons and never counts as an accepted original.
The review queue is part of the product
- Show the document next to the extracted fields, with the reasons highlighted, so a check takes seconds.
- Let the person correct a field and approve, and store both the model's value and the corrected one. Corrections show where the model is weak.
- Measure it. Track how many invoices are accepted, reviewed and rejected, and which reasons are most common. Those numbers tell you what to fix first.
Posting to the accounting system
Only accepted invoices, or invoices approved by a person, should be posted, and the post should be idempotent: use the extraction id as the key so a retry cannot create a second entry. My guide on queue jobs for third-party APIs covers that pattern. Do not let the automation pay anything on its own.
Privacy and cost
- Invoices contain business and sometimes personal data. Check your model provider's data terms before you send documents, and consider redacting what the model does not need.
- Decide how long you keep documents, extractions and logs.
- Every extraction is a model call with a cost. My guide to estimating the cost of an AI assistant shows how to build a worksheet with your own numbers.
Common mistakes
- Floats for money.
- Trusting the total the model read instead of recomputing it.
- Rounding an amount with too many decimals, which hides a misread.
- Accepting a duplicate because the supplier name was capitalised differently.
- Automatic approval with no limit.
- No audit trail, so nobody can say what the model returned.
Frequently asked questions
Which model or OCR tool should I use?
This article does not recommend one. Whichever you choose, run it through the same checker and measure how many invoices need review.
Can the model check its own arithmetic?
Asking it to is cheap and can reduce errors, but do not rely on it. The recomputation in code is deterministic and costs nothing per invoice.
What about tax rules, multiple VAT rates and rounding per line?
They vary by country and company. Add them as further checks. The structure stays the same: recompute, compare, route.
What about invoices in other languages or formats?
That affects extraction quality, not the checker. Test extraction on your own documents.
Can this be built in n8n or Make?
The orchestration can. The checking logic is easier to test and to trust as code, which a workflow tool can call.
Where this fits
If you would like help building an invoice or document intake with a proper review step, see AI Automation Services and Business & Lead Automation, or describe your documents here. More blueprints are collected under AI Workflows.