{
  "name": "Receipt photo to an expense sheet",
  "nodes": [
    {
      "parameters": {
        "content": "## Receipt photo to an expense sheet\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": "5f5886c7-b4fe-4b2a-8751-ebc346092a25",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -40
      ]
    },
    {
      "parameters": {},
      "id": "1bcda2c3-bf2f-44c0-b7ba-0e033239b3ba",
      "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": "receipt-photo-to-expense-sheet",
        "authentication": "none",
        "responseMode": "lastNode",
        "responseData": "firstEntryJson",
        "options": {}
      },
      "id": "68897e0f-e606-402a-969b-3fc6c7b2653f",
      "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": "be6f51ee-e9d9-44b2-8354-ce0e3ab098a0"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const sample = {\n  \"demo\": true,\n  \"from\": \"ap@northwind.example\",\n  \"filename\": \"taxi-receipt.jpg\",\n  \"vendor\": \"City Cab\",\n  \"invoiceNumber\": \"R-19\",\n  \"currency\": \"USD\",\n  \"subtotal\": 28,\n  \"tax\": 2,\n  \"total\": 30,\n  \"dueDate\": \"2026-12-15\",\n  \"text\": \"Vendor: City Cab\\nInvoice R-19\\nSubtotal 28.00\\nTax 2.00\\nTotal 30.00\\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": "b6b99db1-c022-4013-9061-4c2831a47a7d",
      "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: 'Expenses',\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: 'Expenses', 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": "88529d07-bc66-42e3-82bc-e176b808f2b9",
      "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": "c26f3e7c-ad6f-4ca8-8aed-04bbefc1f01e",
              "leftValue": "={{ $json.demo }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "fdff5f60-4e4d-4f66-8b17-4758b62b541b",
      "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: 'receipt-photo-to-expense-sheet',\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": "2b4ea52c-0308-48dd-8e7c-010592cb4ddd",
      "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": "Expenses"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "id": "bfea3d59-b2a3-460c-8db4-e07b24616617",
      "name": "Append Expenses",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1180,
        760
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "PLACEHOLDER_GOOGLESHEETSOAUTH2API",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "message",
        "operation": "post",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "name",
          "value": "#receipts"
        },
        "text": "={{ $json.slackText || $json.summary }}",
        "otherOptions": {}
      },
      "id": "c483189c-4aef-45dd-baf5-5a7e4858ae4a",
      "name": "Post #receipts",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.3,
      "position": [
        1460,
        760
      ],
      "credentials": {
        "slackOAuth2Api": {
          "id": "PLACEHOLDER_SLACKOAUTH2API",
          "name": "Slack 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": "f4274202-8be0-4628-ae5e-1cb3d55e9e53",
      "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
          }
        ]
      ]
    },
    "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 Expenses",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append Expenses": {
      "main": [
        [
          {
            "node": "Post #receipts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "A photographed receipt, already reduced to text, is checked and appended to an expense tab. Unbalanced or merchant-less receipts are flagged in Slack."
  },
  "active": false
}
