{
  "name": "AP inbox -> AI invoice extraction -> Sheets + QuickBooks",
  "nodes": [
    {
      "parameters": {
        "content": "## AP inbox -> AI extraction -> Sheets / QuickBooks\n1. Connect Gmail, Google Sheets, QuickBooks Online (OAuth2), Slack.\n2. Add an **Anthropic API key** as a Header Auth credential (name `x-api-key`).\n3. Create a sheet with a tab **Bills** (headers are written on first append).\n4. Set the sheet URL in both Sheets nodes and the Slack channel.\n\nAuto-approved = all math checks pass, no duplicate, confidence >= 85%.",
        "height": 230,
        "width": 520
      },
      "id": "22aa2380-7c98-5090-a52d-7b29f5d5cc69",
      "name": "Sticky note",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -60,
        -260
      ]
    },
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "simple": false,
        "filters": {
          "q": "has:attachment -label:ap-processed"
        },
        "options": {
          "downloadAttachments": true
        }
      },
      "id": "76d3d9c2-5df1-5ec4-92ec-c0a15d4d5b3c",
      "name": "AP inbox (Gmail)",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// One output item per PDF/image attachment, max 5 MB, skipping inline logos.\nconst out = [];\nfor (const item of $input.all()) {\n  for (const [key, bin] of Object.entries(item.binary || {})) {\n    const ok = ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'].includes(bin.mimeType);\n    const size = Number(bin.fileSize?.replace?.(/[^\\d.]/g, '') || 0) * (String(bin.fileSize).includes('MB') ? 1024 * 1024 : String(bin.fileSize).includes('kB') ? 1024 : 1);\n    if (!ok || size > 5 * 1024 * 1024 || size < 15 * 1024 && bin.mimeType !== 'application/pdf') continue;\n    out.push({\n      json: { messageId: item.json.id, from: item.json.from?.text || '', subject: item.json.subject || '', fileName: bin.fileName, mimeType: bin.mimeType },\n      binary: { data: bin },\n    });\n  }\n}\nreturn out;"
      },
      "id": "f65a94ba-6f5c-5d63-a04e-88128d36f857",
      "name": "Split attachments",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// Builds the Claude Messages API request: document/image block + JSON schema output.\nconst CATEGORIES = ['Office supplies','Furniture & equipment','Software & hosting','Freight & shipping','Packaging materials',\n  'Meals & entertainment','Travel','Professional services','Utilities','Repairs & maintenance','Other'];\nconst n = t => ({ anyOf: [{ type: t }, { type: 'null' }] });\nconst confFields = ['supplier_name','invoice_number','issue_date','due_date','currency','line_items','subtotal','tax_total','total'];\nconst schema = {\n  type: 'object', additionalProperties: false,\n  required: ['document_type','supplier','invoice_number','po_number','issue_date','due_date','currency','prices_include_tax',\n    'line_items','subtotal','tax_rate','tax_total','shipping','discount','total','payment_terms','confidence','notes'],\n  properties: {\n    document_type: { type: 'string', enum: ['invoice','receipt','credit_note','other'] },\n    supplier: { type: 'object', additionalProperties: false, required: ['name','address','tax_id'],\n      properties: { name: n('string'), address: { type: 'string' }, tax_id: { type: 'string' } } },\n    // Claude allows at most 16 nullable (union) fields per schema: optional text uses \"\" and shipping/discount use 0 instead of null.\n    invoice_number: n('string'), po_number: { type: 'string' }, issue_date: n('string'), due_date: { type: 'string' }, currency: n('string'),\n    prices_include_tax: { type: 'boolean' },\n    line_items: { type: 'array', items: { type: 'object', additionalProperties: false,\n      required: ['description','quantity','unit_price','amount','category'],\n      properties: { description: { type: 'string' }, quantity: n('number'), unit_price: n('number'), amount: n('number'),\n        category: { type: 'string', enum: CATEGORIES } } } },\n    subtotal: n('number'), tax_rate: n('number'), tax_total: n('number'), shipping: { type: 'number' }, discount: { type: 'number' }, total: n('number'),\n    payment_terms: { type: 'string' },\n    confidence: { type: 'object', additionalProperties: false, required: confFields,\n      properties: Object.fromEntries(confFields.map(f => [f, { type: 'number' }])) },\n    notes: { type: 'string' },\n  },\n};\nconst system = `You extract accounts-payable data from one supplier document (invoice, bill or receipt).\nCopy values exactly as printed; never compute a value that is not printed (return null). Dates YYYY-MM-DD, currency ISO 4217,\namounts as plain numbers. One line_items entry per printed line across all pages; skip carried-forward rows.\nconfidence: 0-1 per field, lower for faded, handwritten or ambiguous values. notes: one sentence for the reviewer.\nOptional text fields that are not printed: \"\". shipping/discount when none: 0.`;\n\nconst out = [];\nfor (let i = 0; i < $input.all().length; i++) {\n  const item = $input.all()[i];\n  const b64 = (await this.helpers.getBinaryDataBuffer(i, 'data')).toString('base64');\n  const block = item.json.mimeType === 'application/pdf'\n    ? { type: 'document', source: { type: 'base64', media_type: 'application/pdf', data: b64 } }\n    : { type: 'image', source: { type: 'base64', media_type: item.json.mimeType, data: b64 } };\n  out.push({ json: { ...item.json, body: {\n    model: 'claude-opus-5-5', max_tokens: 16000, system,\n    output_config: { effort: 'low', format: { type: 'json_schema', schema } },\n    messages: [{ role: 'user', content: [block, { type: 'text', text: 'Extract this document.' }] }],\n  } } });\n}\nreturn out;"
      },
      "id": "1d3b82a9-6157-54d2-87ca-7ec1a0d380d9",
      "name": "Build Claude request",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        0
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.anthropic.com/v1/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "anthropic-version",
              "value": "2023-06-01"
            },
            {
              "name": "content-type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.body) }}",
        "options": {
          "timeout": 120000,
          "batching": {
            "batch": {
              "batchSize": 2,
              "batchInterval": 1500
            }
          }
        }
      },
      "id": "6e06f1d2-51a0-5550-95d9-29d28dfacef9",
      "name": "Claude: extract invoice",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        0
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "https://docs.google.com/spreadsheets/d/REPLACE_WITH_SHEET_ID/edit"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Bills"
        },
        "options": {}
      },
      "id": "85314edb-72ea-5048-b29c-23280e629727",
      "name": "Read posted bills",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        880,
        0
      ],
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "jsCode": "// Deterministic checks (same rules as the web demo) + duplicate check against bills already in the sheet.\nconst TOL = 0.02, THRESHOLD = 0.85;\nconst posted = $input.all().map(r => r.json);\nconst norm = s => String(s || '').toLowerCase().replace(/[^\\p{L}\\p{N} ]+/gu, ' ')\n  .replace(/\\b(inc|llc|ltd|limited|gmbh|co|corp|company|plc)\\b/g, ' ').replace(/\\s+/g, ' ').trim();\nconst source = $('Split attachments').all();\n\nreturn $('Claude: extract invoice').all().map((res, i) => {\n  if (res.json.stop_reason === 'refusal' || res.json.stop_reason === 'max_tokens') {\n    return { json: { status: 'needs_review', problems: 'model stopped: ' + res.json.stop_reason, fileName: source[i]?.json.fileName } };\n  }\n  const text = (res.json.content || []).find(b => b.type === 'text')?.text || '{}';\n  const d = JSON.parse(text);\n  const problems = [];\n  const r2 = x => Math.round(Number(x) * 100) / 100;\n  const sum = r2((d.line_items || []).reduce((a, l) => a + Number(l.amount || 0), 0));\n  for (const [k, l] of (d.line_items || []).entries())\n    if (l.quantity != null && l.unit_price != null && l.amount != null && Math.abs(r2(l.quantity * l.unit_price) - l.amount) > Math.max(TOL, Math.abs(l.amount) * 0.001))\n      problems.push(`line ${k + 1}: qty x price != amount`);\n  const target = d.prices_include_tax ? d.total : d.subtotal;\n  if (target != null && Math.abs(sum - target) > TOL) problems.push(`lines ${sum} != ${d.prices_include_tax ? 'total' : 'subtotal'} ${target}`);\n  if (d.tax_rate && d.tax_total != null) {\n    const exp = d.prices_include_tax ? r2(d.total - d.total / (1 + d.tax_rate / 100)) : r2((d.subtotal ?? sum) * d.tax_rate / 100);\n    if (Math.abs(exp - d.tax_total) > Math.max(TOL, 0.005 * (d.line_items || []).length)) problems.push(`tax ${d.tax_total} != ${exp}`);\n  }\n  if (d.subtotal != null && d.total != null) {\n    const calc = r2(d.subtotal + (d.tax_total || 0) + (d.prices_include_tax ? 0 : (d.shipping || 0) - (d.discount || 0)));\n    if (Math.abs(calc - d.total) > TOL) problems.push(`total ${d.total} != ${calc}`);\n  }\n  for (const f of ['invoice_number', 'issue_date', 'currency', 'total']) if (d[f] == null || d[f] === '') problems.push(`missing ${f}`);\n  if (!d.supplier?.name) problems.push('missing supplier');\n  const low = Object.entries(d.confidence || {}).filter(([, c]) => c < THRESHOLD).map(([k]) => k);\n  if (low.length) problems.push('low confidence: ' + low.join(', '));\n  const dup = posted.find(p => norm(p.Supplier) === norm(d.supplier?.name) && String(p['Invoice no.']).toUpperCase() === String(d.invoice_number).toUpperCase());\n  if (dup) problems.push(`duplicate of row posted ${dup['Processed at'] || ''}`.trim());\n\n  const usage = res.json.usage || {};\n  return { json: {\n    status: problems.length ? 'needs_review' : 'auto_approved',\n    problems: problems.join('; '),\n    invoice: d,\n    fileName: source[i]?.json.fileName, from: source[i]?.json.from, messageId: source[i]?.json.messageId,\n    costUsd: Math.round(((usage.input_tokens || 0) * 4 + (usage.output_tokens || 0) * 20) / 1e6 * 10000) / 10000,\n  } };\n});"
      },
      "id": "353ad909-ca9e-5fa0-b621-3706b6b7a5c7",
      "name": "Validate + dedupe",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1100,
        0
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "c1",
              "leftValue": "={{ $json.status }}",
              "rightValue": "auto_approved",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "93df5f98-8262-5cbc-8076-ce41449978a0",
      "name": "Auto-approved?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1320,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// QuickBooks Online Bill payload. Map categories to your chart of accounts (IDs below are examples).\nconst ACCOUNTS = { 'Office supplies': '64', 'Furniture & equipment': '15', 'Software & hosting': '72', 'Freight & shipping': '58',\n  'Packaging materials': '61', 'Meals & entertainment': '13', 'Travel': '77', 'Professional services': '70', 'Utilities': '78',\n  'Repairs & maintenance': '75', 'Other': '80' };\nconst VENDORS = {}; // optional: { 'pinecrest office supply': '56' } - otherwise create vendors first in QBO\nreturn $input.all().map(({ json: j }) => {\n  const d = j.invoice;\n  const Line = d.line_items.map(l => ({ DetailType: 'AccountBasedExpenseLineDetail', Amount: l.amount, Description: l.description,\n    AccountBasedExpenseLineDetail: { AccountRef: { value: ACCOUNTS[l.category] || '80' } } }));\n  if (d.shipping) Line.push({ DetailType: 'AccountBasedExpenseLineDetail', Amount: d.shipping, Description: 'Shipping',\n    AccountBasedExpenseLineDetail: { AccountRef: { value: '58' } } });\n  return { json: { ...j, bill: {\n    VendorRef: { value: VENDORS[d.supplier.name.toLowerCase()] || '1', name: d.supplier.name },\n    DocNumber: d.invoice_number, TxnDate: d.issue_date, DueDate: d.due_date || undefined,\n    CurrencyRef: { value: d.currency }, GlobalTaxCalculation: d.prices_include_tax ? 'TaxInclusive' : 'TaxExcluded',\n    Line, PrivateNote: `Auto-imported from ${j.fileName}`,\n  } } };\n});"
      },
      "id": "fc0b3fd6-e9dd-5512-8dd6-81e716bbcd01",
      "name": "Build QuickBooks bill",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1560,
        -120
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://quickbooks.api.intuit.com/v3/company/REPLACE_REALM_ID/bill?minorversion=75",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "quickBooksOAuth2Api",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.bill) }}",
        "options": {}
      },
      "id": "c42fb368-e0ff-5f7d-9cb6-571ec442fd7a",
      "name": "QuickBooks: create bill",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1780,
        -120
      ],
      "continueOnFail": true
    },
    {
      "parameters": {
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "name",
          "value": "#ap-review"
        },
        "text": "=:warning: Invoice needs review: *{{ $json.invoice?.supplier?.name || $json.fileName }}* {{ $json.invoice?.invoice_number || '' }} ({{ $json.invoice?.currency }} {{ $json.invoice?.total }})\n> {{ $json.problems }}",
        "otherOptions": {}
      },
      "id": "22bea352-cb73-523d-b9a5-e5d7d0626b69",
      "name": "Slack: ask reviewer",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.2,
      "position": [
        1560,
        120
      ]
    },
    {
      "parameters": {
        "jsCode": "// Flat row for the \"Bills\" sheet.\nreturn $input.all().map(({ json: j }) => ({ json: {\n  'Processed at': new Date().toISOString(),\n  'Status': j.status,\n  'Problems': j.problems || '',\n  'Supplier': j.invoice?.supplier?.name || '',\n  'Supplier tax ID': j.invoice?.supplier?.tax_id || '',\n  'Invoice no.': j.invoice?.invoice_number || '',\n  'Issue date': j.invoice?.issue_date || '',\n  'Due date': j.invoice?.due_date || '',\n  'Currency': j.invoice?.currency || '',\n  'Subtotal': j.invoice?.subtotal ?? '',\n  'Tax': j.invoice?.tax_total ?? '',\n  'Total': j.invoice?.total ?? '',\n  'Lines': (j.invoice?.line_items || []).length,\n  'File': j.fileName || '',\n  'From': j.from || '',\n  'AI cost USD': j.costUsd ?? '',\n} }));"
      },
      "id": "4a2f5174-f948-5a94-b2a2-015c338e21d2",
      "name": "Sheet row",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2000,
        0
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "https://docs.google.com/spreadsheets/d/REPLACE_WITH_SHEET_ID/edit"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Bills"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        },
        "options": {}
      },
      "id": "cad850aa-ea63-5c39-a39a-dbcb610d42ab",
      "name": "Sheets: append bill",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        2220,
        0
      ]
    }
  ],
  "connections": {
    "AP inbox (Gmail)": {
      "main": [
        [
          {
            "node": "Split attachments",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split attachments": {
      "main": [
        [
          {
            "node": "Build Claude request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Claude request": {
      "main": [
        [
          {
            "node": "Claude: extract invoice",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude: extract invoice": {
      "main": [
        [
          {
            "node": "Read posted bills",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read posted bills": {
      "main": [
        [
          {
            "node": "Validate + dedupe",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate + dedupe": {
      "main": [
        [
          {
            "node": "Auto-approved?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Auto-approved?": {
      "main": [
        [
          {
            "node": "Build QuickBooks bill",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Slack: ask reviewer",
            "type": "main",
            "index": 0
          },
          {
            "node": "Sheet row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build QuickBooks bill": {
      "main": [
        [
          {
            "node": "QuickBooks: create bill",
            "type": "main",
            "index": 0
          },
          {
            "node": "Sheet row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sheet row": {
      "main": [
        [
          {
            "node": "Sheets: append bill",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "saveDataErrorExecution": "all"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "pinData": {},
  "tags": []
}