{
  "name": "Reminder sequence for an unpaid invoice",
  "nodes": [
    {
      "parameters": {
        "content": "## Reminder sequence for an unpaid invoice\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": "944ed03a-f733-435c-aaa7-26d4461c616a",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -40
      ]
    },
    {
      "parameters": {},
      "id": "c60b90b8-792f-4158-88a3-c120bfc22dc5",
      "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": "recurring-invoice-reminder",
        "authentication": "none",
        "responseMode": "lastNode",
        "responseData": "firstEntryJson",
        "options": {}
      },
      "id": "64f5236b-0d06-4a7e-8021-9bd27b411cbc",
      "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": "1d3bda29-4527-4c20-a805-a50d3498d730"
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 8,
              "triggerAtMinute": 15
            }
          ]
        }
      },
      "id": "c3796f5b-c011-4a99-a74b-4325bcc9ab28",
      "name": "Weekday schedule",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        40,
        640
      ],
      "notes": "Monday 08:15. The manual trigger and webhook remain available for tests.",
      "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-11-01\",\n  \"text\": \"Vendor: Northwind Supplies\\nInvoice INV-2041\\nSubtotal 1100.00\\nTax 88.00\\nTotal 1188.00\\nDue 2026-11-01\\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": "564e373d-f552-447f-ba6f-d33f2691ec10",
      "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: 'Collections',\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: 'Collections', 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": "5fb9afed-fb72-4c01-9021-d8976cf9d0ef",
      "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": "98a2621b-9512-4d2a-b9ba-be1ecfc68396",
              "leftValue": "={{ $json.demo }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "280ffe84-750c-43af-b36e-db3e992fd15c",
      "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: 'recurring-invoice-reminder',\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": "215f3e4d-93e0-44f2-83aa-f4a460148523",
      "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": "5454c1a8-bc5e-4346-ad13-0761ea16261e",
      "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": "sheet",
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_SPREADSHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Collections"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "id": "30d405fd-ee38-4765-b430-a0dc7d6ad2e2",
      "name": "Append Collections",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1460,
        760
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "PLACEHOLDER_GOOGLESHEETSOAUTH2API",
          "name": "Google Sheets 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": "8b429cc9-7c77-4d32-ab11-9fd4061db48e",
      "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
          }
        ]
      ]
    },
    "Weekday schedule": {
      "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": "Append Collections",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "An unpaid invoice is classified from its due date and a reminder email is drafted. The sheet records which attempt this is."
  },
  "active": false
}
