Skip to content
// Dedupe, assign an agent round-robin, and schedule the follow-up drip. State lives in workflow static data.
// A dry run computes everything but saves nothing.
const s = $('Settings (edit me)').first().json;
const lead = $input.first().json;
const db = $getWorkflowStaticData('global');
db.leads = db.leads ?? {};
db.rr = db.rr ?? 0;

const key = lead.email || lead.phone;
const prev = db.leads[key];
const now = DateTime.fromISO(lead.received_at);
const isDuplicate = Boolean(prev && prev.status !== 'stopped' && now.diff(DateTime.fromISO(prev.created_at), 'days').days < s.dedupe_days);

let agent;
if (isDuplicate) {
  agent = s.agents.find((a) => a.email === prev.agent_email) ?? s.agents[0];
} else {
  agent = s.agents[db.rr % s.agents.length];
}

const drip = isDuplicate ? prev.drip : s.drip.map((d) => ({ step: d.step, day: d.day, due_at: now.plus({ days: d.day }).toISO(), sent_at: null, last_error: null }));
const record = {
  key, name: lead.name, first_name: lead.first_name, email: lead.email, phone: lead.phone, intent: lead.intent,
  property: lead.asked_listing?.address ?? lead.property, match_ids: lead.matches.map((m) => m.id),
  agent_email: agent.email, agent_name: agent.name, status: 'active',
  created_at: isDuplicate ? prev.created_at : lead.received_at,
  inquiries: (prev?.inquiries ?? 0) + 1, drip,
};

if (!lead.dry_run) {
  if (!isDuplicate) db.rr += 1;
  db.leads[key] = record;
}

return [{ json: { ...lead, is_duplicate: isDuplicate, agent, drip } }];