Files
zhuiguang-ai/scripts/notification-digest.mjs

186 lines
5.1 KiB
JavaScript

// 每日 09:00 运行:为活跃用户生成通知摘要
// Daily notification digest for active users
import { PrismaClient } from "@prisma/client";
import { PrismaMariaDb } from "@prisma/adapter-mariadb";
import "dotenv/config";
const base = (process.env.DATABASE_URL || "mysql://localhost:3306/zhuiguang_ai?charset=utf8mb4")
.replace("mysql://", "mariadb://");
const sep = base.includes("?") ? "&" : "?";
const connectionString = `${base}${sep}connection_limit=5&pool_timeout=15`;
const adapter = new PrismaMariaDb(connectionString);
const prisma = new PrismaClient({ adapter });
// Map NotifType enum values to human-readable Chinese labels
const TYPE_LABEL = {
COMMENT_REPLY: "新回复",
COMMENT_LIKE: "评论点赞",
TOPIC_REPLY: "话题回复",
MENTION: "提及",
BEST_ANSWER: "最佳答案",
POST_LIKE: "点赞",
TOPIC_LIKE: "话题点赞",
SYSTEM: "系统通知",
DIGEST: "摘要",
};
async function main() {
const taskKey = "notification-digest";
const taskName = "通知摘要生成";
const startedAt = new Date();
// Step 1: Find active users - users with activity in the last 7 days
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 3600 * 1000);
// Get users who have notifications or recent profile updates (proxy for active)
const activeUserIds = await prisma.notification.findMany({
where: {
createdAt: { gte: sevenDaysAgo },
type: { notIn: ["DIGEST"] },
},
distinct: ["userId"],
select: { userId: true },
});
console.log(
`[notification-digest] 找到 ${activeUserIds.length} 位活跃用户(近7天有通知)`
);
// Step 2: For each active user, check their notification prefs and compile digest
const past24h = new Date(Date.now() - 24 * 3600 * 1000);
let digestCreated = 0;
let usersSkipped = 0;
let totalDigested = 0;
for (const { userId } of activeUserIds) {
// Check preferences
const prefKey = `notif_prefs_${userId}`;
const prefConfig = await prisma.systemConfig.findUnique({
where: { key: prefKey },
});
let prefs = {
digestMode: "realtime",
channels: {},
quietHours: { enabled: false, start: "22:00", end: "08:00" },
};
if (prefConfig) {
try {
prefs = { ...prefs, ...(prefConfig.value || {}) };
} catch {
// fall back to defaults
}
}
// Skip users who want real-time notifications
if (prefs.digestMode === "realtime") {
usersSkipped++;
continue;
}
// Step 3: Compile their unread notifications from the past 24h (or past 7 days for weekly)
const digestWindow =
prefs.digestMode === "weekly"
? new Date(Date.now() - 7 * 24 * 3600 * 1000)
: past24h;
const recentNotifs = await prisma.notification.findMany({
where: {
userId,
type: { notIn: ["DIGEST"] },
isRead: false,
createdAt: { gte: digestWindow },
},
orderBy: { createdAt: "desc" },
});
if (recentNotifs.length === 0) {
usersSkipped++;
continue;
}
// Group by type
const typeCounts = {};
for (const n of recentNotifs) {
const label = TYPE_LABEL[n.type] || n.type;
typeCounts[label] = (typeCounts[label] || 0) + 1;
}
// Build summary message
const parts = Object.entries(typeCounts).map(
([label, count]) => `${count} 条${label}`
);
const modeLabel =
prefs.digestMode === "weekly" ? "本周" : "今天";
const title = `${modeLabel}你有 ${recentNotifs.length} 条新通知`;
const content = parts.join("、");
// Create the digest notification
try {
await prisma.notification.create({
data: {
userId,
type: "DIGEST",
title,
content,
link: "/notifications",
isRead: false,
},
});
digestCreated++;
totalDigested += recentNotifs.length;
} catch (err) {
console.error(`[notification-digest] 为用户 ${userId} 创建摘要失败:`, err.message);
}
}
const finishedAt = new Date();
const duration = Math.round((finishedAt - startedAt) / 1000);
console.log(
`[notification-digest] 完成: 创建 ${digestCreated} 条摘要,覆盖 ${totalDigested} 条通知,跳过 ${usersSkipped} 位用户,耗时 ${duration}s`
);
// Step 4: Log to TaskLog
await prisma.taskLog.create({
data: {
taskKey,
taskName,
status: "completed",
startedAt,
finishedAt,
duration,
result: {
activeUsers: activeUserIds.length,
digestCreated,
totalDigested,
usersSkipped,
},
},
});
await prisma.$disconnect();
}
main().catch(async (e) => {
console.error("[notification-digest] 执行失败:", e.message);
try {
await prisma.taskLog.create({
data: {
taskKey: "notification-digest",
taskName: "通知摘要生成",
status: "failed",
startedAt: new Date(),
finishedAt: new Date(),
duration: 0,
error: e.message?.slice(0, 500),
},
});
} catch {}
if (prisma) await prisma.$disconnect();
process.exit(1);
});