{
  "name": "Stripe charges versus the bank, with a sheet of exceptions",
  "nodes": [
    {
      "parameters": {
        "content": "## Stripe charges versus the bank, with a sheet of exceptions\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": "0bdf5941-4887-4c6a-8d3c-c6b45579aa37",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -40
      ]
    },
    {
      "parameters": {},
      "id": "83434707-e518-4880-87ce-c00aa557dd1a",
      "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": "stripe-bank-reconciliation",
        "authentication": "none",
        "responseMode": "lastNode",
        "responseData": "firstEntryJson",
        "options": {}
      },
      "id": "2109aad9-fb46-4005-836b-a7e79852f9ed",
      "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": "a4ba47f4-32b7-406a-b059-259ac40011cf"
    },
    {
      "parameters": {
        "events": [
          "charge.succeeded",
          "charge.failed",
          "payout.paid"
        ]
      },
      "id": "be48e927-4d63-419c-9c9d-71946254c150",
      "name": "Stripe trigger",
      "type": "n8n-nodes-base.stripeTrigger",
      "typeVersion": 1,
      "position": [
        40,
        640
      ],
      "credentials": {
        "stripeApi": {
          "id": "PLACEHOLDER_STRIPEAPI",
          "name": "Stripe account"
        }
      },
      "notes": "Listens for charge and payout events. The demo uses the sample event.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const sample = {\n  \"demo\": true,\n  \"stripe\": [\n    {\n      \"id\": \"ch_100\",\n      \"amount\": 149,\n      \"currency\": \"USD\"\n    },\n    {\n      \"id\": \"ch_101\",\n      \"amount\": 49,\n      \"currency\": \"USD\"\n    },\n    {\n      \"id\": \"ch_102\",\n      \"amount\": 399,\n      \"currency\": \"USD\"\n    }\n  ],\n  \"bank\": [\n    {\n      \"id\": \"txn_900\",\n      \"amount\": 149,\n      \"currency\": \"USD\"\n    },\n    {\n      \"id\": \"txn_901\",\n      \"amount\": 49.2,\n      \"currency\": \"USD\"\n    },\n    {\n      \"id\": \"txn_902\",\n      \"amount\": 20,\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": "60007cbf-a790-49f2-a8f7-0347ed6d2713",
      "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.5 && 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.5,\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": "94a5ac34-71ae-4fc1-889d-3c841688e170",
      "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": "c3e7339c-8ae6-4a48-90fb-b9c922bafcb4",
              "leftValue": "={{ $json.demo }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "93400327-b5de-4c63-b5a7-274a7e753864",
      "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: 'stripe-bank-reconciliation',\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": "aa521cb8-3b22-43c4-b863-cdb0795201dc",
      "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": "Reconciliation"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "id": "75194910-bcf4-43a8-9836-6a113c4484ff",
      "name": "Append Reconciliation",
      "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": "ac30c318-08e7-4ed8-a2fb-643e2a6ad370",
      "name": "Post #finance",
      "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": "07752a83-5934-4dd4-9310-4a43d1f3a774",
      "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
          }
        ]
      ]
    },
    "Stripe 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 Reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append Reconciliation": {
      "main": [
        [
          {
            "node": "Post #finance",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Stripe charges are matched to bank lines on amount and currency within 50 cents. Matches are counted. Leftovers on either side become the exception report in Sheets and a Slack summary."
  },
  "active": false
}
