{
  "name": "Lead Intake Workflow",
  "description": null,
  "active": false,
  "isArchived": false,
  "nodes": [
    {
      "id": "n1",
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        0,
        300
      ],
      "parameters": {
        "httpMethod": "POST",
        "path": "lead-intake",
        "responseMode": "onReceived",
        "options": {}
      },
      "webhookId": "23fa2db4-983f-4a46-b851-3ab2c3756600"
    },
    {
      "id": "n2",
      "name": "Normalize Lead",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        260,
        300
      ],
      "parameters": {
        "jsCode": "const raw = $input.first().json.body || $input.first().json;\nconst formType = raw.formType || 'estimate';\n\nconst firstName = String(raw.firstName || '').trim();\nconst lastName = String(raw.lastName || '').trim();\nconst phone = String(raw.phone || '').replace(/[^\\d+\\-() ]/g, '').trim();\nconst email = String(raw.email || '').toLowerCase().trim();\nconst location = String(raw.location || '').trim();\nconst description = String(raw.description || '').trim();\nconst marketingOptIn = Boolean(raw.marketingOptIn);\n\nlet visitPreference, urgency, slaMinutes;\nif (formType === 'referral') {\n  visitPreference = raw.visitPreference || 'schedule';\n  urgency = visitPreference === 'asap' ? 'Emergency' : (raw.urgency === 'urgent' ? 'Urgent' : 'Standard');\n  slaMinutes = visitPreference === 'asap' ? 5 : 10;\n} else {\n  visitPreference = raw.visitPreference || 'schedule';\n  urgency = visitPreference === 'asap' ? 'Emergency' : 'Standard';\n  slaMinutes = visitPreference === 'asap' ? 5 : 10;\n}\n\nconst now = new Date();\nconst slaDueAt = new Date(now.getTime() + slaMinutes * 60 * 1000).toISOString();\nconst preferredDate = raw.preferredDate || '';\nconst preferredTime = raw.preferredTime || '';\n\nconst cityMatch = location.match(/,\\s*([^,\\d]+?)(?:\\s*,|\\s+TX|\\s+Texas|\\s*$)/i);\nconst city = cityMatch ? cityMatch[1].trim() : '';\nconst zipMatch = location.match(/\\b(\\d{5})\\b/);\nconst zip = zipMatch ? zipMatch[1] : '';\n\nconst customerName = `${firstName} ${lastName}`.trim() || 'Unknown';\n\nconst source = formType === 'referral' ? 'Trade Referral' : 'Website Form';\n\nlet leadSummary = '';\nif (urgency === 'Emergency') leadSummary += 'EMERGENCY REQUEST. ';\nif (formType === 'referral') {\n  leadSummary += `Referred by: ${raw.referredBy || 'Unknown'}${raw.referredByCompany ? ' (' + raw.referredByCompany + ')' : ''}, ${raw.referredByTrade || ''}. `;\n}\nif (visitPreference === 'schedule' && preferredDate) {\n  leadSummary += `Wants appt ${preferredDate}${preferredTime ? ' at ' + preferredTime : ''}. `;\n}\nleadSummary += description || 'No details provided.';\n\nreturn [{ json: {\n  firstName, lastName, customerName,\n  phone, email, location, city, zip,\n  visitPreference, urgency,\n  preferredDate, preferredTime,\n  description, marketingOptIn,\n  formType,\n  source,\n  referredBy: raw.referredBy || '',\n  referredByCompany: raw.referredByCompany || '',\n  referredByPhone: raw.referredByPhone || '',\n  referredByTrade: raw.referredByTrade || '',\n  createdAt: now.toISOString(),\n  slaDueAt, leadSummary,\n  inboundRaw: JSON.stringify(raw)\n}}];"
      }
    },
    {
      "id": "n3",
      "name": "Check Duplicate",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        520,
        300
      ],
      "parameters": {
        "method": "GET",
        "url": "https://api.airtable.com/v0/APP_ID/TABLE_ID",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer YOUR_API_KEY"
            }
          ]
        },
        "sendQuery": true,
        "specifyQuery": "keypair",
        "queryParameters": {
          "parameters": [
            {
              "name": "filterByFormula",
              "value": "={{ 'OR({Phone}=\"' + $json.phone + '\",LOWER(TRIM({Email}))=\"' + $json.email + '\")' }}"
            },
            {
              "name": "maxRecords",
              "value": "3"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "n4",
      "name": "Is Duplicate?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        780,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "cond-dup",
              "leftValue": "={{ ($json.records || []).length }}",
              "rightValue": 0,
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "n5",
      "name": "Flag Duplicate",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        1040,
        100
      ],
      "parameters": {
        "method": "PATCH",
        "url": "={{ 'https://api.airtable.com/v0/APP_ID/TABLE_ID/' + $json.records[0].id }}",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer YOUR_API_KEY"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "json",
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ fields: { 'Duplicate Flag': true, 'Notes': 'Duplicate submission on ' + new Date().toLocaleString('en-US', {timeZone:'America/Chicago'}) } }) }}",
        "options": {}
      }
    },
    {
      "id": "n6",
      "name": "Get Team Members",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        1040,
        500
      ],
      "parameters": {
        "method": "GET",
        "url": "https://api.airtable.com/v0/APP_ID/tbltAUtUpmM2ej7U2",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer YOUR_API_KEY"
            }
          ]
        },
        "sendQuery": true,
        "specifyQuery": "keypair",
        "queryParameters": {
          "parameters": [
            {
              "name": "filterByFormula",
              "value": "{Active for Assignment}=TRUE()"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "n7",
      "name": "Assign and Build Payload",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1300,
        500
      ],
      "parameters": {
        "jsCode": "const teamData = $input.first().json;\nconst lead = $('Normalize Lead').first().json;\n\nconst records = (teamData.records || []).filter(r => r.fields);\nconst now = new Date().toISOString();\n\nlet assignedTo = 'Unassigned';\nlet assignedEmail = '';\nlet assignedPhone = '';\nlet memberId = null;\n\nif (records.length > 0) {\n  const sorted = records.sort((a, b) => {\n    const aTime = a.fields['Last Assigned At'] ? new Date(a.fields['Last Assigned At']).getTime() : 0;\n    const bTime = b.fields['Last Assigned At'] ? new Date(b.fields['Last Assigned At']).getTime() : 0;\n    return aTime - bTime;\n  });\n  const assignee = sorted[0];\n  assignedTo = assignee.fields['Name'] || 'Unknown';\n  assignedEmail = assignee.fields['Email'] || '';\n  assignedPhone = assignee.fields['Twilio SMS Target'] || assignee.fields['Phone'] || '';\n  memberId = assignee.id;\n}\n\nconst airtableFields = {\n  'Customer Name': lead.customerName,\n  'Status': memberId ? 'Assigned' : 'New',\n  'Created At': lead.createdAt,\n  'Source': lead.source,\n  'Phone': lead.phone,\n  'Email': lead.email,\n  'Address': lead.location,\n  'City': lead.city,\n  'Zip': lead.zip,\n  'Service Type': 'Other',\n  'Urgency': lead.urgency,\n  'Lead Summary': lead.leadSummary,\n  'Assigned To': assignedTo,\n  'Assignment Timestamp': now,\n  'SLA Due At': lead.slaDueAt,\n  'Inbound Message Raw': lead.inboundRaw\n};\n\n// Add referral fields if this is a trade referral\nif (lead.formType === 'referral') {\n  if (lead.referredBy) airtableFields['Referred By'] = lead.referredBy;\n  if (lead.referredByCompany) airtableFields['Referral Company'] = lead.referredByCompany;\n  if (lead.referredByPhone) airtableFields['Referral Phone'] = lead.referredByPhone;\n  if (lead.referredByTrade) airtableFields['Referral Trade'] = lead.referredByTrade;\n}\n\nreturn [{ json: {\n  ...lead,\n  assignedTo, assignedEmail, assignedPhone, memberId,\n  assignmentTimestamp: now,\n  leadStatus: memberId ? 'Assigned' : 'New',\n  airtableFields\n}}];"
      }
    },
    {
      "id": "n8",
      "name": "Create Lead Record",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        1560,
        500
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.airtable.com/v0/APP_ID/TABLE_ID",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer YOUR_API_KEY"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "json",
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ fields: $json.airtableFields }) }}",
        "options": {}
      }
    },
    {
      "id": "n9",
      "name": "Prep Notifications",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1820,
        500
      ],
      "parameters": {
        "jsCode": "const created = $input.first().json;\nconst d = $('Assign and Build Payload').first().json;\n\nconst digits = (d.phone || '').replace(/\\D/g, '');\nconst telPhone = digits.length === 10 ? '+1' + digits : '+' + digits;\n\nconst urgencyColor = d.urgency === 'Emergency' ? '#DC2626' : d.urgency === 'Urgent' ? '#D97706' : '#222222';\nconst slaTime = new Date(d.slaDueAt).toLocaleTimeString('en-US', {timeZone:'America/Chicago', hour:'numeric', minute:'2-digit'}) + ' CT';\n\nconst referralRow = d.formType === 'referral' && d.referredBy\n  ? '<tr><td style=\"background-color:#f7f7f7;padding:12px 16px;width:120px;border-bottom:1px solid #e6e6e6;\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:bold;color:#6b6b6b;text-transform:uppercase;letter-spacing:0.5px;\">Referred By</span></td><td style=\"padding:12px 16px;border-bottom:1px solid #e6e6e6;\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:14px;color:#222222;\">' + d.referredBy + (d.referredByCompany ? ' (' + d.referredByCompany + ')' : '') + (d.referredByTrade ? ' &bull; ' + d.referredByTrade : '') + '</span></td></tr>'\n  : '';\n\nconst internalAlertHtml = '<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\"></head>'\n  + '<body style=\"margin:0;padding:0;background-color:#f0f0f0;font-family:Arial,Helvetica,sans-serif;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"background-color:#f0f0f0;\"><tr><td align=\"center\" style=\"padding:24px 16px;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"max-width:600px;width:100%;background-color:#ffffff;border-radius:6px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.10);\">'\n  // Urgency banner\n  + '<tr><td style=\"background-color:' + urgencyColor + ';padding:12px 32px;text-align:center;\">'\n  + '<span style=\"display:inline-block;background-color:rgba(255,255,255,0.18);border:1px solid rgba(255,255,255,0.35);border-radius:20px;padding:4px 16px;font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;letter-spacing:1.5px;text-transform:uppercase;color:#ffffff;\">'\n  + d.urgency + ' LEAD</span></td></tr>'\n  // Dark header\n  + '<tr><td style=\"background-color:#222222;padding:24px 32px;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr>'\n  + '<td><span style=\"font-family:Georgia,serif;font-size:22px;font-weight:bold;color:#ffffff;\">ACME</span>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:22px;color:#C98A1A;\"> Home Services</span><br>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;color:#9a9a9a;letter-spacing:1px;text-transform:uppercase;\">Internal Lead Alert</span></td>'\n  + '<td align=\"right\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;color:#9a9a9a;\">example.com</span></td>'\n  + '</tr></table></td></tr>'\n  // Status row\n  + '<tr><td style=\"background-color:' + urgencyColor + ';padding:16px 32px;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr>'\n  + '<td><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:18px;font-weight:bold;color:#ffffff;\">New Inbound Lead</span><br>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:13px;color:rgba(255,255,255,0.85);\">' + d.urgency + ' &bull; SLA: ' + slaTime + ' &bull; ' + d.source + '</span></td>'\n  + '<td align=\"right\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;color:rgba(255,255,255,0.75);\">Assigned to</span><br>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:14px;font-weight:bold;color:#ffffff;\">' + d.assignedTo + '</span></td>'\n  + '</tr></table></td></tr>'\n  // Contact details label\n  + '<tr><td style=\"padding:28px 32px 0 32px;\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;color:#9a9a9a;letter-spacing:1.2px;text-transform:uppercase;\">Contact Information</span></td></tr>'\n  // Contact details table\n  + '<tr><td style=\"padding:12px 32px 0 32px;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"border:1px solid #e6e6e6;border-radius:6px;overflow:hidden;\">'\n  + '<tr><td style=\"background-color:#f7f7f7;padding:12px 16px;width:120px;border-bottom:1px solid #e6e6e6;\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:bold;color:#6b6b6b;text-transform:uppercase;letter-spacing:0.5px;\">Name</span></td>'\n  + '<td style=\"padding:12px 16px;border-bottom:1px solid #e6e6e6;\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:15px;font-weight:bold;color:#222222;\">' + d.customerName + '</span></td></tr>'\n  + '<tr><td style=\"background-color:#f7f7f7;padding:12px 16px;width:120px;border-bottom:1px solid #e6e6e6;\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:bold;color:#6b6b6b;text-transform:uppercase;letter-spacing:0.5px;\">Phone</span></td>'\n  + '<td style=\"padding:12px 16px;border-bottom:1px solid #e6e6e6;\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:15px;font-weight:bold;color:#C98A1A;\">' + d.phone + '</span></td></tr>'\n  + '<tr><td style=\"background-color:#f7f7f7;padding:12px 16px;width:120px;border-bottom:1px solid #e6e6e6;\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:bold;color:#6b6b6b;text-transform:uppercase;letter-spacing:0.5px;\">Email</span></td>'\n  + '<td style=\"padding:12px 16px;border-bottom:1px solid #e6e6e6;\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:14px;color:#C98A1A;\">' + (d.email || 'Not provided') + '</span></td></tr>'\n  + '<tr><td style=\"background-color:#f7f7f7;padding:12px 16px;width:120px' + (referralRow ? ';border-bottom:1px solid #e6e6e6;' : '') + '\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:bold;color:#6b6b6b;text-transform:uppercase;letter-spacing:0.5px;\">Location</span></td>'\n  + '<td style=\"padding:12px 16px' + (referralRow ? ';border-bottom:1px solid #e6e6e6;' : '') + '\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:14px;color:#222222;\">' + (d.location || 'Not provided') + '</span></td></tr>'\n  + referralRow\n  + '</table></td></tr>'\n  // Request summary\n  + '<tr><td style=\"padding:24px 32px 0 32px;\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;color:#9a9a9a;letter-spacing:1.2px;text-transform:uppercase;\">Request Summary</span></td></tr>'\n  + '<tr><td style=\"padding:12px 32px 0 32px;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr>'\n  + '<td style=\"background-color:#f7f7f7;border-left:4px solid ' + urgencyColor + ';padding:16px 20px;border-radius:0 4px 4px 0;\">'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:14px;color:#333333;line-height:1.6;\">' + d.leadSummary + '</span></td></tr></table></td></tr>'\n  // Assignment + SLA cards\n  + '<tr><td style=\"padding:24px 32px 0 32px;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr>'\n  + '<td style=\"width:50%;padding-right:8px;\"><table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"background-color:#222222;border-radius:6px;\"><tr><td style=\"padding:16px 18px;\">'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:bold;color:#9a9a9a;letter-spacing:1px;text-transform:uppercase;display:block;\">Assigned To</span>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:16px;font-weight:bold;color:#ffffff;display:block;margin-top:4px;\">' + d.assignedTo + '</span>'\n  + '</td></tr></table></td>'\n  + '<td style=\"width:50%;padding-left:8px;\"><table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"background-color:' + urgencyColor + ';border-radius:6px;\"><tr><td style=\"padding:16px 18px;\">'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:bold;color:rgba(255,255,255,0.75);letter-spacing:1px;text-transform:uppercase;display:block;\">Response SLA</span>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:16px;font-weight:bold;color:#ffffff;display:block;margin-top:4px;\">' + slaTime + '</span>'\n  + '</td></tr></table></td>'\n  + '</tr></table></td></tr>'\n  // CTA\n  + '<tr><td style=\"padding:28px 32px 32px 32px;text-align:center;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin:0 auto;\"><tr>'\n  + '<td style=\"background-color:#C98A1A;border-radius:6px;\">'\n  + '<a href=\"https://airtable.com/APP_ID/TABLE_ID/VIEW_ID\" style=\"display:inline-block;font-family:Arial,Helvetica,sans-serif;font-size:14px;font-weight:bold;color:#ffffff;text-decoration:none;padding:14px 32px;\">Open New Leads &rarr;</a>'\n  + '</td></tr></table></td></tr>'\n  // Footer\n  + '<tr><td style=\"background-color:#f7f7f7;padding:20px 32px;border-radius:0 0 6px 6px;\">'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#6b6b6b;\">Client Home Services &bull; [REGION] &bull; (555) 000-0000</span><br>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;color:#9a9a9a;\">This is an internal system alert. Do not reply to this email.</span>'\n  + '</td></tr>'\n  + '</table></td></tr></table></body></html>';\n\n// Customer confirmation - emergency vs standard response block\nconst responseBlock = d.urgency === 'Emergency'\n  ? '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"background-color:#FEF2F2;border:1px solid #FECACA;border-left:4px solid #DC2626;border-radius:0 6px 6px 0;\"><tr><td style=\"padding:18px 20px;\">'\n    + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;color:#DC2626;letter-spacing:1.2px;text-transform:uppercase;display:block;margin-bottom:4px;\">Emergency Response</span>'\n    + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:15px;font-weight:bold;color:#222222;display:block;\">A technician will contact you within 30 minutes.</span>'\n    + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:13px;color:#6b6b6b;display:block;margin-top:4px;\">For faster service, call us now: <a href=\"tel:+14695252254\" style=\"color:#DC2626;font-weight:bold;text-decoration:none;\">(555) 000-0000</a></span>'\n    + '</td></tr></table>'\n  : '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"background-color:#FFFBEB;border:1px solid #FDE68A;border-left:4px solid #C98A1A;border-radius:0 6px 6px 0;\"><tr><td style=\"padding:18px 20px;\">'\n    + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;color:#C98A1A;letter-spacing:1.2px;text-transform:uppercase;display:block;margin-bottom:4px;\">What Happens Next</span>'\n    + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:15px;font-weight:bold;color:#222222;display:block;\">We&rsquo;ll be in touch within 2 hours to schedule your assessment.</span>'\n    + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:13px;color:#6b6b6b;display:block;margin-top:4px;\">Need to reach us sooner? Call: <a href=\"tel:+14695252254\" style=\"color:#C98A1A;font-weight:bold;text-decoration:none;\">(555) 000-0000</a></span>'\n    + '</td></tr></table>';\n\nconst customerConfirmationHtml = '<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\"></head>'\n  + '<body style=\"margin:0;padding:0;background-color:#f0f0f0;font-family:Arial,Helvetica,sans-serif;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"background-color:#f0f0f0;\"><tr><td align=\"center\" style=\"padding:24px 16px;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"max-width:600px;width:100%;background-color:#ffffff;border-radius:6px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.10);\">'\n  // Header\n  + '<tr><td style=\"background-color:#222222;padding:32px 32px 24px 32px;text-align:center;\">'\n  + '<div style=\"margin-bottom:6px;\"><span style=\"font-family:Georgia,serif;font-size:28px;font-weight:bold;color:#ffffff;\">ACME</span>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:28px;color:#C98A1A;\"> Home Services</span></div>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#9a9a9a;letter-spacing:2px;text-transform:uppercase;\">Expect Greatness</span>'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin:20px auto 0 auto;width:60px;\"><tr><td style=\"background-color:#C98A1A;height:3px;border-radius:2px;font-size:0;line-height:0;\">&nbsp;</td></tr></table>'\n  + '</td></tr>'\n  // Hero confirmation block\n  + '<tr><td style=\"background-color:#222222;padding:24px 32px 36px 32px;text-align:center;border-bottom:4px solid #C98A1A;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin:0 auto 20px auto;\"><tr>'\n  + '<td style=\"width:60px;height:60px;background-color:#C98A1A;border-radius:50%;text-align:center;vertical-align:middle;\">'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:28px;color:#ffffff;line-height:60px;display:block;\">&#10003;</span>'\n  + '</td></tr></table>'\n  + '<h1 style=\"margin:0 0 10px 0;font-family:Georgia,serif;font-size:26px;font-weight:bold;color:#ffffff;line-height:1.2;\">Got it, ' + d.firstName + '.</h1>'\n  + '<p style=\"margin:0;font-family:Arial,Helvetica,sans-serif;font-size:15px;color:rgba(255,255,255,0.75);line-height:1.5;\">Your request has been received and our team is already on it.</p>'\n  + '</td></tr>'\n  // Response block\n  + '<tr><td style=\"padding:28px 32px 0 32px;\">' + responseBlock + '</td></tr>'\n  // Request summary\n  + '<tr><td style=\"padding:24px 32px 0 32px;\"><span style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;color:#9a9a9a;letter-spacing:1.2px;text-transform:uppercase;\">Your Request</span></td></tr>'\n  + '<tr><td style=\"padding:12px 32px 0 32px;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr>'\n  + '<td style=\"background-color:#f7f7f7;border-left:4px solid #222222;padding:16px 20px;border-radius:0 4px 4px 0;\">'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:14px;color:#333333;line-height:1.6;\">' + d.leadSummary + '</span></td></tr></table></td></tr>'\n  // 24/7 callout\n  + '<tr><td style=\"padding:28px 32px 0 32px;\">'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"background-color:#222222;border-radius:6px;\"><tr><td style=\"padding:24px;text-align:center;\">'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;color:#C98A1A;letter-spacing:2px;text-transform:uppercase;display:block;margin-bottom:8px;\">24/7 Emergency Response</span>'\n  + '<span style=\"font-family:Georgia,serif;font-size:18px;color:#ffffff;display:block;margin-bottom:14px;\">We never stop, because disasters don&rsquo;t keep business hours.</span>'\n  + '<table role=\"presentation\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin:0 auto;\"><tr>'\n  + '<td style=\"background-color:#C98A1A;border-radius:6px;\">'\n  + '<a href=\"tel:+14695252254\" style=\"display:inline-block;font-family:Arial,Helvetica,sans-serif;font-size:16px;font-weight:bold;color:#ffffff;text-decoration:none;padding:13px 28px;\">(555) 000-0000</a>'\n  + '</td></tr></table>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;color:#9a9a9a;display:block;margin-top:10px;\">IICRC Certified &bull; Licensed &amp; Insured &bull; [REGION]</span>'\n  + '</td></tr></table></td></tr>'\n  // Footer\n  + '<tr><td style=\"background-color:#f7f7f7;padding:20px 32px;border-radius:0 0 6px 6px;text-align:center;\">'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:13px;font-weight:bold;color:#222222;display:block;margin-bottom:4px;\">Client Home Services</span>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#6b6b6b;display:block;\">[CITY]</span>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#6b6b6b;display:block;margin-top:2px;\">'\n  + '<a href=\"https://www.example.com\" style=\"color:#C98A1A;text-decoration:none;\">example.com</a> &bull; '\n  + '<a href=\"mailto:contact@example.com\" style=\"color:#C98A1A;text-decoration:none;\">contact@example.com</a></span>'\n  + '<span style=\"font-family:Arial,Helvetica,sans-serif;font-size:11px;color:#9a9a9a;display:block;margin-top:12px;\">You received this email because you submitted a service request on our website.</span>'\n  + '</td></tr>'\n  + '</table></td></tr></table></body></html>';\n\nreturn [{ json: {\n  ...d,\n  leadRecordId: created.id,\n  leadCreatedTime: created.createdTime || new Date().toISOString(),\n  telPhone,\n  internalAlertHtml,\n  customerConfirmationHtml\n}}];"
      }
    },
    {
      "id": "n10",
      "name": "Update Assignee",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        2080,
        280
      ],
      "parameters": {
        "method": "PATCH",
        "url": "={{ 'https://api.airtable.com/v0/APP_ID/tbltAUtUpmM2ej7U2/' + $json.memberId }}",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer YOUR_API_KEY"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "json",
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ fields: { 'Last Assigned At': $json.assignmentTimestamp } }) }}",
        "options": {}
      }
    },
    {
      "id": "n11",
      "name": "Log Activity",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        2080,
        440
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.airtable.com/v0/APP_ID/tblHKpCW58mLxWMvW",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer YOUR_API_KEY"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "json",
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ fields: { 'Event Summary': $json.customerName + ' - Lead Created & Assigned', 'Timestamp': $json.assignmentTimestamp, 'Lead Name': $json.customerName, 'Event Type': 'Lead Created', 'Performed By': 'System', 'Channel': 'System', 'Details': 'Website form submission. Urgency: ' + $json.urgency + '. Assigned to: ' + $json.assignedTo + '. SLA due: ' + $json.slaDueAt, 'Lead Record ID': $json.leadRecordId } }) }}",
        "options": {}
      }
    },
    {
      "id": "n12",
      "name": "Send Internal Alert",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        2080,
        600
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.resend.com/emails",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer re_HYT27bvk_NkJLfMV1X38TTQm2qZpjXUwu"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "json",
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ from: 'Client Leads <noreply@example.com>', to: 'contact@example.com', subject: ($json.urgency === 'Emergency' ? '[EMERGENCY] ' : $json.urgency === 'Urgent' ? '[URGENT] ' : '[New Lead] ') + $json.customerName + ' \u2014 ' + $json.phone, html: $json.internalAlertHtml }) }}",
        "options": {}
      }
    },
    {
      "id": "n13",
      "name": "Send Customer Confirmation",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        2080,
        760
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.resend.com/emails",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer re_HYT27bvk_NkJLfMV1X38TTQm2qZpjXUwu"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "json",
        "specifyBody": "json",
        "jsonBody": "={{ $json.email ? JSON.stringify({ from: 'Client Home Services <noreply@example.com>', to: $json.email, subject: 'We received your request \u2014 Client Home Services', html: $json.customerConfirmationHtml }) : JSON.stringify({ from: 'Client Home Services <noreply@example.com>', to: 'noop@example.com', subject: 'noop', text: 'noop' }) }}",
        "options": {}
      }
    },
    {
      "id": "n14",
      "name": "Send Telegram Alert",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        2080,
        920
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.telegram.org/botYOUR_TELEGRAM_BOT_TOKEN/sendMessage",
        "authentication": "none",
        "sendBody": true,
        "contentType": "json",
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ chat_id: CHAT_ID, text: ($json.formType==='referral'?'\ud83e\udd1d Trade Referral':($json.urgency==='Emergency'?'\ud83d\udea8 EMERGENCY':'\ud83d\udccb New Lead'))+' - Client Home Services\\n\\nCustomer: '+$json.customerName+'\\nPhone: '+$json.telPhone+'\\nEmail: '+($json.email||'Not provided')+'\\nLocation: <a href=\"https://maps.google.com/?q='+encodeURIComponent($json.location||'')+'\">'+($json.location||'Not provided')+'</a>'+'\\nUrgency: '+$json.urgency+($json.formType==='referral'&&$json.referredBy?'\\nReferred by: '+$json.referredBy+($json.referredByCompany?' ('+$json.referredByCompany+')':'')+($json.referredByTrade?', '+$json.referredByTrade:''):'')+' \\n\\n'+$json.leadSummary+'\\n\\n<a href=\"https://airtable.com/APP_ID/TABLE_ID/VIEW_ID\">View New Leads</a>', parse_mode: 'HTML' }) }}",
        "options": {}
      }
    },
    {
      "id": "n16",
      "name": "Prep Duplicate Alert",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1300,
        100
      ],
      "parameters": {
        "jsCode": "const lead = $('Normalize Lead').first().json;\nconst digits = (lead.phone || '').replace(/\\D/g, '');\nconst telPhone = digits.length === 10 ? '+1' + digits : '+' + digits;\n\nconst urgencyColor = lead.urgency === 'Emergency' ? '#dc2626' : '#d97706';\nconst urgencyLabel = lead.urgency === 'Emergency' ? '\ud83d\udea8 EMERGENCY' : '\ud83d\udccb NEW LEAD';\n\nconst duplicateAlertHtml = '<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\"></head><body style=\"margin:0;padding:0;background:#f1f5f9;font-family:Arial,Helvetica,sans-serif;\">'\n  + '<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#f1f5f9;\"><tr><td align=\"center\" style=\"padding:20px 10px;\">'\n  + '<table width=\"600\" cellpadding=\"0\" cellspacing=\"0\" style=\"max-width:600px;width:100%;\">'\n  + '<tr><td style=\"background:' + urgencyColor + ';border-radius:8px 8px 0 0;padding:24px;text-align:center;\">'\n  + '<h1 style=\"color:white;margin:0;font-size:20px;font-weight:700;\">' + urgencyLabel + ' &mdash; DUPLICATE LEAD</h1>'\n  + '<p style=\"color:rgba(255,255,255,0.85);margin:6px 0 0;font-size:12px;letter-spacing:1px;\">ACME SERVICES &bull; [REGION] RESTORATION</p></td></tr>'\n  + '<tr><td style=\"background:#fffbeb;border:2px solid #fcd34d;padding:14px 24px;text-align:center;\">'\n  + '<p style=\"margin:0;color:#92400e;font-size:13px;font-weight:700;\">\u26a0\ufe0f This phone or email already exists in Airtable. Verify before responding.</p></td></tr>'\n  + '<tr><td style=\"background:white;padding:24px;\">'\n  + '<h2 style=\"margin:0 0 16px;color:#1e293b;font-size:18px;\">' + lead.customerName + '</h2>'\n  + '<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">'\n  + '<tr><td style=\"padding:8px 0;border-bottom:1px solid #e2e8f0;width:35%;color:#64748b;font-size:13px;\">Phone</td><td style=\"padding:8px 0;border-bottom:1px solid #e2e8f0;color:#1e293b;font-size:14px;font-weight:600;\">' + lead.phone + '</td></tr>'\n  + '<tr><td style=\"padding:8px 0;border-bottom:1px solid #e2e8f0;color:#64748b;font-size:13px;\">Email</td><td style=\"padding:8px 0;border-bottom:1px solid #e2e8f0;color:#1e293b;font-size:14px;\">' + (lead.email || 'Not provided') + '</td></tr>'\n  + '<tr><td style=\"padding:8px 0;border-bottom:1px solid #e2e8f0;color:#64748b;font-size:13px;\">Location</td><td style=\"padding:8px 0;border-bottom:1px solid #e2e8f0;color:#1e293b;font-size:14px;\">' + (lead.location || 'Not provided') + '</td></tr>'\n  + '<tr><td style=\"padding:8px 0;border-bottom:1px solid #e2e8f0;color:#64748b;font-size:13px;\">Urgency</td><td style=\"padding:8px 0;border-bottom:1px solid #e2e8f0;color:#1e293b;font-size:14px;\">' + lead.urgency + '</td></tr>'\n  + '</table>'\n  + '<div style=\"background:#f8fafc;border-left:3px solid #d97706;border-radius:0 4px 4px 0;padding:12px 16px;margin-top:16px;\">'\n  + '<p style=\"margin:0;color:#475569;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;\">Request</p>'\n  + '<p style=\"margin:6px 0 0;color:#1e293b;font-size:14px;line-height:1.5;\">' + lead.leadSummary + '</p></div></td></tr>'\n  + '<tr><td style=\"background:white;padding:20px 24px;text-align:center;\">'\n  + '<a href=\"https://airtable.com/APP_ID\" style=\"background:#1e40af;color:white;padding:12px 28px;text-decoration:none;border-radius:6px;font-size:14px;font-weight:600;display:inline-block;\">Open Lead Board</a></td></tr>'\n  + '<tr><td style=\"padding:16px;text-align:center;\"><p style=\"color:#94a3b8;font-size:11px;margin:0;\">Client Home Services &bull; [CITY] &bull; example.com</p></td></tr>'\n  + '</table></td></tr></table></body></html>';\n\nreturn [{ json: { ...lead, isDuplicate: true, telPhone, duplicateAlertHtml } }];"
      }
    },
    {
      "id": "n17",
      "name": "Send Duplicate Telegram",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        1560,
        0
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.telegram.org/botYOUR_TELEGRAM_BOT_TOKEN/sendMessage",
        "authentication": "none",
        "sendBody": true,
        "contentType": "json",
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ chat_id: CHAT_ID, text: '\u26a0\ufe0f DUPLICATE LEAD - Client Home Services\\n\\nCustomer: '+$json.customerName+'\\nPhone: '+$json.telPhone+'\\nEmail: '+($json.email||'Not provided')+'\\nLocation: <a href=\"https://maps.google.com/?q='+encodeURIComponent($json.location||'')+'\">'+($json.location||'Not provided')+'</a>'+'\\nUrgency: '+$json.urgency+'\\n\\n'+$json.leadSummary+'\\n\\nAlready exists in Airtable \u2014 verify before responding.\\n<a href=\"https://airtable.com/APP_ID/TABLE_ID/VIEW_ID_2\">View Lost/Duplicate</a>', parse_mode: 'HTML' }) }}",
        "options": {}
      }
    },
    {
      "id": "n18",
      "name": "Send Duplicate Email",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        1560,
        200
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.resend.com/emails",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer re_HYT27bvk_NkJLfMV1X38TTQm2qZpjXUwu"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "json",
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ from: 'Client Leads <noreply@example.com>', to: 'contact@example.com', subject: '[DUPLICATE] ' + $json.customerName + ' \u2014 ' + $json.phone, html: $json.duplicateAlertHtml }) }}",
        "options": {}
      }
    }
  ],
  "connections": {
    "Webhook": {
      "main": [
        [
          {
            "node": "Normalize Lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalize Lead": {
      "main": [
        [
          {
            "node": "Check Duplicate",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Duplicate": {
      "main": [
        [
          {
            "node": "Is Duplicate?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is Duplicate?": {
      "main": [
        [
          {
            "node": "Flag Duplicate",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Get Team Members",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Team Members": {
      "main": [
        [
          {
            "node": "Assign and Build Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Assign and Build Payload": {
      "main": [
        [
          {
            "node": "Create Lead Record",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Lead Record": {
      "main": [
        [
          {
            "node": "Prep Notifications",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prep Notifications": {
      "main": [
        [
          {
            "node": "Update Assignee",
            "type": "main",
            "index": 0
          },
          {
            "node": "Log Activity",
            "type": "main",
            "index": 0
          },
          {
            "node": "Send Internal Alert",
            "type": "main",
            "index": 0
          },
          {
            "node": "Send Customer Confirmation",
            "type": "main",
            "index": 0
          },
          {
            "node": "Send Telegram Alert",
            "type": "0",
            "index": 0
          }
        ]
      ]
    },
    "Flag Duplicate": {
      "main": [
        [
          {
            "node": "Prep Duplicate Alert",
            "type": "0",
            "index": 0
          }
        ]
      ]
    },
    "Prep Duplicate Alert": {
      "main": [
        [
          {
            "node": "Send Duplicate Telegram",
            "type": "0",
            "index": 0
          },
          {
            "node": "Send Duplicate Email",
            "type": "0",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "America/Chicago",
    "saveDataErrorExecution": "all",
    "saveDataSuccessExecution": "all",
    "callerPolicy": "workflowsFromSameOwner",
    "availableInMCP": false
  },
  "staticData": null,
  "meta": null,
  "pinData": null,
  "activeVersionId": null,
  "versionCounter": 46,
  "triggerCount": 1,
  "shared": [
    {
      "updatedAt": "2026-04-15T19:01:39.436Z",
      "createdAt": "2026-04-15T19:01:39.436Z",
      "role": "workflow:owner",
      "workflowId": "11OnkE1OXXKN7h4M",
      "projectId": "6RTJ3ead58ncl4Hy",
      "project": {
        "updatedAt": "2025-01-23T18:31:39.020Z",
        "createdAt": "2025-01-23T05:37:52.794Z",
        "id": "6RTJ3ead58ncl4Hy",
        "name": "Edward Chalupa <echalupa@me.com>",
        "type": "personal",
        "icon": null,
        "description": null,
        "creatorId": "e67b6366-69ec-43f2-91cb-2e5098f53def"
      }
    }
  ],
  "tags": [],
  "activeVersion": null
}