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
|
import { and, desc, eq, gte, inArray, sql } from "drizzle-orm";
import { db } from "./../db";
import {
gateRuns,
notifications,
pullRequests,
repositories,
users,
} from "./../db/schema";
import { sendEmail, type EmailResult } from "./email";
import { config } from "./config";
export interface DigestInput {
userId: string;
since?: Date;
send?: boolean;
}
export interface DigestBody {
subject: string;
text: string;
html: string;
counts: {
notifications: number;
failedGates: number;
repairedGates: number;
mergedPrs: number;
};
}
function fmtRange(from: Date, to: Date): string {
const f = from.toISOString().slice(0, 10);
const t = to.toISOString().slice(0, 10);
return f === t ? f : `${f} \u2192 ${t}`;
}
export async function composeDigest(
userId: string,
since?: Date
): Promise<DigestBody | null> {
const now = new Date();
const from = since || new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
try {
const [user] = await db
.select()
.from(users)
.where(eq(users.id, userId))
.limit(1);
if (!user) return null;
const notifs = await db
.select()
.from(notifications)
.where(
and(
eq(notifications.userId, userId),
gte(notifications.createdAt, from)
)
)
.orderBy(desc(notifications.createdAt))
.limit(25);
const ownedRepos = await db
.select({ id: repositories.id, name: repositories.name })
.from(repositories)
.where(eq(repositories.ownerId, userId));
const repoIds = ownedRepos.map((r) => r.id);
let failedGates: Array<{ repoName: string; gateName: string; sha: string }> = [];
let repairedGates: Array<{ repoName: string; gateName: string; sha: string }> = [];
let mergedPrs: Array<{ repoName: string; title: string }> = [];
if (repoIds.length > 0) {
const gates = await db
.select()
.from(gateRuns)
.where(
and(
inArray(gateRuns.repositoryId, repoIds),
gte(gateRuns.createdAt, from)
)
)
.orderBy(desc(gateRuns.createdAt))
.limit(50);
const byId = new Map(ownedRepos.map((r) => [r.id, r.name]));
for (const g of gates) {
const repoName = byId.get(g.repositoryId) || "?";
if (g.status === "failed") {
failedGates.push({
repoName,
gateName: g.gateName,
sha: g.commitSha.slice(0, 7),
});
} else if (g.status === "repaired") {
repairedGates.push({
repoName,
gateName: g.gateName,
sha: g.commitSha.slice(0, 7),
});
}
}
const merged = await db
.select()
.from(pullRequests)
.where(
and(
inArray(pullRequests.repositoryId, repoIds),
eq(pullRequests.state, "merged"),
gte(pullRequests.updatedAt, from)
)
)
.limit(25);
for (const pr of merged) {
mergedPrs.push({
repoName: byId.get(pr.repositoryId) || "?",
title: pr.title,
});
}
}
const counts = {
notifications: notifs.length,
failedGates: failedGates.length,
repairedGates: repairedGates.length,
mergedPrs: mergedPrs.length,
};
const base = config.appBaseUrl || "https://gluecron.com";
const subject = `Your Gluecron digest (${fmtRange(from, now)})`;
const lines: string[] = [];
lines.push(`Hi ${user.username},`);
lines.push("");
lines.push(`Here's what happened across your repos this week.`);
lines.push("");
lines.push(
`Notifications: ${counts.notifications} · Failed gates: ${counts.failedGates} · Auto-repaired: ${counts.repairedGates} · PRs merged: ${counts.mergedPrs}`
);
lines.push("");
if (notifs.length > 0) {
lines.push("## Notifications");
for (const n of notifs.slice(0, 10)) {
const when = new Date(n.createdAt).toLocaleDateString();
lines.push(`- [${n.kind}] ${n.title || "(untitled)"} — ${when}`);
}
lines.push("");
}
if (failedGates.length > 0) {
lines.push("## Failed gates");
for (const g of failedGates.slice(0, 10)) {
lines.push(`- ${g.repoName} — ${g.gateName} (${g.sha})`);
}
lines.push("");
}
if (repairedGates.length > 0) {
lines.push("## Auto-repairs");
for (const g of repairedGates.slice(0, 10)) {
lines.push(`- ${g.repoName} — ${g.gateName} (${g.sha})`);
}
lines.push("");
}
if (mergedPrs.length > 0) {
lines.push("## Merged PRs");
for (const pr of mergedPrs.slice(0, 10)) {
lines.push(`- ${pr.repoName} — ${pr.title}`);
}
lines.push("");
}
lines.push("---");
lines.push(
`You're receiving this because you opted into weekly digests. Manage at ${base}/settings.`
);
const text = lines.join("\n");
const html = textToHtml(text, base);
return { subject, text, html, counts };
} catch (err) {
console.error("[digest] composeDigest error:", err);
return null;
}
}
function textToHtml(text: string, base: string): string {
const lines = text.split("\n");
const out: string[] = [
`<html><body style="font-family:system-ui,sans-serif;max-width:640px;margin:0 auto;padding:24px;color:#111">`,
];
for (const line of lines) {
if (line.startsWith("## ")) {
out.push(
`<h3 style="border-bottom:1px solid #eee;padding-bottom:4px;margin-top:24px">${escapeHtml(line.slice(3))}</h3>`
);
} else if (line.startsWith("- ")) {
out.push(`<li>${escapeHtml(line.slice(2))}</li>`);
} else if (line === "---") {
out.push(`<hr style="border:none;border-top:1px solid #eee;margin:24px 0" />`);
} else if (line.trim() === "") {
out.push("<br>");
} else {
out.push(`<p>${escapeHtml(line)}</p>`);
}
}
out.push(
`<p style="font-size:12px;color:#777"><a href="${escapeHtml(base)}">${escapeHtml(base)}</a></p>`
);
out.push("</body></html>");
return out.join("\n");
}
function escapeHtml(s: string): string {
return s
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
export async function sendDigestForUser(
userId: string
): Promise<EmailResult | { ok: false; provider: "none"; skipped: string }> {
try {
const [user] = await db
.select()
.from(users)
.where(eq(users.id, userId))
.limit(1);
if (!user) return { ok: false, provider: "none", skipped: "user not found" };
if (!user.notifyEmailDigestWeekly) {
return { ok: false, provider: "none", skipped: "opted out" };
}
const body = await composeDigest(userId);
if (!body) {
return { ok: false, provider: "none", skipped: "compose failed" };
}
const result = await sendEmail({
to: user.email,
subject: body.subject,
text: body.text,
html: body.html,
});
if (result.ok) {
await db
.update(users)
.set({ lastDigestSentAt: new Date() })
.where(eq(users.id, userId));
}
return result;
} catch (err) {
console.error("[digest] sendDigestForUser error:", err);
return { ok: false, provider: "none", skipped: "error" };
}
}
export async function sendDigestsToAll(): Promise<
Array<{ userId: string; username: string; ok: boolean; skipped?: string }>
> {
const results: Array<{
userId: string;
username: string;
ok: boolean;
skipped?: string;
}> = [];
try {
const opted = await db
.select({ id: users.id, username: users.username })
.from(users)
.where(eq(users.notifyEmailDigestWeekly, true));
for (const u of opted) {
const r = await sendDigestForUser(u.id);
results.push({
userId: u.id,
username: u.username,
ok: r.ok,
skipped: "skipped" in r ? r.skipped : undefined,
});
}
} catch (err) {
console.error("[digest] sendDigestsToAll error:", err);
}
return results;
}
export const __internal = { textToHtml, escapeHtml, fmtRange };
void sql;
|