Files
community-rule/lib/server/ruleFollowUp.ts
T

110 lines
2.9 KiB
TypeScript

import type { PrismaClient } from "@prisma/client";
import { logger } from "../logger";
import { originFromHost } from "../siteMetadata";
import { ruleExportMarkdownUrl, ruleExportPdfUrl } from "../sharePaths";
import { getSessionPepper } from "./env";
import { sendRuleFollowUpEmail } from "./mail";
import { ruleExportToken } from "./ruleExportToken";
export const RULE_FOLLOW_UP_AFTER_MS = 48 * 60 * 60 * 1000;
export type RuleFollowUpResult = {
sent: number;
failed: number;
skipped: number;
};
export async function sendDueRuleFollowUpEmails(
db: PrismaClient,
now = new Date(),
): Promise<RuleFollowUpResult> {
const result: RuleFollowUpResult = { sent: 0, failed: 0, skipped: 0 };
let pepper: string;
try {
pepper = getSessionPepper();
} catch (err) {
logger.error({
scope: "ruleFollowUp",
message: err instanceof Error ? err.message : "SESSION_SECRET missing",
});
return result;
}
const origin = originFromHost(null);
const dueBy = new Date(now.getTime() - RULE_FOLLOW_UP_AFTER_MS);
// Rules finished more than seven days before this mail existed are stamped
// in the migration. Anything still unsent stays eligible until claimed, so
// a long scheduler outage does not drop the follow-up.
const rows = await db.publishedRule.findMany({
where: {
followUpEmailSentAt: null,
userId: { not: null },
createdAt: { lte: dueBy },
},
select: {
id: true,
title: true,
user: { select: { email: true } },
},
});
for (const row of rows) {
const email = row.user?.email?.trim().toLowerCase() ?? "";
if (!email.includes("@")) {
result.skipped += 1;
continue;
}
const claimed = await db.publishedRule.updateMany({
where: { id: row.id, followUpEmailSentAt: null },
data: { followUpEmailSentAt: now },
});
if (claimed.count !== 1) {
result.skipped += 1;
continue;
}
const token = ruleExportToken(row.id, pepper);
try {
await sendRuleFollowUpEmail({
to: email,
origin,
communityName: row.title,
pdfUrl: ruleExportPdfUrl(origin, row.id, token),
markdownUrl: ruleExportMarkdownUrl(origin, row.id, token),
});
result.sent += 1;
} catch (err) {
result.failed += 1;
logger.error({
scope: "ruleFollowUp",
message: err instanceof Error ? err.message : "send failed",
});
try {
await db.publishedRule.updateMany({
where: { id: row.id, followUpEmailSentAt: now },
data: { followUpEmailSentAt: null },
});
} catch (releaseErr) {
logger.error({
scope: "ruleFollowUp",
message:
releaseErr instanceof Error
? releaseErr.message
: "claim release failed",
});
}
}
}
logger.info({
scope: "ruleFollowUp",
sent: result.sent,
failed: result.failed,
skipped: result.skipped,
});
return result;
}