// BotCompany โ€” NOTIFIER-01: builds + fires webhook payloads, keeps a feed, // and emails verdict alerts to the boss's Gmail (SMTP app-password channel). // Server-only. import { webhookMeta } from "./business"; import { MAX_WEBHOOK_FEED, getState } from "./store"; import type { Lead, LeadStatus, WebhookBody, WebhookEntry } from "./types"; export function buildBody(lead: Lead, event: string): WebhookBody { return { event, lead: { business: lead.business, owner: lead.owner, phone: lead.phone, city: lead.city, niche: lead.niche, status: lead.status as LeadStatus, score: lead.score, callSlot: lead.callSlot, }, ...webhookMeta(), }; } /** Email the boss via Gmail SMTP (app password). Never throws. */ async function emailBoss(entry: WebhookBody, event: string): Promise { const { notifyEmail, gmailAppPassword } = getState().settings; if (!notifyEmail || !gmailAppPassword) return false; try { const nodemailer = (await import("nodemailer")) as unknown as { createTransport: (opts: Record) => { sendMail: (mail: Record) => Promise; }; }; const transport = nodemailer.createTransport({ host: "smtp.gmail.com", port: 465, secure: true, auth: { user: notifyEmail, pass: gmailAppPassword }, }); const l = entry.lead; const ready = event.startsWith("lead.ready"); await transport.sendMail({ from: `"BotCompany Ops" <${notifyEmail}>`, to: notifyEmail, subject: ready ? `๐Ÿ”” READY: ${l.business} โ€” call ${l.callSlot ?? "slot pending"} (score ${l.score})` : `BotCompany verdict: ${l.business} โ†’ ${l.status}`, text: [ `Client: ${l.owner} ยท ${l.business} (${l.niche}, ${l.city})`, `Phone: ${l.phone}`, `Status: ${l.status} ยท score ${l.score}/100`, l.callSlot ? `Allocated call slot: ${l.callSlot}` : "", "", `Offer: ${entry.offer.price} + ${entry.offer.terms}`, `WhatsApp: ${entry.from.waLink}`, ] .filter(Boolean) .join("\n"), }); return true; } catch { return false; } } /** * Push an entry to the visible feed; POST it to the configured target if any; * email the boss if Gmail notify is configured. Never throws. */ export async function fireWebhook(lead: Lead, event: string): Promise { const state = getState(); const body = buildBody(lead, event); const target = state.settings.webhookUrl.trim(); const entry: WebhookEntry = { id: `wh_${Date.now()}_${Math.floor(Math.random() * 1e6)}`, at: Date.now(), event, target: target || "(feed only โ€” no target configured)", delivered: false, body, }; if (target) { try { const res = await fetch(target, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(3500), }); entry.delivered = res.ok; } catch { entry.delivered = false; } } entry.emailed = await emailBoss(body, event); state.webhooks.unshift(entry); if (state.webhooks.length > MAX_WEBHOOK_FEED) state.webhooks.length = MAX_WEBHOOK_FEED; state.stats.webhooksFired += 1; return entry; }