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>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="text-sm font-medium truncate">{round.name}</p> <p className="text-sm font-medium truncate">{round.name}</p>
<p className="text-xs text-muted-foreground font-mono">{round.slug}</p>
</div> </div>
<Badge <Badge
variant="secondary" variant="secondary"

View File

@ -1,44 +1,125 @@
'use client' 'use client'
import { useState } from 'react' import { useState } from 'react'
import { useParams } from 'next/navigation' import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link' import Link from 'next/link'
import type { Route } from 'next' import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client' import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner' import { toast } from 'sonner'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button' 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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Skeleton } from '@/components/ui/skeleton' import { Skeleton } from '@/components/ui/skeleton'
import { Badge } from '@/components/ui/badge' 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 { RoundConfigForm } from '@/components/admin/competition/round-config-form'
import { ProjectStatesTable } from '@/components/admin/round/project-states-table' 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> = { // -- Status config --
INTAKE: 'bg-gray-100 text-gray-700', const roundStatusConfig = {
FILTERING: 'bg-amber-100 text-amber-700', ROUND_DRAFT: {
EVALUATION: 'bg-blue-100 text-blue-700', label: 'Draft',
SUBMISSION: 'bg-purple-100 text-purple-700', bgClass: 'bg-gray-100 text-gray-700',
MENTORING: 'bg-teal-100 text-teal-700', dotClass: 'bg-gray-500',
LIVE_FINAL: 'bg-red-100 text-red-700', description: 'Not yet active. Configure before launching.',
DELIBERATION: 'bg-indigo-100 text-indigo-700', },
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() { export default function RoundDetailPage() {
const params = useParams() const params = useParams()
const router = useRouter()
const competitionId = params.competitionId as string const competitionId = params.competitionId as string
const roundId = params.roundId as string const roundId = params.roundId as string
const [config, setConfig] = useState<Record<string, unknown>>({}) const [config, setConfig] = useState<Record<string, unknown>>({})
const [hasChanges, setHasChanges] = useState(false) const [hasChanges, setHasChanges] = useState(false)
const [activeTab, setActiveTab] = useState('overview')
const utils = trpc.useUtils() const utils = trpc.useUtils()
const { data: round, isLoading } = trpc.round.getById.useQuery({ id: roundId }) 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) { if (round && !hasChanges) {
const roundConfig = (round.configJson as Record<string, unknown>) ?? {} const roundConfig = (round.configJson as Record<string, unknown>) ?? {}
if (JSON.stringify(roundConfig) !== JSON.stringify(config)) { if (JSON.stringify(roundConfig) !== JSON.stringify(config)) {
@ -46,6 +127,7 @@ export default function RoundDetailPage() {
} }
} }
// -- Mutations --
const updateMutation = trpc.round.update.useMutation({ const updateMutation = trpc.round.update.useMutation({
onSuccess: () => { onSuccess: () => {
utils.round.getById.invalidate({ id: roundId }) utils.round.getById.invalidate({ id: roundId })
@ -55,30 +137,79 @@ export default function RoundDetailPage() {
onError: (err) => toast.error(err.message), 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>) => { const handleConfigChange = (newConfig: Record<string, unknown>) => {
setConfig(newConfig) setConfig(newConfig)
setHasChanges(true) setHasChanges(true)
} }
const handleSave = () => { const handleSave = () => {
updateMutation.mutate({ updateMutation.mutate({ id: roundId, configJson: config })
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) { if (isLoading) {
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Skeleton className="h-8 w-8" /> <Skeleton className="h-8 w-8" />
<div> <div className="space-y-2">
<Skeleton className="h-6 w-48" /> <Skeleton className="h-7 w-64" />
<Skeleton className="h-4 w-32 mt-1" /> <Skeleton className="h-4 w-40" />
</div> </div>
</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-10 w-full" />
<Skeleton className="h-64 w-full" /> <Skeleton className="h-96 w-full" />
</div> </div>
) )
} }
@ -88,73 +219,550 @@ export default function RoundDetailPage() {
<div className="space-y-6"> <div className="space-y-6">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Link href={`/admin/competitions/${competitionId}` as Route}> <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" /> <ArrowLeft className="h-4 w-4" />
</Button> </Button>
</Link> </Link>
<div> <div>
<h1 className="text-xl font-bold">Round Not Found</h1> <h1 className="text-xl font-bold">Round Not Found</h1>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">This round does not exist.</p>
The requested round does not exist
</p>
</div> </div>
</div> </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 ( return (
<div className="space-y-6"> <div className="space-y-6">
{/* Header */} {/* ===== HEADER ===== */}
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between"> <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"> <div className="flex items-start gap-3 min-w-0">
<Link href={`/admin/competitions/${competitionId}` as Route} className="mt-1 shrink-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" /> <ArrowLeft className="h-4 w-4" />
</Button> </Button>
</Link> </Link>
<div className="min-w-0"> <div className="min-w-0">
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
<h1 className="text-xl font-bold truncate">{round.name}</h1> <h1 className="text-xl font-bold tracking-tight truncate">{round.name}</h1>
<Badge <Badge variant="secondary" className={cn('text-xs shrink-0', typeCfg.color)}>
variant="secondary" {typeCfg.label}
className={roundTypeColors[round.roundType] ?? 'bg-gray-100 text-gray-700'}
>
{round.roundType.replace('_', ' ')}
</Badge> </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>
)}
</DropdownMenuContent>
</DropdownMenu>
</div> </div>
<p className="text-sm text-muted-foreground font-mono">{round.slug}</p> <p className="text-sm text-muted-foreground mt-0.5">{typeCfg.description}</p>
</div> </div>
</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 && ( {hasChanges && (
<Button <Button size="sm" onClick={handleSave} disabled={updateMutation.isPending}>
variant="default"
size="sm"
onClick={handleSave}
disabled={updateMutation.isPending}
>
{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> </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>
</div> </div>
{/* Tabs */} {/* ===== STATS BAR ===== */}
<Tabs defaultValue="config" className="space-y-4"> <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"> <TabsList className="w-full sm:w-auto overflow-x-auto">
<TabsTrigger value="config">Configuration</TabsTrigger> <TabsTrigger value="overview">
<TabsTrigger value="projects">Projects</TabsTrigger> <Zap className="h-3.5 w-3.5 mr-1.5" />
<TabsTrigger value="windows">Submission Windows</TabsTrigger> 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> </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"> <TabsContent value="config" className="space-y-4">
<RoundConfigForm <RoundConfigForm
roundType={round.roundType} roundType={round.roundType}
@ -163,16 +771,129 @@ export default function RoundDetailPage() {
/> />
</TabsContent> </TabsContent>
{/* Projects Tab */} {/* ===== DOCUMENTS TAB ===== */}
<TabsContent value="projects" className="space-y-4">
<ProjectStatesTable competitionId={competitionId} roundId={roundId} />
</TabsContent>
{/* Submission Windows Tab */}
<TabsContent value="windows" className="space-y-4"> <TabsContent value="windows" className="space-y-4">
<SubmissionWindowManager competitionId={competitionId} roundId={roundId} /> <FileRequirementsEditor
roundId={roundId}
windowOpenAt={round.windowOpenAt}
windowCloseAt={round.windowCloseAt}
/>
</TabsContent> </TabsContent>
</Tabs> </Tabs>
</div> </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' 'use client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { useState, useCallback } from 'react'
import { Layers } from 'lucide-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 = { type ProjectStatesTableProps = {
competitionId: string competitionId: string
@ -9,25 +74,395 @@ type ProjectStatesTableProps = {
} }
export function ProjectStatesTable({ competitionId, roundId }: ProjectStatesTableProps) { export function ProjectStatesTable({ competitionId, roundId }: ProjectStatesTableProps) {
return ( const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
<Card> const [stateFilter, setStateFilter] = useState<string>('ALL')
<CardHeader> const [batchDialogOpen, setBatchDialogOpen] = useState(false)
<CardTitle className="text-base">Project States</CardTitle> const [batchNewState, setBatchNewState] = useState<ProjectState>('PASSED')
<p className="text-sm text-muted-foreground"> const [removeConfirmId, setRemoveConfirmId] = useState<string | null>(null)
Projects participating in this round const [batchRemoveOpen, setBatchRemoveOpen] = useState(false)
</p>
</CardHeader> const utils = trpc.useUtils()
<CardContent>
<div className="flex flex-col items-center justify-center py-12 text-center"> const { data: projectStates, isLoading } = trpc.roundEngine.getProjectStates.useQuery(
<div className="rounded-full bg-muted p-4 mb-4"> { roundId },
<Layers className="h-8 w-8 text-muted-foreground" /> )
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>
<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 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> </div>
<p className="text-sm font-medium">No Active Projects</p> </CardContent>
<p className="text-xs text-muted-foreground mt-1"> </Card>
Project states will appear here when the round is active )
</p> }
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> </div>
</CardContent> <Link href={'/admin/projects/pool' as Route}>
</Card> <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,33 +33,30 @@ export const cohortRouter = router({
} }
} }
const cohort = await ctx.prisma.$transaction(async (tx) => { const cohort = await ctx.prisma.cohort.create({
const created = await tx.cohort.create({ data: {
data: { roundId: input.roundId,
roundId: input.roundId, name: input.name,
name: input.name, votingMode: input.votingMode,
votingMode: input.votingMode, windowOpenAt: input.windowOpenAt ?? null,
windowOpenAt: input.windowOpenAt ?? null, windowCloseAt: input.windowCloseAt ?? null,
windowCloseAt: input.windowCloseAt ?? null, },
}, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the create
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'CREATE', userId: ctx.user.id,
entityType: 'Cohort', action: 'CREATE',
entityId: created.id, entityType: 'Cohort',
detailsJson: { entityId: cohort.id,
roundId: input.roundId, detailsJson: {
name: input.name, roundId: input.roundId,
votingMode: input.votingMode, name: input.name,
}, votingMode: input.votingMode,
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return created
}) })
return cohort return cohort
@ -157,32 +154,29 @@ export const cohortRouter = router({
? new Date(now.getTime() + input.durationMinutes * 60 * 1000) ? new Date(now.getTime() + input.durationMinutes * 60 * 1000)
: cohort.windowCloseAt : cohort.windowCloseAt
const updated = await ctx.prisma.$transaction(async (tx) => { const updated = await ctx.prisma.cohort.update({
const result = await tx.cohort.update({ where: { id: input.cohortId },
where: { id: input.cohortId }, data: {
data: { isOpen: true,
isOpen: true, windowOpenAt: now,
windowOpenAt: now, windowCloseAt: closeAt,
windowCloseAt: closeAt, },
}, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the voting open
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'COHORT_VOTING_OPENED', userId: ctx.user.id,
entityType: 'Cohort', action: 'COHORT_VOTING_OPENED',
entityId: input.cohortId, entityType: 'Cohort',
detailsJson: { entityId: input.cohortId,
openedAt: now.toISOString(), detailsJson: {
closesAt: closeAt?.toISOString() ?? null, openedAt: now.toISOString(),
projectCount: cohort._count.projects, closesAt: closeAt?.toISOString() ?? null,
}, projectCount: cohort._count.projects,
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return result
}) })
return updated return updated
@ -207,30 +201,27 @@ export const cohortRouter = router({
const now = new Date() const now = new Date()
const updated = await ctx.prisma.$transaction(async (tx) => { const updated = await ctx.prisma.cohort.update({
const result = await tx.cohort.update({ where: { id: input.cohortId },
where: { id: input.cohortId }, data: {
data: { isOpen: false,
isOpen: false, windowCloseAt: now,
windowCloseAt: now, },
}, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the voting close
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'COHORT_VOTING_CLOSED', userId: ctx.user.id,
entityType: 'Cohort', action: 'COHORT_VOTING_CLOSED',
entityId: input.cohortId, entityType: 'Cohort',
detailsJson: { entityId: input.cohortId,
closedAt: now.toISOString(), detailsJson: {
wasOpenSince: cohort.windowOpenAt?.toISOString(), closedAt: now.toISOString(),
}, wasOpenSince: cohort.windowOpenAt?.toISOString(),
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return result
}) })
return updated return updated

View File

@ -36,23 +36,19 @@ export const competitionRouter = router({
where: { id: input.programId }, where: { id: input.programId },
}) })
const competition = await ctx.prisma.$transaction(async (tx) => { const competition = await ctx.prisma.competition.create({
const created = await tx.competition.create({ data: input,
data: input, })
})
await logAudit({ await logAudit({
prisma: tx, prisma: ctx.prisma,
userId: ctx.user.id, userId: ctx.user.id,
action: 'CREATE', action: 'CREATE',
entityType: 'Competition', entityType: 'Competition',
entityId: created.id, entityId: competition.id,
detailsJson: { name: input.name, programId: input.programId }, detailsJson: { name: input.name, programId: input.programId },
ipAddress: ctx.ip, ipAddress: ctx.ip,
userAgent: ctx.userAgent, userAgent: ctx.userAgent,
})
return created
}) })
return competition return competition
@ -178,33 +174,29 @@ export const competitionRouter = router({
} }
} }
const competition = await ctx.prisma.$transaction(async (tx) => { const previous = await ctx.prisma.competition.findUniqueOrThrow({ where: { id } })
const previous = await tx.competition.findUniqueOrThrow({ where: { id } })
const updated = await tx.competition.update({ const competition = await ctx.prisma.competition.update({
where: { id }, where: { id },
data, data,
}) })
await logAudit({ await logAudit({
prisma: tx, prisma: ctx.prisma,
userId: ctx.user.id, userId: ctx.user.id,
action: 'UPDATE', action: 'UPDATE',
entityType: 'Competition', entityType: 'Competition',
entityId: id, entityId: id,
detailsJson: { detailsJson: {
changes: data, changes: data,
previous: { previous: {
name: previous.name, name: previous.name,
status: previous.status, status: previous.status,
slug: previous.slug, slug: previous.slug,
},
}, },
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return updated
}) })
return competition return competition
@ -216,24 +208,20 @@ export const competitionRouter = router({
delete: adminProcedure delete: adminProcedure
.input(z.object({ id: z.string() })) .input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
const competition = await ctx.prisma.$transaction(async (tx) => { const competition = await ctx.prisma.competition.update({
const updated = await tx.competition.update({ where: { id: input.id },
where: { id: input.id }, data: { status: 'ARCHIVED' },
data: { status: 'ARCHIVED' }, })
})
await logAudit({ await logAudit({
prisma: tx, prisma: ctx.prisma,
userId: ctx.user.id, userId: ctx.user.id,
action: 'DELETE', action: 'DELETE',
entityType: 'Competition', entityType: 'Competition',
entityId: input.id, entityId: input.id,
detailsJson: { action: 'archived' }, detailsJson: { action: 'archived' },
ipAddress: ctx.ip, ipAddress: ctx.ip,
userAgent: ctx.userAgent, userAgent: ctx.userAgent,
})
return updated
}) })
return competition return competition

View File

@ -97,22 +97,23 @@ export const decisionRouter = router({
snapshotJson: previousValue as Prisma.InputJsonValue, snapshotJson: previousValue as Prisma.InputJsonValue,
}, },
}) })
})
await logAudit({ // Audit outside transaction so failures don't roll back the override
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'DECISION_OVERRIDE', userId: ctx.user.id,
entityType: input.entityType, action: 'DECISION_OVERRIDE',
entityId: input.entityId, entityType: input.entityType,
detailsJson: { entityId: input.entityId,
reasonCode: input.reasonCode, detailsJson: {
reasonText: input.reasonText, reasonCode: input.reasonCode,
previousState: previousValue.state, reasonText: input.reasonText,
newState: input.newValue.state, previousState: previousValue.state,
}, newState: input.newValue.state,
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
}) })
break break
} }
@ -161,21 +162,22 @@ export const decisionRouter = router({
} as Prisma.InputJsonValue, } as Prisma.InputJsonValue,
}, },
}) })
})
await logAudit({ // Audit outside transaction so failures don't roll back the override
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'DECISION_OVERRIDE', userId: ctx.user.id,
entityType: input.entityType, action: 'DECISION_OVERRIDE',
entityId: input.entityId, entityType: input.entityType,
detailsJson: { entityId: input.entityId,
reasonCode: input.reasonCode, detailsJson: {
previousOutcome: (previousValue as Record<string, unknown>).outcome, reasonCode: input.reasonCode,
newOutcome, previousOutcome: (previousValue as Record<string, unknown>).outcome,
}, newOutcome,
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
}) })
break break
} }
@ -229,21 +231,22 @@ export const decisionRouter = router({
} as Prisma.InputJsonValue, } as Prisma.InputJsonValue,
}, },
}) })
})
await logAudit({ // Audit outside transaction so failures don't roll back the override
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'DECISION_OVERRIDE', userId: ctx.user.id,
entityType: input.entityType, action: 'DECISION_OVERRIDE',
entityId: input.entityId, entityType: input.entityType,
detailsJson: { entityId: input.entityId,
reasonCode: input.reasonCode, detailsJson: {
previousEligible: previousValue.eligible, reasonCode: input.reasonCode,
newEligible, previousEligible: previousValue.eligible,
}, newEligible,
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
}) })
break break
} }

View File

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

View File

@ -36,26 +36,23 @@ export const juryGroupRouter = router({
const { defaultCategoryQuotas, ...rest } = input const { defaultCategoryQuotas, ...rest } = input
const juryGroup = await ctx.prisma.$transaction(async (tx) => { const juryGroup = await ctx.prisma.juryGroup.create({
const created = await tx.juryGroup.create({ data: {
data: { ...rest,
...rest, defaultCategoryQuotas: defaultCategoryQuotas ?? undefined,
defaultCategoryQuotas: defaultCategoryQuotas ?? undefined, },
}, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the create
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'CREATE', userId: ctx.user.id,
entityType: 'JuryGroup', action: 'CREATE',
entityId: created.id, entityType: 'JuryGroup',
detailsJson: { name: input.name, competitionId: input.competitionId }, entityId: juryGroup.id,
ipAddress: ctx.ip, detailsJson: { name: input.name, competitionId: input.competitionId },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return created
}) })
return juryGroup return juryGroup
@ -187,39 +184,36 @@ export const juryGroupRouter = router({
}) })
} }
const member = await ctx.prisma.$transaction(async (tx) => { const member = await ctx.prisma.juryGroupMember.create({
const created = await tx.juryGroupMember.create({ data: {
data: { juryGroupId: input.juryGroupId,
juryGroupId: input.juryGroupId, userId: input.userId,
userId: input.userId, role: input.role,
role: input.role, maxAssignmentsOverride: input.maxAssignmentsOverride ?? undefined,
maxAssignmentsOverride: input.maxAssignmentsOverride ?? undefined, capModeOverride: input.capModeOverride ?? undefined,
capModeOverride: input.capModeOverride ?? undefined, categoryQuotasOverride: input.categoryQuotasOverride ?? undefined,
categoryQuotasOverride: input.categoryQuotasOverride ?? undefined, preferredStartupRatio: input.preferredStartupRatio ?? undefined,
preferredStartupRatio: input.preferredStartupRatio ?? undefined, availabilityNotes: input.availabilityNotes ?? undefined,
availabilityNotes: input.availabilityNotes ?? undefined, },
}, include: {
include: { user: { select: { id: true, name: true, email: true, role: true } },
user: { select: { id: true, name: true, email: true, role: true } }, },
}, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the member add
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'CREATE', userId: ctx.user.id,
entityType: 'JuryGroupMember', action: 'CREATE',
entityId: created.id, entityType: 'JuryGroupMember',
detailsJson: { entityId: member.id,
juryGroupId: input.juryGroupId, detailsJson: {
addedUserId: input.userId, juryGroupId: input.juryGroupId,
role: input.role, addedUserId: input.userId,
}, role: input.role,
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return created
}) })
return member return member
@ -231,31 +225,28 @@ export const juryGroupRouter = router({
removeMember: adminProcedure removeMember: adminProcedure
.input(z.object({ id: z.string() })) .input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
const member = await ctx.prisma.$transaction(async (tx) => { const existing = await ctx.prisma.juryGroupMember.findUniqueOrThrow({
const existing = await tx.juryGroupMember.findUniqueOrThrow({ where: { id: input.id },
where: { id: input.id },
})
await tx.juryGroupMember.delete({ where: { id: input.id } })
await logAudit({
prisma: tx,
userId: ctx.user.id,
action: 'DELETE',
entityType: 'JuryGroupMember',
entityId: input.id,
detailsJson: {
juryGroupId: existing.juryGroupId,
removedUserId: existing.userId,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return existing
}) })
return member await ctx.prisma.juryGroupMember.delete({ where: { id: input.id } })
// Audit outside transaction so failures don't roll back the member removal
await logAudit({
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DELETE',
entityType: 'JuryGroupMember',
entityId: input.id,
detailsJson: {
juryGroupId: existing.juryGroupId,
removedUserId: existing.userId,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return existing
}), }),
/** /**

View File

@ -72,24 +72,25 @@ export const liveRouter = router({
}, },
}) })
await logAudit({
prisma: tx,
userId: ctx.user.id,
action: 'LIVE_SESSION_STARTED',
entityType: 'Round',
entityId: input.roundId,
detailsJson: {
sessionId: created.sessionId,
projectCount: input.projectOrder.length,
firstProjectId: input.projectOrder[0],
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return created return created
}) })
// Audit outside transaction so failures don't roll back the session start
await logAudit({
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'LIVE_SESSION_STARTED',
entityType: 'Round',
entityId: input.roundId,
detailsJson: {
sessionId: cursor.sessionId,
projectCount: input.projectOrder.length,
firstProjectId: input.projectOrder[0],
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return cursor return cursor
}), }),
@ -123,30 +124,27 @@ export const liveRouter = router({
}) })
} }
const updated = await ctx.prisma.$transaction(async (tx) => { const updated = await ctx.prisma.liveProgressCursor.update({
const result = await tx.liveProgressCursor.update({ where: { id: cursor.id },
where: { id: cursor.id }, data: {
data: { activeProjectId: input.projectId,
activeProjectId: input.projectId, activeOrderIndex: index,
activeOrderIndex: index, },
}, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the project set
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'LIVE_ACTIVE_PROJECT_SET', userId: ctx.user.id,
entityType: 'LiveProgressCursor', action: 'LIVE_ACTIVE_PROJECT_SET',
entityId: cursor.id, entityType: 'LiveProgressCursor',
detailsJson: { entityId: cursor.id,
projectId: input.projectId, detailsJson: {
orderIndex: index, projectId: input.projectId,
}, orderIndex: index,
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return result
}) })
return updated return updated
@ -182,31 +180,28 @@ export const liveRouter = router({
const targetProjectId = projectOrder[input.index] const targetProjectId = projectOrder[input.index]
const updated = await ctx.prisma.$transaction(async (tx) => { const updated = await ctx.prisma.liveProgressCursor.update({
const result = await tx.liveProgressCursor.update({ where: { id: cursor.id },
where: { id: cursor.id }, data: {
data: { activeProjectId: targetProjectId,
activeProjectId: targetProjectId, activeOrderIndex: input.index,
activeOrderIndex: input.index, },
}, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the jump
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'LIVE_JUMP', userId: ctx.user.id,
entityType: 'LiveProgressCursor', action: 'LIVE_JUMP',
entityId: cursor.id, entityType: 'LiveProgressCursor',
detailsJson: { entityId: cursor.id,
fromIndex: cursor.activeOrderIndex, detailsJson: {
toIndex: input.index, fromIndex: cursor.activeOrderIndex,
projectId: targetProjectId, toIndex: input.index,
}, projectId: targetProjectId,
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return result
}) })
return updated return updated
@ -255,22 +250,23 @@ export const liveRouter = router({
}, },
}) })
await logAudit({
prisma: tx,
userId: ctx.user.id,
action: 'LIVE_REORDER',
entityType: 'LiveProgressCursor',
entityId: cursor.id,
detailsJson: {
projectCount: input.projectOrder.length,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return updatedCursor return updatedCursor
}) })
// Audit outside transaction so failures don't roll back the reorder
await logAudit({
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'LIVE_REORDER',
entityType: 'LiveProgressCursor',
entityId: cursor.id,
detailsJson: {
projectCount: input.projectOrder.length,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return updated return updated
}), }),
@ -291,24 +287,21 @@ export const liveRouter = router({
}) })
} }
const updated = await ctx.prisma.$transaction(async (tx) => { const updated = await ctx.prisma.liveProgressCursor.update({
const result = await tx.liveProgressCursor.update({ where: { id: cursor.id },
where: { id: cursor.id }, data: { isPaused: true },
data: { isPaused: true }, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the pause
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'LIVE_PAUSED', userId: ctx.user.id,
entityType: 'LiveProgressCursor', action: 'LIVE_PAUSED',
entityId: cursor.id, entityType: 'LiveProgressCursor',
detailsJson: { activeProjectId: cursor.activeProjectId }, entityId: cursor.id,
ipAddress: ctx.ip, detailsJson: { activeProjectId: cursor.activeProjectId },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return result
}) })
return updated return updated
@ -331,24 +324,21 @@ export const liveRouter = router({
}) })
} }
const updated = await ctx.prisma.$transaction(async (tx) => { const updated = await ctx.prisma.liveProgressCursor.update({
const result = await tx.liveProgressCursor.update({ where: { id: cursor.id },
where: { id: cursor.id }, data: { isPaused: false },
data: { isPaused: false }, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the resume
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'LIVE_RESUMED', userId: ctx.user.id,
entityType: 'LiveProgressCursor', action: 'LIVE_RESUMED',
entityId: cursor.id, entityType: 'LiveProgressCursor',
detailsJson: { activeProjectId: cursor.activeProjectId }, entityId: cursor.id,
ipAddress: ctx.ip, detailsJson: { activeProjectId: cursor.activeProjectId },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return result
}) })
return updated return updated

View File

@ -128,54 +128,51 @@ export const mentorRouter = router({
where: { id: input.mentorId }, where: { id: input.mentorId },
}) })
// Create assignment + audit log in transaction // Create assignment
const assignment = await ctx.prisma.$transaction(async (tx) => { const assignment = await ctx.prisma.mentorAssignment.create({
const created = await tx.mentorAssignment.create({ data: {
data: { projectId: input.projectId,
projectId: input.projectId, mentorId: input.mentorId,
mentorId: input.mentorId, method: input.method,
method: input.method, assignedBy: ctx.user.id,
assignedBy: ctx.user.id, aiConfidenceScore: input.aiConfidenceScore,
aiConfidenceScore: input.aiConfidenceScore, expertiseMatchScore: input.expertiseMatchScore,
expertiseMatchScore: input.expertiseMatchScore, aiReasoning: input.aiReasoning,
aiReasoning: input.aiReasoning, },
}, include: {
include: { mentor: {
mentor: { select: {
select: { id: true,
id: true, name: true,
name: true, email: true,
email: true, expertiseTags: true,
expertiseTags: true,
},
},
project: {
select: {
id: true,
title: true,
},
}, },
}, },
}) project: {
select: {
await logAudit({ id: true,
prisma: tx, title: true,
userId: ctx.user.id, },
action: 'MENTOR_ASSIGN',
entityType: 'MentorAssignment',
entityId: created.id,
detailsJson: {
projectId: input.projectId,
projectTitle: created.project.title,
mentorId: input.mentorId,
mentorName: created.mentor.name,
method: input.method,
}, },
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, })
})
return created // Audit outside transaction so failures don't roll back the assignment
await logAudit({
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'MENTOR_ASSIGN',
entityType: 'MentorAssignment',
entityId: assignment.id,
detailsJson: {
projectId: input.projectId,
projectTitle: assignment.project.title,
mentorId: input.mentorId,
mentorName: assignment.mentor.name,
method: input.method,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
}) })
// Get team lead info for mentor notification // Get team lead info for mentor notification
@ -382,27 +379,26 @@ export const mentorRouter = router({
}) })
} }
// Delete assignment + audit log in transaction // Delete assignment
await ctx.prisma.$transaction(async (tx) => { await ctx.prisma.mentorAssignment.delete({
await logAudit({ where: { projectId: input.projectId },
prisma: tx, })
userId: ctx.user.id,
action: 'MENTOR_UNASSIGN',
entityType: 'MentorAssignment',
entityId: assignment.id,
detailsJson: {
projectId: input.projectId,
projectTitle: assignment.project.title,
mentorId: assignment.mentor.id,
mentorName: assignment.mentor.name,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
await tx.mentorAssignment.delete({ // Audit outside transaction so failures don't roll back the unassignment
where: { projectId: input.projectId }, await logAudit({
}) prisma: ctx.prisma,
userId: ctx.user.id,
action: 'MENTOR_UNASSIGN',
entityType: 'MentorAssignment',
entityId: assignment.id,
detailsJson: {
projectId: input.projectId,
projectTitle: assignment.project.title,
mentorId: assignment.mentor.id,
mentorName: assignment.mentor.name,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
}) })
return { success: true } return { success: true }

View File

@ -174,24 +174,24 @@ export const projectPoolRouter = router({
})), })),
}) })
// Create audit log
await logAudit({
prisma: tx,
userId: ctx.user?.id,
action: 'BULK_ASSIGN_TO_ROUND',
entityType: 'Project',
detailsJson: {
roundId,
projectCount: projectIds.length,
projectIds,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return updatedProjects return updatedProjects
}) })
// Audit outside transaction so failures don't roll back the assignment
await logAudit({
prisma: ctx.prisma,
userId: ctx.user?.id,
action: 'BULK_ASSIGN_TO_ROUND',
entityType: 'Project',
detailsJson: {
roundId,
projectCount: projectIds.length,
projectIds,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return { return {
success: true, success: true,
assignedCount: result.count, assignedCount: result.count,
@ -258,24 +258,25 @@ export const projectPoolRouter = router({
})), })),
}) })
await logAudit({
prisma: tx,
userId: ctx.user?.id,
action: 'BULK_ASSIGN_ALL_TO_ROUND',
entityType: 'Project',
detailsJson: {
roundId,
programId,
competitionCategory: competitionCategory || 'ALL',
projectCount: projectIds.length,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return updated return updated
}) })
// Audit outside transaction so failures don't roll back the assignment
await logAudit({
prisma: ctx.prisma,
userId: ctx.user?.id,
action: 'BULK_ASSIGN_ALL_TO_ROUND',
entityType: 'Project',
detailsJson: {
roundId,
programId,
competitionCategory: competitionCategory || 'ALL',
projectCount: projectIds.length,
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return { success: true, assignedCount: result.count, roundId } return { success: true, assignedCount: result.count, roundId }
}), }),
}) })

View File

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

View File

@ -54,39 +54,35 @@ export const roundRouter = router({
? validateRoundConfig(input.roundType, input.configJson) ? validateRoundConfig(input.roundType, input.configJson)
: defaultRoundConfig(input.roundType) : defaultRoundConfig(input.roundType)
const round = await ctx.prisma.$transaction(async (tx) => { const round = await ctx.prisma.round.create({
const created = await tx.round.create({ data: {
data: { competitionId: input.competitionId,
competitionId: input.competitionId, name: input.name,
name: input.name, slug: input.slug,
slug: input.slug, roundType: input.roundType,
roundType: input.roundType, sortOrder: input.sortOrder,
sortOrder: input.sortOrder, configJson: config as unknown as Prisma.InputJsonValue,
configJson: config as unknown as Prisma.InputJsonValue, windowOpenAt: input.windowOpenAt ?? undefined,
windowOpenAt: input.windowOpenAt ?? undefined, windowCloseAt: input.windowCloseAt ?? undefined,
windowCloseAt: input.windowCloseAt ?? undefined, juryGroupId: input.juryGroupId ?? undefined,
juryGroupId: input.juryGroupId ?? undefined, submissionWindowId: input.submissionWindowId ?? undefined,
submissionWindowId: input.submissionWindowId ?? undefined, purposeKey: input.purposeKey ?? undefined,
purposeKey: input.purposeKey ?? undefined, },
}, })
})
await logAudit({ await logAudit({
prisma: tx, prisma: ctx.prisma,
userId: ctx.user.id, userId: ctx.user.id,
action: 'CREATE', action: 'CREATE',
entityType: 'Round', entityType: 'Round',
entityId: created.id, entityId: round.id,
detailsJson: { detailsJson: {
name: input.name, name: input.name,
roundType: input.roundType, roundType: input.roundType,
competitionId: input.competitionId, competitionId: input.competitionId,
}, },
ipAddress: ctx.ip, ipAddress: ctx.ip,
userAgent: ctx.userAgent, userAgent: ctx.userAgent,
})
return created
}) })
return round return round
@ -145,42 +141,38 @@ export const roundRouter = router({
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
const { id, configJson, ...data } = input const { id, configJson, ...data } = input
const round = await ctx.prisma.$transaction(async (tx) => { const existing = await ctx.prisma.round.findUniqueOrThrow({ where: { id } })
const existing = await tx.round.findUniqueOrThrow({ where: { id } })
// If configJson provided, validate it against the round type // If configJson provided, validate it against the round type
let validatedConfig: Prisma.InputJsonValue | undefined let validatedConfig: Prisma.InputJsonValue | undefined
if (configJson) { if (configJson) {
const parsed = validateRoundConfig(existing.roundType, configJson) const parsed = validateRoundConfig(existing.roundType, configJson)
validatedConfig = parsed as unknown as Prisma.InputJsonValue validatedConfig = parsed as unknown as Prisma.InputJsonValue
} }
const updated = await tx.round.update({ const round = await ctx.prisma.round.update({
where: { id }, where: { id },
data: { data: {
...data, ...data,
...(validatedConfig !== undefined ? { configJson: validatedConfig } : {}), ...(validatedConfig !== undefined ? { configJson: validatedConfig } : {}),
},
})
await logAudit({
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'UPDATE',
entityType: 'Round',
entityId: id,
detailsJson: {
changes: input,
previous: {
name: existing.name,
status: existing.status,
}, },
}) },
ipAddress: ctx.ip,
await logAudit({ userAgent: ctx.userAgent,
prisma: tx,
userId: ctx.user.id,
action: 'UPDATE',
entityType: 'Round',
entityId: id,
detailsJson: {
changes: input,
previous: {
name: existing.name,
status: existing.status,
},
},
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return updated
}) })
return round return round
@ -213,30 +205,26 @@ export const roundRouter = router({
delete: adminProcedure delete: adminProcedure
.input(z.object({ id: z.string() })) .input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
const round = await ctx.prisma.$transaction(async (tx) => { const existing = await ctx.prisma.round.findUniqueOrThrow({ where: { id: input.id } })
const existing = await tx.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({ await logAudit({
prisma: tx, prisma: ctx.prisma,
userId: ctx.user.id, userId: ctx.user.id,
action: 'DELETE', action: 'DELETE',
entityType: 'Round', entityType: 'Round',
entityId: input.id, entityId: input.id,
detailsJson: { detailsJson: {
name: existing.name, name: existing.name,
roundType: existing.roundType, roundType: existing.roundType,
competitionId: existing.competitionId, competitionId: existing.competitionId,
}, },
ipAddress: ctx.ip, ipAddress: ctx.ip,
userAgent: ctx.userAgent, userAgent: ctx.userAgent,
})
return existing
}) })
return round return existing
}), }),
// ========================================================================= // =========================================================================
@ -261,33 +249,29 @@ export const roundRouter = router({
}) })
) )
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
const window = await ctx.prisma.$transaction(async (tx) => { const window = await ctx.prisma.submissionWindow.create({
const created = await tx.submissionWindow.create({ data: {
data: { competitionId: input.competitionId,
competitionId: input.competitionId, name: input.name,
name: input.name, slug: input.slug,
slug: input.slug, roundNumber: input.roundNumber,
roundNumber: input.roundNumber, windowOpenAt: input.windowOpenAt,
windowOpenAt: input.windowOpenAt, windowCloseAt: input.windowCloseAt,
windowCloseAt: input.windowCloseAt, deadlinePolicy: input.deadlinePolicy,
deadlinePolicy: input.deadlinePolicy, graceHours: input.graceHours,
graceHours: input.graceHours, lockOnClose: input.lockOnClose,
lockOnClose: input.lockOnClose, },
}, })
})
await logAudit({ await logAudit({
prisma: tx, prisma: ctx.prisma,
userId: ctx.user.id, userId: ctx.user.id,
action: 'CREATE', action: 'CREATE',
entityType: 'SubmissionWindow', entityType: 'SubmissionWindow',
entityId: created.id, entityId: window.id,
detailsJson: { name: input.name, competitionId: input.competitionId }, detailsJson: { name: input.name, competitionId: input.competitionId },
ipAddress: ctx.ip, ipAddress: ctx.ip,
userAgent: ctx.userAgent, userAgent: ctx.userAgent,
})
return created
}) })
return window return window
@ -313,22 +297,19 @@ export const roundRouter = router({
) )
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
const { id, ...data } = input const { id, ...data } = input
const window = await ctx.prisma.$transaction(async (tx) => { const window = await ctx.prisma.submissionWindow.update({
const updated = await tx.submissionWindow.update({ where: { id },
where: { id }, data,
data, })
}) await logAudit({
await logAudit({ prisma: ctx.prisma,
prisma: tx, userId: ctx.user.id,
userId: ctx.user.id, action: 'UPDATE',
action: 'UPDATE', entityType: 'SubmissionWindow',
entityType: 'SubmissionWindow', entityId: id,
entityId: id, detailsJson: data,
detailsJson: data, ipAddress: ctx.ip,
ipAddress: ctx.ip, userAgent: ctx.userAgent,
userAgent: ctx.userAgent,
})
return updated
}) })
return window return window
}), }),
@ -350,18 +331,16 @@ export const roundRouter = router({
message: `Cannot delete window "${window.name}" — it has ${window._count.projectFiles} uploaded files. Remove files first.`, message: `Cannot delete window "${window.name}" — it has ${window._count.projectFiles} uploaded files. Remove files first.`,
}) })
} }
await ctx.prisma.$transaction(async (tx) => { await ctx.prisma.submissionWindow.delete({ where: { id: input.id } })
await tx.submissionWindow.delete({ where: { id: input.id } }) await logAudit({
await logAudit({ prisma: ctx.prisma,
prisma: tx, userId: ctx.user.id,
userId: ctx.user.id, action: 'DELETE',
action: 'DELETE', entityType: 'SubmissionWindow',
entityType: 'SubmissionWindow', entityId: input.id,
entityId: input.id, detailsJson: { name: window.name },
detailsJson: { name: window.name }, ipAddress: ctx.ip,
ipAddress: ctx.ip, userAgent: ctx.userAgent,
userAgent: ctx.userAgent,
})
}) })
return { success: true } return { success: true }
}), }),

View File

@ -140,4 +140,109 @@ export const roundEngineRouter = router({
.query(async ({ ctx, input }) => { .query(async ({ ctx, input }) => {
return getProjectRoundState(input.projectId, input.roundId, ctx.prisma) 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,37 +106,34 @@ export const specialAwardRouter = router({
_max: { sortOrder: true }, _max: { sortOrder: true },
}) })
const award = await ctx.prisma.$transaction(async (tx) => { const award = await ctx.prisma.specialAward.create({
const created = await tx.specialAward.create({ data: {
data: { programId: input.programId,
programId: input.programId, name: input.name,
name: input.name, description: input.description,
description: input.description, criteriaText: input.criteriaText,
criteriaText: input.criteriaText, useAiEligibility: input.useAiEligibility ?? true,
useAiEligibility: input.useAiEligibility ?? true, scoringMode: input.scoringMode,
scoringMode: input.scoringMode, maxRankedPicks: input.maxRankedPicks,
maxRankedPicks: input.maxRankedPicks, autoTagRulesJson: input.autoTagRulesJson as Prisma.InputJsonValue ?? undefined,
autoTagRulesJson: input.autoTagRulesJson as Prisma.InputJsonValue ?? undefined, competitionId: input.competitionId,
competitionId: input.competitionId, evaluationRoundId: input.evaluationRoundId,
evaluationRoundId: input.evaluationRoundId, juryGroupId: input.juryGroupId,
juryGroupId: input.juryGroupId, eligibilityMode: input.eligibilityMode,
eligibilityMode: input.eligibilityMode, sortOrder: (maxOrder._max.sortOrder || 0) + 1,
sortOrder: (maxOrder._max.sortOrder || 0) + 1, },
}, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the create
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'CREATE', userId: ctx.user.id,
entityType: 'SpecialAward', action: 'CREATE',
entityId: created.id, entityType: 'SpecialAward',
detailsJson: { name: input.name, scoringMode: input.scoringMode }, entityId: award.id,
ipAddress: ctx.ip, detailsJson: { name: input.name, scoringMode: input.scoringMode },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return created
}) })
return award return award
@ -190,18 +187,17 @@ export const specialAwardRouter = router({
delete: adminProcedure delete: adminProcedure
.input(z.object({ id: z.string() })) .input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
await ctx.prisma.$transaction(async (tx) => { await ctx.prisma.specialAward.delete({ where: { id: input.id } })
await logAudit({
prisma: tx,
userId: ctx.user.id,
action: 'DELETE',
entityType: 'SpecialAward',
entityId: input.id,
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
await tx.specialAward.delete({ where: { id: input.id } }) // Audit outside transaction so failures don't break the delete
await logAudit({
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DELETE',
entityType: 'SpecialAward',
entityId: input.id,
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
}) })
}), }),
@ -245,32 +241,29 @@ export const specialAwardRouter = router({
} }
} }
const award = await ctx.prisma.$transaction(async (tx) => { const award = await ctx.prisma.specialAward.update({
const updated = await tx.specialAward.update({ where: { id: input.id },
where: { id: input.id }, data: updateData,
data: updateData, })
})
await logAudit({ // Audit outside transaction so failures don't break the status update
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'UPDATE_STATUS', userId: ctx.user.id,
entityType: 'SpecialAward', action: 'UPDATE_STATUS',
entityId: input.id, entityType: 'SpecialAward',
detailsJson: { entityId: input.id,
previousStatus: current.status, detailsJson: {
newStatus: input.status, previousStatus: current.status,
...(votingStartAtUpdated && { newStatus: input.status,
votingStartAtUpdated: true, ...(votingStartAtUpdated && {
previousVotingStartAt: current.votingStartAt, votingStartAtUpdated: true,
newVotingStartAt: now, previousVotingStartAt: current.votingStartAt,
}), newVotingStartAt: now,
}, }),
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return updated
}) })
return award return award
@ -743,33 +736,30 @@ export const specialAwardRouter = router({
select: { winnerProjectId: true }, select: { winnerProjectId: true },
}) })
const award = await ctx.prisma.$transaction(async (tx) => { const award = await ctx.prisma.specialAward.update({
const updated = await tx.specialAward.update({ where: { id: input.awardId },
where: { id: input.awardId }, data: {
data: { winnerProjectId: input.projectId,
winnerProjectId: input.projectId, winnerOverridden: input.overridden,
winnerOverridden: input.overridden, winnerOverriddenBy: input.overridden ? ctx.user.id : null,
winnerOverriddenBy: input.overridden ? ctx.user.id : null, },
}, })
})
await logAudit({ // Audit outside transaction so failures don't break the winner update
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'UPDATE', userId: ctx.user.id,
entityType: 'SpecialAward', action: 'UPDATE',
entityId: input.awardId, entityType: 'SpecialAward',
detailsJson: { entityId: input.awardId,
action: 'SET_AWARD_WINNER', detailsJson: {
previousWinner: previous.winnerProjectId, action: 'SET_AWARD_WINNER',
newWinner: input.projectId, previousWinner: previous.winnerProjectId,
overridden: input.overridden, newWinner: input.projectId,
}, overridden: input.overridden,
ipAddress: ctx.ip, },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return updated
}) })
return award return award

View File

@ -194,22 +194,21 @@ export const userRouter = router({
}) })
} }
// Wrap audit + deletion in a transaction // Delete user
await ctx.prisma.$transaction(async (tx) => { await ctx.prisma.user.delete({
await logAudit({ where: { id: ctx.user.id },
prisma: tx, })
userId: ctx.user.id,
action: 'DELETE_OWN_ACCOUNT',
entityType: 'User',
entityId: ctx.user.id,
detailsJson: { email: user.email },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
await tx.user.delete({ // Audit outside transaction so failures don't roll back the deletion
where: { id: ctx.user.id }, await logAudit({
}) prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DELETE_OWN_ACCOUNT',
entityType: 'User',
entityId: ctx.user.id,
detailsJson: { email: user.email },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
}) })
return { success: true } return { success: true }
@ -384,26 +383,23 @@ export const userRouter = router({
}) })
} }
const user = await ctx.prisma.$transaction(async (tx) => { const user = await ctx.prisma.user.create({
const created = await tx.user.create({ data: {
data: { ...input,
...input, status: 'INVITED',
status: 'INVITED', },
}, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the user creation
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'CREATE', userId: ctx.user.id,
entityType: 'User', action: 'CREATE',
entityId: created.id, entityType: 'User',
detailsJson: { email: input.email, role: input.role }, entityId: user.id,
ipAddress: ctx.ip, detailsJson: { email: input.email, role: input.role },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return created
}) })
return user return user
@ -486,39 +482,36 @@ export const userRouter = router({
...(normalizedEmail !== undefined && { email: normalizedEmail }), ...(normalizedEmail !== undefined && { email: normalizedEmail }),
} }
const user = await ctx.prisma.$transaction(async (tx) => { const user = await ctx.prisma.user.update({
const updated = await tx.user.update({ where: { id },
where: { id }, data: updateData,
data: updateData, })
})
// Audit outside transaction so failures don't roll back the update
await logAudit({
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'UPDATE',
entityType: 'User',
entityId: id,
detailsJson: updateData,
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
// Track role change specifically
if (data.role && data.role !== targetUser.role) {
await logAudit({ await logAudit({
prisma: tx, prisma: ctx.prisma,
userId: ctx.user.id, userId: ctx.user.id,
action: 'UPDATE', action: 'ROLE_CHANGED',
entityType: 'User', entityType: 'User',
entityId: id, entityId: id,
detailsJson: updateData, detailsJson: { previousRole: targetUser.role, newRole: data.role },
ipAddress: ctx.ip, ipAddress: ctx.ip,
userAgent: ctx.userAgent, userAgent: ctx.userAgent,
}) })
}
// Track role change specifically
if (data.role && data.role !== targetUser.role) {
await logAudit({
prisma: tx,
userId: ctx.user.id,
action: 'ROLE_CHANGED',
entityType: 'User',
entityId: id,
detailsJson: { previousRole: targetUser.role, newRole: data.role },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
}
return updated
})
return user return user
}), }),
@ -537,27 +530,26 @@ export const userRouter = router({
}) })
} }
const user = await ctx.prisma.$transaction(async (tx) => { // Fetch user data before deletion for the audit log
// Fetch user data before deletion for the audit log const target = await ctx.prisma.user.findUniqueOrThrow({
const target = await tx.user.findUniqueOrThrow({ where: { id: input.id },
where: { id: input.id }, select: { email: true },
select: { email: true }, })
})
await logAudit({ const user = await ctx.prisma.user.delete({
prisma: tx, where: { id: input.id },
userId: ctx.user.id, })
action: 'DELETE',
entityType: 'User',
entityId: input.id,
detailsJson: { email: target.email },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return tx.user.delete({ // Audit outside transaction so failures don't roll back the deletion
where: { id: input.id }, await logAudit({
}) prisma: ctx.prisma,
userId: ctx.user.id,
action: 'DELETE',
entityType: 'User',
entityId: input.id,
detailsJson: { email: target.email },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
}) })
return user return user
@ -1147,20 +1139,21 @@ export const userRouter = router({
} }
} }
await logAudit({
prisma: tx,
userId: ctx.user.id,
action: 'COMPLETE_ONBOARDING',
entityType: 'User',
entityId: ctx.user.id,
detailsJson: { name: input.name, juryPreferencesCount: input.juryPreferences?.length ?? 0 },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return updated return updated
}) })
// Audit outside transaction so failures don't roll back the onboarding
await logAudit({
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'COMPLETE_ONBOARDING',
entityType: 'User',
entityId: ctx.user.id,
detailsJson: { name: input.name, juryPreferencesCount: input.juryPreferences?.length ?? 0 },
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
})
return user return user
}), }),
@ -1265,29 +1258,26 @@ export const userRouter = router({
// Hash the password // Hash the password
const passwordHash = await hashPassword(input.password) const passwordHash = await hashPassword(input.password)
// Update user with new password + audit in transaction // Update user with new password
const user = await ctx.prisma.$transaction(async (tx) => { const user = await ctx.prisma.user.update({
const updated = await tx.user.update({ where: { id: ctx.user.id },
where: { id: ctx.user.id }, data: {
data: { passwordHash,
passwordHash, passwordSetAt: new Date(),
passwordSetAt: new Date(), mustSetPassword: false,
mustSetPassword: false, },
}, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the password set
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'PASSWORD_SET', userId: ctx.user.id,
entityType: 'User', action: 'PASSWORD_SET',
entityId: ctx.user.id, entityType: 'User',
detailsJson: { timestamp: new Date().toISOString() }, entityId: ctx.user.id,
ipAddress: ctx.ip, detailsJson: { timestamp: new Date().toISOString() },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
return updated
}) })
return { success: true, email: user.email } return { success: true, email: user.email }
@ -1348,26 +1338,25 @@ export const userRouter = router({
// Hash the new password // Hash the new password
const passwordHash = await hashPassword(input.newPassword) const passwordHash = await hashPassword(input.newPassword)
// Update user with new password + audit in transaction // Update user with new password
await ctx.prisma.$transaction(async (tx) => { await ctx.prisma.user.update({
await tx.user.update({ where: { id: ctx.user.id },
where: { id: ctx.user.id }, data: {
data: { passwordHash,
passwordHash, passwordSetAt: new Date(),
passwordSetAt: new Date(), },
}, })
})
await logAudit({ // Audit outside transaction so failures don't roll back the password change
prisma: tx, await logAudit({
userId: ctx.user.id, prisma: ctx.prisma,
action: 'PASSWORD_CHANGED', userId: ctx.user.id,
entityType: 'User', action: 'PASSWORD_CHANGED',
entityId: ctx.user.id, entityType: 'User',
detailsJson: { timestamp: new Date().toISOString() }, entityId: ctx.user.id,
ipAddress: ctx.ip, detailsJson: { timestamp: new Date().toISOString() },
userAgent: ctx.userAgent, ipAddress: ctx.ip,
}) userAgent: ctx.userAgent,
}) })
return { success: true } return { success: true }