Round system redesign: Phases 1-7 complete

Full pipeline/track/stage architecture replacing the legacy round system.

Schema: 11 new models (Pipeline, Track, Stage, StageTransition,
ProjectStageState, RoutingRule, Cohort, CohortProject, LiveProgressCursor,
OverrideAction, AudienceVoter) + 8 new enums.

Backend: 9 new routers (pipeline, stage, routing, stageFiltering,
stageAssignment, cohort, live, decision, award) + 6 new services
(stage-engine, routing-engine, stage-filtering, stage-assignment,
stage-notifications, live-control).

Frontend: Pipeline wizard (17 components), jury stage pages (7),
applicant pipeline pages (3), public stage pages (2), admin pipeline
pages (5), shared stage components (3), SSE route, live hook.

Phase 6 refit: 23 routers/services migrated from roundId to stageId,
all frontend components refitted. Deleted round.ts (985 lines),
roundTemplate.ts, round-helpers.ts, round-settings.ts, round-type-settings.tsx,
10 legacy admin pages, 7 legacy jury pages, 3 legacy dialogs.

Phase 7 validation: 36 tests (10 unit + 8 integration files) all passing,
TypeScript 0 errors, Next.js build succeeds, 13 integrity checks,
legacy symbol sweep clean, auto-seed on first Docker startup.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-13 13:57:09 +01:00
parent 8a328357e3
commit 331b67dae0
256 changed files with 29117 additions and 21424 deletions

View File

@@ -2,6 +2,7 @@
import { useState } from 'react'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import {
Card,
@@ -41,6 +42,7 @@ import {
GitCompare,
UserCheck,
Globe,
Layers,
} from 'lucide-react'
import { formatDateOnly } from '@/lib/utils'
import {
@@ -51,7 +53,7 @@ import {
ProjectRankingsChart,
CriteriaScoresChart,
GeographicDistribution,
CrossRoundComparisonChart,
CrossStageComparisonChart,
JurorConsistencyChart,
DiversityMetricsChart,
} from '@/components/charts'
@@ -59,11 +61,13 @@ import { ExportPdfButton } from '@/components/shared/export-pdf-button'
import { AnimatedCard } from '@/components/shared/animated-container'
function ReportsOverview() {
const { data: programs, isLoading } = trpc.program.list.useQuery({ includeRounds: true })
const { data: programs, isLoading } = trpc.program.list.useQuery({ includeStages: true })
const { data: dashStats, isLoading: statsLoading } = trpc.analytics.getDashboardStats.useQuery()
// Flatten rounds from all programs
const rounds = programs?.flatMap(p => p.rounds.map(r => ({ ...r, programId: p.id, programName: `${p.year} Edition` }))) || []
// Flatten stages from all programs
const rounds = programs?.flatMap(p =>
((p.stages ?? []) as Array<{ id: string; name: string; status: string; votingEndAt?: string | Date | null }>).map((s: { id: string; name: string; status: string; votingEndAt?: string | Date | null }) => ({ ...s, programId: p.id, programName: `${p.year} Edition` }))
) || []
// Project reporting scope (default: latest program, all rounds)
const [selectedValue, setSelectedValue] = useState<string | null>(null)
@@ -73,7 +77,7 @@ function ReportsOverview() {
}
const scopeInput = parseSelection(selectedValue)
const hasScope = !!scopeInput.roundId || !!scopeInput.programId
const hasScope = !!scopeInput.stageId || !!scopeInput.programId
const { data: projectRankings, isLoading: projectsLoading } =
trpc.analytics.getProjectRankings.useQuery(
@@ -103,7 +107,7 @@ function ReportsOverview() {
const totalPrograms = dashStats?.programCount ?? programs?.length ?? 0
const totalProjects = dashStats?.projectCount ?? 0
const activeRounds = dashStats?.activeRoundCount ?? rounds.filter((r) => r.status === 'ACTIVE').length
const activeRounds = dashStats?.activeStageCount ?? rounds.filter((r: { status: string }) => r.status === 'STAGE_ACTIVE').length
const jurorCount = dashStats?.jurorCount ?? 0
const submittedEvaluations = dashStats?.submittedEvaluations ?? 0
const totalEvaluations = dashStats?.totalEvaluations ?? 0
@@ -365,7 +369,7 @@ function ReportsOverview() {
<div className="flex justify-end gap-2 flex-wrap">
<Button variant="outline" size="sm" asChild>
<a
href={`/api/export/evaluations?roundId=${round.id}`}
href={`/api/export/evaluations?stageId=${round.id}`}
target="_blank"
rel="noopener noreferrer"
>
@@ -375,7 +379,7 @@ function ReportsOverview() {
</Button>
<Button variant="outline" size="sm" asChild>
<a
href={`/api/export/results?roundId=${round.id}`}
href={`/api/export/results?stageId=${round.id}`}
target="_blank"
rel="noopener noreferrer"
>
@@ -396,28 +400,30 @@ function ReportsOverview() {
)
}
// Parse selection value: "all:programId" for edition-wide, or roundId
function parseSelection(value: string | null): { roundId?: string; programId?: string } {
// Parse selection value: "all:programId" for edition-wide, or stageId
function parseSelection(value: string | null): { stageId?: string; programId?: string } {
if (!value) return {}
if (value.startsWith('all:')) return { programId: value.slice(4) }
return { roundId: value }
return { stageId: value }
}
function RoundAnalytics() {
function StageAnalytics() {
const [selectedValue, setSelectedValue] = useState<string | null>(null)
const { data: programs, isLoading: roundsLoading } = trpc.program.list.useQuery({ includeRounds: true })
const { data: programs, isLoading: roundsLoading } = trpc.program.list.useQuery({ includeStages: true })
// Flatten rounds from all programs with program name
const rounds = programs?.flatMap(p => p.rounds.map(r => ({ ...r, programId: p.id, programName: `${p.year} Edition` }))) || []
// Flatten stages from all programs with program name
const rounds = programs?.flatMap(p =>
((p.stages ?? []) as Array<{ id: string; name: string }>).map((s: { id: string; name: string }) => ({ ...s, programId: p.id, programName: `${p.year} Edition` }))
) || []
// Set default selected round
// Set default selected stage
if (rounds.length && !selectedValue) {
setSelectedValue(rounds[0].id)
}
const queryInput = parseSelection(selectedValue)
const hasSelection = !!queryInput.roundId || !!queryInput.programId
const hasSelection = !!queryInput.stageId || !!queryInput.programId
const { data: scoreDistribution, isLoading: scoreLoading } =
trpc.analytics.getScoreDistribution.useQuery(
@@ -458,11 +464,11 @@ function RoundAnalytics() {
const selectedRound = rounds.find((r) => r.id === selectedValue)
const geoInput = queryInput.programId
? { programId: queryInput.programId }
: { programId: selectedRound?.programId || '', roundId: queryInput.roundId }
: { programId: selectedRound?.programId || '', stageId: queryInput.stageId }
const { data: geoData, isLoading: geoLoading } =
trpc.analytics.getGeographicDistribution.useQuery(
geoInput,
{ enabled: hasSelection && !!(geoInput.programId || geoInput.roundId) }
{ enabled: hasSelection && !!(geoInput.programId || geoInput.stageId) }
)
if (roundsLoading) {
@@ -600,26 +606,26 @@ function RoundAnalytics() {
)
}
function CrossRoundTab() {
const { data: programs, isLoading: programsLoading } = trpc.program.list.useQuery({ includeRounds: true })
function CrossStageTab() {
const { data: programs, isLoading: programsLoading } = trpc.program.list.useQuery({ includeStages: true })
const rounds = programs?.flatMap(p =>
p.rounds.map(r => ({ id: r.id, name: r.name, programName: `${p.year} Edition` }))
const stages = programs?.flatMap((p) =>
((p.stages ?? []) as Array<{ id: string; name: string }>).map((s: { id: string; name: string }) => ({ id: s.id, name: s.name, programName: `${p.year} Edition` }))
) || []
const [selectedRoundIds, setSelectedRoundIds] = useState<string[]>([])
const [selectedStageIds, setSelectedStageIds] = useState<string[]>([])
const { data: comparison, isLoading: comparisonLoading } =
trpc.analytics.getCrossRoundComparison.useQuery(
{ roundIds: selectedRoundIds },
{ enabled: selectedRoundIds.length >= 2 }
trpc.analytics.getCrossStageComparison.useQuery(
{ stageIds: selectedStageIds },
{ enabled: selectedStageIds.length >= 2 }
)
const toggleRound = (roundId: string) => {
setSelectedRoundIds((prev) =>
prev.includes(roundId)
? prev.filter((id) => id !== roundId)
: [...prev, roundId]
const toggleStage = (stageId: string) => {
setSelectedStageIds((prev) =>
prev.includes(stageId)
? prev.filter((id) => id !== stageId)
: [...prev, stageId]
)
}
@@ -629,40 +635,40 @@ function CrossRoundTab() {
return (
<div className="space-y-6">
{/* Round selector */}
{/* Stage selector */}
<Card>
<CardHeader>
<CardTitle>Select Rounds to Compare</CardTitle>
<CardTitle>Select Stages to Compare</CardTitle>
<CardDescription>
Choose at least 2 rounds to compare metrics side by side
Choose at least 2 stages to compare metrics side by side
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-wrap gap-2">
{rounds.map((round) => {
const isSelected = selectedRoundIds.includes(round.id)
{stages.map((stage) => {
const isSelected = selectedStageIds.includes(stage.id)
return (
<Badge
key={round.id}
key={stage.id}
variant={isSelected ? 'default' : 'outline'}
className="cursor-pointer text-sm py-1.5 px-3"
onClick={() => toggleRound(round.id)}
onClick={() => toggleStage(stage.id)}
>
{round.programName} - {round.name}
{stage.programName} - {stage.name}
</Badge>
)
})}
</div>
{selectedRoundIds.length < 2 && (
{selectedStageIds.length < 2 && (
<p className="text-sm text-muted-foreground mt-3">
Select at least 2 rounds to enable comparison
Select at least 2 stages to enable comparison
</p>
)}
</CardContent>
</Card>
{/* Comparison charts */}
{comparisonLoading && selectedRoundIds.length >= 2 && (
{comparisonLoading && selectedStageIds.length >= 2 && (
<div className="space-y-6">
<Skeleton className="h-[350px]" />
<div className="grid gap-6 lg:grid-cols-2">
@@ -673,9 +679,9 @@ function CrossRoundTab() {
)}
{comparison && (
<CrossRoundComparisonChart data={comparison as Array<{
roundId: string
roundName: string
<CrossStageComparisonChart data={comparison as Array<{
stageId: string
stageName: string
projectCount: number
evaluationCount: number
completionRate: number
@@ -690,18 +696,18 @@ function CrossRoundTab() {
function JurorConsistencyTab() {
const [selectedValue, setSelectedValue] = useState<string | null>(null)
const { data: programs, isLoading: programsLoading } = trpc.program.list.useQuery({ includeRounds: true })
const { data: programs, isLoading: programsLoading } = trpc.program.list.useQuery({ includeStages: true })
const rounds = programs?.flatMap(p =>
p.rounds.map(r => ({ id: r.id, name: r.name, programId: p.id, programName: `${p.year} Edition` }))
const stages = programs?.flatMap((p) =>
((p.stages ?? []) as Array<{ id: string; name: string }>).map((s: { id: string; name: string }) => ({ id: s.id, name: s.name, programId: p.id, programName: `${p.year} Edition` }))
) || []
if (rounds.length && !selectedValue) {
setSelectedValue(rounds[0].id)
if (stages.length && !selectedValue) {
setSelectedValue(stages[0].id)
}
const queryInput = parseSelection(selectedValue)
const hasSelection = !!queryInput.roundId || !!queryInput.programId
const hasSelection = !!queryInput.stageId || !!queryInput.programId
const { data: consistency, isLoading: consistencyLoading } =
trpc.analytics.getJurorConsistency.useQuery(
@@ -716,20 +722,20 @@ function JurorConsistencyTab() {
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<label className="text-sm font-medium">Select Round:</label>
<label className="text-sm font-medium">Select Stage:</label>
<Select value={selectedValue || ''} onValueChange={setSelectedValue}>
<SelectTrigger className="w-[300px]">
<SelectValue placeholder="Select a round" />
<SelectValue placeholder="Select a stage" />
</SelectTrigger>
<SelectContent>
{programs?.map((p) => (
<SelectItem key={`all:${p.id}`} value={`all:${p.id}`}>
{p.year} Edition All Rounds
{p.year} Edition All Stages
</SelectItem>
))}
{rounds.map((round) => (
<SelectItem key={round.id} value={round.id}>
{round.programName} - {round.name}
{stages.map((stage) => (
<SelectItem key={stage.id} value={stage.id}>
{stage.programName} - {stage.name}
</SelectItem>
))}
</SelectContent>
@@ -762,18 +768,18 @@ function JurorConsistencyTab() {
function DiversityTab() {
const [selectedValue, setSelectedValue] = useState<string | null>(null)
const { data: programs, isLoading: programsLoading } = trpc.program.list.useQuery({ includeRounds: true })
const { data: programs, isLoading: programsLoading } = trpc.program.list.useQuery({ includeStages: true })
const rounds = programs?.flatMap(p =>
p.rounds.map(r => ({ id: r.id, name: r.name, programId: p.id, programName: `${p.year} Edition` }))
const stages = programs?.flatMap((p) =>
((p.stages ?? []) as Array<{ id: string; name: string }>).map((s: { id: string; name: string }) => ({ id: s.id, name: s.name, programId: p.id, programName: `${p.year} Edition` }))
) || []
if (rounds.length && !selectedValue) {
setSelectedValue(rounds[0].id)
if (stages.length && !selectedValue) {
setSelectedValue(stages[0].id)
}
const queryInput = parseSelection(selectedValue)
const hasSelection = !!queryInput.roundId || !!queryInput.programId
const hasSelection = !!queryInput.stageId || !!queryInput.programId
const { data: diversity, isLoading: diversityLoading } =
trpc.analytics.getDiversityMetrics.useQuery(
@@ -788,20 +794,20 @@ function DiversityTab() {
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<label className="text-sm font-medium">Select Round:</label>
<label className="text-sm font-medium">Select Stage:</label>
<Select value={selectedValue || ''} onValueChange={setSelectedValue}>
<SelectTrigger className="w-[300px]">
<SelectValue placeholder="Select a round" />
<SelectValue placeholder="Select a stage" />
</SelectTrigger>
<SelectContent>
{programs?.map((p) => (
<SelectItem key={`all:${p.id}`} value={`all:${p.id}`}>
{p.year} Edition All Rounds
{p.year} Edition All Stages
</SelectItem>
))}
{rounds.map((round) => (
<SelectItem key={round.id} value={round.id}>
{round.programName} - {round.name}
{stages.map((stage) => (
<SelectItem key={stage.id} value={stage.id}>
{stage.programName} - {stage.name}
</SelectItem>
))}
</SelectContent>
@@ -826,18 +832,18 @@ function DiversityTab() {
}
export default function ReportsPage() {
const [pdfRoundId, setPdfRoundId] = useState<string | null>(null)
const [pdfStageId, setPdfStageId] = useState<string | null>(null)
const { data: pdfPrograms } = trpc.program.list.useQuery({ includeRounds: true })
const pdfRounds = pdfPrograms?.flatMap((p) =>
p.rounds.map((r) => ({ id: r.id, name: r.name, programName: `${p.year} Edition` }))
const { data: pdfPrograms } = trpc.program.list.useQuery({ includeStages: true })
const pdfStages = pdfPrograms?.flatMap((p) =>
((p.stages ?? []) as Array<{ id: string; name: string }>).map((s: { id: string; name: string }) => ({ id: s.id, name: s.name, programName: `${p.year} Edition` }))
) || []
if (pdfRounds.length && !pdfRoundId) {
setPdfRoundId(pdfRounds[0].id)
if (pdfStages.length && !pdfStageId) {
setPdfStageId(pdfStages[0].id)
}
const selectedPdfRound = pdfRounds.find((r) => r.id === pdfRoundId)
const selectedPdfStage = pdfStages.find((r) => r.id === pdfStageId)
return (
<div className="space-y-6">
@@ -861,7 +867,7 @@ export default function ReportsPage() {
<TrendingUp className="h-4 w-4" />
Analytics
</TabsTrigger>
<TabsTrigger value="cross-round" className="gap-2">
<TabsTrigger value="cross-stage" className="gap-2">
<GitCompare className="h-4 w-4" />
Cross-Round
</TabsTrigger>
@@ -873,25 +879,31 @@ export default function ReportsPage() {
<Globe className="h-4 w-4" />
Diversity
</TabsTrigger>
<TabsTrigger value="pipeline" className="gap-2" asChild>
<Link href={"/admin/reports/stages" as Route}>
<Layers className="h-4 w-4" />
By Pipeline
</Link>
</TabsTrigger>
</TabsList>
<div className="flex items-center gap-2 w-full sm:w-auto justify-between sm:justify-end">
<Select value={pdfRoundId || ''} onValueChange={setPdfRoundId}>
<Select value={pdfStageId || ''} onValueChange={setPdfStageId}>
<SelectTrigger className="w-[220px]">
<SelectValue placeholder="Select round for PDF" />
<SelectValue placeholder="Select stage for PDF" />
</SelectTrigger>
<SelectContent>
{pdfRounds.map((round) => (
<SelectItem key={round.id} value={round.id}>
{round.programName} - {round.name}
{pdfStages.map((stage) => (
<SelectItem key={stage.id} value={stage.id}>
{stage.programName} - {stage.name}
</SelectItem>
))}
</SelectContent>
</Select>
{pdfRoundId && (
{pdfStageId && (
<ExportPdfButton
roundId={pdfRoundId}
roundName={selectedPdfRound?.name}
programName={selectedPdfRound?.programName}
stageId={pdfStageId}
roundName={selectedPdfStage?.name}
programName={selectedPdfStage?.programName}
/>
)}
</div>
@@ -902,11 +914,11 @@ export default function ReportsPage() {
</TabsContent>
<TabsContent value="analytics">
<RoundAnalytics />
<StageAnalytics />
</TabsContent>
<TabsContent value="cross-round">
<CrossRoundTab />
<TabsContent value="cross-stage">
<CrossStageTab />
</TabsContent>
<TabsContent value="consistency">

View File

@@ -0,0 +1,671 @@
'use client'
import { useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import { useEdition } from '@/contexts/edition-context'
import Link from 'next/link'
import type { Route } from 'next'
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { Progress } from '@/components/ui/progress'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import {
ArrowLeft,
BarChart3,
Layers,
Users,
CheckCircle2,
Target,
Trophy,
} from 'lucide-react'
import { cn } from '@/lib/utils'
const stateColors: Record<string, string> = {
PENDING: 'bg-gray-100 text-gray-700',
IN_PROGRESS: 'bg-blue-100 text-blue-700',
PASSED: 'bg-emerald-100 text-emerald-700',
REJECTED: 'bg-red-100 text-red-700',
COMPLETED: 'bg-emerald-100 text-emerald-700',
ELIMINATED: 'bg-red-100 text-red-700',
WAITING: 'bg-amber-100 text-amber-700',
}
const awardStatusColors: Record<string, string> = {
DRAFT: 'bg-gray-100 text-gray-700',
NOMINATIONS_OPEN: 'bg-blue-100 text-blue-700',
VOTING_OPEN: 'bg-amber-100 text-amber-700',
CLOSED: 'bg-emerald-100 text-emerald-700',
ARCHIVED: 'bg-gray-100 text-gray-500',
}
// ─── Stages Tab Content ────────────────────────────────────────────────────
function StagesTabContent({
activePipelineId,
}: {
activePipelineId: string
}) {
const [selectedStageId, setSelectedStageId] = useState<string>('')
const { data: overview, isLoading: overviewLoading } =
trpc.analytics.getStageCompletionOverview.useQuery(
{ pipelineId: activePipelineId },
{ enabled: !!activePipelineId }
)
const { data: scoreDistribution, isLoading: scoresLoading } =
trpc.analytics.getStageScoreDistribution.useQuery(
{ stageId: selectedStageId },
{ enabled: !!selectedStageId }
)
if (overviewLoading) {
return (
<div className="space-y-4">
<div className="grid gap-4 sm:grid-cols-4">
{[...Array(4)].map((_, i) => (
<Skeleton key={i} className="h-24" />
))}
</div>
<Skeleton className="h-64 w-full" />
</div>
)
}
if (!overview) {
return (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
<BarChart3 className="h-12 w-12 text-muted-foreground/50 mb-3" />
<p className="font-medium">No pipeline data</p>
<p className="text-sm text-muted-foreground mt-1">
Select a pipeline to view analytics.
</p>
</CardContent>
</Card>
)
}
return (
<>
{/* Summary cards */}
<div className="grid gap-4 sm:grid-cols-4">
<Card>
<CardContent className="py-5 text-center">
<Layers className="h-5 w-5 text-muted-foreground mx-auto mb-1" />
<p className="text-2xl font-bold">{overview.summary.totalStages}</p>
<p className="text-xs text-muted-foreground">Total Stages</p>
</CardContent>
</Card>
<Card>
<CardContent className="py-5 text-center">
<Target className="h-5 w-5 text-muted-foreground mx-auto mb-1" />
<p className="text-2xl font-bold">{overview.summary.totalProjects}</p>
<p className="text-xs text-muted-foreground">Total Projects</p>
</CardContent>
</Card>
<Card>
<CardContent className="py-5 text-center">
<Users className="h-5 w-5 text-muted-foreground mx-auto mb-1" />
<p className="text-2xl font-bold">{overview.summary.totalAssignments}</p>
<p className="text-xs text-muted-foreground">Total Assignments</p>
</CardContent>
</Card>
<Card>
<CardContent className="py-5 text-center">
<CheckCircle2 className="h-5 w-5 text-emerald-600 mx-auto mb-1" />
<p className="text-2xl font-bold">{overview.summary.totalCompleted}</p>
<p className="text-xs text-muted-foreground">Evaluations Completed</p>
</CardContent>
</Card>
</div>
{/* Stage overview table */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Stage Completion Overview</CardTitle>
<CardDescription>
Click a stage to see detailed score distribution
</CardDescription>
</CardHeader>
<CardContent className="p-0">
<Table>
<TableHeader>
<TableRow>
<TableHead>Stage</TableHead>
<TableHead>Track</TableHead>
<TableHead>Type</TableHead>
<TableHead className="text-center">Projects</TableHead>
<TableHead className="text-center">Assignments</TableHead>
<TableHead className="text-center">Completed</TableHead>
<TableHead className="text-center">Jurors</TableHead>
<TableHead>Progress</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{overview.stages.map((stage) => (
<TableRow
key={stage.stageId}
className={cn(
'cursor-pointer transition-colors',
selectedStageId === stage.stageId && 'bg-brand-blue/5 dark:bg-brand-teal/5'
)}
onClick={() => setSelectedStageId(stage.stageId)}
>
<TableCell className="font-medium">{stage.stageName}</TableCell>
<TableCell className="text-muted-foreground text-sm">{stage.trackName}</TableCell>
<TableCell>
<Badge variant="outline" className="text-xs capitalize">
{stage.stageType.toLowerCase().replace(/_/g, ' ')}
</Badge>
</TableCell>
<TableCell className="text-center tabular-nums">{stage.totalProjects}</TableCell>
<TableCell className="text-center tabular-nums">{stage.totalAssignments}</TableCell>
<TableCell className="text-center tabular-nums">{stage.completedEvaluations}</TableCell>
<TableCell className="text-center tabular-nums">{stage.jurorCount}</TableCell>
<TableCell>
<div className="flex items-center gap-2 min-w-[120px]">
<Progress value={stage.completionRate} className="h-2 flex-1" />
<span className="text-xs tabular-nums font-medium w-8 text-right">
{stage.completionRate}%
</span>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
{/* State breakdown per stage */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Project State Breakdown</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{overview.stages.map((stage) => (
<div key={stage.stageId} className="space-y-2">
<p className="text-sm font-medium">{stage.stageName}</p>
<div className="flex flex-wrap gap-2">
{stage.stateBreakdown.map((sb) => (
<Badge
key={sb.state}
variant="outline"
className={cn('text-xs', stateColors[sb.state])}
>
{sb.state}: {sb.count}
</Badge>
))}
{stage.stateBreakdown.length === 0 && (
<span className="text-xs text-muted-foreground">No projects</span>
)}
</div>
</div>
))}
</div>
</CardContent>
</Card>
{/* Score distribution for selected stage */}
{selectedStageId && (
<Card>
<CardHeader>
<CardTitle className="text-lg">
Score Distribution
{overview.stages.find((s) => s.stageId === selectedStageId) && (
<span className="text-sm font-normal text-muted-foreground ml-2">
{overview.stages.find((s) => s.stageId === selectedStageId)?.stageName}
</span>
)}
</CardTitle>
</CardHeader>
<CardContent>
{scoresLoading ? (
<Skeleton className="h-48 w-full" />
) : scoreDistribution ? (
<div className="space-y-4">
<div className="grid gap-3 sm:grid-cols-3">
<div className="text-center">
<p className="text-2xl font-bold tabular-nums">
{scoreDistribution.totalEvaluations}
</p>
<p className="text-xs text-muted-foreground">Evaluations</p>
</div>
<div className="text-center">
<p className="text-2xl font-bold tabular-nums">
{scoreDistribution.averageGlobalScore.toFixed(1)}
</p>
<p className="text-xs text-muted-foreground">Avg Score</p>
</div>
<div className="text-center">
<p className="text-2xl font-bold tabular-nums">
{scoreDistribution.criterionDistributions.length}
</p>
<p className="text-xs text-muted-foreground">Criteria</p>
</div>
</div>
{/* Score histogram (text-based) */}
<div className="space-y-2">
<p className="text-sm font-medium">Global Score Distribution</p>
{scoreDistribution.globalDistribution.map((bucket) => {
const maxCount = Math.max(
...scoreDistribution.globalDistribution.map((b) => b.count),
1
)
const width = (bucket.count / maxCount) * 100
return (
<div key={bucket.score} className="flex items-center gap-2">
<span className="text-xs tabular-nums w-4 text-right">{bucket.score}</span>
<div className="flex-1 h-5 bg-muted/30 rounded overflow-hidden">
<div
className="h-full bg-brand-blue/60 dark:bg-brand-teal/60 rounded transition-all"
style={{ width: `${width}%` }}
/>
</div>
<span className="text-xs tabular-nums w-6 text-right">{bucket.count}</span>
</div>
)
})}
</div>
</div>
) : (
<p className="text-sm text-muted-foreground">No score data available for this stage.</p>
)}
</CardContent>
</Card>
)}
</>
)
}
// ─── Awards Tab Content ────────────────────────────────────────────────────
function AwardsTabContent({
activePipelineId,
}: {
activePipelineId: string
}) {
const [selectedAwardStageId, setSelectedAwardStageId] = useState<string>('')
const { data: awards, isLoading: awardsLoading } =
trpc.analytics.getAwardSummary.useQuery(
{ pipelineId: activePipelineId },
{ enabled: !!activePipelineId }
)
const { data: voteDistribution, isLoading: votesLoading } =
trpc.analytics.getAwardVoteDistribution.useQuery(
{ stageId: selectedAwardStageId },
{ enabled: !!selectedAwardStageId }
)
if (awardsLoading) {
return (
<div className="space-y-4">
<Skeleton className="h-24" />
<Skeleton className="h-64 w-full" />
</div>
)
}
if (!awards || awards.length === 0) {
return (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
<Trophy className="h-12 w-12 text-muted-foreground/50 mb-3" />
<p className="font-medium">No award tracks</p>
<p className="text-sm text-muted-foreground mt-1">
This pipeline has no award tracks configured.
</p>
</CardContent>
</Card>
)
}
return (
<>
{/* Awards summary table */}
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Trophy className="h-5 w-5" />
Award Tracks
</CardTitle>
<CardDescription>
Click an award&apos;s stage to see vote/score distribution
</CardDescription>
</CardHeader>
<CardContent className="p-0">
<Table>
<TableHeader>
<TableRow>
<TableHead>Award</TableHead>
<TableHead>Status</TableHead>
<TableHead>Scoring</TableHead>
<TableHead>Routing</TableHead>
<TableHead className="text-center">Projects</TableHead>
<TableHead className="text-center">Completion</TableHead>
<TableHead>Winner</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{awards.map((award) => (
<TableRow key={award.trackId}>
<TableCell className="font-medium">{award.awardName}</TableCell>
<TableCell>
{award.awardStatus ? (
<Badge
variant="outline"
className={cn('text-xs', awardStatusColors[award.awardStatus])}
>
{award.awardStatus.replace(/_/g, ' ')}
</Badge>
) : (
<span className="text-xs text-muted-foreground"></span>
)}
</TableCell>
<TableCell>
{award.scoringMode ? (
<Badge variant="outline" className="text-xs capitalize">
{award.scoringMode.toLowerCase().replace(/_/g, ' ')}
</Badge>
) : (
<span className="text-xs text-muted-foreground"></span>
)}
</TableCell>
<TableCell>
{award.routingMode ? (
<Badge variant="outline" className="text-xs">
{award.routingMode}
</Badge>
) : (
<span className="text-xs text-muted-foreground"></span>
)}
</TableCell>
<TableCell className="text-center tabular-nums">{award.projectCount}</TableCell>
<TableCell>
<div className="flex items-center gap-2 min-w-[100px]">
<Progress value={award.completionRate} className="h-2 flex-1" />
<span className="text-xs tabular-nums font-medium w-8 text-right">
{award.completionRate}%
</span>
</div>
</TableCell>
<TableCell>
{award.winner ? (
<div className="flex items-center gap-1.5">
<Trophy className="h-3.5 w-3.5 text-amber-500 shrink-0" />
<span className="text-sm font-medium truncate max-w-[150px]">
{award.winner.title}
</span>
{award.winner.overridden && (
<Badge variant="outline" className="text-[10px] px-1 py-0">
overridden
</Badge>
)}
</div>
) : (
<span className="text-xs text-muted-foreground">Not finalized</span>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
{/* Award stages clickable list */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Award Stage Details</CardTitle>
<CardDescription>
Select a stage to view vote and score distribution
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-3">
{awards.map((award) =>
award.stages.map((stage) => (
<button
key={stage.id}
onClick={() => setSelectedAwardStageId(stage.id)}
className={cn(
'w-full text-left rounded-lg border p-3 transition-colors',
selectedAwardStageId === stage.id
? 'border-brand-blue bg-brand-blue/5 dark:border-brand-teal dark:bg-brand-teal/5'
: 'hover:bg-muted/50'
)}
>
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">{award.awardName} {stage.name}</p>
<p className="text-xs text-muted-foreground mt-0.5">
Type: {stage.stageType.toLowerCase().replace(/_/g, ' ')} | Status: {stage.status}
</p>
</div>
<Badge variant="outline" className="text-xs capitalize">
{stage.stageType.toLowerCase().replace(/_/g, ' ')}
</Badge>
</div>
</button>
))
)}
</div>
</CardContent>
</Card>
{/* Vote/score distribution for selected award stage */}
{selectedAwardStageId && (
<Card>
<CardHeader>
<CardTitle className="text-lg">
Vote / Score Distribution
</CardTitle>
</CardHeader>
<CardContent>
{votesLoading ? (
<Skeleton className="h-48 w-full" />
) : voteDistribution && voteDistribution.projects.length > 0 ? (
<div className="space-y-4">
<div className="grid gap-3 sm:grid-cols-2">
<div className="text-center">
<p className="text-2xl font-bold tabular-nums">
{voteDistribution.totalEvaluations}
</p>
<p className="text-xs text-muted-foreground">Evaluations</p>
</div>
<div className="text-center">
<p className="text-2xl font-bold tabular-nums">
{voteDistribution.totalVotes}
</p>
<p className="text-xs text-muted-foreground">Award Votes</p>
</div>
</div>
<Table>
<TableHeader>
<TableRow>
<TableHead>Project</TableHead>
<TableHead>Team</TableHead>
<TableHead className="text-center">Evals</TableHead>
<TableHead className="text-center">Votes</TableHead>
<TableHead className="text-center">Avg Score</TableHead>
<TableHead className="text-center">Min</TableHead>
<TableHead className="text-center">Max</TableHead>
<TableHead className="text-center">Avg Rank</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{voteDistribution.projects.map((project) => (
<TableRow key={project.projectId}>
<TableCell className="font-medium truncate max-w-[200px]">
{project.title}
</TableCell>
<TableCell className="text-sm text-muted-foreground truncate max-w-[120px]">
{project.teamName || '—'}
</TableCell>
<TableCell className="text-center tabular-nums">
{project.evaluationCount}
</TableCell>
<TableCell className="text-center tabular-nums">
{project.voteCount}
</TableCell>
<TableCell className="text-center tabular-nums font-medium">
{project.avgScore !== null ? project.avgScore.toFixed(1) : '—'}
</TableCell>
<TableCell className="text-center tabular-nums">
{project.minScore !== null ? project.minScore.toFixed(1) : '—'}
</TableCell>
<TableCell className="text-center tabular-nums">
{project.maxScore !== null ? project.maxScore.toFixed(1) : '—'}
</TableCell>
<TableCell className="text-center tabular-nums">
{project.avgRank !== null ? project.avgRank.toFixed(1) : '—'}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
) : (
<p className="text-sm text-muted-foreground">No vote/score data available for this stage.</p>
)}
</CardContent>
</Card>
)}
</>
)
}
// ─── Main Page ─────────────────────────────────────────────────────────────
export default function StageAnalyticsReportsPage() {
const { currentEdition } = useEdition()
const programId = currentEdition?.id ?? ''
const [selectedPipelineId, setSelectedPipelineId] = useState<string>('')
// Fetch pipelines
const { data: pipelines, isLoading: pipelinesLoading } =
trpc.pipeline.list.useQuery(
{ programId },
{ enabled: !!programId }
)
// Auto-select first pipeline
const activePipelineId = selectedPipelineId || (pipelines?.[0]?.id ?? '')
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div className="flex items-center gap-3">
<Button variant="ghost" size="icon" asChild className="h-8 w-8">
<Link href={"/admin/reports" as Route}>
<ArrowLeft className="h-4 w-4" />
</Link>
</Button>
<div>
<h1 className="text-2xl font-bold tracking-tight flex items-center gap-2">
<Layers className="h-6 w-6" />
Pipeline Analytics
</h1>
<p className="text-sm text-muted-foreground mt-0.5">
Stage-level reporting for the pipeline system
</p>
</div>
</div>
{/* Pipeline selector */}
{pipelines && pipelines.length > 0 && (
<Select
value={activePipelineId}
onValueChange={(v) => {
setSelectedPipelineId(v)
}}
>
<SelectTrigger className="w-[240px]">
<SelectValue placeholder="Select pipeline" />
</SelectTrigger>
<SelectContent>
{pipelines.map((p) => (
<SelectItem key={p.id} value={p.id}>
{p.name}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
{pipelinesLoading ? (
<div className="space-y-4">
<div className="grid gap-4 sm:grid-cols-4">
{[...Array(4)].map((_, i) => (
<Skeleton key={i} className="h-24" />
))}
</div>
<Skeleton className="h-64 w-full" />
</div>
) : !activePipelineId ? (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
<BarChart3 className="h-12 w-12 text-muted-foreground/50 mb-3" />
<p className="font-medium">No pipeline data</p>
<p className="text-sm text-muted-foreground mt-1">
Select a pipeline to view analytics.
</p>
</CardContent>
</Card>
) : (
<Tabs defaultValue="stages" className="space-y-6">
<TabsList>
<TabsTrigger value="stages" className="gap-2">
<Layers className="h-4 w-4" />
Stages
</TabsTrigger>
<TabsTrigger value="awards" className="gap-2">
<Trophy className="h-4 w-4" />
Awards
</TabsTrigger>
</TabsList>
<TabsContent value="stages" className="space-y-6">
<StagesTabContent activePipelineId={activePipelineId} />
</TabsContent>
<TabsContent value="awards" className="space-y-6">
<AwardsTabContent activePipelineId={activePipelineId} />
</TabsContent>
</Tabs>
)}
</div>
)
}