Implement 15 platform features: digest, availability, templates, comparison, live voting SSE, file versioning, mentorship, messaging, analytics, drafts, webhooks, peer review, audit enhancements, i18n
Features implemented: - F1: Email digest notifications with cron endpoint and per-user frequency - F2: Jury availability windows and workload preferences in smart assignment - F3: Round templates with save-from-round and CRUD management - F4: Side-by-side project comparison view for jury members - F5: Real-time voting dashboard with Server-Sent Events (SSE) - F6: Live voting UX: QR codes, audience voting, tie-breaking, score animations - F7: File versioning, inline preview, bulk download with presigned URLs - F8: Mentor dashboard: milestones, private notes, activity tracking - F9: Communication hub with broadcasts, templates, and recipient targeting - F10: Advanced analytics: cross-round comparison, juror consistency, diversity metrics, PDF export - F11: Applicant draft saving with magic link resume and cron cleanup - F12: Webhook integration layer with HMAC signing, retry, and delivery logs - F13: Peer review discussions with anonymized scores and threaded comments - F14: Audit log enhancements: before/after diffs, session grouping, anomaly detection, retention - F15: i18n foundation with next-intl (EN/FR), cookie-based locale, language switcher Schema: 12 new models, field additions to User, Project, ProjectFile, LiveVotingSession, LiveVote, MentorAssignment, AuditLog, Program New routers: roundTemplate, message, webhook (registered in _app.ts) New services: email-digest, webhook-dispatcher New cron endpoints: /api/cron/digest, /api/cron/draft-cleanup, /api/cron/audit-cleanup New API routes: /api/live-voting/stream (SSE), /api/files/bulk-download All features are admin-configurable via SystemSettings or per-model settingsJson fields. Docker build verified successfully. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
276
src/server/services/email-digest.ts
Normal file
276
src/server/services/email-digest.ts
Normal file
@@ -0,0 +1,276 @@
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { sendStyledNotificationEmail } from '@/lib/email'
|
||||
|
||||
interface DigestResult {
|
||||
sent: number
|
||||
errors: number
|
||||
}
|
||||
|
||||
interface DigestSection {
|
||||
title: string
|
||||
items: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Process and send email digests for all opted-in users.
|
||||
* Called by cron endpoint.
|
||||
*/
|
||||
export async function processDigests(
|
||||
type: 'daily' | 'weekly'
|
||||
): Promise<DigestResult> {
|
||||
let sent = 0
|
||||
let errors = 0
|
||||
|
||||
// Check if digest feature is enabled
|
||||
const enabledSetting = await prisma.systemSettings.findUnique({
|
||||
where: { key: 'digest_enabled' },
|
||||
})
|
||||
if (enabledSetting?.value === 'false') {
|
||||
return { sent: 0, errors: 0 }
|
||||
}
|
||||
|
||||
// Find users who opted in for this digest frequency
|
||||
const users = await prisma.user.findMany({
|
||||
where: {
|
||||
digestFrequency: type,
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (users.length === 0) {
|
||||
return { sent: 0, errors: 0 }
|
||||
}
|
||||
|
||||
// Load enabled sections from settings
|
||||
const sectionsSetting = await prisma.systemSettings.findUnique({
|
||||
where: { key: 'digest_sections' },
|
||||
})
|
||||
const enabledSections: string[] = sectionsSetting?.value
|
||||
? JSON.parse(sectionsSetting.value)
|
||||
: ['pending_evaluations', 'upcoming_deadlines', 'new_assignments', 'unread_notifications']
|
||||
|
||||
const baseUrl = process.env.NEXTAUTH_URL || 'https://monaco-opc.com'
|
||||
|
||||
for (const user of users) {
|
||||
try {
|
||||
const content = await getDigestContent(user.id, enabledSections)
|
||||
|
||||
// Skip if there's nothing to report
|
||||
if (content.sections.length === 0) continue
|
||||
|
||||
// Build email body from sections
|
||||
const bodyParts: string[] = []
|
||||
for (const section of content.sections) {
|
||||
bodyParts.push(`**${section.title}**`)
|
||||
for (const item of section.items) {
|
||||
bodyParts.push(`- ${item}`)
|
||||
}
|
||||
bodyParts.push('')
|
||||
}
|
||||
|
||||
await sendStyledNotificationEmail(
|
||||
user.email,
|
||||
user.name || '',
|
||||
'DIGEST',
|
||||
{
|
||||
name: user.name || undefined,
|
||||
title: `Your ${type === 'daily' ? 'Daily' : 'Weekly'} Digest`,
|
||||
message: bodyParts.join('\n'),
|
||||
linkUrl: `${baseUrl}/dashboard`,
|
||||
metadata: {
|
||||
digestType: type,
|
||||
pendingEvaluations: content.pendingEvaluations,
|
||||
upcomingDeadlines: content.upcomingDeadlines,
|
||||
newAssignments: content.newAssignments,
|
||||
unreadNotifications: content.unreadNotifications,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Log the digest
|
||||
await prisma.digestLog.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
digestType: type,
|
||||
contentJson: {
|
||||
pendingEvaluations: content.pendingEvaluations,
|
||||
upcomingDeadlines: content.upcomingDeadlines,
|
||||
newAssignments: content.newAssignments,
|
||||
unreadNotifications: content.unreadNotifications,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
sent++
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[Digest] Failed to send ${type} digest to ${user.email}:`,
|
||||
error
|
||||
)
|
||||
errors++
|
||||
}
|
||||
}
|
||||
|
||||
return { sent, errors }
|
||||
}
|
||||
|
||||
/**
|
||||
* Compile digest content for a single user.
|
||||
*/
|
||||
async function getDigestContent(
|
||||
userId: string,
|
||||
enabledSections: string[]
|
||||
): Promise<{
|
||||
sections: DigestSection[]
|
||||
pendingEvaluations: number
|
||||
upcomingDeadlines: number
|
||||
newAssignments: number
|
||||
unreadNotifications: number
|
||||
}> {
|
||||
const now = new Date()
|
||||
const sections: DigestSection[] = []
|
||||
let pendingEvaluations = 0
|
||||
let upcomingDeadlines = 0
|
||||
let newAssignments = 0
|
||||
let unreadNotifications = 0
|
||||
|
||||
// 1. Pending evaluations
|
||||
if (enabledSections.includes('pending_evaluations')) {
|
||||
const pendingAssignments = await prisma.assignment.findMany({
|
||||
where: {
|
||||
userId,
|
||||
isCompleted: false,
|
||||
round: {
|
||||
status: 'ACTIVE',
|
||||
votingEndAt: { gt: now },
|
||||
},
|
||||
},
|
||||
include: {
|
||||
project: { select: { id: true, title: true } },
|
||||
round: { select: { name: true, votingEndAt: true } },
|
||||
},
|
||||
})
|
||||
|
||||
pendingEvaluations = pendingAssignments.length
|
||||
if (pendingAssignments.length > 0) {
|
||||
sections.push({
|
||||
title: `Pending Evaluations (${pendingAssignments.length})`,
|
||||
items: pendingAssignments.map(
|
||||
(a) =>
|
||||
`${a.project.title} - ${a.round.name}${
|
||||
a.round.votingEndAt
|
||||
? ` (due ${a.round.votingEndAt.toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
})})`
|
||||
: ''
|
||||
}`
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Upcoming deadlines (rounds ending within 7 days)
|
||||
if (enabledSections.includes('upcoming_deadlines')) {
|
||||
const sevenDaysFromNow = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000)
|
||||
const upcomingRounds = await prisma.round.findMany({
|
||||
where: {
|
||||
status: 'ACTIVE',
|
||||
votingEndAt: {
|
||||
gt: now,
|
||||
lte: sevenDaysFromNow,
|
||||
},
|
||||
assignments: {
|
||||
some: {
|
||||
userId,
|
||||
isCompleted: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
name: true,
|
||||
votingEndAt: true,
|
||||
},
|
||||
})
|
||||
|
||||
upcomingDeadlines = upcomingRounds.length
|
||||
if (upcomingRounds.length > 0) {
|
||||
sections.push({
|
||||
title: 'Upcoming Deadlines',
|
||||
items: upcomingRounds.map(
|
||||
(r) =>
|
||||
`${r.name} - ${r.votingEndAt?.toLocaleDateString('en-US', {
|
||||
weekday: 'short',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})}`
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 3. New assignments since last digest
|
||||
if (enabledSections.includes('new_assignments')) {
|
||||
const lastDigest = await prisma.digestLog.findFirst({
|
||||
where: { userId },
|
||||
orderBy: { sentAt: 'desc' },
|
||||
select: { sentAt: true },
|
||||
})
|
||||
|
||||
const sinceDate = lastDigest?.sentAt || new Date(now.getTime() - 24 * 60 * 60 * 1000)
|
||||
|
||||
const recentAssignments = await prisma.assignment.findMany({
|
||||
where: {
|
||||
userId,
|
||||
createdAt: { gt: sinceDate },
|
||||
},
|
||||
include: {
|
||||
project: { select: { id: true, title: true } },
|
||||
round: { select: { name: true } },
|
||||
},
|
||||
})
|
||||
|
||||
newAssignments = recentAssignments.length
|
||||
if (recentAssignments.length > 0) {
|
||||
sections.push({
|
||||
title: `New Assignments (${recentAssignments.length})`,
|
||||
items: recentAssignments.map(
|
||||
(a) => `${a.project.title} - ${a.round.name}`
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Unread notifications count
|
||||
if (enabledSections.includes('unread_notifications')) {
|
||||
const unreadCount = await prisma.inAppNotification.count({
|
||||
where: {
|
||||
userId,
|
||||
isRead: false,
|
||||
},
|
||||
})
|
||||
|
||||
unreadNotifications = unreadCount
|
||||
if (unreadCount > 0) {
|
||||
sections.push({
|
||||
title: 'Notifications',
|
||||
items: [`You have ${unreadCount} unread notification${unreadCount !== 1 ? 's' : ''}`],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sections,
|
||||
pendingEvaluations,
|
||||
upcomingDeadlines,
|
||||
newAssignments,
|
||||
unreadNotifications,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user