Add round-type-specific observer reports with dynamic tabs
All checks were successful
Build and Push Docker Image / build (push) Successful in 9m44s

Refactor the observer reports page from a static 3-tab layout to a
dynamic tab system that adapts to each round type (INTAKE, FILTERING,
EVALUATION, SUBMISSION, MENTORING, LIVE_FINAL, DELIBERATION). Adds a
persistent Global tab for edition-wide analytics, juror score heatmap,
expandable juror assignment rows, filtering screening bar, and
deliberation results with tie detection.

- Add 5 observer proxy procedures to analytics router
- Create JurorScoreHeatmap, ExpandableJurorTable, FilteringScreeningBar
- Create 8 round-type tab components + GlobalAnalyticsTab
- Reduce reports page from 914 to ~190 lines (thin dispatcher)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-21 09:29:26 +01:00
parent ee3bfec8b0
commit 2e4b95f29c
14 changed files with 2326 additions and 786 deletions

View File

@@ -10,3 +10,4 @@ export { GeographicSummaryCard } from './geographic-summary-card'
export { CrossStageComparisonChart } from './cross-round-comparison'
export { JurorConsistencyChart } from './juror-consistency'
export { DiversityMetricsChart } from './diversity-metrics'
export { JurorScoreHeatmap } from './juror-score-heatmap'

View File

@@ -0,0 +1,116 @@
'use client'
import { Fragment } from 'react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { scoreGradient } from './chart-theme'
interface JurorScoreHeatmapProps {
jurors: { id: string; name: string }[]
projects: { id: string; title: string }[]
cells: { jurorId: string; projectId: string; score: number | null }[]
truncated?: boolean
totalProjects?: number
}
function getScoreColor(score: number | null): string {
if (score === null) return 'transparent'
return scoreGradient(score)
}
function getTextColor(score: number | null): string {
if (score === null) return 'inherit'
return score >= 6 ? '#ffffff' : '#1a1a1a'
}
export function JurorScoreHeatmap({
jurors,
projects,
cells,
truncated,
totalProjects,
}: JurorScoreHeatmapProps) {
const cellMap = new Map<string, number | null>()
for (const c of cells) {
cellMap.set(`${c.jurorId}:${c.projectId}`, c.score)
}
if (jurors.length === 0 || projects.length === 0) {
return (
<Card>
<CardContent className="flex items-center justify-center py-12">
<p className="text-sm text-muted-foreground">No score data available for heatmap</p>
</CardContent>
</Card>
)
}
return (
<Card>
<CardHeader>
<CardTitle>Score Heatmap</CardTitle>
<CardDescription>
{jurors.length} jurors × {projects.length} projects
{truncated && totalProjects ? ` (showing top 30 of ${totalProjects})` : ''}
</CardDescription>
</CardHeader>
<CardContent>
{/* Mobile fallback */}
<div className="md:hidden text-center py-8">
<p className="text-sm text-muted-foreground">
View on a larger screen for the score heatmap
</p>
</div>
{/* Desktop heatmap */}
<div className="hidden md:block overflow-auto max-h-[600px]">
<div
className="grid gap-px"
style={{
gridTemplateColumns: `180px repeat(${projects.length}, minmax(60px, 1fr))`,
}}
>
{/* Header row */}
<div className="sticky left-0 z-10 bg-background" />
{projects.map((p) => (
<div
key={p.id}
className="text-xs font-medium text-muted-foreground truncate px-1 pb-2 text-center"
title={p.title}
>
{p.title.length > 12 ? p.title.slice(0, 10) + '…' : p.title}
</div>
))}
{/* Data rows */}
{jurors.map((j) => (
<Fragment key={j.id}>
<div
className="sticky left-0 z-10 bg-background text-sm font-medium truncate pr-3 flex items-center"
title={j.name}
>
{j.name}
</div>
{projects.map((p) => {
const score = cellMap.get(`${j.id}:${p.id}`) ?? null
return (
<div
key={`${j.id}-${p.id}`}
className="flex items-center justify-center rounded-sm text-xs font-medium tabular-nums h-8"
style={{
backgroundColor: getScoreColor(score),
color: getTextColor(score),
}}
title={`${j.name}${p.title}: ${score !== null ? score.toFixed(1) : 'N/A'}`}
>
{score !== null ? score.toFixed(1) : '—'}
</div>
)
})}
</Fragment>
))}
</div>
</div>
</CardContent>
</Card>
)
}

View File

@@ -0,0 +1,303 @@
'use client'
import { useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Users, Trophy } from 'lucide-react'
import { RoundTypeStatsCards } from '@/components/observer/round-type-stats'
interface DeliberationReportTabsProps {
roundId: string
programId: string
}
function sessionStatusBadge(status: string) {
switch (status) {
case 'DELIB_LOCKED':
return <Badge variant="default">Locked</Badge>
case 'VOTING':
return <Badge variant="secondary">Voting</Badge>
case 'TALLYING':
return <Badge className="bg-amber-100 text-amber-800 border-amber-200">Tallying</Badge>
case 'RUNOFF':
return <Badge className="bg-rose-100 text-rose-800 border-rose-200">Runoff</Badge>
case 'DELIB_OPEN':
return <Badge variant="outline">Open</Badge>
default:
return <Badge variant="outline">{status}</Badge>
}
}
function sessionModeBadge(mode: string) {
return <Badge variant="outline">{mode.charAt(0) + mode.slice(1).toLowerCase()}</Badge>
}
function SessionsTab({ roundId }: { roundId: string }) {
const { data: sessions, isLoading } =
trpc.analytics.getDeliberationSessions.useQuery({ roundId })
if (isLoading) return <Skeleton className="h-[350px]" />
if (!sessions?.length) {
return (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
<Users className="h-10 w-10 text-muted-foreground/40 mb-3" />
<p className="text-sm font-medium text-muted-foreground">No deliberation sessions yet</p>
<p className="text-xs text-muted-foreground mt-1">
Sessions will appear here once created by administrators
</p>
</CardContent>
</Card>
)
}
return (
<>
{/* Desktop table */}
<div className="hidden md:block rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Category</TableHead>
<TableHead>Mode</TableHead>
<TableHead>Status</TableHead>
<TableHead className="text-right tabular-nums">Participants</TableHead>
<TableHead className="text-right tabular-nums">Votes Cast</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sessions.map((session) => (
<TableRow key={session.id}>
<TableCell className="font-medium">
{session.category ?? <span className="text-muted-foreground italic">General</span>}
</TableCell>
<TableCell>{sessionModeBadge(session.mode)}</TableCell>
<TableCell>{sessionStatusBadge(session.status)}</TableCell>
<TableCell className="text-right tabular-nums">{session._count.participants}</TableCell>
<TableCell className="text-right tabular-nums">{session._count.votes}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{/* Mobile card stack */}
<div className="space-y-3 md:hidden">
{sessions.map((session) => (
<Card key={session.id}>
<CardContent className="pt-4 space-y-3">
<div className="flex items-start justify-between gap-2">
<p className="font-medium text-sm">
{session.category ?? <span className="italic text-muted-foreground">General</span>}
</p>
{sessionStatusBadge(session.status)}
</div>
<div className="flex items-center gap-2">
{sessionModeBadge(session.mode)}
</div>
<div className="grid grid-cols-2 gap-2 text-xs">
<div>
<p className="text-muted-foreground">Participants</p>
<p className="font-medium tabular-nums">{session._count.participants}</p>
</div>
<div>
<p className="text-muted-foreground">Votes Cast</p>
<p className="font-medium tabular-nums">{session._count.votes}</p>
</div>
</div>
</CardContent>
</Card>
))}
</div>
</>
)
}
function ResultsTab({ roundId }: { roundId: string }) {
const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null)
const { data: sessions, isLoading: sessionsLoading } =
trpc.analytics.getDeliberationSessions.useQuery({ roundId })
const activeSessions = sessions?.filter((s) => s._count.votes > 0) ?? []
const activeSessionId = selectedSessionId ?? activeSessions[0]?.id ?? null
const { data: aggregate, isLoading: aggregateLoading } =
trpc.analytics.getDeliberationAggregate.useQuery(
{ sessionId: activeSessionId! },
{ enabled: !!activeSessionId }
)
if (sessionsLoading) return <Skeleton className="h-[400px]" />
if (!activeSessions.length) {
return (
<Card>
<CardContent className="flex items-center justify-center py-12">
<p className="text-sm text-muted-foreground">
No votes have been cast yet. Results will appear once deliberation is underway.
</p>
</CardContent>
</Card>
)
}
const currentSessionId = selectedSessionId ?? activeSessions[0]?.id
return (
<div className="space-y-4">
{/* Session selector if multiple */}
{activeSessions.length > 1 && (
<div className="flex items-center gap-3 flex-wrap">
{activeSessions.map((s) => (
<button
key={s.id}
onClick={() => setSelectedSessionId(s.id)}
className={
currentSessionId === s.id
? 'rounded-full px-3 py-1 text-sm font-medium bg-primary text-primary-foreground'
: 'rounded-full px-3 py-1 text-sm font-medium bg-muted text-muted-foreground hover:bg-muted/80 transition-colors'
}
>
{s.category ?? 'General'}
</button>
))}
</div>
)}
{aggregateLoading ? (
<Skeleton className="h-[300px]" />
) : aggregate ? (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Trophy className="h-4 w-4 text-amber-500" />
Ranking Results
</CardTitle>
<CardDescription>
{aggregate.rankings.length} project{aggregate.rankings.length !== 1 ? 's' : ''} ranked
{aggregate.hasTies && (
<span className="ml-1 text-amber-600 font-medium">· Ties detected</span>
)}
</CardDescription>
</CardHeader>
<CardContent>
{/* Desktop table */}
<div className="hidden md:block rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-12 text-center">Rank</TableHead>
<TableHead>Project</TableHead>
<TableHead>Team</TableHead>
<TableHead className="text-right tabular-nums">Score</TableHead>
<TableHead className="text-right tabular-nums">Votes</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{aggregate.rankings.map((r, idx) => {
const isTied = aggregate.tiedProjectIds.includes(r.projectId)
return (
<TableRow key={r.projectId} className={isTied ? 'bg-amber-50/50' : undefined}>
<TableCell className="text-center font-bold tabular-nums text-lg">
{idx + 1}
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<span className="font-medium">{r.projectTitle}</span>
{isTied && (
<Badge className="bg-amber-100 text-amber-800 border-amber-200 text-[10px]">
Tie
</Badge>
)}
</div>
</TableCell>
<TableCell className="text-muted-foreground text-sm">{r.teamName}</TableCell>
<TableCell className="text-right tabular-nums">
{typeof r.score === 'number' ? r.score : '—'}
</TableCell>
<TableCell className="text-right tabular-nums">{r.voteCount}</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</div>
{/* Mobile list */}
<div className="space-y-2 md:hidden">
{aggregate.rankings.map((r, idx) => {
const isTied = aggregate.tiedProjectIds.includes(r.projectId)
return (
<div
key={r.projectId}
className={`flex items-center gap-3 rounded-md p-3 border${isTied ? ' bg-amber-50/50' : ''}`}
>
<span className="text-2xl font-bold tabular-nums w-8 text-center shrink-0">
{idx + 1}
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<p className="font-medium text-sm truncate">{r.projectTitle}</p>
{isTied && (
<Badge className="bg-amber-100 text-amber-800 border-amber-200 text-[10px]">
Tie
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground">{r.teamName}</p>
</div>
<p className="text-xs text-muted-foreground tabular-nums shrink-0">
{r.voteCount} votes
</p>
</div>
)
})}
</div>
</CardContent>
</Card>
) : null}
</div>
)
}
export function DeliberationReportTabs({ roundId }: DeliberationReportTabsProps) {
return (
<div className="space-y-6">
<RoundTypeStatsCards roundId={roundId} />
<Tabs defaultValue="sessions" className="space-y-6">
<TabsList>
<TabsTrigger value="sessions" className="gap-2">
<Users className="h-4 w-4" />
Sessions
</TabsTrigger>
<TabsTrigger value="results" className="gap-2">
<Trophy className="h-4 w-4" />
Results
</TabsTrigger>
</TabsList>
<TabsContent value="sessions">
<SessionsTab roundId={roundId} />
</TabsContent>
<TabsContent value="results">
<ResultsTab roundId={roundId} />
</TabsContent>
</Tabs>
</div>
)
}

View File

@@ -0,0 +1,764 @@
'use client'
import { useState, useCallback } from 'react'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Skeleton } from '@/components/ui/skeleton'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Button } from '@/components/ui/button'
import {
FileSpreadsheet,
BarChart3,
Users,
TrendingUp,
Download,
Clock,
} from 'lucide-react'
import { formatDateOnly } from '@/lib/utils'
import {
ScoreDistributionChart,
EvaluationTimelineChart,
StatusBreakdownChart,
CriteriaScoresChart,
JurorConsistencyChart,
JurorScoreHeatmap,
} from '@/components/charts'
import { BarChart } from '@tremor/react'
import { CsvExportDialog } from '@/components/shared/csv-export-dialog'
import { ExportPdfButton } from '@/components/shared/export-pdf-button'
import { AnimatedCard } from '@/components/shared/animated-container'
import { RoundTypeStatsCards } from '@/components/observer/round-type-stats'
import { ExpandableJurorTable } from './expandable-juror-table'
const ROUND_TYPE_LABELS: Record<string, string> = {
INTAKE: 'Intake',
FILTERING: 'Filtering',
EVALUATION: 'Evaluation',
SUBMISSION: 'Submission',
MENTORING: 'Mentoring',
LIVE_FINAL: 'Live Final',
DELIBERATION: 'Deliberation',
}
type Stage = {
id: string
name: string
status: string
roundType: string
windowCloseAt: Date | null
_count: { projects: number; assignments: number; evaluations: number }
programId: string
programName: string
}
function roundStatusLabel(status: string): string {
if (status === 'ROUND_ACTIVE') return 'Active'
if (status === 'ROUND_CLOSED') return 'Closed'
if (status === 'ROUND_DRAFT') return 'Draft'
if (status === 'ROUND_ARCHIVED') return 'Archived'
return status
}
function roundStatusVariant(status: string): 'default' | 'secondary' | 'outline' {
if (status === 'ROUND_ACTIVE') return 'default'
if (status === 'ROUND_CLOSED') return 'secondary'
return 'outline'
}
function parseSelection(value: string | null): { roundId?: string; programId?: string } {
if (!value) return {}
if (value.startsWith('all:')) return { programId: value.slice(4) }
return { roundId: value }
}
interface EvaluationReportTabsProps {
roundId: string
programId: string
stages: Stage[]
selectedValue: string | null
}
// ---- Progress sub-tab ----
function ProgressSubTab({
selectedValue,
stages,
stagesLoading,
selectedRound,
}: {
selectedValue: string | null
stages: Stage[]
stagesLoading: boolean
selectedRound: Stage | undefined
}) {
const queryInput = parseSelection(selectedValue)
const hasSelection = !!queryInput.roundId || !!queryInput.programId
const { data: overviewStats, isLoading: statsLoading } =
trpc.analytics.getOverviewStats.useQuery(queryInput, { enabled: hasSelection })
const { data: timeline, isLoading: timelineLoading } =
trpc.analytics.getEvaluationTimeline.useQuery(queryInput, { enabled: hasSelection })
const [csvOpen, setCsvOpen] = useState(false)
const [csvData, setCsvData] = useState<{ data: Record<string, unknown>[]; columns: string[] } | undefined>()
const [csvLoading, setCsvLoading] = useState(false)
const handleRequestCsvData = useCallback(async () => {
setCsvLoading(true)
const columns = ['roundName', 'roundType', 'status', 'projects', 'assignments', 'completionRate']
const data = stages.map((s) => {
const assigned = s._count.assignments
const projects = s._count.projects
const rate = assigned > 0 && projects > 0 ? Math.round((assigned / projects) * 100) : 0
return {
roundName: s.name,
roundType: ROUND_TYPE_LABELS[s.roundType] || s.roundType,
status: roundStatusLabel(s.status),
projects,
assignments: assigned,
completionRate: rate,
}
})
const result = { data, columns }
setCsvData(result)
setCsvLoading(false)
return result
}, [stages])
return (
<div className="space-y-6">
<div className="flex items-center justify-between flex-wrap gap-3">
<div>
<h2 className="text-base font-semibold">Progress Overview</h2>
<p className="text-sm text-muted-foreground">Evaluation progress across rounds</p>
</div>
<div className="flex items-center gap-2">
{selectedValue && !selectedValue.startsWith('all:') && (
<ExportPdfButton
roundId={selectedValue}
roundName={selectedRound?.name}
programName={selectedRound?.programName}
/>
)}
<Button
variant="outline"
size="sm"
onClick={() => setCsvOpen(true)}
disabled={stagesLoading || stages.length === 0}
>
<Download className="mr-2 h-4 w-4" />
Export CSV
</Button>
</div>
</div>
<CsvExportDialog
open={csvOpen}
onOpenChange={setCsvOpen}
exportData={csvData}
isLoading={csvLoading}
filename="round-progress"
onRequestData={handleRequestCsvData}
/>
{/* Stats tiles */}
{hasSelection && (
<>
{statsLoading ? (
<div className="grid gap-4 sm:grid-cols-3">
{[...Array(3)].map((_, i) => (
<Card key={i}>
<CardHeader className="space-y-0 pb-2">
<Skeleton className="h-4 w-20" />
</CardHeader>
<CardContent>
<Skeleton className="h-8 w-16" />
<Skeleton className="mt-2 h-3 w-24" />
</CardContent>
</Card>
))}
</div>
) : overviewStats ? (
<div className="grid gap-4 sm:grid-cols-3">
<AnimatedCard index={0}>
<Card className="border-l-4 border-l-blue-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
<CardContent className="p-5">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-muted-foreground">Project Count</p>
<p className="text-2xl font-bold mt-1">{overviewStats.projectCount}</p>
<p className="text-xs text-muted-foreground mt-1">In selection</p>
</div>
<div className="rounded-xl bg-blue-50 p-3">
<FileSpreadsheet className="h-5 w-5 text-blue-600" />
</div>
</div>
</CardContent>
</Card>
</AnimatedCard>
<AnimatedCard index={1}>
<Card className="border-l-4 border-l-emerald-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
<CardContent className="p-5">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-muted-foreground">Evaluation Count</p>
<p className="text-2xl font-bold mt-1">{overviewStats.evaluationCount}</p>
<p className="text-xs text-muted-foreground mt-1">Submitted</p>
</div>
<div className="rounded-xl bg-emerald-50 p-3">
<TrendingUp className="h-5 w-5 text-emerald-600" />
</div>
</div>
</CardContent>
</Card>
</AnimatedCard>
<AnimatedCard index={2}>
<Card className="border-l-4 border-l-violet-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
<CardContent className="p-5">
<div>
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-muted-foreground">Completion Rate</p>
<p className="text-2xl font-bold mt-1">{overviewStats.completionRate}%</p>
</div>
<div className="rounded-xl bg-violet-50 p-3">
<BarChart3 className="h-5 w-5 text-violet-600" />
</div>
</div>
<Progress value={overviewStats.completionRate} className="mt-3 h-2" gradient />
</div>
</CardContent>
</Card>
</AnimatedCard>
</div>
) : null}
</>
)}
{/* Completion Timeline */}
{hasSelection && (
<>
{timelineLoading ? (
<Skeleton className="h-[320px]" />
) : timeline?.length ? (
<EvaluationTimelineChart data={timeline} />
) : (
<Card>
<CardContent className="flex items-center justify-center py-12">
<p className="text-muted-foreground text-sm">No evaluation timeline data available yet</p>
</CardContent>
</Card>
)}
</>
)}
{/* Round Breakdown Table - Desktop */}
{stagesLoading ? (
<Skeleton className="h-[300px]" />
) : (
<>
<Card className="hidden md:block">
<CardHeader>
<CardTitle>Round Breakdown</CardTitle>
<CardDescription>Progress overview for each round</CardDescription>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Round</TableHead>
<TableHead>Type</TableHead>
<TableHead>Status</TableHead>
<TableHead className="text-right">Projects</TableHead>
<TableHead className="text-right">Assignments</TableHead>
<TableHead className="min-w-[140px]">Completion</TableHead>
<TableHead className="text-right">Avg Days</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{stages.map((stage) => {
const projects = stage._count.projects
const assignments = stage._count.assignments
const evaluations = stage._count.evaluations
const isClosed = stage.status === 'ROUND_CLOSED' || stage.status === 'ROUND_ARCHIVED'
const rate = isClosed
? 100
: assignments > 0
? Math.min(100, Math.round((evaluations / assignments) * 100))
: 0
return (
<TableRow key={stage.id}>
<TableCell>
<div>
<p className="font-medium">{stage.name}</p>
{stage.windowCloseAt && (
<p className="text-xs text-muted-foreground flex items-center gap-1 mt-0.5">
<Clock className="h-3 w-3" />
{formatDateOnly(stage.windowCloseAt)}
</p>
)}
</div>
</TableCell>
<TableCell>
<Badge variant="outline">
{ROUND_TYPE_LABELS[stage.roundType] || stage.roundType}
</Badge>
</TableCell>
<TableCell>
<Badge variant={roundStatusVariant(stage.status)}>
{roundStatusLabel(stage.status)}
</Badge>
</TableCell>
<TableCell className="text-right">{projects}</TableCell>
<TableCell className="text-right">{assignments}</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<Progress value={rate} className="h-2 w-20" />
<span className="text-sm tabular-nums">{rate}%</span>
</div>
</TableCell>
<TableCell className="text-right text-muted-foreground">-</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</CardContent>
</Card>
{/* Round Breakdown Cards - Mobile */}
<div className="space-y-3 md:hidden">
<h2 className="text-base font-semibold">Round Breakdown</h2>
{stages.map((stage) => {
const projects = stage._count.projects
const assignments = stage._count.assignments
const evaluations = stage._count.evaluations
const isClosed = stage.status === 'ROUND_CLOSED' || stage.status === 'ROUND_ARCHIVED'
const rate = isClosed
? 100
: assignments > 0
? Math.min(100, Math.round((evaluations / assignments) * 100))
: 0
return (
<Card key={stage.id}>
<CardContent className="pt-4 space-y-3">
<div className="flex items-start justify-between gap-2">
<p className="font-medium leading-tight">{stage.name}</p>
<Badge variant={roundStatusVariant(stage.status)} className="shrink-0">
{roundStatusLabel(stage.status)}
</Badge>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline">
{ROUND_TYPE_LABELS[stage.roundType] || stage.roundType}
</Badge>
</div>
<div className="grid grid-cols-2 gap-2 text-sm">
<div>
<p className="text-muted-foreground text-xs">Projects</p>
<p className="font-medium">{projects}</p>
</div>
<div>
<p className="text-muted-foreground text-xs">Assignments</p>
<p className="font-medium">{assignments}</p>
</div>
</div>
<div>
<div className="flex items-center justify-between text-sm mb-1">
<span className="text-muted-foreground text-xs">Completion</span>
<span className="font-medium">{rate}%</span>
</div>
<Progress value={rate} className="h-2" />
</div>
{stage.windowCloseAt && (
<p className="text-xs text-muted-foreground flex items-center gap-1">
<Clock className="h-3 w-3" />
Closes: {formatDateOnly(stage.windowCloseAt)}
</p>
)}
</CardContent>
</Card>
)
})}
</div>
</>
)}
</div>
)
}
// ---- Jurors sub-tab ----
function JurorsSubTab({ roundId, selectedValue }: { roundId: string; selectedValue: string | null }) {
const queryInput = parseSelection(selectedValue)
const hasSelection = !!queryInput.roundId || !!queryInput.programId
const { data: workload, isLoading: workloadLoading } =
trpc.analytics.getJurorWorkload.useQuery(queryInput, { enabled: hasSelection })
const { data: consistency, isLoading: consistencyLoading } =
trpc.analytics.getJurorConsistency.useQuery(queryInput, { enabled: hasSelection })
const { data: heatmapData, isLoading: heatmapLoading } =
trpc.analytics.getJurorScoreMatrix.useQuery({ roundId }, { enabled: !!roundId })
const [csvOpen, setCsvOpen] = useState(false)
const [csvData, setCsvData] = useState<{ data: Record<string, unknown>[]; columns: string[] } | undefined>()
const [csvLoading, setCsvLoading] = useState(false)
type WorkloadItem = { id: string; name: string; assigned: number; completed: number; completionRate: number; projects: { id: string; title: string; evalStatus: string }[] }
type ConsistencyJuror = { userId: string; name: string; evaluationCount: number; averageScore: number; stddev: number; isOutlier: boolean }
const handleRequestCsvData = useCallback(async () => {
setCsvLoading(true)
const columns = ['name', 'assigned', 'completed', 'completionRate', 'avgScore', 'stddev', 'isOutlier']
const workloadMap = new Map<string, WorkloadItem>()
if (workload) {
for (const w of (workload as unknown as WorkloadItem[])) {
workloadMap.set(w.id, w)
}
}
const jurors = (consistency as { overallAverage: number; jurors: ConsistencyJuror[] } | undefined)?.jurors ?? []
const data = jurors.map((j) => {
const w = workloadMap.get(j.userId)
return {
name: j.name,
assigned: w?.assigned ?? '-',
completed: w?.completed ?? '-',
completionRate: w ? `${w.completionRate}%` : '-',
avgScore: j.averageScore,
stddev: j.stddev,
isOutlier: j.isOutlier ? 'Yes' : 'No',
}
})
const result = { data, columns }
setCsvData(result)
setCsvLoading(false)
return result
}, [workload, consistency])
const isLoading = workloadLoading || consistencyLoading
type JurorRow = {
userId: string
name: string
assigned: number
completed: number
completionRate: number
averageScore: number
stddev: number
isOutlier: boolean
projects: { id: string; title: string; evalStatus: string }[]
}
const jurors: JurorRow[] = (() => {
if (!consistency) return []
const workloadMap = new Map<string, WorkloadItem>()
if (workload) {
for (const w of (workload as unknown as WorkloadItem[])) {
workloadMap.set(w.id, w)
}
}
const jurorList = (consistency as { overallAverage: number; jurors: ConsistencyJuror[] }).jurors ?? []
return jurorList
.map((j) => {
const w = workloadMap.get(j.userId)
return {
userId: j.userId,
name: j.name,
assigned: w?.assigned ?? 0,
completed: w?.completed ?? 0,
completionRate: w?.completionRate ?? 0,
averageScore: j.averageScore,
stddev: j.stddev,
isOutlier: j.isOutlier,
projects: w?.projects ?? [],
}
})
.sort((a, b) => b.assigned - a.assigned)
})()
return (
<div className="space-y-6">
<div className="flex items-center justify-between flex-wrap gap-3">
<div>
<h2 className="text-base font-semibold">Juror Performance</h2>
<p className="text-sm text-muted-foreground">Workload and scoring consistency per juror</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => setCsvOpen(true)}
disabled={!hasSelection || isLoading}
>
<Download className="mr-2 h-4 w-4" />
Export CSV
</Button>
</div>
<CsvExportDialog
open={csvOpen}
onOpenChange={setCsvOpen}
exportData={csvData}
isLoading={csvLoading}
filename="juror-performance"
onRequestData={handleRequestCsvData}
/>
{/* Expandable Juror Table */}
{isLoading ? (
<Skeleton className="h-[400px]" />
) : jurors.length > 0 ? (
<ExpandableJurorTable jurors={jurors} />
) : hasSelection ? (
<Card>
<CardContent className="flex items-center justify-center py-12">
<p className="text-sm text-muted-foreground">No juror data available for this selection</p>
</CardContent>
</Card>
) : null}
{/* Juror Score Heatmap */}
{heatmapLoading ? (
<Skeleton className="h-[400px]" />
) : heatmapData ? (
<JurorScoreHeatmap
jurors={heatmapData.jurors}
projects={heatmapData.projects}
cells={heatmapData.cells}
truncated={heatmapData.truncated}
totalProjects={heatmapData.totalProjects}
/>
) : null}
{/* Juror Consistency Chart */}
{consistencyLoading ? (
<Skeleton className="h-[400px]" />
) : consistency ? (
<JurorConsistencyChart
data={consistency as { overallAverage: number; jurors: Array<{ userId: string; name: string; evaluationCount: number; averageScore: number; stddev: number; deviationFromOverall: number; isOutlier: boolean }> }}
/>
) : null}
</div>
)
}
// ---- Scores sub-tab ----
function ScoresSubTab({ selectedValue, programId }: { selectedValue: string | null; programId: string }) {
const queryInput = parseSelection(selectedValue)
const hasSelection = !!queryInput.roundId || !!queryInput.programId
const { data: scoreDistribution, isLoading: scoreLoading } =
trpc.analytics.getScoreDistribution.useQuery(queryInput, { enabled: hasSelection })
const { data: statusBreakdown, isLoading: statusLoading } =
trpc.analytics.getStatusBreakdown.useQuery(queryInput, { enabled: hasSelection })
const { data: criteriaScores, isLoading: criteriaLoading } =
trpc.analytics.getCriteriaScores.useQuery(queryInput, { enabled: hasSelection })
const geoProgramId = queryInput.programId || programId
const { data: geoData, isLoading: geoLoading } =
trpc.analytics.getGeographicDistribution.useQuery(
{ programId: geoProgramId, roundId: queryInput.roundId },
{ enabled: !!geoProgramId }
)
const [csvOpen, setCsvOpen] = useState(false)
const [csvData, setCsvData] = useState<{ data: Record<string, unknown>[]; columns: string[] } | undefined>()
const [csvLoading, setCsvLoading] = useState(false)
type CriterionItem = { criterionName: string; averageScore: number; count: number }
const handleRequestCsvData = useCallback(async () => {
setCsvLoading(true)
const columns = ['criterionName', 'averageScore', 'count']
const data = ((criteriaScores as CriterionItem[] | undefined) ?? []).map((c) => ({
criterionName: c.criterionName,
averageScore: c.averageScore,
count: c.count,
}))
const result = { data, columns }
setCsvData(result)
setCsvLoading(false)
return result
}, [criteriaScores])
const countryChartData = (() => {
if (!geoData?.length) return []
const sorted = [...geoData].sort((a, b) => b.count - a.count)
return sorted.slice(0, 15).map((d) => {
let name = d.countryCode
try {
const displayNames = new Intl.DisplayNames(['en'], { type: 'region' })
name = displayNames.of(d.countryCode.toUpperCase()) || d.countryCode
} catch { /* keep code */ }
return { country: name, Projects: d.count }
})
})()
return (
<div className="space-y-6">
<div className="flex items-center justify-between flex-wrap gap-3">
<div>
<h2 className="text-base font-semibold">Scores & Analytics</h2>
<p className="text-sm text-muted-foreground">Score distributions, criteria breakdown and geographic data</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => setCsvOpen(true)}
disabled={!hasSelection || criteriaLoading}
>
<Download className="mr-2 h-4 w-4" />
Export CSV
</Button>
</div>
<CsvExportDialog
open={csvOpen}
onOpenChange={setCsvOpen}
exportData={csvData}
isLoading={csvLoading}
filename="scores-criteria"
onRequestData={handleRequestCsvData}
/>
{/* Score Distribution & Status Breakdown */}
<div className="grid gap-6 lg:grid-cols-2">
{scoreLoading ? (
<Skeleton className="h-[350px]" />
) : scoreDistribution ? (
<ScoreDistributionChart
data={scoreDistribution.distribution ?? []}
averageScore={scoreDistribution.averageScore ?? 0}
totalScores={scoreDistribution.totalScores ?? 0}
/>
) : hasSelection ? (
<Card>
<CardContent className="flex items-center justify-center py-12">
<p className="text-sm text-muted-foreground">No score data available yet</p>
</CardContent>
</Card>
) : null}
{statusLoading ? (
<Skeleton className="h-[350px]" />
) : statusBreakdown ? (
<StatusBreakdownChart data={statusBreakdown} />
) : hasSelection ? (
<Card>
<CardContent className="flex items-center justify-center py-12">
<p className="text-sm text-muted-foreground">No status data available yet</p>
</CardContent>
</Card>
) : null}
</div>
{/* Criteria Breakdown */}
{criteriaLoading ? (
<Skeleton className="h-[350px]" />
) : criteriaScores?.length ? (
<CriteriaScoresChart data={criteriaScores} />
) : hasSelection ? (
<Card>
<CardContent className="flex items-center justify-center py-12">
<p className="text-sm text-muted-foreground">No criteria score data available yet</p>
</CardContent>
</Card>
) : null}
{/* Country Distribution */}
{geoLoading ? (
<Skeleton className="h-[400px]" />
) : countryChartData.length > 0 ? (
<Card>
<CardHeader>
<CardTitle className="flex items-center justify-between">
<span>Top Countries</span>
<span className="text-sm font-normal text-muted-foreground">
{geoData?.length ?? 0} countries represented
</span>
</CardTitle>
</CardHeader>
<CardContent>
<BarChart
data={countryChartData}
index="country"
categories={['Projects']}
colors={['blue']}
layout="vertical"
yAxisWidth={140}
showLegend={false}
className="h-[400px]"
/>
</CardContent>
</Card>
) : null}
</div>
)
}
// ---- Main component ----
export function EvaluationReportTabs({ roundId, programId, stages, selectedValue }: EvaluationReportTabsProps) {
const selectedRound = stages.find((s) => s.id === selectedValue)
const stagesLoading = false // stages passed from parent already loaded
return (
<div className="space-y-6">
<RoundTypeStatsCards roundId={roundId} />
<Tabs defaultValue="progress" className="space-y-6">
<TabsList>
<TabsTrigger value="progress" className="gap-2">
<TrendingUp className="h-4 w-4" />
Progress
</TabsTrigger>
<TabsTrigger value="jurors" className="gap-2">
<Users className="h-4 w-4" />
Jurors
</TabsTrigger>
<TabsTrigger value="scores" className="gap-2">
<BarChart3 className="h-4 w-4" />
Scores
</TabsTrigger>
</TabsList>
<TabsContent value="progress">
<ProgressSubTab
selectedValue={selectedValue}
stages={stages}
stagesLoading={stagesLoading}
selectedRound={selectedRound}
/>
</TabsContent>
<TabsContent value="jurors">
<JurorsSubTab roundId={roundId} selectedValue={selectedValue} />
</TabsContent>
<TabsContent value="scores">
<ScoresSubTab selectedValue={selectedValue} programId={programId} />
</TabsContent>
</Tabs>
</div>
)
}

View File

@@ -0,0 +1,232 @@
'use client'
import { useState } from 'react'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { ChevronDown, ChevronUp } from 'lucide-react'
import Link from 'next/link'
interface JurorRow {
userId: string
name: string
assigned: number
completed: number
completionRate: number
averageScore: number
stddev: number
isOutlier: boolean
projects: { id: string; title: string; evalStatus: string }[]
}
interface ExpandableJurorTableProps {
jurors: JurorRow[]
}
function evalStatusBadge(status: string) {
switch (status) {
case 'REVIEWED':
return <Badge variant="default">Reviewed</Badge>
case 'UNDER_REVIEW':
return <Badge variant="secondary">Under Review</Badge>
default:
return <Badge variant="outline">Not Reviewed</Badge>
}
}
export function ExpandableJurorTable({ jurors }: ExpandableJurorTableProps) {
const [expanded, setExpanded] = useState<string | null>(null)
function toggle(userId: string) {
setExpanded((prev) => (prev === userId ? null : userId))
}
if (jurors.length === 0) {
return (
<Card>
<CardContent className="flex items-center justify-center py-12">
<p className="text-sm text-muted-foreground">No juror data available</p>
</CardContent>
</Card>
)
}
return (
<>
{/* Desktop table */}
<div className="hidden md:block rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Juror</TableHead>
<TableHead className="text-right tabular-nums">Assigned</TableHead>
<TableHead className="text-right tabular-nums">Completed</TableHead>
<TableHead>Rate</TableHead>
<TableHead className="text-right tabular-nums">Avg Score</TableHead>
<TableHead className="text-right tabular-nums">Std Dev</TableHead>
<TableHead>Status</TableHead>
<TableHead className="w-8" />
</TableRow>
</TableHeader>
<TableBody>
{jurors.map((j) => (
<>
<TableRow
key={j.userId}
className="cursor-pointer hover:bg-muted/50"
onClick={() => toggle(j.userId)}
>
<TableCell className="font-medium">{j.name}</TableCell>
<TableCell className="text-right tabular-nums">{j.assigned}</TableCell>
<TableCell className="text-right tabular-nums">{j.completed}</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<Progress value={j.completionRate} className="w-20 h-2" />
<span className="text-xs tabular-nums text-muted-foreground">
{j.completionRate.toFixed(0)}%
</span>
</div>
</TableCell>
<TableCell className="text-right tabular-nums">
{j.averageScore > 0 ? j.averageScore.toFixed(2) : '—'}
</TableCell>
<TableCell className="text-right tabular-nums">
{j.stddev > 0 ? j.stddev.toFixed(2) : '—'}
</TableCell>
<TableCell>
{j.isOutlier ? (
<Badge variant="destructive">Outlier</Badge>
) : (
<Badge variant="outline">Normal</Badge>
)}
</TableCell>
<TableCell>
{expanded === j.userId ? (
<ChevronUp className="h-4 w-4 text-muted-foreground" />
) : (
<ChevronDown className="h-4 w-4 text-muted-foreground" />
)}
</TableCell>
</TableRow>
{expanded === j.userId && (
<TableRow key={`${j.userId}-expanded`}>
<TableCell colSpan={8} className="bg-muted/30 p-0">
<div className="px-6 py-3">
{j.projects.length === 0 ? (
<p className="text-sm text-muted-foreground">No projects</p>
) : (
<table className="w-full text-sm">
<thead>
<tr className="text-left text-xs text-muted-foreground border-b">
<th className="pb-2 font-medium">Project</th>
<th className="pb-2 font-medium">Evaluation Status</th>
</tr>
</thead>
<tbody>
{j.projects.map((p) => (
<tr key={p.id} className="border-b last:border-0">
<td className="py-1.5 pr-4">
<Link
href={`/observer/projects/${p.id}`}
className="text-primary hover:underline"
onClick={(e) => e.stopPropagation()}
>
{p.title}
</Link>
</td>
<td className="py-1.5">{evalStatusBadge(p.evalStatus)}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</TableCell>
</TableRow>
)}
</>
))}
</TableBody>
</Table>
</div>
{/* Mobile card stack */}
<div className="space-y-3 md:hidden">
{jurors.map((j) => (
<Card key={j.userId}>
<CardContent className="p-4">
<button
className="w-full text-left"
onClick={() => toggle(j.userId)}
>
<div className="flex items-center justify-between">
<div>
<p className="font-medium">{j.name}</p>
<p className="text-xs text-muted-foreground mt-0.5">
{j.completed}/{j.assigned} completed
</p>
</div>
<div className="flex items-center gap-2">
{j.isOutlier && <Badge variant="destructive">Outlier</Badge>}
{expanded === j.userId ? (
<ChevronUp className="h-4 w-4 text-muted-foreground" />
) : (
<ChevronDown className="h-4 w-4 text-muted-foreground" />
)}
</div>
</div>
<div className="mt-2 flex items-center gap-2">
<Progress value={j.completionRate} className="flex-1 h-1.5" />
<span className="text-xs tabular-nums text-muted-foreground">
{j.completionRate.toFixed(0)}%
</span>
</div>
<div className="mt-2 grid grid-cols-2 gap-2 text-xs">
<div>
<span className="text-muted-foreground">Avg Score: </span>
<span className="tabular-nums font-medium">
{j.averageScore > 0 ? j.averageScore.toFixed(2) : '—'}
</span>
</div>
<div>
<span className="text-muted-foreground">Std Dev: </span>
<span className="tabular-nums font-medium">
{j.stddev > 0 ? j.stddev.toFixed(2) : '—'}
</span>
</div>
</div>
</button>
{expanded === j.userId && j.projects.length > 0 && (
<div className="mt-3 pt-3 border-t space-y-2">
{j.projects.map((p) => (
<div key={p.id} className="flex items-center justify-between gap-2">
<Link
href={`/observer/projects/${p.id}`}
className="text-sm text-primary hover:underline truncate"
>
{p.title}
</Link>
{evalStatusBadge(p.evalStatus)}
</div>
))}
</div>
)}
{expanded === j.userId && j.projects.length === 0 && (
<p className="mt-3 pt-3 border-t text-sm text-muted-foreground">No projects</p>
)}
</CardContent>
</Card>
))}
</div>
</>
)
}

View File

@@ -0,0 +1,231 @@
'use client'
import { useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Badge } from '@/components/ui/badge'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { RoundTypeStatsCards } from '@/components/observer/round-type-stats'
import { FilteringScreeningBar } from './filtering-screening-bar'
interface FilteringReportTabsProps {
roundId: string
programId: string
}
type OutcomeFilter = 'ALL' | 'PASSED' | 'FILTERED_OUT' | 'FLAGGED'
function outcomeBadge(outcome: string) {
switch (outcome) {
case 'PASSED':
return <Badge className="bg-emerald-100 text-emerald-800 border-emerald-200">Passed</Badge>
case 'FILTERED_OUT':
return <Badge className="bg-rose-100 text-rose-800 border-rose-200">Filtered Out</Badge>
case 'FLAGGED':
return <Badge className="bg-amber-100 text-amber-800 border-amber-200">Flagged</Badge>
default:
return <Badge variant="outline">{outcome}</Badge>
}
}
function ProjectsTab({ roundId }: { roundId: string }) {
const [outcomeFilter, setOutcomeFilter] = useState<OutcomeFilter>('ALL')
const [page, setPage] = useState(1)
const perPage = 20
const { data, isLoading } = trpc.analytics.getFilteringResults.useQuery({
roundId,
outcome: outcomeFilter === 'ALL' ? undefined : outcomeFilter,
page,
perPage,
})
function handleOutcomeChange(value: string) {
setOutcomeFilter(value as OutcomeFilter)
setPage(1)
}
return (
<div className="space-y-4">
<div className="flex items-center gap-3">
<Select value={outcomeFilter} onValueChange={handleOutcomeChange}>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="All Outcomes" />
</SelectTrigger>
<SelectContent>
<SelectItem value="ALL">All Outcomes</SelectItem>
<SelectItem value="PASSED">Passed</SelectItem>
<SelectItem value="FILTERED_OUT">Filtered Out</SelectItem>
<SelectItem value="FLAGGED">Flagged</SelectItem>
</SelectContent>
</Select>
{data && (
<p className="text-sm text-muted-foreground">
{data.total} result{data.total !== 1 ? 's' : ''}
</p>
)}
</div>
{isLoading ? (
<Skeleton className="h-[400px]" />
) : data?.results.length ? (
<>
{/* Desktop table */}
<div className="hidden md:block rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Project Title</TableHead>
<TableHead>Team</TableHead>
<TableHead>Category</TableHead>
<TableHead>Country</TableHead>
<TableHead>Outcome</TableHead>
<TableHead>Award Routing</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.results.map((r) => {
const effectiveOutcome = r.finalOutcome ?? r.outcome
const awardRouting = r.project.awardEligibilities
.map((ae) => ae.award.name)
.join(', ')
return (
<TableRow key={r.id}>
<TableCell className="font-medium">{r.project.title}</TableCell>
<TableCell className="text-muted-foreground">{r.project.teamName}</TableCell>
<TableCell className="text-muted-foreground">
{r.project.competitionCategory ?? '—'}
</TableCell>
<TableCell className="text-muted-foreground">
{r.project.country ?? '—'}
</TableCell>
<TableCell>{outcomeBadge(effectiveOutcome)}</TableCell>
<TableCell className="text-sm text-muted-foreground">
{awardRouting || '—'}
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</div>
{/* Mobile card stack */}
<div className="space-y-3 md:hidden">
{data.results.map((r) => {
const effectiveOutcome = r.finalOutcome ?? r.outcome
const awardRouting = r.project.awardEligibilities
.map((ae) => ae.award.name)
.join(', ')
return (
<Card key={r.id}>
<CardContent className="pt-4 space-y-2">
<div className="flex items-start justify-between gap-2">
<p className="font-medium text-sm leading-tight">{r.project.title}</p>
{outcomeBadge(effectiveOutcome)}
</div>
<p className="text-xs text-muted-foreground">{r.project.teamName}</p>
<div className="flex gap-3 text-xs text-muted-foreground">
{r.project.competitionCategory && <span>{r.project.competitionCategory}</span>}
{r.project.country && <span>{r.project.country}</span>}
</div>
{awardRouting && (
<p className="text-xs text-muted-foreground">Award: {awardRouting}</p>
)}
</CardContent>
</Card>
)
})}
</div>
{/* Pagination */}
{data.totalPages > 1 && (
<div className="flex items-center justify-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setPage((p) => Math.max(1, p - 1))}
disabled={page === 1}
>
<ChevronLeft className="h-4 w-4" />
</Button>
{Array.from({ length: Math.min(data.totalPages, 7) }, (_, i) => {
const pageNum = i + 1
return (
<Button
key={pageNum}
variant={page === pageNum ? 'default' : 'outline'}
size="sm"
onClick={() => setPage(pageNum)}
>
{pageNum}
</Button>
)
})}
<Button
variant="outline"
size="sm"
onClick={() => setPage((p) => Math.min(data.totalPages, p + 1))}
disabled={page === data.totalPages}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
)}
</>
) : (
<Card>
<CardContent className="flex items-center justify-center py-12">
<p className="text-sm text-muted-foreground">No filtering results found</p>
</CardContent>
</Card>
)}
</div>
)
}
function ScreeningResultsTab({ roundId }: { roundId: string }) {
return (
<div className="space-y-6">
<RoundTypeStatsCards roundId={roundId} />
<FilteringScreeningBar roundId={roundId} />
</div>
)
}
export function FilteringReportTabs({ roundId }: FilteringReportTabsProps) {
return (
<Tabs defaultValue="screening" className="space-y-6">
<TabsList>
<TabsTrigger value="screening">Screening Results</TabsTrigger>
<TabsTrigger value="projects">Projects</TabsTrigger>
</TabsList>
<TabsContent value="screening">
<ScreeningResultsTab roundId={roundId} />
</TabsContent>
<TabsContent value="projects">
<ProjectsTab roundId={roundId} />
</TabsContent>
</Tabs>
)
}

View File

@@ -0,0 +1,115 @@
'use client'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { cn } from '@/lib/utils'
const SEGMENTS = [
{ key: 'passed' as const, label: 'Passed', color: '#2d8659', bg: '#2d865915' },
{ key: 'filteredOut' as const, label: 'Filtered Out', color: '#de0f1e', bg: '#de0f1e15' },
{ key: 'flagged' as const, label: 'Flagged', color: '#d97706', bg: '#d9770615' },
]
interface FilteringScreeningBarProps {
roundId: string
className?: string
}
export function FilteringScreeningBar({ roundId, className }: FilteringScreeningBarProps) {
const { data, isLoading } = trpc.analytics.getFilteringResultStats.useQuery(
{ roundId },
{ enabled: !!roundId }
)
return (
<Card className={cn(className)}>
<CardHeader>
<CardTitle className="text-base">Screening Results</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{isLoading ? (
<>
<Skeleton className="h-5 w-full rounded-full" />
<div className="flex flex-wrap gap-2">
<Skeleton className="h-8 w-28 rounded-lg" />
<Skeleton className="h-8 w-32 rounded-lg" />
<Skeleton className="h-8 w-24 rounded-lg" />
</div>
</>
) : !data || data.total === 0 ? (
<p className="text-sm text-muted-foreground">No screening data available.</p>
) : (
<>
{/* Segmented bar */}
<div className="flex h-5 w-full overflow-hidden rounded-full bg-muted">
{SEGMENTS.map(({ key, color }) => {
const pct = (data[key] / data.total) * 100
if (pct === 0) return null
return (
<div
key={key}
title={`${data[key]} (${Math.round(pct)}%)`}
style={{ width: `${pct}%`, backgroundColor: color, minWidth: '4px' }}
className="transition-all duration-500 first:rounded-l-full last:rounded-r-full"
/>
)
})}
</div>
{/* Stat pills */}
<div className="flex flex-wrap gap-2">
{SEGMENTS.map(({ key, label, color, bg }) => {
const count = data[key]
const pct = Math.round((count / data.total) * 100)
return (
<div
key={key}
className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium"
style={{ backgroundColor: bg, color }}
>
<span
className="inline-block h-2 w-2 shrink-0 rounded-full"
style={{ backgroundColor: color }}
/>
<span>{label}</span>
<span className="tabular-nums font-bold">{count}</span>
<span className="font-normal opacity-70">({pct}%)</span>
</div>
)
})}
{/* Total */}
<div className="flex items-center gap-1.5 rounded-lg bg-muted px-3 py-1.5 text-sm font-medium text-muted-foreground">
<span>Total</span>
<span className="tabular-nums font-bold text-foreground">{data.total}</span>
</div>
{/* Overridden — only if any */}
{data.overridden > 0 && (
<div
className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium"
style={{ backgroundColor: '#7c3aed15', color: '#7c3aed' }}
>
<span>Overridden</span>
<span className="tabular-nums font-bold">{data.overridden}</span>
</div>
)}
{/* Routed to awards — only if any */}
{data.routedToAwards > 0 && (
<div
className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium"
style={{ backgroundColor: '#053d5715', color: '#053d57' }}
>
<span>Routed to Awards</span>
<span className="tabular-nums font-bold">{data.routedToAwards}</span>
</div>
)}
</div>
</>
)}
</CardContent>
</Card>
)
}

View File

@@ -0,0 +1,69 @@
'use client'
import { trpc } from '@/lib/trpc/client'
import { Skeleton } from '@/components/ui/skeleton'
import {
GeographicDistribution,
StatusBreakdownChart,
DiversityMetricsChart,
CrossStageComparisonChart,
} from '@/components/charts'
interface GlobalAnalyticsTabProps {
programId: string
roundIds?: string[]
}
export function GlobalAnalyticsTab({ programId, roundIds }: GlobalAnalyticsTabProps) {
const { data: geoData, isLoading: geoLoading } =
trpc.analytics.getGeographicDistribution.useQuery({ programId })
const { data: diversity, isLoading: diversityLoading } =
trpc.analytics.getDiversityMetrics.useQuery({ programId })
const { data: statusBreakdown, isLoading: statusLoading } =
trpc.analytics.getStatusBreakdown.useQuery({ programId })
const { data: crossRound, isLoading: crossLoading } =
trpc.analytics.getCrossRoundComparison.useQuery(
{ roundIds: roundIds ?? [] },
{ enabled: !!roundIds && roundIds.length >= 2 }
)
return (
<div className="space-y-6">
{/* Geographic Distribution */}
{geoLoading ? (
<Skeleton className="h-[400px]" />
) : geoData?.length ? (
<GeographicDistribution data={geoData} />
) : null}
{/* Status and Diversity side by side */}
<div className="grid gap-6 lg:grid-cols-2">
{statusLoading ? (
<Skeleton className="h-[350px]" />
) : statusBreakdown ? (
<StatusBreakdownChart data={statusBreakdown} />
) : null}
{diversityLoading ? (
<Skeleton className="h-[350px]" />
) : diversity ? (
<DiversityMetricsChart data={diversity} />
) : null}
</div>
{/* Cross-Round Comparison */}
{roundIds && roundIds.length >= 2 && (
<>
{crossLoading ? (
<Skeleton className="h-[350px]" />
) : crossRound ? (
<CrossStageComparisonChart data={crossRound} />
) : null}
</>
)}
</div>
)
}

View File

@@ -0,0 +1,37 @@
'use client'
import { trpc } from '@/lib/trpc/client'
import { Skeleton } from '@/components/ui/skeleton'
import { StatusBreakdownChart, DiversityMetricsChart } from '@/components/charts'
import { RoundTypeStatsCards } from '@/components/observer/round-type-stats'
interface IntakeReportTabsProps {
roundId: string
programId: string
}
export function IntakeReportTabs({ roundId, programId }: IntakeReportTabsProps) {
const { data: statusBreakdown, isLoading: statusLoading } =
trpc.analytics.getStatusBreakdown.useQuery({ roundId })
const { data: diversity, isLoading: diversityLoading } =
trpc.analytics.getDiversityMetrics.useQuery({ roundId })
return (
<div className="space-y-6">
<RoundTypeStatsCards roundId={roundId} />
{statusLoading ? (
<Skeleton className="h-[350px]" />
) : statusBreakdown ? (
<StatusBreakdownChart data={statusBreakdown} />
) : null}
{diversityLoading ? (
<Skeleton className="h-[400px]" />
) : diversity ? (
<DiversityMetricsChart data={diversity} />
) : null}
</div>
)
}

View File

@@ -0,0 +1,29 @@
'use client'
import { trpc } from '@/lib/trpc/client'
import { Skeleton } from '@/components/ui/skeleton'
import { StatusBreakdownChart } from '@/components/charts'
import { RoundTypeStatsCards } from '@/components/observer/round-type-stats'
interface LiveFinalReportTabsProps {
roundId: string
programId: string
}
function StatusBreakdownSection({ roundId }: { roundId: string }) {
const { data: statusBreakdown, isLoading } =
trpc.analytics.getStatusBreakdown.useQuery({ roundId })
if (isLoading) return <Skeleton className="h-[350px]" />
if (!statusBreakdown) return null
return <StatusBreakdownChart data={statusBreakdown} />
}
export function LiveFinalReportTabs({ roundId }: LiveFinalReportTabsProps) {
return (
<div className="space-y-6">
<RoundTypeStatsCards roundId={roundId} />
<StatusBreakdownSection roundId={roundId} />
</div>
)
}

View File

@@ -0,0 +1,29 @@
'use client'
import { trpc } from '@/lib/trpc/client'
import { Skeleton } from '@/components/ui/skeleton'
import { StatusBreakdownChart } from '@/components/charts'
import { RoundTypeStatsCards } from '@/components/observer/round-type-stats'
interface MentoringReportTabsProps {
roundId: string
programId: string
}
function StatusBreakdownSection({ roundId }: { roundId: string }) {
const { data: statusBreakdown, isLoading } =
trpc.analytics.getStatusBreakdown.useQuery({ roundId })
if (isLoading) return <Skeleton className="h-[350px]" />
if (!statusBreakdown) return null
return <StatusBreakdownChart data={statusBreakdown} />
}
export function MentoringReportTabs({ roundId }: MentoringReportTabsProps) {
return (
<div className="space-y-6">
<RoundTypeStatsCards roundId={roundId} />
<StatusBreakdownSection roundId={roundId} />
</div>
)
}

View File

@@ -0,0 +1,29 @@
'use client'
import { trpc } from '@/lib/trpc/client'
import { Skeleton } from '@/components/ui/skeleton'
import { StatusBreakdownChart } from '@/components/charts'
import { RoundTypeStatsCards } from '@/components/observer/round-type-stats'
interface SubmissionReportTabsProps {
roundId: string
programId: string
}
function StatusBreakdownSection({ roundId }: { roundId: string }) {
const { data: statusBreakdown, isLoading } =
trpc.analytics.getStatusBreakdown.useQuery({ roundId })
if (isLoading) return <Skeleton className="h-[350px]" />
if (!statusBreakdown) return null
return <StatusBreakdownChart data={statusBreakdown} />
}
export function SubmissionReportTabs({ roundId }: SubmissionReportTabsProps) {
return (
<div className="space-y-6">
<RoundTypeStatsCards roundId={roundId} />
<StatusBreakdownSection roundId={roundId} />
</div>
)
}