{
  "name": "AI Invoice OCR + Deterministic Math Audit Guardrail (Apify MCP)",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "invoice-audit-webhook",
        "responseMode": "lastNode",
        "options": {}
      },
      "id": "node-webhook-trigger",
      "name": "Webhook: Receive Invoice Payload",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [220, 300],
      "notes": "Trigger this workflow from Gmail attachment, Google Drive PDF upload, or ERP webhook."
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.openai.com/v1/chat/completions",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $env.OPENAI_API_KEY }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"model\": \"gpt-4o-mini\",\n  \"response_format\": { \"type\": \"json_object\" },\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"Extract invoice fields as JSON: invoice_number, vendor_name, vendor_tax_id, issue_date, due_date, currency, tax_rate, line_items[{description, quantity, unit_price, line_total}], subtotal, tax_amount, total.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": {{ JSON.stringify($json.body.rawInvoiceText || $json.body) }}\n    }\n  ]\n}",
        "options": {}
      },
      "id": "node-ai-ocr-extract",
      "name": "AI OCR / LLM Extract Raw JSON",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [470, 300],
      "notes": "Replace with any OCR / Claude / Mistral / Gemini extraction node. Output raw invoice JSON."
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.apify.com/v2/acts/snowy_divide_r1t~structured-invoice-line-validator/run-sync-get-dataset-items",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $env.APIFY_TOKEN }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"invoice\": {{ $json.choices ? JSON.parse($json.choices[0].message.content) : $json }},\n  \"options\": {\n    \"toleranceMinorUnits\": 1,\n    \"strictTaxId\": true,\n    \"detectDuplicates\": true,\n    \"autoCorrectOutput\": true\n  }\n}",
        "options": {
          "timeout": 30000
        }
      },
      "id": "node-apify-validator",
      "name": "Apify: Deterministic Invoice Audit ($0.004/inv)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [740, 300],
      "notes": "Zero-scraping pure-compute BigInt validator. Store: https://apify.com/snowy_divide_r1t/structured-invoice-line-validator"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "cond-hallucination",
              "leftValue": "={{ $json.hallucinationDetected }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "equals"
              }
            },
            {
              "id": "cond-invalid",
              "leftValue": "={{ $json.status }}",
              "rightValue": "INVALID",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "or"
        },
        "options": {}
      },
      "id": "node-if-hallucination",
      "name": "IF: Hallucination or Error Detected?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [1010, 300]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $env.SLACK_WEBHOOK_URL }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"text\": \"🚨 Invoice Math Hallucination Caught: {{ $json.invoiceNumber || 'UNKNOWN' }} | Status: {{ $json.status }} | Score: {{ $json.confidenceScore }}/100 | Reported Total: {{ $json.auditTrail.grandTotal.reported }} vs Computed: {{ $json.auditTrail.grandTotal.computed }} {{ $json.currency }} (Delta: {{ $json.auditTrail.grandTotal.delta }})\"\n}",
        "options": {}
      },
      "id": "node-slack-alert",
      "name": "Slack: Alert Finance Team (Diff Details)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1290, 190],
      "notes": "Set SLACK_WEBHOOK_URL in n8n environment variables."
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "YOUR_GOOGLE_SHEET_ID",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Verified_Invoices",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "invoice_number": "={{ $json.normalizedInvoice.invoice_number }}",
            "vendor_name": "={{ $json.normalizedInvoice.vendor_name }}",
            "vendor_tax_id": "={{ $json.normalizedInvoice.vendor_tax_id }}",
            "issue_date": "={{ $json.normalizedInvoice.issue_date }}",
            "currency": "={{ $json.normalizedInvoice.currency }}",
            "subtotal": "={{ $json.normalizedInvoice.subtotal }}",
            "tax_amount": "={{ $json.normalizedInvoice.tax_amount }}",
            "total": "={{ $json.normalizedInvoice.total }}",
            "audit_status": "={{ $json.status }}"
          }
        },
        "options": {}
      },
      "id": "node-gsheets-erp",
      "name": "Google Sheets / ERP: Write Clean Invoice",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [1290, 410],
      "notes": "Auto-posts 100% deterministically verified normalizedInvoice JSON."
    }
  ],
  "connections": {
    "Webhook: Receive Invoice Payload": {
      "main": [
        [
          {
            "node": "AI OCR / LLM Extract Raw JSON",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI OCR / LLM Extract Raw JSON": {
      "main": [
        [
          {
            "node": "Apify: Deterministic Invoice Audit ($0.004/inv)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apify: Deterministic Invoice Audit ($0.004/inv)": {
      "main": [
        [
          {
            "node": "IF: Hallucination or Error Detected?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF: Hallucination or Error Detected?": {
      "main": [
        [
          {
            "node": "Slack: Alert Finance Team (Diff Details)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Google Sheets / ERP: Write Clean Invoice",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateSource": "https://mcp.miaodui.workers.dev/",
    "apifyActor": "https://apify.com/snowy_divide_r1t/structured-invoice-line-validator"
  },
  "tags": [
    { "name": "finance-automation" },
    { "name": "apify-mcp" },
    { "name": "deterministic-audit" }
  ]
}
