🎯 Lead Generation
🎯 Mục tiêu bài học
Sau bài học này, bạn sẽ:
✅ Xây dựng form submission handler với data validation
✅ Implement lead enrichment và lead scoring system
✅ Tạo CRM integration và email nurture sequences
✅ Thiết kế hot lead alerts và sales handoff workflow
Convert visitors into customers automatically. Bài này hướng dẫn automate entire lead generation funnel từ capture đến conversion.
🔍 Lead Generation Automation Overview
The Lead Funnel:
Lead Generation Funnel
Checkpoint
Lead funnel bao gồm mấy giai đoạn chính?
⚡ Workflow 1: Form Submission Handler
Process Lead Forms:
Lead Form Handler
Form Data Processing:
1const formData = $input.item.json;23// Clean and validate4function cleanData(data) {5 return {6 email: data.email?.toLowerCase().trim(),7 firstName: data.firstName?.trim() || data.name?.split(' ')[0]?.trim(),8 lastName: data.lastName?.trim() || data.name?.split(' ').slice(1).join(' ')?.trim(),9 company: data.company?.trim(),10 phone: data.phone?.replace(/[^\d+]/g, ''),11 jobTitle: data.jobTitle?.trim(),12 13 // Form context14 source: data.source || 'website',15 formId: data.formId,16 landingPage: data.pageUrl,17 utmSource: data.utm_source,18 utmMedium: data.utm_medium,19 utmCampaign: data.utm_campaign,20 21 // Timestamps22 submittedAt: new Date().toISOString(),23 ip: data.ip,24 userAgent: data.userAgent25 };26}2728// Validate required fields29function validate(data) {30 const errors = [];31 32 if (!data.email || !data.email.includes('@')) {33 errors.push('Invalid email');34 }35 36 if (!data.firstName) {37 errors.push('First name required');38 }39 40 return {41 isValid: errors.length === 0,42 errors43 };44}4546const cleaned = cleanData(formData);47const validation = validate(cleaned);4849return {50 ...cleaned,51 ...validation,52 processingId: `lead_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`53};Checkpoint
Form submission handler thực hiện validate và clean data như thế nào?
🔧 Workflow 2: Lead Enrichment
Enrich Lead Data:
Lead Enrichment
Enrichment Processing:
1const lead = $input.item.json;23// Combine enrichment data from various sources4const enrichedData = {5 // From Clearbit or similar6 company: {7 name: lead.clearbit?.company?.name || lead.company,8 domain: lead.clearbit?.company?.domain,9 industry: lead.clearbit?.company?.category?.industry,10 employeeCount: lead.clearbit?.company?.metrics?.employees,11 annualRevenue: lead.clearbit?.company?.metrics?.annualRevenue,12 founded: lead.clearbit?.company?.foundedYear,13 location: {14 city: lead.clearbit?.company?.geo?.city,15 country: lead.clearbit?.company?.geo?.country16 },17 technologies: lead.clearbit?.company?.tech || [],18 linkedInUrl: lead.clearbit?.company?.linkedin?.handle 19 ? `https://linkedin.com/company/${lead.clearbit.company.linkedin.handle}`20 : null21 },22 23 // Person data24 person: {25 fullName: lead.clearbit?.person?.name?.fullName || `${lead.firstName} ${lead.lastName}`,26 title: lead.clearbit?.person?.employment?.title || lead.jobTitle,27 seniority: lead.clearbit?.person?.employment?.seniority,28 linkedInUrl: lead.clearbit?.person?.linkedin?.handle29 ? `https://linkedin.com/in/${lead.clearbit.person.linkedin.handle}`30 : null,31 twitterUrl: lead.clearbit?.person?.twitter?.handle32 ? `https://twitter.com/${lead.clearbit.person.twitter.handle}`33 : null,34 bio: lead.clearbit?.person?.bio35 },36 37 // Enrichment metadata38 enrichedAt: new Date().toISOString(),39 enrichmentSources: ['clearbit', 'linkedin'].filter(s => lead[s])40};4142return {43 leadId: lead.id,44 original: lead,45 enriched: enrichedData46};Checkpoint
Lead enrichment thu thập data từ những sources nào?
🏗️ Workflow 3: Lead Scoring
Score and Qualify Leads:
Lead Scoring Engine
Lead Scoring Logic:
1const lead = $input.item.json;23// FIT SCORING (max 50 points)4function calculateFitScore(lead) {5 let score = 0;6 const company = lead.enriched?.company || {};7 const person = lead.enriched?.person || {};8 9 // Company size (max 15 points)10 const employees = company.employeeCount || 0;11 if (employees >= 1000) score += 15;12 else if (employees >= 200) score += 12;13 else if (employees >= 50) score += 10;14 else if (employees >= 10) score += 5;15 else score += 2;16 17 // Industry match (max 15 points)18 const targetIndustries = ['technology', 'software', 'saas', 'finance', 'healthcare'];19 const industry = (company.industry || '').toLowerCase();20 if (targetIndustries.some(t => industry.includes(t))) score += 15;21 else if (company.industry) score += 5;22 23 // Job title/seniority (max 10 points)24 const title = (person.title || lead.jobTitle || '').toLowerCase();25 const seniorTitles = ['ceo', 'cto', 'cfo', 'vp', 'director', 'head', 'chief'];26 const midTitles = ['manager', 'lead', 'senior'];27 28 if (seniorTitles.some(t => title.includes(t))) score += 10;29 else if (midTitles.some(t => title.includes(t))) score += 7;30 else if (title) score += 3;31 32 // Geography (max 10 points)33 const targetCountries = ['united states', 'usa', 'uk', 'australia', 'canada', 'germany'];34 const country = (company.location?.country || '').toLowerCase();35 if (targetCountries.some(c => country.includes(c))) score += 10;36 else if (country) score += 5;37 38 return score;39}4041// ENGAGEMENT SCORING (max 50 points)42function calculateEngagementScore(lead) {43 let score = 0;44 const activity = lead.activity || {};45 46 // Page views (max 10 points)47 const pageViews = activity.pageViews || 0;48 score += Math.min(pageViews * 0.5, 10);49 50 // Email engagement (max 15 points)51 const emailOpens = activity.emailOpens || 0;52 const emailClicks = activity.emailClicks || 0;53 score += Math.min(emailOpens, 5);54 score += Math.min(emailClicks * 2, 10);55 56 // Content downloads (max 15 points)57 const downloads = activity.downloads || 0;58 score += Math.min(downloads * 5, 15);59 60 // High-intent actions (max 10 points)61 if (activity.demoRequested) score += 10;62 else if (activity.pricingViewed) score += 5;63 else if (activity.contactViewed) score += 3;64 65 return score;66}6768const fitScore = calculateFitScore(lead);69const engagementScore = calculateEngagementScore(lead);70const totalScore = fitScore + engagementScore;7172// Determine status73let status, priority;74if (totalScore >= 80) {75 status = 'hot';76 priority = 'high';77} else if (totalScore >= 50) {78 status = 'warm';79 priority = 'medium';80} else {81 status = 'cold';82 priority = 'low';83}8485return {86 leadId: lead.id,87 scoring: {88 fit: fitScore,89 engagement: engagementScore,90 total: totalScore,91 status,92 priority,93 calculatedAt: new Date().toISOString()94 },95 action: status === 'hot' ? 'alert_sales' : 'continue_nurture'96};Checkpoint
Lead scoring system tính total score từ mấy thành phần?
📊 Workflow 4: CRM Integration
Sync to CRM:
CRM Sync
CRM Field Mapping:
1const lead = $input.item.json;23// Map to HubSpot format (adapt for Salesforce, Pipedrive, etc.)4const hubspotContact = {5 properties: {6 // Basic info7 email: lead.email,8 firstname: lead.firstName,9 lastname: lead.lastName,10 phone: lead.phone,11 jobtitle: lead.enriched?.person?.title || lead.jobTitle,12 company: lead.enriched?.company?.name || lead.company,13 14 // Company details15 company_size: lead.enriched?.company?.employeeCount?.toString(),16 industry: lead.enriched?.company?.industry,17 website: lead.enriched?.company?.domain 18 ? `https://${lead.enriched.company.domain}` 19 : null,20 21 // Lead source22 hs_lead_status: lead.scoring?.status?.toUpperCase(),23 leadsource: lead.source,24 original_source: lead.utmSource,25 original_campaign: lead.utmCampaign,26 27 // Scoring28 lead_score: lead.scoring?.total,29 lead_fit_score: lead.scoring?.fit,30 lead_engagement_score: lead.scoring?.engagement,31 32 // Social33 linkedin_profile: lead.enriched?.person?.linkedInUrl,34 twitter_profile: lead.enriched?.person?.twitterUrl,35 36 // Metadata37 first_conversion_date: lead.submittedAt,38 landing_page_url: lead.landingPage39 }40};4142// Create task for sales follow-up43const task = {44 subject: `Follow up with ${lead.firstName} ${lead.lastName}`,45 taskType: 'TODO',46 priority: lead.scoring?.priority === 'high' ? 'HIGH' : 'MEDIUM',47 status: 'NOT_STARTED',48 notes: `49Lead Score: ${lead.scoring?.total}50Company: ${lead.company}51Source: ${lead.source}52 `.trim()53};5455return {56 contact: hubspotContact,57 task: task,58 company: lead.enriched?.company?.name ? {59 properties: {60 name: lead.enriched.company.name,61 domain: lead.enriched.company.domain,62 industry: lead.enriched.company.industry,63 numberofemployees: lead.enriched.company.employeeCount,64 annualrevenue: lead.enriched.company.annualRevenue65 }66 } : null67};Checkpoint
CRM sync map fields tới HubSpot format bao gồm những gì?
💡 Workflow 5: Email Nurture Sequence
Automated Drip Campaigns:
Lead Nurture Sequence
Nurture Email Generator:
1const lead = $input.item.json;2const sequenceStep = lead.sequenceStep || 1;34const emailSequence = {5 1: {6 subject: `Welcome ${lead.firstName}! Here's what's next`,7 template: 'welcome',8 delay: 09 },10 2: {11 subject: '3 ways to [solve problem]',12 template: 'value_content_1',13 delay: 3 * 24 * 60 // 3 days in minutes14 },15 3: {16 subject: 'How [similar company] achieved [result]',17 template: 'case_study',18 delay: 6 * 24 * 6019 },20 4: {21 subject: 'See it in action? Quick 15-min demo',22 template: 'demo_cta',23 delay: 10 * 24 * 6024 },25 5: {26 subject: "Last chance: Your exclusive resource",27 template: 'final_push',28 delay: 14 * 24 * 6029 },30 6: {31 subject: "Should I stop sending these?",32 template: 'breakup',33 delay: 21 * 24 * 6034 }35};3637const currentEmail = emailSequence[sequenceStep];3839// Personalization tokens40const personalization = {41 firstName: lead.firstName,42 company: lead.company || 'your company',43 industry: lead.enriched?.company?.industry || 'your industry',44 painPoint: determinePainPoint(lead),45 relevantCaseStudy: selectCaseStudy(lead.enriched?.company?.industry)46};4748function determinePainPoint(lead) {49 // Logic based on lead source or behavior50 const source = lead.source?.toLowerCase() || '';51 if (source.includes('productivity')) return 'saving time on repetitive tasks';52 if (source.includes('automation')) return 'automating manual workflows';53 if (source.includes('integration')) return 'connecting your tools';54 return 'streamlining your operations';55}5657function selectCaseStudy(industry) {58 const caseStudies = {59 'technology': 'TechCorp',60 'finance': 'FinanceInc',61 'healthcare': 'HealthOrg',62 'default': 'a company like yours'63 };64 return caseStudies[industry?.toLowerCase()] || caseStudies.default;65}6667return {68 leadId: lead.id,69 email: currentEmail,70 personalization,71 nextStep: sequenceStep + 1,72 sendAt: new Date(Date.now() + currentEmail.delay * 60 * 1000).toISOString()73};Checkpoint
Email nurture sequence bao gồm bao nhiêu emails?
🌟 Workflow 6: Sales Handoff
Hot Lead Alert:
Sales Alert & Handoff
Sales Alert Message:
1const lead = $input.item.json;23// Round-robin assignment4const salesReps = [5 { name: 'Alice', slackId: 'U123', territories: ['us', 'canada'] },6 { name: 'Bob', slackId: 'U456', territories: ['uk', 'europe'] },7 { name: 'Charlie', slackId: 'U789', territories: ['asia', 'default'] }8];910function assignRep(lead) {11 const country = lead.enriched?.company?.location?.country?.toLowerCase() || 'default';12 13 for (const rep of salesReps) {14 if (rep.territories.some(t => country.includes(t) || t === 'default')) {15 return rep;16 }17 }18 return salesReps[0];19}2021const assignedRep = assignRep(lead);2223const slackMessage = {24 channel: '#sales-alerts',25 text: `🔥 Hot Lead Alert!`,26 blocks: [27 {28 type: 'header',29 text: { type: 'plain_text', text: '🔥 Hot Lead Alert!' }30 },31 {32 type: 'section',33 fields: [34 { type: 'mrkdwn', text: `*Name:*\n${lead.firstName} ${lead.lastName}` },35 { type: 'mrkdwn', text: `*Company:*\n${lead.company}` },36 { type: 'mrkdwn', text: `*Title:*\n${lead.jobTitle || 'Unknown'}` },37 { type: 'mrkdwn', text: `*Lead Score:*\n${lead.scoring?.total}/100` }38 ]39 },40 {41 type: 'section',42 text: {43 type: 'mrkdwn',44 text: `*Score Breakdown:*\n• Fit: ${lead.scoring?.fit}/50\n• Engagement: ${lead.scoring?.engagement}/50`45 }46 },47 {48 type: 'section',49 text: {50 type: 'mrkdwn',51 text: `*Recent Activity:*\n${formatRecentActivity(lead.activity)}`52 }53 },54 {55 type: 'section',56 text: {57 type: 'mrkdwn',58 text: `*Assigned to:* <@${assignedRep.slackId}>`59 }60 },61 {62 type: 'actions',63 elements: [64 {65 type: 'button',66 text: { type: 'plain_text', text: '📞 Call Now' },67 url: `tel:${lead.phone}`,68 style: 'primary'69 },70 {71 type: 'button',72 text: { type: 'plain_text', text: '✉️ Email' },73 url: `mailto:${lead.email}`74 },75 {76 type: 'button',77 text: { type: 'plain_text', text: '📊 View in CRM' },78 url: `https://crm.example.com/leads/${lead.id}`79 }80 ]81 }82 ]83};8485function formatRecentActivity(activity) {86 if (!activity) return 'No recent activity';87 88 const items = [];89 if (activity.demoRequested) items.push('✅ Requested demo');90 if (activity.pricingViewed) items.push('👀 Viewed pricing page');91 if (activity.downloads?.length) items.push(`📥 Downloaded ${activity.downloads.length} resource(s)`);92 if (activity.emailClicks) items.push(`🔗 Clicked ${activity.emailClicks} email link(s)`);93 94 return items.length > 0 ? items.join('\n') : 'Browse only';95}9697return {98 slackMessage,99 assignedRep,100 followUpDeadline: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()101};Checkpoint
Sales handoff assign rep theo round-robin hay territory?
📈 Lead Generation Metrics
Funnel Metrics:
- Visitors → Leads (Conversion Rate)
- Leads → MQLs (Marketing Qualified)
- MQLs → SQLs (Sales Qualified)
- SQLs → Opportunities
- Opportunities → Customers
Per-Lead Metrics:
- Cost per Lead (CPL)
- Lead Score accuracy
- Time to qualification
- Nurture engagement rate
- Sales acceptance rate
Checkpoint
Những funnel metrics nào cần track?
📋 Best Practices
DO:
- ✅ Respond to leads quickly (under 5 min ideal)
- ✅ Personalize based on lead data
- ✅ Score leads consistently
- ✅ Clean and validate data
- ✅ Get consent (GDPR/privacy)
DON'T:
- ❌ Spam or over-email
- ❌ Ignore lead source in scoring
- ❌ Delay sales handoff for hot leads
- ❌ Forget to track conversions
- ❌ Buy email lists
Checkpoint
Thời gian response lý tưởng cho leads là bao lâu?
📝 Bài Tập Thực Hành
Build your lead machine:
- Create form submission workflow
- Implement lead scoring system
- Set up CRM sync (HubSpot/Airtable)
- Build 5-email nurture sequence
- Configure hot lead alerts
Start converting! 🎯
Checkpoint
Bạn đã hoàn thành những challenges nào trong bài tập?
🧠 Key Takeaways
- 🎯 Score intelligently - Fit + Engagement
- ⚡ Speed matters - Fast response = higher conversion
- 🔄 Nurture consistently - Stay top of mind
- 📊 Measure everything - Optimize based on data
- 🤝 Align sales & marketing - Clear handoff criteria
Checkpoint
Tại sao Speed matters - Fast response = higher conversion?
🚀 Bài tiếp theo
Complex Multi-Step Workflows — Advanced patterns combining everything you've learned.
