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,48 @@
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { prisma } from '@/lib/prisma'
export async function GET(request: NextRequest): Promise<NextResponse> {
const cronSecret = request.headers.get('x-cron-secret')
if (!cronSecret || cronSecret !== process.env.CRON_SECRET) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
// Read retention period from system settings (default: 365 days)
const retentionSetting = await prisma.systemSettings.findUnique({
where: { key: 'audit_retention_days' },
})
const retentionDays = retentionSetting
? parseInt(retentionSetting.value, 10) || 365
: 365
const cutoffDate = new Date()
cutoffDate.setDate(cutoffDate.getDate() - retentionDays)
// Delete audit log entries older than the retention period
const result = await prisma.auditLog.deleteMany({
where: {
timestamp: {
lt: cutoffDate,
},
},
})
return NextResponse.json({
ok: true,
cleanedUp: result.count,
retentionDays,
cutoffDate: cutoffDate.toISOString(),
timestamp: new Date().toISOString(),
})
} catch (error) {
console.error('Cron audit cleanup failed:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,39 @@
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { processDigests } from '@/server/services/email-digest'
export async function GET(request: NextRequest): Promise<NextResponse> {
const cronSecret = request.headers.get('x-cron-secret')
if (!cronSecret || cronSecret !== process.env.CRON_SECRET) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
// Determine digest type: check query param, or default based on day of week
const { searchParams } = new URL(request.url)
let digestType = searchParams.get('type') as 'daily' | 'weekly' | null
if (!digestType) {
const dayOfWeek = new Date().getDay()
// Monday = 1 → run weekly; all other days → run daily
digestType = dayOfWeek === 1 ? 'weekly' : 'daily'
}
const result = await processDigests(digestType)
return NextResponse.json({
ok: true,
digestType,
sent: result.sent,
errors: result.errors,
timestamp: new Date().toISOString(),
})
} catch (error) {
console.error('Cron digest processing failed:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,37 @@
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { prisma } from '@/lib/prisma'
export async function GET(request: NextRequest): Promise<NextResponse> {
const cronSecret = request.headers.get('x-cron-secret')
if (!cronSecret || cronSecret !== process.env.CRON_SECRET) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const now = new Date()
// Delete projects where isDraft=true AND draftExpiresAt has passed
const result = await prisma.project.deleteMany({
where: {
isDraft: true,
draftExpiresAt: {
lt: now,
},
},
})
return NextResponse.json({
ok: true,
cleanedUp: result.count,
timestamp: now.toISOString(),
})
} catch (error) {
console.error('Cron draft cleanup failed:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,124 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { getPresignedUrl, BUCKET_NAME } from '@/lib/minio'
export async function POST(request: NextRequest): Promise<NextResponse> {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const body = await request.json()
const { projectId, fileIds } = body as {
projectId?: string
fileIds?: string[]
}
if (!projectId || !fileIds || !Array.isArray(fileIds) || fileIds.length === 0) {
return NextResponse.json(
{ error: 'projectId and fileIds array are required' },
{ status: 400 }
)
}
const userId = session.user.id
const userRole = session.user.role
// Authorization: must be admin or assigned jury/mentor for this project
const isAdmin = userRole === 'SUPER_ADMIN' || userRole === 'PROGRAM_ADMIN'
if (!isAdmin) {
// Check if user is assigned as jury
const juryAssignment = await prisma.assignment.findFirst({
where: {
userId,
projectId,
},
})
// Check if user is assigned as mentor
const mentorAssignment = await prisma.mentorAssignment.findFirst({
where: {
mentorId: userId,
projectId,
},
})
if (!juryAssignment && !mentorAssignment) {
return NextResponse.json(
{ error: 'You do not have access to this project\'s files' },
{ status: 403 }
)
}
}
// Fetch file metadata from DB
const files = await prisma.projectFile.findMany({
where: {
id: { in: fileIds },
projectId,
},
select: {
id: true,
fileName: true,
objectKey: true,
mimeType: true,
size: true,
},
})
if (files.length === 0) {
return NextResponse.json(
{ error: 'No matching files found' },
{ status: 404 }
)
}
// Generate signed download URLs for each file
const downloadUrls = await Promise.all(
files.map(async (file) => {
try {
const downloadUrl = await getPresignedUrl(
BUCKET_NAME,
file.objectKey,
'GET',
3600 // 1 hour expiry for bulk downloads
)
return {
id: file.id,
fileName: file.fileName,
mimeType: file.mimeType,
size: file.size,
downloadUrl,
}
} catch (error) {
console.error(`[BulkDownload] Failed to get URL for file ${file.id}:`, error)
return {
id: file.id,
fileName: file.fileName,
mimeType: file.mimeType,
size: file.size,
downloadUrl: null,
error: 'Failed to generate download URL',
}
}
})
)
return NextResponse.json({
projectId,
files: downloadUrls,
expiresIn: 3600,
})
} catch (error) {
console.error('[BulkDownload] Error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,180 @@
import { NextRequest } from 'next/server'
import { prisma } from '@/lib/prisma'
export const dynamic = 'force-dynamic'
export async function GET(request: NextRequest): Promise<Response> {
const { searchParams } = new URL(request.url)
const sessionId = searchParams.get('sessionId')
if (!sessionId) {
return new Response(JSON.stringify({ error: 'sessionId is required' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
})
}
// Verify the session exists
const session = await prisma.liveVotingSession.findUnique({
where: { id: sessionId },
select: { id: true, status: true },
})
if (!session) {
return new Response(JSON.stringify({ error: 'Session not found' }), {
status: 404,
headers: { 'Content-Type': 'application/json' },
})
}
const encoder = new TextEncoder()
const stream = new ReadableStream({
async start(controller) {
// Track state for change detection
let lastVoteCount = -1
let lastProjectId: string | null = null
let lastStatus: string | null = null
const sendEvent = (event: string, data: unknown) => {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
controller.enqueue(encoder.encode(payload))
}
// Send initial connection event
sendEvent('connected', { sessionId, timestamp: new Date().toISOString() })
const poll = async () => {
try {
const currentSession = await prisma.liveVotingSession.findUnique({
where: { id: sessionId },
select: {
status: true,
currentProjectId: true,
currentProjectIndex: true,
votingEndsAt: true,
},
})
if (!currentSession) {
sendEvent('session_status', { status: 'DELETED' })
controller.close()
return false
}
// Check for status changes
if (lastStatus !== null && currentSession.status !== lastStatus) {
sendEvent('session_status', {
status: currentSession.status,
timestamp: new Date().toISOString(),
})
}
lastStatus = currentSession.status
// Check for project changes
if (
lastProjectId !== null &&
currentSession.currentProjectId !== lastProjectId
) {
sendEvent('project_change', {
projectId: currentSession.currentProjectId,
projectIndex: currentSession.currentProjectIndex,
timestamp: new Date().toISOString(),
})
}
lastProjectId = currentSession.currentProjectId
// Check for vote updates on the current project
if (currentSession.currentProjectId) {
const voteCount = await prisma.liveVote.count({
where: {
sessionId,
projectId: currentSession.currentProjectId,
},
})
if (lastVoteCount !== -1 && voteCount !== lastVoteCount) {
// Get the latest vote info
const latestVotes = await prisma.liveVote.findMany({
where: {
sessionId,
projectId: currentSession.currentProjectId,
},
select: {
score: true,
isAudienceVote: true,
votedAt: true,
},
orderBy: { votedAt: 'desc' },
take: 1,
})
const avgScore = await prisma.liveVote.aggregate({
where: {
sessionId,
projectId: currentSession.currentProjectId,
},
_avg: { score: true },
_count: true,
})
sendEvent('vote_update', {
projectId: currentSession.currentProjectId,
totalVotes: voteCount,
averageScore: avgScore._avg.score,
latestVote: latestVotes[0] || null,
timestamp: new Date().toISOString(),
})
}
lastVoteCount = voteCount
}
// Stop polling if session is completed
if (currentSession.status === 'COMPLETED') {
sendEvent('session_status', {
status: 'COMPLETED',
timestamp: new Date().toISOString(),
})
controller.close()
return false
}
return true
} catch (error) {
console.error('[SSE] Poll error:', error)
return true // Keep trying
}
}
// Initial poll to set baseline state
const shouldContinue = await poll()
if (!shouldContinue) return
// Poll every 2 seconds
const interval = setInterval(async () => {
const cont = await poll()
if (!cont) {
clearInterval(interval)
}
}, 2000)
// Clean up on abort
request.signal.addEventListener('abort', () => {
clearInterval(interval)
try {
controller.close()
} catch {
// Stream may already be closed
}
})
},
})
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
},
})
}