Skip to content
// Blend rule score (40%) with the AI fit score (60%), pick a tier, and write the CRM note.
const s = $('Settings (edit me)').first().json;

return $input.all().map((item, i) => {
  const lead = $('Rule Score').all()[i].json;
  const ai = item.json.output ?? {};
  const aiScore = Math.max(0, Math.min(100, Math.round(Number(ai.fit_score) || 0)));
  const score = lead.dry_run ? lead.rule_score : Math.round(0.4 * lead.rule_score + 0.6 * aiScore);
  const tier = score >= s.hot_threshold ? 'hot' : score >= s.warm_threshold ? 'warm' : 'cold';

  const note = [
    `🤖 AI lead qualification: ${tier.toUpperCase()} (${score}/100)`,
    ai.summary ? `Summary: ${ai.summary}` : null,
    ai.intent ? `Intent: ${ai.intent}` : null,
    ai.budget_signal ? `Budget: ${ai.budget_signal}` : null,
    ai.next_step ? `Suggested next step: ${ai.next_step}` : null,
    `Signals: ${lead.rule_signals.join(', ') || 'none'}`,
    lead.dry_run ? '' : `Scores: rules ${lead.rule_score}, AI ${aiScore}`,
  ].filter(Boolean).join('\n');

  return {
    json: {
      contact_id: lead.contact_id,
      name: lead.name,
      email: lead.email,
      score,
      tier,
      tag: s[`${tier}_tag`],
      rule_score: lead.rule_score,
      ai_score: lead.dry_run ? null : aiScore,
      signals: lead.rule_signals,
      summary: ai.summary ?? null,
      next_step: ai.next_step ?? null,
      note,
      dry_run: lead.dry_run,
    },
  };
});