Fix observer reports: charts, filtering, project preview, dashboard stats
All checks were successful
Build and Push Docker Image / build (push) Successful in 9m32s

- Rewrite diversity metrics: horizontal bar charts for ocean issues and
  geographic distribution (replaces unreadable vertical/donut charts)
- Rewrite juror score heatmap: expandable table with score distribution
- Rewrite juror consistency: horizontal bar visual with juror names
- Merge filtering tabs into single screening view with per-project
  AI reasoning and expandable rows
- Add project preview dialog for juror performance table
- Fix status breakdown for evaluation rounds (Fully/Partially/Not Reviewed)
- Show active round name instead of count on observer dashboard
- Move Global tab to last position, default to first round-specific tab
- Add 4-card stats layout for evaluation with reviews/project ratio
- Fix oceanIssue field (singular) and remove non-existent aiSummary

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-21 10:12:21 +01:00
parent 2e4b95f29c
commit 161cd1684a
12 changed files with 948 additions and 334 deletions

View File

@@ -129,7 +129,7 @@ function ReportsPageContent() {
const searchParams = useSearchParams() const searchParams = useSearchParams()
const roundFromUrl = searchParams.get('round') const roundFromUrl = searchParams.get('round')
const [selectedValue, setSelectedValue] = useState<string | null>(roundFromUrl) const [selectedValue, setSelectedValue] = useState<string | null>(roundFromUrl)
const [activeTab, setActiveTab] = useState('global') const [activeTab, setActiveTab] = useState<string | null>(null)
const { data: programs, isLoading: stagesLoading } = trpc.program.list.useQuery({ includeStages: true }) const { data: programs, isLoading: stagesLoading } = trpc.program.list.useQuery({ includeStages: true })
@@ -150,9 +150,9 @@ function ReportsPageContent() {
} }
}, [stages.length, selectedValue]) }, [stages.length, selectedValue])
// Reset to global tab when round selection changes // Reset to first round-specific tab when round selection changes
useEffect(() => { useEffect(() => {
setActiveTab('global') setActiveTab(null)
}, [selectedValue]) }, [selectedValue])
const isAllRounds = selectedValue?.startsWith('all:') const isAllRounds = selectedValue?.startsWith('all:')
@@ -167,8 +167,8 @@ function ReportsPageContent() {
: getRoundTabs(roundType) : getRoundTabs(roundType)
const allTabs: TabDef[] = [ const allTabs: TabDef[] = [
{ value: 'global', label: 'Global', icon: Globe },
...roundSpecificTabs, ...roundSpecificTabs,
{ value: 'global', label: 'Global', icon: Globe },
] ]
return ( return (
@@ -206,7 +206,7 @@ function ReportsPageContent() {
</div> </div>
{selectedValue && ( {selectedValue && (
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6"> <Tabs value={activeTab ?? allTabs[0]?.value ?? 'global'} onValueChange={setActiveTab} className="space-y-6">
<TabsList> <TabsList>
{allTabs.map((tab) => ( {allTabs.map((tab) => (
<TabsTrigger key={tab.value} value={tab.value} className="gap-2"> <TabsTrigger key={tab.value} value={tab.value} className="gap-2">

View File

@@ -52,6 +52,10 @@ export const TREMOR_STATUS_COLORS: Record<string, string> = {
IN_PROGRESS: 'blue', IN_PROGRESS: 'blue',
PASSED: 'emerald', PASSED: 'emerald',
COMPLETED: 'indigo', COMPLETED: 'indigo',
// Evaluation review states
FULLY_REVIEWED: 'emerald',
PARTIALLY_REVIEWED: 'amber',
NOT_REVIEWED: 'rose',
} }
// Project status colors — mapped to actual ProjectStatus enum values // Project status colors — mapped to actual ProjectStatus enum values
@@ -64,12 +68,16 @@ export const STATUS_COLORS: Record<string, string> = {
REJECTED: '#de0f1e', // Red REJECTED: '#de0f1e', // Red
DRAFT: '#9ca3af', // Gray DRAFT: '#9ca3af', // Gray
WITHDRAWN: '#6b7280', // Dark Gray WITHDRAWN: '#6b7280', // Dark Gray
// Evaluation review states
FULLY_REVIEWED: '#2d8659', // Sea Green
PARTIALLY_REVIEWED: '#d97706', // Amber
NOT_REVIEWED: '#de0f1e', // Red
} }
// Human-readable status labels // Human-readable status labels
export const STATUS_LABELS: Record<string, string> = { export const STATUS_LABELS: Record<string, string> = {
SUBMITTED: 'Submitted', SUBMITTED: 'Submitted',
ELIGIBLE: 'Eligible', ELIGIBLE: 'In-Competition',
ASSIGNED: 'Special Award', ASSIGNED: 'Special Award',
SEMIFINALIST: 'Semi-finalist', SEMIFINALIST: 'Semi-finalist',
FINALIST: 'Finalist', FINALIST: 'Finalist',
@@ -81,6 +89,10 @@ export const STATUS_LABELS: Record<string, string> = {
IN_PROGRESS: 'In Progress', IN_PROGRESS: 'In Progress',
PASSED: 'Passed', PASSED: 'Passed',
COMPLETED: 'Completed', COMPLETED: 'Completed',
// Evaluation review states
FULLY_REVIEWED: 'Fully Reviewed',
PARTIALLY_REVIEWED: 'Partially Reviewed',
NOT_REVIEWED: 'Not Reviewed',
} }
/** /**

View File

@@ -1,9 +1,8 @@
'use client' 'use client'
import { DonutChart, BarChart } from '@tremor/react' import { BarChart } from '@tremor/react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
import { TREMOR_CHART_COLORS } from './chart-theme'
interface DiversityData { interface DiversityData {
total: number total: number
@@ -48,76 +47,69 @@ export function DiversityMetricsChart({ data }: DiversityMetricsProps) {
) )
} }
// Top countries for donut chart (max 10, others grouped) // Top countries — horizontal bar chart for readability
const topCountries = (data.byCountry || []).slice(0, 10) const countryBarData = (data.byCountry || []).slice(0, 15).map((c) => ({
const otherCountries = (data.byCountry || []).slice(10) country: getCountryName(c.country),
const countryData = otherCountries.length > 0 Projects: c.count,
? [...topCountries, {
country: 'Others',
count: otherCountries.reduce((sum, c) => sum + c.count, 0),
percentage: otherCountries.reduce((sum, c) => sum + c.percentage, 0),
}]
: topCountries
const donutData = countryData.map((c) => ({
name: getCountryName(c.country),
value: c.count,
})) }))
const categoryData = (data.byCategory || []).slice(0, 10).map((c) => ({ const categoryData = (data.byCategory || []).slice(0, 10).map((c) => ({
category: formatLabel(c.category), category: formatLabel(c.category),
Count: c.count, Projects: c.count,
})) }))
const oceanIssueData = (data.byOceanIssue || []).slice(0, 15).map((o) => ({ const oceanIssueData = (data.byOceanIssue || []).slice(0, 15).map((o) => ({
issue: formatLabel(o.issue), issue: formatLabel(o.issue),
Count: o.count, Projects: o.count,
})) }))
return ( return (
<div className="space-y-6"> <div className="space-y-6">
{/* Summary */} {/* Summary stats row */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4"> <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
<Card> <Card>
<CardContent className="pt-6"> <CardContent className="p-4">
<div className="text-2xl font-bold">{data.total}</div> <p className="text-2xl font-bold tabular-nums">{data.total}</p>
<p className="text-sm text-muted-foreground">Total Projects</p> <p className="text-xs text-muted-foreground">Total Projects</p>
</CardContent> </CardContent>
</Card> </Card>
<Card> <Card>
<CardContent className="pt-6"> <CardContent className="p-4">
<div className="text-2xl font-bold">{(data.byCountry || []).length}</div> <p className="text-2xl font-bold tabular-nums">{(data.byCountry || []).length}</p>
<p className="text-sm text-muted-foreground">Countries Represented</p> <p className="text-xs text-muted-foreground">Countries</p>
</CardContent> </CardContent>
</Card> </Card>
<Card> <Card>
<CardContent className="pt-6"> <CardContent className="p-4">
<div className="text-2xl font-bold">{(data.byCategory || []).length}</div> <p className="text-2xl font-bold tabular-nums">{(data.byCategory || []).length}</p>
<p className="text-sm text-muted-foreground">Categories</p> <p className="text-xs text-muted-foreground">Categories</p>
</CardContent> </CardContent>
</Card> </Card>
<Card> <Card>
<CardContent className="pt-6"> <CardContent className="p-4">
<div className="text-2xl font-bold">{(data.byTag || []).length}</div> <p className="text-2xl font-bold tabular-nums">{(data.byOceanIssue || []).length}</p>
<p className="text-sm text-muted-foreground">Unique Tags</p> <p className="text-xs text-muted-foreground">Ocean Issues</p>
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
<div className="grid gap-6 lg:grid-cols-2"> <div className="grid gap-6 lg:grid-cols-2">
{/* Country Distribution */} {/* Country Distribution — horizontal bars */}
<Card> <Card>
<CardHeader> <CardHeader className="pb-2">
<CardTitle>Geographic Distribution</CardTitle> <CardTitle className="text-base">Geographic Distribution</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{donutData.length > 0 ? ( {countryBarData.length > 0 ? (
<DonutChart <BarChart
data={donutData} data={countryBarData}
category="value" index="country"
index="name" categories={['Projects']}
colors={[...TREMOR_CHART_COLORS]} colors={['cyan']}
className="h-[400px]" showLegend={false}
layout="horizontal"
yAxisWidth={120}
className="h-[360px]"
/> />
) : ( ) : (
<p className="text-muted-foreground text-center py-8">No geographic data</p> <p className="text-muted-foreground text-center py-8">No geographic data</p>
@@ -125,23 +117,47 @@ export function DiversityMetricsChart({ data }: DiversityMetricsProps) {
</CardContent> </CardContent>
</Card> </Card>
{/* Category Distribution */} {/* Competition Categories — horizontal bars */}
<Card> <Card>
<CardHeader> <CardHeader className="pb-2">
<CardTitle>Competition Categories</CardTitle> <CardTitle className="text-base">Competition Categories</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{categoryData.length > 0 ? ( {categoryData.length > 0 ? (
<BarChart categoryData.length <= 4 ? (
data={categoryData} /* Clean stacked bars for few categories */
index="category" <div className="space-y-4 pt-2">
categories={['Count']} {categoryData.map((c) => {
colors={['indigo']} const maxCount = Math.max(...categoryData.map((d) => d.Projects))
layout="horizontal" const pct = maxCount > 0 ? (c.Projects / maxCount) * 100 : 0
yAxisWidth={120} return (
showLegend={false} <div key={c.category} className="space-y-1.5">
className="h-[400px]" <div className="flex items-center justify-between text-sm">
/> <span className="font-medium">{c.category}</span>
<span className="tabular-nums text-muted-foreground">{c.Projects}</span>
</div>
<div className="h-3 w-full rounded-full bg-muted overflow-hidden">
<div
className="h-full rounded-full bg-[#053d57] transition-all duration-500"
style={{ width: `${pct}%` }}
/>
</div>
</div>
)
})}
</div>
) : (
<BarChart
data={categoryData}
index="category"
categories={['Projects']}
colors={['indigo']}
layout="horizontal"
yAxisWidth={140}
showLegend={false}
className="h-[280px]"
/>
)
) : ( ) : (
<p className="text-muted-foreground text-center py-8">No category data</p> <p className="text-muted-foreground text-center py-8">No category data</p>
)} )}
@@ -149,45 +165,43 @@ export function DiversityMetricsChart({ data }: DiversityMetricsProps) {
</Card> </Card>
</div> </div>
{/* Ocean Issues */} {/* Ocean Issues — horizontal bars for readability */}
{oceanIssueData.length > 0 && ( {oceanIssueData.length > 0 && (
<Card> <Card>
<CardHeader> <CardHeader className="pb-2">
<CardTitle>Ocean Issues Addressed</CardTitle> <CardTitle className="text-base">Ocean Issues Addressed</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<BarChart <BarChart
data={oceanIssueData} data={oceanIssueData}
index="issue" index="issue"
categories={['Count']} categories={['Projects']}
colors={['blue']} colors={['blue']}
showLegend={false} showLegend={false}
yAxisWidth={40} layout="horizontal"
yAxisWidth={200}
className="h-[400px]" className="h-[400px]"
rotateLabelX={{ angle: -35, xAxisHeight: 80 }}
/> />
</CardContent> </CardContent>
</Card> </Card>
)} )}
{/* Tags Cloud */} {/* Tags — clean pill cloud */}
{(data.byTag || []).length > 0 && ( {(data.byTag || []).length > 0 && (
<Card> <Card>
<CardHeader> <CardHeader className="pb-2">
<CardTitle>Project Tags</CardTitle> <CardTitle className="text-base">Project Tags</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{(data.byTag || []).slice(0, 30).map((tag) => ( {(data.byTag || []).slice(0, 30).map((tag) => (
<Badge <Badge
key={tag.tag} key={tag.tag}
variant="secondary" variant="outline"
className="text-sm" className="px-3 py-1 text-sm font-normal"
style={{
fontSize: `${Math.max(0.75, Math.min(1.4, 0.75 + tag.percentage / 20))}rem`,
}}
> >
{tag.tag} ({tag.count}) {tag.tag}
<span className="ml-1.5 text-muted-foreground tabular-nums">({tag.count})</span>
</Badge> </Badge>
))} ))}
</div> </div>

View File

@@ -1,6 +1,5 @@
'use client' 'use client'
import { ScatterChart } from '@tremor/react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
import { import {
@@ -12,6 +11,7 @@ import {
TableRow, TableRow,
} from '@/components/ui/table' } from '@/components/ui/table'
import { AlertTriangle } from 'lucide-react' import { AlertTriangle } from 'lucide-react'
import { scoreGradient } from './chart-theme'
interface JurorMetric { interface JurorMetric {
userId: string userId: string
@@ -30,6 +30,24 @@ interface JurorConsistencyProps {
} }
} }
function ScoreDot({ score, maxScore = 10 }: { score: number; maxScore?: number }) {
const pct = ((score / maxScore) * 100).toFixed(1)
return (
<div className="flex items-center gap-2 w-full min-w-[120px]">
<div className="flex-1 h-2.5 rounded-full bg-muted overflow-hidden">
<div
className="h-full rounded-full transition-all duration-300"
style={{
width: `${pct}%`,
backgroundColor: scoreGradient(score),
}}
/>
</div>
<span className="text-xs tabular-nums font-medium w-8 text-right">{score.toFixed(1)}</span>
</div>
)
}
export function JurorConsistencyChart({ data }: JurorConsistencyProps) { export function JurorConsistencyChart({ data }: JurorConsistencyProps) {
if (!data?.jurors?.length) { if (!data?.jurors?.length) {
return ( return (
@@ -42,27 +60,19 @@ export function JurorConsistencyChart({ data }: JurorConsistencyProps) {
} }
const outlierCount = data.jurors.filter((j) => j.isOutlier).length const outlierCount = data.jurors.filter((j) => j.isOutlier).length
const sorted = [...data.jurors].sort((a, b) => b.averageScore - a.averageScore)
const scatterData = data.jurors.map((j) => ({
'Average Score': parseFloat(j.averageScore.toFixed(2)),
'Std Deviation': parseFloat(j.stddev.toFixed(2)),
category: j.isOutlier ? 'Outlier' : 'Normal',
name: j.name,
evaluations: j.evaluationCount,
size: Math.max(8, Math.min(20, j.evaluationCount * 2)),
}))
return ( return (
<div className="space-y-6"> <div className="space-y-6">
{/* Scatter: Average Score vs Standard Deviation */} {/* Juror Scoring Patterns — bar-based visual instead of scatter */}
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle className="flex items-center justify-between"> <CardTitle className="flex items-center justify-between flex-wrap gap-2">
<span>Juror Scoring Patterns</span> <span className="text-base">Juror Scoring Patterns</span>
<span className="text-sm font-normal text-muted-foreground"> <span className="text-sm font-normal text-muted-foreground flex items-center gap-2">
Overall Avg: {data.overallAverage.toFixed(2)} Overall Avg: {data.overallAverage.toFixed(2)}
{outlierCount > 0 && ( {outlierCount > 0 && (
<Badge variant="destructive" className="ml-2"> <Badge variant="destructive">
{outlierCount} outlier{outlierCount > 1 ? 's' : ''} {outlierCount} outlier{outlierCount > 1 ? 's' : ''}
</Badge> </Badge>
)} )}
@@ -70,18 +80,31 @@ export function JurorConsistencyChart({ data }: JurorConsistencyProps) {
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<ScatterChart <div className="space-y-2">
data={scatterData} {sorted.map((juror) => (
x="Average Score" <div
y="Std Deviation" key={juror.userId}
category="category" className={`flex items-center gap-3 rounded-md px-3 py-2 ${juror.isOutlier ? 'bg-destructive/5 border border-destructive/20' : 'hover:bg-muted/50'}`}
size="size" >
colors={['blue', 'rose']} <div className="w-36 shrink-0 truncate">
className="h-[400px]" <span className="text-sm font-medium">{juror.name}</span>
/> </div>
<p className="text-xs text-muted-foreground mt-2 text-center"> <div className="flex-1">
Dot size represents number of evaluations. Red dots indicate outlier <ScoreDot score={juror.averageScore} />
jurors (2+ points from mean). </div>
<div className="hidden sm:flex items-center gap-3 text-xs text-muted-foreground shrink-0">
<span className="tabular-nums">&sigma; {juror.stddev.toFixed(1)}</span>
<span className="tabular-nums">{juror.evaluationCount} eval{juror.evaluationCount !== 1 ? 's' : ''}</span>
</div>
{juror.isOutlier && (
<AlertTriangle className="h-3.5 w-3.5 text-destructive shrink-0" />
)}
</div>
))}
</div>
{/* Overall average line */}
<p className="text-xs text-muted-foreground mt-4 text-center">
Bars show average score per juror. &sigma; = standard deviation. Outliers deviate 2+ points from the overall mean.
</p> </p>
</CardContent> </CardContent>
</Card> </Card>
@@ -89,57 +112,92 @@ export function JurorConsistencyChart({ data }: JurorConsistencyProps) {
{/* Juror details table */} {/* Juror details table */}
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle>Juror Consistency Details</CardTitle> <CardTitle className="text-base">Juror Consistency Details</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<Table> {/* Desktop table */}
<TableHeader> <div className="hidden md:block">
<TableRow> <Table>
<TableHead>Juror</TableHead> <TableHeader>
<TableHead className="text-right">Evaluations</TableHead> <TableRow>
<TableHead className="text-right">Avg Score</TableHead> <TableHead>Juror</TableHead>
<TableHead className="text-right">Std Dev</TableHead> <TableHead className="text-right">Evaluations</TableHead>
<TableHead className="text-right"> <TableHead className="text-right">Avg Score</TableHead>
Deviation from Mean <TableHead className="text-right">Std Dev</TableHead>
</TableHead> <TableHead className="text-right">Deviation</TableHead>
<TableHead className="text-center">Status</TableHead> <TableHead className="text-center">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.jurors.map((juror) => (
<TableRow
key={juror.userId}
className={juror.isOutlier ? 'bg-destructive/5' : ''}
>
<TableCell>
<p className="font-medium">{juror.name}</p>
</TableCell>
<TableCell className="text-right tabular-nums">
{juror.evaluationCount}
</TableCell>
<TableCell className="text-right tabular-nums">
{juror.averageScore.toFixed(2)}
</TableCell>
<TableCell className="text-right tabular-nums">
{juror.stddev.toFixed(2)}
</TableCell>
<TableCell className="text-right tabular-nums">
{juror.deviationFromOverall.toFixed(2)}
</TableCell>
<TableCell className="text-center">
{juror.isOutlier ? (
<Badge variant="destructive" className="gap-1">
<AlertTriangle className="h-3 w-3" />
Outlier
</Badge>
) : (
<Badge variant="secondary">Normal</Badge>
)}
</TableCell>
</TableRow> </TableRow>
))} </TableHeader>
</TableBody> <TableBody>
</Table> {sorted.map((juror) => (
<TableRow
key={juror.userId}
className={juror.isOutlier ? 'bg-destructive/5' : ''}
>
<TableCell className="font-medium">{juror.name}</TableCell>
<TableCell className="text-right tabular-nums">
{juror.evaluationCount}
</TableCell>
<TableCell className="text-right tabular-nums">
{juror.averageScore.toFixed(2)}
</TableCell>
<TableCell className="text-right tabular-nums">
{juror.stddev.toFixed(2)}
</TableCell>
<TableCell className="text-right tabular-nums">
{juror.deviationFromOverall >= 0 ? '+' : ''}{juror.deviationFromOverall.toFixed(2)}
</TableCell>
<TableCell className="text-center">
{juror.isOutlier ? (
<Badge variant="destructive" className="gap-1">
<AlertTriangle className="h-3 w-3" />
Outlier
</Badge>
) : (
<Badge variant="secondary">Normal</Badge>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{/* Mobile card stack */}
<div className="space-y-2 md:hidden">
{sorted.map((juror) => (
<div
key={juror.userId}
className={`rounded-md border p-3 space-y-1 ${juror.isOutlier ? 'bg-destructive/5 border-destructive/20' : ''}`}
>
<div className="flex items-center justify-between">
<span className="text-sm font-medium">{juror.name}</span>
{juror.isOutlier ? (
<Badge variant="destructive" className="gap-1 text-[10px]">
<AlertTriangle className="h-3 w-3" />
Outlier
</Badge>
) : (
<Badge variant="secondary" className="text-[10px]">Normal</Badge>
)}
</div>
<div className="grid grid-cols-3 gap-2 text-xs">
<div>
<p className="text-muted-foreground">Avg Score</p>
<p className="font-medium tabular-nums">{juror.averageScore.toFixed(2)}</p>
</div>
<div>
<p className="text-muted-foreground">Std Dev</p>
<p className="font-medium tabular-nums">{juror.stddev.toFixed(2)}</p>
</div>
<div>
<p className="text-muted-foreground">Evals</p>
<p className="font-medium tabular-nums">{juror.evaluationCount}</p>
</div>
</div>
</div>
))}
</div>
</CardContent> </CardContent>
</Card> </Card>
</div> </div>

View File

@@ -1,7 +1,8 @@
'use client' 'use client'
import { Fragment } from 'react' import { Fragment, useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card' import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { scoreGradient } from './chart-theme' import { scoreGradient } from './chart-theme'
interface JurorScoreHeatmapProps { interface JurorScoreHeatmapProps {
@@ -22,6 +23,121 @@ function getTextColor(score: number | null): string {
return score >= 6 ? '#ffffff' : '#1a1a1a' return score >= 6 ? '#ffffff' : '#1a1a1a'
} }
function ScoreBadge({ score }: { score: number }) {
return (
<span
className="inline-flex items-center justify-center rounded-md px-2 py-0.5 text-xs font-semibold tabular-nums min-w-[36px]"
style={{
backgroundColor: getScoreColor(score),
color: getTextColor(score),
}}
>
{score.toFixed(1)}
</span>
)
}
function JurorSummaryRow({
juror,
scores,
averageScore,
projectCount,
isExpanded,
onToggle,
projects,
}: {
juror: { id: string; name: string }
scores: { projectId: string; score: number | null }[]
averageScore: number | null
projectCount: number
isExpanded: boolean
onToggle: () => void
projects: { id: string; title: string }[]
}) {
const scored = scores.filter((s) => s.score !== null)
const unscored = projectCount - scored.length
return (
<>
<tr
className="border-b cursor-pointer transition-colors hover:bg-muted/50"
onClick={onToggle}
>
<td className="py-3 px-4 font-medium text-sm whitespace-nowrap">
<div className="flex items-center gap-2">
<span className={`inline-flex h-5 w-5 items-center justify-center rounded text-[10px] font-bold transition-transform ${isExpanded ? 'rotate-90' : ''}`}>
</span>
{juror.name}
</div>
</td>
<td className="py-3 px-4 text-center tabular-nums text-sm">
{scored.length}
<span className="text-muted-foreground">/{projectCount}</span>
</td>
<td className="py-3 px-4 text-center">
{averageScore !== null ? (
<ScoreBadge score={averageScore} />
) : (
<span className="text-xs text-muted-foreground"></span>
)}
</td>
<td className="py-3 px-4">
{/* Mini score bar */}
<div className="flex items-center gap-0.5">
{scored
.sort((a, b) => (a.score ?? 0) - (b.score ?? 0))
.map((s, i) => (
<div
key={i}
className="h-4 w-1.5 rounded-full"
style={{ backgroundColor: getScoreColor(s.score) }}
title={`${s.score?.toFixed(1)}`}
/>
))}
{unscored > 0 &&
Array.from({ length: Math.min(unscored, 10) }).map((_, i) => (
<div
key={`empty-${i}`}
className="h-4 w-1.5 rounded-full bg-muted"
/>
))}
</div>
</td>
</tr>
{isExpanded && (
<tr className="border-b bg-muted/30">
<td colSpan={4} className="p-4">
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-2">
{projects.map((p) => {
const cell = scores.find((s) => s.projectId === p.id)
const score = cell?.score ?? null
return (
<div
key={p.id}
className="flex items-center gap-2 rounded-md border bg-background px-2.5 py-1.5"
>
{score !== null ? (
<ScoreBadge score={score} />
) : (
<span className="inline-flex items-center justify-center rounded-md bg-muted px-2 py-0.5 text-xs text-muted-foreground min-w-[36px]">
</span>
)}
<span className="text-xs truncate" title={p.title}>
{p.title}
</span>
</div>
)
})}
</div>
</td>
</tr>
)}
</>
)
}
export function JurorScoreHeatmap({ export function JurorScoreHeatmap({
jurors, jurors,
projects, projects,
@@ -29,6 +145,8 @@ export function JurorScoreHeatmap({
truncated, truncated,
totalProjects, totalProjects,
}: JurorScoreHeatmapProps) { }: JurorScoreHeatmapProps) {
const [expandedId, setExpandedId] = useState<string | null>(null)
const cellMap = new Map<string, number | null>() const cellMap = new Map<string, number | null>()
for (const c of cells) { for (const c of cells) {
cellMap.set(`${c.jurorId}:${c.projectId}`, c.score) cellMap.set(`${c.jurorId}:${c.projectId}`, c.score)
@@ -44,71 +162,77 @@ export function JurorScoreHeatmap({
) )
} }
// Compute per-juror data
const jurorData = jurors.map((j) => {
const scores = projects.map((p) => ({
projectId: p.id,
score: cellMap.get(`${j.id}:${p.id}`) ?? null,
}))
const scored = scores.filter((s) => s.score !== null)
const avg = scored.length > 0
? scored.reduce((sum, s) => sum + (s.score ?? 0), 0) / scored.length
: null
return { juror: j, scores, averageScore: avg ? parseFloat(avg.toFixed(1)) : null, scoredCount: scored.length }
})
// Sort: jurors with most evaluations first
jurorData.sort((a, b) => b.scoredCount - a.scoredCount)
// Color legend
const legendScores = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
return ( return (
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle>Score Heatmap</CardTitle> <div className="flex items-start justify-between gap-4">
<CardDescription> <div>
{jurors.length} jurors × {projects.length} projects <CardTitle className="text-base">Score Heatmap</CardTitle>
{truncated && totalProjects ? ` (showing top 30 of ${totalProjects})` : ''} <CardDescription>
</CardDescription> {jurors.length} juror{jurors.length !== 1 ? 's' : ''} &middot; {projects.length} project{projects.length !== 1 ? 's' : ''}
{truncated && totalProjects ? ` (top ${projects.length} of ${totalProjects})` : ''}
</CardDescription>
</div>
{/* Color legend */}
<div className="hidden sm:flex items-center gap-1 shrink-0">
<span className="text-[10px] text-muted-foreground mr-1">Low</span>
{legendScores.map((s) => (
<div
key={s}
className="h-4 w-4 rounded-sm"
style={{ backgroundColor: getScoreColor(s) }}
title={s.toString()}
/>
))}
<span className="text-[10px] text-muted-foreground ml-1">High</span>
</div>
</div>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{/* Mobile fallback */} <div className="overflow-x-auto">
<div className="md:hidden text-center py-8"> <table className="w-full">
<p className="text-sm text-muted-foreground"> <thead>
View on a larger screen for the score heatmap <tr className="border-b text-xs text-muted-foreground">
</p> <th className="text-left py-2 px-4 font-medium">Juror</th>
</div> <th className="text-center py-2 px-4 font-medium whitespace-nowrap">Reviewed</th>
<th className="text-center py-2 px-4 font-medium">Avg</th>
{/* Desktop heatmap */} <th className="text-left py-2 px-4 font-medium">Score Distribution</th>
<div className="hidden md:block overflow-auto max-h-[600px]"> </tr>
<div </thead>
className="grid gap-px" <tbody>
style={{ {jurorData.map(({ juror, scores, averageScore }) => (
gridTemplateColumns: `180px repeat(${projects.length}, minmax(60px, 1fr))`, <JurorSummaryRow
}} key={juror.id}
> juror={juror}
{/* Header row */} scores={scores}
<div className="sticky left-0 z-10 bg-background" /> averageScore={averageScore}
{projects.map((p) => ( projectCount={projects.length}
<div isExpanded={expandedId === juror.id}
key={p.id} onToggle={() => setExpandedId(expandedId === juror.id ? null : juror.id)}
className="text-xs font-medium text-muted-foreground truncate px-1 pb-2 text-center" projects={projects}
title={p.title} />
> ))}
{p.title.length > 12 ? p.title.slice(0, 10) + '…' : p.title} </tbody>
</div> </table>
))}
{/* 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> </div>
</CardContent> </CardContent>
</Card> </Card>

View File

@@ -210,14 +210,16 @@ export function ObserverDashboardContent({ userName }: { userName?: string }) {
<div className="grid grid-cols-3 md:grid-cols-6 divide-x divide-border"> <div className="grid grid-cols-3 md:grid-cols-6 divide-x divide-border">
{[ {[
{ value: stats.projectCount, label: 'Projects' }, { value: stats.projectCount, label: 'Projects' },
{ value: stats.activeRoundCount, label: 'Active Rounds' }, { value: stats.activeRoundName ?? `${stats.activeRoundCount} Active`, label: 'Active Round', isText: !!stats.activeRoundName },
{ value: avgScore, label: 'Avg Score' }, { value: avgScore, label: 'Avg Score' },
{ value: `${stats.completionRate}%`, label: 'Completion' }, { value: `${stats.completionRate}%`, label: 'Completion' },
{ value: stats.jurorCount, label: 'Jurors' }, { value: stats.jurorCount, label: 'Jurors' },
{ value: countryCount, label: 'Countries' }, { value: countryCount, label: 'Countries' },
].map((stat) => ( ].map((stat) => (
<div key={stat.label} className="px-4 py-3.5 text-center"> <div key={stat.label} className="px-4 py-3.5 text-center">
<p className="text-xl font-semibold tabular-nums leading-tight">{stat.value}</p> <p className={`font-semibold leading-tight ${
'isText' in stat && stat.isText ? 'text-sm truncate' : 'text-xl tabular-nums'
}`}>{stat.value}</p>
<p className="text-[11px] text-muted-foreground mt-0.5">{stat.label}</p> <p className="text-[11px] text-muted-foreground mt-0.5">{stat.label}</p>
</div> </div>
))} ))}

View File

@@ -23,6 +23,7 @@ import {
TrendingUp, TrendingUp,
Download, Download,
Clock, Clock,
ClipboardCheck,
} from 'lucide-react' } from 'lucide-react'
import { formatDateOnly } from '@/lib/utils' import { formatDateOnly } from '@/lib/utils'
import { import {
@@ -190,15 +191,15 @@ function ProgressSubTab({
))} ))}
</div> </div>
) : overviewStats ? ( ) : overviewStats ? (
<div className="grid gap-4 sm:grid-cols-3"> <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<AnimatedCard index={0}> <AnimatedCard index={0}>
<Card className="border-l-4 border-l-blue-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md"> <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"> <CardContent className="p-5">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<p className="text-sm font-medium text-muted-foreground">Project Count</p> <p className="text-sm font-medium text-muted-foreground">Projects</p>
<p className="text-2xl font-bold mt-1">{overviewStats.projectCount}</p> <p className="text-2xl font-bold mt-1">{overviewStats.projectCount}</p>
<p className="text-xs text-muted-foreground mt-1">In selection</p> <p className="text-xs text-muted-foreground mt-1">In round</p>
</div> </div>
<div className="rounded-xl bg-blue-50 p-3"> <div className="rounded-xl bg-blue-50 p-3">
<FileSpreadsheet className="h-5 w-5 text-blue-600" /> <FileSpreadsheet className="h-5 w-5 text-blue-600" />
@@ -209,13 +210,38 @@ function ProgressSubTab({
</AnimatedCard> </AnimatedCard>
<AnimatedCard index={1}> <AnimatedCard index={1}>
<Card className="border-l-4 border-l-teal-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">Assignments</p>
<p className="text-2xl font-bold mt-1">{overviewStats.assignmentCount}</p>
<p className="text-xs text-muted-foreground mt-1">
{overviewStats.projectCount > 0
? `${(overviewStats.assignmentCount / overviewStats.projectCount).toFixed(1)} reviews/project`
: 'No projects'}
</p>
</div>
<div className="rounded-xl bg-teal-50 p-3">
<ClipboardCheck className="h-5 w-5 text-teal-600" />
</div>
</div>
</CardContent>
</Card>
</AnimatedCard>
<AnimatedCard index={2}>
<Card className="border-l-4 border-l-emerald-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md"> <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"> <CardContent className="p-5">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<p className="text-sm font-medium text-muted-foreground">Evaluation Count</p> <p className="text-sm font-medium text-muted-foreground">Evaluations</p>
<p className="text-2xl font-bold mt-1">{overviewStats.evaluationCount}</p> <p className="text-2xl font-bold mt-1">{overviewStats.evaluationCount}</p>
<p className="text-xs text-muted-foreground mt-1">Submitted</p> <p className="text-xs text-muted-foreground mt-1">
{overviewStats.assignmentCount > 0
? `${overviewStats.evaluationCount}/${overviewStats.assignmentCount} submitted`
: 'Submitted'}
</p>
</div> </div>
<div className="rounded-xl bg-emerald-50 p-3"> <div className="rounded-xl bg-emerald-50 p-3">
<TrendingUp className="h-5 w-5 text-emerald-600" /> <TrendingUp className="h-5 w-5 text-emerald-600" />
@@ -225,13 +251,13 @@ function ProgressSubTab({
</Card> </Card>
</AnimatedCard> </AnimatedCard>
<AnimatedCard index={2}> <AnimatedCard index={3}>
<Card className="border-l-4 border-l-violet-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md"> <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"> <CardContent className="p-5">
<div> <div>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<p className="text-sm font-medium text-muted-foreground">Completion Rate</p> <p className="text-sm font-medium text-muted-foreground">Completion</p>
<p className="text-2xl font-bold mt-1">{overviewStats.completionRate}%</p> <p className="text-2xl font-bold mt-1">{overviewStats.completionRate}%</p>
</div> </div>
<div className="rounded-xl bg-violet-50 p-3"> <div className="rounded-xl bg-violet-50 p-3">

View File

@@ -13,7 +13,8 @@ import {
TableRow, TableRow,
} from '@/components/ui/table' } from '@/components/ui/table'
import { ChevronDown, ChevronUp } from 'lucide-react' import { ChevronDown, ChevronUp } from 'lucide-react'
import Link from 'next/link' import { scoreGradient } from '@/components/charts/chart-theme'
import { ProjectPreviewDialog } from './project-preview-dialog'
interface JurorRow { interface JurorRow {
userId: string userId: string
@@ -24,7 +25,7 @@ interface JurorRow {
averageScore: number averageScore: number
stddev: number stddev: number
isOutlier: boolean isOutlier: boolean
projects: { id: string; title: string; evalStatus: string }[] projects: { id: string; title: string; evalStatus: string; score?: number | null }[]
} }
interface ExpandableJurorTableProps { interface ExpandableJurorTableProps {
@@ -42,13 +43,32 @@ function evalStatusBadge(status: string) {
} }
} }
function ScorePill({ score }: { score: number }) {
const bg = scoreGradient(score)
const text = score >= 6 ? '#ffffff' : '#1a1a1a'
return (
<span
className="inline-flex items-center justify-center rounded-md px-2 py-0.5 text-xs font-semibold tabular-nums min-w-[36px]"
style={{ backgroundColor: bg, color: text }}
>
{score.toFixed(1)}
</span>
)
}
export function ExpandableJurorTable({ jurors }: ExpandableJurorTableProps) { export function ExpandableJurorTable({ jurors }: ExpandableJurorTableProps) {
const [expanded, setExpanded] = useState<string | null>(null) const [expanded, setExpanded] = useState<string | null>(null)
const [previewProjectId, setPreviewProjectId] = useState<string | null>(null)
function toggle(userId: string) { function toggle(userId: string) {
setExpanded((prev) => (prev === userId ? null : userId)) setExpanded((prev) => (prev === userId ? null : userId))
} }
function openPreview(projectId: string, e: React.MouseEvent) {
e.stopPropagation()
setPreviewProjectId(projectId)
}
if (jurors.length === 0) { if (jurors.length === 0) {
return ( return (
<Card> <Card>
@@ -127,22 +147,29 @@ export function ExpandableJurorTable({ jurors }: ExpandableJurorTableProps) {
<thead> <thead>
<tr className="text-left text-xs text-muted-foreground border-b"> <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">Project</th>
<th className="pb-2 font-medium">Evaluation Status</th> <th className="pb-2 font-medium text-center">Score</th>
<th className="pb-2 font-medium text-right">Status</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{j.projects.map((p) => ( {j.projects.map((p) => (
<tr key={p.id} className="border-b last:border-0"> <tr key={p.id} className="border-b last:border-0">
<td className="py-1.5 pr-4"> <td className="py-2 pr-4">
<Link <button
href={`/observer/projects/${p.id}`} className="text-primary hover:underline text-left"
className="text-primary hover:underline" onClick={(e) => openPreview(p.id, e)}
onClick={(e) => e.stopPropagation()}
> >
{p.title} {p.title}
</Link> </button>
</td> </td>
<td className="py-1.5">{evalStatusBadge(p.evalStatus)}</td> <td className="py-2 text-center">
{p.score != null ? (
<ScorePill score={p.score} />
) : (
<span className="text-xs text-muted-foreground"></span>
)}
</td>
<td className="py-2 text-right">{evalStatusBadge(p.evalStatus)}</td>
</tr> </tr>
))} ))}
</tbody> </tbody>
@@ -209,13 +236,16 @@ export function ExpandableJurorTable({ jurors }: ExpandableJurorTableProps) {
<div className="mt-3 pt-3 border-t space-y-2"> <div className="mt-3 pt-3 border-t space-y-2">
{j.projects.map((p) => ( {j.projects.map((p) => (
<div key={p.id} className="flex items-center justify-between gap-2"> <div key={p.id} className="flex items-center justify-between gap-2">
<Link <button
href={`/observer/projects/${p.id}`} className="text-sm text-primary hover:underline truncate text-left"
className="text-sm text-primary hover:underline truncate" onClick={(e) => openPreview(p.id, e)}
> >
{p.title} {p.title}
</Link> </button>
{evalStatusBadge(p.evalStatus)} <div className="flex items-center gap-2 shrink-0">
{p.score != null && <ScorePill score={p.score} />}
{evalStatusBadge(p.evalStatus)}
</div>
</div> </div>
))} ))}
</div> </div>
@@ -227,6 +257,13 @@ export function ExpandableJurorTable({ jurors }: ExpandableJurorTableProps) {
</Card> </Card>
))} ))}
</div> </div>
{/* Project Preview Dialog */}
<ProjectPreviewDialog
projectId={previewProjectId}
open={!!previewProjectId}
onOpenChange={(open) => { if (!open) setPreviewProjectId(null) }}
/>
</> </>
) )
} }

View File

@@ -21,10 +21,10 @@ import {
SelectValue, SelectValue,
} from '@/components/ui/select' } from '@/components/ui/select'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { ChevronLeft, ChevronRight, ChevronDown, ChevronUp } from 'lucide-react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { RoundTypeStatsCards } from '@/components/observer/round-type-stats' import { RoundTypeStatsCards } from '@/components/observer/round-type-stats'
import { FilteringScreeningBar } from './filtering-screening-bar' import { FilteringScreeningBar } from './filtering-screening-bar'
import { ProjectPreviewDialog } from './project-preview-dialog'
interface FilteringReportTabsProps { interface FilteringReportTabsProps {
roundId: string roundId: string
@@ -46,9 +46,30 @@ function outcomeBadge(outcome: string) {
} }
} }
function ProjectsTab({ roundId }: { roundId: string }) { /** Extract reasoning text from aiScreeningJson */
function extractReasoning(aiScreeningJson: unknown): string | null {
if (!aiScreeningJson || typeof aiScreeningJson !== 'object' || Array.isArray(aiScreeningJson)) {
return null
}
const obj = aiScreeningJson as Record<string, unknown>
// Direct reasoning field
if (typeof obj.reasoning === 'string') return obj.reasoning
// Nested under rule ID: { [ruleId]: { reasoning, confidence, ... } }
for (const key of Object.keys(obj)) {
const inner = obj[key]
if (inner && typeof inner === 'object' && !Array.isArray(inner)) {
const innerObj = inner as Record<string, unknown>
if (typeof innerObj.reasoning === 'string') return innerObj.reasoning
}
}
return null
}
export function FilteringReportTabs({ roundId }: FilteringReportTabsProps) {
const [outcomeFilter, setOutcomeFilter] = useState<OutcomeFilter>('ALL') const [outcomeFilter, setOutcomeFilter] = useState<OutcomeFilter>('ALL')
const [page, setPage] = useState(1) const [page, setPage] = useState(1)
const [expandedId, setExpandedId] = useState<string | null>(null)
const [previewProjectId, setPreviewProjectId] = useState<string | null>(null)
const perPage = 20 const perPage = 20
const { data, isLoading } = trpc.analytics.getFilteringResults.useQuery({ const { data, isLoading } = trpc.analytics.getFilteringResults.useQuery({
@@ -63,8 +84,21 @@ function ProjectsTab({ roundId }: { roundId: string }) {
setPage(1) setPage(1)
} }
function toggleExpand(id: string) {
setExpandedId((prev) => (prev === id ? null : id))
}
function openPreview(projectId: string, e: React.MouseEvent) {
e.stopPropagation()
setPreviewProjectId(projectId)
}
return ( return (
<div className="space-y-4"> <div className="space-y-6">
<RoundTypeStatsCards roundId={roundId} />
<FilteringScreeningBar roundId={roundId} />
{/* Filter + count */}
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Select value={outcomeFilter} onValueChange={handleOutcomeChange}> <Select value={outcomeFilter} onValueChange={handleOutcomeChange}>
<SelectTrigger className="w-[180px]"> <SelectTrigger className="w-[180px]">
@@ -79,7 +113,7 @@ function ProjectsTab({ roundId }: { roundId: string }) {
</Select> </Select>
{data && ( {data && (
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
{data.total} result{data.total !== 1 ? 's' : ''} {data.total} project{data.total !== 1 ? 's' : ''}
</p> </p>
)} )}
</div> </div>
@@ -93,35 +127,85 @@ function ProjectsTab({ roundId }: { roundId: string }) {
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>Project Title</TableHead> <TableHead className="w-8" />
<TableHead>Project</TableHead>
<TableHead>Team</TableHead> <TableHead>Team</TableHead>
<TableHead>Category</TableHead> <TableHead>Category</TableHead>
<TableHead>Country</TableHead> <TableHead>Country</TableHead>
<TableHead>Outcome</TableHead> <TableHead>Outcome</TableHead>
<TableHead>Award Routing</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{data.results.map((r) => { {data.results.map((r) => {
const effectiveOutcome = r.finalOutcome ?? r.outcome const effectiveOutcome = r.finalOutcome ?? r.outcome
const awardRouting = r.project.awardEligibilities const reasoning = extractReasoning(r.aiScreeningJson)
.map((ae) => ae.award.name) const isExpanded = expandedId === r.id
.join(', ')
return ( return (
<TableRow key={r.id}> <>
<TableCell className="font-medium">{r.project.title}</TableCell> <TableRow
<TableCell className="text-muted-foreground">{r.project.teamName}</TableCell> key={r.id}
<TableCell className="text-muted-foreground"> className="cursor-pointer hover:bg-muted/50"
{r.project.competitionCategory ?? '—'} onClick={() => toggleExpand(r.id)}
</TableCell> >
<TableCell className="text-muted-foreground"> <TableCell className="w-8 pr-0">
{r.project.country ?? '—'} {isExpanded ? (
</TableCell> <ChevronUp className="h-4 w-4 text-muted-foreground" />
<TableCell>{outcomeBadge(effectiveOutcome)}</TableCell> ) : (
<TableCell className="text-sm text-muted-foreground"> <ChevronDown className="h-4 w-4 text-muted-foreground" />
{awardRouting || '—'} )}
</TableCell> </TableCell>
</TableRow> <TableCell>
<button
className="font-medium text-primary hover:underline text-left"
onClick={(e) => openPreview(r.project.id, e)}
>
{r.project.title}
</button>
</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>
</TableRow>
{isExpanded && (
<TableRow key={`${r.id}-detail`}>
<TableCell colSpan={6} className="bg-muted/30 p-0">
<div className="px-6 py-4 space-y-2">
{reasoning ? (
<div>
<p className="text-xs font-medium text-muted-foreground mb-1">AI Reasoning</p>
<p className="text-sm whitespace-pre-wrap leading-relaxed">{reasoning}</p>
</div>
) : (
<p className="text-sm text-muted-foreground italic">No AI reasoning available</p>
)}
{r.overrideReason && (
<div className="mt-2">
<p className="text-xs font-medium text-amber-700 mb-1">Override Reason</p>
<p className="text-sm rounded-md bg-amber-50 border border-amber-200 p-2">
{r.overrideReason}
</p>
</div>
)}
{r.project.awardEligibilities.length > 0 && (
<div className="mt-2">
<p className="text-xs font-medium text-muted-foreground mb-1">Award Routing</p>
<div className="flex gap-1.5">
{r.project.awardEligibilities.map((ae, i) => (
<Badge key={i} variant="secondary">{ae.award.name}</Badge>
))}
</div>
</div>
)}
</div>
</TableCell>
</TableRow>
)}
</>
) )
})} })}
</TableBody> </TableBody>
@@ -132,23 +216,59 @@ function ProjectsTab({ roundId }: { roundId: string }) {
<div className="space-y-3 md:hidden"> <div className="space-y-3 md:hidden">
{data.results.map((r) => { {data.results.map((r) => {
const effectiveOutcome = r.finalOutcome ?? r.outcome const effectiveOutcome = r.finalOutcome ?? r.outcome
const awardRouting = r.project.awardEligibilities const reasoning = extractReasoning(r.aiScreeningJson)
.map((ae) => ae.award.name) const isExpanded = expandedId === r.id
.join(', ')
return ( return (
<Card key={r.id}> <Card key={r.id}>
<CardContent className="pt-4 space-y-2"> <CardContent className="p-4">
<div className="flex items-start justify-between gap-2"> <button
<p className="font-medium text-sm leading-tight">{r.project.title}</p> className="w-full text-left"
{outcomeBadge(effectiveOutcome)} onClick={() => toggleExpand(r.id)}
</div> >
<p className="text-xs text-muted-foreground">{r.project.teamName}</p> <div className="flex items-start justify-between gap-2">
<div className="flex gap-3 text-xs text-muted-foreground"> <div className="min-w-0">
{r.project.competitionCategory && <span>{r.project.competitionCategory}</span>} <button
{r.project.country && <span>{r.project.country}</span>} className="font-medium text-sm text-primary hover:underline text-left truncate block max-w-full"
</div> onClick={(e) => openPreview(r.project.id, e)}
{awardRouting && ( >
<p className="text-xs text-muted-foreground">Award: {awardRouting}</p> {r.project.title}
</button>
<p className="text-xs text-muted-foreground mt-0.5">{r.project.teamName}</p>
</div>
<div className="flex items-center gap-2 shrink-0">
{outcomeBadge(effectiveOutcome)}
{isExpanded ? (
<ChevronUp className="h-4 w-4 text-muted-foreground" />
) : (
<ChevronDown className="h-4 w-4 text-muted-foreground" />
)}
</div>
</div>
<div className="flex gap-3 text-xs text-muted-foreground mt-1">
{r.project.competitionCategory && <span>{r.project.competitionCategory}</span>}
{r.project.country && <span>{r.project.country}</span>}
</div>
</button>
{isExpanded && (
<div className="mt-3 pt-3 border-t space-y-2">
{reasoning ? (
<div>
<p className="text-xs font-medium text-muted-foreground mb-1">AI Reasoning</p>
<p className="text-sm whitespace-pre-wrap leading-relaxed">{reasoning}</p>
</div>
) : (
<p className="text-sm text-muted-foreground italic">No AI reasoning available</p>
)}
{r.overrideReason && (
<div>
<p className="text-xs font-medium text-amber-700 mb-1">Override Reason</p>
<p className="text-sm rounded-md bg-amber-50 border border-amber-200 p-2">
{r.overrideReason}
</p>
</div>
)}
</div>
)} )}
</CardContent> </CardContent>
</Card> </Card>
@@ -198,34 +318,12 @@ function ProjectsTab({ roundId }: { roundId: string }) {
</CardContent> </CardContent>
</Card> </Card>
)} )}
<ProjectPreviewDialog
projectId={previewProjectId}
open={!!previewProjectId}
onOpenChange={(open) => { if (!open) setPreviewProjectId(null) }}
/>
</div> </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

@@ -32,14 +32,21 @@ export function GlobalAnalyticsTab({ programId, roundIds }: GlobalAnalyticsTabPr
return ( return (
<div className="space-y-6"> <div className="space-y-6">
{/* Geographic Distribution */} {/* Diversity Metrics — includes summary cards, category breakdown, ocean issues, tags */}
{geoLoading ? ( {diversityLoading ? (
<Skeleton className="h-[400px]" /> <Skeleton className="h-[400px]" />
) : diversity ? (
<DiversityMetricsChart data={diversity} />
) : null}
{/* Geographic Distribution — full-width map with top countries */}
{geoLoading ? (
<Skeleton className="h-[500px]" />
) : geoData?.length ? ( ) : geoData?.length ? (
<GeographicDistribution data={geoData} /> <GeographicDistribution data={geoData} />
) : null} ) : null}
{/* Status and Diversity side by side */} {/* Project Status + Cross-Round Comparison */}
<div className="grid gap-6 lg:grid-cols-2"> <div className="grid gap-6 lg:grid-cols-2">
{statusLoading ? ( {statusLoading ? (
<Skeleton className="h-[350px]" /> <Skeleton className="h-[350px]" />
@@ -47,23 +54,16 @@ export function GlobalAnalyticsTab({ programId, roundIds }: GlobalAnalyticsTabPr
<StatusBreakdownChart data={statusBreakdown} /> <StatusBreakdownChart data={statusBreakdown} />
) : null} ) : null}
{diversityLoading ? ( {roundIds && roundIds.length >= 2 && (
<Skeleton className="h-[350px]" /> <>
) : diversity ? ( {crossLoading ? (
<DiversityMetricsChart data={diversity} /> <Skeleton className="h-[350px]" />
) : null} ) : crossRound ? (
<CrossStageComparisonChart data={crossRound} />
) : null}
</>
)}
</div> </div>
{/* Cross-Round Comparison */}
{roundIds && roundIds.length >= 2 && (
<>
{crossLoading ? (
<Skeleton className="h-[350px]" />
) : crossRound ? (
<CrossStageComparisonChart data={crossRound} />
) : null}
</>
)}
</div> </div>
) )
} }

View File

@@ -0,0 +1,183 @@
'use client'
import { trpc } from '@/lib/trpc/client'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { Separator } from '@/components/ui/separator'
import { StatusBadge } from '@/components/shared/status-badge'
import { ExternalLink, MapPin, Waves, Users } from 'lucide-react'
import Link from 'next/link'
import type { Route } from 'next'
import { scoreGradient } from '@/components/charts/chart-theme'
interface ProjectPreviewDialogProps {
projectId: string | null
open: boolean
onOpenChange: (open: boolean) => void
}
function ScorePill({ score }: { score: number }) {
const bg = scoreGradient(score)
const text = score >= 6 ? '#ffffff' : '#1a1a1a'
return (
<span
className="inline-flex items-center justify-center rounded-md px-2.5 py-1 text-sm font-bold tabular-nums"
style={{ backgroundColor: bg, color: text }}
>
{score.toFixed(1)}
</span>
)
}
export function ProjectPreviewDialog({ projectId, open, onOpenChange }: ProjectPreviewDialogProps) {
const { data, isLoading } = trpc.analytics.getProjectDetail.useQuery(
{ id: projectId! },
{ enabled: !!projectId && open },
)
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
{isLoading || !data ? (
<>
<DialogHeader>
<Skeleton className="h-6 w-48" />
</DialogHeader>
<div className="space-y-4">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-20 w-full" />
<Skeleton className="h-32 w-full" />
</div>
</>
) : (
<>
<DialogHeader>
<DialogTitle className="text-lg leading-tight pr-8">
{data.project.title}
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
{/* Project info row */}
<div className="flex flex-wrap items-center gap-2">
<StatusBadge status={data.project.status} />
{data.project.teamName && (
<Badge variant="outline" className="gap-1">
<Users className="h-3 w-3" />
{data.project.teamName}
</Badge>
)}
{data.project.country && (
<Badge variant="outline" className="gap-1">
<MapPin className="h-3 w-3" />
{data.project.country}
</Badge>
)}
{data.project.competitionCategory && (
<Badge variant="secondary">{data.project.competitionCategory}</Badge>
)}
</div>
{/* Description */}
{data.project.description && (
<p className="text-sm text-muted-foreground line-clamp-4">
{data.project.description}
</p>
)}
{/* Ocean Issue */}
{data.project.oceanIssue && (
<Badge variant="outline" className="gap-1 text-xs">
<Waves className="h-3 w-3" />
{data.project.oceanIssue.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, (c: string) => c.toUpperCase())}
</Badge>
)}
<Separator />
{/* Evaluation summary */}
{data.stats && (
<div>
<h3 className="text-sm font-semibold mb-2">Evaluation Summary</h3>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
<div className="rounded-md border p-3 text-center">
<p className="text-lg font-bold tabular-nums">
{data.stats.averageGlobalScore != null ? (
<ScorePill score={data.stats.averageGlobalScore} />
) : '—'}
</p>
<p className="text-xs text-muted-foreground mt-1">Avg Score</p>
</div>
<div className="rounded-md border p-3 text-center">
<p className="text-lg font-bold tabular-nums">{data.stats.totalEvaluations ?? 0}</p>
<p className="text-xs text-muted-foreground mt-1">Evaluations</p>
</div>
<div className="rounded-md border p-3 text-center">
<p className="text-lg font-bold tabular-nums">{data.assignments?.length ?? 0}</p>
<p className="text-xs text-muted-foreground mt-1">Assignments</p>
</div>
<div className="rounded-md border p-3 text-center">
<p className="text-lg font-bold tabular-nums">
{data.stats.yesPercentage != null ? `${Math.round(data.stats.yesPercentage)}%` : '—'}
</p>
<p className="text-xs text-muted-foreground mt-1">Recommend</p>
</div>
</div>
</div>
)}
{/* Individual evaluations */}
{data.assignments?.length > 0 && (
<div>
<h3 className="text-sm font-semibold mb-2">Juror Evaluations</h3>
<div className="space-y-1.5">
{data.assignments.map((a: { id: string; user: { name: string | null }; evaluation: { status: string; globalScore: unknown } | null }) => {
const ev = a.evaluation
const score = ev?.status === 'SUBMITTED' && ev.globalScore != null
? Number(ev.globalScore)
: null
return (
<div key={a.id} className="flex items-center justify-between rounded-md border px-3 py-2">
<div className="flex items-center gap-2">
<span className="text-sm font-medium">{a.user.name ?? 'Unknown'}</span>
{ev?.status === 'SUBMITTED' ? (
<Badge variant="default" className="text-[10px]">Reviewed</Badge>
) : ev?.status === 'DRAFT' ? (
<Badge variant="secondary" className="text-[10px]">Draft</Badge>
) : (
<Badge variant="outline" className="text-[10px]">Pending</Badge>
)}
</div>
{score !== null && <ScorePill score={score} />}
</div>
)
})}
</div>
</div>
)}
<Separator />
{/* View full project button */}
<div className="flex justify-end">
<Button asChild>
<Link href={`/observer/projects/${projectId}` as Route}>
<ExternalLink className="mr-2 h-4 w-4" />
View Full Project
</Link>
</Button>
</div>
</div>
</>
)}
</DialogContent>
</Dialog>
)
}

View File

@@ -126,7 +126,7 @@ export const analyticsRouter = router({
user: { select: { name: true } }, user: { select: { name: true } },
project: { select: { id: true, title: true } }, project: { select: { id: true, title: true } },
evaluation: { evaluation: {
select: { id: true, status: true }, select: { id: true, status: true, globalScore: true },
}, },
}, },
}) })
@@ -134,7 +134,7 @@ export const analyticsRouter = router({
// Group by user // Group by user
const byUser: Record< const byUser: Record<
string, string,
{ name: string; assigned: number; completed: number; projects: { id: string; title: string; evalStatus: string }[] } { name: string; assigned: number; completed: number; projects: { id: string; title: string; evalStatus: string; score: number | null }[] }
> = {} > = {}
assignments.forEach((assignment) => { assignments.forEach((assignment) => {
@@ -156,6 +156,9 @@ export const analyticsRouter = router({
id: assignment.project.id, id: assignment.project.id,
title: assignment.project.title, title: assignment.project.title,
evalStatus: evalStatus === 'SUBMITTED' ? 'REVIEWED' : evalStatus === 'DRAFT' ? 'UNDER_REVIEW' : 'NOT_REVIEWED', evalStatus: evalStatus === 'SUBMITTED' ? 'REVIEWED' : evalStatus === 'DRAFT' ? 'UNDER_REVIEW' : 'NOT_REVIEWED',
score: evalStatus === 'SUBMITTED' && assignment.evaluation?.globalScore != null
? Number(assignment.evaluation.globalScore)
: null,
}) })
}) })
@@ -251,7 +254,59 @@ export const analyticsRouter = router({
.input(editionOrRoundInput) .input(editionOrRoundInput)
.query(async ({ ctx, input }) => { .query(async ({ ctx, input }) => {
if (input.roundId) { if (input.roundId) {
// Round-level: use ProjectRoundState for accurate per-round breakdown // Check if this is an evaluation round — show eval-level status breakdown
const round = await ctx.prisma.round.findUnique({
where: { id: input.roundId },
select: { roundType: true },
})
if (round?.roundType === 'EVALUATION') {
// For evaluation rounds, break down by evaluation status per project
const projects = await ctx.prisma.projectRoundState.findMany({
where: { roundId: input.roundId },
select: {
projectId: true,
project: {
select: {
assignments: {
where: { roundId: input.roundId },
select: {
evaluation: { select: { status: true } },
},
},
},
},
},
})
let fullyReviewed = 0
let partiallyReviewed = 0
let notReviewed = 0
for (const p of projects) {
const assignments = p.project.assignments
if (assignments.length === 0) {
notReviewed++
continue
}
const submitted = assignments.filter((a) => a.evaluation?.status === 'SUBMITTED').length
if (submitted === 0) {
notReviewed++
} else if (submitted === assignments.length) {
fullyReviewed++
} else {
partiallyReviewed++
}
}
const result = []
if (fullyReviewed > 0) result.push({ status: 'FULLY_REVIEWED', count: fullyReviewed })
if (partiallyReviewed > 0) result.push({ status: 'PARTIALLY_REVIEWED', count: partiallyReviewed })
if (notReviewed > 0) result.push({ status: 'NOT_REVIEWED', count: notReviewed })
return result
}
// Non-evaluation rounds: use ProjectRoundState
const states = await ctx.prisma.projectRoundState.groupBy({ const states = await ctx.prisma.projectRoundState.groupBy({
by: ['state'], by: ['state'],
where: { roundId: input.roundId }, where: { roundId: input.roundId },
@@ -668,7 +723,7 @@ export const analyticsRouter = router({
const [ const [
programCount, programCount,
activeRoundCount, activeRounds,
projectCount, projectCount,
jurorCount, jurorCount,
submittedEvaluations, submittedEvaluations,
@@ -676,12 +731,11 @@ export const analyticsRouter = router({
evaluationScores, evaluationScores,
] = await Promise.all([ ] = await Promise.all([
ctx.prisma.program.count(), ctx.prisma.program.count(),
roundId ctx.prisma.round.findMany({
? ctx.prisma.round.findUnique({ where: { id: roundId }, select: { competitionId: true } }) where: { status: 'ROUND_ACTIVE' },
.then((r) => r?.competitionId select: { id: true, name: true },
? ctx.prisma.round.count({ where: { competitionId: r.competitionId, status: 'ROUND_ACTIVE' } }) take: 5,
: ctx.prisma.round.count({ where: { status: 'ROUND_ACTIVE' } })) }),
: ctx.prisma.round.count({ where: { status: 'ROUND_ACTIVE' } }),
ctx.prisma.project.count({ where: projectFilter }), ctx.prisma.project.count({ where: projectFilter }),
roundId roundId
? ctx.prisma.assignment.findMany({ ? ctx.prisma.assignment.findMany({
@@ -716,7 +770,8 @@ export const analyticsRouter = router({
return { return {
programCount, programCount,
activeRoundCount, activeRoundCount: activeRounds.length,
activeRoundName: activeRounds.length === 1 ? activeRounds[0].name : null,
projectCount, projectCount,
jurorCount, jurorCount,
submittedEvaluations, submittedEvaluations,
@@ -1551,7 +1606,12 @@ export const analyticsRouter = router({
skip, skip,
take: perPage, take: perPage,
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
include: { select: {
id: true,
outcome: true,
finalOutcome: true,
aiScreeningJson: true,
overrideReason: true,
project: { project: {
select: { select: {
id: true, id: true,