swadhinbiswas chore: update src/lib/chat-notifications.ts · 2/18/2026
7640c46
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
/**
* Chat & Notification Integrations Library
* Microsoft Teams, Discord, Enhanced Email
*/
import { pgTable, text, timestamp, boolean, jsonb } from "drizzle-orm/pg-core";
import { getDatabase, schema } from "@/db";
import { eq, and, gte, inArray, desc } from "drizzle-orm";
import { logger } from "./logger";
import { repositories } from "@/db/schema/repositories";
// ============================================================================
// SCHEMA
// ============================================================================
export const chatIntegrations = pgTable("chat_integrations", {
id: text("id").primaryKey(),
repositoryId: text("repository_id")
.references(() => repositories.id, { onDelete: "cascade" }),
organizationId: text("organization_id"),
provider: text("provider").notNull(), // slack, teams, discord, email
name: text("name").notNull(),
webhookUrl: text("webhook_url"),
apiToken: text("api_token"),
channelId: text("channel_id"),
isEnabled: boolean("is_enabled").default(true),
events: jsonb("events").$type<string[]>().default([]),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
});
export const emailSettings = pgTable("email_settings", {
id: text("id").primaryKey(),
organizationId: text("organization_id"),
smtpHost: text("smtp_host"),
smtpPort: text("smtp_port"),
smtpUser: text("smtp_user"),
smtpPass: text("smtp_pass"), // Encrypted
fromAddress: text("from_address"),
fromName: text("from_name"),
isEnabled: boolean("is_enabled").default(true),
createdAt: timestamp("created_at").notNull().defaultNow(),
});
export type ChatIntegration = typeof chatIntegrations.$inferSelect;
export type EmailSettings = typeof emailSettings.$inferSelect;
// ============================================================================
// NOTIFICATION EVENT TYPES
// ============================================================================
export type NotificationEvent =
| "pr_opened"
| "pr_merged"
| "pr_closed"
| "pr_review_requested"
| "pr_review_submitted"
| "pr_comment"
| "issue_opened"
| "issue_closed"
| "issue_assigned"
| "ci_failed"
| "ci_passed"
| "deploy_started"
| "deploy_completed"
| "security_alert";
export interface NotificationPayload {
event: NotificationEvent;
title: string;
message: string;
url?: string;
actor?: { name: string; avatar?: string };
repository?: { name: string; url: string };
metadata?: Record<string, unknown>;
}
// ============================================================================
// MICROSOFT TEAMS INTEGRATION
// ============================================================================
export async function sendTeamsNotification(
webhookUrl: string,
payload: NotificationPayload
): Promise<boolean> {
try {
const card = buildTeamsAdaptiveCard(payload);
const response = await fetch(webhookUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(card),
});
if (!response.ok) {
logger.error({ status: response.status }, "Teams notification failed");
return false;
}
return true;
} catch (error) {
logger.error({ error }, "Teams notification error");
return false;
}
}
function buildTeamsAdaptiveCard(payload: NotificationPayload): Record<string, unknown> {
const themeColor = getEventColor(payload.event);
return {
"@type": "MessageCard",
"@context": "http://schema.org/extensions",
themeColor,
summary: payload.title,
sections: [
{
activityTitle: payload.title,
activitySubtitle: payload.repository?.name || "",
activityImage: payload.actor?.avatar,
facts: [
{ name: "Event", value: formatEventName(payload.event) },
...(payload.actor ? [{ name: "By", value: payload.actor.name }] : []),
],
markdown: true,
text: payload.message,
},
],
potentialAction: payload.url
? [
{
"@type": "OpenUri",
name: "View Details",
targets: [{ os: "default", uri: payload.url }],
},
]
: [],
};
}
// ============================================================================
// DISCORD INTEGRATION
// ============================================================================
export async function sendDiscordNotification(
webhookUrl: string,
payload: NotificationPayload
): Promise<boolean> {
try {
const embed = buildDiscordEmbed(payload);
const response = await fetch(webhookUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ embeds: [embed] }),
});
if (!response.ok) {
logger.error({ status: response.status }, "Discord notification failed");
return false;
}
return true;
} catch (error) {
logger.error({ error }, "Discord notification error");
return false;
}
}
function buildDiscordEmbed(payload: NotificationPayload): Record<string, unknown> {
const color = getEventColorInt(payload.event);
return {
title: payload.title,
description: payload.message,
url: payload.url,
color,
author: payload.actor
? {
name: payload.actor.name,
icon_url: payload.actor.avatar,
}
: undefined,
footer: payload.repository
? {
text: payload.repository.name,
}
: undefined,
timestamp: new Date().toISOString(),
fields: [
{
name: "Event",
value: formatEventName(payload.event),
inline: true,
},
],
};
}
// ============================================================================
// ENHANCED EMAIL INTEGRATION
// ============================================================================
export interface EmailOptions {
to: string | string[];
subject: string;
html?: string;
text?: string;
replyTo?: string;
cc?: string[];
bcc?: string[];
attachments?: { filename: string; content: string | Buffer }[];
}
export async function sendEmail(
settings: EmailSettings,
options: EmailOptions
): Promise<boolean> {
if (!settings.isEnabled || !settings.smtpHost) {
logger.warn("Email not configured");
return false;
}
try {
// Use nodemailer-like interface
const transport = createTransport(settings);
await transport.sendMail({
from: `${settings.fromName} <${settings.fromAddress}>`,
to: Array.isArray(options.to) ? options.to.join(", ") : options.to,
subject: options.subject,
html: options.html,
text: options.text,
replyTo: options.replyTo,
cc: options.cc?.join(", "),
bcc: options.bcc?.join(", "),
});
return true;
} catch (error) {
logger.error({ error }, "Email send failed");
return false;
}
}
function createTransport(settings: EmailSettings) {
// Simulated transport - in production use nodemailer
return {
sendMail: async (options: Record<string, unknown>) => {
// SMTP connection logic
const response = await fetch(`https://${settings.smtpHost}:${settings.smtpPort}/send`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Basic ${Buffer.from(`${settings.smtpUser}:${settings.smtpPass}`).toString("base64")}`,
},
body: JSON.stringify(options),
});
if (!response.ok) throw new Error("SMTP error");
return response;
},
};
}
export function buildNotificationEmail(payload: NotificationPayload): { subject: string; html: string } {
const eventName = formatEventName(payload.event);
const subject = `[${payload.repository?.name || "OpenCodeHub"}] ${payload.title}`;
const html = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }
.container { max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.header { background: ${getEventColor(payload.event)}; color: white; padding: 20px; }
.header h1 { margin: 0; font-size: 18px; }
.content { padding: 20px; }
.actor { display: flex; align-items: center; margin-bottom: 16px; }
.actor img { width: 40px; height: 40px; border-radius: 50%; margin-right: 12px; }
.message { color: #333; line-height: 1.6; }
.button { display: inline-block; background: #0066cc; color: white; padding: 10px 20px; text-decoration: none; border-radius: 4px; margin-top: 16px; }
.footer { padding: 16px 20px; background: #f9f9f9; border-top: 1px solid #eee; font-size: 12px; color: #666; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>${eventName}</h1>
</div>
<div class="content">
${payload.actor ? `
<div class="actor">
${payload.actor.avatar ? `<img src="${payload.actor.avatar}" alt="${payload.actor.name}">` : ""}
<strong>${payload.actor.name}</strong>
</div>
` : ""}
<h2>${payload.title}</h2>
<p class="message">${payload.message}</p>
${payload.url ? `<a href="${payload.url}" class="button">View Details</a>` : ""}
</div>
<div class="footer">
${payload.repository ? `Repository: ${payload.repository.name}` : ""}
</div>
</div>
</body>
</html>`;
return { subject, html };
}
// ============================================================================
// UNIFIED NOTIFICATION DISPATCH
// ============================================================================
export async function dispatchNotification(
repositoryId: string,
payload: NotificationPayload
): Promise<{ sent: number; failed: number }> {
const db = getDatabase();
let sent = 0;
let failed = 0;
try {
const integrations = await db.query.chatIntegrations?.findMany({
where: and(
eq(schema.chatIntegrations.repositoryId, repositoryId),
eq(schema.chatIntegrations.isEnabled, true)
),
}) || [];
for (const integration of integrations) {
// Check if this integration wants this event
const events = (integration.events as string[]) || [];
if (events.length > 0 && !events.includes(payload.event)) {
continue;
}
let success = false;
switch (integration.provider) {
case "slack":
success = await sendSlackNotification(integration.webhookUrl || "", payload);
break;
case "teams":
success = await sendTeamsNotification(integration.webhookUrl || "", payload);
break;
case "discord":
success = await sendDiscordNotification(integration.webhookUrl || "", payload);
break;
}
if (success) sent++;
else failed++;
}
} catch (error) {
logger.error({ error }, "Notification dispatch failed");
}
return { sent, failed };
}
// Slack notification (wrapper for existing implementation)
async function sendSlackNotification(webhookUrl: string, payload: NotificationPayload): Promise<boolean> {
try {
const response = await fetch(webhookUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
attachments: [
{
color: getEventColor(payload.event),
author_name: payload.actor?.name,
author_icon: payload.actor?.avatar,
title: payload.title,
title_link: payload.url,
text: payload.message,
footer: payload.repository?.name,
ts: Math.floor(Date.now() / 1000),
},
],
}),
});
return response.ok;
} catch {
return false;
}
}
// ============================================================================
// CONFIGURATION FUNCTIONS
// ============================================================================
export async function configureChatIntegration(options: {
repositoryId?: string;
organizationId?: string;
provider: "slack" | "teams" | "discord";
name: string;
webhookUrl: string;
events?: NotificationEvent[];
}): Promise<ChatIntegration> {
const db = getDatabase();
const integration = {
id: crypto.randomUUID(),
repositoryId: options.repositoryId || null,
organizationId: options.organizationId || null,
provider: options.provider,
name: options.name,
webhookUrl: options.webhookUrl,
apiToken: null,
channelId: null,
isEnabled: true,
events: options.events || [],
createdAt: new Date(),
updatedAt: new Date(),
};
// @ts-expect-error - Drizzle multi-db union type issue
await db.insert(schema.chatIntegrations).values(integration);
logger.info({ provider: options.provider }, "Chat integration configured");
return integration as ChatIntegration;
}
export async function configureEmailSettings(options: {
organizationId?: string;
smtpHost: string;
smtpPort: string;
smtpUser: string;
smtpPass: string;
fromAddress: string;
fromName: string;
}): Promise<EmailSettings> {
const db = getDatabase();
const settings = {
id: crypto.randomUUID(),
organizationId: options.organizationId || null,
smtpHost: options.smtpHost,
smtpPort: options.smtpPort,
smtpUser: options.smtpUser,
smtpPass: options.smtpPass,
fromAddress: options.fromAddress,
fromName: options.fromName,
isEnabled: true,
createdAt: new Date(),
};
// @ts-expect-error - Drizzle multi-db union type issue
await db.insert(schema.emailSettings).values(settings);
logger.info("Email settings configured");
return settings as EmailSettings;
}
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
function getEventColor(event: NotificationEvent): string {
const colors: Record<string, string> = {
pr_opened: "#6f42c1",
pr_merged: "#28a745",
pr_closed: "#dc3545",
pr_review_requested: "#fd7e14",
pr_review_submitted: "#17a2b8",
pr_comment: "#6c757d",
issue_opened: "#28a745",
issue_closed: "#6c757d",
issue_assigned: "#17a2b8",
ci_failed: "#dc3545",
ci_passed: "#28a745",
deploy_started: "#fd7e14",
deploy_completed: "#28a745",
security_alert: "#dc3545",
};
return colors[event] || "#6c757d";
}
function getEventColorInt(event: NotificationEvent): number {
const hex = getEventColor(event).replace("#", "");
return parseInt(hex, 16);
}
function formatEventName(event: NotificationEvent): string {
const names: Record<string, string> = {
pr_opened: "Pull Request Opened",
pr_merged: "Pull Request Merged",
pr_closed: "Pull Request Closed",
pr_review_requested: "Review Requested",
pr_review_submitted: "Review Submitted",
pr_comment: "New Comment",
issue_opened: "Issue Opened",
issue_closed: "Issue Closed",
issue_assigned: "Issue Assigned",
ci_failed: "CI Failed",
ci_passed: "CI Passed",
deploy_started: "Deployment Started",
deploy_completed: "Deployment Completed",
security_alert: "Security Alert",
};
return names[event] || event;
}
// ============================================================================
// DIGEST EMAILS
// ============================================================================
export interface DigestOptions {
userId: string;
period: "daily" | "weekly";
includeEvents: NotificationEvent[];
}
export async function generateDigestEmail(options: DigestOptions): Promise<{
subject: string;
html: string;
itemCount: number;
}> {
const db = getDatabase();
const now = new Date();
const from = new Date(now);
if (options.period === "daily") {
from.setDate(from.getDate() - 1);
} else {
from.setDate(from.getDate() - 7);
}
const whereClauses = [
eq(schema.notifications.userId, options.userId),
gte(schema.notifications.createdAt, from),
eq(schema.notifications.isArchived, false),
];
if (options.includeEvents.length > 0) {
whereClauses.push(inArray(schema.notifications.type, options.includeEvents));
}
const notifications = await db.query.notifications.findMany({
where: and(...whereClauses),
orderBy: [desc(schema.notifications.createdAt)],
with: {
repository: true,
actor: true,
},
limit: 50,
});
const periodLabel = options.period === "daily" ? "Daily" : "Weekly";
const itemCount = notifications.length;
const unreadCount = notifications.filter((n) => !n.isRead).length;
const eventCounts = new Map<string, number>();
for (const n of notifications) {
eventCounts.set(n.type, (eventCounts.get(n.type) || 0) + 1);
}
const escapeHtml = (value: string) =>
value
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
const subject = `Your ${periodLabel} OpenCodeHub Digest`;
const summaryItems = Array.from(eventCounts.entries())
.sort((a, b) => b[1] - a[1])
.map(([event, count]) => `<li><strong>${count}</strong> ${escapeHtml(formatEventName(event as NotificationEvent))}</li>`)
.join("");
const itemRows = notifications
.slice(0, 20)
.map((n) => {
const title = escapeHtml(n.title);
const body = escapeHtml(n.body || "");
const repo = n.repository?.name ? ` in ${escapeHtml(n.repository.name)}` : "";
const actor = n.actor?.username ? ` by ${escapeHtml(n.actor.username)}` : "";
const url = n.url || "#";
const createdAt = n.createdAt.toISOString().replace("T", " ").slice(0, 16);
return `
<div class="item">
<div class="item-icon">•</div>
<div class="item-content">
<div><a href="${escapeHtml(url)}" style="color:#111;text-decoration:none;"><strong>${title}</strong></a></div>
<div style="color:#666;font-size:13px;">${escapeHtml(formatEventName(n.type as NotificationEvent))}${repo}${actor}</div>
${body ? `<div style="color:#444;font-size:13px;margin-top:4px;">${body}</div>` : ""}
<div style="color:#999;font-size:12px;margin-top:4px;">${createdAt}</div>
</div>
</div>`;
})
.join("");
const html = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }
.container { max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden; }
.header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px 20px; text-align: center; }
.header h1 { margin: 0; font-size: 24px; }
.section { padding: 20px; border-bottom: 1px solid #eee; }
.section h2 { margin: 0 0 16px; font-size: 16px; color: #333; }
.item { display: flex; padding: 8px 0; border-bottom: 1px solid #f0f0f0; }
.item:last-child { border-bottom: none; }
.item-icon { width: 24px; margin-right: 12px; }
.item-content { flex: 1; }
.footer { padding: 20px; text-align: center; font-size: 12px; color: #666; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>${periodLabel} Digest</h1>
<p>${itemCount} notification${itemCount === 1 ? "" : "s"} (${unreadCount} unread)</p>
</div>
<div class="section">
<h2>📬 Activity Summary</h2>
${summaryItems ? `<ul>${summaryItems}</ul>` : "<p>No notifications for this period.</p>"}
</div>
<div class="section">
<h2>📝 Recent Items</h2>
${itemRows || "<p>No recent items.</p>"}
</div>
<div class="footer">
<p>You're receiving this because you subscribed to ${options.period} digests.</p>
<a href="#">Manage notification preferences</a>
</div>
</div>
</body>
</html>`;
return { subject, html, itemCount };
}