{
  "name": "Lead intake: clean, validate, score, store, notify",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "lead-intake",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "node-01",
      "name": "Lead Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        300
      ],
      "webhookId": "a6f1c1de-0000-4000-8000-1ead1ead0001"
    },
    {
      "parameters": {
        "jsCode": "// Clean and Validate: normalise the form fields, collect every problem, never throw.\nconst body = $input.first().json.body || {};\nconst clean = (v) => String(v === undefined || v === null ? '' : v).replace(/\\s+/g, ' ').trim();\nconst name = clean(body.name);\nconst email = clean(body.email).toLowerCase();\nconst company = clean(body.company);\nconst message = clean(body.message);\nlet phone = clean(body.phone).replace(/[^\\d+]/g, '');\nif (phone.startsWith('00')) phone = '+' + phone.slice(2);\nconst budgetDigits = clean(body.budget).replace(/[^\\d.]/g, '');\nconst budget = budgetDigits ? Number(budgetDigits) : 0;\n\nconst errors = [];\nif (name.length < 2) errors.push('name: required, at least 2 characters');\nif (!/^[a-z0-9._%+-]+@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.[a-z]{2,}$/.test(email)) errors.push('email: not a valid address');\nif (phone && !/^\\+?\\d{7,15}$/.test(phone)) errors.push('phone: expected 7 to 15 digits');\nif (message.length < 10) errors.push('message: required, at least 10 characters');\nif (budgetDigits && !Number.isFinite(budget)) errors.push('budget: not a number');\n\nreturn [{\n  json: {\n    valid: errors.length === 0,\n    errors,\n    receivedAt: new Date().toISOString(),\n    lead: { name, email, phone, company, budget, message },\n  },\n}];\n"
      },
      "id": "node-02",
      "name": "Clean and Validate",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        260,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "c-18",
              "leftValue": "={{ $json.valid }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "node-03",
      "name": "Valid?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        520,
        300
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'rejected', errors: $json.errors }) }}",
        "options": {
          "responseCode": 422
        }
      },
      "id": "node-04",
      "name": "Respond 422 Rejected",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        780,
        520
      ]
    },
    {
      "parameters": {
        "operation": "read",
        "fileSelector": "./data/leads.csv",
        "options": {}
      },
      "id": "node-05",
      "name": "Read Leads CSV",
      "type": "n8n-nodes-base.readWriteFile",
      "typeVersion": 1,
      "position": [
        780,
        300
      ],
      "onError": "continueRegularOutput",
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "jsCode": "// Dedupe and Score: look the email up in the existing CSV, then score the lead 0-100.\nconst v = $('Clean and Validate').first().json;\nconst lead = v.lead;\nconst first = $input.first();\n\n// The file read can fail on the very first run (no file yet): treat that as \"no rows\".\nlet existing = '';\nif (first && first.binary && first.binary.data) {\n  existing = (await this.helpers.getBinaryDataBuffer(0, 'data')).toString('utf8');\n}\nconst lines = existing.split(/\\r?\\n/).filter((l) => l.trim() !== '');\nconst rows = lines.slice(1).map((l) => {\n  const cells = [];\n  let cur = '', q = false;\n  for (let i = 0; i < l.length; i++) {\n    const c = l[i];\n    if (q) { if (c === '\"' && l[i + 1] === '\"') { cur += '\"'; i++; } else if (c === '\"') q = false; else cur += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { cells.push(cur); cur = ''; }\n    else cur += c;\n  }\n  cells.push(cur);\n  return cells;\n});\nconst hit = rows.find((r) => (r[3] || '').trim().toLowerCase() === lead.email);\nconst rowCount = rows.length;\nif (hit) {\n  return [{ json: { isDuplicate: true, duplicateOf: hit[0], rowCount, fileExists: lines.length > 0, lead } }];\n}\n\nconst free = ['gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com', 'icloud.com', 'proton.me', 'aol.com'];\nconst domain = lead.email.split('@')[1];\nconst breakdown = [];\nconst add = (label, pts) => { if (pts) breakdown.push({ label, pts }); };\nadd('budget', lead.budget >= 5000 ? 40 : lead.budget >= 1000 ? 25 : lead.budget > 0 ? 10 : 0);\nadd('company given', lead.company ? 15 : 0);\nadd('business email domain', free.includes(domain) ? 0 : 20);\nadd('phone given', lead.phone ? 10 : 0);\nadd('detailed message', lead.message.length >= 40 ? 10 : 0);\nadd('urgent wording', /\\b(asap|urgent|urgently|this week|immediately)\\b/i.test(lead.message) ? 15 : 0);\nconst score = Math.min(100, breakdown.reduce((s, b) => s + b.pts, 0));\nconst tier = score >= 70 ? 'hot' : score >= 40 ? 'warm' : 'cold';\nconst leadId = 'LD-' + String(rowCount + 1).padStart(4, '0');\n\nreturn [{ json: { isDuplicate: false, leadId, score, tier, breakdown, rowCount, fileExists: lines.length > 0, receivedAt: v.receivedAt, lead } }];\n"
      },
      "id": "node-06",
      "name": "Dedupe and Score",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "c-24",
              "leftValue": "={{ $json.isDuplicate }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "node-07",
      "name": "Duplicate?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1300,
        300
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'duplicate', duplicateOf: $json.duplicateOf }) }}",
        "options": {
          "responseCode": 409
        }
      },
      "id": "node-08",
      "name": "Respond 409 Duplicate",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        1560,
        520
      ]
    },
    {
      "parameters": {
        "jsCode": "// Build CSV Row: one CSV line (plus header on the first write) as a binary for the Write File node.\nconst d = $input.first().json;\nconst l = d.lead;\n// Text that starts with = + - @ could run as a formula when the CSV is opened in a spreadsheet.\nconst safe = (s) => (/^[=+\\-@]/.test(s) ? \"'\" + s : s);\nconst cell = (s) => '\"' + String(s).replace(/\"/g, '\"\"') + '\"';\nconst header = 'lead_id,received_at,name,email,phone,company,budget,score,tier,message\\n';\nconst line = [\n  d.leadId, d.receivedAt, cell(safe(l.name)), l.email, l.phone, cell(safe(l.company)), l.budget, d.score, d.tier, cell(safe(l.message)),\n].join(',') + '\\n';\nconst text = (d.fileExists ? '' : header) + line;\nconst row = await this.helpers.prepareBinaryData(Buffer.from(text, 'utf8'), 'leads.csv', 'text/csv');\nreturn [{ json: d, binary: { row } }];\n"
      },
      "id": "node-09",
      "name": "Build CSV Row",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1560,
        300
      ]
    },
    {
      "parameters": {
        "operation": "write",
        "fileName": "./data/leads.csv",
        "dataPropertyName": "row",
        "options": {
          "append": true
        }
      },
      "id": "node-10",
      "name": "Write Lead to CSV",
      "type": "n8n-nodes-base.readWriteFile",
      "typeVersion": 1,
      "position": [
        1820,
        300
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 500,
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "jsCode": "// Format Notification: the text that would go to chat or email, also appended to notifications.txt.\nconst d = $('Build CSV Row').first().json;\nconst l = d.lead;\nconst money = l.budget ? l.budget.toLocaleString('en-US') + ' USD' : 'not given';\nconst notification = [\n  `NEW LEAD ${d.leadId} [${d.tier.toUpperCase()} ${d.score}/100]`,\n  `${l.name}${l.company ? ', ' + l.company : ''}`,\n  `${l.email}${l.phone ? ' | ' + l.phone : ''}`,\n  `Budget: ${money}`,\n  `Message: ${l.message}`,\n].join('\\n');\nconst notice = await this.helpers.prepareBinaryData(Buffer.from(notification + '\\n---\\n', 'utf8'), 'notifications.txt', 'text/plain');\nreturn [{ json: { leadId: d.leadId, score: d.score, tier: d.tier, notification }, binary: { notice } }];\n"
      },
      "id": "node-11",
      "name": "Format Notification",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2080,
        300
      ]
    },
    {
      "parameters": {
        "operation": "write",
        "fileName": "./data/notifications.txt",
        "dataPropertyName": "notice",
        "options": {
          "append": true
        }
      },
      "id": "node-12",
      "name": "Write Notification",
      "type": "n8n-nodes-base.readWriteFile",
      "typeVersion": 1,
      "position": [
        2340,
        300
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 500,
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'accepted', leadId: $('Format Notification').first().json.leadId, score: $('Format Notification').first().json.score, tier: $('Format Notification').first().json.tier, notification: $('Format Notification').first().json.notification }) }}",
        "options": {
          "responseCode": 201
        }
      },
      "id": "node-13",
      "name": "Respond 201 Accepted",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        2600,
        300
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'error', message: 'A write step failed after 3 tries. See the n8n execution for the error.' }) }}",
        "options": {
          "responseCode": 500
        }
      },
      "id": "node-14",
      "name": "Respond 500 Error",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        2600,
        520
      ]
    }
  ],
  "connections": {
    "Lead Webhook": {
      "main": [
        [
          {
            "node": "Clean and Validate",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Clean and Validate": {
      "main": [
        [
          {
            "node": "Valid?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Valid?": {
      "main": [
        [
          {
            "node": "Read Leads CSV",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Respond 422 Rejected",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Leads CSV": {
      "main": [
        [
          {
            "node": "Dedupe and Score",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Dedupe and Score": {
      "main": [
        [
          {
            "node": "Duplicate?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Duplicate?": {
      "main": [
        [
          {
            "node": "Respond 409 Duplicate",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build CSV Row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build CSV Row": {
      "main": [
        [
          {
            "node": "Write Lead to CSV",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write Lead to CSV": {
      "main": [
        [
          {
            "node": "Format Notification",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Respond 500 Error",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Notification": {
      "main": [
        [
          {
            "node": "Write Notification",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write Notification": {
      "main": [
        [
          {
            "node": "Respond 201 Accepted",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Respond 500 Error",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": true
  }
}
