{
  "name": "CDUDU WF02 — Omnichannel Lead Normalizer, BANT Scorer & 15m SLA Escalation Router",
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "timezone": "Asia/Ho_Chi_Minh",
    "saveManualExecutions": true,
    "saveDataErrorExecution": "all",
    "saveDataSuccessExecution": "all",
    "callerPolicy": "workflowsFromSameOwner",
    "errorWorkflow": "CDUDU_GLOBAL_DLQ_ERROR_WORKFLOW"
  },
  "versionId": "cdudu-wf02-v2026.12.02",
  "meta": {
    "instanceId": "cdudu-enterprise-n8n-2x",
    "templateCredsSetupCompleted": false,
    "author": "Công ty Giải Pháp và Công Nghệ Cdudu (https://cdudu.com)"
  },
  "tags": [
    { "name": "cdudu-production" },
    { "name": "lead-sla-15m" },
    { "name": "bant-scoring" }
  ],
  "nodes": [
    {
      "id": "wf02-n1-webhook",
      "name": "Webhook Omnichannel Lead",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [180, 300],
      "webhookId": "cdudu-wf02-lead-intake",
      "parameters": {
        "httpMethod": "POST",
        "path": "cdudu/v1/lead-sla-router",
        "authentication": "headerAuth",
        "responseMode": "responseNode",
        "options": {}
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "CREDENTIAL_ID_CDUDU_WEBHOOK_HEADER_AUTH",
          "name": "Cdudu Webhook Header Auth"
        }
      }
    },
    {
      "id": "wf02-n2-normalize-dedupe",
      "name": "Normalize VN Phone & Dedupe",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [440, 300],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "function simpleHash(str) {\n  let h1 = 0xdeadbeef ^ str.length, h2 = 0x41c6ce57 ^ str.length;\n  for (let i = 0; i < str.length; i++) {\n    const ch = str.charCodeAt(i);\n    h1 = Math.imul(h1 ^ ch, 2654435761);\n    h2 = Math.imul(h2 ^ ch, 1597334677);\n  }\n  h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n  h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0');\n}\n\nfunction normalizeVietnamPhone(raw) {\n  const digits = String(raw || '').replace(/[^\\d+]/g, '');\n  let cleaned = digits.replace(/^\\+/, '');\n  if (cleaned.startsWith('84') && cleaned.length === 11) {\n    cleaned = '0' + cleaned.slice(2);\n  }\n  const isValidMobile = /^0(3[2-9]|5[25689]|7[06-9]|8[1-9]|9[0-9])\\d{7}$/.test(cleaned);\n  const isValidLandline = /^02\\d{8,9}$/.test(cleaned);\n  let carrier = 'UNKNOWN';\n  if (/^0(3[2-9]|86|9[678])/.test(cleaned)) carrier = 'Viettel';\n  else if (/^0(7[06-9]|89|9[03])/.test(cleaned)) carrier = 'MobiFone';\n  else if (/^0(8[1-58]|9[14])/.test(cleaned)) carrier = 'VinaPhone';\n  else if (/^0(5[268]|92)/.test(cleaned)) carrier = 'Vietnamobile';\n  else if (isValidLandline) carrier = 'VN_Landline';\n  return {\n    raw: String(raw || ''),\n    normalized: cleaned,\n    e164: isValidMobile ? ('+84' + cleaned.slice(1)) : '',\n    valid: isValidMobile || isValidLandline,\n    carrier\n  };\n}\n\nconst out = [];\nfor (const item of $input.all()) {\n  const body = item.json.body !== undefined ? item.json.body : item.json;\n  const phoneInfo = normalizeVietnamPhone(body.phone || '');\n  const channel = String(body.channel || 'website').trim().toLowerCase();\n  const dayBucket = new Date().toISOString().slice(0, 10);\n  const dedupeBasis = (phoneInfo.normalized || String(body.email || 'anon').toLowerCase()) + '|' + channel + '|' + dayBucket;\n  const dedupeKey = 'lead_' + simpleHash(dedupeBasis);\n  const existingKeys = new Set(Array.isArray(body.existing_lead_keys) ? body.existing_lead_keys : []);\n\n  out.push({\n    json: {\n      lead_id: 'LD-' + dayBucket.replace(/-/g, '') + '-' + simpleHash(dedupeBasis + Date.now()).slice(0, 6).toUpperCase(),\n      dedupe_key: dedupeKey,\n      is_duplicate: existingKeys.has(dedupeKey),\n      channel,\n      full_name: String(body.full_name || 'Khách hàng B2B').trim().slice(0, 120),\n      company_name: String(body.company_name || '').trim().slice(0, 160),\n      role_title: String(body.role_title || '').trim().slice(0, 80),\n      phone: phoneInfo,\n      email: String(body.email || '').trim().toLowerCase(),\n      budget_vnd: Number(body.budget_vnd || 0),\n      need_summary: String(body.need_summary || '').trim().slice(0, 500),\n      timeline: String(body.timeline || 'this_month').trim().toLowerCase(),\n      requires_vat_invoice: Boolean(body.requires_vat_invoice !== false),\n      received_at_iso: new Date().toISOString()\n    }\n  });\n}\nreturn out;"
      }
    },
    {
      "id": "wf02-n3-bant-scorer",
      "name": "Score BANT & Assign Sales",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [700, 300],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const out = [];\nfor (const item of $input.all()) {\n  const d = item.json;\n  let budgetScore = 5;\n  if (d.budget_vnd >= 20000000) budgetScore = 30;\n  else if (d.budget_vnd >= 10000000) budgetScore = 24;\n  else if (d.budget_vnd >= 5000000) budgetScore = 18;\n  else if (d.budget_vnd > 0) budgetScore = 10;\n\n  const roleLower = String(d.role_title || '').toLowerCase();\n  let authorityScore = 8;\n  if (/(giám đốc|ceo|founder|chủ tịch|chủ doanh nghiệp|cfo|cto|director|owner)/i.test(roleLower)) authorityScore = 25;\n  else if (/(trưởng phòng|kế toán trưởng|manager|head|lead|quản lý)/i.test(roleLower)) authorityScore = 18;\n\n  const needLower = String(d.need_summary || '').toLowerCase();\n  let needScore = 10;\n  if (/(hóa đơn|vat|vietqr|sepay|erp|crm|zalo|sla|n8n|tự động|kế toán|server riêng)/i.test(needLower)) needScore += 12;\n  if (d.company_name) needScore += 3;\n  needScore = Math.min(25, needScore);\n\n  let timelineScore = 8;\n  if (/(ngay|tuần này|urgent|asap|immediate|this_week)/i.test(d.timeline)) timelineScore = 20;\n  else if (/(tháng này|this_month|30 ngày)/i.test(d.timeline)) timelineScore = 14;\n  else if (/(quý này|this_quarter)/i.test(d.timeline)) timelineScore = 8;\n  else timelineScore = 4;\n\n  const totalScore = budgetScore + authorityScore + needScore + timelineScore;\n  let tier = 'NURTURE_C';\n  let assignedSales = 'Sales Inbound Pool (SLA 60p)';\n  let slaMinutes = 60;\n  let escalationTarget = 'Sales Team Lead';\n\n  if (totalScore >= 75) {\n    tier = 'HOT_A';\n    assignedSales = 'Senior B2B Solutions Closer (Ưu tiên #1)';\n    slaMinutes = 15;\n    escalationTarget = 'Giám đốc Kinh doanh & CEO';\n  } else if (totalScore >= 50) {\n    tier = 'WARM_B';\n    assignedSales = 'B2B Automation Consultant';\n    slaMinutes = 15;\n    escalationTarget = 'Trưởng phòng Kinh doanh';\n  }\n\n  const slaDeadlineIso = new Date(Date.now() + slaMinutes * 60000).toISOString();\n\n  out.push({\n    json: {\n      ...d,\n      bant: {\n        budget: budgetScore,\n        authority: authorityScore,\n        need: needScore,\n        timeline: timelineScore,\n        total: totalScore,\n        tier\n      },\n      routing: {\n        assigned_sales: assignedSales,\n        sla_minutes: slaMinutes,\n        sla_deadline_iso: slaDeadlineIso,\n        escalation_target: escalationTarget,\n        phone_valid: Boolean(d.phone && d.phone.valid)\n      }\n    }\n  });\n}\nreturn out;"
      }
    },
    {
      "id": "wf02-n4-if-dup",
      "name": "Check Duplicate Lead",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [960, 300],
      "parameters": {
        "conditions": {
          "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict" },
          "conditions": [
            {
              "id": "cond-lead-dup",
              "leftValue": "={{ $json.is_duplicate }}",
              "rightValue": true,
              "operator": { "type": "boolean", "operation": "true", "singleValue": true }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "wf02-n5-respond-dup",
      "name": "Respond Duplicate Lead 200",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [1220, 140],
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'duplicate_lead_merged', dedupe_key: $json.dedupe_key, lead_id: $json.lead_id }) }}",
        "options": { "responseCode": 200 }
      }
    },
    {
      "id": "wf02-n6-upsert-crm",
      "name": "Upsert CRM Lead (Postgres)",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [1220, 380],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2500,
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO crm_leads_sla (lead_id, dedupe_key, channel, full_name, company_name, phone_normalized, bant_score, bant_tier, assigned_sales, sla_minutes, sla_deadline, status, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::timestamptz, 'NEW_PENDING_RESPONSE', NOW()) ON CONFLICT (dedupe_key) DO NOTHING;",
        "options": {
          "queryReplacement": "={{ [$json.lead_id, $json.dedupe_key, $json.channel, $json.full_name, $json.company_name, $json.phone.normalized, $json.bant.total, $json.bant.tier, $json.routing.assigned_sales, $json.routing.sla_minutes, $json.routing.sla_deadline_iso] }}"
        }
      },
      "credentials": {
        "postgres": {
          "id": "CREDENTIAL_ID_CDUDU_POSTGRES",
          "name": "Cdudu CRM Postgres"
        }
      }
    },
    {
      "id": "wf02-n7-notify-sales",
      "name": "Notify Assigned Sales (Zalo/Telegram)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1480, 380],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "parameters": {
        "method": "POST",
        "url": "={{ $vars.CDUDU_SALES_WEBHOOK_URL }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ event: 'NEW_LEAD_ASSIGNED', lead_id: $('Score BANT & Assign Sales').item.json.lead_id, tier: $('Score BANT & Assign Sales').item.json.bant.tier, bant_score: $('Score BANT & Assign Sales').item.json.bant.total, assigned_sales: $('Score BANT & Assign Sales').item.json.routing.assigned_sales, sla_minutes: $('Score BANT & Assign Sales').item.json.routing.sla_minutes }) }}",
        "options": { "timeout": 10000 }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "CREDENTIAL_ID_CDUDU_NOTIFY_AUTH",
          "name": "Cdudu Internal Notify Auth"
        }
      }
    },
    {
      "id": "wf02-n8-respond-201",
      "name": "Respond Accepted 201",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [1740, 260],
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ status: 'assigned', lead_id: $('Score BANT & Assign Sales').item.json.lead_id, bant: $('Score BANT & Assign Sales').item.json.bant, routing: $('Score BANT & Assign Sales').item.json.routing }) }}",
        "options": { "responseCode": 201 }
      }
    },
    {
      "id": "wf02-n9-wait-15m",
      "name": "Wait 15 Minutes SLA Window",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [1740, 480],
      "parameters": {
        "resume": "timeInterval",
        "amount": 15,
        "unit": "minutes"
      }
    },
    {
      "id": "wf02-n10-check-sla",
      "name": "Check Lead First Response (Postgres)",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [1980, 480],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2500,
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT lead_id, status, first_response_at, assigned_sales, bant_tier FROM crm_leads_sla WHERE lead_id = $1 LIMIT 1;",
        "options": {
          "queryReplacement": "={{ [$('Score BANT & Assign Sales').item.json.lead_id] }}"
        }
      },
      "credentials": {
        "postgres": {
          "id": "CREDENTIAL_ID_CDUDU_POSTGRES",
          "name": "Cdudu CRM Postgres"
        }
      }
    },
    {
      "id": "wf02-n11-if-breached",
      "name": "Is SLA Breached?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [2220, 480],
      "parameters": {
        "conditions": {
          "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict" },
          "conditions": [
            {
              "id": "cond-sla-breach",
              "leftValue": "={{ $json.first_response_at || '' }}",
              "rightValue": "",
              "operator": { "type": "string", "operation": "empty", "singleValue": true }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "wf02-n12-escalate",
      "name": "Escalate SLA Breach to Manager",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [2480, 480],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "parameters": {
        "method": "POST",
        "url": "={{ $vars.CDUDU_ALERT_WEBHOOK_URL }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ level: 'SLA_ESCALATION', lead_id: $json.lead_id, bant_tier: $json.bant_tier, assigned_sales: $json.assigned_sales, message: 'CẢNH BÁO SLA 15 PHÚT: Lead chưa được phản hồi sau 15 phút — đề nghị quản lý tiếp quản ngay!' }) }}",
        "options": { "timeout": 10000 }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "CREDENTIAL_ID_CDUDU_NOTIFY_AUTH",
          "name": "Cdudu Internal Notify Auth"
        }
      }
    },
    {
      "id": "wf02-n13-error-trigger",
      "name": "Error Trigger",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [180, 680],
      "parameters": {}
    },
    {
      "id": "wf02-n14-error-alert",
      "name": "Alert Lead Pipeline Error",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [460, 680],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "parameters": {
        "method": "POST",
        "url": "={{ $vars.CDUDU_ALERT_WEBHOOK_URL }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ level: 'CRITICAL', workflow: 'WF02_LEAD_SLA_ROUTER', error: $json.execution && $json.execution.error ? $json.execution.error.message : 'Unknown error' }) }}",
        "options": { "timeout": 10000 }
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "CREDENTIAL_ID_CDUDU_NOTIFY_AUTH",
          "name": "Cdudu Internal Notify Auth"
        }
      }
    }
  ],
  "connections": {
    "Webhook Omnichannel Lead": {
      "main": [[{ "node": "Normalize VN Phone & Dedupe", "type": "main", "index": 0 }]]
    },
    "Normalize VN Phone & Dedupe": {
      "main": [[{ "node": "Score BANT & Assign Sales", "type": "main", "index": 0 }]]
    },
    "Score BANT & Assign Sales": {
      "main": [[{ "node": "Check Duplicate Lead", "type": "main", "index": 0 }]]
    },
    "Check Duplicate Lead": {
      "main": [
        [{ "node": "Respond Duplicate Lead 200", "type": "main", "index": 0 }],
        [{ "node": "Upsert CRM Lead (Postgres)", "type": "main", "index": 0 }]
      ]
    },
    "Upsert CRM Lead (Postgres)": {
      "main": [[{ "node": "Notify Assigned Sales (Zalo/Telegram)", "type": "main", "index": 0 }]]
    },
    "Notify Assigned Sales (Zalo/Telegram)": {
      "main": [[
        { "node": "Respond Accepted 201", "type": "main", "index": 0 },
        { "node": "Wait 15 Minutes SLA Window", "type": "main", "index": 0 }
      ]]
    },
    "Wait 15 Minutes SLA Window": {
      "main": [[{ "node": "Check Lead First Response (Postgres)", "type": "main", "index": 0 }]]
    },
    "Check Lead First Response (Postgres)": {
      "main": [[{ "node": "Is SLA Breached?", "type": "main", "index": 0 }]]
    },
    "Is SLA Breached?": {
      "main": [
        [{ "node": "Escalate SLA Breach to Manager", "type": "main", "index": 0 }],
        []
      ]
    },
    "Error Trigger": {
      "main": [[{ "node": "Alert Lead Pipeline Error", "type": "main", "index": 0 }]]
    }
  }
}
