{
  "name": "Match an invoice to a payment",
  "nodes": [
    {
      "parameters": {
        "content": "## Match an invoice to a payment\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": "6d76964b-058e-4c0e-b444-421c21d915b9",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -40
      ]
    },
    {
      "parameters": {},
      "id": "bed9f700-63c5-42fd-ac4f-5b9f2ad628ea",
      "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": "invoice-versus-payment",
        "authentication": "none",
        "responseMode": "lastNode",
        "responseData": "firstEntryJson",
        "options": {}
      },
      "id": "6e00ba8d-47d5-409a-a60b-3b939188c4fb",
      "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": "cbedf454-efdb-4953-82f4-4cd320308186"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const sample = {\n  \"demo\": true,\n  \"stripe\": [\n    {\n      \"id\": \"INV-2041\",\n      \"amount\": 1188,\n      \"currency\": \"USD\"\n    },\n    {\n      \"id\": \"INV-2042\",\n      \"amount\": 400,\n      \"currency\": \"USD\"\n    }\n  ],\n  \"bank\": [\n    {\n      \"id\": \"wire_44\",\n      \"amount\": 1188,\n      \"currency\": \"USD\"\n    }\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": "0c31867e-7b4f-40fd-80be-6cf8633d4035",
      "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 leftRows = item.stripe || item.left || [];\nconst rightRows = item.bank || item.right || [];\nconst used = new Set();\nconst matched = [];\nconst onlyLeft = [];\nfor (const row of leftRows) {\n  const amount = Number(row.amount);\n  const hit = rightRows.findIndex((other, index) => !used.has(index) && Math.abs(Number(other.amount) - amount) <= 0 && String(other.currency || row.currency || 'USD') === String(row.currency || 'USD'));\n  if (hit >= 0) {\n    used.add(hit);\n    matched.push({ id: row.id, amount, pair: rightRows[hit].id });\n  } else {\n    onlyLeft.push(row);\n  }\n}\nconst onlyRight = rightRows.filter((_, index) => !used.has(index));\nconst record = {\n  matched: matched.length,\n  unmatchedLeft: onlyLeft.length,\n  unmatchedRight: onlyRight.length,\n  onlyLeft,\n  onlyRight,\n  tolerance: 0,\n};\nconst route = onlyLeft.length || onlyRight.length ? 'exceptions' : 'clean';\nreturn {\n  summary: matched.length + ' pairs matched. ' + onlyLeft.length + ' stripe and ' + onlyRight.length + ' bank rows still open.',\n  route,\n  record,\n  slackText: route.toUpperCase() + ' reconciliation: ' + matched.length + ' matched, ' + (onlyLeft.length + onlyRight.length) + ' exceptions.',\n  actions: [{ app: 'Sheets', operation: 'write exceptions', payload: record }],\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": "c95e9d67-f47e-4329-9a7c-ff4104b0bee4",
      "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": "c16b48b0-18f1-4abd-8fa4-1097594cbbbc",
              "leftValue": "={{ $json.demo }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "79cd19eb-304d-48cd-9fa6-4ee77dc8bb7c",
      "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: 'invoice-versus-payment',\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": "41d3de0b-fd20-4833-9d61-ec7b74ef5e6b",
      "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": "Cash application"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "id": "a4bbe123-a580-4feb-a887-51781163fb01",
      "name": "Append Cash application",
      "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": "#finance"
        },
        "text": "={{ $json.slackText || $json.summary }}",
        "otherOptions": {}
      },
      "id": "657e1ada-3c7e-4bf2-a644-dfc53e239d55",
      "name": "Post #finance",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.3,
      "position": [
        1460,
        760
      ],
      "credentials": {
        "slackOAuth2Api": {
          "id": "PLACEHOLDER_SLACKOAUTH2API",
          "name": "Slack account"
        }
      }
    },
    {
      "parameters": {
        "resource": "invoice",
        "operation": "create",
        "organizationId": "YOUR_XERO_ORGANIZATION_ID",
        "type": "ACCREC",
        "contactId": "YOUR_XERO_CONTACT_ID"
      },
      "id": "02d1b78c-c675-4e42-ba30-27216a6e2d91",
      "name": "Create Xero invoice",
      "type": "n8n-nodes-base.xero",
      "typeVersion": 1.1,
      "position": [
        1740,
        760
      ],
      "credentials": {
        "xeroOAuth2Api": {
          "id": "PLACEHOLDER_XEROOAUTH2API",
          "name": "Xero 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": "f46766b5-3119-4fd4-9ad3-c848225273ae",
      "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 Cash application",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append Cash application": {
      "main": [
        [
          {
            "node": "Post #finance",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Post #finance": {
      "main": [
        [
          {
            "node": "Create Xero invoice",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Open invoices are matched to payments on amount. Unmatched invoices stay in the exception list."
  },
  "active": false
}
