{
  "name": "AI invoice and receipt extraction from Gmail to Sheets, Xero, and QuickBooks",
  "nodes": [
    {
      "parameters": {
        "content": "## AI invoice and receipt extraction from Gmail to Sheets, Xero, and QuickBooks\n\nPortfolio demo only. This workflow is an original example for demonstration. It is not client work and it does not represent a deployment for any customer.\n\nRun **Run demo** to execute the offline rules engine. The live branch is used only when the incoming item sets `demo` to false and the placeholder credentials have been replaced.",
        "height": 220,
        "width": 520,
        "color": 4
      },
      "id": "a706f5da-c97b-44af-aa4f-c09a002da98e",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -40
      ]
    },
    {
      "parameters": {},
      "id": "7dfba1cf-dbee-4697-b870-4aea65854a5d",
      "name": "Run demo",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        40,
        280
      ],
      "notes": "CLI and the n8n editor start here. An empty manual run loads the bundled sample.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "ai-invoice-gmail-to-sheets",
        "authentication": "none",
        "responseMode": "lastNode",
        "responseData": "firstEntryJson",
        "options": {}
      },
      "id": "97608853-5c32-40e9-b300-083414269d26",
      "name": "Inbound webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        40,
        460
      ],
      "notes": "POST JSON to this path. Include demo:false only after credentials are connected.",
      "notesInFlow": true,
      "webhookId": "8bf33294-d05f-40c2-8d11-ae356f10ef20"
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "event": "messageReceived",
        "simple": true
      },
      "id": "028ed26c-8560-491f-8987-805c4ebc7691",
      "name": "Gmail trigger",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        40,
        640
      ],
      "credentials": {
        "gmailOAuth2": {
          "id": "PLACEHOLDER_GMAILOAUTH2",
          "name": "Gmail account"
        }
      },
      "notes": "Polls the mailbox once credentials replace the placeholder. Tests do not call Gmail.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const sample = {\n  \"demo\": true,\n  \"from\": \"ap@northwind.example\",\n  \"filename\": \"northwind-inv-2041.pdf\",\n  \"vendor\": \"Northwind Supplies\",\n  \"invoiceNumber\": \"INV-2041\",\n  \"currency\": \"USD\",\n  \"subtotal\": 1100,\n  \"tax\": 88,\n  \"total\": 1188,\n  \"dueDate\": \"2026-12-15\",\n  \"text\": \"Vendor: Northwind Supplies\\nInvoice INV-2041\\nSubtotal 1100.00\\nTax 88.00\\nTotal 1188.00\\nDue 2026-12-15\\n\"\n};\nconst incoming = $input.first()?.json ?? {};\nconst provided = Object.keys(incoming).filter((key) => incoming[key] !== undefined && incoming[key] !== null && incoming[key] !== '');\nconst base = provided.length ? { ...sample, ...incoming } : { ...sample };\nconst flag = incoming.demo;\nbase.demo = !(flag === false || flag === 'false' || flag === 0 || flag === '0');\nreturn [{ json: base }];\n"
      },
      "id": "d3933067-9f4e-453a-b573-8f929c580093",
      "name": "Normalize input",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        340,
        360
      ],
      "notes": "Merges the request over the bundled sample. demo stays true unless the caller explicitly turns it off.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const item = $input.first().json;\nconst produced = (() => {\n\nconst text = String(item.text || item.body || '');\nconst vendor = item.vendor || (text.match(/vendor[:\\s]+([^\\n]+)/i) || [])[1] || 'Unknown vendor';\nconst invoiceNumber = item.invoiceNumber || (text.match(/inv(?:oice)?\\s*#?\\s*([A-Z0-9-]+)/i) || [])[1] || 'UNKNOWN';\nconst currency = item.currency || 'USD';\nconst total = Number(item.total ?? matchAmount(text, 'total') ?? 0);\nconst tax = Number(item.tax ?? matchAmount(text, 'tax') ?? 0);\nconst subtotal = Number(item.subtotal ?? matchAmount(text, 'subtotal') ?? (total - tax));\nconst dueDate = item.dueDate || (text.match(/due[:\\s]+(\\d{4}-\\d{2}-\\d{2})/i) || [])[1] || '';\nconst expected = Math.round((subtotal + tax) * 100) / 100;\nconst balanced = Math.abs(expected - total) <= Math.max(0.5, total * 0.02);\nconst record = {\n  vendor: String(vendor).trim(),\n  invoiceNumber,\n  currency,\n  subtotal,\n  tax,\n  total,\n  dueDate,\n  balanced,\n  mailbox: item.from || '',\n  filename: item.filename || 'invoice.pdf',\n  destination: 'Google Sheets',\n};\nreturn {\n  summary: record.vendor + ' ' + invoiceNumber + ' for ' + total + ' ' + currency + (balanced ? ' balances.' : ' does not balance.'),\n  route: balanced ? 'post' : 'review',\n  record,\n  slackText: (balanced ? 'Post' : 'Review') + ' invoice ' + invoiceNumber + ' from ' + record.vendor + ' (' + total + ' ' + currency + ').',\n  actions: [{ app: 'Google Sheets', operation: balanced ? 'create' : 'flag', payload: record }],\n};\nfunction matchAmount(source, label) {\n  const pattern = new RegExp(label + '[:\\\\s]*\\\\$?([0-9,]+(?:\\\\.[0-9]{2})?)', 'i');\n  const found = source.match(pattern);\n  return found ? Number(found[1].replace(/,/g, '')) : null;\n}\n\n})();\nif (!produced || typeof produced.summary !== 'string' || !produced.summary.trim()) {\n  throw new Error('Apply rules must return a summary string');\n}\nreturn [{\n  json: {\n    ...item,\n    ...produced,\n    demo: item.demo !== false,\n  },\n}];\n"
      },
      "id": "9c00cee1-9b61-4ee8-b8c0-5fe0a2e777f3",
      "name": "Apply rules",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        620,
        360
      ],
      "notes": "Deterministic stand-in for the model or enrichment API. Replace or precede this with a live model node when you turn demo mode off.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "ac050d37-6cef-4316-813a-553bec314de9",
              "leftValue": "={{ $json.demo }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "562c1101-d318-4dc4-b505-1a18f43f2dd1",
      "name": "Demo mode?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        900,
        360
      ],
      "notes": "True: package the offline result. False: run the credentialed apps.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const item = $input.first().json;\nreturn [{\n  json: {\n    demo: true,\n    status: 'demo_ready',\n    workflow: 'ai-invoice-gmail-to-sheets',\n    summary: item.summary,\n    route: item.route ?? null,\n    record: item.record ?? {},\n    actions: item.actions ?? [],\n    slackText: item.slackText ?? item.summary,\n    notes: 'Demo mode did not call external apps. Send {\"demo\": false} after placeholder credentials are replaced.',\n  },\n}];\n"
      },
      "id": "2124960f-0762-431e-a8c3-11bf9cc5ddf3",
      "name": "Package demo result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1180,
        180
      ]
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "sheet",
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_SPREADSHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Invoices"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "id": "4f665633-5d1f-4451-a248-73b922c0929c",
      "name": "Append Invoices",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1180,
        760
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "PLACEHOLDER_GOOGLESHEETSOAUTH2API",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "resource": "invoice",
        "operation": "create",
        "organizationId": "YOUR_XERO_ORGANIZATION_ID",
        "type": "ACCREC",
        "contactId": "YOUR_XERO_CONTACT_ID"
      },
      "id": "ba91f34f-2b04-49ba-be3c-70557b1d13c9",
      "name": "Create Xero invoice",
      "type": "n8n-nodes-base.xero",
      "typeVersion": 1.1,
      "position": [
        1460,
        760
      ],
      "credentials": {
        "xeroOAuth2Api": {
          "id": "PLACEHOLDER_XEROOAUTH2API",
          "name": "Xero account"
        }
      }
    },
    {
      "parameters": {
        "resource": "bill",
        "operation": "create",
        "VendorRef": "YOUR_QUICKBOOKS_VENDOR_ID",
        "CustomerRef": "YOUR_QUICKBOOKS_CUSTOMER_ID"
      },
      "id": "ed35fcf7-9401-4ec5-bd85-ff83a6ff8602",
      "name": "Create QuickBooks bill",
      "type": "n8n-nodes-base.quickbooks",
      "typeVersion": 1,
      "position": [
        1740,
        760
      ],
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "PLACEHOLDER_QUICKBOOKSOAUTH2API",
          "name": "QuickBooks account"
        }
      }
    },
    {
      "parameters": {
        "content": "## Live path\n\nReplace every `PLACEHOLDER_*` credential, then POST the sample with `\"demo\": false`.\n\nThe nodes on this branch use the `record` and `actions` fields produced by Apply rules.",
        "height": 180,
        "width": 420,
        "color": 6
      },
      "id": "dfb93e57-20ba-4d65-bacb-b94de0ab5b07",
      "name": "Live path",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1120,
        520
      ]
    }
  ],
  "connections": {
    "Run demo": {
      "main": [
        [
          {
            "node": "Normalize input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Inbound webhook": {
      "main": [
        [
          {
            "node": "Normalize input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gmail trigger": {
      "main": [
        [
          {
            "node": "Normalize input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalize input": {
      "main": [
        [
          {
            "node": "Apply rules",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apply rules": {
      "main": [
        [
          {
            "node": "Demo mode?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Demo mode?": {
      "main": [
        [
          {
            "node": "Package demo result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Append Invoices",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append Invoices": {
      "main": [
        [
          {
            "node": "Create Xero invoice",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Xero invoice": {
      "main": [
        [
          {
            "node": "Create QuickBooks bill",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "A mailbox attachment is read as text, the vendor, invoice number, tax, and total are checked against each other, and a balanced bill is ready for Sheets plus either Xero or QuickBooks."
  },
  "active": false
}
