n8n

n8n Lead Scoring: automatizare calificare vânzări

Petru Constantin
--13 min lectura
#n8n#lead scoring#sales automation#CRM#marketing automation

Petru Constantin este fondatorul DeviDevs și a proiectat platforma multi-agent pe care rulează firma, cu guardrails impuse în cod. Exemplele de cod sunt scrise pe documentația n8n 2.47 (stable 2.47.7).

Automatizarea Lead Scoring cu n8n: Construirea de Workflow-uri Inteligente pentru Calificarea Vânzărilor

Lead scoring-ul transformă semnalele din CRM și de pe site într-un singur număr după care echipa de vânzări poate sorta. Ghidul construiește pașii de scorare, rutare, sincronizare cu CRM-ul și raportare ca Code node-uri n8n, cu ponderile și pragurile ținute în obiecte simple, ușor de ajustat.

Framework-ul de Lead Scoring

Motorul Principal de Scorare

// Code node (Run Once for All Items): lead scoring engine
// Each input item is one lead record from your CRM, form or enrichment step.
 
const WEIGHTS = { demographic: 0.30, behavioral: 0.40, engagement: 0.20, intent: 0.10 };
 
const COMPANY_SIZE = { enterprise: 100, mid_market: 80, small_business: 60, startup: 40, unknown: 20 };
const INDUSTRY = { technology: 100, finance: 95, healthcare: 90, manufacturing: 85, retail: 75, other: 50 };
const JOB_TITLE_PATTERNS = [
  { regex: /^(c-level|ceo|cto|cfo|coo|cmo)/i, score: 100 },
  { regex: /^(vp|vice president|director)/i, score: 90 },
  { regex: /^(head|senior manager|manager)/i, score: 75 },
  { regex: /^(senior|lead|principal)/i, score: 60 }
];
const LOCATION_SCORE = { tier1_markets: 100, tier2_markets: 80, tier3_markets: 60 };
const EMAIL_ENGAGEMENT = { high: 100, medium: 60, low: 30, none: 0 };
const WEBINAR = { attended_live: 100, watched_recording: 70, registered_no_show: 30, none: 0 };
const SOCIAL = { high: 100, medium: 60, low: 30, none: 0 };
const FREQUENCY = { daily: 100, weekly: 70, monthly: 40, rarely: 10 };
 
// Returns the score of the first step whose minimum the value reaches
const tier = (value, steps) => {
  for (const [min, score] of steps) {
    if (value >= min) return score;
  }
  return 0;
};
 
function determineLocationTier(country) {
  const tier1 = ['US', 'GB', 'CA', 'AU', 'DE'];
  const tier2 = ['FR', 'NL', 'SE', 'NO', 'DK', 'CH', 'JP'];
  if (tier1.includes(country)) return 'tier1_markets';
  if (tier2.includes(country)) return 'tier2_markets';
  return 'tier3_markets';
}
 
function demographicScore(lead) {
  const size = COMPANY_SIZE[lead.company_size] ?? COMPANY_SIZE.unknown;
  const industry = INDUSTRY[lead.industry] ?? INDUSTRY.other;
  const title = JOB_TITLE_PATTERNS.find(p => p.regex.test(lead.job_title || ''))?.score ?? 40;
  const location = LOCATION_SCORE[determineLocationTier(lead.country)];
  return size * 0.25 + industry * 0.25 + title * 0.30 + location * 0.20;
}
 
function behavioralScore(lead) {
  const b = lead.behavior || {};
  const pageViews = tier(b.page_views || 0, [[20, 100], [10, 80], [5, 60], [1, 40]]);
  const pricing = tier(b.pricing_page_visits || 0, [[3, 100], [2, 80], [1, 50]]);
  const downloads = tier(b.content_downloads || 0, [[5, 100], [3, 80], [1, 50]]);
  const demo = b.demo_requested ? 100 : 0;
  const email = EMAIL_ENGAGEMENT[b.email_engagement] ?? 0;
  return pageViews * 0.20 + pricing * 0.25 + downloads * 0.20 + demo * 0.25 + email * 0.10;
}
 
function engagementScore(lead) {
  const e = lead.engagement || {};
  const opens = tier(e.email_opens || 0, [[10, 100], [5, 80], [1, 50]]);
  const clicks = tier(e.email_clicks || 0, [[5, 100], [2, 70], [1, 40]]);
  const webinar = WEBINAR[e.webinar_status] ?? 0;
  const social = SOCIAL[e.social_engagement] ?? 0;
  return opens * 0.25 + clicks * 0.30 + webinar * 0.25 + social * 0.20;
}
 
function intentScore(lead) {
  const i = lead.intent || {};
  let recency = 0;
  if (i.last_activity) {
    const days = Math.floor((Date.now() - new Date(i.last_activity).getTime()) / 86400000);
    recency = days <= 1 ? 100 : days <= 7 ? 80 : days <= 30 ? 50 : days <= 90 ? 20 : 0;
  }
  const frequency = FREQUENCY[i.visit_frequency] ?? FREQUENCY.rarely;
  return recency * 0.50 + frequency * 0.50;
}
 
function determineGrade(score) {
  if (score >= 80) return 'A';
  if (score >= 60) return 'B';
  if (score >= 40) return 'C';
  if (score >= 20) return 'D';
  return 'F';
}
 
function determineQualificationStatus(score, grade, lead) {
  if (score >= 75 && lead.behavior?.demo_requested) return 'SQL';
  if (score >= 80) return 'SQL';
  if (score >= 50 && ['A', 'B'].includes(grade)) return 'MQL';
  if (score >= 40 && (lead.behavior?.pricing_page_visits || 0) >= 2) return 'MQL';
  return 'Lead';
}
 
function scoreLead(lead) {
  const scores = {
    demographic: demographicScore(lead),
    behavioral: behavioralScore(lead),
    engagement: engagementScore(lead),
    intent: intentScore(lead)
  };
 
  const total = Math.round(
    scores.demographic * WEIGHTS.demographic +
    scores.behavioral * WEIGHTS.behavioral +
    scores.engagement * WEIGHTS.engagement +
    scores.intent * WEIGHTS.intent
  );
 
  const grade = determineGrade(total);
  const previous = lead.previous_score ?? null;
 
  return {
    lead_id: lead.id,
    email: lead.email,
    scores: {
      demographic: Math.round(scores.demographic),
      behavioral: Math.round(scores.behavioral),
      engagement: Math.round(scores.engagement),
      intent: Math.round(scores.intent),
      total
    },
    grade,
    qualification_status: determineQualificationStatus(total, grade, lead),
    score_breakdown: {
      demographic_factors: {
        company_size: lead.company_size,
        industry: lead.industry,
        job_title: lead.job_title,
        location: lead.country
      },
      behavioral_factors: {
        page_views: lead.behavior?.page_views || 0,
        pricing_visits: lead.behavior?.pricing_page_visits || 0,
        downloads: lead.behavior?.content_downloads || 0,
        demo_requested: lead.behavior?.demo_requested || false
      }
    },
    scored_at: new Date().toISOString(),
    previous_score: previous,
    score_change: previous !== null ? total - previous : null
  };
}
 
return $input.all().map(item => ({ json: scoreLead(item.json) }));

Actualizări de Scor în Timp Real

// Code node (Run Once for All Items): real-time score updater
// Input: one tracking event. "Get Lead Scores" is the node that loaded the lead's current scores.
const event = $input.first().json;
const currentScores = $('Get Lead Scores').first()?.json || {};
 
// Event scoring adjustments
const eventScoreAdjustments = {
  // Website events
  page_view: 1,
  pricing_page_view: 5,
  product_page_view: 3,
  case_study_view: 4,
  blog_post_view: 1,
 
  // Content events
  ebook_download: 10,
  whitepaper_download: 12,
  checklist_download: 8,
  webinar_registration: 15,
  webinar_attendance: 20,
 
  // Form submissions
  demo_request: 30,
  contact_form: 25,
  pricing_request: 28,
  trial_signup: 35,
 
  // Email events
  email_open: 2,
  email_click: 5,
  email_reply: 15,
  unsubscribe: -20,
 
  // Negative events
  bounce: -10,
  spam_complaint: -50,
  inactive_30_days: -15,
  inactive_60_days: -25,
  inactive_90_days: -40
};
 
const eventType = String(event.event_type || '');
const adjustment = eventScoreAdjustments[eventType] || 0;
 
// 2% decay per inactive week
function applyScoreDecay(currentScore, lastActivityDate) {
  if (!lastActivityDate) return currentScore;
  const daysSinceActivity = Math.floor(
    (Date.now() - new Date(lastActivityDate).getTime()) / 86400000
  );
  const weeksInactive = Math.floor(daysSinceActivity / 7);
  return Math.round(currentScore * Math.pow(0.98, weeksInactive));
}
 
let newBehavioralScore = (currentScores.behavioral || 0) + adjustment;
 
if (eventType.includes('inactive')) {
  newBehavioralScore = applyScoreDecay(newBehavioralScore, currentScores.last_activity_date);
}
 
// Keep the score within bounds
newBehavioralScore = Math.max(0, Math.min(100, newBehavioralScore));
 
const thresholds = { mql: 50, sql: 75, hot_lead: 85 };
 
const previousTotal = currentScores.total || 0;
const newTotal = Math.round(
  (currentScores.demographic || 0) * 0.30 +
  newBehavioralScore * 0.40 +
  (currentScores.engagement || 0) * 0.20 +
  (currentScores.intent || 0) * 0.10
);
 
const thresholdsCrossed = [];
for (const [name, threshold] of Object.entries(thresholds)) {
  if (previousTotal < threshold && newTotal >= threshold) {
    thresholdsCrossed.push({ threshold: name, direction: 'up' });
  } else if (previousTotal >= threshold && newTotal < threshold) {
    thresholdsCrossed.push({ threshold: name, direction: 'down' });
  }
}
 
const crossedUp = (name) => thresholdsCrossed.some(t => t.threshold === name && t.direction === 'up');
const actions = [];
 
if (crossedUp('sql')) {
  actions.push({
    type: 'notify_sales',
    priority: 'high',
    message: `Lead ${event.lead_id} is now SQL (score: ${newTotal})`
  });
  actions.push({
    type: 'create_task',
    assignee: 'sales_round_robin',
    task: `Follow up with SQL: ${event.lead_email}`
  });
}
 
if (crossedUp('mql')) {
  actions.push({
    type: 'add_to_nurture',
    campaign: 'mql_nurture',
    message: 'Added to MQL nurture sequence'
  });
}
 
if (crossedUp('hot_lead')) {
  actions.push({
    type: 'notify_sales',
    priority: 'urgent',
    message: `Hot lead alert! ${event.lead_id} score: ${newTotal}`
  });
}
 
return [{
  json: {
    lead_id: event.lead_id,
    event: eventType,
    score_adjustment: adjustment,
    scores: {
      previous: { behavioral: currentScores.behavioral ?? null, total: previousTotal },
      current: { behavioral: newBehavioralScore, total: newTotal }
    },
    thresholds_crossed: thresholdsCrossed,
    actions,
    updated_at: new Date().toISOString()
  }
}];

Rutarea Lead-urilor

// Code node (Run Once for All Items): lead router
// Input: the scored lead. "Get Sales Team" returns one item per sales rep.
const scoredLead = $input.first().json;
const salesTeam = $('Get Sales Team').all().map(i => i.json);
 
// Routing rules, checked in order
const routingRules = {
  enterprise: {
    condition: (lead) => lead.company_size === 'enterprise' || lead.scores.total >= 85,
    team: 'enterprise_sales',
    sla_minutes: 15
  },
  mid_market: {
    condition: (lead) => lead.company_size === 'mid_market' || lead.scores.total >= 70,
    team: 'mid_market_sales',
    sla_minutes: 30
  },
  smb: {
    condition: () => true, // Default
    team: 'smb_sales',
    sla_minutes: 60
  }
};
 
// Industry-specific routing
const industryRouting = {
  healthcare: 'healthcare_specialist',
  finance: 'financial_services_specialist',
  technology: 'tech_specialist'
};
 
// Geographic routing
const geoRouting = {
  US: { CA: 'west_coast_team', NY: 'east_coast_team' },
  GB: 'emea_team',
  DE: 'emea_team',
  JP: 'apac_team',
  AU: 'apac_team'
};
 
function determineRoute(lead) {
  let segment = 'smb';
  for (const [seg, rule] of Object.entries(routingRules)) {
    if (rule.condition(lead)) {
      segment = seg;
      break;
    }
  }
 
  const specialist = industryRouting[lead.industry] || null;
 
  let geoTeam = null;
  const geo = geoRouting[lead.country];
  if (geo) {
    geoTeam = typeof geo === 'object' ? geo[lead.state] || null : geo;
  }
 
  return {
    segment,
    team: routingRules[segment].team,
    specialist,
    geo_team: geoTeam,
    sla_minutes: routingRules[segment].sla_minutes
  };
}
 
function selectSalesRep(team, availableReps) {
  const hasCapacity = rep => rep.is_available && rep.current_leads < rep.max_leads;
  const teamReps = availableReps.filter(rep => rep.team === team && hasCapacity(rep));
 
  if (teamReps.length === 0) {
    // Fall back to any available rep
    const anyAvailable = availableReps.filter(hasCapacity);
    if (anyAvailable.length === 0) return null;
    return anyAvailable.sort((a, b) => a.current_leads - b.current_leads)[0];
  }
 
  // Lowest load first, then longest since last assignment
  return teamReps.sort((a, b) => {
    const loadDiff = a.current_leads - b.current_leads;
    if (loadDiff !== 0) return loadDiff;
    return new Date(a.last_assigned) - new Date(b.last_assigned);
  })[0];
}
 
const route = determineRoute(scoredLead);
const assignedRep = selectSalesRep(route.team, salesTeam);
 
return [{
  json: {
    lead_id: scoredLead.lead_id,
    routing: {
      segment: route.segment,
      team: route.team,
      specialist_required: route.specialist,
      geographic_team: route.geo_team,
      sla_minutes: route.sla_minutes,
      sla_deadline: new Date(Date.now() + route.sla_minutes * 60 * 1000).toISOString()
    },
    assignment: assignedRep ? {
      rep_id: assignedRep.id,
      rep_name: assignedRep.name,
      rep_email: assignedRep.email,
      assigned_at: new Date().toISOString()
    } : null,
    fallback_required: !assignedRep,
    lead_score: scoredLead.scores.total,
    lead_grade: scoredLead.grade,
    qualification: scoredLead.qualification_status
  }
}];

Integrarea cu CRM

// Code node (Run Once for All Items): CRM sync payload
// Input: the routing result. "Lead Scoring" is the scoring node above.
// CRM_URL is read with $env, which needs N8N_BLOCK_ENV_ACCESS_IN_NODE=false.
// Set that variable explicitly: the n8n 2.0 breaking changes guide lists true as the new default.
const routingResult = $input.first().json;
const scoredLead = $('Lead Scoring').first().json;
const crmUrl = $env.CRM_URL;
 
function mapQualificationToStage(qualification) {
  const mapping = {
    Lead: 'new_lead',
    MQL: 'marketing_qualified',
    SQL: 'sales_qualified',
    Opportunity: 'opportunity'
  };
  return mapping[qualification] || 'new_lead';
}
 
function buildTaskDescription(lead, routing) {
  const f = lead.score_breakdown.behavioral_factors;
  const signals = [
    f.demo_requested ? '- Requested demo' : null,
    f.pricing_visits > 0 ? `- Visited pricing page ${f.pricing_visits} times` : null,
    f.downloads > 0 ? `- Downloaded ${f.downloads} resources` : null
  ].filter(Boolean).join('\n');
 
  return [
    '## Lead Overview',
    `- **Score**: ${lead.scores.total} (Grade: ${lead.grade})`,
    `- **Status**: ${lead.qualification_status}`,
    `- **Segment**: ${routing.routing.segment}`,
    '',
    '## Score Breakdown',
    `- Demographic: ${lead.scores.demographic}/100`,
    `- Behavioral: ${lead.scores.behavioral}/100`,
    `- Engagement: ${lead.scores.engagement}/100`,
    `- Intent: ${lead.scores.intent}/100`,
    '',
    '## Key Signals',
    signals || '- None',
    '',
    '## SLA',
    `- **Deadline**: ${routing.routing.sla_deadline}`,
    `- **Time allowed**: ${routing.routing.sla_minutes} minutes`
  ].join('\n');
}
 
function buildCRMPayload(lead, routing) {
  return {
    contact: {
      id: lead.lead_id,
      email: lead.email,
      custom_fields: {
        lead_score: lead.scores.total,
        lead_grade: lead.grade,
        demographic_score: lead.scores.demographic,
        behavioral_score: lead.scores.behavioral,
        engagement_score: lead.scores.engagement,
        intent_score: lead.scores.intent,
        last_scored_at: new Date().toISOString()
      }
    },
    lifecycle: {
      stage: mapQualificationToStage(lead.qualification_status),
      status: 'active',
      score: lead.scores.total
    },
    assignment: routing.assignment ? {
      owner_id: routing.assignment.rep_id,
      assigned_at: routing.assignment.assigned_at,
      assignment_reason: `Auto-routed: ${routing.routing.segment} segment`
    } : null,
    task: routing.assignment ? {
      title: `Follow up with ${lead.qualification_status}: ${lead.email}`,
      description: buildTaskDescription(lead, routing),
      due_date: routing.routing.sla_deadline,
      priority: lead.scores.total >= 80 ? 'high' : 'normal',
      assignee_id: routing.assignment.rep_id,
      type: 'follow_up'
    } : null,
    activity: {
      type: 'score_update',
      timestamp: new Date().toISOString(),
      details: {
        previous_score: lead.previous_score,
        new_score: lead.scores.total,
        score_change: lead.score_change,
        triggered_by: 'automated_scoring'
      }
    }
  };
}
 
// Map these generic fields to your CRM's API (HubSpot, Salesforce, ...) in the node that sends them
const crmPayload = buildCRMPayload(scoredLead, routingResult);
 
const notification = routingResult.assignment ? {
  type: 'new_lead_assignment',
  recipient: routingResult.assignment.rep_email,
  subject: `New ${scoredLead.qualification_status} Assigned: ${scoredLead.email}`,
  body: {
    lead_email: scoredLead.email,
    score: scoredLead.scores.total,
    grade: scoredLead.grade,
    sla_deadline: routingResult.routing.sla_deadline,
    quick_view_url: crmUrl ? `${crmUrl}/leads/${encodeURIComponent(scoredLead.lead_id)}` : null
  },
  channel: scoredLead.scores.total >= 80 ? 'slack_dm' : 'email'
} : null;
 
return [{
  json: {
    crm_payload: crmPayload,
    notification,
    metadata: {
      lead_id: scoredLead.lead_id,
      processed_at: new Date().toISOString()
    }
  }
}];

Analiza și Raportare

// Code node (Run Once for All Items): scoring analytics
// Input: one item per scored lead for the reporting period.
const allLeads = $input.all().map(i => i.json);
const total = allLeads.length;
 
const metrics = {
  total_leads: total,
  by_grade: { A: 0, B: 0, C: 0, D: 0, F: 0 },
  by_qualification: { Lead: 0, MQL: 0, SQL: 0 },
  score_distribution: [],
  average_scores: { demographic: 0, behavioral: 0, engagement: 0, intent: 0, total: 0 }
};
 
for (const lead of allLeads) {
  metrics.by_grade[lead.grade] = (metrics.by_grade[lead.grade] || 0) + 1;
  metrics.by_qualification[lead.qualification_status] =
    (metrics.by_qualification[lead.qualification_status] || 0) + 1;
 
  for (const key of Object.keys(metrics.average_scores)) {
    metrics.average_scores[key] += lead.scores[key] || 0;
  }
}
 
for (const key of Object.keys(metrics.average_scores)) {
  metrics.average_scores[key] = total > 0 ? Math.round(metrics.average_scores[key] / total) : 0;
}
 
const buckets = [
  { min: 0, max: 20, label: '0-20' },
  { min: 21, max: 40, label: '21-40' },
  { min: 41, max: 60, label: '41-60' },
  { min: 61, max: 80, label: '61-80' },
  { min: 81, max: 100, label: '81-100' }
];
 
for (const bucket of buckets) {
  const count = allLeads.filter(l =>
    l.scores.total >= bucket.min && l.scores.total <= bucket.max
  ).length;
  metrics.score_distribution.push({
    range: bucket.label,
    count,
    percentage: total > 0 ? Math.round((count / total) * 100) : 0
  });
}
 
// Conversion rates need closed-won data from the CRM; compute them in a separate
// step from real opportunity records instead of hardcoding values here.
 
function generateInsights(m) {
  const insights = [];
  if (m.total_leads === 0) return insights;
 
  const aGradePercent = (m.by_grade.A / m.total_leads) * 100;
  if (aGradePercent < 10) {
    insights.push({
      type: 'warning',
      message: `Only ${aGradePercent.toFixed(1)}% of leads are A-grade. Consider reviewing acquisition channels.`
    });
  }
 
  if (m.average_scores.total < 40) {
    insights.push({
      type: 'info',
      message: `Average lead score is ${m.average_scores.total}. Focus on lead quality improvement.`
    });
  }
 
  return insights;
}
 
function generateRecommendations(m) {
  const recommendations = [];
 
  if (m.total_leads > 0 && m.average_scores.behavioral < 40) {
    recommendations.push({
      area: 'engagement',
      recommendation: 'Implement more interactive content to boost behavioral scores'
    });
  }
 
  if (m.by_qualification.MQL > m.by_qualification.SQL * 3) {
    recommendations.push({
      area: 'conversion',
      recommendation: 'Review MQL to SQL conversion - consider adjusting thresholds or nurture campaigns'
    });
  }
 
  return recommendations;
}
 
return [{
  json: {
    generated_at: new Date().toISOString(),
    period: 'last_30_days',
    metrics,
    insights: generateInsights(metrics),
    recommendations: generateRecommendations(metrics)
  }
}];

Bune Practici

Designul Lead Scoring-ului

  1. Începe simplu: Pornește cu un scoring de bază și rafinează pe parcurs
  2. Validează cu echipa de vânzări: Asigură-te că scorurile se corelează cu conversiile reale
  3. Calibrare regulată: Ajustează ponderile pe baza datelor de performanță
  4. Scorare negativă: Nu uita să penalizezi lipsa de engagement

Sfaturi de Implementare

  • Actualizează scorurile în timp real pentru acțiuni prompte
  • Implementează score decay pentru lead-urile inactive
  • Creează procese clare de predare la depășirea pragurilor
  • Monitorizează regulat acuratețea modelului de scoring

Automatizarea lead scoring-ului cu n8n asigură calificare consistentă, permițând în același timp echipelor de vânzări să se concentreze pe oportunitățile cu cel mai mare potențial.


Surse oficiale

Pe același subiect: Automatizare AI: Zapier vs Make vs n8n - Pe care sa o alegi?, n8n automatizare CRM: pattern-uri HubSpot si Salesforce, n8n automatizare onboarding clienti: end-to-end. Mai multe articole în categoria n8n Automation.

Vrei agenți AI și automatizări pe care firma ta chiar se poate baza?

Le construim în sprinturi fixe de două săptămâni, apoi le securizăm. Programează un apel de 30 de minute ca să stabilim ce construim.

Programează un apel

Înainte de apel poți vedea ce construim, cât costă un sprint și ce garantăm, ce am construit deja sau ne poți scrie direct.

Digest săptămânal: agenți AI, automatizări și securitate

Cum construim agenți AI și automatizări cu Claude Code, plus securitate AI practică, integrări și note de platformă, în fiecare săptămână.

Fără spam. Te poți dezabona oricând.