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:
2026-02-05 23:31:41 +01:00
parent f038c95777
commit 59436ed67a
68 changed files with 14541 additions and 546 deletions

View 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,
}
}

View File

@@ -4,20 +4,22 @@
* Calculates scores for jury/mentor-project matching based on:
* - Tag overlap (expertise match)
* - Bio/description match (text similarity)
* - Workload balance
* - Workload balance (respects preferredWorkload and maxAssignments)
* - Country match (mentors only)
* - Geographic diversity penalty (prevents clustering by country)
* - Previous round familiarity bonus (continuity across rounds)
* - COI penalty (conflict of interest hard-block)
* - Availability window check (F2: penalizes jurors unavailable during voting)
*
* Score Breakdown:
* - Tag overlap: 0-40 points (weighted by confidence)
* - Bio match: 0-15 points (if bio exists)
* - Workload balance: 0-25 points
* - Workload balance: 0-25 points (uses preferredWorkload as soft target)
* - Country match: 0-15 points (mentors only)
* - Geo diversity: -15 per excess same-country assignment (threshold: 2)
* - Previous round familiarity: +10 if reviewed in earlier round
* - COI: juror skipped entirely if conflict declared
* - Availability: -30 if unavailable during voting window
*/
import { prisma } from '@/lib/prisma'
@@ -32,6 +34,7 @@ export interface ScoreBreakdown {
geoDiversityPenalty: number
previousRoundFamiliarity: number
coiPenalty: number
availabilityPenalty: number
}
export interface AssignmentScore {
@@ -65,6 +68,7 @@ const GEO_DIVERSITY_THRESHOLD = 2
const GEO_DIVERSITY_PENALTY_PER_EXCESS = -15
const PREVIOUS_ROUND_FAMILIARITY_BONUS = 10
// COI jurors are skipped entirely rather than penalized (effectively -Infinity)
const AVAILABILITY_PENALTY = -30 // Heavy penalty for unavailable jurors
// Common words to exclude from bio matching
const STOP_WORDS = new Set([
@@ -224,6 +228,45 @@ export function calculateCountryMatchScore(
return 0
}
/**
* Check if a user is available during the round's voting window.
* availabilityJson is an array of { start, end } date-range objects
* representing when the user IS available.
* Returns 0 (available) or AVAILABILITY_PENALTY (unavailable).
*/
export function calculateAvailabilityPenalty(
availabilityJson: unknown,
votingStartAt: Date | null | undefined,
votingEndAt: Date | null | undefined
): number {
// If no availability windows set, user is always available
if (!availabilityJson || !Array.isArray(availabilityJson) || availabilityJson.length === 0) {
return 0
}
// If no voting window defined, can't check availability
if (!votingStartAt || !votingEndAt) {
return 0
}
// Check if any availability window overlaps with the voting window
for (const window of availabilityJson) {
if (!window || typeof window !== 'object') continue
const start = new Date((window as { start: string }).start)
const end = new Date((window as { end: string }).end)
if (isNaN(start.getTime()) || isNaN(end.getTime())) continue
// Check overlap: user available window overlaps with voting window
if (start <= votingEndAt && end >= votingStartAt) {
return 0 // Available during at least part of the voting window
}
}
// No availability window overlaps with voting window
return AVAILABILITY_PENALTY
}
// ─── Main Scoring Function ───────────────────────────────────────────────────
/**
@@ -275,6 +318,8 @@ export async function getSmartSuggestions(options: {
expertiseTags: true,
maxAssignments: true,
country: true,
availabilityJson: true,
preferredWorkload: true,
_count: {
select: {
assignments: {
@@ -289,6 +334,12 @@ export async function getSmartSuggestions(options: {
return []
}
// Get round voting window for availability checking
const roundForAvailability = await prisma.round.findUnique({
where: { id: roundId },
select: { votingStartAt: true, votingEndAt: true },
})
// Get existing assignments to avoid duplicates
const existingAssignments = await prisma.assignment.findMany({
where: { roundId },
@@ -399,9 +450,12 @@ export async function getSmartSuggestions(options: {
project.description
)
// Use preferredWorkload as a soft target when available, fallback to calculated target
const effectiveTarget = user.preferredWorkload ?? targetPerUser
const workloadScore = calculateWorkloadScore(
currentCount,
targetPerUser,
effectiveTarget,
user.maxAssignments
)
@@ -410,6 +464,13 @@ export async function getSmartSuggestions(options: {
? calculateCountryMatchScore(user.country, project.country)
: 0
// Availability check against the round's voting window
const availabilityPenalty = calculateAvailabilityPenalty(
user.availabilityJson,
roundForAvailability?.votingStartAt,
roundForAvailability?.votingEndAt
)
// ── New scoring factors ─────────────────────────────────────────────
// Geographic diversity penalty
@@ -437,7 +498,8 @@ export async function getSmartSuggestions(options: {
workloadScore +
countryScore +
geoDiversityPenalty +
previousRoundFamiliarity
previousRoundFamiliarity +
availabilityPenalty
// Build reasoning
const reasoning: string[] = []
@@ -452,6 +514,9 @@ export async function getSmartSuggestions(options: {
} else if (workloadScore > 0) {
reasoning.push('Moderate workload')
}
if (user.preferredWorkload) {
reasoning.push(`Preferred workload: ${user.preferredWorkload}`)
}
if (countryScore > 0) {
reasoning.push('Same country')
}
@@ -461,6 +526,9 @@ export async function getSmartSuggestions(options: {
if (previousRoundFamiliarity > 0) {
reasoning.push('Reviewed in previous round (+10)')
}
if (availabilityPenalty < 0) {
reasoning.push(`Unavailable during voting window (${availabilityPenalty})`)
}
suggestions.push({
userId: user.id,
@@ -477,6 +545,7 @@ export async function getSmartSuggestions(options: {
geoDiversityPenalty,
previousRoundFamiliarity,
coiPenalty: 0, // COI jurors are skipped entirely
availabilityPenalty,
},
reasoning,
matchingTags,
@@ -602,6 +671,7 @@ export async function getMentorSuggestionsForProject(
geoDiversityPenalty: 0,
previousRoundFamiliarity: 0,
coiPenalty: 0,
availabilityPenalty: 0,
},
reasoning,
matchingTags,

View File

@@ -0,0 +1,174 @@
import crypto from 'crypto'
import { Prisma } from '@prisma/client'
import { prisma } from '@/lib/prisma'
/**
* Dispatch a webhook event to all active webhooks subscribed to this event.
*/
export async function dispatchWebhookEvent(
event: string,
payload: Record<string, unknown>
): Promise<number> {
const webhooks = await prisma.webhook.findMany({
where: {
isActive: true,
events: { has: event },
},
})
if (webhooks.length === 0) return 0
let deliveryCount = 0
for (const webhook of webhooks) {
try {
const delivery = await prisma.webhookDelivery.create({
data: {
webhookId: webhook.id,
event,
payload: payload as Prisma.InputJsonValue,
status: 'PENDING',
attempts: 0,
},
})
// Attempt delivery asynchronously (don't block the caller)
deliverWebhook(delivery.id).catch((err) => {
console.error(`[Webhook] Background delivery failed for ${delivery.id}:`, err)
})
deliveryCount++
} catch (error) {
console.error(`[Webhook] Failed to create delivery for webhook ${webhook.id}:`, error)
}
}
return deliveryCount
}
/**
* Attempt to deliver a single webhook.
*/
export async function deliverWebhook(deliveryId: string): Promise<void> {
const delivery = await prisma.webhookDelivery.findUnique({
where: { id: deliveryId },
include: { webhook: true },
})
if (!delivery || !delivery.webhook) {
console.error(`[Webhook] Delivery ${deliveryId} not found`)
return
}
const { webhook } = delivery
const payloadStr = JSON.stringify(delivery.payload)
// Sign payload with HMAC-SHA256
const signature = crypto
.createHmac('sha256', webhook.secret)
.update(payloadStr)
.digest('hex')
// Build headers
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'X-Webhook-Signature': `sha256=${signature}`,
'X-Webhook-Event': delivery.event,
'X-Webhook-Delivery': delivery.id,
}
// Merge custom headers from webhook config
if (webhook.headers && typeof webhook.headers === 'object') {
const customHeaders = webhook.headers as Record<string, string>
for (const [key, value] of Object.entries(customHeaders)) {
if (typeof value === 'string') {
headers[key] = value
}
}
}
try {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 30000) // 30s timeout
const response = await fetch(webhook.url, {
method: 'POST',
headers,
body: payloadStr,
signal: controller.signal,
})
clearTimeout(timeout)
const responseBody = await response.text().catch(() => '')
await prisma.webhookDelivery.update({
where: { id: deliveryId },
data: {
status: response.ok ? 'DELIVERED' : 'FAILED',
responseStatus: response.status,
responseBody: responseBody.slice(0, 4000), // Truncate long responses
attempts: delivery.attempts + 1,
lastAttemptAt: new Date(),
},
})
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
await prisma.webhookDelivery.update({
where: { id: deliveryId },
data: {
status: 'FAILED',
responseBody: errorMessage.slice(0, 4000),
attempts: delivery.attempts + 1,
lastAttemptAt: new Date(),
},
})
}
}
/**
* Retry all failed webhook deliveries that haven't exceeded max retries.
* Called by cron.
*/
export async function retryFailedDeliveries(): Promise<{
retried: number
errors: number
}> {
let retried = 0
let errors = 0
const failedDeliveries = await prisma.webhookDelivery.findMany({
where: {
status: 'FAILED',
},
include: {
webhook: {
select: { maxRetries: true, isActive: true },
},
},
})
for (const delivery of failedDeliveries) {
// Skip if webhook is inactive or max retries exceeded
if (!delivery.webhook.isActive) continue
if (delivery.attempts >= delivery.webhook.maxRetries) continue
try {
await deliverWebhook(delivery.id)
retried++
} catch (error) {
console.error(`[Webhook] Retry failed for delivery ${delivery.id}:`, error)
errors++
}
}
return { retried, errors }
}
/**
* Generate a random HMAC secret for webhook signing.
*/
export function generateWebhookSecret(): string {
return crypto.randomBytes(32).toString('hex')
}