File size: 13,584 Bytes
5f138d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import { callLLM, MODELS } from "../shared/llm/nvidia-client";
import { getSupabaseClient } from "../shared/supabase/client";
import { manualDiscoveryTask } from "../discovery/trigger-tasks/manual-discovery";
import { logger } from "../shared/utils/logger";
import axios from "axios";
import { getEnv } from "../shared/config/env";

const env = getEnv();

// Helper to post messages back to Slack
async function replyToSlack(channelId: string, text: string, threadTs?: string): Promise<void> {
  try {
    await axios.post(
      "https://slack.com/api/chat.postMessage",
      {
        channel: channelId,
        text,
        thread_ts: threadTs,
      },
      {
        headers: { Authorization: `Bearer ${env.SLACK_BOT_TOKEN}` },
        timeout: 5000,
      }
    );
  } catch (err) {
    logger.error({ err }, "Failed to reply to Slack");
  }
}

// ─── Intent System Prompt ──────────────────────────────────────

const AGENT_SYSTEM_PROMPT = `You are "Lead Finder AI", an intelligent Slack Chatbot assistant.
Your job is to parse the user's natural language request (in English, Urdu, or Roman Urdu) and map it to a structured action.

You must respond ONLY with a valid JSON object matching this schema:
{
  "intent": "discover" | "leads" | "lead_detail" | "status" | "pause" | "resume" | "quota" | "chat",
  "params": {
    "region": "US" | "UK" | "AU" | "UAE" | "SA" | "SG" (optional),
    "industry": string (optional),
    "maxCompanies": number (optional),
    "companyName": string (optional),
    "quotaAmount": number (optional),
    "quotaPermanent": boolean (optional)
  },
  "explanation": "A very brief, friendly sentence in Roman Urdu explaining what you understood and what you are doing (e.g. 'Ji bilkul! Main abhi US ke dental leads dhoondta hoon.' or 'Bilkul, ye rahi aaj ki leads summary:')"
}

Intents mapping rules:
1. "discover": Manual trigger of search/enrichment/scoring.
   - Example: "aj US me SaaS leads dhoondo", "manual run UK dental", "dental leads US", "UK clinical leads nikal do", "discover dental UAE"
   - Default region to US if not specified. Default maxCompanies to 10 if not specified.
2. "leads": Today's qualified leads list.
   - Example: "aj ki leads dikhao", "show today's leads", "aj kya mila?", "today leads summary", "leads"
3. "lead_detail": Profile/score details about a specific company.
   - Example: "clickup ki details do", "show lead clickup", "clickup ka batao", "lead detail of Google"
   - Extract company name into companyName.
4. "status": System config status (quota, pause/run mode, coordinates).
   - Example: "status batao", "system kaisa chal raha?", "running status", "check status"
5. "pause": Pauses automatic CRON daily runs.
   - Example: "pause system", "automatic run rok do", "pause auto mode", "stop runs"
6. "resume": Resumes automatic CRON daily runs.
   - Example: "resume system", "auto runs start kar do", "resume run"
7. "quota": Changes daily lead quota.
   - Example: "quota 15 kar do", "set today's quota to 20", "set permanent quota to 50"
   - Extract quotaAmount and quotaPermanent.
8. "chat": General greetings, small talk, questions about how you work, or how to use you.
   - Example: "hello", "hi", "tum kon ho?", "how do you work?", "help me"

Respond ONLY with raw JSON. Do not include markdown code block syntax or explanation outside JSON.`;

// ─── Main Chatbot handler ──────────────────────────────────────

export async function handleSlackChat(
  userText: string,
  userId: string,
  channelId: string,
  threadTs?: string
): Promise<void> {
  const cleanText = userText.trim();
  logger.info({ userId, cleanText }, "πŸ€– AI Chatbot processing message");

  // Call the LLM to parse the intent
  const llmRes = await callLLM({
    operation: "slack_intent_classification",
    modelIndex: MODELS.LLAMA_70B, // Use LLaMA 70B for highly accurate intent mapping
    systemPrompt: AGENT_SYSTEM_PROMPT,
    userPrompt: cleanText,
    jsonMode: true,
    traceId: `slack-chat-${Date.now()}`,
  });

  if (!llmRes.parsed) {
    await replyToSlack(
      channelId,
      "Maaf kijiye ga, mujhe aap ki baat samajh nahi aayi. Kya aap dobara keh sakte hain? (Greetings, /discover, /leads waghaira ke liye pooch sakte hain)",
      threadTs
    );
    return;
  }

  const { intent, params, explanation } = llmRes.parsed as {
    intent: string;
    params: any;
    explanation: string;
  };

  logger.info({ intent, params }, "🎯 Decoded intent");

  // Respond with explanation first so user knows we are on it
  if (explanation && intent !== "chat") {
    await replyToSlack(channelId, `πŸ’¬ *Lead Finder AI:* ${explanation}`, threadTs);
  }

  const db = getSupabaseClient();

  try {
    switch (intent) {
      case "discover": {
        const region = params?.region || "US";
        const industry = params?.industry || "SaaS";
        const maxCompanies = params?.maxCompanies || 10;

        await manualDiscoveryTask.trigger({
          region: region.toUpperCase(),
          industry,
          maxCompanies,
          triggeredBy: `slack-chat:${userId}`,
        });

        await replyToSlack(
          channelId,
          `πŸš€ **Manual Discovery Triggered!**\nβ€’ *Region:* ${region.toUpperCase()}\nβ€’ *Industry:* ${industry}\nβ€’ *Max Leads:* ${maxCompanies}\n\nJaise hi leads ready honge, main isi channel me card deliver kar dunga!`,
          threadTs
        );
        break;
      }

      case "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, city, service_match),
            contacts (full_name, email, email_verified, linkedin_personal_url)
          `)
          .gte("created_at", today.toISOString())
          .order("total_score", { ascending: false });

        if (!leads?.length) {
          await replyToSlack(channelId, "πŸ“‹ Aaj ke din abhi tak koi leads qualified nahi huin.", threadTs);
          break;
        }

        const lines = leads.map((l: any, i: number) => {
          const emoji = l.tier === "hot" ? "πŸ”₯" : l.tier === "warm" ? "βœ…" : "πŸ“‹";
          const email = l.contacts?.email_verified ? "πŸ“§βœ“" : l.contacts?.email ? "πŸ“§" : "β€”";
          const li = l.contacts?.linkedin_personal_url ? "πŸ’Ό" : "β€”";
          return `${emoji} *${l.total_score}* | *${l.companies?.name ?? "?"}* | ${l.companies?.industry ?? "?"} | ${l.companies?.city ?? "?"} | ${email} ${li}`;
        });

        const reply = `*Today's Leads Summary (${leads.length}):*\n\n` +
          `Score | Company | Industry | City | Channels\n` +
          `─`.repeat(40) + `\n` +
          lines.join("\n") +
          `\n\nAap kisi bhi company ki details pooch sakte hain (e.g. "ClickUp ki details do").`;

        await replyToSlack(channelId, reply, threadTs);
        break;
      }

      case "lead_detail": {
        const companySearch = params?.companyName || "";
        if (!companySearch) {
          await replyToSlack(channelId, "Mujhe company ka naam batayein taake main detail nikal sakoon.", threadTs);
          break;
        }

        const { data: companies } = await db
          .from("companies")
          .select("*")
          .ilike("name", `%${companySearch.trim()}%`)
          .limit(1);

        if (!companies?.length) {
          await replyToSlack(channelId, `❌ Mujhe "${companySearch}" naam ki koi company database me nahi mili.`, threadTs);
          break;
        }

        const company = companies[0];
        const { data: contacts } = await db.from("contacts").select("*").eq("company_id", company.id);
        const { data: scores } = await db.from("lead_scores").select("*").eq("company_id", company.id).limit(1);
        const { data: profiles } = await db.from("lead_profiles").select("*").eq("company_id", company.id).limit(1);

        const score = scores?.[0];
        const profile = profiles?.[0];
        const contact = contacts?.[0];

        const channels: string[] = [];
        if (contact?.email) channels.push(`πŸ“§ ${contact.email} ${contact.email_verified ? "βœ“" : "(unverified)"}`);
        if (contact?.linkedin_personal_url) channels.push(`πŸ’Ό <${contact.linkedin_personal_url}|LinkedIn>`);

        const responseText = `*🏒 ${company.name}* (Domain: ${company.domain})\n` +
          `β€’ *Location:* ${company.city ?? "?"}, ${company.country ?? "?"}\n` +
          `β€’ *Industry:* ${company.industry ?? "?"} Β· *Employees:* ${company.employee_count ?? "?"}\n` +
          `β€’ *Service Match:* ${company.service_match ?? "β€”"}\n\n` +
          `*πŸ“Š AI Scoring: ${score?.total_score ?? "?"}/100 β€” ${score?.tier?.toUpperCase() ?? "?"}*\n` +
          `  - Fit: ${score?.company_fit ?? "?"}/25 Β· AI Readiness: ${score?.ai_readiness ?? "?"}/20\n` +
          `  - Service Fit: ${score?.service_match_score ?? "?"}/20 Β· Contact: ${score?.decision_maker ?? "?"}/20\n\n` +
          `*🧠 Profile Summary:*\n_${profile?.profile_summary ?? "No profile summary available."}_\n\n` +
          `*🎯 Personalized Outreach Angle:*\n_"${profile?.outreach_angle ?? "β€”"}"_\n\n` +
          `*πŸ‘€ Decision Maker:* ${contact?.full_name ?? "?"} (${contact?.title ?? "?"})\n` +
          `  - Channels: ${channels.join(" | ") || "None found"}`;

        await replyToSlack(channelId, responseText, threadTs);
        break;
      }

      case "status": {
        const { data: autoConfig } = await db.from("system_config").select("value").eq("key", "auto_mode").single();
        const paused = autoConfig?.value?.paused ?? false;

        const { data: quotaConfig } = await db.from("system_config").select("value").eq("key", "daily_quota").single();
        const quota = quotaConfig?.value;

        const { data: territory } = await db.from("system_config").select("value").eq("key", "current_territory").single();
        const pos = territory?.value;

        const { data: todayRuns } = await db
          .from("discovery_runs")
          .select("status, leads_qualified")
          .gte("ran_at", new Date(new Date().setHours(0, 0, 0, 0)).toISOString());

        const todayLeads = todayRuns?.reduce((sum: number, r: any) => sum + (r.leads_qualified ?? 0), 0) ?? 0;

        const reply = `βš™οΈ **System Status Report**\n` +
          `β€’ *Auto Runs Status:* ${paused ? "⏸️ PAUSED" : "▢️ RUNNING"}\n` +
          `β€’ *Daily Quota:* ${(quota as any)?.today_override ?? (quota as any)?.default ?? 10} leads/day\n` +
          `β€’ *Qualified Today:* ${todayLeads} leads\n` +
          `β€’ *Active Territory:* ${(pos as any)?.countryCode ?? "?"} city#${(pos as any)?.cityIndex ?? 0}\n` +
          `β€’ *Runs Executed Today:* ${todayRuns?.length ?? 0}`;

        await replyToSlack(channelId, reply, threadTs);
        break;
      }

      case "pause": {
        await db.from("system_config").update({
          value: { enabled: true, paused: true, paused_by: "slack-chat" },
          updated_at: new Date().toISOString(),
        }).eq("key", "auto_mode");

        await replyToSlack(channelId, "⏸️ **System Paused!** Daily automatic runs ko rok diya gaya hai. Jab tak aap resume nahi karenge, automatic process nahi chale ga.", threadTs);
        break;
      }

      case "resume": {
        await db.from("system_config").update({
          value: { enabled: true, paused: false, paused_by: null },
          updated_at: new Date().toISOString(),
        }).eq("key", "auto_mode");

        await replyToSlack(channelId, "▢️ **System Resumed!** Automatic runs dubara schedule par start ho gayi hain.", threadTs);
        break;
      }

      case "quota": {
        const num = params?.quotaAmount;
        if (!num || isNaN(num) || num < 1 || num > 100) {
          await replyToSlack(channelId, "Usage: 'quota 15 kar do' (max 100)", threadTs);
          break;
        }

        const permanent = !!params?.quotaPermanent;
        const key = "daily_quota";
        const { data: config } = await db.from("system_config").select("value").eq("key", key).single();
        const val = config?.value || { default: 10, today_override: null };

        if (permanent) {
          val.default = num;
          val.today_override = null;
        } else {
          val.today_override = num;
        }

        await db.from("system_config").update({
          value: val,
          updated_at: new Date().toISOString()
        }).eq("key", key);

        await replyToSlack(
          channelId,
          permanent
            ? `βœ… **Daily Quota permanently set to ${num} leads/day!**`
            : `βœ… **Today's Quota set to ${num} leads!** Kal automatic default par wapas chala jaye ga.`,
          threadTs
        );
        break;
      }

      case "chat": {
        // Chatbot replies using LLM in Roman Urdu directly
        await replyToSlack(channelId, `πŸ’¬ ${explanation}`, threadTs);
        break;
      }

      default: {
        await replyToSlack(channelId, "Mujhe aap ka naya command samajh nahi aaya. Kya aap explain kar sakte hain?", threadTs);
      }
    }
    logger.info({ intent }, "πŸ€– Chatbot action completed successfully");
  } catch (err: any) {
    logger.error({ err, intent }, "Error executing Slack AI Chatbot action");
    await replyToSlack(channelId, `❌ Action fail ho gaya: ${err.message || err}`, threadTs);
  }
}