Skip to content
// Keep open deals with no activity for longer than their stage allows, most urgent first.
// urgency = overdue days × deal size factor (no activity date counts as one stage-limit overdue).
const s = $('Settings (edit me)').first().json;
const req = $('Stale Check API').isExecuted ? $('Stale Check API').first().json : null;
const now = req?.body?.now ? DateTime.fromISO(req.body.now) : DateTime.now();

const stale = [];
for (const { json: d } of $input.all()) {
  if (s.closed_stages.includes(d.stage)) continue;
  const limit = s.stale_days[d.stage] ?? s.stale_days.default;
  const last = d.last_activity ? DateTime.fromISO(d.last_activity) : null;
  const idle = last && last.isValid ? Math.floor(now.diff(last, 'days').days) : 999;
  if (idle <= limit) continue;
  const overdue = idle - limit;
  const sizeFactor = 1 + Math.log10(Math.max(d.amount, 1000) / 1000);
  stale.push({
    ...d,
    idle_days: idle === 999 ? null : idle,
    limit_days: limit,
    overdue_days: idle === 999 ? null : overdue,
    urgency: Math.round((idle === 999 ? limit : overdue) * sizeFactor * 10) / 10,
  });
}
stale.sort((a, b) => b.urgency - a.urgency);
return stale.map((json) => ({ json }));