Skip to content
// One digest per owner: their stale deals, most urgent first, with a ready-to-send message.
const money = (n) => (n ? '$' + Math.round(n).toLocaleString('en-US') : 'no amount');
const byOwner = {};
for (const { json: d } of $input.all()) (byOwner[d.owner] ??= []).push(d);

const owners = Object.entries(byOwner)
  .map(([owner, deals]) => {
    const total = deals.reduce((sum, d) => sum + d.amount, 0);
    const lines = deals.map((d, i) =>
      `${i + 1}. ${d.name} (${money(d.amount)}, ${d.stage}): ${d.idle_days === null ? 'no activity recorded' : `${d.idle_days} days quiet (limit ${d.limit_days})`}` +
      (d.url ? `\n   ${d.url}` : '') +
      `\n   Draft: "${d.draft_subject}"`);
    return {
      owner,
      deal_count: deals.length,
      pipeline_at_risk: total,
      message: `👋 ${owner.split(' ')[0]}, ${deals.length} deal${deals.length > 1 ? 's' : ''} (${money(total)}) went quiet:\n\n${lines.join('\n')}`,
      deals,
    };
  })
  .sort((a, b) => b.pipeline_at_risk - a.pipeline_at_risk);

return owners.map((json) => ({ json }));