Reconcile schema with migrations and fix failed migration
Build and Push Docker Image / build (push) Successful in 17m39s Details

- Align schema.prisma with add_15_features migration (15 discrepancies):
  nullability, column names, PKs, missing/extra columns, onDelete behavior
- Make universal_apply_programid migration idempotent for safe re-execution
- Add reconciliation migration for missing FKs and indexes
- Fix message.ts and mentor.ts to match corrected schema field names

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Matt 2026-02-08 14:37:32 +01:00
parent 04d0deced1
commit e0e4cb2a32
18 changed files with 1174 additions and 353 deletions

View File

@ -1,6 +1,9 @@
#!/bin/sh
set -e
echo "==> Resolving any failed migrations..."
npx prisma migrate resolve --rolled-back 20260207000000_universal_apply_programid 2>/dev/null || true
echo "==> Running database migrations..."
npx prisma migrate deploy

11
package-lock.json generated
View File

@ -55,6 +55,7 @@
"next": "^15.1.0",
"next-auth": "^5.0.0-beta.25",
"next-intl": "^4.8.2",
"next-themes": "^0.4.6",
"nodemailer": "^7.0.7",
"openai": "^6.16.0",
"papaparse": "^5.4.1",
@ -10906,6 +10907,16 @@
"tslib": "^2.8.0"
}
},
"node_modules/next-themes": {
"version": "0.4.6",
"resolved": "https://registry.npmjs.org/next-themes/-/next-themes-0.4.6.tgz",
"integrity": "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA==",
"license": "MIT",
"peerDependencies": {
"react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc"
}
},
"node_modules/next/node_modules/postcss": {
"version": "8.4.31",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz",

View File

@ -68,6 +68,7 @@
"next": "^15.1.0",
"next-auth": "^5.0.0-beta.25",
"next-intl": "^4.8.2",
"next-themes": "^0.4.6",
"nodemailer": "^7.0.7",
"openai": "^6.16.0",
"papaparse": "^5.4.1",

View File

@ -1,51 +1,91 @@
-- Universal Apply Page: Make Project.roundId nullable and add programId FK
-- This migration enables projects to be submitted to a program/edition without being assigned to a specific round
-- NOTE: Written to be idempotent (safe to re-run if partially applied)
-- Step 1: Add Program.slug for edition-wide apply URLs (nullable for existing programs)
ALTER TABLE "Program" ADD COLUMN "slug" TEXT;
CREATE UNIQUE INDEX "Program_slug_key" ON "Program"("slug");
ALTER TABLE "Program" ADD COLUMN IF NOT EXISTS "slug" TEXT;
CREATE UNIQUE INDEX IF NOT EXISTS "Program_slug_key" ON "Program"("slug");
-- Step 2: Add programId column (nullable initially to handle existing data)
ALTER TABLE "Project" ADD COLUMN "programId" TEXT;
ALTER TABLE "Project" ADD COLUMN IF NOT EXISTS "programId" TEXT;
-- Step 3: Backfill programId from existing round relationships
-- Every project currently has a roundId, so we can populate programId from Round.programId
-- Only update rows where programId is still NULL (idempotent)
UPDATE "Project" p
SET "programId" = r."programId"
FROM "Round" r
WHERE p."roundId" = r.id;
WHERE p."roundId" = r.id
AND p."programId" IS NULL;
-- Step 4: Verify backfill succeeded (should be 0 rows with NULL programId)
-- If this fails, manual intervention is needed
-- Step 4: Handle orphaned projects (no roundId = no way to derive programId)
-- Assign them to the first available program, or delete them if no program exists
DO $$
DECLARE
null_count INTEGER;
fallback_program_id TEXT;
BEGIN
SELECT COUNT(*) INTO null_count FROM "Project" WHERE "programId" IS NULL;
IF null_count > 0 THEN
RAISE EXCEPTION 'Migration failed: % projects have NULL programId after backfill', null_count;
SELECT id INTO fallback_program_id FROM "Program" ORDER BY "createdAt" ASC LIMIT 1;
IF fallback_program_id IS NOT NULL THEN
UPDATE "Project" SET "programId" = fallback_program_id WHERE "programId" IS NULL;
RAISE NOTICE 'Assigned % orphaned projects to fallback program %', null_count, fallback_program_id;
ELSE
DELETE FROM "Project" WHERE "programId" IS NULL;
RAISE NOTICE 'Deleted % orphaned projects (no program exists to assign them to)', null_count;
END IF;
END IF;
END $$;
-- Step 5: Make programId required (NOT NULL constraint)
ALTER TABLE "Project" ALTER COLUMN "programId" SET NOT NULL;
-- Step 5: Make programId required (NOT NULL constraint) - safe if already NOT NULL
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'Project' AND column_name = 'programId' AND is_nullable = 'YES'
) THEN
ALTER TABLE "Project" ALTER COLUMN "programId" SET NOT NULL;
END IF;
END $$;
-- Step 6: Add foreign key constraint for programId
ALTER TABLE "Project" ADD CONSTRAINT "Project_programId_fkey"
FOREIGN KEY ("programId") REFERENCES "Program"("id") ON DELETE CASCADE;
-- Step 6: Add foreign key constraint for programId (skip if already exists)
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.table_constraints
WHERE constraint_name = 'Project_programId_fkey' AND table_name = 'Project'
) THEN
ALTER TABLE "Project" ADD CONSTRAINT "Project_programId_fkey"
FOREIGN KEY ("programId") REFERENCES "Program"("id") ON DELETE CASCADE;
END IF;
END $$;
-- Step 7: Make roundId nullable (allow projects without round assignment)
ALTER TABLE "Project" ALTER COLUMN "roundId" DROP NOT NULL;
-- Safe: DROP NOT NULL is idempotent if already nullable
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'Project' AND column_name = 'roundId' AND is_nullable = 'NO'
) THEN
ALTER TABLE "Project" ALTER COLUMN "roundId" DROP NOT NULL;
END IF;
END $$;
-- Step 8: Update round FK to SET NULL on delete (instead of CASCADE)
-- Projects should remain in the database if their round is deleted
ALTER TABLE "Project" DROP CONSTRAINT "Project_roundId_fkey";
ALTER TABLE "Project" ADD CONSTRAINT "Project_roundId_fkey"
FOREIGN KEY ("roundId") REFERENCES "Round"("id") ON DELETE SET NULL;
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.table_constraints
WHERE constraint_name = 'Project_roundId_fkey' AND table_name = 'Project'
) THEN
ALTER TABLE "Project" DROP CONSTRAINT "Project_roundId_fkey";
END IF;
ALTER TABLE "Project" ADD CONSTRAINT "Project_roundId_fkey"
FOREIGN KEY ("roundId") REFERENCES "Round"("id") ON DELETE SET NULL;
END $$;
-- Step 9: Add performance indexes
-- Index for filtering unassigned projects (WHERE roundId IS NULL)
CREATE INDEX "Project_programId_idx" ON "Project"("programId");
CREATE INDEX "Project_programId_roundId_idx" ON "Project"("programId", "roundId");
-- Note: The existing "Project_roundId_idx" remains for queries filtering by round
CREATE INDEX IF NOT EXISTS "Project_programId_idx" ON "Project"("programId");
CREATE INDEX IF NOT EXISTS "Project_programId_roundId_idx" ON "Project"("programId", "roundId");

View File

@ -0,0 +1,41 @@
-- Reconciliation migration: Add missing foreign keys and indexes
-- The add_15_features migration omitted some FKs and indexes that the schema expects
-- This migration brings the database in line with the Prisma schema
-- =====================================================
-- Missing Foreign Keys
-- =====================================================
-- RoundTemplate → Program
ALTER TABLE "RoundTemplate" ADD CONSTRAINT "RoundTemplate_programId_fkey"
FOREIGN KEY ("programId") REFERENCES "Program"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- RoundTemplate → User (creator)
ALTER TABLE "RoundTemplate" ADD CONSTRAINT "RoundTemplate_createdBy_fkey"
FOREIGN KEY ("createdBy") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- Message → Round
ALTER TABLE "Message" ADD CONSTRAINT "Message_roundId_fkey"
FOREIGN KEY ("roundId") REFERENCES "Round"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- EvaluationDiscussion → Round
ALTER TABLE "EvaluationDiscussion" ADD CONSTRAINT "EvaluationDiscussion_roundId_fkey"
FOREIGN KEY ("roundId") REFERENCES "Round"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- ProjectFile → ProjectFile (self-relation for file versioning)
ALTER TABLE "ProjectFile" ADD CONSTRAINT "ProjectFile_replacedById_fkey"
FOREIGN KEY ("replacedById") REFERENCES "ProjectFile"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- =====================================================
-- Missing Indexes
-- =====================================================
CREATE INDEX "RoundTemplate_roundType_idx" ON "RoundTemplate"("roundType");
CREATE INDEX "MentorNote_authorId_idx" ON "MentorNote"("authorId");
CREATE INDEX "MentorMilestoneCompletion_completedById_idx" ON "MentorMilestoneCompletion"("completedById");
CREATE INDEX "Webhook_createdById_idx" ON "Webhook"("createdById");
CREATE INDEX "WebhookDelivery_event_idx" ON "WebhookDelivery"("event");
CREATE INDEX "Message_roundId_idx" ON "Message"("roundId");
CREATE INDEX "EvaluationDiscussion_closedById_idx" ON "EvaluationDiscussion"("closedById");
CREATE INDEX "DiscussionComment_discussionId_idx" ON "DiscussionComment"("discussionId");
CREATE INDEX "DiscussionComment_userId_idx" ON "DiscussionComment"("userId");

View File

@ -114,6 +114,8 @@ enum SettingCategory {
LOCALIZATION
DIGEST
ANALYTICS
INTEGRATIONS
COMMUNICATION
}
enum NotificationChannel {
@ -227,7 +229,7 @@ model User {
inviteTokenExpiresAt DateTime?
// Digest & availability preferences
digestFrequency String? // 'none' | 'daily' | 'weekly'
digestFrequency String @default("none") // 'none' | 'daily' | 'weekly'
preferredWorkload Int?
availabilityJson Json? @db.JsonB // { startDate?: string, endDate?: string }
@ -749,7 +751,8 @@ model AuditLog {
entityId String?
// Details
detailsJson Json? @db.JsonB // Before/after values, additional context
detailsJson Json? @db.JsonB // Before/after values, additional context
previousDataJson Json? @db.JsonB // Previous state for tracking changes
// Request info
ipAddress String?
@ -1031,8 +1034,8 @@ model LiveVotingSession {
// Audience & presentation settings
allowAudienceVotes Boolean @default(false)
audienceVoteWeight Float? // 0.0 to 1.0
tieBreakerMethod String? // 'admin_decides' | 'highest_individual' | 'revote'
audienceVoteWeight Float @default(0) // 0.0 to 1.0
tieBreakerMethod String @default("admin_decides") // 'admin_decides' | 'highest_individual' | 'revote'
presentationSettingsJson Json? @db.JsonB
createdAt DateTime @default(now())
@ -1588,6 +1591,7 @@ model MentorMilestone {
}
model MentorMilestoneCompletion {
id String @id @default(cuid())
milestoneId String
mentorAssignmentId String
completedById String
@ -1598,7 +1602,7 @@ model MentorMilestoneCompletion {
mentorAssignment MentorAssignment @relation(fields: [mentorAssignmentId], references: [id], onDelete: Cascade)
completedBy User @relation("MilestoneCompletedBy", fields: [completedById], references: [id])
@@id([milestoneId, mentorAssignmentId])
@@unique([milestoneId, mentorAssignmentId])
@@index([mentorAssignmentId])
@@index([completedById])
}
@ -1612,12 +1616,10 @@ model EvaluationDiscussion {
projectId String
roundId String
status String @default("open") // 'open' | 'closed'
createdAt DateTime @default(now())
closedAt DateTime?
closedById String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Relations
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
round Round @relation(fields: [roundId], references: [id], onDelete: Cascade)
@ -1662,12 +1664,12 @@ model Message {
scheduledAt DateTime?
sentAt DateTime?
metadata Json? @db.JsonB
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Relations
sender User @relation("MessageSender", fields: [senderId], references: [id], onDelete: Cascade)
sender User @relation("MessageSender", fields: [senderId], references: [id])
round Round? @relation(fields: [roundId], references: [id], onDelete: SetNull)
template MessageTemplate? @relation(fields: [templateId], references: [id], onDelete: SetNull)
recipients MessageRecipient[]
@ -1678,15 +1680,13 @@ model Message {
}
model MessageRecipient {
id String @id @default(cuid())
messageId String
userId String
channel String // 'EMAIL', 'IN_APP', etc.
isRead Boolean @default(false)
readAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
id String @id @default(cuid())
messageId String
userId String
channel String // 'EMAIL', 'IN_APP', etc.
isRead Boolean @default(false)
readAt DateTime?
deliveredAt DateTime?
// Relations
message Message @relation(fields: [messageId], references: [id], onDelete: Cascade)
@ -1697,21 +1697,21 @@ model MessageRecipient {
}
model MessageTemplate {
id String @id @default(cuid())
name String
category String // 'SYSTEM', 'EVALUATION', 'ASSIGNMENT'
subject String
body String @db.Text
variables Json? @db.JsonB
createdById String
isActive Boolean @default(true)
id String @id @default(cuid())
name String
category String // 'SYSTEM', 'EVALUATION', 'ASSIGNMENT'
subject String
body String @db.Text
variables Json? @db.JsonB
isActive Boolean @default(true)
createdBy String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Relations
createdBy User @relation("MessageTemplateCreator", fields: [createdById], references: [id], onDelete: Cascade)
messages Message[]
creator User @relation("MessageTemplateCreator", fields: [createdBy], references: [id])
messages Message[]
@@index([category])
@@index([isActive])
@ -1736,7 +1736,7 @@ model Webhook {
updatedAt DateTime @updatedAt
// Relations
createdBy User @relation("WebhookCreator", fields: [createdById], references: [id], onDelete: Cascade)
createdBy User @relation("WebhookCreator", fields: [createdById], references: [id])
deliveries WebhookDelivery[]
@@index([isActive])
@ -1755,7 +1755,6 @@ model WebhookDelivery {
lastAttemptAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Relations
webhook Webhook @relation(fields: [webhookId], references: [id], onDelete: Cascade)
@ -1776,11 +1775,9 @@ model DigestLog {
contentJson Json @db.JsonB
sentAt DateTime @default(now())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Relations
user User @relation("DigestLog", fields: [userId], references: [id], onDelete: Cascade)
@@index([userId, sentAt])
@@index([userId])
@@index([sentAt])
}

View File

@ -29,8 +29,24 @@ import {
ExternalLink,
AlertCircle,
} from 'lucide-react'
import { Progress } from '@/components/ui/progress'
import { formatDate, truncate } from '@/lib/utils'
function getCriteriaProgress(evaluation: {
criterionScoresJson: unknown
form: { criteriaJson: unknown }
} | null): { completed: number; total: number } | null {
if (!evaluation || !evaluation.form?.criteriaJson) return null
const criteria = evaluation.form.criteriaJson as Array<{ id: string; type?: string }>
// Only count scoreable criteria (exclude section_header)
const scoreable = criteria.filter((c) => c.type !== 'section_header')
const total = scoreable.length
if (total === 0) return null
const scores = (evaluation.criterionScoresJson || {}) as Record<string, unknown>
const completed = scoreable.filter((c) => scores[c.id] != null && scores[c.id] !== '').length
return { completed, total }
}
async function AssignmentsContent({
roundId,
}: {
@ -85,6 +101,12 @@ async function AssignmentsContent({
status: true,
submittedAt: true,
updatedAt: true,
criterionScoresJson: true,
form: {
select: {
criteriaJson: true,
},
},
},
},
},
@ -141,14 +163,17 @@ async function AssignmentsContent({
return (
<TableRow key={assignment.id}>
<TableCell>
<div>
<p className="font-medium">
<Link
href={`/jury/projects/${assignment.project.id}`}
className="block group"
>
<p className="font-medium group-hover:text-primary group-hover:underline transition-colors">
{truncate(assignment.project.title, 40)}
</p>
<p className="text-sm text-muted-foreground">
{assignment.project.teamName}
</p>
</div>
</Link>
</TableCell>
<TableCell>
<div>
@ -180,10 +205,23 @@ async function AssignmentsContent({
Completed
</Badge>
) : isDraft ? (
<Badge variant="warning">
<Clock className="mr-1 h-3 w-3" />
In Progress
</Badge>
<div className="space-y-1.5">
<Badge variant="warning">
<Clock className="mr-1 h-3 w-3" />
In Progress
</Badge>
{(() => {
const progress = getCriteriaProgress(assignment.evaluation)
if (!progress) return null
const pct = Math.round((progress.completed / progress.total) * 100)
return (
<div className="flex items-center gap-2">
<Progress value={pct} className="h-1.5 w-16" />
<span className="text-xs text-muted-foreground">{progress.completed}/{progress.total}</span>
</div>
)
})()}
</div>
) : (
<Badge variant="secondary">Pending</Badge>
)}
@ -237,14 +275,17 @@ async function AssignmentsContent({
<Card key={assignment.id}>
<CardHeader className="pb-3">
<div className="flex items-start justify-between">
<div className="space-y-1">
<CardTitle className="text-base">
<Link
href={`/jury/projects/${assignment.project.id}`}
className="space-y-1 group"
>
<CardTitle className="text-base group-hover:text-primary group-hover:underline transition-colors">
{assignment.project.title}
</CardTitle>
<CardDescription>
{assignment.project.teamName}
</CardDescription>
</div>
</Link>
{isCompleted ? (
<Badge variant="success">
<CheckCircle2 className="mr-1 h-3 w-3" />
@ -271,6 +312,20 @@ async function AssignmentsContent({
<span>{formatDate(assignment.round.votingEndAt)}</span>
</div>
)}
{isDraft && (() => {
const progress = getCriteriaProgress(assignment.evaluation)
if (!progress) return null
const pct = Math.round((progress.completed / progress.total) * 100)
return (
<div className="space-y-1">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">Progress</span>
<span className="text-xs">{progress.completed}/{progress.total} criteria</span>
</div>
<Progress value={pct} className="h-1.5" />
</div>
)
})()}
<div className="pt-2">
{isCompleted ? (
<Button

View File

@ -14,6 +14,15 @@ import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Separator } from '@/components/ui/separator'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import {
Select,
SelectContent,
@ -29,18 +38,114 @@ import {
FileText,
CheckCircle2,
Clock,
XCircle,
ThumbsUp,
ThumbsDown,
} from 'lucide-react'
import { cn } from '@/lib/utils'
type Criterion = {
id: string
label: string
description?: string
scale?: string
weight?: number
type?: string
}
type ComparisonItem = {
project: Record<string, unknown>
evaluation: Record<string, unknown> | null
assignmentId: string
}
type ComparisonData = {
items: ComparisonItem[]
criteria: Criterion[] | null
scales: Record<string, { min: number; max: number }> | null
}
function getScoreColor(score: number, max: number): string {
const ratio = score / max
if (ratio >= 0.8) return 'bg-green-500'
if (ratio >= 0.6) return 'bg-emerald-400'
if (ratio >= 0.4) return 'bg-amber-400'
if (ratio >= 0.2) return 'bg-orange-400'
return 'bg-red-400'
}
function getScoreTextColor(score: number, max: number): string {
const ratio = score / max
if (ratio >= 0.8) return 'text-green-600 dark:text-green-400'
if (ratio >= 0.6) return 'text-emerald-600 dark:text-emerald-400'
if (ratio >= 0.4) return 'text-amber-600 dark:text-amber-400'
return 'text-red-600 dark:text-red-400'
}
function ScoreRing({ score, max }: { score: number; max: number }) {
const pct = Math.round((score / max) * 100)
const circumference = 2 * Math.PI * 36
const offset = circumference - (pct / 100) * circumference
return (
<div className="relative inline-flex items-center justify-center">
<svg className="w-20 h-20 -rotate-90" viewBox="0 0 80 80">
<circle
cx="40" cy="40" r="36"
className="stroke-muted"
strokeWidth="6" fill="none"
/>
<circle
cx="40" cy="40" r="36"
className={cn(
'transition-all duration-500',
pct >= 80 ? 'stroke-green-500' :
pct >= 60 ? 'stroke-emerald-400' :
pct >= 40 ? 'stroke-amber-400' : 'stroke-red-400'
)}
strokeWidth="6" fill="none"
strokeDasharray={circumference}
strokeDashoffset={offset}
strokeLinecap="round"
/>
</svg>
<div className="absolute flex flex-col items-center">
<span className="text-lg font-bold tabular-nums">{score}</span>
<span className="text-[10px] text-muted-foreground">/{max}</span>
</div>
</div>
)
}
function ScoreBar({ score, max, isHighest }: { score: number; max: number; isHighest: boolean }) {
const pct = Math.round((score / max) * 100)
return (
<div className="flex items-center gap-2">
<div className="flex-1 h-2 bg-muted rounded-full overflow-hidden">
<div
className={cn('h-full rounded-full transition-all', getScoreColor(score, max))}
style={{ width: `${pct}%` }}
/>
</div>
<span className={cn(
'text-sm font-medium tabular-nums w-8 text-right',
isHighest && 'font-bold',
getScoreTextColor(score, max)
)}>
{score}
</span>
</div>
)
}
export default function CompareProjectsPage() {
const [selectedRoundId, setSelectedRoundId] = useState<string>('')
const [selectedIds, setSelectedIds] = useState<string[]>([])
const [comparing, setComparing] = useState(false)
// Fetch all assigned projects
const { data: assignments, isLoading: loadingAssignments } =
trpc.assignment.myAssignments.useQuery({})
// Derive unique rounds from assignments
const rounds = useMemo(() => {
if (!assignments) return []
const roundMap = new Map<string, { id: string; name: string }>()
@ -52,10 +157,8 @@ export default function CompareProjectsPage() {
return Array.from(roundMap.values())
}, [assignments])
// Auto-select the first round if none selected
const activeRoundId = selectedRoundId || (rounds.length > 0 ? rounds[0].id : '')
// Filter assignments to current round
const roundProjects = useMemo(() => {
if (!assignments || !activeRoundId) return []
return (assignments as Array<{
@ -71,7 +174,6 @@ export default function CompareProjectsPage() {
}))
}, [assignments, activeRoundId])
// Fetch comparison data when comparing
const { data: comparisonData, isLoading: loadingComparison } =
trpc.evaluation.getMultipleForComparison.useQuery(
{ projectIds: selectedIds, roundId: activeRoundId },
@ -90,9 +192,7 @@ export default function CompareProjectsPage() {
}
const handleCompare = () => {
if (selectedIds.length >= 2) {
setComparing(true)
}
if (selectedIds.length >= 2) setComparing(true)
}
const handleReset = () => {
@ -106,9 +206,9 @@ export default function CompareProjectsPage() {
setComparing(false)
}
if (loadingAssignments) {
return <CompareSkeleton />
}
if (loadingAssignments) return <CompareSkeleton />
const data = comparisonData as ComparisonData | undefined
return (
<div className="space-y-6">
@ -136,10 +236,7 @@ export default function CompareProjectsPage() {
</Button>
)}
{!comparing && (
<Button
onClick={handleCompare}
disabled={selectedIds.length < 2}
>
<Button onClick={handleCompare} disabled={selectedIds.length < 2}>
<GitCompare className="mr-2 h-4 w-4" />
Compare ({selectedIds.length})
</Button>
@ -157,9 +254,7 @@ export default function CompareProjectsPage() {
</SelectTrigger>
<SelectContent>
{rounds.map((r) => (
<SelectItem key={r.id} value={r.id}>
{r.name}
</SelectItem>
<SelectItem key={r.id} value={r.id}>{r.name}</SelectItem>
))}
</SelectContent>
</Select>
@ -177,13 +272,14 @@ export default function CompareProjectsPage() {
return (
<Card
key={projectId}
className={`cursor-pointer transition-colors ${
className={cn(
'cursor-pointer transition-all',
isSelected
? 'border-primary ring-2 ring-primary/20'
: isDisabled
? 'opacity-50'
: 'hover:border-primary/50'
}`}
)}
onClick={() => !isDisabled && toggleProject(projectId)}
>
<CardContent className="p-4">
@ -201,11 +297,6 @@ export default function CompareProjectsPage() {
<p className="text-sm text-muted-foreground truncate">
{String(project.teamName || '')}
</p>
{!!project.roundName && (
<Badge variant="secondary" className="mt-1 text-xs">
{String(project.roundName)}
</Badge>
)}
</div>
{project.evaluation ? (
<CheckCircle2 className="h-4 w-4 text-green-500 shrink-0" />
@ -235,23 +326,34 @@ export default function CompareProjectsPage() {
{/* Comparison view */}
{comparing && loadingComparison && <CompareSkeleton />}
{comparing && comparisonData && (
<div
className={`grid gap-4 grid-cols-1 ${
selectedIds.length === 2 ? 'md:grid-cols-2' : 'md:grid-cols-2 lg:grid-cols-3'
}`}
>
{(comparisonData as Array<{
project: Record<string, unknown>
evaluation: Record<string, unknown> | null
assignmentId: string
}>).map((item) => (
<ComparisonCard
key={String(item.project.id)}
project={item.project}
evaluation={item.evaluation}
{comparing && data && (
<div className="space-y-6">
{/* Project summary cards */}
<div
className={cn(
'grid gap-4 grid-cols-1',
data.items.length === 2 ? 'md:grid-cols-2' : 'md:grid-cols-2 lg:grid-cols-3'
)}
>
{data.items.map((item) => (
<ComparisonCard
key={String(item.project.id)}
project={item.project}
evaluation={item.evaluation}
criteria={data.criteria}
scales={data.scales}
/>
))}
</div>
{/* Side-by-side criterion comparison table */}
{data.criteria && data.criteria.filter((c) => c.type !== 'section_header').length > 0 && (
<CriterionComparisonTable
items={data.items}
criteria={data.criteria}
scales={data.scales}
/>
))}
)}
</div>
)}
</div>
@ -261,24 +363,71 @@ export default function CompareProjectsPage() {
function ComparisonCard({
project,
evaluation,
criteria,
scales,
}: {
project: Record<string, unknown>
evaluation: Record<string, unknown> | null
criteria: Criterion[] | null
scales: Record<string, { min: number; max: number }> | null
}) {
const tags = Array.isArray(project.tags) ? project.tags : []
const files = Array.isArray(project.files) ? project.files : []
const scores = evaluation?.scores as Record<string, unknown> | undefined
const scores = (evaluation?.criterionScoresJson || evaluation?.scores) as Record<string, unknown> | undefined
const globalScore = evaluation?.globalScore as number | null | undefined
const binaryDecision = evaluation?.binaryDecision as boolean | null | undefined
// Build a criterion label lookup
const criterionLabels = useMemo(() => {
const map: Record<string, { label: string; scale?: string }> = {}
if (criteria) {
for (const c of criteria) {
map[c.id] = { label: c.label, scale: c.scale }
}
}
return map
}, [criteria])
const getMax = (criterionId: string) => {
const scale = criterionLabels[criterionId]?.scale
if (scale && scales && scales[scale]) return scales[scale].max
return 10
}
return (
<Card>
<CardHeader>
<CardTitle className="text-lg">{String(project.title || 'Untitled')}</CardTitle>
<CardDescription className="flex items-center gap-1">
<Users className="h-3 w-3" />
{String(project.teamName || 'N/A')}
</CardDescription>
<CardHeader className="pb-3">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<CardTitle className="text-lg">{String(project.title || 'Untitled')}</CardTitle>
<CardDescription className="flex items-center gap-1 mt-1">
<Users className="h-3 w-3" />
{String(project.teamName || 'N/A')}
</CardDescription>
</div>
{/* Global score ring */}
{evaluation && globalScore != null && (
<ScoreRing score={globalScore} max={10} />
)}
</div>
</CardHeader>
<CardContent className="space-y-4">
<CardContent className="space-y-3">
{/* Binary decision */}
{evaluation && binaryDecision != null && (
<div className={cn(
'flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium',
binaryDecision
? 'bg-green-50 text-green-700 dark:bg-green-950/30 dark:text-green-400'
: 'bg-red-50 text-red-700 dark:bg-red-950/30 dark:text-red-400'
)}>
{binaryDecision ? (
<><ThumbsUp className="h-4 w-4" /> Recommended to advance</>
) : (
<><ThumbsDown className="h-4 w-4" /> Not recommended</>
)}
</div>
)}
{/* Country */}
{!!project.country && (
<div className="flex items-center gap-2 text-sm">
@ -289,82 +438,211 @@ function ComparisonCard({
{/* Description */}
{!!project.description && (
<div>
<p className="text-xs font-medium text-muted-foreground mb-1">Description</p>
<p className="text-sm line-clamp-4">{String(project.description)}</p>
</div>
<p className="text-sm text-muted-foreground line-clamp-3">{String(project.description)}</p>
)}
{/* Tags */}
{tags.length > 0 && (
<div>
<p className="text-xs font-medium text-muted-foreground mb-1">Tags</p>
<div className="flex flex-wrap gap-1">
{tags.map((tag: unknown, i: number) => (
<Badge key={i} variant="secondary" className="text-xs">
{String(tag)}
</Badge>
))}
</div>
<div className="flex flex-wrap gap-1">
{tags.map((tag: unknown, i: number) => (
<Badge key={i} variant="secondary" className="text-xs">
{String(tag)}
</Badge>
))}
</div>
)}
{/* Files */}
{files.length > 0 && (
<div>
<p className="text-xs font-medium text-muted-foreground mb-1">
Files ({files.length})
</p>
<div className="space-y-1">
{files.map((file: unknown, i: number) => {
const f = file as Record<string, unknown>
return (
<div key={i} className="flex items-center gap-2 text-sm">
<FileText className="h-3 w-3 text-muted-foreground" />
<span className="truncate">{String(f.fileName || f.fileType || 'File')}</span>
<div className="text-sm text-muted-foreground flex items-center gap-1">
<FileText className="h-3 w-3" />
{files.length} file{files.length > 1 ? 's' : ''} attached
</div>
)}
<Separator />
{/* Evaluation scores with bars */}
{evaluation && scores && typeof scores === 'object' ? (
<div className="space-y-2">
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">Criterion Scores</p>
{Object.entries(scores).map(([criterionId, score]) => {
const numScore = Number(score)
if (isNaN(numScore)) return null
const label = criterionLabels[criterionId]?.label || criterionId
const max = getMax(criterionId)
return (
<div key={criterionId} className="space-y-0.5">
<div className="flex items-center justify-between">
<span className="text-xs text-muted-foreground truncate">{label}</span>
</div>
<ScoreBar score={numScore} max={max} isHighest={false} />
</div>
)
})}
</div>
) : evaluation ? (
<Badge variant="outline">
<CheckCircle2 className="mr-1 h-3 w-3" />
Submitted
</Badge>
) : (
<Badge variant="outline">
<Clock className="mr-1 h-3 w-3" />
Not yet evaluated
</Badge>
)}
</CardContent>
</Card>
)
}
function CriterionComparisonTable({
items,
criteria,
scales,
}: {
items: ComparisonItem[]
criteria: Criterion[]
scales: Record<string, { min: number; max: number }> | null
}) {
const scoreableCriteria = criteria.filter((c) => c.type !== 'section_header')
const getMax = (criterion: Criterion) => {
if (criterion.scale && scales && scales[criterion.scale]) return scales[criterion.scale].max
return 10
}
// Build score matrix
const getScore = (item: ComparisonItem, criterionId: string): number | null => {
const scores = (item.evaluation?.criterionScoresJson || item.evaluation?.scores) as Record<string, unknown> | undefined
if (!scores) return null
const val = scores[criterionId]
if (val == null) return null
const num = Number(val)
return isNaN(num) ? null : num
}
return (
<Card>
<CardHeader>
<CardTitle className="text-lg">Criterion-by-Criterion Comparison</CardTitle>
<CardDescription>
Scores compared side by side. Highest score per criterion is highlighted.
</CardDescription>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead className="min-w-[200px]">Criterion</TableHead>
{items.map((item) => (
<TableHead key={item.assignmentId} className="text-center min-w-[150px]">
{String((item.project as Record<string, unknown>).title || 'Untitled')}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{scoreableCriteria.map((criterion) => {
const max = getMax(criterion)
const itemScores = items.map((item) => getScore(item, criterion.id))
const validScores = itemScores.filter((s): s is number => s !== null)
const highestScore = validScores.length > 0 ? Math.max(...validScores) : null
return (
<TableRow key={criterion.id}>
<TableCell className="font-medium">
<div>
<span className="text-sm">{criterion.label}</span>
{criterion.weight && criterion.weight > 1 && (
<span className="text-xs text-muted-foreground ml-1">
(x{criterion.weight})
</span>
)}
</div>
</TableCell>
{items.map((item, idx) => {
const score = itemScores[idx]
const isHighest = score !== null && score === highestScore && validScores.filter((s) => s === highestScore).length < validScores.length
return (
<TableCell key={item.assignmentId} className="text-center">
{score !== null ? (
<div className="flex flex-col items-center gap-1">
<span className={cn(
'text-sm font-medium tabular-nums',
isHighest && 'text-green-600 dark:text-green-400 font-bold',
getScoreTextColor(score, max)
)}>
{score}/{max}
</span>
<div className="w-full max-w-[80px] h-1.5 bg-muted rounded-full overflow-hidden">
<div
className={cn('h-full rounded-full', getScoreColor(score, max))}
style={{ width: `${(score / max) * 100}%` }}
/>
</div>
</div>
) : (
<span className="text-sm text-muted-foreground">-</span>
)}
</TableCell>
)
})}
</TableRow>
)
})}
</div>
</div>
)}
{/* Evaluation scores */}
{evaluation && (
<div className="border-t pt-3">
<p className="text-xs font-medium text-muted-foreground mb-2">Your Evaluation</p>
{scores && typeof scores === 'object' ? (
<div className="space-y-1">
{Object.entries(scores).map(([criterion, score]) => (
<div key={criterion} className="flex items-center justify-between text-sm">
<span className="text-muted-foreground truncate">{criterion}</span>
<span className="font-medium tabular-nums">{String(score)}</span>
</div>
))}
</div>
) : (
<Badge variant="outline">
<CheckCircle2 className="mr-1 h-3 w-3" />
Submitted
</Badge>
)}
{evaluation.globalScore != null && (
<div className="mt-2 flex items-center justify-between font-medium text-sm border-t pt-2">
<span>Overall Score</span>
<span className="text-primary">{String(evaluation.globalScore)}</span>
</div>
)}
</div>
)}
{/* Global score row */}
<TableRow className="border-t-2 font-semibold">
<TableCell>Overall Score</TableCell>
{items.map((item) => {
const globalScore = item.evaluation?.globalScore as number | null | undefined
return (
<TableCell key={item.assignmentId} className="text-center">
{globalScore != null ? (
<span className={cn(
'text-base font-bold tabular-nums',
getScoreTextColor(globalScore, 10)
)}>
{globalScore}/10
</span>
) : (
<span className="text-muted-foreground">-</span>
)}
</TableCell>
)
})}
</TableRow>
{!evaluation && (
<div className="border-t pt-3">
<Badge variant="outline">
<Clock className="mr-1 h-3 w-3" />
Not yet evaluated
</Badge>
</div>
)}
{/* Binary decision row */}
<TableRow>
<TableCell>Advance Decision</TableCell>
{items.map((item) => {
const decision = item.evaluation?.binaryDecision as boolean | null | undefined
return (
<TableCell key={item.assignmentId} className="text-center">
{decision != null ? (
decision ? (
<Badge variant="success" className="gap-1">
<CheckCircle2 className="h-3 w-3" /> Yes
</Badge>
) : (
<Badge variant="destructive" className="gap-1">
<XCircle className="h-3 w-3" /> No
</Badge>
)
) : (
<span className="text-muted-foreground">-</span>
)}
</TableCell>
)
})}
</TableRow>
</TableBody>
</Table>
</div>
</CardContent>
</Card>
)

View File

@ -17,15 +17,28 @@ import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Progress } from '@/components/ui/progress'
import { Skeleton } from '@/components/ui/skeleton'
import { Separator } from '@/components/ui/separator'
import {
ClipboardList,
CheckCircle2,
Clock,
AlertCircle,
ArrowRight,
GitCompare,
Zap,
BarChart3,
Target,
} from 'lucide-react'
import { formatDateOnly } from '@/lib/utils'
import { CountdownTimer } from '@/components/shared/countdown-timer'
import { cn } from '@/lib/utils'
function getGreeting(): string {
const hour = new Date().getHours()
if (hour < 12) return 'Good morning'
if (hour < 18) return 'Good afternoon'
return 'Good evening'
}
async function JuryDashboardContent() {
const session = await auth()
@ -37,15 +50,14 @@ async function JuryDashboardContent() {
// Get all assignments for this jury member
const assignments = await prisma.assignment.findMany({
where: {
userId,
},
where: { userId },
include: {
project: {
select: {
id: true,
title: true,
teamName: true,
country: true,
},
},
round: {
@ -58,6 +70,7 @@ async function JuryDashboardContent() {
program: {
select: {
name: true,
year: true,
},
},
},
@ -67,6 +80,10 @@ async function JuryDashboardContent() {
id: true,
status: true,
submittedAt: true,
criterionScoresJson: true,
form: {
select: { criteriaJson: true },
},
},
},
},
@ -118,7 +135,6 @@ async function JuryDashboardContent() {
},
})
// Build a map of roundId -> latest extendedUntil
const graceByRound = new Map<string, Date>()
for (const gp of gracePeriods) {
const existing = graceByRound.get(gp.roundId)
@ -127,7 +143,7 @@ async function JuryDashboardContent() {
}
}
// Get active rounds (voting window is open)
// Active rounds (voting window open)
const now = new Date()
const activeRounds = Object.values(assignmentsByRound).filter(
({ round }) =>
@ -138,157 +154,393 @@ async function JuryDashboardContent() {
new Date(round.votingEndAt) >= now
)
// Find next unevaluated assignment in an active round
const nextUnevaluated = assignments.find((a) => {
const isActive =
a.round.status === 'ACTIVE' &&
a.round.votingStartAt &&
a.round.votingEndAt &&
new Date(a.round.votingStartAt) <= now &&
new Date(a.round.votingEndAt) >= now
const isIncomplete = !a.evaluation || a.evaluation.status === 'NOT_STARTED' || a.evaluation.status === 'DRAFT'
return isActive && isIncomplete
})
// Recent assignments for the quick list (latest 5)
const recentAssignments = assignments.slice(0, 6)
// Get active round remaining count
const activeRemaining = assignments.filter((a) => {
const isActive =
a.round.status === 'ACTIVE' &&
a.round.votingStartAt &&
a.round.votingEndAt &&
new Date(a.round.votingStartAt) <= now &&
new Date(a.round.votingEndAt) >= now
const isIncomplete = !a.evaluation || a.evaluation.status !== 'SUBMITTED'
return isActive && isIncomplete
}).length
const stats = [
{
label: 'Total Assignments',
value: totalAssignments,
icon: ClipboardList,
iconBg: 'bg-blue-100 dark:bg-blue-900/30',
iconColor: 'text-blue-600 dark:text-blue-400',
},
{
label: 'Completed',
value: completedAssignments,
icon: CheckCircle2,
iconBg: 'bg-green-100 dark:bg-green-900/30',
iconColor: 'text-green-600 dark:text-green-400',
},
{
label: 'In Progress',
value: inProgressAssignments,
icon: Clock,
iconBg: 'bg-amber-100 dark:bg-amber-900/30',
iconColor: 'text-amber-600 dark:text-amber-400',
},
{
label: 'Pending',
value: pendingAssignments,
icon: Target,
iconBg: 'bg-slate-100 dark:bg-slate-800',
iconColor: 'text-slate-500',
},
]
return (
<>
{/* Hero CTA - Jump to next evaluation */}
{nextUnevaluated && activeRemaining > 0 && (
<Card className="border-primary/20 bg-gradient-to-r from-primary/5 to-accent/5">
<CardContent className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 py-5">
<div className="flex items-center gap-3">
<div className="rounded-full bg-primary/10 p-2.5">
<Zap className="h-5 w-5 text-primary" />
</div>
<div>
<p className="font-semibold">
{activeRemaining} evaluation{activeRemaining > 1 ? 's' : ''} remaining
</p>
<p className="text-sm text-muted-foreground">
Continue with &quot;{nextUnevaluated.project.title}&quot;
</p>
</div>
</div>
<Button asChild>
<Link href={`/jury/projects/${nextUnevaluated.project.id}/evaluate`}>
{nextUnevaluated.evaluation?.status === 'DRAFT' ? 'Continue Evaluation' : 'Start Evaluation'}
<ArrowRight className="ml-2 h-4 w-4" />
</Link>
</Button>
</CardContent>
</Card>
)}
{/* Stats */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Total Assignments
</CardTitle>
<ClipboardList className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totalAssignments}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Completed</CardTitle>
<CheckCircle2 className="h-4 w-4 text-green-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{completedAssignments}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">In Progress</CardTitle>
<Clock className="h-4 w-4 text-amber-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{inProgressAssignments}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Pending</CardTitle>
<AlertCircle className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{pendingAssignments}</div>
</CardContent>
</Card>
{stats.map((stat) => (
<Card key={stat.label}>
<CardContent className="flex items-center gap-4 py-4">
<div className={cn('rounded-full p-2.5', stat.iconBg)}>
<stat.icon className={cn('h-5 w-5', stat.iconColor)} />
</div>
<div>
<p className="text-2xl font-bold tabular-nums">{stat.value}</p>
<p className="text-sm text-muted-foreground">{stat.label}</p>
</div>
</CardContent>
</Card>
))}
</div>
{/* Progress */}
{/* Overall Progress */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Overall Progress</CardTitle>
</CardHeader>
<CardContent>
<Progress value={completionRate} className="h-3" />
<p className="mt-2 text-sm text-muted-foreground">
{completedAssignments} of {totalAssignments} evaluations completed (
{completionRate.toFixed(0)}%)
</p>
<CardContent className="py-4">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<BarChart3 className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium">Overall Completion</span>
</div>
<span className="text-sm font-semibold tabular-nums">
{completedAssignments}/{totalAssignments} ({completionRate.toFixed(0)}%)
</span>
</div>
<Progress value={completionRate} className="h-2.5" />
</CardContent>
</Card>
{/* Active Rounds */}
{activeRounds.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-lg">Active Voting Rounds</CardTitle>
<CardDescription>
These rounds are currently open for evaluation
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{activeRounds.map(({ round, assignments: roundAssignments }) => {
const roundCompleted = roundAssignments.filter(
(a) => a.evaluation?.status === 'SUBMITTED'
).length
const roundTotal = roundAssignments.length
const roundProgress =
roundTotal > 0 ? (roundCompleted / roundTotal) * 100 : 0
{/* Main content — two column layout */}
<div className="grid gap-6 lg:grid-cols-12">
{/* Left column */}
<div className="lg:col-span-7 space-y-6">
{/* Recent Assignments */}
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-lg">My Assignments</CardTitle>
<Button variant="ghost" size="sm" asChild>
<Link href="/jury/assignments">
View all
<ArrowRight className="ml-1 h-3 w-3" />
</Link>
</Button>
</div>
</CardHeader>
<CardContent>
{recentAssignments.length > 0 ? (
<div className="divide-y">
{recentAssignments.map((assignment) => {
const evaluation = assignment.evaluation
const isCompleted = evaluation?.status === 'SUBMITTED'
const isDraft = evaluation?.status === 'DRAFT'
const isVotingOpen =
assignment.round.status === 'ACTIVE' &&
assignment.round.votingStartAt &&
assignment.round.votingEndAt &&
new Date(assignment.round.votingStartAt) <= now &&
new Date(assignment.round.votingEndAt) >= now
return (
<div
key={round.id}
className="rounded-lg border p-4 space-y-3"
>
<div className="flex items-start justify-between">
<div>
<h3 className="font-medium">{round.name}</h3>
<p className="text-sm text-muted-foreground">
{round.program.name}
</p>
</div>
<Badge variant="default">Active</Badge>
</div>
<div className="space-y-1">
<div className="flex justify-between text-sm">
<span>Progress</span>
<span>
{roundCompleted}/{roundTotal}
</span>
</div>
<Progress value={roundProgress} className="h-2" />
</div>
{round.votingEndAt && (
<div className="flex items-center gap-2 flex-wrap">
<CountdownTimer
deadline={graceByRound.get(round.id) ?? new Date(round.votingEndAt)}
label="Deadline:"
/>
<span className="text-xs text-muted-foreground">
({formatDateOnly(round.votingEndAt)})
</span>
</div>
)}
<Button asChild size="sm" className="w-full sm:w-auto">
<Link href={`/jury/assignments?round=${round.id}`}>
View Assignments
<ArrowRight className="ml-2 h-4 w-4" />
</Link>
</Button>
return (
<div
key={assignment.id}
className="flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0"
>
<Link
href={`/jury/projects/${assignment.project.id}`}
className="flex-1 min-w-0 group"
>
<p className="text-sm font-medium truncate group-hover:text-primary group-hover:underline transition-colors">
{assignment.project.title}
</p>
<div className="flex items-center gap-2 mt-0.5">
<span className="text-xs text-muted-foreground truncate">
{assignment.project.teamName}
</span>
<Badge variant="secondary" className="text-[10px] px-1.5 py-0">
{assignment.round.name}
</Badge>
</div>
</Link>
<div className="flex items-center gap-2 shrink-0">
{isCompleted ? (
<Badge variant="success" className="text-xs">
<CheckCircle2 className="mr-1 h-3 w-3" />
Done
</Badge>
) : isDraft ? (
<Badge variant="warning" className="text-xs">
<Clock className="mr-1 h-3 w-3" />
Draft
</Badge>
) : (
<Badge variant="secondary" className="text-xs">Pending</Badge>
)}
{isCompleted ? (
<Button variant="ghost" size="sm" asChild className="h-7 px-2">
<Link href={`/jury/projects/${assignment.project.id}/evaluation`}>
View
</Link>
</Button>
) : isVotingOpen ? (
<Button size="sm" asChild className="h-7 px-2">
<Link href={`/jury/projects/${assignment.project.id}/evaluate`}>
{isDraft ? 'Continue' : 'Evaluate'}
</Link>
</Button>
) : (
<Button variant="ghost" size="sm" asChild className="h-7 px-2">
<Link href={`/jury/projects/${assignment.project.id}`}>
View
</Link>
</Button>
)}
</div>
</div>
)
})}
</div>
)
})}
</CardContent>
</Card>
)}
) : (
<div className="flex flex-col items-center justify-center py-8 text-center">
<ClipboardList className="h-10 w-10 text-muted-foreground/30" />
<p className="mt-2 text-sm text-muted-foreground">
No assignments yet
</p>
</div>
)}
</CardContent>
</Card>
{/* No active rounds message */}
{activeRounds.length === 0 && totalAssignments > 0 && (
<Card>
<CardContent className="flex flex-col items-center justify-center py-8 text-center">
<Clock className="h-12 w-12 text-muted-foreground/50" />
<p className="mt-2 font-medium">No active voting rounds</p>
<p className="text-sm text-muted-foreground">
Check back later when a voting window opens
</p>
</CardContent>
</Card>
)}
{/* Quick Actions */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-lg">Quick Actions</CardTitle>
</CardHeader>
<CardContent>
<div className="grid gap-3 sm:grid-cols-2">
<Button variant="outline" className="justify-start h-auto py-3" asChild>
<Link href="/jury/assignments">
<ClipboardList className="mr-2 h-4 w-4 text-muted-foreground" />
<div className="text-left">
<p className="font-medium">All Assignments</p>
<p className="text-xs text-muted-foreground">View and manage evaluations</p>
</div>
</Link>
</Button>
<Button variant="outline" className="justify-start h-auto py-3" asChild>
<Link href="/jury/compare">
<GitCompare className="mr-2 h-4 w-4 text-muted-foreground" />
<div className="text-left">
<p className="font-medium">Compare Projects</p>
<p className="text-xs text-muted-foreground">Side-by-side comparison</p>
</div>
</Link>
</Button>
</div>
</CardContent>
</Card>
</div>
{/* No assignments message */}
{/* Right column */}
<div className="lg:col-span-5 space-y-6">
{/* Active Rounds */}
{activeRounds.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-lg">Active Voting Rounds</CardTitle>
<CardDescription>
Rounds currently open for evaluation
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{activeRounds.map(({ round, assignments: roundAssignments }) => {
const roundCompleted = roundAssignments.filter(
(a) => a.evaluation?.status === 'SUBMITTED'
).length
const roundTotal = roundAssignments.length
const roundProgress =
roundTotal > 0 ? (roundCompleted / roundTotal) * 100 : 0
const isAlmostDone = roundProgress >= 80
const deadline = graceByRound.get(round.id) ?? (round.votingEndAt ? new Date(round.votingEndAt) : null)
const isUrgent = deadline && (deadline.getTime() - now.getTime()) < 24 * 60 * 60 * 1000
return (
<div
key={round.id}
className={cn(
'rounded-lg border p-4 space-y-3 transition-colors',
isUrgent && 'border-red-200 bg-red-50/50 dark:border-red-900 dark:bg-red-950/20'
)}
>
<div className="flex items-start justify-between">
<div>
<h3 className="font-medium">{round.name}</h3>
<p className="text-xs text-muted-foreground">
{round.program.name} &middot; {round.program.year}
</p>
</div>
{isAlmostDone ? (
<Badge variant="success">Almost done</Badge>
) : (
<Badge variant="default">Active</Badge>
)}
</div>
<div className="space-y-1">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Progress</span>
<span className="font-medium tabular-nums">
{roundCompleted}/{roundTotal}
</span>
</div>
<Progress value={roundProgress} className="h-2" />
</div>
{deadline && (
<div className="flex items-center gap-2 flex-wrap">
<CountdownTimer
deadline={deadline}
label="Deadline:"
/>
{round.votingEndAt && (
<span className="text-xs text-muted-foreground">
({formatDateOnly(round.votingEndAt)})
</span>
)}
</div>
)}
<Button asChild size="sm" className="w-full">
<Link href={`/jury/assignments?round=${round.id}`}>
View Assignments
<ArrowRight className="ml-2 h-4 w-4" />
</Link>
</Button>
</div>
)
})}
</CardContent>
</Card>
)}
{/* No active rounds */}
{activeRounds.length === 0 && totalAssignments > 0 && (
<Card>
<CardContent className="flex flex-col items-center justify-center py-8 text-center">
<div className="rounded-full bg-muted p-3 mb-3">
<Clock className="h-6 w-6 text-muted-foreground" />
</div>
<p className="font-medium">No active voting rounds</p>
<p className="text-sm text-muted-foreground mt-1">
Check back later when a voting window opens
</p>
</CardContent>
</Card>
)}
{/* Completion Summary by Round */}
{Object.keys(assignmentsByRound).length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-lg">Round Summary</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{Object.values(assignmentsByRound).map(({ round, assignments: roundAssignments }) => {
const done = roundAssignments.filter((a) => a.evaluation?.status === 'SUBMITTED').length
const total = roundAssignments.length
const pct = total > 0 ? Math.round((done / total) * 100) : 0
return (
<div key={round.id} className="space-y-1.5">
<div className="flex items-center justify-between text-sm">
<span className="font-medium truncate">{round.name}</span>
<span className="text-muted-foreground tabular-nums shrink-0 ml-2">
{done}/{total} ({pct}%)
</span>
</div>
<Progress value={pct} className="h-1.5" />
</div>
)
})}
</CardContent>
</Card>
)}
</div>
</div>
{/* No assignments at all */}
{totalAssignments === 0 && (
<Card>
<CardContent className="flex flex-col items-center justify-center py-8 text-center">
<ClipboardList className="h-12 w-12 text-muted-foreground/50" />
<p className="mt-2 font-medium">No assignments yet</p>
<p className="text-sm text-muted-foreground">
You&apos;ll see your project assignments here once they&apos;re
assigned
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
<div className="rounded-full bg-muted p-4 mb-4">
<ClipboardList className="h-8 w-8 text-muted-foreground" />
</div>
<p className="text-lg font-medium">No assignments yet</p>
<p className="text-sm text-muted-foreground mt-1 max-w-sm">
You&apos;ll see your project assignments here once they&apos;re assigned to you by an administrator.
</p>
</CardContent>
</Card>
@ -303,24 +555,51 @@ function DashboardSkeleton() {
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{[...Array(4)].map((_, i) => (
<Card key={i}>
<CardHeader className="space-y-0 pb-2">
<Skeleton className="h-4 w-24" />
</CardHeader>
<CardContent>
<Skeleton className="h-8 w-12" />
<CardContent className="flex items-center gap-4 py-4">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="space-y-2">
<Skeleton className="h-6 w-12" />
<Skeleton className="h-4 w-20" />
</div>
</CardContent>
</Card>
))}
</div>
<Card>
<CardHeader>
<Skeleton className="h-5 w-32" />
</CardHeader>
<CardContent>
<Skeleton className="h-3 w-full" />
<Skeleton className="mt-2 h-4 w-48" />
<CardContent className="py-4">
<Skeleton className="h-2.5 w-full" />
</CardContent>
</Card>
<div className="grid gap-6 lg:grid-cols-12">
<div className="lg:col-span-7">
<Card>
<CardHeader>
<Skeleton className="h-5 w-32" />
</CardHeader>
<CardContent className="space-y-4">
{[...Array(4)].map((_, i) => (
<div key={i} className="flex items-center justify-between">
<div className="space-y-1.5">
<Skeleton className="h-4 w-48" />
<Skeleton className="h-3 w-32" />
</div>
<Skeleton className="h-7 w-20" />
</div>
))}
</CardContent>
</Card>
</div>
<div className="lg:col-span-5">
<Card>
<CardHeader>
<Skeleton className="h-5 w-40" />
</CardHeader>
<CardContent className="space-y-4">
<Skeleton className="h-24 w-full rounded-lg" />
</CardContent>
</Card>
</div>
</div>
</>
)
}
@ -332,9 +611,11 @@ export default async function JuryDashboardPage() {
<div className="space-y-6">
{/* Header */}
<div>
<h1 className="text-2xl font-semibold tracking-tight">Dashboard</h1>
<h1 className="text-2xl font-semibold tracking-tight">
{getGreeting()}, {session?.user?.name || 'Juror'}
</h1>
<p className="text-muted-foreground">
Welcome back, {session?.user?.name || 'Juror'}
Here&apos;s an overview of your evaluation progress
</p>
</div>

View File

@ -18,6 +18,7 @@ import { Separator } from '@/components/ui/separator'
import { Skeleton } from '@/components/ui/skeleton'
import {
ArrowLeft,
ArrowRight,
CheckCircle2,
ThumbsUp,
ThumbsDown,
@ -89,6 +90,28 @@ async function EvaluationContent({ projectId }: { projectId: string }) {
notFound()
}
// Find next unevaluated project for "Next Project" navigation
const now = new Date()
const nextAssignment = await prisma.assignment.findFirst({
where: {
userId,
id: { not: assignment?.id ?? undefined },
round: {
status: 'ACTIVE',
votingStartAt: { lte: now },
votingEndAt: { gte: now },
},
OR: [
{ evaluation: null },
{ evaluation: { status: { in: ['NOT_STARTED', 'DRAFT'] } } },
],
},
select: {
project: { select: { id: true, title: true } },
},
orderBy: { round: { votingEndAt: 'asc' } },
})
if (!assignment) {
return (
<div className="space-y-6">
@ -332,13 +355,23 @@ async function EvaluationContent({ projectId }: { projectId: string }) {
</Card>
{/* Navigation */}
<div className="flex justify-between">
<div className="flex flex-col gap-3 sm:flex-row sm:justify-between">
<Button variant="outline" asChild>
<Link href={`/jury/projects/${projectId}`}>View Project Details</Link>
</Button>
<Button asChild>
<Link href="/jury/assignments">Back to All Assignments</Link>
</Button>
<div className="flex gap-2">
<Button variant="outline" asChild>
<Link href="/jury/assignments">All Assignments</Link>
</Button>
{nextAssignment && (
<Button asChild>
<Link href={`/jury/projects/${nextAssignment.project.id}/evaluate`}>
Next Project
<ArrowRight className="ml-2 h-4 w-4" />
</Link>
</Button>
)}
</div>
</div>
</div>
)

View File

@ -25,7 +25,7 @@ export default async function RootLayout({
const messages = await getMessages()
return (
<html lang={locale} className="light">
<html lang={locale} suppressHydrationWarning>
<body className="min-h-screen bg-background font-sans antialiased">
<NextIntlClientProvider messages={messages}>
<Providers>{children}</Providers>

View File

@ -2,6 +2,7 @@
import { useState } from 'react'
import { SessionProvider } from 'next-auth/react'
import { ThemeProvider } from 'next-themes'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { httpBatchLink } from '@trpc/client'
import superjson from 'superjson'
@ -52,10 +53,12 @@ export function Providers({ children }: { children: React.ReactNode }) {
)
return (
<SessionProvider>
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</trpc.Provider>
</SessionProvider>
<ThemeProvider attribute="class" defaultTheme="light" enableSystem={false}>
<SessionProvider>
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</trpc.Provider>
</SessionProvider>
</ThemeProvider>
)
}

View File

@ -2,6 +2,8 @@
import { BookOpen, ClipboardList, GitCompare, Home } from 'lucide-react'
import { RoleNav, type NavItem, type RoleNavUser } from '@/components/layouts/role-nav'
import { trpc } from '@/lib/trpc/client'
import { Badge } from '@/components/ui/badge'
const navigation: NavItem[] = [
{
@ -30,6 +32,38 @@ interface JuryNavProps {
user: RoleNavUser
}
function RemainingBadge() {
const { data: assignments } = trpc.assignment.myAssignments.useQuery(
{},
{ refetchInterval: 60000 }
)
if (!assignments) return null
const now = new Date()
const remaining = (assignments as Array<{
round: { status: string; votingStartAt: Date | null; votingEndAt: Date | null }
evaluation: { status: string } | null
}>).filter((a) => {
const isActive =
a.round.status === 'ACTIVE' &&
a.round.votingStartAt &&
a.round.votingEndAt &&
new Date(a.round.votingStartAt) <= now &&
new Date(a.round.votingEndAt) >= now
const isIncomplete = !a.evaluation || a.evaluation.status !== 'SUBMITTED'
return isActive && isIncomplete
}).length
if (remaining === 0) return null
return (
<Badge variant="secondary" className="text-xs font-medium">
{remaining} remaining
</Badge>
)
}
export function JuryNav({ user }: JuryNavProps) {
return (
<RoleNav
@ -37,6 +71,7 @@ export function JuryNav({ user }: JuryNavProps) {
roleName="Jury"
user={user}
basePath="/jury"
statusBadge={<RemainingBadge />}
/>
)
}

View File

@ -1,6 +1,6 @@
'use client'
import { useState } from 'react'
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { signOut } from 'next-auth/react'
@ -17,7 +17,8 @@ import {
} from '@/components/ui/dropdown-menu'
import type { Route } from 'next'
import type { LucideIcon } from 'lucide-react'
import { LogOut, Menu, Settings, User, X } from 'lucide-react'
import { LogOut, Menu, Moon, Settings, Sun, User, X } from 'lucide-react'
import { useTheme } from 'next-themes'
import { Logo } from '@/components/shared/logo'
import { NotificationBell } from '@/components/shared/notification-bell'
@ -38,23 +39,31 @@ type RoleNavProps = {
user: RoleNavUser
/** The base path for the role (e.g., '/jury', '/mentor', '/observer'). Used for active state detection on the dashboard link. */
basePath: string
/** Optional status badge displayed next to the logo (e.g., remaining evaluations count) */
statusBadge?: React.ReactNode
}
function isNavItemActive(pathname: string, href: string, basePath: string): boolean {
return pathname === href || (href !== basePath && pathname.startsWith(href))
}
export function RoleNav({ navigation, roleName, user, basePath }: RoleNavProps) {
export function RoleNav({ navigation, roleName, user, basePath, statusBadge }: RoleNavProps) {
const pathname = usePathname()
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
const { data: avatarUrl } = trpc.avatar.getUrl.useQuery()
const { theme, setTheme } = useTheme()
const [mounted, setMounted] = useState(false)
useEffect(() => setMounted(true), [])
return (
<header className="sticky top-0 z-40 border-b bg-card">
<div className="container-app">
<div className="flex h-16 items-center justify-between">
{/* Logo */}
<Logo showText textSuffix={roleName} />
<div className="flex items-center gap-3">
<Logo showText textSuffix={roleName} />
{statusBadge}
</div>
{/* Desktop nav */}
<nav className="hidden md:flex items-center gap-1">
@ -80,6 +89,20 @@ export function RoleNav({ navigation, roleName, user, basePath }: RoleNavProps)
{/* User menu & mobile toggle */}
<div className="flex items-center gap-2">
{mounted && (
<Button
variant="ghost"
size="icon"
onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
aria-label="Toggle theme"
>
{theme === 'dark' ? (
<Sun className="h-5 w-5" />
) : (
<Moon className="h-5 w-5" />
)}
</Button>
)}
<NotificationBell />
<DropdownMenu>
<DropdownMenuTrigger asChild>

View File

@ -1,6 +1,6 @@
'use client'
import { useState } from 'react'
import { useEffect, useState } from 'react'
import Link from 'next/link'
import type { Route } from 'next'
import { usePathname } from 'next/navigation'
@ -250,6 +250,14 @@ export function NotificationBell() {
onSuccess: () => refetch(),
})
// Auto-mark all notifications as read when popover opens
useEffect(() => {
if (open && (countData ?? 0) > 0) {
markAllAsReadMutation.mutate()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open])
const unreadCount = countData ?? 0
const notifications = notificationData?.notifications ?? []

View File

@ -674,11 +674,23 @@ export const evaluationRouter = router({
})
}
return assignments.map((a) => ({
project: a.project,
evaluation: a.evaluation,
assignmentId: a.id,
}))
// Fetch the active evaluation form for this round to get criteria labels
const evaluationForm = await ctx.prisma.evaluationForm.findFirst({
where: { roundId: input.roundId, isActive: true },
select: { criteriaJson: true, scalesJson: true },
})
return {
items: assignments.map((a) => ({
project: a.project,
evaluation: a.evaluation,
assignmentId: a.id,
})),
criteria: evaluationForm?.criteriaJson as Array<{
id: string; label: string; description?: string; scale?: string; weight?: number; type?: string
}> | null,
scales: evaluationForm?.scalesJson as Record<string, { min: number; max: number }> | null,
}
}),
// =========================================================================

View File

@ -1057,7 +1057,7 @@ export const mentorRouter = router({
userId: ctx.user.id,
action: 'COMPLETE_MILESTONE',
entityType: 'MentorMilestoneCompletion',
entityId: `${completion.milestoneId}_${completion.mentorAssignmentId}`,
entityId: completion.id,
detailsJson: {
milestoneId: input.milestoneId,
mentorAssignmentId: input.mentorAssignmentId,

View File

@ -247,7 +247,7 @@ export const messageRouter = router({
subject: input.subject,
body: input.body,
variables: input.variables ?? undefined,
createdById: ctx.user.id,
createdBy: ctx.user.id,
},
})