File size: 9,316 Bytes
bd28470
 
 
 
 
 
 
 
 
 
 
5f138d4
 
 
bd28470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/**
 * Slack Service β€” 3-Layer Data Delivery
 * 
 * Layer 1: Daily Digest (1 rich message per day β€” summary table)
 * Layer 2: Real-time Alerts (only HOT leads 85+ β€” immediate)
 * Layer 3: Commands (/leads, /discover, /status, /pause, /quota)
 * 
 * NOT Slack blast β€” organized, formatted, actionable.
 */

import axios from "axios";
import { getEnv } from "../shared/config/env";
import { getSupabaseClient } from "../shared/supabase/client";
import { logger } from "../shared/utils/logger";

// ─── Slack API helper ────────────────────────────────────────

async function postMessage(channelId: string, blocks: unknown[], text: string): Promise<void> {
  const env = getEnv();
  try {
    await axios.post("https://slack.com/api/chat.postMessage", {
      channel: channelId,
      text,
      blocks,
    }, {
      headers: { Authorization: `Bearer ${env.SLACK_BOT_TOKEN}` },
      timeout: 5_000,
    });
  } catch (err) {
    logger.warn({ err }, "Slack post failed β€” non-critical");
  }
}

// ─── LAYER 1: Daily Digest ───────────────────────────────────

export async function sendDailyDigest(runSummary: {
  territory: string;
  industry: string;
  companiesSearched: number;
  leadsQualified: number;
  hotLeads: number;
  warmLeads: number;
  nurtureLeads: number;
  tokensUsed: number;
  durationMinutes: number;
}): Promise<void> {
  const env = getEnv();
  const db = getSupabaseClient();

  // Fetch today's qualified leads
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const { data: leads } = await db
    .from("lead_scores")
    .select(`
      total_score, tier,
      companies (name, domain, industry, employee_count, city, service_match),
      contacts (full_name, title, email, email_verified, linkedin_personal_url)
    `)
    .gte("created_at", today.toISOString())
    .order("total_score", { ascending: false })
    .limit(20);

  // Build lead table
  const leadRows = (leads ?? []).map((lead: any, i: number) => {
    const emoji = lead.tier === "hot" ? "πŸ”₯" : lead.tier === "warm" ? "βœ…" : "πŸ“‹";
    const company = lead.companies;
    const contact = lead.contacts;
    const emailIcon = contact?.email_verified ? "πŸ“§βœ“" : contact?.email ? "πŸ“§" : "β€”";
    const linkedinIcon = contact?.linkedin_personal_url ? "πŸ’Όβœ“" : "β€”";

    return `${emoji} *${company?.name ?? "Unknown"}* β€” ${lead.total_score}/100 ${lead.tier.toUpperCase()}\n` +
      `    ${company?.industry ?? "?"} Β· ${company?.employee_count ?? "?"} emp Β· ${company?.city ?? "?"}\n` +
      `    ${contact?.full_name ?? "?"} (${contact?.title ?? "?"})\n` +
      `    ${emailIcon} ${linkedinIcon} Β· Match: ${company?.service_match ?? "β€”"}`;
  }).join("\n\n");

  const blocks = [
    // Header
    {
      type: "header",
      text: { type: "plain_text", text: `πŸ“Š Daily Lead Report β€” ${formatDate(new Date())}` },
    },
    // Summary stats
    {
      type: "section",
      text: {
        type: "mrkdwn",
        text: `*Territory:* ${runSummary.territory} β†’ ${runSummary.industry}\n` +
          `*Searched:* ${runSummary.companiesSearched} companies\n` +
          `*Qualified:* ${runSummary.leadsQualified} leads ` +
          `(πŸ”₯ ${runSummary.hotLeads} hot Β· βœ… ${runSummary.warmLeads} warm Β· πŸ“‹ ${runSummary.nurtureLeads} nurture)\n` +
          `*Duration:* ${runSummary.durationMinutes} min Β· *Tokens:* ${runSummary.tokensUsed.toLocaleString()}`,
      },
    },
    { type: "divider" },
    // Lead list
    {
      type: "section",
      text: {
        type: "mrkdwn",
        text: leadRows || "_No qualified leads found today_",
      },
    },
    { type: "divider" },
    // Actions
    {
      type: "context",
      elements: [
        {
          type: "mrkdwn",
          text: "Type `/leads` for full details Β· `/discover region:UK` for manual run Β· `/status` for system status",
        },
      ],
    },
  ];

  await postMessage(env.SLACK_ALERT_CHANNEL_ID, blocks,
    `Daily Report: ${runSummary.leadsQualified} leads found`);
}

// ─── LAYER 2: Hot Lead Alert (85+ only) ──────────────────────

export async function sendHotLeadAlert(lead: {
  companyName: string;
  domain: string;
  industry: string;
  employeeCount: number | null;
  city: string | null;
  score: number;
  tier: string;
  contactName: string;
  contactTitle: string;
  email: string | null;
  emailVerified: boolean;
  linkedinPersonal: string | null;
  linkedinCompany: string | null;
  serviceMatch: string | null;
  outreachAngle: string;
  painPoints: string[];
  socialProfiles: Record<string, string | null>;
}): Promise<void> {
  const env = getEnv();
  const emoji = lead.score >= 90 ? "πŸ”₯πŸ”₯πŸ”₯" : lead.score >= 85 ? "πŸ”₯πŸ”₯" : "πŸ”₯";

  // Contact channels summary
  const channels: string[] = [];
  if (lead.email && lead.emailVerified) channels.push(`πŸ“§ ${lead.email} βœ“`);
  else if (lead.email) channels.push(`πŸ“§ ${lead.email} (unverified)`);
  if (lead.linkedinPersonal) channels.push(`πŸ’Ό <${lead.linkedinPersonal}|LinkedIn>`);
  if (lead.linkedinCompany) channels.push(`🏒 <${lead.linkedinCompany}|Company LI>`);
  if (lead.socialProfiles?.instagram) channels.push(`πŸ“· <${lead.socialProfiles.instagram}|Instagram>`);
  if (lead.socialProfiles?.facebook) channels.push(`πŸ‘₯ <${lead.socialProfiles.facebook}|Facebook>`);

  const blocks = [
    {
      type: "header",
      text: { type: "plain_text", text: `${emoji} HOT LEAD β€” ${lead.companyName}` },
    },
    {
      type: "section",
      fields: [
        { type: "mrkdwn", text: `*Score:*\n${lead.score}/100 β€” ${lead.tier.toUpperCase()}` },
        { type: "mrkdwn", text: `*Industry:*\n${lead.industry}` },
        { type: "mrkdwn", text: `*Employees:*\n${lead.employeeCount ?? "Unknown"}` },
        { type: "mrkdwn", text: `*Location:*\n${lead.city ?? "Unknown"}` },
        { type: "mrkdwn", text: `*Service Match:*\n${lead.serviceMatch ?? "General"}` },
        { type: "mrkdwn", text: `*Domain:*\n${lead.domain}` },
      ],
    },
    { type: "divider" },
    {
      type: "section",
      text: {
        type: "mrkdwn",
        text: `*πŸ‘€ Decision Maker:*\n${lead.contactName} β€” ${lead.contactTitle}\n\n` +
          `*πŸ“± Channels:*\n${channels.join("\n") || "None found"}\n\n` +
          `*🎯 Outreach Angle:*\n_"${lead.outreachAngle}"_\n\n` +
          `*πŸ’’ Pain Points:*\n${lead.painPoints.map(p => `β€’ ${p}`).join("\n")}`,
      },
    },
  ];

  await postMessage(env.SLACK_ALERT_CHANNEL_ID, blocks,
    `πŸ”₯ HOT LEAD: ${lead.companyName} β€” Score ${lead.score}`);
}

// ─── LAYER 2: Run Progress Updates ──────────────────────────

export async function sendRunStarted(territory: string, industry: string, quota: number): Promise<void> {
  const env = getEnv();
  await postMessage(env.SLACK_ALERT_CHANNEL_ID, [
    {
      type: "section",
      text: {
        type: "mrkdwn",
        text: `πŸš€ *Daily run started*\n` +
          `Territory: ${territory} β†’ ${industry}\n` +
          `Quota: ${quota} leads\n` +
          `Estimated: ~90 min`,
      },
    },
  ], `Run started: ${territory} ${industry}`);
}

export async function sendRunProgress(qualified: number, quota: number, searched: number): Promise<void> {
  const env = getEnv();
  const progress = Math.round((qualified / quota) * 100);
  const bar = "β–ˆ".repeat(Math.round(progress / 10)) + "β–‘".repeat(10 - Math.round(progress / 10));

  await postMessage(env.SLACK_ALERT_CHANNEL_ID, [
    {
      type: "section",
      text: {
        type: "mrkdwn",
        text: `πŸ“Š *Progress:* ${qualified}/${quota} qualified [${bar}] ${progress}%\n` +
          `Searched: ${searched} companies`,
      },
    },
  ], `Progress: ${qualified}/${quota}`);
}

// ─── LAYER 3: Clarifying Questions ──────────────────────────

export async function sendClarifyingQuestions(
  userMessage: string,
  questions: { question: string; options: string[] }[]
): Promise<void> {
  const env = getEnv();

  const blocks: unknown[] = [
    {
      type: "section",
      text: {
        type: "mrkdwn",
        text: `πŸ€” *Got it: "${userMessage}"*\nMujhe kuch clarify karna hai:`,
      },
    },
  ];

  for (const q of questions) {
    blocks.push({
      type: "section",
      text: {
        type: "mrkdwn",
        text: `*${q.question}*\n${q.options.map((o, i) => `${i + 1}. ${o}`).join("\n")}`,
      },
    });
  }

  blocks.push({
    type: "context",
    elements: [{
      type: "mrkdwn",
      text: "Just reply with numbers (e.g., `1 2 3`) or type your own answer",
    }],
  });

  await postMessage(env.SLACK_ALERT_CHANNEL_ID, blocks,
    "Clarifying questions for manual discovery");
}

// ─── Helpers ─────────────────────────────────────────────────

function formatDate(date: Date): string {
  return date.toLocaleDateString("en-US", {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
  });
}