Round detail overhaul, file requirements, project management, audit log fix

- Redesign round detail page with 6 tabs (overview, projects, filtering, assignments, config, documents)
- Add jury group assignment selector in round stats bar
- Add FileRequirementsEditor component replacing SubmissionWindowManager
- Add FilteringDashboard component for AI-powered project screening
- Add project removal from rounds (single + bulk) with cascading to subsequent rounds
- Add project add/remove UI in ProjectStatesTable with confirmation dialogs
- Fix logAudit inside $transaction pattern across all 12 router files
  (PostgreSQL aborted-transaction state caused silent operation failures)
- Fix special awards creation, deletion, status update, and winner assignment

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Matt 2026-02-16 07:49:39 +01:00
parent f572336781
commit 7f334ed095
18 changed files with 3387 additions and 968 deletions

View File

@ -362,7 +362,6 @@ export default function CompetitionDetailPage() {
</div>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium truncate">{round.name}</p>
<p className="text-xs text-muted-foreground font-mono">{round.slug}</p>
</div>
<Badge
variant="secondary"

View File

@ -1,44 +1,125 @@
'use client'
import { useState } from 'react'
import { useParams } from 'next/navigation'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Skeleton } from '@/components/ui/skeleton'
import { Badge } from '@/components/ui/badge'
import { ArrowLeft, Save, Loader2 } from 'lucide-react'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
ArrowLeft,
Save,
Loader2,
ChevronDown,
Play,
Square,
Archive,
Layers,
Users,
CalendarDays,
BarChart3,
ClipboardList,
Settings,
Zap,
ExternalLink,
FileText,
Shield,
UserPlus,
} from 'lucide-react'
import { RoundConfigForm } from '@/components/admin/competition/round-config-form'
import { ProjectStatesTable } from '@/components/admin/round/project-states-table'
import { SubmissionWindowManager } from '@/components/admin/round/submission-window-manager'
import { FileRequirementsEditor } from '@/components/admin/round/file-requirements-editor'
import { FilteringDashboard } from '@/components/admin/round/filtering-dashboard'
const roundTypeColors: Record<string, string> = {
INTAKE: 'bg-gray-100 text-gray-700',
FILTERING: 'bg-amber-100 text-amber-700',
EVALUATION: 'bg-blue-100 text-blue-700',
SUBMISSION: 'bg-purple-100 text-purple-700',
MENTORING: 'bg-teal-100 text-teal-700',
LIVE_FINAL: 'bg-red-100 text-red-700',
DELIBERATION: 'bg-indigo-100 text-indigo-700',
// -- Status config --
const roundStatusConfig = {
ROUND_DRAFT: {
label: 'Draft',
bgClass: 'bg-gray-100 text-gray-700',
dotClass: 'bg-gray-500',
description: 'Not yet active. Configure before launching.',
},
ROUND_ACTIVE: {
label: 'Active',
bgClass: 'bg-emerald-100 text-emerald-700',
dotClass: 'bg-emerald-500 animate-pulse',
description: 'Round is live. Projects can be processed.',
},
ROUND_CLOSED: {
label: 'Closed',
bgClass: 'bg-blue-100 text-blue-700',
dotClass: 'bg-blue-500',
description: 'No longer accepting changes. Results are final.',
},
ROUND_ARCHIVED: {
label: 'Archived',
bgClass: 'bg-muted text-muted-foreground',
dotClass: 'bg-muted-foreground',
description: 'Historical record only.',
},
} as const
const roundTypeConfig: Record<string, { label: string; color: string; description: string }> = {
INTAKE: { label: 'Intake', color: 'bg-gray-100 text-gray-700', description: 'Collecting applications' },
FILTERING: { label: 'Filtering', color: 'bg-amber-100 text-amber-700', description: 'AI + manual screening' },
EVALUATION: { label: 'Evaluation', color: 'bg-blue-100 text-blue-700', description: 'Jury evaluation & scoring' },
SUBMISSION: { label: 'Submission', color: 'bg-purple-100 text-purple-700', description: 'Document submission' },
MENTORING: { label: 'Mentoring', color: 'bg-teal-100 text-teal-700', description: 'Mentor-guided development' },
LIVE_FINAL: { label: 'Live Final', color: 'bg-red-100 text-red-700', description: 'Live presentations & voting' },
DELIBERATION: { label: 'Deliberation', color: 'bg-indigo-100 text-indigo-700', description: 'Final jury deliberation' },
}
export default function RoundDetailPage() {
const params = useParams()
const router = useRouter()
const competitionId = params.competitionId as string
const roundId = params.roundId as string
const [config, setConfig] = useState<Record<string, unknown>>({})
const [hasChanges, setHasChanges] = useState(false)
const [activeTab, setActiveTab] = useState('overview')
const utils = trpc.useUtils()
const { data: round, isLoading } = trpc.round.getById.useQuery({ id: roundId })
const { data: projectStates } = trpc.roundEngine.getProjectStates.useQuery({ roundId })
const { data: juryGroups } = trpc.juryGroup.list.useQuery(
{ competitionId },
{ enabled: !!competitionId },
)
// Update local config when round data changes
// Sync config from server when not dirty
if (round && !hasChanges) {
const roundConfig = (round.configJson as Record<string, unknown>) ?? {}
if (JSON.stringify(roundConfig) !== JSON.stringify(config)) {
@ -46,6 +127,7 @@ export default function RoundDetailPage() {
}
}
// -- Mutations --
const updateMutation = trpc.round.update.useMutation({
onSuccess: () => {
utils.round.getById.invalidate({ id: roundId })
@ -55,30 +137,79 @@ export default function RoundDetailPage() {
onError: (err) => toast.error(err.message),
})
const activateMutation = trpc.roundEngine.activate.useMutation({
onSuccess: () => {
utils.round.getById.invalidate({ id: roundId })
toast.success('Round activated')
},
onError: (err) => toast.error(err.message),
})
const closeMutation = trpc.roundEngine.close.useMutation({
onSuccess: () => {
utils.round.getById.invalidate({ id: roundId })
toast.success('Round closed')
},
onError: (err) => toast.error(err.message),
})
const archiveMutation = trpc.roundEngine.archive.useMutation({
onSuccess: () => {
utils.round.getById.invalidate({ id: roundId })
toast.success('Round archived')
},
onError: (err) => toast.error(err.message),
})
const assignJuryMutation = trpc.round.update.useMutation({
onSuccess: () => {
utils.round.getById.invalidate({ id: roundId })
toast.success('Jury group updated')
},
onError: (err) => toast.error(err.message),
})
const isTransitioning = activateMutation.isPending || closeMutation.isPending || archiveMutation.isPending
const handleConfigChange = (newConfig: Record<string, unknown>) => {
setConfig(newConfig)
setHasChanges(true)
}
const handleSave = () => {
updateMutation.mutate({
id: roundId,
configJson: config,
})
updateMutation.mutate({ id: roundId, configJson: config })
}
// -- Computed --
const projectCount = round?._count?.projectRoundStates ?? 0
const stateCounts = projectStates?.reduce((acc: Record<string, number>, ps: any) => {
acc[ps.state] = (acc[ps.state] || 0) + 1
return acc
}, {} as Record<string, number>) ?? {}
const juryGroup = round?.juryGroup
const juryMemberCount = juryGroup?.members?.length ?? 0
// Determine available tabs based on round type
const isFiltering = round?.roundType === 'FILTERING'
const isEvaluation = round?.roundType === 'EVALUATION'
const hasSubmissionWindows = round?.roundType === 'SUBMISSION' || round?.roundType === 'EVALUATION' || round?.roundType === 'INTAKE'
// Loading
if (isLoading) {
return (
<div className="space-y-6">
<div className="flex items-center gap-3">
<Skeleton className="h-8 w-8" />
<div>
<Skeleton className="h-6 w-48" />
<Skeleton className="h-4 w-32 mt-1" />
<div className="space-y-2">
<Skeleton className="h-7 w-64" />
<Skeleton className="h-4 w-40" />
</div>
</div>
<div className="grid gap-3 grid-cols-2 sm:grid-cols-4">
{[1, 2, 3, 4].map((i) => <Skeleton key={i} className="h-24" />)}
</div>
<Skeleton className="h-10 w-full" />
<Skeleton className="h-64 w-full" />
<Skeleton className="h-96 w-full" />
</div>
)
}
@ -88,73 +219,550 @@ export default function RoundDetailPage() {
<div className="space-y-6">
<div className="flex items-center gap-3">
<Link href={`/admin/competitions/${competitionId}` as Route}>
<Button variant="ghost" size="icon" className="h-8 w-8" aria-label="Back to competition details">
<Button variant="ghost" size="icon" className="h-8 w-8" aria-label="Back">
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
<div>
<h1 className="text-xl font-bold">Round Not Found</h1>
<p className="text-sm text-muted-foreground">
The requested round does not exist
</p>
<p className="text-sm text-muted-foreground">This round does not exist.</p>
</div>
</div>
</div>
)
}
const status = round.status as keyof typeof roundStatusConfig
const statusCfg = roundStatusConfig[status] || roundStatusConfig.ROUND_DRAFT
const typeCfg = roundTypeConfig[round.roundType] || roundTypeConfig.INTAKE
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
{/* ===== HEADER ===== */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div className="flex items-start gap-3 min-w-0">
<Link href={`/admin/competitions/${competitionId}` as Route} className="mt-1 shrink-0">
<Button variant="ghost" size="icon" className="h-8 w-8" aria-label="Back to competition details">
<Button variant="ghost" size="icon" className="h-8 w-8" aria-label="Back to competition">
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-xl font-bold truncate">{round.name}</h1>
<Badge
variant="secondary"
className={roundTypeColors[round.roundType] ?? 'bg-gray-100 text-gray-700'}
>
{round.roundType.replace('_', ' ')}
<h1 className="text-xl font-bold tracking-tight truncate">{round.name}</h1>
<Badge variant="secondary" className={cn('text-xs shrink-0', typeCfg.color)}>
{typeCfg.label}
</Badge>
{/* Status dropdown */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
className={cn(
'inline-flex items-center gap-1.5 text-[11px] font-medium px-2.5 py-1 rounded-full transition-colors shrink-0',
statusCfg.bgClass,
'hover:opacity-80',
)}
>
<span className={cn('h-1.5 w-1.5 rounded-full', statusCfg.dotClass)} />
{statusCfg.label}
<ChevronDown className="h-3 w-3" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
{status === 'ROUND_DRAFT' && (
<DropdownMenuItem
onClick={() => activateMutation.mutate({ roundId })}
disabled={isTransitioning}
>
<Play className="h-4 w-4 mr-2 text-emerald-600" />
Activate Round
</DropdownMenuItem>
)}
{status === 'ROUND_ACTIVE' && (
<DropdownMenuItem
onClick={() => closeMutation.mutate({ roundId })}
disabled={isTransitioning}
>
<Square className="h-4 w-4 mr-2 text-blue-600" />
Close Round
</DropdownMenuItem>
)}
{status === 'ROUND_CLOSED' && (
<>
<DropdownMenuItem
onClick={() => activateMutation.mutate({ roundId })}
disabled={isTransitioning}
>
<Play className="h-4 w-4 mr-2 text-emerald-600" />
Reactivate Round
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => archiveMutation.mutate({ roundId })}
disabled={isTransitioning}
>
<Archive className="h-4 w-4 mr-2" />
Archive Round
</DropdownMenuItem>
</>
)}
{isTransitioning && (
<div className="flex items-center gap-2 px-2 py-1.5 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" />
Updating...
</div>
<p className="text-sm text-muted-foreground font-mono">{round.slug}</p>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
<p className="text-sm text-muted-foreground mt-0.5">{typeCfg.description}</p>
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
{/* Action buttons */}
<div className="flex items-center gap-2 shrink-0 flex-wrap">
{hasChanges && (
<Button
variant="default"
size="sm"
onClick={handleSave}
disabled={updateMutation.isPending}
>
<Button size="sm" onClick={handleSave} disabled={updateMutation.isPending}>
{updateMutation.isPending ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
<Loader2 className="h-4 w-4 mr-1.5 animate-spin" />
) : (
<Save className="h-4 w-4 mr-2" />
<Save className="h-4 w-4 mr-1.5" />
)}
Save Changes
Save Config
</Button>
)}
{(isEvaluation || isFiltering) && (
<Link href={`/admin/competitions/${competitionId}/assignments` as Route}>
<Button variant="outline" size="sm">
<ClipboardList className="h-4 w-4 mr-1.5" />
Assignments
</Button>
</Link>
)}
<Link href={'/admin/projects/pool' as Route}>
<Button variant="outline" size="sm">
<Layers className="h-4 w-4 mr-1.5" />
Project Pool
</Button>
</Link>
</div>
</div>
{/* Tabs */}
<Tabs defaultValue="config" className="space-y-4">
{/* ===== STATS BAR ===== */}
<div className="grid gap-3 grid-cols-2 sm:grid-cols-4">
<Card>
<CardContent className="pt-4 pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Layers className="h-4 w-4 text-blue-500" />
<span className="text-sm font-medium">Projects</span>
</div>
</div>
<p className="text-2xl font-bold mt-1">{projectCount}</p>
<div className="flex flex-wrap gap-1.5 mt-1.5">
{Object.entries(stateCounts).map(([state, count]) => (
<span key={state} className="text-[10px] text-muted-foreground">
{String(count)} {state.toLowerCase().replace('_', ' ')}
</span>
))}
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-4 pb-3">
<div className="flex items-center gap-2 mb-1" data-jury-select>
<Users className="h-4 w-4 text-purple-500" />
<span className="text-sm font-medium">Jury</span>
</div>
{juryGroups && juryGroups.length > 0 ? (
<Select
value={round.juryGroupId ?? '__none__'}
onValueChange={(value) => {
assignJuryMutation.mutate({
id: roundId,
juryGroupId: value === '__none__' ? null : value,
})
}}
disabled={assignJuryMutation.isPending}
>
<SelectTrigger className="h-8 text-xs mt-1">
<SelectValue placeholder="Select jury group..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">No jury assigned</SelectItem>
{juryGroups.map((jg: any) => (
<SelectItem key={jg.id} value={jg.id}>
{jg.name} ({jg._count?.members ?? 0} members)
</SelectItem>
))}
</SelectContent>
</Select>
) : juryGroup ? (
<>
<p className="text-2xl font-bold mt-1">{juryMemberCount}</p>
<p className="text-xs text-muted-foreground truncate">{juryGroup.name}</p>
</>
) : (
<>
<p className="text-2xl font-bold mt-1 text-muted-foreground"></p>
<p className="text-xs text-muted-foreground">No jury groups yet</p>
</>
)}
</CardContent>
</Card>
<Card>
<CardContent className="pt-4 pb-3">
<div className="flex items-center gap-2">
<CalendarDays className="h-4 w-4 text-emerald-500" />
<span className="text-sm font-medium">Window</span>
</div>
{round.windowOpenAt || round.windowCloseAt ? (
<>
<p className="text-sm font-bold mt-1">
{round.windowOpenAt
? new Date(round.windowOpenAt).toLocaleDateString()
: 'No start'}
</p>
<p className="text-xs text-muted-foreground">
{round.windowCloseAt
? `Closes ${new Date(round.windowCloseAt).toLocaleDateString()}`
: 'No deadline'}
</p>
</>
) : (
<>
<p className="text-2xl font-bold mt-1 text-muted-foreground"></p>
<p className="text-xs text-muted-foreground">No dates set</p>
</>
)}
</CardContent>
</Card>
<Card>
<CardContent className="pt-4 pb-3">
<div className="flex items-center gap-2">
<BarChart3 className="h-4 w-4 text-amber-500" />
<span className="text-sm font-medium">Advancement</span>
</div>
{round.advancementRules && round.advancementRules.length > 0 ? (
<>
<p className="text-2xl font-bold mt-1">{round.advancementRules.length}</p>
<p className="text-xs text-muted-foreground">
{round.advancementRules.map((r: any) => r.ruleType.replace('_', ' ').toLowerCase()).join(', ')}
</p>
</>
) : (
<>
<p className="text-2xl font-bold mt-1 text-muted-foreground"></p>
<p className="text-xs text-muted-foreground">Admin selection</p>
</>
)}
</CardContent>
</Card>
</div>
{/* ===== TABS ===== */}
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
<TabsList className="w-full sm:w-auto overflow-x-auto">
<TabsTrigger value="config">Configuration</TabsTrigger>
<TabsTrigger value="projects">Projects</TabsTrigger>
<TabsTrigger value="windows">Submission Windows</TabsTrigger>
<TabsTrigger value="overview">
<Zap className="h-3.5 w-3.5 mr-1.5" />
Overview
</TabsTrigger>
<TabsTrigger value="projects">
<Layers className="h-3.5 w-3.5 mr-1.5" />
Projects
</TabsTrigger>
{isFiltering && (
<TabsTrigger value="filtering">
<Shield className="h-3.5 w-3.5 mr-1.5" />
Filtering
</TabsTrigger>
)}
{isEvaluation && (
<TabsTrigger value="assignments">
<ClipboardList className="h-3.5 w-3.5 mr-1.5" />
Assignments
</TabsTrigger>
)}
<TabsTrigger value="config">
<Settings className="h-3.5 w-3.5 mr-1.5" />
Config
</TabsTrigger>
<TabsTrigger value="windows">
<FileText className="h-3.5 w-3.5 mr-1.5" />
Documents
</TabsTrigger>
</TabsList>
{/* Config Tab */}
{/* ===== OVERVIEW TAB ===== */}
<TabsContent value="overview" className="space-y-6">
{/* Quick Actions */}
<Card>
<CardHeader>
<CardTitle className="text-base">Quick Actions</CardTitle>
<CardDescription>Common operations for this round</CardDescription>
</CardHeader>
<CardContent>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{/* Status transitions */}
{status === 'ROUND_DRAFT' && (
<AlertDialog>
<AlertDialogTrigger asChild>
<button className="flex items-start gap-3 p-4 rounded-lg border hover:bg-muted/50 transition-colors text-left">
<Play className="h-5 w-5 text-emerald-600 mt-0.5 shrink-0" />
<div>
<p className="text-sm font-medium">Activate Round</p>
<p className="text-xs text-muted-foreground mt-0.5">
Start this round and allow project processing
</p>
</div>
</button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Activate this round?</AlertDialogTitle>
<AlertDialogDescription>
The round will go live. Projects can be processed and jury members will be able to see their assignments.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={() => activateMutation.mutate({ roundId })}>
Activate
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
{status === 'ROUND_ACTIVE' && (
<AlertDialog>
<AlertDialogTrigger asChild>
<button className="flex items-start gap-3 p-4 rounded-lg border hover:bg-muted/50 transition-colors text-left">
<Square className="h-5 w-5 text-blue-600 mt-0.5 shrink-0" />
<div>
<p className="text-sm font-medium">Close Round</p>
<p className="text-xs text-muted-foreground mt-0.5">
Stop accepting changes and finalize results
</p>
</div>
</button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Close this round?</AlertDialogTitle>
<AlertDialogDescription>
No further changes will be accepted. You can reactivate later if needed.
{projectCount > 0 && (
<span className="block mt-2">
{projectCount} projects are currently in this round.
</span>
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={() => closeMutation.mutate({ roundId })}>
Close Round
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
{/* Assign projects */}
<Link href={'/admin/projects/pool' as Route}>
<button className="flex items-start gap-3 p-4 rounded-lg border hover:bg-muted/50 transition-colors text-left w-full">
<Layers className="h-5 w-5 text-blue-600 mt-0.5 shrink-0" />
<div>
<p className="text-sm font-medium">Assign Projects</p>
<p className="text-xs text-muted-foreground mt-0.5">
Add projects from the pool to this round
</p>
</div>
</button>
</Link>
{/* Filtering specific */}
{isFiltering && (
<button
onClick={() => setActiveTab('filtering')}
className="flex items-start gap-3 p-4 rounded-lg border hover:bg-muted/50 transition-colors text-left"
>
<Shield className="h-5 w-5 text-amber-600 mt-0.5 shrink-0" />
<div>
<p className="text-sm font-medium">Run AI Filtering</p>
<p className="text-xs text-muted-foreground mt-0.5">
Screen projects with AI and manual review
</p>
</div>
</button>
)}
{/* Jury assignment for evaluation/filtering */}
{(isEvaluation || isFiltering) && !juryGroup && (
<button
onClick={() => {
const el = document.querySelector('[data-jury-select]')
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' })
}}
className="flex items-start gap-3 p-4 rounded-lg border hover:bg-muted/50 transition-colors text-left border-amber-200 bg-amber-50/50"
>
<UserPlus className="h-5 w-5 text-amber-600 mt-0.5 shrink-0" />
<div>
<p className="text-sm font-medium">Assign Jury Group</p>
<p className="text-xs text-muted-foreground mt-0.5">
No jury group assigned. Select one in the Jury card above.
</p>
</div>
</button>
)}
{/* Evaluation specific */}
{isEvaluation && (
<Link href={`/admin/competitions/${competitionId}/assignments` as Route}>
<button className="flex items-start gap-3 p-4 rounded-lg border hover:bg-muted/50 transition-colors text-left w-full">
<ClipboardList className="h-5 w-5 text-blue-600 mt-0.5 shrink-0" />
<div>
<p className="text-sm font-medium">Manage Assignments</p>
<p className="text-xs text-muted-foreground mt-0.5">
Generate and review jury-project assignments
</p>
</div>
</button>
</Link>
)}
{/* View projects */}
<button
onClick={() => setActiveTab('projects')}
className="flex items-start gap-3 p-4 rounded-lg border hover:bg-muted/50 transition-colors text-left"
>
<BarChart3 className="h-5 w-5 text-purple-600 mt-0.5 shrink-0" />
<div>
<p className="text-sm font-medium">Manage Projects</p>
<p className="text-xs text-muted-foreground mt-0.5">
View, filter, and transition project states
</p>
</div>
</button>
</div>
</CardContent>
</Card>
{/* Round info */}
<div className="grid gap-4 sm:grid-cols-2">
<Card>
<CardHeader>
<CardTitle className="text-sm">Round Details</CardTitle>
</CardHeader>
<CardContent className="space-y-3 text-sm">
<div className="flex justify-between">
<span className="text-muted-foreground">Type</span>
<Badge variant="secondary" className={cn('text-xs', typeCfg.color)}>{typeCfg.label}</Badge>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Status</span>
<span className="font-medium">{statusCfg.label}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Sort Order</span>
<span className="font-medium font-mono">{round.sortOrder}</span>
</div>
{round.purposeKey && (
<div className="flex justify-between">
<span className="text-muted-foreground">Purpose</span>
<span className="font-medium">{round.purposeKey}</span>
</div>
)}
<div className="flex justify-between">
<span className="text-muted-foreground">Jury Group</span>
<span className="font-medium">
{juryGroup ? juryGroup.name : '—'}
</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Opens</span>
<span className="font-medium">
{round.windowOpenAt ? new Date(round.windowOpenAt).toLocaleString() : '—'}
</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Closes</span>
<span className="font-medium">
{round.windowCloseAt ? new Date(round.windowCloseAt).toLocaleString() : '—'}
</span>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-sm">Project Breakdown</CardTitle>
</CardHeader>
<CardContent>
{projectCount === 0 ? (
<p className="text-sm text-muted-foreground py-4 text-center">
No projects assigned yet
</p>
) : (
<div className="space-y-2">
{['PENDING', 'IN_PROGRESS', 'PASSED', 'REJECTED', 'COMPLETED', 'WITHDRAWN'].map((state) => {
const count = stateCounts[state] || 0
if (count === 0) return null
const pct = ((count / projectCount) * 100).toFixed(0)
const colors: Record<string, string> = {
PENDING: 'bg-gray-400',
IN_PROGRESS: 'bg-blue-500',
PASSED: 'bg-green-500',
REJECTED: 'bg-red-500',
COMPLETED: 'bg-emerald-500',
WITHDRAWN: 'bg-orange-400',
}
return (
<div key={state}>
<div className="flex justify-between text-xs mb-1">
<span className="text-muted-foreground capitalize">{state.toLowerCase().replace('_', ' ')}</span>
<span className="font-medium">{count} ({pct}%)</span>
</div>
<div className="h-1.5 bg-muted rounded-full overflow-hidden">
<div
className={cn('h-full rounded-full transition-all', colors[state])}
style={{ width: `${pct}%` }}
/>
</div>
</div>
)
})}
</div>
)}
</CardContent>
</Card>
</div>
</TabsContent>
{/* ===== PROJECTS TAB ===== */}
<TabsContent value="projects" className="space-y-4">
<ProjectStatesTable competitionId={competitionId} roundId={roundId} />
</TabsContent>
{/* ===== FILTERING TAB ===== */}
{isFiltering && (
<TabsContent value="filtering" className="space-y-4">
<FilteringDashboard competitionId={competitionId} roundId={roundId} />
</TabsContent>
)}
{/* ===== ASSIGNMENTS TAB (Evaluation rounds) ===== */}
{isEvaluation && (
<TabsContent value="assignments" className="space-y-4">
<RoundAssignmentsOverview competitionId={competitionId} roundId={roundId} />
</TabsContent>
)}
{/* ===== CONFIG TAB ===== */}
<TabsContent value="config" className="space-y-4">
<RoundConfigForm
roundType={round.roundType}
@ -163,16 +771,129 @@ export default function RoundDetailPage() {
/>
</TabsContent>
{/* Projects Tab */}
<TabsContent value="projects" className="space-y-4">
<ProjectStatesTable competitionId={competitionId} roundId={roundId} />
</TabsContent>
{/* Submission Windows Tab */}
{/* ===== DOCUMENTS TAB ===== */}
<TabsContent value="windows" className="space-y-4">
<SubmissionWindowManager competitionId={competitionId} roundId={roundId} />
<FileRequirementsEditor
roundId={roundId}
windowOpenAt={round.windowOpenAt}
windowCloseAt={round.windowCloseAt}
/>
</TabsContent>
</Tabs>
</div>
)
}
// ===== Inline sub-component for evaluation round assignments =====
function RoundAssignmentsOverview({ competitionId, roundId }: { competitionId: string; roundId: string }) {
const { data: coverage, isLoading: coverageLoading } = trpc.roundAssignment.coverageReport.useQuery({
roundId,
requiredReviews: 3,
})
const { data: unassigned, isLoading: unassignedLoading } = trpc.roundAssignment.unassignedQueue.useQuery(
{ roundId, requiredReviews: 3 },
)
return (
<div className="space-y-6">
{/* Coverage stats */}
{coverageLoading ? (
<div className="grid gap-4 grid-cols-1 sm:grid-cols-3">
{[1, 2, 3].map((i) => <Skeleton key={i} className="h-28" />)}
</div>
) : coverage ? (
<div className="grid gap-4 grid-cols-1 sm:grid-cols-3">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Fully Assigned</CardTitle>
<Users className="h-4 w-4 text-green-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{coverage.fullyAssigned || 0}</div>
<p className="text-xs text-muted-foreground">
of {coverage.totalProjects || 0} projects ({coverage.totalProjects ? ((coverage.fullyAssigned / coverage.totalProjects) * 100).toFixed(0) : 0}%)
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Avg Reviews/Project</CardTitle>
<BarChart3 className="h-4 w-4 text-blue-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{coverage.avgReviewsPerProject?.toFixed(1) || '0'}</div>
<p className="text-xs text-muted-foreground">Target: 3 per project</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Unassigned</CardTitle>
<Layers className="h-4 w-4 text-amber-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-amber-700">{coverage.unassigned || 0}</div>
<p className="text-xs text-muted-foreground">Need more assignments</p>
</CardContent>
</Card>
</div>
) : null}
{/* Unassigned queue */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-base">Unassigned Projects</CardTitle>
<CardDescription>Projects with fewer than 3 jury assignments</CardDescription>
</div>
<Link href={`/admin/competitions/${competitionId}/assignments` as Route}>
<Button size="sm">
<ClipboardList className="h-4 w-4 mr-1.5" />
Full Assignment Dashboard
<ExternalLink className="h-3 w-3 ml-1.5" />
</Button>
</Link>
</div>
</CardHeader>
<CardContent>
{unassignedLoading ? (
<div className="space-y-2">
{[1, 2, 3].map((i) => <Skeleton key={i} className="h-14 w-full" />)}
</div>
) : unassigned && unassigned.length > 0 ? (
<div className="space-y-2 max-h-[400px] overflow-y-auto">
{unassigned.map((project: any) => (
<div
key={project.id}
className="flex justify-between items-center p-3 border rounded-md hover:bg-muted/30"
>
<div className="min-w-0">
<p className="text-sm font-medium truncate">{project.title}</p>
<p className="text-xs text-muted-foreground">
{project.competitionCategory || 'No category'}
{project.teamName && ` · ${project.teamName}`}
</p>
</div>
<Badge variant="outline" className={cn(
'text-xs shrink-0 ml-3',
(project.assignmentCount || 0) === 0
? 'bg-red-50 text-red-700 border-red-200'
: 'bg-amber-50 text-amber-700 border-amber-200'
)}>
{project.assignmentCount || 0} / 3
</Badge>
</div>
))}
</div>
) : (
<p className="text-sm text-muted-foreground text-center py-6">
All projects have sufficient assignments
</p>
)}
</CardContent>
</Card>
</div>
)
}

View File

@ -0,0 +1,399 @@
'use client'
import { useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Checkbox } from '@/components/ui/checkbox'
import { Skeleton } from '@/components/ui/skeleton'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import {
Loader2,
Plus,
Pencil,
Trash2,
FileText,
GripVertical,
FileCheck,
FileQuestion,
} from 'lucide-react'
type FileRequirementsEditorProps = {
roundId: string
windowOpenAt?: Date | string | null
windowCloseAt?: Date | string | null
}
type FormState = {
name: string
description: string
acceptedMimeTypes: string
maxSizeMB: string
isRequired: boolean
}
const emptyForm: FormState = {
name: '',
description: '',
acceptedMimeTypes: '',
maxSizeMB: '',
isRequired: true,
}
const COMMON_MIME_PRESETS: { label: string; value: string }[] = [
{ label: 'PDF only', value: 'application/pdf' },
{ label: 'Images', value: 'image/png, image/jpeg, image/webp' },
{ label: 'Video', value: 'video/mp4, video/quicktime, video/webm' },
{ label: 'Documents', value: 'application/pdf, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document' },
{ label: 'Spreadsheets', value: 'application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, text/csv' },
{ label: 'Presentations', value: 'application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation' },
{ label: 'Any file', value: '' },
]
export function FileRequirementsEditor({ roundId, windowOpenAt, windowCloseAt }: FileRequirementsEditorProps) {
const [dialogOpen, setDialogOpen] = useState(false)
const [editingId, setEditingId] = useState<string | null>(null)
const [form, setForm] = useState<FormState>(emptyForm)
const utils = trpc.useUtils()
const { data: requirements, isLoading } = trpc.file.listRequirements.useQuery({ roundId })
const createMutation = trpc.file.createRequirement.useMutation({
onSuccess: () => {
utils.file.listRequirements.invalidate({ roundId })
toast.success('Requirement added')
closeDialog()
},
onError: (err) => toast.error(err.message),
})
const updateMutation = trpc.file.updateRequirement.useMutation({
onSuccess: () => {
utils.file.listRequirements.invalidate({ roundId })
toast.success('Requirement updated')
closeDialog()
},
onError: (err) => toast.error(err.message),
})
const deleteMutation = trpc.file.deleteRequirement.useMutation({
onSuccess: () => {
utils.file.listRequirements.invalidate({ roundId })
toast.success('Requirement removed')
},
onError: (err) => toast.error(err.message),
})
const closeDialog = () => {
setDialogOpen(false)
setEditingId(null)
setForm(emptyForm)
}
const openCreateDialog = () => {
setForm(emptyForm)
setEditingId(null)
setDialogOpen(true)
}
const openEditDialog = (req: any) => {
setForm({
name: req.name,
description: req.description || '',
acceptedMimeTypes: (req.acceptedMimeTypes || []).join(', '),
maxSizeMB: req.maxSizeMB?.toString() || '',
isRequired: req.isRequired ?? true,
})
setEditingId(req.id)
setDialogOpen(true)
}
const handleSubmit = () => {
const mimeTypes = form.acceptedMimeTypes
.split(',')
.map((s) => s.trim())
.filter(Boolean)
const maxSize = form.maxSizeMB ? parseInt(form.maxSizeMB, 10) : undefined
if (editingId) {
updateMutation.mutate({
id: editingId,
name: form.name,
description: form.description || null,
acceptedMimeTypes: mimeTypes,
maxSizeMB: maxSize ?? null,
isRequired: form.isRequired,
})
} else {
createMutation.mutate({
roundId,
name: form.name,
description: form.description || undefined,
acceptedMimeTypes: mimeTypes,
maxSizeMB: maxSize,
isRequired: form.isRequired,
sortOrder: (requirements?.length ?? 0),
})
}
}
const isSaving = createMutation.isPending || updateMutation.isPending
if (isLoading) {
return (
<div className="space-y-3">
<Skeleton className="h-10 w-full" />
{[1, 2, 3].map((i) => <Skeleton key={i} className="h-20 w-full" />)}
</div>
)
}
return (
<div className="space-y-4">
{/* Submission period info */}
<Card>
<CardContent className="pt-4 pb-3">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">Submission Period</p>
<p className="text-xs text-muted-foreground mt-0.5">
Applicants can upload documents during the round&apos;s active window
</p>
</div>
<div className="text-right text-sm">
{windowOpenAt || windowCloseAt ? (
<>
<p className="font-medium">
{windowOpenAt ? new Date(windowOpenAt).toLocaleDateString() : 'No start'} &mdash;{' '}
{windowCloseAt ? new Date(windowCloseAt).toLocaleDateString() : 'No deadline'}
</p>
<p className="text-xs text-muted-foreground">
Set in the Config tab under round time windows
</p>
</>
) : (
<p className="text-muted-foreground">No dates configured &mdash; set in Config tab</p>
)}
</div>
</div>
</CardContent>
</Card>
{/* Requirements list */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-base">Required Documents</CardTitle>
<CardDescription>
Define what files applicants must submit for this round
</CardDescription>
</div>
<Button size="sm" onClick={openCreateDialog}>
<Plus className="h-4 w-4 mr-1.5" />
Add Requirement
</Button>
</div>
</CardHeader>
<CardContent>
{!requirements || requirements.length === 0 ? (
<div className="flex flex-col items-center justify-center py-10 text-center">
<div className="rounded-full bg-muted p-4 mb-4">
<FileText className="h-8 w-8 text-muted-foreground" />
</div>
<p className="text-sm font-medium">No Document Requirements</p>
<p className="text-xs text-muted-foreground mt-1 max-w-sm">
Add requirements to specify what documents applicants must upload during this round.
</p>
<Button size="sm" variant="outline" className="mt-4" onClick={openCreateDialog}>
<Plus className="h-4 w-4 mr-1.5" />
Add First Requirement
</Button>
</div>
) : (
<div className="space-y-2">
{requirements.map((req: any) => (
<div
key={req.id}
className="flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/30 transition-colors"
>
<div className="mt-0.5 text-muted-foreground">
{req.isRequired ? (
<FileCheck className="h-4 w-4 text-blue-500" />
) : (
<FileQuestion className="h-4 w-4 text-gray-400" />
)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="text-sm font-medium">{req.name}</p>
<Badge variant={req.isRequired ? 'default' : 'secondary'} className="text-[10px]">
{req.isRequired ? 'Required' : 'Optional'}
</Badge>
</div>
{req.description && (
<p className="text-xs text-muted-foreground mt-0.5">{req.description}</p>
)}
<div className="flex flex-wrap gap-2 mt-1.5">
{req.acceptedMimeTypes?.length > 0 ? (
<span className="text-[10px] text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
{req.acceptedMimeTypes.map((t: string) => {
if (t === 'application/pdf') return 'PDF'
if (t.startsWith('image/')) return t.replace('image/', '').toUpperCase()
if (t.startsWith('video/')) return t.replace('video/', '').toUpperCase()
return t.split('/').pop()?.toUpperCase() || t
}).join(', ')}
</span>
) : (
<span className="text-[10px] text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
Any file type
</span>
)}
{req.maxSizeMB && (
<span className="text-[10px] text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
Max {req.maxSizeMB} MB
</span>
)}
</div>
</div>
<div className="flex items-center gap-1 shrink-0">
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEditDialog(req)}>
<Pencil className="h-3.5 w-3.5" />
</Button>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="ghost" size="icon" className="h-7 w-7 text-destructive hover:text-destructive">
<Trash2 className="h-3.5 w-3.5" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete requirement?</AlertDialogTitle>
<AlertDialogDescription>
This will remove &quot;{req.name}&quot; from the round. Previously uploaded files will not be deleted.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => deleteMutation.mutate({ id: req.id })}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
{/* Create / Edit Dialog */}
<Dialog open={dialogOpen} onOpenChange={(open) => { if (!open) closeDialog() }}>
<DialogContent>
<DialogHeader>
<DialogTitle>{editingId ? 'Edit Requirement' : 'Add Document Requirement'}</DialogTitle>
<DialogDescription>
{editingId
? 'Update the document requirement details.'
: 'Define a new document that applicants must submit.'}
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">Name</label>
<Input
placeholder="e.g. Business Plan, Pitch Deck, Financial Projections"
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Description</label>
<Textarea
placeholder="Describe what this document should contain..."
rows={3}
value={form.description}
onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Accepted File Types</label>
<Input
placeholder="application/pdf, image/png (leave empty for any)"
value={form.acceptedMimeTypes}
onChange={(e) => setForm((f) => ({ ...f, acceptedMimeTypes: e.target.value }))}
/>
<div className="flex flex-wrap gap-1.5">
{COMMON_MIME_PRESETS.map((preset) => (
<button
key={preset.label}
type="button"
onClick={() => setForm((f) => ({ ...f, acceptedMimeTypes: preset.value }))}
className="text-[10px] px-2 py-1 rounded-full border hover:bg-muted transition-colors"
>
{preset.label}
</button>
))}
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Max File Size (MB)</label>
<Input
type="number"
placeholder="e.g. 50"
value={form.maxSizeMB}
onChange={(e) => setForm((f) => ({ ...f, maxSizeMB: e.target.value }))}
/>
</div>
<div className="flex items-center gap-2">
<Checkbox
id="isRequired"
checked={form.isRequired}
onCheckedChange={(checked) => setForm((f) => ({ ...f, isRequired: !!checked }))}
/>
<label htmlFor="isRequired" className="text-sm">
Required document (applicant must upload to proceed)
</label>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={closeDialog}>Cancel</Button>
<Button onClick={handleSubmit} disabled={isSaving || !form.name.trim()}>
{isSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
{editingId ? 'Update' : 'Add Requirement'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}

View File

@ -0,0 +1,841 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Checkbox } from '@/components/ui/checkbox'
import { Skeleton } from '@/components/ui/skeleton'
import { Textarea } from '@/components/ui/textarea'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import {
Play,
Loader2,
CheckCircle2,
XCircle,
AlertTriangle,
RefreshCw,
Eye,
ChevronLeft,
ChevronRight,
Shield,
Sparkles,
Ban,
Flag,
RotateCcw,
} from 'lucide-react'
type FilteringDashboardProps = {
competitionId: string
roundId: string
}
type OutcomeFilter = 'ALL' | 'PASSED' | 'FILTERED_OUT' | 'FLAGGED'
type AIScreeningData = {
meetsCriteria?: boolean
confidence?: number
reasoning?: string
qualityScore?: number
spamRisk?: boolean
}
export function FilteringDashboard({ competitionId, roundId }: FilteringDashboardProps) {
const [outcomeFilter, setOutcomeFilter] = useState<OutcomeFilter>('ALL')
const [page, setPage] = useState(1)
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [pollingJobId, setPollingJobId] = useState<string | null>(null)
const [overrideDialogOpen, setOverrideDialogOpen] = useState(false)
const [overrideTarget, setOverrideTarget] = useState<{ id: string; name: string } | null>(null)
const [overrideOutcome, setOverrideOutcome] = useState<'PASSED' | 'FILTERED_OUT' | 'FLAGGED'>('PASSED')
const [overrideReason, setOverrideReason] = useState('')
const [bulkOverrideDialogOpen, setBulkOverrideDialogOpen] = useState(false)
const [bulkOutcome, setBulkOutcome] = useState<'PASSED' | 'FILTERED_OUT' | 'FLAGGED'>('PASSED')
const [bulkReason, setBulkReason] = useState('')
const [detailResult, setDetailResult] = useState<any>(null)
const utils = trpc.useUtils()
// -- Queries --
const { data: stats, isLoading: statsLoading } = trpc.filtering.getResultStats.useQuery(
{ roundId },
)
const { data: latestJob, isLoading: jobLoading } = trpc.filtering.getLatestJob.useQuery(
{ roundId },
)
const { data: rules } = trpc.filtering.getRules.useQuery({ roundId })
const { data: resultsPage, isLoading: resultsLoading } = trpc.filtering.getResults.useQuery(
{
roundId,
outcome: outcomeFilter === 'ALL' ? undefined : outcomeFilter,
page,
perPage: 25,
},
)
const { data: jobStatus } = trpc.filtering.getJobStatus.useQuery(
{ jobId: pollingJobId! },
{
enabled: !!pollingJobId,
refetchInterval: 2000,
},
)
// Stop polling when job completes
useEffect(() => {
if (jobStatus && (jobStatus.status === 'COMPLETED' || jobStatus.status === 'FAILED')) {
setPollingJobId(null)
utils.filtering.getLatestJob.invalidate({ roundId })
utils.filtering.getResults.invalidate()
utils.filtering.getResultStats.invalidate({ roundId })
if (jobStatus.status === 'COMPLETED') {
toast.success(`Filtering complete: ${jobStatus.passedCount} passed, ${jobStatus.filteredCount} filtered, ${jobStatus.flaggedCount} flagged`)
} else {
toast.error(`Filtering failed: ${jobStatus.errorMessage || 'Unknown error'}`)
}
}
}, [jobStatus, roundId, utils])
// Auto-detect running job on mount
useEffect(() => {
if (latestJob && latestJob.status === 'RUNNING') {
setPollingJobId(latestJob.id)
}
}, [latestJob])
// -- Mutations --
const startJobMutation = trpc.filtering.startJob.useMutation({
onSuccess: (data) => {
setPollingJobId(data.jobId)
toast.success('Filtering job started')
},
onError: (err) => toast.error(err.message),
})
const overrideMutation = trpc.filtering.overrideResult.useMutation({
onSuccess: () => {
utils.filtering.getResults.invalidate()
utils.filtering.getResultStats.invalidate({ roundId })
setOverrideDialogOpen(false)
setOverrideTarget(null)
setOverrideReason('')
toast.success('Override applied')
},
onError: (err) => toast.error(err.message),
})
const bulkOverrideMutation = trpc.filtering.bulkOverride.useMutation({
onSuccess: (data) => {
utils.filtering.getResults.invalidate()
utils.filtering.getResultStats.invalidate({ roundId })
setBulkOverrideDialogOpen(false)
setSelectedIds(new Set())
setBulkReason('')
toast.success(`${data.updated} results overridden`)
},
onError: (err) => toast.error(err.message),
})
const finalizeMutation = trpc.filtering.finalizeResults.useMutation({
onSuccess: (data) => {
utils.filtering.getResults.invalidate()
utils.filtering.getResultStats.invalidate({ roundId })
toast.success(
`Finalized: ${data.passed} passed, ${data.filteredOut} filtered out` +
(data.advancedToStageName ? `. Next round: ${data.advancedToStageName}` : '')
)
if (data.categoryWarnings.length > 0) {
data.categoryWarnings.forEach((w) => toast.warning(w))
}
},
onError: (err) => toast.error(err.message),
})
// -- Handlers --
const handleStartJob = () => {
startJobMutation.mutate({ roundId })
}
const handleOverride = () => {
if (!overrideTarget) return
overrideMutation.mutate({
id: overrideTarget.id,
finalOutcome: overrideOutcome,
reason: overrideReason,
})
}
const handleBulkOverride = () => {
bulkOverrideMutation.mutate({
ids: Array.from(selectedIds),
finalOutcome: bulkOutcome,
reason: bulkReason,
})
}
const handleFinalize = () => {
finalizeMutation.mutate({ roundId })
}
const toggleSelect = (id: string) => {
setSelectedIds((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}
const toggleSelectAll = useCallback(() => {
if (!resultsPage) return
const allIds = resultsPage.results.map((r: any) => r.id)
const allSelected = allIds.every((id: string) => selectedIds.has(id))
if (allSelected) {
setSelectedIds((prev) => {
const next = new Set(prev)
allIds.forEach((id: string) => next.delete(id))
return next
})
} else {
setSelectedIds((prev) => {
const next = new Set(prev)
allIds.forEach((id: string) => next.add(id))
return next
})
}
}, [resultsPage, selectedIds])
const parseAIData = (json: unknown): AIScreeningData | null => {
if (!json || typeof json !== 'object') return null
return json as AIScreeningData
}
// Is there a running job?
const isRunning = !!pollingJobId || latestJob?.status === 'RUNNING'
const activeJob = jobStatus || (latestJob?.status === 'RUNNING' ? latestJob : null)
const hasResults = stats && stats.total > 0
const hasRules = rules && rules.length > 0
return (
<div className="space-y-6">
{/* Job Control */}
<Card>
<CardHeader>
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
<div>
<CardTitle className="text-base">AI Filtering</CardTitle>
<CardDescription>
Run AI screening against {hasRules ? rules.length : 0} active rule{rules?.length !== 1 ? 's' : ''}
</CardDescription>
</div>
<div className="flex items-center gap-2">
<Button
onClick={handleStartJob}
disabled={isRunning || startJobMutation.isPending || !hasRules}
size="sm"
>
{isRunning ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Play className="h-4 w-4 mr-2" />
)}
{isRunning ? 'Running...' : 'Run Filtering'}
</Button>
{hasResults && (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm" disabled={isRunning || finalizeMutation.isPending}>
<Shield className="h-4 w-4 mr-2" />
Finalize Results
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Finalize Filtering Results?</AlertDialogTitle>
<AlertDialogDescription>
This will mark PASSED projects as eligible and FILTERED_OUT projects as rejected.
{stats && (
<span className="block mt-2 font-medium">
{stats.passed} will pass, {stats.filteredOut} will be filtered out, {stats.flagged} flagged for review.
</span>
)}
This action can be reversed but requires manual intervention.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleFinalize}>
{finalizeMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Finalize
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
</div>
</div>
</CardHeader>
{/* Job Progress */}
{isRunning && activeJob && (
<CardContent className="pt-0">
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
Processing batch {activeJob.currentBatch} of {activeJob.totalBatches || '?'}
</span>
<span className="font-mono">
{activeJob.processedCount}/{activeJob.totalProjects}
</span>
</div>
<Progress
value={activeJob.totalProjects > 0
? (activeJob.processedCount / activeJob.totalProjects) * 100
: 0
}
/>
</div>
</CardContent>
)}
{/* Last job summary */}
{!isRunning && latestJob && latestJob.status === 'COMPLETED' && (
<CardContent className="pt-0">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<CheckCircle2 className="h-4 w-4 text-green-600" />
Last run completed: {latestJob.passedCount} passed, {latestJob.filteredCount} filtered, {latestJob.flaggedCount} flagged
<span className="text-xs">
({new Date(latestJob.completedAt!).toLocaleDateString()})
</span>
</div>
</CardContent>
)}
{!isRunning && latestJob && latestJob.status === 'FAILED' && (
<CardContent className="pt-0">
<div className="flex items-center gap-2 text-sm text-red-600">
<XCircle className="h-4 w-4" />
Last run failed: {latestJob.errorMessage || 'Unknown error'}
</div>
</CardContent>
)}
{!hasRules && (
<CardContent className="pt-0">
<p className="text-sm text-amber-600">
No active filtering rules configured. Add rules in the Configuration tab first.
</p>
</CardContent>
)}
</Card>
{/* Stats Cards */}
{statsLoading ? (
<div className="grid gap-4 grid-cols-2 lg:grid-cols-5">
{[1, 2, 3, 4, 5].map((i) => (
<Skeleton key={i} className="h-24" />
))}
</div>
) : stats && stats.total > 0 ? (
<div className="grid gap-4 grid-cols-2 lg:grid-cols-5">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Total</CardTitle>
<Sparkles className="h-4 w-4 text-blue-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats.total}</div>
<p className="text-xs text-muted-foreground">Projects screened</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Passed</CardTitle>
<CheckCircle2 className="h-4 w-4 text-green-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-green-700">{stats.passed}</div>
<p className="text-xs text-muted-foreground">
{stats.total > 0 ? `${((stats.passed / stats.total) * 100).toFixed(0)}%` : '0%'}
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Filtered Out</CardTitle>
<Ban className="h-4 w-4 text-red-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-red-700">{stats.filteredOut}</div>
<p className="text-xs text-muted-foreground">
{stats.total > 0 ? `${((stats.filteredOut / stats.total) * 100).toFixed(0)}%` : '0%'}
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Flagged</CardTitle>
<Flag className="h-4 w-4 text-amber-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-amber-700">{stats.flagged}</div>
<p className="text-xs text-muted-foreground">Need review</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Overridden</CardTitle>
<RotateCcw className="h-4 w-4 text-purple-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-purple-700">{stats.overridden}</div>
<p className="text-xs text-muted-foreground">Manual changes</p>
</CardContent>
</Card>
</div>
) : null}
{/* Results Table */}
{(hasResults || resultsLoading) && (
<Card>
<CardHeader>
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
<div>
<CardTitle className="text-base">Filtering Results</CardTitle>
<CardDescription>
Review AI screening outcomes and override decisions
</CardDescription>
</div>
<div className="flex items-center gap-2">
<Select
value={outcomeFilter}
onValueChange={(v) => {
setOutcomeFilter(v as OutcomeFilter)
setPage(1)
setSelectedIds(new Set())
}}
>
<SelectTrigger className="w-[160px]">
<SelectValue />
</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>
{selectedIds.size > 0 && (
<Button
variant="outline"
size="sm"
onClick={() => setBulkOverrideDialogOpen(true)}
>
Override {selectedIds.size} Selected
</Button>
)}
<Button
variant="ghost"
size="icon"
onClick={() => {
utils.filtering.getResults.invalidate()
utils.filtering.getResultStats.invalidate({ roundId })
}}
>
<RefreshCw className="h-4 w-4" />
</Button>
</div>
</div>
</CardHeader>
<CardContent>
{resultsLoading ? (
<div className="space-y-2">
{[1, 2, 3, 4, 5].map((i) => (
<Skeleton key={i} className="h-14 w-full" />
))}
</div>
) : resultsPage && resultsPage.results.length > 0 ? (
<div className="space-y-1">
{/* Table Header */}
<div className="grid grid-cols-[40px_1fr_120px_80px_80px_80px_100px] gap-2 px-3 py-2 text-xs font-medium text-muted-foreground border-b">
<div>
<Checkbox
checked={
resultsPage.results.length > 0 &&
resultsPage.results.every((r: any) => selectedIds.has(r.id))
}
onCheckedChange={toggleSelectAll}
/>
</div>
<div>Project</div>
<div>Category</div>
<div>Outcome</div>
<div>Confidence</div>
<div>Quality</div>
<div>Actions</div>
</div>
{/* Rows */}
{resultsPage.results.map((result: any) => {
const ai = parseAIData(result.aiScreeningJson)
const effectiveOutcome = result.finalOutcome || result.outcome
return (
<div
key={result.id}
className="grid grid-cols-[40px_1fr_120px_80px_80px_80px_100px] gap-2 px-3 py-2.5 items-center border-b last:border-b-0 hover:bg-muted/50 text-sm"
>
<div>
<Checkbox
checked={selectedIds.has(result.id)}
onCheckedChange={() => toggleSelect(result.id)}
/>
</div>
<div className="min-w-0">
<p className="font-medium truncate">{result.project?.title || 'Unknown'}</p>
<p className="text-xs text-muted-foreground truncate">
{result.project?.teamName}
{result.project?.country && ` · ${result.project.country}`}
</p>
</div>
<div>
<Badge variant="outline" className="text-xs">
{result.project?.competitionCategory || '—'}
</Badge>
</div>
<div>
<OutcomeBadge outcome={effectiveOutcome} overridden={!!result.finalOutcome && result.finalOutcome !== result.outcome} />
</div>
<div>
{ai?.confidence != null ? (
<ConfidenceIndicator value={ai.confidence} />
) : (
<span className="text-xs text-muted-foreground"></span>
)}
</div>
<div>
{ai?.qualityScore != null ? (
<span className={`text-sm font-mono font-medium ${
ai.qualityScore >= 7 ? 'text-green-700' :
ai.qualityScore >= 4 ? 'text-amber-700' :
'text-red-700'
}`}>
{ai.qualityScore}/10
</span>
) : (
<span className="text-xs text-muted-foreground"></span>
)}
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => setDetailResult(result)}
title="View AI feedback"
>
<Eye className="h-3.5 w-3.5" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => {
setOverrideTarget({ id: result.id, name: result.project?.title || 'Unknown' })
setOverrideOutcome(effectiveOutcome === 'PASSED' ? 'FILTERED_OUT' : 'PASSED')
setOverrideDialogOpen(true)
}}
title="Override decision"
>
<RotateCcw className="h-3.5 w-3.5" />
</Button>
</div>
</div>
)
})}
{/* Pagination */}
{resultsPage.totalPages > 1 && (
<div className="flex items-center justify-between pt-4">
<p className="text-sm text-muted-foreground">
Page {resultsPage.page} of {resultsPage.totalPages} ({resultsPage.total} total)
</p>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={page <= 1}
onClick={() => setPage((p) => p - 1)}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="sm"
disabled={page >= resultsPage.totalPages}
onClick={() => setPage((p) => p + 1)}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
</div>
) : (
<div className="flex flex-col items-center justify-center py-12 text-center">
<Sparkles className="h-8 w-8 text-muted-foreground mb-3" />
<p className="text-sm font-medium">No results yet</p>
<p className="text-xs text-muted-foreground mt-1">
Run the filtering job to screen projects
</p>
</div>
)}
</CardContent>
</Card>
)}
{/* AI Detail Dialog */}
<Dialog open={!!detailResult} onOpenChange={(open) => !open && setDetailResult(null)}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>{detailResult?.project?.title || 'Project'}</DialogTitle>
<DialogDescription>
AI screening feedback and reasoning
</DialogDescription>
</DialogHeader>
{detailResult && (() => {
const ai = parseAIData(detailResult.aiScreeningJson)
const effectiveOutcome = detailResult.finalOutcome || detailResult.outcome
return (
<div className="space-y-4">
<div className="flex items-center gap-3">
<OutcomeBadge outcome={effectiveOutcome} overridden={!!detailResult.finalOutcome && detailResult.finalOutcome !== detailResult.outcome} />
{detailResult.finalOutcome && detailResult.finalOutcome !== detailResult.outcome && (
<span className="text-xs text-muted-foreground">
Original: <OutcomeBadge outcome={detailResult.outcome} overridden={false} />
</span>
)}
</div>
{ai && (
<>
<div className="grid grid-cols-3 gap-3">
<div className="rounded-lg border p-3 text-center">
<p className="text-xs text-muted-foreground mb-1">Confidence</p>
<p className="text-lg font-bold">
{ai.confidence != null ? `${(ai.confidence * 100).toFixed(0)}%` : '—'}
</p>
</div>
<div className="rounded-lg border p-3 text-center">
<p className="text-xs text-muted-foreground mb-1">Quality</p>
<p className="text-lg font-bold">
{ai.qualityScore != null ? `${ai.qualityScore}/10` : '—'}
</p>
</div>
<div className="rounded-lg border p-3 text-center">
<p className="text-xs text-muted-foreground mb-1">Spam Risk</p>
<p className={`text-lg font-bold ${ai.spamRisk ? 'text-red-600' : 'text-green-600'}`}>
{ai.spamRisk ? 'Yes' : 'No'}
</p>
</div>
</div>
{ai.reasoning && (
<div>
<p className="text-sm font-medium mb-1">AI Reasoning</p>
<div className="rounded-lg bg-muted p-3 text-sm whitespace-pre-wrap">
{ai.reasoning}
</div>
</div>
)}
</>
)}
{detailResult.overrideReason && (
<div>
<p className="text-sm font-medium mb-1">Override Reason</p>
<div className="rounded-lg bg-amber-50 border border-amber-200 p-3 text-sm">
{detailResult.overrideReason}
{detailResult.overriddenByUser && (
<p className="text-xs text-muted-foreground mt-1">
By {detailResult.overriddenByUser.name || detailResult.overriddenByUser.email}
{detailResult.overriddenAt && ` on ${new Date(detailResult.overriddenAt).toLocaleDateString()}`}
</p>
)}
</div>
</div>
)}
{/* Rule-by-rule results */}
{detailResult.ruleResultsJson && Array.isArray(detailResult.ruleResultsJson) && (
<div>
<p className="text-sm font-medium mb-1">Rule Results</p>
<div className="space-y-1">
{(detailResult.ruleResultsJson as any[]).map((rule: any, i: number) => (
<div key={i} className="flex items-center justify-between text-sm px-2 py-1.5 rounded border">
<span>{rule.ruleName || `Rule ${i + 1}`}</span>
<Badge variant={rule.passed ? 'default' : 'destructive'} className="text-xs">
{rule.passed ? 'Pass' : 'Fail'}
</Badge>
</div>
))}
</div>
</div>
)}
</div>
)
})()}
</DialogContent>
</Dialog>
{/* Single Override Dialog */}
<Dialog open={overrideDialogOpen} onOpenChange={setOverrideDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Override Decision</DialogTitle>
<DialogDescription>
Change the outcome for: {overrideTarget?.name}
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<label className="text-sm font-medium mb-1.5 block">New Outcome</label>
<Select value={overrideOutcome} onValueChange={(v) => setOverrideOutcome(v as any)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="PASSED">Passed</SelectItem>
<SelectItem value="FILTERED_OUT">Filtered Out</SelectItem>
<SelectItem value="FLAGGED">Flagged</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<label className="text-sm font-medium mb-1.5 block">Reason</label>
<Textarea
placeholder="Explain why you're overriding this decision..."
value={overrideReason}
onChange={(e) => setOverrideReason(e.target.value)}
rows={3}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setOverrideDialogOpen(false)}>Cancel</Button>
<Button
onClick={handleOverride}
disabled={!overrideReason.trim() || overrideMutation.isPending}
>
{overrideMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Apply Override
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Bulk Override Dialog */}
<Dialog open={bulkOverrideDialogOpen} onOpenChange={setBulkOverrideDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Bulk Override</DialogTitle>
<DialogDescription>
Override {selectedIds.size} selected results
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<label className="text-sm font-medium mb-1.5 block">Set All To</label>
<Select value={bulkOutcome} onValueChange={(v) => setBulkOutcome(v as any)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="PASSED">Passed</SelectItem>
<SelectItem value="FILTERED_OUT">Filtered Out</SelectItem>
<SelectItem value="FLAGGED">Flagged</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<label className="text-sm font-medium mb-1.5 block">Reason</label>
<Textarea
placeholder="Explain why you're overriding these decisions..."
value={bulkReason}
onChange={(e) => setBulkReason(e.target.value)}
rows={3}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setBulkOverrideDialogOpen(false)}>Cancel</Button>
<Button
onClick={handleBulkOverride}
disabled={!bulkReason.trim() || bulkOverrideMutation.isPending}
>
{bulkOverrideMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Override {selectedIds.size} Results
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
// -- Sub-components --
function OutcomeBadge({ outcome, overridden }: { outcome: string; overridden: boolean }) {
const styles: Record<string, string> = {
PASSED: 'bg-green-100 text-green-800 border-green-200',
FILTERED_OUT: 'bg-red-100 text-red-800 border-red-200',
FLAGGED: 'bg-amber-100 text-amber-800 border-amber-200',
}
return (
<Badge variant="outline" className={`text-xs ${styles[outcome] || ''} ${overridden ? 'ring-1 ring-purple-400' : ''}`}>
{outcome === 'FILTERED_OUT' ? 'Filtered' : outcome === 'PASSED' ? 'Passed' : 'Flagged'}
{overridden && ' *'}
</Badge>
)
}
function ConfidenceIndicator({ value }: { value: number }) {
const pct = Math.round(value * 100)
const color = pct >= 80 ? 'text-green-700' : pct >= 50 ? 'text-amber-700' : 'text-red-700'
return (
<span className={`text-sm font-mono font-medium ${color}`}>
{pct}%
</span>
)
}

View File

@ -1,7 +1,72 @@
'use client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Layers } from 'lucide-react'
import { useState, useCallback } from 'react'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import { Skeleton } from '@/components/ui/skeleton'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
Loader2,
MoreHorizontal,
ArrowRight,
XCircle,
CheckCircle2,
Clock,
Play,
LogOut,
Layers,
Trash2,
Plus,
} from 'lucide-react'
import Link from 'next/link'
import type { Route } from 'next'
const PROJECT_STATES = ['PENDING', 'IN_PROGRESS', 'PASSED', 'REJECTED', 'COMPLETED', 'WITHDRAWN'] as const
type ProjectState = (typeof PROJECT_STATES)[number]
const stateConfig: Record<ProjectState, { label: string; color: string; icon: React.ElementType }> = {
PENDING: { label: 'Pending', color: 'bg-gray-100 text-gray-700 border-gray-200', icon: Clock },
IN_PROGRESS: { label: 'In Progress', color: 'bg-blue-100 text-blue-700 border-blue-200', icon: Play },
PASSED: { label: 'Passed', color: 'bg-green-100 text-green-700 border-green-200', icon: CheckCircle2 },
REJECTED: { label: 'Rejected', color: 'bg-red-100 text-red-700 border-red-200', icon: XCircle },
COMPLETED: { label: 'Completed', color: 'bg-emerald-100 text-emerald-700 border-emerald-200', icon: CheckCircle2 },
WITHDRAWN: { label: 'Withdrawn', color: 'bg-orange-100 text-orange-700 border-orange-200', icon: LogOut },
}
type ProjectStatesTableProps = {
competitionId: string
@ -9,25 +74,395 @@ type ProjectStatesTableProps = {
}
export function ProjectStatesTable({ competitionId, roundId }: ProjectStatesTableProps) {
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [stateFilter, setStateFilter] = useState<string>('ALL')
const [batchDialogOpen, setBatchDialogOpen] = useState(false)
const [batchNewState, setBatchNewState] = useState<ProjectState>('PASSED')
const [removeConfirmId, setRemoveConfirmId] = useState<string | null>(null)
const [batchRemoveOpen, setBatchRemoveOpen] = useState(false)
const utils = trpc.useUtils()
const { data: projectStates, isLoading } = trpc.roundEngine.getProjectStates.useQuery(
{ roundId },
)
const transitionMutation = trpc.roundEngine.transitionProject.useMutation({
onSuccess: () => {
utils.roundEngine.getProjectStates.invalidate({ roundId })
toast.success('Project state updated')
},
onError: (err) => toast.error(err.message),
})
const batchTransitionMutation = trpc.roundEngine.batchTransition.useMutation({
onSuccess: (data) => {
utils.roundEngine.getProjectStates.invalidate({ roundId })
setSelectedIds(new Set())
setBatchDialogOpen(false)
toast.success(`${data.succeeded.length} projects updated${data.failed.length > 0 ? `, ${data.failed.length} failed` : ''}`)
},
onError: (err) => toast.error(err.message),
})
const removeMutation = trpc.roundEngine.removeFromRound.useMutation({
onSuccess: (data) => {
utils.roundEngine.getProjectStates.invalidate({ roundId })
setRemoveConfirmId(null)
toast.success(`Removed from ${data.removedFromRounds} round(s)`)
},
onError: (err) => toast.error(err.message),
})
const batchRemoveMutation = trpc.roundEngine.batchRemoveFromRound.useMutation({
onSuccess: (data) => {
utils.roundEngine.getProjectStates.invalidate({ roundId })
setSelectedIds(new Set())
setBatchRemoveOpen(false)
toast.success(`${data.removedCount} project(s) removed from this round and later rounds`)
},
onError: (err) => toast.error(err.message),
})
const handleTransition = (projectId: string, newState: ProjectState) => {
transitionMutation.mutate({ projectId, roundId, newState })
}
const handleBatchTransition = () => {
batchTransitionMutation.mutate({
projectIds: Array.from(selectedIds),
roundId,
newState: batchNewState,
})
}
const toggleSelect = (id: string) => {
setSelectedIds((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}
const filtered = projectStates?.filter((ps: any) =>
stateFilter === 'ALL' ? true : ps.state === stateFilter
) ?? []
const toggleSelectAll = useCallback(() => {
const ids = filtered.map((ps: any) => ps.projectId)
const allSelected = ids.length > 0 && ids.every((id: string) => selectedIds.has(id))
if (allSelected) {
setSelectedIds((prev) => {
const next = new Set(prev)
ids.forEach((id: string) => next.delete(id))
return next
})
} else {
setSelectedIds((prev) => {
const next = new Set(prev)
ids.forEach((id: string) => next.add(id))
return next
})
}
}, [filtered, selectedIds])
// State counts
const counts = projectStates?.reduce((acc: Record<string, number>, ps: any) => {
acc[ps.state] = (acc[ps.state] || 0) + 1
return acc
}, {} as Record<string, number>) ?? {}
if (isLoading) {
return (
<div className="space-y-3">
<Skeleton className="h-10 w-full" />
{[1, 2, 3, 4, 5].map((i) => (
<Skeleton key={i} className="h-14 w-full" />
))}
</div>
)
}
if (!projectStates || projectStates.length === 0) {
return (
<Card>
<CardHeader>
<CardTitle className="text-base">Project States</CardTitle>
<p className="text-sm text-muted-foreground">
Projects participating in this round
</p>
</CardHeader>
<CardContent>
<div className="flex flex-col items-center justify-center py-12 text-center">
<CardContent className="py-12">
<div className="flex flex-col items-center justify-center text-center">
<div className="rounded-full bg-muted p-4 mb-4">
<Layers className="h-8 w-8 text-muted-foreground" />
</div>
<p className="text-sm font-medium">No Active Projects</p>
<p className="text-xs text-muted-foreground mt-1">
Project states will appear here when the round is active
<p className="text-sm font-medium">No Projects in This Round</p>
<p className="text-xs text-muted-foreground mt-1 max-w-sm">
Assign projects from the Project Pool to this round to get started.
</p>
<Link href={'/admin/projects/pool' as Route}>
<Button size="sm" className="mt-4">
<Plus className="h-4 w-4 mr-1.5" />
Go to Project Pool
</Button>
</Link>
</div>
</CardContent>
</Card>
)
}
return (
<div className="space-y-4">
{/* Top bar: filters + add button */}
<div className="flex items-center justify-between gap-4 flex-wrap">
<div className="flex flex-wrap gap-2">
<button
onClick={() => { setStateFilter('ALL'); setSelectedIds(new Set()) }}
className={`text-xs px-3 py-1.5 rounded-full border transition-colors ${
stateFilter === 'ALL'
? 'bg-foreground text-background border-foreground'
: 'bg-muted text-muted-foreground border-transparent hover:border-border'
}`}
>
All ({projectStates.length})
</button>
{PROJECT_STATES.map((state) => {
const count = counts[state] || 0
if (count === 0) return null
const cfg = stateConfig[state]
return (
<button
key={state}
onClick={() => { setStateFilter(state); setSelectedIds(new Set()) }}
className={`text-xs px-3 py-1.5 rounded-full border transition-colors ${
stateFilter === state
? cfg.color + ' border-current'
: 'bg-muted text-muted-foreground border-transparent hover:border-border'
}`}
>
{cfg.label} ({count})
</button>
)
})}
</div>
<Link href={'/admin/projects/pool' as Route}>
<Button size="sm" variant="outline">
<Plus className="h-4 w-4 mr-1.5" />
Add from Pool
</Button>
</Link>
</div>
{/* Bulk actions bar */}
{selectedIds.size > 0 && (
<div className="flex items-center gap-3 p-3 rounded-lg bg-muted/50 border">
<span className="text-sm font-medium">{selectedIds.size} selected</span>
<div className="flex items-center gap-2 ml-auto">
<Button
variant="outline"
size="sm"
onClick={() => setBatchDialogOpen(true)}
>
<ArrowRight className="h-3.5 w-3.5 mr-1.5" />
Change State
</Button>
<Button
variant="outline"
size="sm"
className="text-destructive border-destructive/30 hover:bg-destructive/10"
onClick={() => setBatchRemoveOpen(true)}
>
<Trash2 className="h-3.5 w-3.5 mr-1.5" />
Remove from Round
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setSelectedIds(new Set())}
>
Clear
</Button>
</div>
</div>
)}
{/* Table */}
<div className="border rounded-lg overflow-hidden">
{/* Header */}
<div className="grid grid-cols-[40px_1fr_140px_120px_100px_48px] gap-2 px-4 py-2.5 bg-muted/40 text-xs font-medium text-muted-foreground border-b">
<div>
<Checkbox
checked={filtered.length > 0 && filtered.every((ps: any) => selectedIds.has(ps.projectId))}
onCheckedChange={toggleSelectAll}
/>
</div>
<div>Project</div>
<div>Category</div>
<div>State</div>
<div>Entered</div>
<div />
</div>
{/* Rows */}
{filtered.map((ps: any) => {
const cfg = stateConfig[ps.state as ProjectState] || stateConfig.PENDING
const StateIcon = cfg.icon
return (
<div
key={ps.id}
className="grid grid-cols-[40px_1fr_140px_120px_100px_48px] gap-2 px-4 py-3 items-center border-b last:border-b-0 hover:bg-muted/30 text-sm"
>
<div>
<Checkbox
checked={selectedIds.has(ps.projectId)}
onCheckedChange={() => toggleSelect(ps.projectId)}
/>
</div>
<div className="min-w-0">
<p className="font-medium truncate">{ps.project?.title || 'Unknown'}</p>
<p className="text-xs text-muted-foreground truncate">{ps.project?.teamName}</p>
</div>
<div>
<Badge variant="outline" className="text-xs">
{ps.project?.competitionCategory || '—'}
</Badge>
</div>
<div>
<Badge variant="outline" className={`text-xs ${cfg.color}`}>
<StateIcon className="h-3 w-3 mr-1" />
{cfg.label}
</Badge>
</div>
<div className="text-xs text-muted-foreground">
{ps.enteredAt ? new Date(ps.enteredAt).toLocaleDateString() : '—'}
</div>
<div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-7 w-7">
<MoreHorizontal className="h-3.5 w-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{PROJECT_STATES.filter((s) => s !== ps.state).map((state) => {
const sCfg = stateConfig[state]
return (
<DropdownMenuItem
key={state}
onClick={() => handleTransition(ps.projectId, state)}
disabled={transitionMutation.isPending}
>
<sCfg.icon className="h-3.5 w-3.5 mr-2" />
Move to {sCfg.label}
</DropdownMenuItem>
)
})}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setRemoveConfirmId(ps.projectId)}
className="text-destructive focus:text-destructive"
>
<Trash2 className="h-3.5 w-3.5 mr-2" />
Remove from Round
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
)
})}
</div>
{/* Single Remove Confirmation */}
<AlertDialog open={!!removeConfirmId} onOpenChange={(open) => { if (!open) setRemoveConfirmId(null) }}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove project from this round?</AlertDialogTitle>
<AlertDialogDescription>
The project will be removed from this round and all subsequent rounds.
It will remain in any prior rounds it was already assigned to.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
if (removeConfirmId) {
removeMutation.mutate({ projectId: removeConfirmId, roundId })
}
}}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
disabled={removeMutation.isPending}
>
{removeMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Remove
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Batch Remove Confirmation */}
<AlertDialog open={batchRemoveOpen} onOpenChange={setBatchRemoveOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove {selectedIds.size} projects from this round?</AlertDialogTitle>
<AlertDialogDescription>
These projects will be removed from this round and all subsequent rounds in the competition.
They will remain in any prior rounds they were already assigned to.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
batchRemoveMutation.mutate({
projectIds: Array.from(selectedIds),
roundId,
})
}}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
disabled={batchRemoveMutation.isPending}
>
{batchRemoveMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Remove {selectedIds.size} Projects
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Batch Transition Dialog */}
<Dialog open={batchDialogOpen} onOpenChange={setBatchDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Change State for {selectedIds.size} Projects</DialogTitle>
<DialogDescription>
All selected projects will be moved to the new state.
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<label className="text-sm font-medium">New State</label>
<Select value={batchNewState} onValueChange={(v) => setBatchNewState(v as ProjectState)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{PROJECT_STATES.map((state) => (
<SelectItem key={state} value={state}>
{stateConfig[state].label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setBatchDialogOpen(false)}>Cancel</Button>
<Button
onClick={handleBatchTransition}
disabled={batchTransitionMutation.isPending}
>
{batchTransitionMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Update {selectedIds.size} Projects
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}

View File

@ -33,8 +33,7 @@ export const cohortRouter = router({
}
}
const cohort = await ctx.prisma.$transaction(async (tx) => {
const created = await tx.cohort.create({
const cohort = await ctx.prisma.cohort.create({
data: {
roundId: input.roundId,
name: input.name,
@ -44,12 +43,13 @@ export const cohortRouter = router({
},
})
// Audit outside transaction so failures don't roll back the create
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'CREATE',
entityType: 'Cohort',
entityId: created.id,
entityId: cohort.id,
detailsJson: {
roundId: input.roundId,
name: input.name,
@ -59,9 +59,6 @@ export const cohortRouter = router({
userAgent: ctx.userAgent,
})
return created
})
return cohort
}),
@ -157,8 +154,7 @@ export const cohortRouter = router({
? new Date(now.getTime() + input.durationMinutes * 60 * 1000)
: cohort.windowCloseAt
const updated = await ctx.prisma.$transaction(async (tx) => {
const result = await tx.cohort.update({
const updated = await ctx.prisma.cohort.update({
where: { id: input.cohortId },
data: {
isOpen: true,
@ -167,8 +163,9 @@ export const cohortRouter = router({
},
})
// Audit outside transaction so failures don't roll back the voting open
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'COHORT_VOTING_OPENED',
entityType: 'Cohort',
@ -182,9 +179,6 @@ export const cohortRouter = router({
userAgent: ctx.userAgent,
})
return result
})
return updated
}),
@ -207,8 +201,7 @@ export const cohortRouter = router({
const now = new Date()
const updated = await ctx.prisma.$transaction(async (tx) => {
const result = await tx.cohort.update({
const updated = await ctx.prisma.cohort.update({
where: { id: input.cohortId },
data: {
isOpen: false,
@ -216,8 +209,9 @@ export const cohortRouter = router({
},
})
// Audit outside transaction so failures don't roll back the voting close
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'COHORT_VOTING_CLOSED',
entityType: 'Cohort',
@ -230,9 +224,6 @@ export const cohortRouter = router({
userAgent: ctx.userAgent,
})
return result
})
return updated
}),

View File

@ -36,25 +36,21 @@ export const competitionRouter = router({
where: { id: input.programId },
})
const competition = await ctx.prisma.$transaction(async (tx) => {
const created = await tx.competition.create({
const competition = await ctx.prisma.competition.create({
data: input,
})
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'CREATE',
entityType: 'Competition',
entityId: created.id,
entityId: competition.id,
detailsJson: { name: input.name, programId: input.programId },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return created
})
return competition
}),
@ -178,16 +174,15 @@ export const competitionRouter = router({
}
}
const competition = await ctx.prisma.$transaction(async (tx) => {
const previous = await tx.competition.findUniqueOrThrow({ where: { id } })
const previous = await ctx.prisma.competition.findUniqueOrThrow({ where: { id } })
const updated = await tx.competition.update({
const competition = await ctx.prisma.competition.update({
where: { id },
data,
})
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'UPDATE',
entityType: 'Competition',
@ -204,9 +199,6 @@ export const competitionRouter = router({
userAgent: ctx.userAgent,
})
return updated
})
return competition
}),
@ -216,14 +208,13 @@ export const competitionRouter = router({
delete: adminProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
const competition = await ctx.prisma.$transaction(async (tx) => {
const updated = await tx.competition.update({
const competition = await ctx.prisma.competition.update({
where: { id: input.id },
data: { status: 'ARCHIVED' },
})
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DELETE',
entityType: 'Competition',
@ -233,9 +224,6 @@ export const competitionRouter = router({
userAgent: ctx.userAgent,
})
return updated
})
return competition
}),

View File

@ -97,9 +97,11 @@ export const decisionRouter = router({
snapshotJson: previousValue as Prisma.InputJsonValue,
},
})
})
// Audit outside transaction so failures don't roll back the override
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DECISION_OVERRIDE',
entityType: input.entityType,
@ -113,7 +115,6 @@ export const decisionRouter = router({
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
})
break
}
@ -161,9 +162,11 @@ export const decisionRouter = router({
} as Prisma.InputJsonValue,
},
})
})
// Audit outside transaction so failures don't roll back the override
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DECISION_OVERRIDE',
entityType: input.entityType,
@ -176,7 +179,6 @@ export const decisionRouter = router({
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
})
break
}
@ -229,9 +231,11 @@ export const decisionRouter = router({
} as Prisma.InputJsonValue,
},
})
})
// Audit outside transaction so failures don't roll back the override
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DECISION_OVERRIDE',
entityType: input.entityType,
@ -244,7 +248,6 @@ export const decisionRouter = router({
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
})
break
}
}

View File

@ -517,26 +517,27 @@ export const fileRouter = router({
data: { replacedById: newFile.id },
})
return newFile
})
// Audit outside transaction so failures don't roll back the file replacement
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'REPLACE_FILE',
entityType: 'ProjectFile',
entityId: newFile.id,
entityId: result.id,
detailsJson: {
projectId: input.projectId,
oldFileId: input.oldFileId,
oldVersion: oldFile.version,
newVersion: newFile.version,
newVersion: result.version,
fileName: input.fileName,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return newFile
})
return result
}),

View File

@ -36,28 +36,25 @@ export const juryGroupRouter = router({
const { defaultCategoryQuotas, ...rest } = input
const juryGroup = await ctx.prisma.$transaction(async (tx) => {
const created = await tx.juryGroup.create({
const juryGroup = await ctx.prisma.juryGroup.create({
data: {
...rest,
defaultCategoryQuotas: defaultCategoryQuotas ?? undefined,
},
})
// Audit outside transaction so failures don't roll back the create
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'CREATE',
entityType: 'JuryGroup',
entityId: created.id,
entityId: juryGroup.id,
detailsJson: { name: input.name, competitionId: input.competitionId },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return created
})
return juryGroup
}),
@ -187,8 +184,7 @@ export const juryGroupRouter = router({
})
}
const member = await ctx.prisma.$transaction(async (tx) => {
const created = await tx.juryGroupMember.create({
const member = await ctx.prisma.juryGroupMember.create({
data: {
juryGroupId: input.juryGroupId,
userId: input.userId,
@ -204,12 +200,13 @@ export const juryGroupRouter = router({
},
})
// Audit outside transaction so failures don't roll back the member add
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'CREATE',
entityType: 'JuryGroupMember',
entityId: created.id,
entityId: member.id,
detailsJson: {
juryGroupId: input.juryGroupId,
addedUserId: input.userId,
@ -219,9 +216,6 @@ export const juryGroupRouter = router({
userAgent: ctx.userAgent,
})
return created
})
return member
}),
@ -231,15 +225,15 @@ export const juryGroupRouter = router({
removeMember: adminProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
const member = await ctx.prisma.$transaction(async (tx) => {
const existing = await tx.juryGroupMember.findUniqueOrThrow({
const existing = await ctx.prisma.juryGroupMember.findUniqueOrThrow({
where: { id: input.id },
})
await tx.juryGroupMember.delete({ where: { id: input.id } })
await ctx.prisma.juryGroupMember.delete({ where: { id: input.id } })
// Audit outside transaction so failures don't roll back the member removal
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DELETE',
entityType: 'JuryGroupMember',
@ -253,9 +247,6 @@ export const juryGroupRouter = router({
})
return existing
})
return member
}),
/**

View File

@ -72,14 +72,18 @@ export const liveRouter = router({
},
})
return created
})
// Audit outside transaction so failures don't roll back the session start
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'LIVE_SESSION_STARTED',
entityType: 'Round',
entityId: input.roundId,
detailsJson: {
sessionId: created.sessionId,
sessionId: cursor.sessionId,
projectCount: input.projectOrder.length,
firstProjectId: input.projectOrder[0],
},
@ -87,9 +91,6 @@ export const liveRouter = router({
userAgent: ctx.userAgent,
})
return created
})
return cursor
}),
@ -123,8 +124,7 @@ export const liveRouter = router({
})
}
const updated = await ctx.prisma.$transaction(async (tx) => {
const result = await tx.liveProgressCursor.update({
const updated = await ctx.prisma.liveProgressCursor.update({
where: { id: cursor.id },
data: {
activeProjectId: input.projectId,
@ -132,8 +132,9 @@ export const liveRouter = router({
},
})
// Audit outside transaction so failures don't roll back the project set
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'LIVE_ACTIVE_PROJECT_SET',
entityType: 'LiveProgressCursor',
@ -146,9 +147,6 @@ export const liveRouter = router({
userAgent: ctx.userAgent,
})
return result
})
return updated
}),
@ -182,8 +180,7 @@ export const liveRouter = router({
const targetProjectId = projectOrder[input.index]
const updated = await ctx.prisma.$transaction(async (tx) => {
const result = await tx.liveProgressCursor.update({
const updated = await ctx.prisma.liveProgressCursor.update({
where: { id: cursor.id },
data: {
activeProjectId: targetProjectId,
@ -191,8 +188,9 @@ export const liveRouter = router({
},
})
// Audit outside transaction so failures don't roll back the jump
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'LIVE_JUMP',
entityType: 'LiveProgressCursor',
@ -206,9 +204,6 @@ export const liveRouter = router({
userAgent: ctx.userAgent,
})
return result
})
return updated
}),
@ -255,8 +250,12 @@ export const liveRouter = router({
},
})
return updatedCursor
})
// Audit outside transaction so failures don't roll back the reorder
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'LIVE_REORDER',
entityType: 'LiveProgressCursor',
@ -268,9 +267,6 @@ export const liveRouter = router({
userAgent: ctx.userAgent,
})
return updatedCursor
})
return updated
}),
@ -291,14 +287,14 @@ export const liveRouter = router({
})
}
const updated = await ctx.prisma.$transaction(async (tx) => {
const result = await tx.liveProgressCursor.update({
const updated = await ctx.prisma.liveProgressCursor.update({
where: { id: cursor.id },
data: { isPaused: true },
})
// Audit outside transaction so failures don't roll back the pause
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'LIVE_PAUSED',
entityType: 'LiveProgressCursor',
@ -308,9 +304,6 @@ export const liveRouter = router({
userAgent: ctx.userAgent,
})
return result
})
return updated
}),
@ -331,14 +324,14 @@ export const liveRouter = router({
})
}
const updated = await ctx.prisma.$transaction(async (tx) => {
const result = await tx.liveProgressCursor.update({
const updated = await ctx.prisma.liveProgressCursor.update({
where: { id: cursor.id },
data: { isPaused: false },
})
// Audit outside transaction so failures don't roll back the resume
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'LIVE_RESUMED',
entityType: 'LiveProgressCursor',
@ -348,9 +341,6 @@ export const liveRouter = router({
userAgent: ctx.userAgent,
})
return result
})
return updated
}),

View File

@ -128,9 +128,8 @@ export const mentorRouter = router({
where: { id: input.mentorId },
})
// Create assignment + audit log in transaction
const assignment = await ctx.prisma.$transaction(async (tx) => {
const created = await tx.mentorAssignment.create({
// Create assignment
const assignment = await ctx.prisma.mentorAssignment.create({
data: {
projectId: input.projectId,
mentorId: input.mentorId,
@ -158,26 +157,24 @@ export const mentorRouter = router({
},
})
// Audit outside transaction so failures don't roll back the assignment
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'MENTOR_ASSIGN',
entityType: 'MentorAssignment',
entityId: created.id,
entityId: assignment.id,
detailsJson: {
projectId: input.projectId,
projectTitle: created.project.title,
projectTitle: assignment.project.title,
mentorId: input.mentorId,
mentorName: created.mentor.name,
mentorName: assignment.mentor.name,
method: input.method,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return created
})
// Get team lead info for mentor notification
const teamLead = await ctx.prisma.teamMember.findFirst({
where: { projectId: input.projectId, role: 'LEAD' },
@ -382,10 +379,14 @@ export const mentorRouter = router({
})
}
// Delete assignment + audit log in transaction
await ctx.prisma.$transaction(async (tx) => {
// Delete assignment
await ctx.prisma.mentorAssignment.delete({
where: { projectId: input.projectId },
})
// Audit outside transaction so failures don't roll back the unassignment
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'MENTOR_UNASSIGN',
entityType: 'MentorAssignment',
@ -400,11 +401,6 @@ export const mentorRouter = router({
userAgent: ctx.userAgent,
})
await tx.mentorAssignment.delete({
where: { projectId: input.projectId },
})
})
return { success: true }
}),

View File

@ -174,9 +174,12 @@ export const projectPoolRouter = router({
})),
})
// Create audit log
return updatedProjects
})
// Audit outside transaction so failures don't roll back the assignment
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user?.id,
action: 'BULK_ASSIGN_TO_ROUND',
entityType: 'Project',
@ -189,9 +192,6 @@ export const projectPoolRouter = router({
userAgent: ctx.userAgent,
})
return updatedProjects
})
return {
success: true,
assignedCount: result.count,
@ -258,8 +258,12 @@ export const projectPoolRouter = router({
})),
})
return updated
})
// Audit outside transaction so failures don't roll back the assignment
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user?.id,
action: 'BULK_ASSIGN_ALL_TO_ROUND',
entityType: 'Project',
@ -273,9 +277,6 @@ export const projectPoolRouter = router({
userAgent: ctx.userAgent,
})
return updated
})
return { success: true, assignedCount: result.count, roundId }
}),
})

View File

@ -590,12 +590,16 @@ export const projectRouter = router({
}
}
return { project: created, membersToInvite: inviteList }
})
// Audit outside transaction so failures don't roll back the project creation
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'CREATE',
entityType: 'Project',
entityId: created.id,
entityId: project.id,
detailsJson: {
title: input.title,
programId: resolvedProgramId,
@ -605,9 +609,6 @@ export const projectRouter = router({
userAgent: ctx.userAgent,
})
return { project: created, membersToInvite: inviteList }
})
// Send invite emails outside the transaction (never fail project creation)
if (membersToInvite.length > 0) {
const baseUrl = process.env.NEXTAUTH_URL || 'https://monaco-opc.com'
@ -782,14 +783,18 @@ export const projectRouter = router({
delete: adminProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
const project = await ctx.prisma.$transaction(async (tx) => {
const target = await tx.project.findUniqueOrThrow({
const target = await ctx.prisma.project.findUniqueOrThrow({
where: { id: input.id },
select: { id: true, title: true },
})
const project = await ctx.prisma.project.delete({
where: { id: input.id },
})
// Audit outside transaction so failures don't roll back the delete
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DELETE',
entityType: 'Project',
@ -799,11 +804,6 @@ export const projectRouter = router({
userAgent: ctx.userAgent,
})
return tx.project.delete({
where: { id: input.id },
})
})
return project
}),
@ -829,9 +829,13 @@ export const projectRouter = router({
})
}
const result = await ctx.prisma.$transaction(async (tx) => {
const result = await ctx.prisma.project.deleteMany({
where: { id: { in: projects.map((p) => p.id) } },
})
// Audit outside transaction so failures don't roll back the bulk delete
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'BULK_DELETE',
entityType: 'Project',
@ -844,11 +848,6 @@ export const projectRouter = router({
userAgent: ctx.userAgent,
})
return tx.project.deleteMany({
where: { id: { in: projects.map((p) => p.id) } },
})
})
return { deleted: result.count }
}),
@ -996,19 +995,20 @@ export const projectRouter = router({
})
}
return result
})
// Audit outside transaction so failures don't roll back the bulk update
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'BULK_UPDATE_STATUS',
entityType: 'Project',
detailsJson: { ids: matchingIds, status: input.status, count: result.count },
detailsJson: { ids: matchingIds, status: input.status, count: updated.count },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return result
})
// Notify project teams based on status
if (projects.length > 0) {
const notificationConfig: Record<

View File

@ -54,8 +54,7 @@ export const roundRouter = router({
? validateRoundConfig(input.roundType, input.configJson)
: defaultRoundConfig(input.roundType)
const round = await ctx.prisma.$transaction(async (tx) => {
const created = await tx.round.create({
const round = await ctx.prisma.round.create({
data: {
competitionId: input.competitionId,
name: input.name,
@ -72,11 +71,11 @@ export const roundRouter = router({
})
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'CREATE',
entityType: 'Round',
entityId: created.id,
entityId: round.id,
detailsJson: {
name: input.name,
roundType: input.roundType,
@ -86,9 +85,6 @@ export const roundRouter = router({
userAgent: ctx.userAgent,
})
return created
})
return round
}),
@ -145,8 +141,7 @@ export const roundRouter = router({
.mutation(async ({ ctx, input }) => {
const { id, configJson, ...data } = input
const round = await ctx.prisma.$transaction(async (tx) => {
const existing = await tx.round.findUniqueOrThrow({ where: { id } })
const existing = await ctx.prisma.round.findUniqueOrThrow({ where: { id } })
// If configJson provided, validate it against the round type
let validatedConfig: Prisma.InputJsonValue | undefined
@ -155,7 +150,7 @@ export const roundRouter = router({
validatedConfig = parsed as unknown as Prisma.InputJsonValue
}
const updated = await tx.round.update({
const round = await ctx.prisma.round.update({
where: { id },
data: {
...data,
@ -164,7 +159,7 @@ export const roundRouter = router({
})
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'UPDATE',
entityType: 'Round',
@ -180,9 +175,6 @@ export const roundRouter = router({
userAgent: ctx.userAgent,
})
return updated
})
return round
}),
@ -213,13 +205,12 @@ export const roundRouter = router({
delete: adminProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
const round = await ctx.prisma.$transaction(async (tx) => {
const existing = await tx.round.findUniqueOrThrow({ where: { id: input.id } })
const existing = await ctx.prisma.round.findUniqueOrThrow({ where: { id: input.id } })
await tx.round.delete({ where: { id: input.id } })
await ctx.prisma.round.delete({ where: { id: input.id } })
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DELETE',
entityType: 'Round',
@ -234,9 +225,6 @@ export const roundRouter = router({
})
return existing
})
return round
}),
// =========================================================================
@ -261,8 +249,7 @@ export const roundRouter = router({
})
)
.mutation(async ({ ctx, input }) => {
const window = await ctx.prisma.$transaction(async (tx) => {
const created = await tx.submissionWindow.create({
const window = await ctx.prisma.submissionWindow.create({
data: {
competitionId: input.competitionId,
name: input.name,
@ -277,19 +264,16 @@ export const roundRouter = router({
})
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'CREATE',
entityType: 'SubmissionWindow',
entityId: created.id,
entityId: window.id,
detailsJson: { name: input.name, competitionId: input.competitionId },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return created
})
return window
}),
@ -313,13 +297,12 @@ export const roundRouter = router({
)
.mutation(async ({ ctx, input }) => {
const { id, ...data } = input
const window = await ctx.prisma.$transaction(async (tx) => {
const updated = await tx.submissionWindow.update({
const window = await ctx.prisma.submissionWindow.update({
where: { id },
data,
})
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'UPDATE',
entityType: 'SubmissionWindow',
@ -328,8 +311,6 @@ export const roundRouter = router({
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return updated
})
return window
}),
@ -350,10 +331,9 @@ export const roundRouter = router({
message: `Cannot delete window "${window.name}" — it has ${window._count.projectFiles} uploaded files. Remove files first.`,
})
}
await ctx.prisma.$transaction(async (tx) => {
await tx.submissionWindow.delete({ where: { id: input.id } })
await ctx.prisma.submissionWindow.delete({ where: { id: input.id } })
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DELETE',
entityType: 'SubmissionWindow',
@ -362,7 +342,6 @@ export const roundRouter = router({
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
})
return { success: true }
}),

View File

@ -140,4 +140,109 @@ export const roundEngineRouter = router({
.query(async ({ ctx, input }) => {
return getProjectRoundState(input.projectId, input.roundId, ctx.prisma)
}),
/**
* Remove a project from a round (and all subsequent rounds in that competition).
* The project remains in all prior rounds.
*/
removeFromRound: adminProcedure
.input(
z.object({
projectId: z.string(),
roundId: z.string(),
})
)
.mutation(async ({ ctx, input }) => {
// Get the round to know its competition and sort order
const round = await ctx.prisma.round.findUniqueOrThrow({
where: { id: input.roundId },
select: { id: true, competitionId: true, sortOrder: true },
})
// Find all rounds at this sort order or later in the same competition
const roundsToRemoveFrom = await ctx.prisma.round.findMany({
where: {
competitionId: round.competitionId,
sortOrder: { gte: round.sortOrder },
},
select: { id: true },
})
const roundIds = roundsToRemoveFrom.map((r) => r.id)
// Delete ProjectRoundState entries for this project in all affected rounds
const deleted = await ctx.prisma.projectRoundState.deleteMany({
where: {
projectId: input.projectId,
roundId: { in: roundIds },
},
})
// Check if the project is still in any round at all
const remainingStates = await ctx.prisma.projectRoundState.count({
where: { projectId: input.projectId },
})
// If no longer in any round, reset project status back to SUBMITTED
if (remainingStates === 0) {
await ctx.prisma.project.update({
where: { id: input.projectId },
data: { status: 'SUBMITTED' },
})
}
return { success: true, removedFromRounds: deleted.count }
}),
/**
* Batch remove projects from a round (and all subsequent rounds).
*/
batchRemoveFromRound: adminProcedure
.input(
z.object({
projectIds: z.array(z.string()).min(1),
roundId: z.string(),
})
)
.mutation(async ({ ctx, input }) => {
const round = await ctx.prisma.round.findUniqueOrThrow({
where: { id: input.roundId },
select: { id: true, competitionId: true, sortOrder: true },
})
const roundsToRemoveFrom = await ctx.prisma.round.findMany({
where: {
competitionId: round.competitionId,
sortOrder: { gte: round.sortOrder },
},
select: { id: true },
})
const roundIds = roundsToRemoveFrom.map((r) => r.id)
const deleted = await ctx.prisma.projectRoundState.deleteMany({
where: {
projectId: { in: input.projectIds },
roundId: { in: roundIds },
},
})
// For projects with no remaining round states, reset to SUBMITTED
const projectsStillInRounds = await ctx.prisma.projectRoundState.findMany({
where: { projectId: { in: input.projectIds } },
select: { projectId: true },
distinct: ['projectId'],
})
const stillInRoundIds = new Set(projectsStillInRounds.map((p) => p.projectId))
const orphanedIds = input.projectIds.filter((id) => !stillInRoundIds.has(id))
if (orphanedIds.length > 0) {
await ctx.prisma.project.updateMany({
where: { id: { in: orphanedIds } },
data: { status: 'SUBMITTED' },
})
}
return { success: true, removedCount: deleted.count }
}),
})

View File

@ -106,8 +106,7 @@ export const specialAwardRouter = router({
_max: { sortOrder: true },
})
const award = await ctx.prisma.$transaction(async (tx) => {
const created = await tx.specialAward.create({
const award = await ctx.prisma.specialAward.create({
data: {
programId: input.programId,
name: input.name,
@ -125,20 +124,18 @@ export const specialAwardRouter = router({
},
})
// Audit outside transaction so failures don't roll back the create
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'CREATE',
entityType: 'SpecialAward',
entityId: created.id,
entityId: award.id,
detailsJson: { name: input.name, scoringMode: input.scoringMode },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return created
})
return award
}),
@ -190,9 +187,11 @@ export const specialAwardRouter = router({
delete: adminProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
await ctx.prisma.$transaction(async (tx) => {
await ctx.prisma.specialAward.delete({ where: { id: input.id } })
// Audit outside transaction so failures don't break the delete
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DELETE',
entityType: 'SpecialAward',
@ -200,9 +199,6 @@ export const specialAwardRouter = router({
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
await tx.specialAward.delete({ where: { id: input.id } })
})
}),
/**
@ -245,14 +241,14 @@ export const specialAwardRouter = router({
}
}
const award = await ctx.prisma.$transaction(async (tx) => {
const updated = await tx.specialAward.update({
const award = await ctx.prisma.specialAward.update({
where: { id: input.id },
data: updateData,
})
// Audit outside transaction so failures don't break the status update
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'UPDATE_STATUS',
entityType: 'SpecialAward',
@ -270,9 +266,6 @@ export const specialAwardRouter = router({
userAgent: ctx.userAgent,
})
return updated
})
return award
}),
@ -743,8 +736,7 @@ export const specialAwardRouter = router({
select: { winnerProjectId: true },
})
const award = await ctx.prisma.$transaction(async (tx) => {
const updated = await tx.specialAward.update({
const award = await ctx.prisma.specialAward.update({
where: { id: input.awardId },
data: {
winnerProjectId: input.projectId,
@ -753,8 +745,9 @@ export const specialAwardRouter = router({
},
})
// Audit outside transaction so failures don't break the winner update
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'UPDATE',
entityType: 'SpecialAward',
@ -769,9 +762,6 @@ export const specialAwardRouter = router({
userAgent: ctx.userAgent,
})
return updated
})
return award
}),
})

View File

@ -194,10 +194,14 @@ export const userRouter = router({
})
}
// Wrap audit + deletion in a transaction
await ctx.prisma.$transaction(async (tx) => {
// Delete user
await ctx.prisma.user.delete({
where: { id: ctx.user.id },
})
// Audit outside transaction so failures don't roll back the deletion
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DELETE_OWN_ACCOUNT',
entityType: 'User',
@ -207,11 +211,6 @@ export const userRouter = router({
userAgent: ctx.userAgent,
})
await tx.user.delete({
where: { id: ctx.user.id },
})
})
return { success: true }
}),
@ -384,28 +383,25 @@ export const userRouter = router({
})
}
const user = await ctx.prisma.$transaction(async (tx) => {
const created = await tx.user.create({
const user = await ctx.prisma.user.create({
data: {
...input,
status: 'INVITED',
},
})
// Audit outside transaction so failures don't roll back the user creation
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'CREATE',
entityType: 'User',
entityId: created.id,
entityId: user.id,
detailsJson: { email: input.email, role: input.role },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return created
})
return user
}),
@ -486,14 +482,14 @@ export const userRouter = router({
...(normalizedEmail !== undefined && { email: normalizedEmail }),
}
const user = await ctx.prisma.$transaction(async (tx) => {
const updated = await tx.user.update({
const user = await ctx.prisma.user.update({
where: { id },
data: updateData,
})
// Audit outside transaction so failures don't roll back the update
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'UPDATE',
entityType: 'User',
@ -506,7 +502,7 @@ export const userRouter = router({
// Track role change specifically
if (data.role && data.role !== targetUser.role) {
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'ROLE_CHANGED',
entityType: 'User',
@ -517,9 +513,6 @@ export const userRouter = router({
})
}
return updated
})
return user
}),
@ -537,15 +530,19 @@ export const userRouter = router({
})
}
const user = await ctx.prisma.$transaction(async (tx) => {
// Fetch user data before deletion for the audit log
const target = await tx.user.findUniqueOrThrow({
const target = await ctx.prisma.user.findUniqueOrThrow({
where: { id: input.id },
select: { email: true },
})
const user = await ctx.prisma.user.delete({
where: { id: input.id },
})
// Audit outside transaction so failures don't roll back the deletion
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DELETE',
entityType: 'User',
@ -555,11 +552,6 @@ export const userRouter = router({
userAgent: ctx.userAgent,
})
return tx.user.delete({
where: { id: input.id },
})
})
return user
}),
@ -1147,8 +1139,12 @@ export const userRouter = router({
}
}
return updated
})
// Audit outside transaction so failures don't roll back the onboarding
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'COMPLETE_ONBOARDING',
entityType: 'User',
@ -1158,9 +1154,6 @@ export const userRouter = router({
userAgent: ctx.userAgent,
})
return updated
})
return user
}),
@ -1265,9 +1258,8 @@ export const userRouter = router({
// Hash the password
const passwordHash = await hashPassword(input.password)
// Update user with new password + audit in transaction
const user = await ctx.prisma.$transaction(async (tx) => {
const updated = await tx.user.update({
// Update user with new password
const user = await ctx.prisma.user.update({
where: { id: ctx.user.id },
data: {
passwordHash,
@ -1276,8 +1268,9 @@ export const userRouter = router({
},
})
// Audit outside transaction so failures don't roll back the password set
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'PASSWORD_SET',
entityType: 'User',
@ -1287,9 +1280,6 @@ export const userRouter = router({
userAgent: ctx.userAgent,
})
return updated
})
return { success: true, email: user.email }
}),
@ -1348,9 +1338,8 @@ export const userRouter = router({
// Hash the new password
const passwordHash = await hashPassword(input.newPassword)
// Update user with new password + audit in transaction
await ctx.prisma.$transaction(async (tx) => {
await tx.user.update({
// Update user with new password
await ctx.prisma.user.update({
where: { id: ctx.user.id },
data: {
passwordHash,
@ -1358,8 +1347,9 @@ export const userRouter = router({
},
})
// Audit outside transaction so failures don't roll back the password change
await logAudit({
prisma: tx,
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'PASSWORD_CHANGED',
entityType: 'User',
@ -1368,7 +1358,6 @@ export const userRouter = router({
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
})
return { success: true }
}),