Files
MOPC-Portal/src/components/admin/round/project-states-table.tsx
Matt 7f334ed095
All checks were successful
Build and Push Docker Image / build (push) Successful in 7m32s
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>
2026-02-16 07:49:39 +01:00

469 lines
17 KiB
TypeScript

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