Files
MOPC-Portal/src/app/(admin)/admin/awards/[id]/edit/page.tsx
Matt 7bc2b84d1d
All checks were successful
Build and Push Docker Image / build (push) Successful in 8m5s
refactor(awards): remove AWARD_MASTER role, fold features into jury chair flow
The AWARD_MASTER role split sponsor jurors into a parallel UI that hid
project files (only showed when the award was anchored to an evaluation
round) and duplicated the jury voting path with no real difference in
authority — tie-break and finalize were already governed by AwardJuror.isChair
regardless of the user's global role. Inviting a juror via the award page
defaulted to AWARD_MASTER, randomly fragmenting jury panels.

This collapses the role into JURY_MEMBER + isChair:

- specialAward.getMyAwardDetail now returns evaluation scores, chair
  visibility into other jurors' votes, and juror roster
- specialAward.submitVote accepts an optional justification per vote
- specialAward.confirmWinner moves from awardMasterProcedure to
  protectedProcedure (juror+chair check inside)
- bulkInviteJurors creates JURY_MEMBER accounts and, when the award has
  a juryGroupId, also adds them to that JuryGroup so they appear on
  the round-page jury panel
- jury award page renders justification, eval-score badges, and a
  chair tools panel with vote tally + finalize-winner CTA
- juryGroup.list includes attached SpecialAwards; the jury-list UI
  shows a trophy pill alongside round pills
- (award-master) route group, awardMasterProcedure, AWARD_MASTER role
  enum value, and AWARD_MASTER_DECISION decisionMode are deleted
- migration demotes any residual AWARD_MASTER users to JURY_MEMBER and
  recreates the UserRole enum without the value

Coup de Coeur on prod: Didier (the sponsor juror added today as
AWARD_MASTER by the buggy invite form) was migrated to JURY_MEMBER and
attached to the existing "Coup de Coeur" JuryGroup; the SpecialAward
itself was linked to that group (juryGroupId was NULL).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 15:21:09 +02:00

380 lines
14 KiB
TypeScript

'use client'
import { use, useState, useEffect } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Skeleton } from '@/components/ui/skeleton'
import { toast } from 'sonner'
import { ArrowLeft, Save, Loader2 } from 'lucide-react'
export default function EditAwardPage({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id: awardId } = use(params)
const router = useRouter()
const utils = trpc.useUtils()
const { data: award, isLoading } = trpc.specialAward.get.useQuery({ id: awardId })
// Rounds come from the award's included competition relation
const competitionRounds = award?.competition?.rounds ?? []
const updateAward = trpc.specialAward.update.useMutation({
onSuccess: () => {
utils.specialAward.get.invalidate({ id: awardId })
utils.specialAward.list.invalidate()
},
})
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const [criteriaText, setCriteriaText] = useState('')
const [scoringMode, setScoringMode] = useState<'PICK_WINNER' | 'RANKED' | 'SCORED'>('PICK_WINNER')
const [useAiEligibility, setUseAiEligibility] = useState(true)
const [maxRankedPicks, setMaxRankedPicks] = useState('3')
const [votingStartAt, setVotingStartAt] = useState('')
const [votingEndAt, setVotingEndAt] = useState('')
const [evaluationRoundId, setEvaluationRoundId] = useState('')
const [eligibilityMode, setEligibilityMode] = useState<'STAY_IN_MAIN' | 'SEPARATE_POOL'>('STAY_IN_MAIN')
const [decisionMode, setDecisionMode] = useState<'JURY_VOTE' | 'ADMIN_DECISION'>('JURY_VOTE')
// Helper to format date for datetime-local input
const formatDateForInput = (date: Date | string | null | undefined): string => {
if (!date) return ''
const d = new Date(date)
// Format: YYYY-MM-DDTHH:mm
return d.toISOString().slice(0, 16)
}
// Load existing values when award data arrives
useEffect(() => {
if (award) {
setName(award.name)
setDescription(award.description || '')
setCriteriaText(award.criteriaText || '')
setScoringMode(award.scoringMode as 'PICK_WINNER' | 'RANKED' | 'SCORED')
setUseAiEligibility(award.useAiEligibility)
setMaxRankedPicks(String(award.maxRankedPicks || 3))
setVotingStartAt(formatDateForInput(award.votingStartAt))
setVotingEndAt(formatDateForInput(award.votingEndAt))
setEvaluationRoundId(award.evaluationRoundId || '')
setEligibilityMode(award.eligibilityMode as 'STAY_IN_MAIN' | 'SEPARATE_POOL')
setDecisionMode((award.decisionMode as typeof decisionMode) || 'JURY_VOTE')
}
}, [award])
const handleSubmit = async () => {
if (!name.trim()) return
try {
await updateAward.mutateAsync({
id: awardId,
name: name.trim(),
description: description.trim() || undefined,
criteriaText: criteriaText.trim() || undefined,
useAiEligibility,
scoringMode,
maxRankedPicks: scoringMode === 'RANKED' ? parseInt(maxRankedPicks) : undefined,
votingStartAt: votingStartAt ? new Date(votingStartAt) : undefined,
votingEndAt: votingEndAt ? new Date(votingEndAt) : undefined,
evaluationRoundId: evaluationRoundId || undefined,
eligibilityMode,
decisionMode,
})
toast.success('Award updated')
router.push(`/admin/awards/${awardId}`)
} catch (error) {
toast.error(
error instanceof Error ? error.message : 'Failed to update award'
)
}
}
if (isLoading) {
return (
<div className="space-y-6">
<Skeleton className="h-9 w-48" />
<Skeleton className="h-[400px] w-full" />
</div>
)
}
if (!award) return null
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<Button variant="ghost" className="-ml-4" onClick={() => router.back()}>
<ArrowLeft className="mr-2 h-4 w-4" />
Back
</Button>
</div>
<div>
<h1 className="text-2xl font-semibold tracking-tight">
Edit Award
</h1>
<p className="text-muted-foreground">
Update award settings and eligibility criteria
</p>
</div>
<Card>
<CardHeader>
<CardTitle>Award Details</CardTitle>
<CardDescription>
Configure the award name, criteria, and scoring mode
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name">Award Name</Label>
<Input
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g., Mediterranean Entrepreneurship Award"
/>
</div>
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Brief description of this award"
rows={3}
/>
</div>
<div className="space-y-2">
<Label htmlFor="criteria">Eligibility Criteria</Label>
<Textarea
id="criteria"
value={criteriaText}
onChange={(e) => setCriteriaText(e.target.value)}
placeholder="Describe the criteria in plain language. AI will interpret this to evaluate project eligibility."
rows={4}
/>
<p className="text-xs text-muted-foreground">
This text will be used by AI to determine which projects are
eligible for this award.
</p>
</div>
<div className="flex items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<Label htmlFor="ai-toggle">AI Eligibility</Label>
<p className="text-xs text-muted-foreground">
Use AI to automatically evaluate project eligibility based on the criteria above.
Turn off for awards decided by feeling or manual selection.
</p>
</div>
<Switch
id="ai-toggle"
checked={useAiEligibility}
onCheckedChange={setUseAiEligibility}
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="scoring">Scoring Mode</Label>
<Select
value={scoringMode}
onValueChange={(v) =>
setScoringMode(v as 'PICK_WINNER' | 'RANKED' | 'SCORED')
}
>
<SelectTrigger id="scoring">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="PICK_WINNER">
Pick Winner Each juror picks 1
</SelectItem>
<SelectItem value="RANKED">
Ranked Each juror ranks top N
</SelectItem>
<SelectItem value="SCORED">
Scored Use evaluation form
</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="decisionMode">Decision Mode</Label>
<Select
value={decisionMode}
onValueChange={(v) => setDecisionMode(v as typeof decisionMode)}
>
<SelectTrigger id="decisionMode">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="JURY_VOTE">Jury Vote tallied from all jurors</SelectItem>
<SelectItem value="ADMIN_DECISION">Admin Decision admin selects winner</SelectItem>
</SelectContent>
</Select>
</div>
{scoringMode === 'RANKED' && (
<div className="space-y-2">
<Label htmlFor="maxPicks">Max Ranked Picks</Label>
<Input
id="maxPicks"
type="number"
min="1"
max="20"
value={maxRankedPicks}
onChange={(e) => setMaxRankedPicks(e.target.value)}
/>
</div>
)}
</div>
</CardContent>
</Card>
{/* Source Round & Eligibility */}
<Card>
<CardHeader>
<CardTitle>Source Round & Pool</CardTitle>
<CardDescription>
Define which round feeds projects into this award and how they interact with the main competition
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="sourceRound">Source Round</Label>
<Select
value={evaluationRoundId || 'none'}
onValueChange={(v) => setEvaluationRoundId(v === 'none' ? '' : v)}
>
<SelectTrigger id="sourceRound">
<SelectValue placeholder="Select round..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">No source round</SelectItem>
{competitionRounds.map((round) => (
<SelectItem key={round.id} value={round.id}>
{round.name} ({round.roundType})
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Projects from this round will be considered for award eligibility
</p>
</div>
<div className="space-y-2">
<Label htmlFor="eligibilityMode">Eligibility Mode</Label>
<Select
value={eligibilityMode}
onValueChange={(v) =>
setEligibilityMode(v as 'STAY_IN_MAIN' | 'SEPARATE_POOL')
}
>
<SelectTrigger id="eligibilityMode">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="STAY_IN_MAIN">
Stay in Main Projects remain in competition
</SelectItem>
<SelectItem value="SEPARATE_POOL">
Separate Pool Projects exit to award track
</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Whether award-eligible projects continue in the main competition or move to a separate track
</p>
</div>
</div>
</CardContent>
</Card>
{/* Voting Window Card */}
<Card>
<CardHeader>
<CardTitle>Voting Window</CardTitle>
<CardDescription>
Set the time period during which jurors can submit their votes
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="votingStart">Voting Opens</Label>
<Input
id="votingStart"
type="datetime-local"
value={votingStartAt}
onChange={(e) => setVotingStartAt(e.target.value)}
/>
<p className="text-xs text-muted-foreground">
When jurors can start voting (leave empty to set when opening voting)
</p>
</div>
<div className="space-y-2">
<Label htmlFor="votingEnd">Voting Closes</Label>
<Input
id="votingEnd"
type="datetime-local"
value={votingEndAt}
onChange={(e) => setVotingEndAt(e.target.value)}
/>
<p className="text-xs text-muted-foreground">
Deadline for juror votes
</p>
</div>
</div>
</CardContent>
</Card>
<div className="flex justify-end gap-4">
<Button variant="outline" asChild>
<Link href={`/admin/awards/${awardId}`}>Cancel</Link>
</Button>
<Button
onClick={handleSubmit}
disabled={updateAward.isPending || !name.trim()}
>
{updateAward.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Save className="mr-2 h-4 w-4" />
)}
Save Changes
</Button>
</div>
</div>
)
}