{
  "name": "Lead Engine \u00b7 Intake, Qualify, Follow-up",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "lead-intake",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "38e542c9-2f85-46b2-8021-fd37bae085d3",
      "name": "1 \u00b7 Receive Lead (Webhook)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        240,
        300
      ],
      "webhookId": "ae213d40-632c-4053-98ba-c9bdecffac2d"
    },
    {
      "parameters": {
        "jsCode": "// Central settings: change values here, never inside individual nodes.\nconst cfg = {\n  openaiKey: 'PASTE_OPENAI_KEY',        // missing / invalid key -> AI step fails -> rule-based fallback takes over\n  model: 'gpt-4o-mini',\n  dedupeDays: 30,                       // same email/phone inside this window = duplicate, no second follow-up\n  followUpMinutes: 2,                   // demo value. Production: 1440 (24h)\n  notifyUrl: 'https://httpbin.org/anything/telegram',  // stand-in for Telegram / Slack incoming webhook\n};\nreturn $input.all().map(item => {\n  const lead = item.json.body ?? item.json;\n  return { json: { lead, cfg, receivedAt: new Date().toISOString() } };\n});"
      },
      "id": "c6828bab-f14b-4cc6-8f73-d5ba79e15a1f",
      "name": "0.1 Config \u00b7 Settings",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// Clean every field first, so later steps never deal with messy input.\nreturn $input.all().map(({ json }) => {\n  const raw = json.lead || {};\n  const s = v => (v === undefined || v === null) ? '' : String(v).trim();\n  const lead = {\n    name: s(raw.name),\n    email: s(raw.email).toLowerCase(),\n    phone: s(raw.phone).replace(/[^\\d+]/g, ''),\n    company: s(raw.company),\n    message: s(raw.message),\n    source: s(raw.source) || 'website-form',\n    simulate: s(raw.simulate),          // demo switch: 'notify_fail' forces the notification step to fail\n  };\n  const missing = [];\n  if (!lead.name) missing.push('name');\n  if (!lead.email && !lead.phone) missing.push('email or phone');\n  if (lead.email && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/.test(lead.email)) missing.push('valid email');\n  if (!lead.message) missing.push('message');\n  return { json: { ...json, lead, leadKey: lead.email || lead.phone, missing, isComplete: missing.length === 0 } };\n});"
      },
      "id": "8a96e62d-46f7-45ec-9366-32d034b395f6",
      "name": "1.1 Normalize & Validate",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        760,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "1077040a-0996-45b5-8ca3-da38b737ff0d",
              "leftValue": "={{ $json.isComplete }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "372c92f3-4201-43e8-aa0a-a42de4aca9dc",
      "name": "1.2 Complete?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1020,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// Incomplete submissions are parked for a human, never processed blindly.\nconst sd = $getWorkflowStaticData('global');\nsd.reviewQueue = sd.reviewQueue || [];\nreturn $input.all().map(({ json }) => {\n  sd.reviewQueue.push({ at: json.receivedAt, lead: json.lead, missing: json.missing });\n  if (sd.reviewQueue.length > 200) sd.reviewQueue.shift();\n  return { json: { status: 'needs_review', missing: json.missing } };\n});"
      },
      "id": "4779561e-b1c6-4ec7-97b5-bc1981b90ebd",
      "name": "1.3 Flag for Review",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1280,
        520
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify($json) }}",
        "options": {
          "responseCode": 202
        }
      },
      "id": "526dbe53-e496-4188-824f-e3d18025bf8e",
      "name": "1.4 Respond \u00b7 Needs Review",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        1540,
        520
      ]
    },
    {
      "parameters": {
        "jsCode": "// Look the lead up before doing anything with side effects.\nconst sd = $getWorkflowStaticData('global');\nsd.leads = sd.leads || {};\nreturn $input.all().map(({ json }) => {\n  const prev = sd.leads[json.leadKey];\n  const windowMs = json.cfg.dedupeDays * 864e5;\n  const isDuplicate = !!prev && (Date.now() - new Date(prev.savedAt).getTime()) < windowMs;\n  return { json: { ...json, isDuplicate, previousAt: prev ? prev.savedAt : null } };\n});"
      },
      "id": "7b64008c-ef81-4029-a464-76e6c0607153",
      "name": "2.1 Dedupe Check",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1280,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "605b79d6-33c0-4c8a-ac53-5c95f43ba2ed",
              "leftValue": "={{ $json.isDuplicate }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "51e9b855-8346-47a0-88dd-de45eb88823c",
      "name": "2.2 New Lead?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1540,
        300
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'duplicate', lead: $json.leadKey, firstSeen: $json.previousAt, action: 'skipped, no second follow-up' }) }}",
        "options": {
          "responseCode": 200
        }
      },
      "id": "039369e4-7326-4210-aaa2-0c4a5124a7d7",
      "name": "2.3 Respond \u00b7 Duplicate (skipped)",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        1800,
        520
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.openai.com/v1/chat/completions",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ model: $json.cfg.model, temperature: 0, response_format: { type: 'json_object' }, messages: [{ role: 'system', content: 'You qualify inbound B2B leads. Reply ONLY with JSON: {\"priority\":\"hot|warm|cold\",\"category\":\"short need label\",\"reason\":\"one sentence\"}. hot = clear need plus budget or urgency.' },{ role: 'user', content: 'Name: ' + $json.lead.name + '\\nCompany: ' + $json.lead.company + '\\nMessage: ' + $json.lead.message } ] }) }}",
        "options": {
          "timeout": 15000
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $json.cfg.openaiKey }}"
            }
          ]
        }
      },
      "id": "ead5c8a7-2099-4dd5-945e-70eb44bfa8cf",
      "name": "3.1 AI Classify (OpenAI)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1800,
        300
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "jsCode": "// AI answered: validate its JSON instead of trusting it.\nconst base = $('2.1 Dedupe Check').item.json;\nlet ai = {};\ntry { ai = JSON.parse($json.choices[0].message.content); } catch (e) { ai = {}; }\nconst ok = ['hot', 'warm', 'cold'].includes(ai.priority);\nreturn { json: { ...base,\n  priority: ok ? ai.priority : 'warm',\n  category: ai.category || 'general',\n  reason: ai.reason || 'AI reply unparseable, defaulted to warm',\n  classifiedBy: ok ? 'ai' : 'ai-default' } };",
        "mode": "runOnceForEachItem"
      },
      "id": "29bed4fa-58e6-4611-a84e-f7d83150dad8",
      "name": "3.2 Parse AI Result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2060,
        180
      ]
    },
    {
      "parameters": {
        "jsCode": "// Runs only when the AI call still failed after 3 retries (bad key, timeout, rate limit, outage).\n// The lead is never lost: deterministic rules classify it instead.\nconst base = $('2.1 Dedupe Check').item.json;\nconst text = (base.lead.message + ' ' + base.lead.company).toLowerCase();\nconst urgent = /(asap|urgent|this week|today|immediately)/.test(text);\nconst budget = /(\\$|usd|eur|\u20ac|\u00a3)\\s?\\d|budget/.test(text);\nconst priority = (budget && (urgent || base.lead.company)) ? 'hot' : ((budget || urgent) ? 'warm' : 'cold');\nconst category = /(whatsapp|chat|bot|assistant)/.test(text) ? 'ai-assistant'\n  : /(crm|lead|pipeline)/.test(text) ? 'crm-automation'\n  : /(booking|appointment|calendar)/.test(text) ? 'booking' : 'general';\nconst err = $json.error && ($json.error.message || $json.error);\nreturn { json: { ...base, priority, category,\n  reason: 'Rule-based fallback (AI unavailable: ' + String(err || 'error').slice(0, 80) + ')',\n  classifiedBy: 'fallback-rules' } };",
        "mode": "runOnceForEachItem"
      },
      "id": "10c99a7c-fe5b-4af4-a2ca-bf2f52f07da0",
      "name": "3.3 Fallback \u00b7 Rule Classifier",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2060,
        420
      ]
    },
    {
      "parameters": {
        "jsCode": "// CRM stand-in (workflow static data). In production swap for HubSpot / Airtable / Google Sheets node.\nconst sd = $getWorkflowStaticData('global');\nsd.leads = sd.leads || {};\nreturn $input.all().map(({ json }) => {\n  const now = Date.now();\n  const record = {\n    ...json.lead, priority: json.priority, category: json.category, reason: json.reason,\n    classifiedBy: json.classifiedBy, savedAt: new Date(now).toISOString(),\n    followUpAt: json.priority === 'hot' ? null : new Date(now + json.cfg.followUpMinutes * 60000).toISOString(),\n    followUpSent: false, followUpAttempts: 0,\n  };\n  sd.leads[json.leadKey] = record;\n  return { json: { ...json, record } };\n});"
      },
      "id": "376310e7-f33c-4132-b42d-6d01a9766640",
      "name": "4.1 Save Lead (CRM)",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2320,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "aca62250-934c-413d-a768-d3d405c8ca15",
              "leftValue": "={{ $json.priority }}",
              "rightValue": "hot",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "19702989-b951-4a7a-b7e6-88f9f0672a2f",
      "name": "4.2 Hot Lead?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        2580,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $json.lead.simulate === 'notify_fail' ? 'https://httpbin.org/status/503' : $json.cfg.notifyUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: '\ud83d\udd25 Hot lead: ' + $json.lead.name + (($json.lead.company) ? ' (' + $json.lead.company + ')' : '') + ' | ' + $json.category + ' | ' + $json.reason, lead: $json.leadKey }) }}",
        "options": {
          "timeout": 15000
        }
      },
      "id": "6effe7a7-a801-4a36-83e1-bedcb93ee7e9",
      "name": "4.3 Notify Sales (Telegram)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2840,
        180
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1000,
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "jsCode": "const base = $('4.1 Save Lead (CRM)').item.json;\nreturn { json: { ...base, notify: 'sent' } };",
        "mode": "runOnceForEachItem"
      },
      "id": "47cd2231-f2b3-463b-8aee-8f43f092c2fa",
      "name": "4.4 Mark Notified",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3100,
        80
      ]
    },
    {
      "parameters": {
        "jsCode": "// Notification failed after 3 retries: queue it. The follow-up runner retries it later, the lead is already saved.\nconst base = $('4.1 Save Lead (CRM)').item.json;\nconst sd = $getWorkflowStaticData('global');\nsd.notifyQueue = sd.notifyQueue || [];\nconst err = $json.error && ($json.error.message || $json.error);\nsd.notifyQueue.push({ leadKey: base.leadKey, attempts: 3, lastError: String(err || 'error').slice(0, 120), queuedAt: new Date().toISOString() });\nreturn { json: { ...base, notify: 'queued_for_retry' } };",
        "mode": "runOnceForEachItem"
      },
      "id": "7674f615-4fb5-42c1-80c9-0a2b64e7cb5e",
      "name": "4.5 Queue Failed Notification",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3100,
        280
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'accepted', lead: $json.leadKey, priority: $json.priority, category: $json.category, classifiedBy: $json.classifiedBy, notify: $json.notify || 'not hot: follow-up scheduled' }) }}",
        "options": {
          "responseCode": 200
        }
      },
      "id": "85392a68-0e08-4897-a3d8-54e1de01f05d",
      "name": "4.6 Respond \u00b7 Accepted",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        3360,
        300
      ]
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 1
            }
          ]
        }
      },
      "id": "5686085b-8b7a-479e-9357-03237b5c1854",
      "name": "5 \u00b7 Follow-up Runner (every minute)",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        240,
        980
      ]
    },
    {
      "parameters": {
        "jsCode": "// Picks only work that is due and not done yet.\n// A follow-up is marked \"sending\" BEFORE it goes out, so a late success\n// (provider accepted it, but answered after our timeout) is never sent twice.\nconst sd = $getWorkflowStaticData('global');\nconst now = Date.now();\nconst GRACE = 10 * 60 * 1000; // wait this long before asking the provider about an unclear send\nconst out = [];\nfor (const [key, l] of Object.entries(sd.leads || {})) {\n  if (l.followUpSent !== false || !l.followUpAt) continue;\n  if (!l.followUpState && new Date(l.followUpAt).getTime() <= now) {\n    l.followUpState = 'sending';\n    l.followUpKey = key + ':follow_up';          // idempotency key: same lead + step = same key\n    l.followUpSentAt = now;\n    out.push({ json: { kind: 'follow_up', leadKey: key, to: l.email || l.phone, name: l.name, idempotencyKey: l.followUpKey } });\n  } else if ((l.followUpState === 'unclear' || l.followUpState === 'sending') && now - (l.followUpSentAt || 0) >= GRACE) {\n    // timed out (or the run crashed mid-send): look before retrying\n    out.push({ json: { kind: 'follow_up_check', leadKey: key, idempotencyKey: l.followUpKey } });\n  }\n}\nfor (const q of (sd.notifyQueue || [])) {\n  if (q.attempts < 6) out.push({ json: { kind: 'notify_retry', leadKey: q.leadKey } });\n}\nreturn out;"
      },
      "id": "1f15c617-d874-422b-9052-549594ae3688",
      "name": "5.1 Collect Due Work",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        980
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://httpbin.org/anything/{{ $json.kind }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ kind: $json.kind, lead: $json.leadKey, to: $json.to || null, idempotencyKey: $json.idempotencyKey || null }) }}",
        "options": {
          "timeout": 15000
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Idempotency-Key",
              "value": "={{ $json.idempotencyKey || '' }}"
            }
          ]
        }
      },
      "id": "2782d268-0fc7-44b5-bfe5-f4d1387cf71f",
      "name": "5.2 Send Follow-up / Retry Notify",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        760,
        980
      ],
      "retryOnFail": false,
      "onError": "continueErrorOutput",
      "notes": "No built-in retry: a timeout goes straight to 5.4 (marked \"unclear\"), and the 10-min follow_up_check decides. A blind retry could send a second email if the provider accepted the first one late."
    },
    {
      "parameters": {
        "jsCode": "const job = $('5.1 Collect Due Work').item.json;\nconst sd = $getWorkflowStaticData('global');\nconst l = sd.leads && sd.leads[job.leadKey];\nif (job.kind === 'follow_up' && l) { l.followUpSent = true; l.followUpState = 'sent'; }\nif (job.kind === 'follow_up_check' && l) {\n  // Production: 5.2 asks your provider (message search / events API, or the Sent folder over IMAP)\n  // for idempotencyKey and returns { found: true | false }. The demo endpoint echoes, so found stays unknown.\n  const found = $json.found ?? ($json.json && $json.json.found);\n  if (found === true) { l.followUpSent = true; l.followUpState = 'sent'; }\n  else if (found === false && !l.followUpRetried) { l.followUpRetried = true; l.followUpState = null; } // never arrived: send once more on the next tick\n  else { l.followUpSent = 'needs_human'; l.followUpState = 'needs_human'; }                           // still unknown: park it, a human decides\n}\nif (job.kind === 'notify_retry') sd.notifyQueue = (sd.notifyQueue || []).filter(q => q.leadKey !== job.leadKey);\nreturn { json: { ...job, result: (l && l.followUpState) || 'done' } };",
        "mode": "runOnceForEachItem"
      },
      "id": "8b098bcf-e8da-4035-a78b-9d7eec57ad59",
      "name": "5.3 Mark Done",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1020,
        880
      ]
    },
    {
      "parameters": {
        "jsCode": "// Failed or timed out. A follow-up is NOT resent blindly (it may have gone out):\n// it waits GRACE minutes and then the provider is asked about its idempotency key.\nconst job = $('5.1 Collect Due Work').item.json;\nconst sd = $getWorkflowStaticData('global');\nconst l = sd.leads && sd.leads[job.leadKey];\nif (job.kind === 'notify_retry') {\n  const q = (sd.notifyQueue || []).find(x => x.leadKey === job.leadKey);\n  if (q) q.attempts += 1;\n} else if (job.kind === 'follow_up' && l) {\n  l.followUpState = 'unclear';\n} else if (job.kind === 'follow_up_check' && l) {\n  l.followUpChecks = (l.followUpChecks || 0) + 1;\n  if (l.followUpChecks >= 3) { l.followUpSent = 'needs_human'; l.followUpState = 'needs_human'; }\n  else l.followUpSentAt = Date.now();\n}\nreturn { json: { ...job, result: (l && l.followUpState) || 'failed_will_retry' } };",
        "mode": "runOnceForEachItem"
      },
      "id": "1e732c46-75b0-414b-b31f-db2b2cbcc497",
      "name": "5.4 Count Failed Attempt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1020,
        1080
      ]
    },
    {
      "parameters": {
        "httpMethod": "GET",
        "path": "lead-admin",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "29ec8607-5b26-4638-86cb-00ea337ca99f",
      "name": "6 \u00b7 Admin View (GET)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        1800,
        980
      ],
      "webhookId": "565b5a58-16aa-4c2e-a129-69d38f44064a"
    },
    {
      "parameters": {
        "jsCode": "const sd = $getWorkflowStaticData('global');\nconst leads = Object.values(sd.leads || {});\nconst needsHuman = leads.filter(l => l.followUpState === 'needs_human');\nreturn [{ json: {\n  totals: { leads: leads.length, hot: leads.filter(l => l.priority === 'hot').length,\n            reviewQueue: (sd.reviewQueue || []).length, notifyQueue: (sd.notifyQueue || []).length,\n            followUpsNeedingHuman: needsHuman.length },\n  leads: leads.slice(-10), reviewQueue: (sd.reviewQueue || []).slice(-10), notifyQueue: sd.notifyQueue || [],\n  followUpsNeedingHuman: needsHuman } }];"
      },
      "id": "377f17bf-85ff-4765-9559-730ce30195f7",
      "name": "6.1 Read State",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2060,
        980
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify($json) }}",
        "options": {
          "responseCode": 200
        }
      },
      "id": "2b9f8af5-f327-46ab-95a4-39ec77d5ec9f",
      "name": "6.2 Respond \u00b7 State",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        2320,
        980
      ]
    },
    {
      "parameters": {
        "content": "## Lead Engine: intake \u2192 qualify \u2192 act\n**Naming:** `<stage>.<step> Verb \u00b7 Object`, so every execution log reads like a sentence.\n\n**Stage 1 \u00b7 Intake:** normalize every field, then gate on completeness. Incomplete submissions go to a review queue instead of being processed blindly.",
        "width": 1040,
        "height": 200
      },
      "id": "c185236e-f5cd-40f2-b8f6-c6b864f0a142",
      "name": "Note 0a09c8",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        200,
        40
      ]
    },
    {
      "parameters": {
        "content": "## Stage 2 \u00b7 Dedupe before side effects\nSame email/phone within 30 days = duplicate: answered politely, **no second follow-up, no second notification**.",
        "width": 520,
        "height": 200,
        "color": 5
      },
      "id": "e14f3ba1-2d28-4e33-ae50-1d8302c077f4",
      "name": "Note cb6532",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1240,
        40
      ]
    },
    {
      "parameters": {
        "content": "## Stage 3 \u00b7 AI with a fallback\nOpenAI call: **3 retries, 2s apart**. If it still fails (bad key, timeout, 429, outage) the error output routes to a deterministic rule classifier. AI JSON is validated, never trusted blindly.",
        "width": 560,
        "height": 200,
        "color": 4
      },
      "id": "029b640c-4f7b-468d-b681-df3ea3f2ddbd",
      "name": "Note c0c237",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1760,
        40
      ]
    },
    {
      "parameters": {
        "content": "## Stage 4 \u00b7 Store, then notify\nThe lead is **saved before** any notification, so a Telegram/Slack outage can never lose it. Failed notifications (3 retries) are queued and retried by the runner.\n\nDemo: send `\"simulate\":\"notify_fail\"` to force this path.",
        "width": 1100,
        "height": 200,
        "color": 6
      },
      "id": "07a6f660-3a66-41e6-a53a-89048c4ebfbc",
      "name": "Note aadd1b",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        2280,
        40
      ]
    },
    {
      "parameters": {
        "content": "## Stage 5 \u00b7 Follow-up runner\nPicks only due + not-done work (idempotent). A follow-up is marked **sending before** it goes out and carries an `Idempotency-Key` (lead + step). A timeout is never resent blindly: after a 10 min grace the provider is asked about that key \u2014 found \u2192 sent; not found \u2192 one retry; still unknown \u2192 parked as `needs_human` in the admin view.\n\nDemo interval: 1 min \u00b7 production: 15\u201360 min.",
        "width": 1040,
        "height": 200,
        "color": 3
      },
      "id": "a250afb8-09b6-45c2-838e-5709bdf4359e",
      "name": "Note 67f190",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        200,
        700
      ]
    },
    {
      "parameters": {
        "content": "## Stage 6 \u00b7 Admin view\n`GET /webhook/lead-admin` returns totals, latest leads, review queue and notification queue.\n\n**Error workflow:** Settings \u2192 Error workflow \u2192 *Lead Engine \u00b7 Error Handler* (alerts on any unhandled crash).",
        "width": 780,
        "height": 200,
        "color": 7
      },
      "id": "fb247c04-ab5f-41d8-8818-a613b51679a8",
      "name": "Note d63a98",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1760,
        700
      ]
    }
  ],
  "connections": {
    "1 \u00b7 Receive Lead (Webhook)": {
      "main": [
        [
          {
            "node": "0.1 Config \u00b7 Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "0.1 Config \u00b7 Settings": {
      "main": [
        [
          {
            "node": "1.1 Normalize & Validate",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "1.1 Normalize & Validate": {
      "main": [
        [
          {
            "node": "1.2 Complete?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "1.3 Flag for Review": {
      "main": [
        [
          {
            "node": "1.4 Respond \u00b7 Needs Review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "2.1 Dedupe Check": {
      "main": [
        [
          {
            "node": "2.2 New Lead?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "3.2 Parse AI Result": {
      "main": [
        [
          {
            "node": "4.1 Save Lead (CRM)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "3.3 Fallback \u00b7 Rule Classifier": {
      "main": [
        [
          {
            "node": "4.1 Save Lead (CRM)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "4.1 Save Lead (CRM)": {
      "main": [
        [
          {
            "node": "4.2 Hot Lead?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "4.4 Mark Notified": {
      "main": [
        [
          {
            "node": "4.6 Respond \u00b7 Accepted",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "4.5 Queue Failed Notification": {
      "main": [
        [
          {
            "node": "4.6 Respond \u00b7 Accepted",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "1.2 Complete?": {
      "main": [
        [
          {
            "node": "2.1 Dedupe Check",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "1.3 Flag for Review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "2.2 New Lead?": {
      "main": [
        [
          {
            "node": "3.1 AI Classify (OpenAI)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "2.3 Respond \u00b7 Duplicate (skipped)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "3.1 AI Classify (OpenAI)": {
      "main": [
        [
          {
            "node": "3.2 Parse AI Result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "3.3 Fallback \u00b7 Rule Classifier",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "4.2 Hot Lead?": {
      "main": [
        [
          {
            "node": "4.3 Notify Sales (Telegram)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "4.6 Respond \u00b7 Accepted",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "4.3 Notify Sales (Telegram)": {
      "main": [
        [
          {
            "node": "4.4 Mark Notified",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "4.5 Queue Failed Notification",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "5 \u00b7 Follow-up Runner (every minute)": {
      "main": [
        [
          {
            "node": "5.1 Collect Due Work",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "5.1 Collect Due Work": {
      "main": [
        [
          {
            "node": "5.2 Send Follow-up / Retry Notify",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "5.2 Send Follow-up / Retry Notify": {
      "main": [
        [
          {
            "node": "5.3 Mark Done",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "5.4 Count Failed Attempt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "6 \u00b7 Admin View (GET)": {
      "main": [
        [
          {
            "node": "6.1 Read State",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "6.1 Read State": {
      "main": [
        [
          {
            "node": "6.2 Respond \u00b7 State",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "saveManualExecutions": true
  },
  "pinData": {},
  "active": false
}