|
| 1 | +import { and, db, eq, isNull } from "@databuddy/db"; |
| 2 | +import { |
| 3 | + type InsightDelivery, |
| 4 | + insightGenerationConfigs, |
| 5 | + slackIntegrations, |
| 6 | +} from "@databuddy/db/schema"; |
| 7 | +import { decrypt } from "@databuddy/encryption"; |
| 8 | +import { env } from "@databuddy/env/insights"; |
| 9 | +import { captureInsightsError, emitInsightsEvent } from "./lib/evlog-insights"; |
| 10 | + |
| 11 | +const SLACK_POST_URL = "https://slack.com/api/chat.postMessage"; |
| 12 | +const MAX_DIGEST_INSIGHTS = 5; |
| 13 | +const SLACK_HEADER_MAX = 150; |
| 14 | +const SLACK_SECTION_TEXT_MAX = 3000; |
| 15 | + |
| 16 | +function truncate(value: string, max: number): string { |
| 17 | + return value.length > max ? `${value.slice(0, max - 1)}…` : value; |
| 18 | +} |
| 19 | + |
| 20 | +interface DigestInsight { |
| 21 | + description: string; |
| 22 | + severity: string; |
| 23 | + suggestion: string; |
| 24 | + title: string; |
| 25 | +} |
| 26 | + |
| 27 | +interface SlackBlock { |
| 28 | + text?: { text: string; type: string }; |
| 29 | + type: string; |
| 30 | +} |
| 31 | + |
| 32 | +function escapeMrkdwn(value: string): string { |
| 33 | + return value |
| 34 | + .replaceAll("&", "&") |
| 35 | + .replaceAll("<", "<") |
| 36 | + .replaceAll(">", ">"); |
| 37 | +} |
| 38 | + |
| 39 | +async function resolveDeliveries( |
| 40 | + organizationId: string, |
| 41 | + websiteId: string |
| 42 | +): Promise<InsightDelivery[]> { |
| 43 | + const [websiteConfig] = await db |
| 44 | + .select({ deliveries: insightGenerationConfigs.deliveries }) |
| 45 | + .from(insightGenerationConfigs) |
| 46 | + .where( |
| 47 | + and( |
| 48 | + eq(insightGenerationConfigs.organizationId, organizationId), |
| 49 | + eq(insightGenerationConfigs.websiteId, websiteId) |
| 50 | + ) |
| 51 | + ) |
| 52 | + .limit(1); |
| 53 | + if (websiteConfig) { |
| 54 | + return websiteConfig.deliveries; |
| 55 | + } |
| 56 | + |
| 57 | + const [orgConfig] = await db |
| 58 | + .select({ deliveries: insightGenerationConfigs.deliveries }) |
| 59 | + .from(insightGenerationConfigs) |
| 60 | + .where( |
| 61 | + and( |
| 62 | + eq(insightGenerationConfigs.organizationId, organizationId), |
| 63 | + isNull(insightGenerationConfigs.websiteId) |
| 64 | + ) |
| 65 | + ) |
| 66 | + .limit(1); |
| 67 | + return orgConfig?.deliveries ?? []; |
| 68 | +} |
| 69 | + |
| 70 | +async function loadBotToken(organizationId: string): Promise<string | null> { |
| 71 | + const key = env.DATABUDDY_ENCRYPTION_KEY; |
| 72 | + if (!key) { |
| 73 | + return null; |
| 74 | + } |
| 75 | + const [integration] = await db |
| 76 | + .select({ ciphertext: slackIntegrations.botTokenCiphertext }) |
| 77 | + .from(slackIntegrations) |
| 78 | + .where( |
| 79 | + and( |
| 80 | + eq(slackIntegrations.organizationId, organizationId), |
| 81 | + eq(slackIntegrations.status, "active") |
| 82 | + ) |
| 83 | + ) |
| 84 | + .limit(1); |
| 85 | + if (!integration) { |
| 86 | + return null; |
| 87 | + } |
| 88 | + return decrypt(integration.ciphertext, key); |
| 89 | +} |
| 90 | + |
| 91 | +function buildBlocks( |
| 92 | + websiteDomain: string, |
| 93 | + insights: DigestInsight[] |
| 94 | +): SlackBlock[] { |
| 95 | + const blocks: SlackBlock[] = [ |
| 96 | + { |
| 97 | + type: "header", |
| 98 | + text: { |
| 99 | + type: "plain_text", |
| 100 | + text: truncate(`Insights for ${websiteDomain}`, SLACK_HEADER_MAX), |
| 101 | + }, |
| 102 | + }, |
| 103 | + ]; |
| 104 | + for (const insight of insights.slice(0, MAX_DIGEST_INSIGHTS)) { |
| 105 | + blocks.push({ |
| 106 | + type: "section", |
| 107 | + text: { |
| 108 | + type: "mrkdwn", |
| 109 | + text: truncate( |
| 110 | + `*${escapeMrkdwn(insight.title)}*\n${escapeMrkdwn(insight.description)}\n_${escapeMrkdwn(insight.suggestion)}_`, |
| 111 | + SLACK_SECTION_TEXT_MAX |
| 112 | + ), |
| 113 | + }, |
| 114 | + }); |
| 115 | + } |
| 116 | + return blocks; |
| 117 | +} |
| 118 | + |
| 119 | +async function postToSlack( |
| 120 | + token: string, |
| 121 | + channelId: string, |
| 122 | + blocks: SlackBlock[], |
| 123 | + text: string |
| 124 | +): Promise<void> { |
| 125 | + const res = await fetch(SLACK_POST_URL, { |
| 126 | + method: "POST", |
| 127 | + headers: { |
| 128 | + "Content-Type": "application/json", |
| 129 | + Authorization: `Bearer ${token}`, |
| 130 | + }, |
| 131 | + body: JSON.stringify({ channel: channelId, blocks, text }), |
| 132 | + }); |
| 133 | + const body = (await res.json()) as { ok: boolean; error?: string }; |
| 134 | + if (!body.ok) { |
| 135 | + throw new Error( |
| 136 | + `slack chat.postMessage failed: ${body.error ?? "unknown_error"}` |
| 137 | + ); |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +export async function deliverInsightDigests(params: { |
| 142 | + insights: DigestInsight[]; |
| 143 | + organizationId: string; |
| 144 | + websiteDomain: string; |
| 145 | + websiteId: string; |
| 146 | +}): Promise<void> { |
| 147 | + if (params.insights.length === 0) { |
| 148 | + return; |
| 149 | + } |
| 150 | + |
| 151 | + const deliveries = await resolveDeliveries( |
| 152 | + params.organizationId, |
| 153 | + params.websiteId |
| 154 | + ); |
| 155 | + const slackChannelIds = [ |
| 156 | + ...new Set( |
| 157 | + deliveries.filter((d) => d.type === "slack").map((d) => d.channelId) |
| 158 | + ), |
| 159 | + ]; |
| 160 | + if (slackChannelIds.length === 0) { |
| 161 | + return; |
| 162 | + } |
| 163 | + |
| 164 | + const token = await loadBotToken(params.organizationId); |
| 165 | + if (!token) { |
| 166 | + emitInsightsEvent("warn", "delivery.slack.skipped_no_integration", { |
| 167 | + organization_id: params.organizationId, |
| 168 | + website_id: params.websiteId, |
| 169 | + delivery_count: slackChannelIds.length, |
| 170 | + }); |
| 171 | + return; |
| 172 | + } |
| 173 | + |
| 174 | + const blocks = buildBlocks(params.websiteDomain, params.insights); |
| 175 | + const text = `Insights for ${params.websiteDomain}`; |
| 176 | + for (const channelId of slackChannelIds) { |
| 177 | + try { |
| 178 | + await postToSlack(token, channelId, blocks, text); |
| 179 | + emitInsightsEvent("info", "delivery.slack.posted", { |
| 180 | + organization_id: params.organizationId, |
| 181 | + website_id: params.websiteId, |
| 182 | + slack_channel_id: channelId, |
| 183 | + insight_count: Math.min(params.insights.length, MAX_DIGEST_INSIGHTS), |
| 184 | + }); |
| 185 | + } catch (error) { |
| 186 | + captureInsightsError(error, "delivery.slack.failed", { |
| 187 | + organization_id: params.organizationId, |
| 188 | + website_id: params.websiteId, |
| 189 | + slack_channel_id: channelId, |
| 190 | + }); |
| 191 | + } |
| 192 | + } |
| 193 | +} |
0 commit comments