# Math-Verified Invoice & Bank PDF to QuickBooks/Xero JSON (`zenonnnnnn/math-verified-invoice-json`) Actor

Convert invoices, receipts, and bank statement PDFs into mathematically verified JSON + ready-to-import QuickBooks Online & Xero payloads. Dual-engine Gemini 2.5 Flash + deterministic pdfplumber parser with exact Python Decimal cross-footing & running-balance auditing.

- **URL**: https://apify.com/zenonnnnnn/math-verified-invoice-json.md
- **Developed by:** [xu zenon](https://apify.com/zenonnnnnn) (community)
- **Categories:** AI, Automation
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$25.00 / 1,000 document pages audited

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Math-Verified Invoice & Bank Statement PDF to QuickBooks/Xero JSON Converter

Turn raw **commercial invoices, receipts, and multi-line bank statement PDFs** into **mathematically verified structured JSON**, complete with **ready-to-import QuickBooks Online (`Bill` / `Purchase`) and Xero (`ACCPAY` / `BankTransactions`) API payloads**.

Unlike generic OCR or LLM wrappers that silently hallucinate digits (`$1,280.00` read as `$1,230.00` or dropped statement rows), every extracted document passes through a deterministic **Python `decimal.Decimal` Cross-Footing & Continuity Audit Engine**—never touching IEEE-754 floating-point arithmetic (`float`) for currency calculations.

***

### Why Accounting Automation Teams Choose This Actor

1. **Dual-Engine Extraction (Zero-Key Ready + BYOK Multimodal)**
   - **Engine A — Gemini 2.5 Flash Multimodal Structured Engine**: Handles scanned paper invoices, smartphone receipt photos, skewed PDFs, and complex multi-column bank statements using strict JSON Schema output. Works out-of-the-box via built-in service capacity or with your own `geminiApiKey` (BYOK).
   - **Engine B — Deterministic `pdfplumber` Layout & Native Table Engine**: Extracts native digital PDFs and raw invoice/statement text with **zero external API calls**, ensuring 100% deterministic reproducibility for electronic SaaS bills, ERP invoices, and digital bank exports.
2. **4-Pillar `decimal.Decimal` Accounting Audit (`mathAudit`)**
   - **Invoice Row Cross-Footing**: Verifies `round(quantity * unit_price - line_discount, 2) == line_amount` on every single line item and pinpoints the exact miscalculated row (`ROW_TOTAL_MISMATCH`).
   - **Invoice Column Footing**: Verifies `sum(line_amounts) == subtotal` (`SUBTOTAL_MISMATCH`) and `subtotal + total_tax + shipping_fee - discount_total == grand_total` (`GRAND_TOTAL_MISMATCH`).
   - **Bank Statement Running-Balance Continuity**: Verifies row-by-row `prev_balance + credit - debit == running_balance` (`RUNNING_BALANCE_MISMATCH`) and full-period reconciliation `opening_balance + sum(credits) - sum(debits) == closing_balance` (`CLOSING_BALANCE_MISMATCH`)—instantly catching skipped scan lines or transposed digits between specific dates.
   - **Date & Effective Tax Sanity**: Validates `due_date >= issue_date`, statement period ordering, and flags abnormal effective tax rates (`effective_tax_rate_pct`).
3. **Drop-In QuickBooks Online & Xero Payloads**
   - Outputs `quickbooksBillPayload` (QuickBooks Online Accounting API v3 `Bill` / `Purchase` / `Deposit` schema) and `xeroInvoicePayload` (Xero Accounting API `ACCPAY` `Invoices` / `BankTransactions` schema) ready for **n8n, Make, Zapier, or Pipedream**.
   - Automatically marks discrepancies with `[MATH_DISCREPANCY_HOLD]` in `DRAFT` status so unbalanced bills never auto-post to your General Ledger.
4. **Fair Pay-Per-Event Pricing**
   - Charged per successfully extracted and math-audited page (`document-page-audited`). Unreadable, empty, or corrupted files are **never charged**.

***

### Input Configuration Example

```json
{
  "documentUrls": [
    "https://example.com/invoices/INV-2026-1042.pdf"
  ],
  "documentsBase64": [
    {
      "filename": "november_checking_statement.pdf",
      "mimeType": "application/pdf",
      "contentBase64": "JVBERi0xLjQK...",
      "documentType": "bank_statement"
    }
  ],
  "documentType": "auto",
  "extractionMode": "auto",
  "mathTolerance": "0.02",
  "defaultAccountCode": "400",
  "defaultCurrency": "USD"
}
```

***

### Output Example (With Caught `$50.00` Line Discrepancy)

```json
{
  "documentId": "doc_8f31c9a210b4",
  "sourceName": "invoice_discrepancy_50usd.pdf",
  "documentType": "invoice",
  "extractionEngine": "deterministic_pdfplumber",
  "pageCount": 1,
  "currency": "USD",
  "documentNumber": "INV-2026-0902",
  "counterpartyName": "Northstar Cloud Systems LLC",
  "issueDate": "2026-11-05",
  "dueDate": "2026-12-05",
  "totalAmount": "1620.00",
  "auditPassed": false,
  "confidenceScore": 0.625,
  "discrepancyCount": 2,
  "mathAudit": {
    "passed": false,
    "confidenceScore": 0.625,
    "checksRun": 8,
    "checksPassed": 6,
    "tolerance": "0.02",
    "effectiveTaxRatePct": "8.00",
    "discrepancies": [
      {
        "code": "ROW_TOTAL_MISMATCH",
        "field": "lineItems[1].amount",
        "expected": "450.00",
        "actual": "400.00",
        "delta": "-50.00",
        "severity": "ERROR",
        "message": "Line 2 ('Security Penetration Testing Hours'): round(5.00 * 90.00 - 0.00, 2) = 450.00, but stated line amount is 400.00 (delta -50.00)."
      },
      {
        "code": "SUBTOTAL_MISMATCH",
        "field": "subtotal",
        "expected": "1450.00",
        "actual": "1500.00",
        "delta": "50.00",
        "severity": "ERROR",
        "message": "Sum of stated line item amounts (1450.00) does not match stated subtotal (1500.00) (delta +50.00)."
      }
    ]
  },
  "quickbooksBillPayload": { "...": "QuickBooks Online v3 Bill JSON" },
  "xeroInvoicePayload": { "...": "Xero ACCPAY Invoice JSON" }
}
```

***

### Compliance & Data Privacy

- **100% White-Hat Document Processor**: Processes only user-supplied URLs, Base64 files, or raw text—zero third-party website scraping, zero cookie/session harvesting, and zero CAPTCHA circumvention.
- **Ephemeral In-Memory Parsing**: Uploaded documents are parsed strictly in memory during the Actor run and are never persisted outside your private Apify Dataset.

# Actor input Schema

## `documentUrls` (type: `array`):

Publicly accessible HTTPS/HTTP URLs pointing to invoice, receipt, or bank statement PDFs or images.

## `documentsBase64` (type: `array`):

Array of Base64-encoded document strings (or objects with {"filename", "contentBase64", "mimeType", "documentType"}). Ideal for n8n, Make, and Zapier webhook pipelines.

## `rawDocumentsText` (type: `array`):

Optional array of raw OCR or email invoice/statement text strings (or objects with {"filename", "rawText", "documentType"}). Leave empty to run the built-in sample commercial invoice demo.

## `documentType` (type: `string`):

Specify whether inputs are commercial invoices/receipts, bank statements, or auto-detected per document.

## `extractionMode` (type: `string`):

Auto uses Gemini 2.5 Flash multimodal extraction when an API key is available (built-in or BYOK) and seamlessly falls back to the deterministic pdfplumber layout/table engine for native digital PDFs.

## `geminiApiKey` (type: `string`):

Optional: Provide your own Google Gemini API key (Bring Your Own Key). Leave blank to use the Actor's built-in multimodal service or deterministic PDF parser.

## `geminiModel` (type: `string`):

Google Gemini multimodal model used when Engine A is active.

## `mathTolerance` (type: `string`):

Maximum allowed rounding variance (as a Decimal string, e.g. '0.02' for 2 cents) when auditing row cross-footing, column footing, and bank running balances.

## `defaultAccountCode` (type: `string`):

Default General Ledger expense account code mapped onto exported QuickBooks Online Bill and Xero ACCPAY line items.

## `defaultCurrency` (type: `string`):

Fallback 3-letter ISO currency code when a document omits explicit currency symbols.

## `maxPagesPerRun` (type: `integer`):

Safety cap on total audited document pages in a single Actor run (non-paying free-tier cloud runs are automatically capped at 5 pages).

## Actor input object example

```json
{
  "documentUrls": [],
  "documentsBase64": [],
  "rawDocumentsText": [
    "INVOICE #INV-2026-1042\nVendor: CloudScale Infrastructure Inc.\nBill To: Acme Analytics Corp.\nDate: 2026-12-01 | Due Date: 2026-12-31 | Currency: USD\n1. Dedicated Bare-Metal GPU Node (Qty: 2, Unit Price: 1250.00, Amount: 2500.00)\n2. Enterprise Object Storage 10TB (Qty: 3, Unit Price: 150.00, Amount: 450.00)\nSubtotal: 2950.00\nSales Tax (8.00%): 236.00\nTotal Due: 3186.00"
  ],
  "documentType": "auto",
  "extractionMode": "auto",
  "geminiModel": "gemini-2.5-flash",
  "mathTolerance": "0.02",
  "defaultAccountCode": "400",
  "defaultCurrency": "USD",
  "maxPagesPerRun": 100
}
```

# Actor output Schema

## `auditedDocuments` (type: `string`):

Extracted line items, Decimal audit results, and QuickBooks/Xero JSON payloads.

## `runSummary` (type: `string`):

Total audited pages, pass/discrepancy counts, and run diagnostics.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "rawDocumentsText": [
        "INVOICE #INV-2026-1042\nVendor: CloudScale Infrastructure Inc.\nBill To: Acme Analytics Corp.\nDate: 2026-12-01 | Due Date: 2026-12-31 | Currency: USD\n1. Dedicated Bare-Metal GPU Node (Qty: 2, Unit Price: 1250.00, Amount: 2500.00)\n2. Enterprise Object Storage 10TB (Qty: 3, Unit Price: 150.00, Amount: 450.00)\nSubtotal: 2950.00\nSales Tax (8.00%): 236.00\nTotal Due: 3186.00"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("zenonnnnnn/math-verified-invoice-json").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "rawDocumentsText": ["""INVOICE #INV-2026-1042
Vendor: CloudScale Infrastructure Inc.
Bill To: Acme Analytics Corp.
Date: 2026-12-01 | Due Date: 2026-12-31 | Currency: USD
1. Dedicated Bare-Metal GPU Node (Qty: 2, Unit Price: 1250.00, Amount: 2500.00)
2. Enterprise Object Storage 10TB (Qty: 3, Unit Price: 150.00, Amount: 450.00)
Subtotal: 2950.00
Sales Tax (8.00%): 236.00
Total Due: 3186.00"""] }

# Run the Actor and wait for it to finish
run = client.actor("zenonnnnnn/math-verified-invoice-json").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "rawDocumentsText": [
    "INVOICE #INV-2026-1042\\nVendor: CloudScale Infrastructure Inc.\\nBill To: Acme Analytics Corp.\\nDate: 2026-12-01 | Due Date: 2026-12-31 | Currency: USD\\n1. Dedicated Bare-Metal GPU Node (Qty: 2, Unit Price: 1250.00, Amount: 2500.00)\\n2. Enterprise Object Storage 10TB (Qty: 3, Unit Price: 150.00, Amount: 450.00)\\nSubtotal: 2950.00\\nSales Tax (8.00%): 236.00\\nTotal Due: 3186.00"
  ]
}' |
apify call zenonnnnnn/math-verified-invoice-json --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,zenonnnnnn/math-verified-invoice-json"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/TeoJAayBw1I1HRP2R/builds/mvmvzbbAqRdIyLRM0/openapi.json
