{
  "name": "Lead Ops Demo – MaxAssist99 (web-to-lead with retries + DLQ)",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "lead-ops-demo",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "ecae68a8-323f-48fa-933e-07eb59303101",
      "name": "Lead Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        300
      ],
      "webhookId": "27b7ae0f-e66d-41e4-af68-aee5c07a16bf"
    },
    {
      "parameters": {
        "jsCode": "// Validate & normalize every incoming lead.\n// Output keeps the lead even when invalid, so the IF node can send it to the error branch.\nconst EMAIL_RE = /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\\.[a-z]{2,24}$/;\nconst clip = (v, n) => (v == null ? '' : String(v)).replace(/\\s+/g, ' ').trim().slice(0, n);\nconst titleCase = (s) => s.toLowerCase().replace(/(^|[\\s'-])([a-z])/g, (m, p, c) => p + c.toUpperCase());\n\nfunction toE164(raw) {\n  const s = clip(raw, 40);\n  if (!s) return null;\n  const digits = s.replace(/\\D/g, '');\n  if (s.startsWith('+') && digits.length >= 8 && digits.length <= 15) return '+' + digits;\n  if (digits.length === 10 && /^[2-9]/.test(digits)) return '+1' + digits; // default region: US/Canada\n  if (digits.length === 11 && digits.startsWith('1')) return '+' + digits;\n  return null;\n}\n\nconst out = [];\nfor (const item of $input.all()) {\n  // Webhook node puts the POST body under .body\n  const b = item.json.body || item.json;\n  const lead = {\n    name: titleCase(clip(b.name, 120)),\n    email: clip(b.email, 254).toLowerCase().replace(/\\s+/g, ''),\n    company: clip(b.company, 120),\n    phone: toE164(b.phone),\n    phone_raw: clip(b.phone, 40),\n    need: clip(b.need, 1000),\n    budget: ['under-1k', '1k-5k', '5k-15k', '15k-plus'].includes(b.budget) ? b.budget : 'not-sure',\n    received_at: new Date().toISOString(),\n  };\n  const problems = [];\n  if (!lead.name) problems.push('name is required');\n  if (!lead.email) problems.push('email is required');\n  else if (!EMAIL_RE.test(lead.email)) problems.push('invalid email: ' + lead.email);\n  out.push({ json: { ...lead, valid: problems.length === 0, error_reason: problems.join('; '), failed_step: problems.length ? 'validate' : null, raw: b } });\n}\nreturn out;"
      },
      "id": "6145fcde-39e5-4d52-9668-3f82e4699564",
      "name": "Validate & Normalize",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "c5dbcdb7-6ad1-458e-a82e-8357b3a48187",
              "leftValue": "={{ $json.valid }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "c228c99e-4cbe-4ceb-818e-b2bcc90fecfa",
      "name": "Valid?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        440,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// Dedupe: flag the same email seen in the last 24h.\n// Uses workflow static data, which persists between PRODUCTION executions\n// (active workflow, production webhook URL). Manual test runs do not save it.\n// Swap for a CRM search or a Redis/Sheet lookup if you run several n8n workers.\nconst store = $getWorkflowStaticData('global');\nstore.seen = store.seen || {};\nconst now = Date.now();\nconst DAY = 24 * 60 * 60 * 1000;\nfor (const [k, t] of Object.entries(store.seen)) if (now - t > DAY) delete store.seen[k];\n\nconst out = [];\nfor (const item of $input.all()) {\n  const key = item.json.email;\n  const duplicate = Boolean(store.seen[key]);\n  // Mark as seen only on first sight. (If you want \"seen = stored in CRM\",\n  // move this write to after the CRM node succeeds.)\n  if (!duplicate) store.seen[key] = now;\n  out.push({ json: { ...item.json, duplicate } });\n}\nreturn out;"
      },
      "id": "83682d42-e6ad-4812-9e70-e910ca9812c7",
      "name": "Dedupe (24h)",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        660,
        200
      ]
    },
    {
      "parameters": {
        "jsCode": "// Enrich (domain, free vs business email) + score + route.\nconst FREE = new Set(['gmail.com','googlemail.com','yahoo.com','hotmail.com','outlook.com','live.com','aol.com','icloud.com','me.com','proton.me','protonmail.com','gmx.com','comcast.net','verizon.net','att.net']);\nconst BUDGET_POINTS = { 'under-1k': 5, '1k-5k': 20, '5k-15k': 30, '15k-plus': 40, 'not-sure': 10 };\nconst URGENT = ['asap','urgent','this week','today','tomorrow','broken','down','losing','missed','deadline'];\nconst FIT = ['crm','lead','automation','n8n','make','zapier','hubspot','pipedrive','follow-up','follow up','intake','booking','form'];\n\nreturn $input.all().map((item) => {\n  const l = { ...item.json };\n  const domain = l.email.split('@')[1];\n  l.email_domain = domain;\n  l.email_type = FREE.has(domain) ? 'free' : 'business';\n  l.company_domain = l.email_type === 'business' ? domain : null;\n  if (!l.company && l.company_domain) l.company = domain.split('.')[0];\n\n  let score = BUDGET_POINTS[l.budget] ?? 10;\n  if (l.email_type === 'business') score += 20;\n  if (l.phone) score += 10;\n  if (l.company) score += 5;\n  const need = (l.need || '').toLowerCase();\n  if (URGENT.some((w) => need.includes(w))) score += 15;\n  if (FIT.some((w) => need.includes(w))) score += 10;\n  if (need.length < 15) score -= 5;\n  score = Math.max(0, Math.min(100, score));\n\n  l.score = score;\n  l.tier = score >= 70 ? 'hot' : score >= 40 ? 'warm' : 'cold';\n  l.slack_channel = { hot: '#leads-hot', warm: '#leads', cold: '#leads-nurture' }[l.tier];\n  l.sla = { hot: 'call within 5 minutes', warm: 'reply within 1 business day', cold: 'nurture sequence' }[l.tier];\n  l.crm_payload = {\n    email: l.email, name: l.name, company: l.company, phone: l.phone,\n    lead_score: score, lead_tier: l.tier, need: l.need, budget: l.budget, source: 'web-form',\n  };\n  return { json: l };\n});"
      },
      "id": "a1116c34-34bf-4f46-9870-f739c638659f",
      "name": "Enrich, Score & Route",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        200
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://YOUR-CRM.example.com/api/contacts/upsert",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.crm_payload) }}",
        "options": {
          "timeout": 10000
        }
      },
      "id": "08510576-fb45-4e84-aa5a-94a2792714cb",
      "name": "CRM Upsert",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1100,
        200
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "REPLACE_ME",
          "name": "CRM API key (placeholder)"
        }
      },
      "retryOnFail": true,
      "maxTries": 4,
      "waitBetweenTries": 2000,
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "jsCode": "// HTTP Request output replaces the item with the CRM response.\n// Pull the scored lead back from the node before it, matched by item index.\nreturn $input.all().map((item, i) => ({ json: { ...$('Enrich, Score & Route').all()[i].json, crm_response: item.json } }));"
      },
      "id": "932e75e2-ea52-431a-b0d5-bedd97a1e379",
      "name": "Restore Lead Fields",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1320,
        100
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "a9772e44-5990-4018-9d29-1c7edb33b678",
              "leftValue": "={{ $json.duplicate }}",
              "rightValue": false,
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "c3715dc6-1db0-49f5-b9a6-56c307c5925f",
      "name": "New Lead?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1540,
        100
      ]
    },
    {
      "parameters": {
        "select": "channel",
        "channelId": {
          "__rl": true,
          "value": "={{ $json.slack_channel }}",
          "mode": "name"
        },
        "text": "=New {{ $json.tier }} lead ({{ $json.score }}/100): {{ $json.name }}{{ $json.company ? ' @ ' + $json.company : '' }}, {{ $json.email }}{{ $json.phone ? ', ' + $json.phone : '' }}. Need: {{ $json.need }}. SLA: {{ $json.sla }}",
        "otherOptions": {}
      },
      "id": "a7d068bd-a5be-4a33-a410-bb4b0a913c0f",
      "name": "Slack Alert",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.2,
      "position": [
        1760,
        0
      ],
      "credentials": {
        "slackApi": {
          "id": "REPLACE_ME",
          "name": "Slack bot token (placeholder)"
        }
      }
    },
    {
      "parameters": {
        "fromEmail": "hello@YOUR-DOMAIN.com",
        "toEmail": "={{ $('New Lead?').item.json.email }}",
        "subject": "=Got it, {{ $('New Lead?').item.json.name.split(' ')[0] }}. We received your request",
        "emailFormat": "text",
        "text": "=Hi {{ $('New Lead?').item.json.name.split(' ')[0] }},\n\nThanks for reaching out. We got your request and a real person will reply {{ $('New Lead?').item.json.tier === 'hot' ? 'in the next few minutes' : 'within one business day' }}.\n\nIf it's urgent, just reply to this email.\n\n— The team",
        "options": {}
      },
      "id": "978a9530-c7e0-4b14-b6c6-aeeb5a351bad",
      "name": "Instant Ack Email",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [
        1980,
        0
      ],
      "credentials": {
        "smtp": {
          "id": "REPLACE_ME",
          "name": "SMTP (placeholder)"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { \"status\": \"ok\", \"duplicate\": $('New Lead?').item.json.duplicate, \"tier\": $('New Lead?').item.json.tier } }}",
        "options": {
          "responseCode": 200
        }
      },
      "id": "416b2122-b784-4845-9e2e-54111fbac270",
      "name": "Respond OK",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        2200,
        100
      ]
    },
    {
      "parameters": {
        "jsCode": "// Build one dead-letter row for anything that failed (validation or CRM).\n// Items from the CRM error output carry only { error }, so recover the lead\n// from the scoring node by paired item.\nreturn $input.all().map((item, i) => {\n  let j = item.json;\n  if (!j.email && j.error !== undefined) {\n    const idx = (item.pairedItem && item.pairedItem.item) ?? i;\n    j = { ...$('Enrich, Score & Route').all()[idx].json, error: j.error, failed_step: 'crm' };\n  }\n  const failedStep = j.failed_step || 'crm';\n  return { json: {\n    dlq_id: 'dlq_' + Math.random().toString(16).slice(2, 10),\n    parked_at: new Date().toISOString(),\n    failed_step: failedStep,\n    reason: j.error_reason || (j.error && (j.error.message || JSON.stringify(j.error))) || 'CRM request failed after retries',\n    replayable: failedStep === 'crm',\n    email: j.email || '',\n    name: j.name || '',\n    payload: JSON.stringify(j.raw || j.crm_payload || j),\n  } };\n});"
      },
      "id": "0a5cab7c-fc3d-4480-b678-66ccb837adfd",
      "name": "Build DLQ Row",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1320,
        480
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "REPLACE_WITH_GOOGLE_SHEET_ID",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "DLQ",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "id": "d4952048-884b-41b9-83ff-68970c3665fc",
      "name": "Dead-Letter Queue (Sheet)",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1540,
        480
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "REPLACE_ME",
          "name": "Google Sheets (placeholder)"
        }
      }
    },
    {
      "parameters": {
        "select": "channel",
        "channelId": {
          "__rl": true,
          "value": "#leads-errors",
          "mode": "name"
        },
        "text": "=:warning: Lead {{ $('Build DLQ Row').item.json.name || $('Build DLQ Row').item.json.email }} did not reach the CRM. Step: {{ $('Build DLQ Row').item.json.failed_step }}. Reason: {{ $('Build DLQ Row').item.json.reason }}. Parked as {{ $('Build DLQ Row').item.json.dlq_id }}.",
        "otherOptions": {}
      },
      "id": "dc9243e2-c5aa-48b3-bebf-1ffe8e2f0005",
      "name": "Owner Alert (Slack)",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.2,
      "position": [
        1760,
        480
      ],
      "credentials": {
        "slackApi": {
          "id": "REPLACE_ME",
          "name": "Slack bot token (placeholder)"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { \"status\": \"parked\", \"dlq_id\": $('Build DLQ Row').item.json.dlq_id, \"reason\": $('Build DLQ Row').item.json.reason } }}",
        "options": {
          "responseCode": 202
        }
      },
      "id": "d4ab13f4-6cf8-4380-8911-6a1068c74859",
      "name": "Respond Parked",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        1980,
        480
      ]
    },
    {
      "parameters": {
        "content": "## Lead-ops demo (MaxAssist99)\nDemo build, same flow as https://allmkts.com/demo/lead-ops/\n\n1. Replace the placeholder credentials (CRM header auth, Slack, SMTP, Google Sheets) and the CRM URL.\n2. Create a Google Sheet with a tab named **DLQ**.\n3. Activate, then POST JSON to the production webhook URL.\n\nRetries: n8n's built-in retry on **CRM Upsert** waits a fixed 2s between up to 4 tries (n8n caps it at 5 tries / 5s). The hosted demo shows exponential backoff; for that in n8n, replace the retry with a Wait + loop.\nDedupe uses workflow static data (production executions only).",
        "height": 300,
        "width": 520
      },
      "id": "f2abdfe0-1132-47ab-afc5-9cbceaab911d",
      "name": "README",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        -160
      ]
    }
  ],
  "connections": {
    "Lead Webhook": {
      "main": [
        [
          {
            "node": "Validate & Normalize",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate & Normalize": {
      "main": [
        [
          {
            "node": "Valid?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Valid?": {
      "main": [
        [
          {
            "node": "Dedupe (24h)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build DLQ Row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Dedupe (24h)": {
      "main": [
        [
          {
            "node": "Enrich, Score & Route",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Enrich, Score & Route": {
      "main": [
        [
          {
            "node": "CRM Upsert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "CRM Upsert": {
      "main": [
        [
          {
            "node": "Restore Lead Fields",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build DLQ Row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Restore Lead Fields": {
      "main": [
        [
          {
            "node": "New Lead?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "New Lead?": {
      "main": [
        [
          {
            "node": "Slack Alert",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Respond OK",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Slack Alert": {
      "main": [
        [
          {
            "node": "Instant Ack Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Instant Ack Email": {
      "main": [
        [
          {
            "node": "Respond OK",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build DLQ Row": {
      "main": [
        [
          {
            "node": "Dead-Letter Queue (Sheet)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Dead-Letter Queue (Sheet)": {
      "main": [
        [
          {
            "node": "Owner Alert (Slack)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Owner Alert (Slack)": {
      "main": [
        [
          {
            "node": "Respond Parked",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}