{
  "name": "Failed payment dunning sequence",
  "nodes": [
    {
      "parameters": {
        "content": "## Failed payment dunning sequence\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": "7a40c74d-d67f-44da-a009-f527a8a2dcff",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -40
      ]
    },
    {
      "parameters": {},
      "id": "69cb4c94-3f24-4d4a-a293-c2c65bceb512",
      "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": "failed-payment-dunning",
        "authentication": "none",
        "responseMode": "lastNode",
        "responseData": "firstEntryJson",
        "options": {}
      },
      "id": "e50a491b-7c2f-4281-a4f9-73b1ce6cb0e9",
      "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": "600ae281-3447-4e70-8abc-1481fa9706f2"
    },
    {
      "parameters": {
        "events": [
          "charge.succeeded",
          "charge.failed",
          "payout.paid"
        ]
      },
      "id": "ba71d52d-d010-46fd-92fb-14e203dd21c1",
      "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  \"email\": \"billing@brightline.example\",\n  \"customer\": \"Brightline Studio\",\n  \"amount\": 149,\n  \"currency\": \"USD\",\n  \"failedAt\": \"2026-11-22T08:00:00.000Z\"\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": "7960a232-805f-4a07-add2-1d4034348c55",
      "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 failedAt = Date.parse(item.failedAt || item.created || new Date().toISOString());\nconst days = Math.floor((Date.now() - failedAt) / 86400000);\nconst steps = [0, 3, 7];\nconst step = steps.filter((value) => days >= value).pop();\nconst attempt = steps.indexOf(step) + 1;\nconst amount = Number(item.amount || 0);\nconst record = {\n  customer: item.customer || item.email,\n  email: item.email || '',\n  amount,\n  currency: item.currency || 'USD',\n  days,\n  attempt,\n  subject: 'Payment attempt ' + attempt + ' for ' + amount + ' ' + (item.currency || 'USD'),\n  body: 'The latest charge failed ' + days + ' days ago. Update the card to keep the workspace active.',\n};\nconst route = attempt >= steps.length ? 'final' : 'retry';\nreturn {\n  summary: 'Dunning step ' + attempt + ' for ' + record.customer + ' (' + amount + ' ' + record.currency + ', ' + days + ' days).',\n  route,\n  record,\n  slackText: route.toUpperCase() + ' dunning for ' + record.customer,\n  actions: [{ app: 'email', operation: 'send', 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": "07fe0663-1fe5-47a3-b238-06360fd4818b",
      "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": "3b03fd79-c49e-42f7-b507-d0ace0d0a711",
              "leftValue": "={{ $json.demo }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "dbdcffe2-0731-4b45-bdd8-fd09b5910a7c",
      "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: 'failed-payment-dunning',\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": "7d845ea6-2f4b-48fb-b090-6e073a444d39",
      "name": "Package demo result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1180,
        180
      ]
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "draft",
        "operation": "create",
        "sendTo": "={{ $json.record.email || $json.email || 'lead@example.com' }}",
        "subject": "={{ $json.record.subject || $json.summary }}",
        "message": "={{ $json.record.body || $json.record.message || $json.summary }}",
        "emailType": "text",
        "messageId": "={{ $json.record.messageId || 'MESSAGE_ID' }}",
        "labelIds": [
          "Label_1"
        ]
      },
      "id": "33754795-8716-4b2b-b48a-1bb65133b8d9",
      "name": "Create Gmail draft",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1180,
        760
      ],
      "credentials": {
        "gmailOAuth2": {
          "id": "PLACEHOLDER_GMAILOAUTH2",
          "name": "Gmail account"
        }
      }
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "message",
        "operation": "post",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "name",
          "value": "#billing"
        },
        "text": "={{ $json.slackText || $json.summary }}",
        "otherOptions": {}
      },
      "id": "15fb2ad9-b282-40a8-8860-3462e2e9c8b7",
      "name": "Post #billing",
      "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": "eabac38c-b401-469d-b3db-c2427350780f",
      "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": "Create Gmail draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Gmail draft": {
      "main": [
        [
          {
            "node": "Post #billing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "A failed charge is placed on step 1, 2, or 3 from how many days have passed. The email is drafted. The last step is marked final."
  },
  "active": false
}
