Implement 15 platform features: digest, availability, templates, comparison, live voting SSE, file versioning, mentorship, messaging, analytics, drafts, webhooks, peer review, audit enhancements, i18n
Features implemented: - F1: Email digest notifications with cron endpoint and per-user frequency - F2: Jury availability windows and workload preferences in smart assignment - F3: Round templates with save-from-round and CRUD management - F4: Side-by-side project comparison view for jury members - F5: Real-time voting dashboard with Server-Sent Events (SSE) - F6: Live voting UX: QR codes, audience voting, tie-breaking, score animations - F7: File versioning, inline preview, bulk download with presigned URLs - F8: Mentor dashboard: milestones, private notes, activity tracking - F9: Communication hub with broadcasts, templates, and recipient targeting - F10: Advanced analytics: cross-round comparison, juror consistency, diversity metrics, PDF export - F11: Applicant draft saving with magic link resume and cron cleanup - F12: Webhook integration layer with HMAC signing, retry, and delivery logs - F13: Peer review discussions with anonymized scores and threaded comments - F14: Audit log enhancements: before/after diffs, session grouping, anomaly detection, retention - F15: i18n foundation with next-intl (EN/FR), cookie-based locale, language switcher Schema: 12 new models, field additions to User, Project, ProjectFile, LiveVotingSession, LiveVote, MentorAssignment, AuditLog, Program New routers: roundTemplate, message, webhook (registered in _app.ts) New services: email-digest, webhook-dispatcher New cron endpoints: /api/cron/digest, /api/cron/draft-cleanup, /api/cron/audit-cleanup New API routes: /api/live-voting/stream (SSE), /api/files/bulk-download All features are admin-configurable via SystemSettings or per-model settingsJson fields. Docker build verified successfully. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -48,7 +48,11 @@ import {
|
||||
ChevronRight,
|
||||
RefreshCw,
|
||||
RotateCcw,
|
||||
AlertTriangle,
|
||||
Layers,
|
||||
ArrowLeftRight,
|
||||
} from 'lucide-react'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -127,6 +131,7 @@ export default function AuditLogPage() {
|
||||
const [page, setPage] = useState(1)
|
||||
const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set())
|
||||
const [showFilters, setShowFilters] = useState(true)
|
||||
const [groupBySession, setGroupBySession] = useState(false)
|
||||
|
||||
// Build query input
|
||||
const queryInput = useMemo(
|
||||
@@ -153,6 +158,11 @@ export default function AuditLogPage() {
|
||||
perPage: 100,
|
||||
})
|
||||
|
||||
// Fetch anomalies
|
||||
const { data: anomalyData } = trpc.audit.getAnomalies.useQuery({}, {
|
||||
retry: false,
|
||||
})
|
||||
|
||||
// Export mutation
|
||||
const exportLogs = trpc.export.auditLogs.useQuery(
|
||||
{
|
||||
@@ -384,6 +394,54 @@ export default function AuditLogPage() {
|
||||
</Card>
|
||||
</Collapsible>
|
||||
|
||||
{/* Anomaly Alerts */}
|
||||
{anomalyData && anomalyData.anomalies.length > 0 && (
|
||||
<Card className="border-amber-500/50 bg-amber-500/5">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-lg flex items-center gap-2 text-amber-700">
|
||||
<AlertTriangle className="h-5 w-5" />
|
||||
Anomaly Alerts ({anomalyData.anomalies.length})
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{anomalyData.anomalies.slice(0, 5).map((anomaly, i) => (
|
||||
<div key={i} className="flex items-start gap-3 rounded-lg border border-amber-200 bg-white p-3 text-sm">
|
||||
<AlertTriangle className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium">{anomaly.isRapid ? 'Rapid Activity' : 'Bulk Operations'}</p>
|
||||
<p className="text-xs text-muted-foreground">{String(anomaly.actionCount)} actions in {String(anomaly.timeWindowMinutes)} min ({anomaly.actionsPerMinute.toFixed(1)}/min)</p>
|
||||
{anomaly.userId && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
User: {String(anomaly.user?.name || anomaly.userId)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground shrink-0">
|
||||
{String(anomaly.actionCount)} actions
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Session Grouping Toggle */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="session-grouping"
|
||||
checked={groupBySession}
|
||||
onCheckedChange={setGroupBySession}
|
||||
/>
|
||||
<label htmlFor="session-grouping" className="text-sm cursor-pointer flex items-center gap-1">
|
||||
<Layers className="h-4 w-4" />
|
||||
Group by Session
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Results */}
|
||||
{isLoading ? (
|
||||
<AuditLogSkeleton />
|
||||
@@ -485,6 +543,28 @@ export default function AuditLogPage() {
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
{!!(log as Record<string, unknown>).previousDataJson && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground mb-1 flex items-center gap-1">
|
||||
<ArrowLeftRight className="h-3 w-3" />
|
||||
Changes (Before / After)
|
||||
</p>
|
||||
<DiffViewer
|
||||
before={(log as Record<string, unknown>).previousDataJson}
|
||||
after={log.detailsJson}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{groupBySession && !!(log as Record<string, unknown>).sessionId && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground">
|
||||
Session ID
|
||||
</p>
|
||||
<p className="font-mono text-xs">
|
||||
{String((log as Record<string, unknown>).sessionId)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
@@ -625,6 +705,42 @@ export default function AuditLogPage() {
|
||||
)
|
||||
}
|
||||
|
||||
function DiffViewer({ before, after }: { before: unknown; after: unknown }) {
|
||||
const beforeObj = typeof before === 'object' && before !== null ? before as Record<string, unknown> : {}
|
||||
const afterObj = typeof after === 'object' && after !== null ? after as Record<string, unknown> : {}
|
||||
const allKeys = Array.from(new Set([...Object.keys(beforeObj), ...Object.keys(afterObj)]))
|
||||
const changedKeys = allKeys.filter(
|
||||
(key) => JSON.stringify(beforeObj[key]) !== JSON.stringify(afterObj[key])
|
||||
)
|
||||
|
||||
if (changedKeys.length === 0) {
|
||||
return (
|
||||
<p className="text-xs text-muted-foreground italic">No differences detected</p>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border overflow-hidden text-xs font-mono">
|
||||
<div className="grid grid-cols-3 bg-muted p-2 font-medium">
|
||||
<span>Field</span>
|
||||
<span>Before</span>
|
||||
<span>After</span>
|
||||
</div>
|
||||
{changedKeys.map((key) => (
|
||||
<div key={key} className="grid grid-cols-3 p-2 border-t">
|
||||
<span className="font-medium text-muted-foreground">{key}</span>
|
||||
<span className="text-red-600 break-all">
|
||||
{beforeObj[key] !== undefined ? JSON.stringify(beforeObj[key]) : '--'}
|
||||
</span>
|
||||
<span className="text-green-600 break-all">
|
||||
{afterObj[key] !== undefined ? JSON.stringify(afterObj[key]) : '--'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AuditLogSkeleton() {
|
||||
return (
|
||||
<Card>
|
||||
|
||||
551
src/app/(admin)/admin/messages/page.tsx
Normal file
551
src/app/(admin)/admin/messages/page.tsx
Normal file
@@ -0,0 +1,551 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { trpc } from '@/lib/trpc/client'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from '@/components/ui/tabs'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import {
|
||||
Send,
|
||||
Mail,
|
||||
Bell,
|
||||
Clock,
|
||||
Loader2,
|
||||
LayoutTemplate,
|
||||
AlertCircle,
|
||||
Inbox,
|
||||
CheckCircle2,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
|
||||
type RecipientType = 'ALL' | 'ROLE' | 'ROUND_JURY' | 'PROGRAM_TEAM' | 'USER'
|
||||
|
||||
const RECIPIENT_TYPE_OPTIONS: { value: RecipientType; label: string }[] = [
|
||||
{ value: 'ALL', label: 'All Users' },
|
||||
{ value: 'ROLE', label: 'By Role' },
|
||||
{ value: 'ROUND_JURY', label: 'Round Jury' },
|
||||
{ value: 'PROGRAM_TEAM', label: 'Program Team' },
|
||||
{ value: 'USER', label: 'Specific User' },
|
||||
]
|
||||
|
||||
const ROLES = ['JURY_MEMBER', 'MENTOR', 'OBSERVER', 'APPLICANT', 'PROGRAM_ADMIN']
|
||||
|
||||
export default function MessagesPage() {
|
||||
const [recipientType, setRecipientType] = useState<RecipientType>('ALL')
|
||||
const [selectedRole, setSelectedRole] = useState('')
|
||||
const [roundId, setRoundId] = useState('')
|
||||
const [selectedProgramId, setSelectedProgramId] = useState('')
|
||||
const [selectedUserId, setSelectedUserId] = useState('')
|
||||
const [subject, setSubject] = useState('')
|
||||
const [body, setBody] = useState('')
|
||||
const [selectedTemplateId, setSelectedTemplateId] = useState('')
|
||||
const [deliveryChannels, setDeliveryChannels] = useState<string[]>(['EMAIL', 'IN_APP'])
|
||||
const [isScheduled, setIsScheduled] = useState(false)
|
||||
const [scheduledAt, setScheduledAt] = useState('')
|
||||
|
||||
const utils = trpc.useUtils()
|
||||
|
||||
// Fetch supporting data
|
||||
const { data: rounds } = trpc.round.listAll.useQuery()
|
||||
const { data: programs } = trpc.program.list.useQuery()
|
||||
const { data: templates } = trpc.message.listTemplates.useQuery()
|
||||
const { data: users } = trpc.user.list.useQuery(
|
||||
{ page: 1, perPage: 100 },
|
||||
{ enabled: recipientType === 'USER' }
|
||||
)
|
||||
|
||||
// Fetch sent messages for history
|
||||
const { data: sentMessages, isLoading: loadingSent } = trpc.message.inbox.useQuery(
|
||||
{ page: 1, pageSize: 50 }
|
||||
)
|
||||
|
||||
const sendMutation = trpc.message.send.useMutation({
|
||||
onSuccess: (data) => {
|
||||
const count = (data as Record<string, unknown>)?.recipientCount || ''
|
||||
toast.success(`Message sent successfully${count ? ` to ${count} recipients` : ''}`)
|
||||
resetForm()
|
||||
utils.message.inbox.invalidate()
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const resetForm = () => {
|
||||
setSubject('')
|
||||
setBody('')
|
||||
setSelectedTemplateId('')
|
||||
setSelectedRole('')
|
||||
setRoundId('')
|
||||
setSelectedProgramId('')
|
||||
setSelectedUserId('')
|
||||
setIsScheduled(false)
|
||||
setScheduledAt('')
|
||||
}
|
||||
|
||||
const handleTemplateSelect = (templateId: string) => {
|
||||
setSelectedTemplateId(templateId)
|
||||
if (templateId && templateId !== '__none__' && templates) {
|
||||
const template = (templates as Array<Record<string, unknown>>).find(
|
||||
(t) => String(t.id) === templateId
|
||||
)
|
||||
if (template) {
|
||||
setSubject(String(template.subject || ''))
|
||||
setBody(String(template.body || ''))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const toggleChannel = (channel: string) => {
|
||||
setDeliveryChannels((prev) =>
|
||||
prev.includes(channel)
|
||||
? prev.filter((c) => c !== channel)
|
||||
: [...prev, channel]
|
||||
)
|
||||
}
|
||||
|
||||
const buildRecipientFilter = (): unknown => {
|
||||
switch (recipientType) {
|
||||
case 'ROLE':
|
||||
return selectedRole ? { role: selectedRole } : undefined
|
||||
case 'USER':
|
||||
return selectedUserId ? { userId: selectedUserId } : undefined
|
||||
case 'PROGRAM_TEAM':
|
||||
return selectedProgramId ? { programId: selectedProgramId } : undefined
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
const handleSend = () => {
|
||||
if (!subject.trim()) {
|
||||
toast.error('Subject is required')
|
||||
return
|
||||
}
|
||||
if (!body.trim()) {
|
||||
toast.error('Message body is required')
|
||||
return
|
||||
}
|
||||
if (deliveryChannels.length === 0) {
|
||||
toast.error('Select at least one delivery channel')
|
||||
return
|
||||
}
|
||||
if (recipientType === 'ROLE' && !selectedRole) {
|
||||
toast.error('Please select a role')
|
||||
return
|
||||
}
|
||||
if (recipientType === 'ROUND_JURY' && !roundId) {
|
||||
toast.error('Please select a round')
|
||||
return
|
||||
}
|
||||
if (recipientType === 'PROGRAM_TEAM' && !selectedProgramId) {
|
||||
toast.error('Please select a program')
|
||||
return
|
||||
}
|
||||
if (recipientType === 'USER' && !selectedUserId) {
|
||||
toast.error('Please select a user')
|
||||
return
|
||||
}
|
||||
|
||||
sendMutation.mutate({
|
||||
recipientType,
|
||||
recipientFilter: buildRecipientFilter(),
|
||||
roundId: roundId || undefined,
|
||||
subject: subject.trim(),
|
||||
body: body.trim(),
|
||||
deliveryChannels,
|
||||
scheduledAt: isScheduled && scheduledAt ? new Date(scheduledAt).toISOString() : undefined,
|
||||
templateId: selectedTemplateId && selectedTemplateId !== '__none__' ? selectedTemplateId : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">Communication Hub</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Send messages and notifications to platform users
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/admin/messages/templates">
|
||||
<LayoutTemplate className="mr-2 h-4 w-4" />
|
||||
Templates
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="compose">
|
||||
<TabsList>
|
||||
<TabsTrigger value="compose">
|
||||
<Send className="mr-2 h-4 w-4" />
|
||||
Compose
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="history">
|
||||
<Inbox className="mr-2 h-4 w-4" />
|
||||
Sent History
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="compose" className="space-y-4 mt-4">
|
||||
{/* Compose Form */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Compose Message</CardTitle>
|
||||
<CardDescription>
|
||||
Send a message via email, in-app notifications, or both
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Recipient type */}
|
||||
<div className="space-y-2">
|
||||
<Label>Recipient Type</Label>
|
||||
<Select
|
||||
value={recipientType}
|
||||
onValueChange={(v) => {
|
||||
setRecipientType(v as RecipientType)
|
||||
setSelectedRole('')
|
||||
setRoundId('')
|
||||
setSelectedProgramId('')
|
||||
setSelectedUserId('')
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{RECIPIENT_TYPE_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Conditional sub-filters */}
|
||||
{recipientType === 'ROLE' && (
|
||||
<div className="space-y-2">
|
||||
<Label>Select Role</Label>
|
||||
<Select value={selectedRole} onValueChange={setSelectedRole}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Choose a role..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ROLES.map((role) => (
|
||||
<SelectItem key={role} value={role}>
|
||||
{role.replace(/_/g, ' ')}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{recipientType === 'ROUND_JURY' && (
|
||||
<div className="space-y-2">
|
||||
<Label>Select Round</Label>
|
||||
<Select value={roundId} onValueChange={setRoundId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Choose a round..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(rounds as Array<{ id: string; name: string; program?: { name: string } }> | undefined)?.map((round) => (
|
||||
<SelectItem key={round.id} value={round.id}>
|
||||
{round.program ? `${round.program.name} - ${round.name}` : round.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{recipientType === 'PROGRAM_TEAM' && (
|
||||
<div className="space-y-2">
|
||||
<Label>Select Program</Label>
|
||||
<Select value={selectedProgramId} onValueChange={setSelectedProgramId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Choose a program..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(programs as Array<{ id: string; name: string }> | undefined)?.map((prog) => (
|
||||
<SelectItem key={prog.id} value={prog.id}>
|
||||
{prog.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{recipientType === 'USER' && (
|
||||
<div className="space-y-2">
|
||||
<Label>Select User</Label>
|
||||
<Select value={selectedUserId} onValueChange={setSelectedUserId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Choose a user..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(users as { users: Array<{ id: string; name: string | null; email: string }> } | undefined)?.users?.map((u) => (
|
||||
<SelectItem key={u.id} value={u.id}>
|
||||
{u.name || u.email}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{recipientType === 'ALL' && (
|
||||
<div className="flex items-center gap-2 rounded-lg bg-amber-500/10 p-3 text-amber-700">
|
||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
||||
<p className="text-sm">
|
||||
This message will be sent to all platform users.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Template selector */}
|
||||
{templates && (templates as unknown[]).length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<Label>Template (optional)</Label>
|
||||
<Select value={selectedTemplateId} onValueChange={handleTemplateSelect}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Load from template..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__none__">No template</SelectItem>
|
||||
{(templates as Array<Record<string, unknown>>).map((t) => (
|
||||
<SelectItem key={String(t.id)} value={String(t.id)}>
|
||||
{String(t.name)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Subject */}
|
||||
<div className="space-y-2">
|
||||
<Label>Subject</Label>
|
||||
<Input
|
||||
placeholder="Message subject..."
|
||||
value={subject}
|
||||
onChange={(e) => setSubject(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>Message Body</Label>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Variables: {'{{projectName}}'}, {'{{userName}}'}, {'{{deadline}}'}, {'{{roundName}}'}, {'{{programName}}'}
|
||||
</span>
|
||||
</div>
|
||||
<Textarea
|
||||
placeholder="Write your message..."
|
||||
value={body}
|
||||
onChange={(e) => setBody(e.target.value)}
|
||||
rows={6}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Delivery channels */}
|
||||
<div className="space-y-2">
|
||||
<Label>Delivery Channels</Label>
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="channel-email"
|
||||
checked={deliveryChannels.includes('EMAIL')}
|
||||
onCheckedChange={() => toggleChannel('EMAIL')}
|
||||
/>
|
||||
<label htmlFor="channel-email" className="text-sm cursor-pointer flex items-center gap-1">
|
||||
<Mail className="h-3 w-3" />
|
||||
Email
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="channel-inapp"
|
||||
checked={deliveryChannels.includes('IN_APP')}
|
||||
onCheckedChange={() => toggleChannel('IN_APP')}
|
||||
/>
|
||||
<label htmlFor="channel-inapp" className="text-sm cursor-pointer flex items-center gap-1">
|
||||
<Bell className="h-3 w-3" />
|
||||
In-App
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Schedule */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="schedule-toggle"
|
||||
checked={isScheduled}
|
||||
onCheckedChange={setIsScheduled}
|
||||
/>
|
||||
<label htmlFor="schedule-toggle" className="text-sm cursor-pointer flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
Schedule for later
|
||||
</label>
|
||||
</div>
|
||||
{isScheduled && (
|
||||
<Input
|
||||
type="datetime-local"
|
||||
value={scheduledAt}
|
||||
onChange={(e) => setScheduledAt(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Send button */}
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={handleSend} disabled={sendMutation.isPending}>
|
||||
{sendMutation.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Send className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{isScheduled ? 'Schedule' : 'Send Message'}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="history" className="mt-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Sent Messages</CardTitle>
|
||||
<CardDescription>
|
||||
Recent messages sent through the platform
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingSent ? (
|
||||
<div className="space-y-3">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<div key={i} className="flex items-center gap-4">
|
||||
<Skeleton className="h-4 w-48" />
|
||||
<Skeleton className="h-6 w-24" />
|
||||
<Skeleton className="h-4 w-32 ml-auto" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : sentMessages && sentMessages.items.length > 0 ? (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Subject</TableHead>
|
||||
<TableHead className="hidden md:table-cell">From</TableHead>
|
||||
<TableHead className="hidden md:table-cell">Channel</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">Status</TableHead>
|
||||
<TableHead className="text-right">Date</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sentMessages.items.map((item: Record<string, unknown>) => {
|
||||
const msg = item.message as Record<string, unknown> | undefined
|
||||
const sender = msg?.sender as Record<string, unknown> | undefined
|
||||
const channel = String(item.channel || 'EMAIL')
|
||||
const isRead = !!item.isRead
|
||||
|
||||
return (
|
||||
<TableRow key={String(item.id)}>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
{!isRead && (
|
||||
<div className="h-2 w-2 rounded-full bg-primary shrink-0" />
|
||||
)}
|
||||
<span className={isRead ? 'text-muted-foreground' : 'font-medium'}>
|
||||
{String(msg?.subject || 'No subject')}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="hidden md:table-cell text-sm text-muted-foreground">
|
||||
{String(sender?.name || sender?.email || 'System')}
|
||||
</TableCell>
|
||||
<TableCell className="hidden md:table-cell">
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{channel === 'EMAIL' ? (
|
||||
<><Mail className="mr-1 h-3 w-3" />Email</>
|
||||
) : (
|
||||
<><Bell className="mr-1 h-3 w-3" />In-App</>
|
||||
)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="hidden lg:table-cell">
|
||||
{isRead ? (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
<CheckCircle2 className="mr-1 h-3 w-3" />
|
||||
Read
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="default" className="text-xs">New</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right text-sm text-muted-foreground">
|
||||
{msg?.createdAt
|
||||
? formatDate(msg.createdAt as string | Date)
|
||||
: ''}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<Inbox className="h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="mt-2 font-medium">No messages yet</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sent messages will appear here.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
472
src/app/(admin)/admin/messages/templates/page.tsx
Normal file
472
src/app/(admin)/admin/messages/templates/page.tsx
Normal file
@@ -0,0 +1,472 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { trpc } from '@/lib/trpc/client'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Plus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Loader2,
|
||||
LayoutTemplate,
|
||||
Eye,
|
||||
Variable,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
const AVAILABLE_VARIABLES = [
|
||||
{ name: '{{projectName}}', desc: 'Project title' },
|
||||
{ name: '{{userName}}', desc: "Recipient's name" },
|
||||
{ name: '{{deadline}}', desc: 'Deadline date' },
|
||||
{ name: '{{roundName}}', desc: 'Round name' },
|
||||
{ name: '{{programName}}', desc: 'Program name' },
|
||||
]
|
||||
|
||||
interface TemplateFormData {
|
||||
name: string
|
||||
category: string
|
||||
subject: string
|
||||
body: string
|
||||
variables: string[]
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
const defaultForm: TemplateFormData = {
|
||||
name: '',
|
||||
category: '',
|
||||
subject: '',
|
||||
body: '',
|
||||
variables: [],
|
||||
isActive: true,
|
||||
}
|
||||
|
||||
export default function MessageTemplatesPage() {
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null)
|
||||
const [formData, setFormData] = useState<TemplateFormData>(defaultForm)
|
||||
const [showPreview, setShowPreview] = useState(false)
|
||||
|
||||
const utils = trpc.useUtils()
|
||||
|
||||
const { data: templates, isLoading } = trpc.message.listTemplates.useQuery()
|
||||
|
||||
const createMutation = trpc.message.createTemplate.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.message.listTemplates.invalidate()
|
||||
toast.success('Template created')
|
||||
closeDialog()
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const updateMutation = trpc.message.updateTemplate.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.message.listTemplates.invalidate()
|
||||
toast.success('Template updated')
|
||||
closeDialog()
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const deleteMutation = trpc.message.deleteTemplate.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.message.listTemplates.invalidate()
|
||||
toast.success('Template deleted')
|
||||
setDeleteId(null)
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const closeDialog = () => {
|
||||
setDialogOpen(false)
|
||||
setEditingId(null)
|
||||
setFormData(defaultForm)
|
||||
setShowPreview(false)
|
||||
}
|
||||
|
||||
const openEdit = (template: Record<string, unknown>) => {
|
||||
setEditingId(String(template.id))
|
||||
setFormData({
|
||||
name: String(template.name || ''),
|
||||
category: String(template.category || ''),
|
||||
subject: String(template.subject || ''),
|
||||
body: String(template.body || ''),
|
||||
variables: Array.isArray(template.variables) ? template.variables.map(String) : [],
|
||||
isActive: template.isActive !== false,
|
||||
})
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
const insertVariable = (variable: string) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
body: prev.body + variable,
|
||||
}))
|
||||
}
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!formData.name.trim() || !formData.subject.trim()) {
|
||||
toast.error('Name and subject are required')
|
||||
return
|
||||
}
|
||||
|
||||
const payload = {
|
||||
name: formData.name.trim(),
|
||||
category: formData.category.trim() || 'General',
|
||||
subject: formData.subject.trim(),
|
||||
body: formData.body.trim(),
|
||||
variables: formData.variables.length > 0 ? formData.variables : undefined,
|
||||
}
|
||||
|
||||
if (editingId) {
|
||||
updateMutation.mutate({ id: editingId, ...payload, isActive: formData.isActive })
|
||||
} else {
|
||||
createMutation.mutate(payload)
|
||||
}
|
||||
}
|
||||
|
||||
const getPreviewText = (text: string): string => {
|
||||
return text
|
||||
.replace(/\{\{userName\}\}/g, 'John Doe')
|
||||
.replace(/\{\{projectName\}\}/g, 'Ocean Cleanup Initiative')
|
||||
.replace(/\{\{roundName\}\}/g, 'Round 1 - Semi-Finals')
|
||||
.replace(/\{\{programName\}\}/g, 'MOPC 2026')
|
||||
.replace(/\{\{deadline\}\}/g, 'March 15, 2026')
|
||||
}
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" asChild className="-ml-4">
|
||||
<Link href="/admin/messages">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back to Messages
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">Message Templates</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Create and manage reusable message templates
|
||||
</p>
|
||||
</div>
|
||||
<Dialog open={dialogOpen} onOpenChange={(open) => !open && closeDialog()}>
|
||||
<DialogTrigger asChild>
|
||||
<Button onClick={() => { setFormData(defaultForm); setEditingId(null); setDialogOpen(true) }}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create Template
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingId ? 'Edit Template' : 'Create Template'}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Define a reusable message template with variable placeholders.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label>Template Name</Label>
|
||||
<Input
|
||||
placeholder="e.g., Evaluation Reminder"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Category</Label>
|
||||
<Input
|
||||
placeholder="e.g., Notification, Reminder"
|
||||
value={formData.category}
|
||||
onChange={(e) => setFormData({ ...formData, category: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Subject</Label>
|
||||
<Input
|
||||
placeholder="e.g., Reminder: {{roundName}} evaluation deadline"
|
||||
value={formData.subject}
|
||||
onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>Message Body</Label>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowPreview(!showPreview)}
|
||||
>
|
||||
<Eye className="mr-1 h-3 w-3" />
|
||||
{showPreview ? 'Edit' : 'Preview'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showPreview ? (
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-sm font-medium mb-2">
|
||||
Subject: {getPreviewText(formData.subject)}
|
||||
</p>
|
||||
<div className="text-sm whitespace-pre-wrap border-t pt-2">
|
||||
{getPreviewText(formData.body) || 'No content yet'}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Textarea
|
||||
placeholder="Write your template message..."
|
||||
value={formData.body}
|
||||
onChange={(e) => setFormData({ ...formData, body: e.target.value })}
|
||||
rows={8}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Variable buttons */}
|
||||
{!showPreview && (
|
||||
<div className="space-y-2">
|
||||
<Label className="flex items-center gap-1">
|
||||
<Variable className="h-3 w-3" />
|
||||
Insert Variable
|
||||
</Label>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{AVAILABLE_VARIABLES.map((v) => (
|
||||
<Button
|
||||
key={v.name}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-xs"
|
||||
onClick={() => insertVariable(v.name)}
|
||||
title={v.desc}
|
||||
>
|
||||
{v.name}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editingId && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="template-active"
|
||||
checked={formData.isActive}
|
||||
onCheckedChange={(checked) =>
|
||||
setFormData({ ...formData, isActive: checked })
|
||||
}
|
||||
/>
|
||||
<label htmlFor="template-active" className="text-sm cursor-pointer">
|
||||
Active
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={closeDialog}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={isPending}>
|
||||
{isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{editingId ? 'Update' : 'Create'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{/* Variable reference panel */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Variable className="h-4 w-4" />
|
||||
Available Template Variables
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{AVAILABLE_VARIABLES.map((v) => (
|
||||
<div key={v.name} className="flex items-center gap-2">
|
||||
<code className="text-xs bg-muted rounded px-2 py-1 font-mono">
|
||||
{v.name}
|
||||
</code>
|
||||
<span className="text-xs text-muted-foreground">{v.desc}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Templates list */}
|
||||
{isLoading ? (
|
||||
<TemplatesSkeleton />
|
||||
) : templates && (templates as unknown[]).length > 0 ? (
|
||||
<Card>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead className="hidden md:table-cell">Category</TableHead>
|
||||
<TableHead className="hidden md:table-cell">Subject</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">Status</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{(templates as Array<Record<string, unknown>>).map((template) => (
|
||||
<TableRow key={String(template.id)}>
|
||||
<TableCell className="font-medium">
|
||||
{String(template.name)}
|
||||
</TableCell>
|
||||
<TableCell className="hidden md:table-cell">
|
||||
{template.category ? (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{String(template.category)}
|
||||
</Badge>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">--</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="hidden md:table-cell text-sm text-muted-foreground truncate max-w-[200px]">
|
||||
{String(template.subject || '')}
|
||||
</TableCell>
|
||||
<TableCell className="hidden lg:table-cell">
|
||||
{template.isActive !== false ? (
|
||||
<Badge variant="default" className="text-xs">Active</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs">Inactive</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => openEdit(template)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setDeleteId(String(template.id))}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<LayoutTemplate className="h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="mt-2 font-medium">No templates yet</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Create a template to speed up message composition.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Delete confirmation */}
|
||||
<AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Template</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete this template? This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => deleteId && deleteMutation.mutate({ id: deleteId })}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleteMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TemplatesSkeleton() {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="space-y-4">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<div key={i} className="flex items-center gap-4">
|
||||
<Skeleton className="h-4 w-40" />
|
||||
<Skeleton className="h-6 w-24" />
|
||||
<Skeleton className="h-4 w-48" />
|
||||
<Skeleton className="h-8 w-16 ml-auto" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
433
src/app/(admin)/admin/programs/[id]/mentorship/page.tsx
Normal file
433
src/app/(admin)/admin/programs/[id]/mentorship/page.tsx
Normal file
@@ -0,0 +1,433 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useParams } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { trpc } from '@/lib/trpc/client'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Plus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Loader2,
|
||||
ChevronUp,
|
||||
ChevronDown,
|
||||
Target,
|
||||
Calendar,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
interface MilestoneFormData {
|
||||
name: string
|
||||
description: string
|
||||
isRequired: boolean
|
||||
deadlineOffsetDays: number
|
||||
sortOrder: number
|
||||
}
|
||||
|
||||
const defaultMilestoneForm: MilestoneFormData = {
|
||||
name: '',
|
||||
description: '',
|
||||
isRequired: false,
|
||||
deadlineOffsetDays: 30,
|
||||
sortOrder: 0,
|
||||
}
|
||||
|
||||
export default function MentorshipMilestonesPage() {
|
||||
const params = useParams()
|
||||
const programId = params.id as string
|
||||
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null)
|
||||
const [formData, setFormData] = useState<MilestoneFormData>(defaultMilestoneForm)
|
||||
|
||||
const utils = trpc.useUtils()
|
||||
|
||||
const { data: milestones, isLoading } = trpc.mentor.getMilestones.useQuery({ programId })
|
||||
|
||||
const createMutation = trpc.mentor.createMilestone.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.mentor.getMilestones.invalidate({ programId })
|
||||
toast.success('Milestone created')
|
||||
closeDialog()
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const updateMutation = trpc.mentor.updateMilestone.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.mentor.getMilestones.invalidate({ programId })
|
||||
toast.success('Milestone updated')
|
||||
closeDialog()
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const deleteMutation = trpc.mentor.deleteMilestone.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.mentor.getMilestones.invalidate({ programId })
|
||||
toast.success('Milestone deleted')
|
||||
setDeleteId(null)
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const reorderMutation = trpc.mentor.reorderMilestones.useMutation({
|
||||
onSuccess: () => utils.mentor.getMilestones.invalidate({ programId }),
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const closeDialog = () => {
|
||||
setDialogOpen(false)
|
||||
setEditingId(null)
|
||||
setFormData(defaultMilestoneForm)
|
||||
}
|
||||
|
||||
const openEdit = (milestone: Record<string, unknown>) => {
|
||||
setEditingId(String(milestone.id))
|
||||
setFormData({
|
||||
name: String(milestone.name || ''),
|
||||
description: String(milestone.description || ''),
|
||||
isRequired: Boolean(milestone.isRequired),
|
||||
deadlineOffsetDays: Number(milestone.deadlineOffsetDays || 30),
|
||||
sortOrder: Number(milestone.sortOrder || 0),
|
||||
})
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
const openCreate = () => {
|
||||
const nextOrder = milestones ? (milestones as unknown[]).length : 0
|
||||
setFormData({ ...defaultMilestoneForm, sortOrder: nextOrder })
|
||||
setEditingId(null)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!formData.name.trim()) {
|
||||
toast.error('Milestone name is required')
|
||||
return
|
||||
}
|
||||
|
||||
if (editingId) {
|
||||
updateMutation.mutate({
|
||||
milestoneId: editingId,
|
||||
name: formData.name.trim(),
|
||||
description: formData.description.trim() || undefined,
|
||||
isRequired: formData.isRequired,
|
||||
deadlineOffsetDays: formData.deadlineOffsetDays,
|
||||
sortOrder: formData.sortOrder,
|
||||
})
|
||||
} else {
|
||||
createMutation.mutate({
|
||||
programId,
|
||||
name: formData.name.trim(),
|
||||
description: formData.description.trim() || undefined,
|
||||
isRequired: formData.isRequired,
|
||||
deadlineOffsetDays: formData.deadlineOffsetDays,
|
||||
sortOrder: formData.sortOrder,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const moveMilestone = (id: string, direction: 'up' | 'down') => {
|
||||
if (!milestones) return
|
||||
const list = milestones as Array<Record<string, unknown>>
|
||||
const index = list.findIndex((m) => String(m.id) === id)
|
||||
if (index === -1) return
|
||||
if (direction === 'up' && index === 0) return
|
||||
if (direction === 'down' && index === list.length - 1) return
|
||||
|
||||
const ids = list.map((m) => String(m.id))
|
||||
const [moved] = ids.splice(index, 1)
|
||||
ids.splice(direction === 'up' ? index - 1 : index + 1, 0, moved)
|
||||
|
||||
reorderMutation.mutate({ milestoneIds: ids })
|
||||
}
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" asChild className="-ml-4">
|
||||
<Link href="/admin/programs">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back to Programs
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">
|
||||
Mentorship Milestones
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Configure milestones for the mentorship program
|
||||
</p>
|
||||
</div>
|
||||
<Dialog open={dialogOpen} onOpenChange={(open) => !open && closeDialog()}>
|
||||
<DialogTrigger asChild>
|
||||
<Button onClick={openCreate}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Milestone
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingId ? 'Edit Milestone' : 'Add Milestone'}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure a milestone for the mentorship program.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Name</Label>
|
||||
<Input
|
||||
placeholder="e.g., Business Plan Review"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Description</Label>
|
||||
<Textarea
|
||||
placeholder="Describe what this milestone involves..."
|
||||
value={formData.description}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, description: e.target.value })
|
||||
}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="milestone-required"
|
||||
checked={formData.isRequired}
|
||||
onCheckedChange={(checked) =>
|
||||
setFormData({ ...formData, isRequired: !!checked })
|
||||
}
|
||||
/>
|
||||
<label htmlFor="milestone-required" className="text-sm cursor-pointer">
|
||||
Required milestone
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Deadline Offset (days from program start)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={365}
|
||||
value={formData.deadlineOffsetDays}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
deadlineOffsetDays: parseInt(e.target.value) || 30,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={closeDialog}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={isPending}>
|
||||
{isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{editingId ? 'Update' : 'Create'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{/* Milestones list */}
|
||||
{isLoading ? (
|
||||
<MilestonesSkeleton />
|
||||
) : milestones && (milestones as unknown[]).length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{(milestones as Array<Record<string, unknown>>).map((milestone, index) => {
|
||||
const completions = milestone.completions as Array<unknown> | undefined
|
||||
const completionCount = completions ? completions.length : 0
|
||||
|
||||
return (
|
||||
<Card key={String(milestone.id)}>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Order number and reorder buttons */}
|
||||
<div className="flex flex-col items-center gap-0.5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-5 w-5"
|
||||
disabled={index === 0 || reorderMutation.isPending}
|
||||
onClick={() => moveMilestone(String(milestone.id), 'up')}
|
||||
>
|
||||
<ChevronUp className="h-3 w-3" />
|
||||
</Button>
|
||||
<span className="text-xs font-medium text-muted-foreground w-5 text-center">
|
||||
{index + 1}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-5 w-5"
|
||||
disabled={
|
||||
index === (milestones as unknown[]).length - 1 ||
|
||||
reorderMutation.isPending
|
||||
}
|
||||
onClick={() => moveMilestone(String(milestone.id), 'down')}
|
||||
>
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-medium">{String(milestone.name)}</span>
|
||||
{!!milestone.isRequired && (
|
||||
<Badge variant="default" className="text-xs">Required</Badge>
|
||||
)}
|
||||
<Badge variant="outline" className="text-xs">
|
||||
<Calendar className="mr-1 h-3 w-3" />
|
||||
Day {String(milestone.deadlineOffsetDays || 30)}
|
||||
</Badge>
|
||||
{completionCount > 0 && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{completionCount} completions
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{!!milestone.description && (
|
||||
<p className="text-sm text-muted-foreground mt-1 line-clamp-2">
|
||||
{String(milestone.description)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => openEdit(milestone)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setDeleteId(String(milestone.id))}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<Target className="h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="mt-2 font-medium">No milestones defined</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Add milestones to track mentor-mentee progress.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Delete confirmation */}
|
||||
<AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Milestone</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete this milestone? Progress data associated
|
||||
with it may be lost.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() =>
|
||||
deleteId && deleteMutation.mutate({ milestoneId: deleteId })
|
||||
}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleteMutation.isPending && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function MilestonesSkeleton() {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Card key={i}>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Skeleton className="h-16 w-6" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-5 w-48" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-16" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -494,6 +494,7 @@ function ProjectDetailContent({ projectId }: { projectId: string }) {
|
||||
<CardContent className="space-y-4">
|
||||
{files && files.length > 0 ? (
|
||||
<FileViewer
|
||||
projectId={projectId}
|
||||
files={files.map((f) => ({
|
||||
id: f.id,
|
||||
fileName: f.fileName,
|
||||
@@ -502,6 +503,7 @@ function ProjectDetailContent({ projectId }: { projectId: string }) {
|
||||
size: f.size,
|
||||
bucket: f.bucket,
|
||||
objectKey: f.objectKey,
|
||||
version: f.version,
|
||||
}))}
|
||||
/>
|
||||
) : (
|
||||
|
||||
@@ -39,6 +39,10 @@ import {
|
||||
CheckCircle2,
|
||||
PieChart,
|
||||
TrendingUp,
|
||||
GitCompare,
|
||||
UserCheck,
|
||||
Globe,
|
||||
Printer,
|
||||
} from 'lucide-react'
|
||||
import { formatDateOnly } from '@/lib/utils'
|
||||
import {
|
||||
@@ -49,6 +53,9 @@ import {
|
||||
ProjectRankingsChart,
|
||||
CriteriaScoresChart,
|
||||
GeographicDistribution,
|
||||
CrossRoundComparisonChart,
|
||||
JurorConsistencyChart,
|
||||
DiversityMetricsChart,
|
||||
} from '@/components/charts'
|
||||
|
||||
function ReportsOverview() {
|
||||
@@ -414,6 +421,215 @@ function RoundAnalytics() {
|
||||
)
|
||||
}
|
||||
|
||||
function CrossRoundTab() {
|
||||
const { data: programs, isLoading: programsLoading } = trpc.program.list.useQuery({ includeRounds: true })
|
||||
|
||||
const rounds = programs?.flatMap(p =>
|
||||
p.rounds.map(r => ({ id: r.id, name: r.name, programName: `${p.year} Edition` }))
|
||||
) || []
|
||||
|
||||
const [selectedRoundIds, setSelectedRoundIds] = useState<string[]>([])
|
||||
|
||||
const { data: comparison, isLoading: comparisonLoading } =
|
||||
trpc.analytics.getCrossRoundComparison.useQuery(
|
||||
{ roundIds: selectedRoundIds },
|
||||
{ enabled: selectedRoundIds.length >= 2 }
|
||||
)
|
||||
|
||||
const toggleRound = (roundId: string) => {
|
||||
setSelectedRoundIds((prev) =>
|
||||
prev.includes(roundId)
|
||||
? prev.filter((id) => id !== roundId)
|
||||
: [...prev, roundId]
|
||||
)
|
||||
}
|
||||
|
||||
if (programsLoading) {
|
||||
return <Skeleton className="h-[400px]" />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Round selector */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Select Rounds to Compare</CardTitle>
|
||||
<CardDescription>
|
||||
Choose at least 2 rounds to compare metrics side by side
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{rounds.map((round) => {
|
||||
const isSelected = selectedRoundIds.includes(round.id)
|
||||
return (
|
||||
<Badge
|
||||
key={round.id}
|
||||
variant={isSelected ? 'default' : 'outline'}
|
||||
className="cursor-pointer text-sm py-1.5 px-3"
|
||||
onClick={() => toggleRound(round.id)}
|
||||
>
|
||||
{round.programName} - {round.name}
|
||||
</Badge>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{selectedRoundIds.length < 2 && (
|
||||
<p className="text-sm text-muted-foreground mt-3">
|
||||
Select at least 2 rounds to enable comparison
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Comparison charts */}
|
||||
{comparisonLoading && selectedRoundIds.length >= 2 && (
|
||||
<div className="space-y-6">
|
||||
<Skeleton className="h-[350px]" />
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<Skeleton className="h-[300px]" />
|
||||
<Skeleton className="h-[300px]" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{comparison && (
|
||||
<CrossRoundComparisonChart data={comparison as Array<{
|
||||
roundId: string
|
||||
roundName: string
|
||||
projectCount: number
|
||||
evaluationCount: number
|
||||
completionRate: number
|
||||
averageScore: number | null
|
||||
scoreDistribution: { score: number; count: number }[]
|
||||
}>} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function JurorConsistencyTab() {
|
||||
const [selectedRoundId, setSelectedRoundId] = useState<string | null>(null)
|
||||
|
||||
const { data: programs, isLoading: programsLoading } = trpc.program.list.useQuery({ includeRounds: true })
|
||||
|
||||
const rounds = programs?.flatMap(p =>
|
||||
p.rounds.map(r => ({ id: r.id, name: r.name, programName: `${p.year} Edition` }))
|
||||
) || []
|
||||
|
||||
if (rounds.length && !selectedRoundId) {
|
||||
setSelectedRoundId(rounds[0].id)
|
||||
}
|
||||
|
||||
const { data: consistency, isLoading: consistencyLoading } =
|
||||
trpc.analytics.getJurorConsistency.useQuery(
|
||||
{ roundId: selectedRoundId! },
|
||||
{ enabled: !!selectedRoundId }
|
||||
)
|
||||
|
||||
if (programsLoading) {
|
||||
return <Skeleton className="h-[400px]" />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<label className="text-sm font-medium">Select Round:</label>
|
||||
<Select value={selectedRoundId || ''} onValueChange={setSelectedRoundId}>
|
||||
<SelectTrigger className="w-[300px]">
|
||||
<SelectValue placeholder="Select a round" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{rounds.map((round) => (
|
||||
<SelectItem key={round.id} value={round.id}>
|
||||
{round.programName} - {round.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{consistencyLoading && <Skeleton className="h-[400px]" />}
|
||||
|
||||
{consistency && (
|
||||
<JurorConsistencyChart
|
||||
data={consistency as {
|
||||
overallAverage: number
|
||||
jurors: Array<{
|
||||
userId: string
|
||||
name: string
|
||||
email: string
|
||||
evaluationCount: number
|
||||
averageScore: number
|
||||
stddev: number
|
||||
deviationFromOverall: number
|
||||
isOutlier: boolean
|
||||
}>
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DiversityTab() {
|
||||
const [selectedRoundId, setSelectedRoundId] = useState<string | null>(null)
|
||||
|
||||
const { data: programs, isLoading: programsLoading } = trpc.program.list.useQuery({ includeRounds: true })
|
||||
|
||||
const rounds = programs?.flatMap(p =>
|
||||
p.rounds.map(r => ({ id: r.id, name: r.name, programName: `${p.year} Edition` }))
|
||||
) || []
|
||||
|
||||
if (rounds.length && !selectedRoundId) {
|
||||
setSelectedRoundId(rounds[0].id)
|
||||
}
|
||||
|
||||
const { data: diversity, isLoading: diversityLoading } =
|
||||
trpc.analytics.getDiversityMetrics.useQuery(
|
||||
{ roundId: selectedRoundId! },
|
||||
{ enabled: !!selectedRoundId }
|
||||
)
|
||||
|
||||
if (programsLoading) {
|
||||
return <Skeleton className="h-[400px]" />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<label className="text-sm font-medium">Select Round:</label>
|
||||
<Select value={selectedRoundId || ''} onValueChange={setSelectedRoundId}>
|
||||
<SelectTrigger className="w-[300px]">
|
||||
<SelectValue placeholder="Select a round" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{rounds.map((round) => (
|
||||
<SelectItem key={round.id} value={round.id}>
|
||||
{round.programName} - {round.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{diversityLoading && <Skeleton className="h-[400px]" />}
|
||||
|
||||
{diversity && (
|
||||
<DiversityMetricsChart
|
||||
data={diversity as {
|
||||
total: number
|
||||
byCountry: { country: string; count: number; percentage: number }[]
|
||||
byCategory: { category: string; count: number; percentage: number }[]
|
||||
byOceanIssue: { issue: string; count: number; percentage: number }[]
|
||||
byTag: { tag: string; count: number; percentage: number }[]
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function ReportsPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -427,16 +643,40 @@ export default function ReportsPage() {
|
||||
|
||||
{/* Tabs */}
|
||||
<Tabs defaultValue="overview" className="space-y-6">
|
||||
<TabsList>
|
||||
<TabsTrigger value="overview" className="gap-2">
|
||||
<FileSpreadsheet className="h-4 w-4" />
|
||||
Overview
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="analytics" className="gap-2">
|
||||
<TrendingUp className="h-4 w-4" />
|
||||
Analytics
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<div className="flex items-center justify-between flex-wrap gap-4">
|
||||
<TabsList>
|
||||
<TabsTrigger value="overview" className="gap-2">
|
||||
<FileSpreadsheet className="h-4 w-4" />
|
||||
Overview
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="analytics" className="gap-2">
|
||||
<TrendingUp className="h-4 w-4" />
|
||||
Analytics
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="cross-round" className="gap-2">
|
||||
<GitCompare className="h-4 w-4" />
|
||||
Cross-Round
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="consistency" className="gap-2">
|
||||
<UserCheck className="h-4 w-4" />
|
||||
Juror Consistency
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="diversity" className="gap-2">
|
||||
<Globe className="h-4 w-4" />
|
||||
Diversity
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
window.print()
|
||||
}}
|
||||
>
|
||||
<Printer className="mr-2 h-4 w-4" />
|
||||
Export PDF
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<TabsContent value="overview">
|
||||
<ReportsOverview />
|
||||
@@ -445,6 +685,18 @@ export default function ReportsPage() {
|
||||
<TabsContent value="analytics">
|
||||
<RoundAnalytics />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="cross-round">
|
||||
<CrossRoundTab />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="consistency">
|
||||
<JurorConsistencyTab />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="diversity">
|
||||
<DiversityTab />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
|
||||
443
src/app/(admin)/admin/round-templates/[id]/page.tsx
Normal file
443
src/app/(admin)/admin/round-templates/[id]/page.tsx
Normal file
@@ -0,0 +1,443 @@
|
||||
'use client'
|
||||
|
||||
import { use, useState } 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 { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Loader2,
|
||||
Save,
|
||||
Trash2,
|
||||
LayoutTemplate,
|
||||
Plus,
|
||||
X,
|
||||
GripVertical,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
const ROUND_TYPE_LABELS: Record<string, string> = {
|
||||
FILTERING: 'Filtering',
|
||||
EVALUATION: 'Evaluation',
|
||||
LIVE_EVENT: 'Live Event',
|
||||
}
|
||||
|
||||
const CRITERION_TYPES = [
|
||||
{ value: 'numeric', label: 'Numeric (1-10)' },
|
||||
{ value: 'text', label: 'Text' },
|
||||
{ value: 'boolean', label: 'Yes/No' },
|
||||
{ value: 'section_header', label: 'Section Header' },
|
||||
]
|
||||
|
||||
type Criterion = {
|
||||
id: string
|
||||
label: string
|
||||
type: string
|
||||
description?: string
|
||||
weight?: number
|
||||
min?: number
|
||||
max?: number
|
||||
}
|
||||
|
||||
export default function RoundTemplateDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const { id } = use(params)
|
||||
const router = useRouter()
|
||||
const utils = trpc.useUtils()
|
||||
|
||||
const { data: template, isLoading } = trpc.roundTemplate.getById.useQuery({ id })
|
||||
const [name, setName] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [roundType, setRoundType] = useState('EVALUATION')
|
||||
const [criteria, setCriteria] = useState<Criterion[]>([])
|
||||
const [initialized, setInitialized] = useState(false)
|
||||
const [deleteOpen, setDeleteOpen] = useState(false)
|
||||
|
||||
// Initialize form state from loaded data
|
||||
if (template && !initialized) {
|
||||
setName(template.name)
|
||||
setDescription(template.description || '')
|
||||
setRoundType(template.roundType)
|
||||
setCriteria((template.criteriaJson as Criterion[]) || [])
|
||||
setInitialized(true)
|
||||
}
|
||||
|
||||
const updateTemplate = trpc.roundTemplate.update.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.roundTemplate.getById.invalidate({ id })
|
||||
utils.roundTemplate.list.invalidate()
|
||||
toast.success('Template saved')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const deleteTemplate = trpc.roundTemplate.delete.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.roundTemplate.list.invalidate()
|
||||
router.push('/admin/round-templates')
|
||||
toast.success('Template deleted')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const handleSave = () => {
|
||||
updateTemplate.mutate({
|
||||
id,
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
roundType: roundType as 'FILTERING' | 'EVALUATION' | 'LIVE_EVENT',
|
||||
criteriaJson: criteria,
|
||||
})
|
||||
}
|
||||
|
||||
const addCriterion = () => {
|
||||
setCriteria([
|
||||
...criteria,
|
||||
{
|
||||
id: `criterion_${Date.now()}`,
|
||||
label: '',
|
||||
type: 'numeric',
|
||||
weight: 1,
|
||||
min: 1,
|
||||
max: 10,
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
const updateCriterion = (index: number, updates: Partial<Criterion>) => {
|
||||
setCriteria(criteria.map((c, i) => (i === index ? { ...c, ...updates } : c)))
|
||||
}
|
||||
|
||||
const removeCriterion = (index: number) => {
|
||||
setCriteria(criteria.filter((_, i) => i !== index))
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Skeleton className="h-9 w-36" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-8 w-64" />
|
||||
<Skeleton className="h-4 w-96" />
|
||||
</div>
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!template) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Button variant="ghost" asChild className="-ml-4">
|
||||
<Link href="/admin/round-templates">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back to Templates
|
||||
</Link>
|
||||
</Button>
|
||||
<Card>
|
||||
<CardContent className="py-12 text-center">
|
||||
<p className="font-medium">Template not found</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" asChild className="-ml-4">
|
||||
<Link href="/admin/round-templates">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back to Templates
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<LayoutTemplate className="h-7 w-7 text-primary" />
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">
|
||||
{template.name}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Edit template configuration and criteria
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
className="text-destructive"
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={updateTemplate.isPending}>
|
||||
{updateTemplate.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Save Changes
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Basic Info */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Basic Information</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Template Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="e.g., Standard Evaluation Round"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description">Description</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Describe what this template is for..."
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Round Type</Label>
|
||||
<Select value={roundType} onValueChange={setRoundType}>
|
||||
<SelectTrigger className="w-[240px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(ROUND_TYPE_LABELS).map(([value, label]) => (
|
||||
<SelectItem key={value} value={value}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="pt-2 text-sm text-muted-foreground">
|
||||
Created {new Date(template.createdAt).toLocaleDateString()} | Last updated{' '}
|
||||
{new Date(template.updatedAt).toLocaleDateString()}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Criteria */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle className="text-lg">Evaluation Criteria</CardTitle>
|
||||
<CardDescription>
|
||||
Define the criteria jurors will use to evaluate projects
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={addCriterion}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Criterion
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{criteria.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<p>No criteria defined yet.</p>
|
||||
<Button variant="outline" className="mt-3" onClick={addCriterion}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add First Criterion
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{criteria.map((criterion, index) => (
|
||||
<div key={criterion.id}>
|
||||
{index > 0 && <Separator className="mb-4" />}
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="mt-2 text-muted-foreground">
|
||||
<GripVertical className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="flex-1 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div className="sm:col-span-2 lg:col-span-2">
|
||||
<Label className="text-xs text-muted-foreground">Label</Label>
|
||||
<Input
|
||||
value={criterion.label}
|
||||
onChange={(e) =>
|
||||
updateCriterion(index, { label: e.target.value })
|
||||
}
|
||||
placeholder="e.g., Innovation"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground">Type</Label>
|
||||
<Select
|
||||
value={criterion.type}
|
||||
onValueChange={(val) =>
|
||||
updateCriterion(index, { type: val })
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CRITERION_TYPES.map((t) => (
|
||||
<SelectItem key={t.value} value={t.value}>
|
||||
{t.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{criterion.type === 'numeric' && (
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground">Weight</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={10}
|
||||
step={0.1}
|
||||
value={criterion.weight ?? 1}
|
||||
onChange={(e) =>
|
||||
updateCriterion(index, {
|
||||
weight: parseFloat(e.target.value) || 1,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="sm:col-span-2 lg:col-span-4">
|
||||
<Label className="text-xs text-muted-foreground">
|
||||
Description (optional)
|
||||
</Label>
|
||||
<Input
|
||||
value={criterion.description || ''}
|
||||
onChange={(e) =>
|
||||
updateCriterion(index, { description: e.target.value })
|
||||
}
|
||||
placeholder="Help text for jurors..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="mt-5 h-8 w-8 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => removeCriterion(index)}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Template Metadata */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Template Info</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-4 sm:grid-cols-3 text-sm">
|
||||
<div>
|
||||
<p className="text-muted-foreground">Type</p>
|
||||
<Badge variant="secondary" className="mt-1">
|
||||
{ROUND_TYPE_LABELS[template.roundType] || template.roundType}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Criteria Count</p>
|
||||
<p className="font-medium mt-1">{criteria.length}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Has Custom Settings</p>
|
||||
<p className="font-medium mt-1">
|
||||
{template.settingsJson && Object.keys(template.settingsJson as object).length > 0
|
||||
? 'Yes'
|
||||
: 'No'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Delete Dialog */}
|
||||
<Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete Template</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to delete "{template.name}"? This action
|
||||
cannot be undone.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDeleteOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => deleteTemplate.mutate({ id })}
|
||||
disabled={deleteTemplate.isPending}
|
||||
>
|
||||
{deleteTemplate.isPending && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Delete Template
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
302
src/app/(admin)/admin/round-templates/page.tsx
Normal file
302
src/app/(admin)/admin/round-templates/page.tsx
Normal file
@@ -0,0 +1,302 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { trpc } from '@/lib/trpc/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
LayoutTemplate,
|
||||
Plus,
|
||||
Calendar,
|
||||
Settings2,
|
||||
Trash2,
|
||||
Loader2,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
const ROUND_TYPE_LABELS: Record<string, string> = {
|
||||
FILTERING: 'Filtering',
|
||||
EVALUATION: 'Evaluation',
|
||||
LIVE_EVENT: 'Live Event',
|
||||
}
|
||||
|
||||
const ROUND_TYPE_COLORS: Record<string, 'default' | 'secondary' | 'outline'> = {
|
||||
FILTERING: 'secondary',
|
||||
EVALUATION: 'default',
|
||||
LIVE_EVENT: 'outline',
|
||||
}
|
||||
|
||||
export default function RoundTemplatesPage() {
|
||||
const utils = trpc.useUtils()
|
||||
const { data: templates, isLoading } = trpc.roundTemplate.list.useQuery()
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [newName, setNewName] = useState('')
|
||||
const [newDescription, setNewDescription] = useState('')
|
||||
const [newRoundType, setNewRoundType] = useState('EVALUATION')
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null)
|
||||
|
||||
const createTemplate = trpc.roundTemplate.create.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.roundTemplate.list.invalidate()
|
||||
setCreateOpen(false)
|
||||
setNewName('')
|
||||
setNewDescription('')
|
||||
setNewRoundType('EVALUATION')
|
||||
toast.success('Template created')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const deleteTemplate = trpc.roundTemplate.delete.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.roundTemplate.list.invalidate()
|
||||
setDeleteId(null)
|
||||
toast.success('Template deleted')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const handleCreate = () => {
|
||||
if (!newName.trim()) return
|
||||
createTemplate.mutate({
|
||||
name: newName.trim(),
|
||||
description: newDescription.trim() || undefined,
|
||||
roundType: newRoundType as 'FILTERING' | 'EVALUATION' | 'LIVE_EVENT',
|
||||
criteriaJson: [],
|
||||
})
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<Skeleton className="h-9 w-48" />
|
||||
<Skeleton className="h-9 w-40" />
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{[...Array(3)].map((_, i) => (
|
||||
<Skeleton key={i} className="h-40" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">
|
||||
Round Templates
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Save and reuse round configurations across editions
|
||||
</p>
|
||||
</div>
|
||||
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Template
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create Template</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a blank template. You can also save an existing round as a template from the round detail page.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="template-name">Name</Label>
|
||||
<Input
|
||||
id="template-name"
|
||||
placeholder="e.g., Standard Evaluation Round"
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="template-description">Description</Label>
|
||||
<Textarea
|
||||
id="template-description"
|
||||
placeholder="Describe what this template is for..."
|
||||
value={newDescription}
|
||||
onChange={(e) => setNewDescription(e.target.value)}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="template-type">Round Type</Label>
|
||||
<Select value={newRoundType} onValueChange={setNewRoundType}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(ROUND_TYPE_LABELS).map(([value, label]) => (
|
||||
<SelectItem key={value} value={value}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setCreateOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleCreate}
|
||||
disabled={!newName.trim() || createTemplate.isPending}
|
||||
>
|
||||
{createTemplate.isPending && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Create
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{/* Templates Grid */}
|
||||
{templates && templates.length > 0 ? (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{templates.map((template) => {
|
||||
const criteria = (template.criteriaJson as Array<unknown>) || []
|
||||
const hasSettings = template.settingsJson && Object.keys(template.settingsJson as object).length > 0
|
||||
|
||||
return (
|
||||
<Card key={template.id} className="group relative transition-colors hover:bg-muted/50">
|
||||
<Link href={`/admin/round-templates/${template.id}`}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-start justify-between">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<LayoutTemplate className="h-5 w-5 text-primary" />
|
||||
{template.name}
|
||||
</CardTitle>
|
||||
<Badge variant={ROUND_TYPE_COLORS[template.roundType] || 'secondary'}>
|
||||
{ROUND_TYPE_LABELS[template.roundType] || template.roundType}
|
||||
</Badge>
|
||||
</div>
|
||||
{template.description && (
|
||||
<CardDescription className="line-clamp-2">
|
||||
{template.description}
|
||||
</CardDescription>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-4 text-sm text-muted-foreground">
|
||||
<div className="flex items-center gap-1">
|
||||
<Settings2 className="h-4 w-4" />
|
||||
{criteria.length} criteria
|
||||
</div>
|
||||
{hasSettings && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
Custom settings
|
||||
</Badge>
|
||||
)}
|
||||
<div className="flex items-center gap-1 ml-auto">
|
||||
<Calendar className="h-3.5 w-3.5" />
|
||||
{new Date(template.createdAt).toLocaleDateString()}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Link>
|
||||
{/* Delete button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute top-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity h-8 w-8"
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setDeleteId(template.id)
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" />
|
||||
</Button>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<LayoutTemplate className="h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="mt-2 font-medium">No templates yet</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Create a template or save an existing round configuration as a template
|
||||
</p>
|
||||
<Button className="mt-4" onClick={() => setCreateOpen(true)}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create Template
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<Dialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete Template</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to delete this template? This action cannot be undone.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDeleteId(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => deleteId && deleteTemplate.mutate({ id: deleteId })}
|
||||
disabled={deleteTemplate.isPending}
|
||||
>
|
||||
{deleteTemplate.isPending && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Delete
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -32,7 +32,10 @@ import {
|
||||
type Criterion,
|
||||
} from '@/components/forms/evaluation-form-builder'
|
||||
import { RoundTypeSettings } from '@/components/forms/round-type-settings'
|
||||
import { ArrowLeft, Loader2, AlertCircle, AlertTriangle, Bell } from 'lucide-react'
|
||||
import { ArrowLeft, Loader2, AlertCircle, AlertTriangle, Bell, GitCompare, MessageSquare, FileText, Calendar } from 'lucide-react'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Slider } from '@/components/ui/slider'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { DateTimePicker } from '@/components/ui/datetime-picker'
|
||||
import {
|
||||
Select,
|
||||
@@ -458,6 +461,321 @@ function EditRoundContent({ roundId }: { roundId: string }) {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Jury Features */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<GitCompare className="h-5 w-5" />
|
||||
Jury Features
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Configure project comparison and peer review for jury members
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Comparison settings */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-sm font-medium">Enable Project Comparison</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Allow jury members to compare projects side by side
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={Boolean(roundSettings.enable_comparison)}
|
||||
onCheckedChange={(checked) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
enable_comparison: checked,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{!!roundSettings.enable_comparison && (
|
||||
<div className="space-y-2 pl-4 border-l-2 border-muted">
|
||||
<Label className="text-sm">Max Projects to Compare</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={2}
|
||||
max={5}
|
||||
value={Number(roundSettings.comparison_max_projects || 3)}
|
||||
onChange={(e) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
comparison_max_projects: parseInt(e.target.value) || 3,
|
||||
}))
|
||||
}
|
||||
className="max-w-[120px]"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Peer review settings */}
|
||||
<div className="border-t pt-4 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-sm font-medium flex items-center gap-1">
|
||||
<MessageSquare className="h-4 w-4" />
|
||||
Enable Peer Review / Discussion
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Allow jury members to discuss and see aggregated scores
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={Boolean(roundSettings.peer_review_enabled)}
|
||||
onCheckedChange={(checked) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
peer_review_enabled: checked,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{!!roundSettings.peer_review_enabled && (
|
||||
<div className="space-y-4 pl-4 border-l-2 border-muted">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">Divergence Threshold</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Score divergence level that triggers a warning (0.0 - 1.0)
|
||||
</p>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={Number(roundSettings.divergence_threshold || 0.3)}
|
||||
onChange={(e) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
divergence_threshold: parseFloat(e.target.value) || 0.3,
|
||||
}))
|
||||
}
|
||||
className="max-w-[120px]"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">Anonymization Level</Label>
|
||||
<Select
|
||||
value={String(roundSettings.anonymization_level || 'partial')}
|
||||
onValueChange={(v) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
anonymization_level: v,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="max-w-[200px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">No anonymization</SelectItem>
|
||||
<SelectItem value="partial">Partial (Juror 1, 2...)</SelectItem>
|
||||
<SelectItem value="full">Full anonymization</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">Discussion Window (hours)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={720}
|
||||
value={Number(roundSettings.discussion_window_hours || 48)}
|
||||
onChange={(e) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
discussion_window_hours: parseInt(e.target.value) || 48,
|
||||
}))
|
||||
}
|
||||
className="max-w-[120px]"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">Max Comment Length</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={100}
|
||||
max={5000}
|
||||
value={Number(roundSettings.max_comment_length || 2000)}
|
||||
onChange={(e) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
max_comment_length: parseInt(e.target.value) || 2000,
|
||||
}))
|
||||
}
|
||||
className="max-w-[120px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* File Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<FileText className="h-5 w-5" />
|
||||
File Settings
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Configure allowed file types and versioning for this round
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">Allowed File Types</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Comma-separated MIME types or extensions
|
||||
</p>
|
||||
<Input
|
||||
placeholder="application/pdf, video/mp4, image/jpeg"
|
||||
value={String(roundSettings.allowed_file_types || '')}
|
||||
onChange={(e) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
allowed_file_types: e.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">Max File Size (MB)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={2048}
|
||||
value={Number(roundSettings.max_file_size_mb || 500)}
|
||||
onChange={(e) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
max_file_size_mb: parseInt(e.target.value) || 500,
|
||||
}))
|
||||
}
|
||||
className="max-w-[150px]"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-sm font-medium">Enable File Versioning</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Keep previous versions when files are replaced
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={Boolean(roundSettings.file_versioning)}
|
||||
onCheckedChange={(checked) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
file_versioning: checked,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{!!roundSettings.file_versioning && (
|
||||
<div className="space-y-2 pl-4 border-l-2 border-muted">
|
||||
<Label className="text-sm">Max Versions per File</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={2}
|
||||
max={20}
|
||||
value={Number(roundSettings.max_file_versions || 5)}
|
||||
onChange={(e) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
max_file_versions: parseInt(e.target.value) || 5,
|
||||
}))
|
||||
}
|
||||
className="max-w-[120px]"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Availability Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Calendar className="h-5 w-5" />
|
||||
Jury Availability Settings
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Configure how jury member availability affects assignments
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-sm font-medium">Require Availability</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Jury members must set availability before receiving assignments
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={Boolean(roundSettings.require_availability)}
|
||||
onCheckedChange={(checked) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
require_availability: checked,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">Availability Mode</Label>
|
||||
<Select
|
||||
value={String(roundSettings.availability_mode || 'soft_penalty')}
|
||||
onValueChange={(v) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
availability_mode: v,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="max-w-[250px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="hard_block">
|
||||
Hard Block (unavailable jurors excluded)
|
||||
</SelectItem>
|
||||
<SelectItem value="soft_penalty">
|
||||
Soft Penalty (reduce assignment priority)
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">
|
||||
Availability Weight ({Number(roundSettings.availability_weight || 50)}%)
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
How much weight to give availability when using soft penalty mode
|
||||
</p>
|
||||
<Slider
|
||||
value={[Number(roundSettings.availability_weight || 50)]}
|
||||
min={0}
|
||||
max={100}
|
||||
step={5}
|
||||
onValueChange={([value]) =>
|
||||
setRoundSettings((prev) => ({
|
||||
...prev,
|
||||
availability_weight: value,
|
||||
}))
|
||||
}
|
||||
className="max-w-xs"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Evaluation Criteria */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { Suspense, use, useState, useEffect } from 'react'
|
||||
import { Suspense, use, useState, useEffect, useCallback } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { trpc } from '@/lib/trpc/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -15,6 +15,15 @@ import {
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { toast } from 'sonner'
|
||||
import {
|
||||
ArrowLeft,
|
||||
@@ -28,6 +37,10 @@ import {
|
||||
AlertCircle,
|
||||
ExternalLink,
|
||||
RefreshCw,
|
||||
QrCode,
|
||||
Settings2,
|
||||
Scale,
|
||||
UserCheck,
|
||||
} from 'lucide-react'
|
||||
import {
|
||||
DndContext,
|
||||
@@ -46,6 +59,8 @@ import {
|
||||
verticalListSortingStrategy,
|
||||
} from '@dnd-kit/sortable'
|
||||
import { CSS } from '@dnd-kit/utilities'
|
||||
import { useLiveVotingSSE, type VoteUpdate } from '@/hooks/use-live-voting-sse'
|
||||
import { QRCodeDisplay } from '@/components/shared/qr-code-display'
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ id: string }>
|
||||
@@ -119,11 +134,38 @@ function LiveVotingContent({ roundId }: { roundId: string }) {
|
||||
const [projectOrder, setProjectOrder] = useState<string[]>([])
|
||||
const [countdown, setCountdown] = useState<number | null>(null)
|
||||
const [votingDuration, setVotingDuration] = useState(30)
|
||||
const [liveVoteCount, setLiveVoteCount] = useState<number | null>(null)
|
||||
const [liveAvgScore, setLiveAvgScore] = useState<number | null>(null)
|
||||
|
||||
// Fetch session data
|
||||
// Fetch session data - reduced polling since SSE handles real-time
|
||||
const { data: sessionData, isLoading, refetch } = trpc.liveVoting.getSession.useQuery(
|
||||
{ roundId },
|
||||
{ refetchInterval: 2000 } // Poll every 2 seconds
|
||||
{ refetchInterval: 5000 }
|
||||
)
|
||||
|
||||
// SSE for real-time vote updates
|
||||
const onVoteUpdate = useCallback((data: VoteUpdate) => {
|
||||
setLiveVoteCount(data.totalVotes)
|
||||
setLiveAvgScore(data.averageScore)
|
||||
}, [])
|
||||
|
||||
const onSessionStatus = useCallback(() => {
|
||||
refetch()
|
||||
}, [refetch])
|
||||
|
||||
const onProjectChange = useCallback(() => {
|
||||
setLiveVoteCount(null)
|
||||
setLiveAvgScore(null)
|
||||
refetch()
|
||||
}, [refetch])
|
||||
|
||||
const { isConnected } = useLiveVotingSSE(
|
||||
sessionData?.id || null,
|
||||
{
|
||||
onVoteUpdate,
|
||||
onSessionStatus,
|
||||
onProjectChange,
|
||||
}
|
||||
)
|
||||
|
||||
// Mutations
|
||||
@@ -166,6 +208,26 @@ function LiveVotingContent({ roundId }: { roundId: string }) {
|
||||
},
|
||||
})
|
||||
|
||||
const updateSessionConfig = trpc.liveVoting.updateSessionConfig.useMutation({
|
||||
onSuccess: () => {
|
||||
toast.success('Session config updated')
|
||||
refetch()
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error.message)
|
||||
},
|
||||
})
|
||||
|
||||
const updatePresentationSettings = trpc.liveVoting.updatePresentationSettings.useMutation({
|
||||
onSuccess: () => {
|
||||
toast.success('Presentation settings updated')
|
||||
refetch()
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error.message)
|
||||
},
|
||||
})
|
||||
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor),
|
||||
useSensor(KeyboardSensor, {
|
||||
@@ -446,61 +508,185 @@ function LiveVotingContent({ roundId }: { roundId: string }) {
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Users className="h-5 w-5" />
|
||||
Current Votes
|
||||
{isConnected && (
|
||||
<span className="h-2 w-2 rounded-full bg-green-500 animate-pulse" />
|
||||
)}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{sessionData.currentVotes.length === 0 ? (
|
||||
<p className="text-muted-foreground text-center py-4">
|
||||
No votes yet
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Total votes</span>
|
||||
<span className="font-medium">
|
||||
{sessionData.currentVotes.length}
|
||||
</span>
|
||||
{(() => {
|
||||
const voteCount = liveVoteCount ?? sessionData.currentVotes.length
|
||||
const avgScore = liveAvgScore ?? (
|
||||
sessionData.currentVotes.length > 0
|
||||
? sessionData.currentVotes.reduce((sum, v) => sum + v.score, 0) / sessionData.currentVotes.length
|
||||
: null
|
||||
)
|
||||
if (voteCount === 0) {
|
||||
return (
|
||||
<p className="text-muted-foreground text-center py-4">
|
||||
No votes yet
|
||||
</p>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Total votes</span>
|
||||
<span className="font-medium">{voteCount}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Average score</span>
|
||||
<span className="font-medium">
|
||||
{avgScore !== null ? avgScore.toFixed(1) : '--'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Average score</span>
|
||||
<span className="font-medium">
|
||||
{(
|
||||
sessionData.currentVotes.reduce(
|
||||
(sum, v) => sum + v.score,
|
||||
0
|
||||
) / sessionData.currentVotes.length
|
||||
).toFixed(1)}
|
||||
)
|
||||
})()}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Session Configuration */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Settings2 className="h-5 w-5" />
|
||||
Session Config
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="audience-votes" className="text-sm">
|
||||
Audience Voting
|
||||
</Label>
|
||||
<Switch
|
||||
id="audience-votes"
|
||||
checked={!!sessionData.allowAudienceVotes}
|
||||
onCheckedChange={(checked) => {
|
||||
updateSessionConfig.mutate({
|
||||
sessionId: sessionData.id,
|
||||
allowAudienceVotes: checked,
|
||||
})
|
||||
}}
|
||||
disabled={isCompleted}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{sessionData.allowAudienceVotes && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">Audience Weight</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="50"
|
||||
value={(sessionData.audienceVoteWeight || 0) * 100}
|
||||
onChange={(e) => {
|
||||
updateSessionConfig.mutate({
|
||||
sessionId: sessionData.id,
|
||||
audienceVoteWeight: parseInt(e.target.value) / 100,
|
||||
})
|
||||
}}
|
||||
className="flex-1"
|
||||
disabled={isCompleted}
|
||||
/>
|
||||
<span className="text-sm font-medium w-12 text-right">
|
||||
{Math.round((sessionData.audienceVoteWeight || 0) * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">Tie-Breaker Method</Label>
|
||||
<Select
|
||||
value={sessionData.tieBreakerMethod || 'admin_decides'}
|
||||
onValueChange={(v) => {
|
||||
updateSessionConfig.mutate({
|
||||
sessionId: sessionData.id,
|
||||
tieBreakerMethod: v as 'admin_decides' | 'highest_individual' | 'revote',
|
||||
})
|
||||
}}
|
||||
disabled={isCompleted}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="admin_decides">Admin Decides</SelectItem>
|
||||
<SelectItem value="highest_individual">Highest Individual Score</SelectItem>
|
||||
<SelectItem value="revote">Revote</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm">Score Display Format</Label>
|
||||
<Select
|
||||
value={
|
||||
(sessionData.presentationSettingsJson as Record<string, unknown>)?.scoreDisplayFormat as string || 'bar'
|
||||
}
|
||||
onValueChange={(v) => {
|
||||
const existing = (sessionData.presentationSettingsJson as Record<string, unknown>) || {}
|
||||
updatePresentationSettings.mutate({
|
||||
sessionId: sessionData.id,
|
||||
presentationSettingsJson: {
|
||||
...existing,
|
||||
scoreDisplayFormat: v as 'bar' | 'number' | 'radial',
|
||||
},
|
||||
})
|
||||
}}
|
||||
disabled={isCompleted}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="bar">Bar Chart</SelectItem>
|
||||
<SelectItem value="number">Number Only</SelectItem>
|
||||
<SelectItem value="radial">Radial</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Links */}
|
||||
{/* QR Codes & Links */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Voting Links</CardTitle>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<QrCode className="h-5 w-5" />
|
||||
Voting Links
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Share these links with participants
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<Button variant="outline" className="w-full justify-start" asChild>
|
||||
<Link href={`/jury/live/${sessionData.id}`} target="_blank">
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
Jury Voting Page
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="outline" className="w-full justify-start" asChild>
|
||||
<Link
|
||||
href={`/live-scores/${sessionData.id}`}
|
||||
target="_blank"
|
||||
>
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
Public Score Display
|
||||
</Link>
|
||||
</Button>
|
||||
<CardContent className="space-y-4">
|
||||
<QRCodeDisplay
|
||||
url={`${typeof window !== 'undefined' ? window.location.origin : ''}/jury/live/${sessionData.id}`}
|
||||
title="Jury Voting"
|
||||
size={160}
|
||||
/>
|
||||
<QRCodeDisplay
|
||||
url={`${typeof window !== 'undefined' ? window.location.origin : ''}/live-scores/${sessionData.id}`}
|
||||
title="Public Scoreboard"
|
||||
size={160}
|
||||
/>
|
||||
<div className="flex flex-col gap-2 pt-2 border-t">
|
||||
<Button variant="outline" className="w-full justify-start" asChild>
|
||||
<Link href={`/jury/live/${sessionData.id}`} target="_blank">
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
Open Jury Page
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="outline" className="w-full justify-start" asChild>
|
||||
<Link href={`/live-scores/${sessionData.id}`} target="_blank">
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
Open Scoreboard
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
ListChecks,
|
||||
ClipboardCheck,
|
||||
Sparkles,
|
||||
LayoutTemplate,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { AssignProjectsDialog } from '@/components/admin/assign-projects-dialog'
|
||||
@@ -126,6 +127,21 @@ function RoundDetailContent({ roundId }: { roundId: string }) {
|
||||
const startJob = trpc.filtering.startJob.useMutation()
|
||||
const finalizeResults = trpc.filtering.finalizeResults.useMutation()
|
||||
|
||||
// Save as template
|
||||
const saveAsTemplate = trpc.roundTemplate.createFromRound.useMutation({
|
||||
onSuccess: (data) => {
|
||||
toast.success('Saved as template', {
|
||||
action: {
|
||||
label: 'View',
|
||||
onClick: () => router.push(`/admin/round-templates/${data.id}`),
|
||||
},
|
||||
})
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
// AI summary bulk generation
|
||||
const bulkSummaries = trpc.evaluation.generateBulkSummaries.useMutation({
|
||||
onSuccess: (data) => {
|
||||
@@ -794,6 +810,24 @@ function RoundDetailContent({ roundId }: { roundId: string }) {
|
||||
)}
|
||||
{bulkSummaries.isPending ? 'Generating...' : 'Generate AI Summaries'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
saveAsTemplate.mutate({
|
||||
roundId: round.id,
|
||||
name: `${round.name} Template`,
|
||||
})
|
||||
}
|
||||
disabled={saveAsTemplate.isPending}
|
||||
>
|
||||
{saveAsTemplate.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<LayoutTemplate className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Save as Template
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
@@ -34,7 +34,8 @@ import {
|
||||
FormMessage,
|
||||
} from '@/components/ui/form'
|
||||
import { RoundTypeSettings } from '@/components/forms/round-type-settings'
|
||||
import { ArrowLeft, Loader2, AlertCircle, Bell } from 'lucide-react'
|
||||
import { ArrowLeft, Loader2, AlertCircle, Bell, LayoutTemplate } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { DateTimePicker } from '@/components/ui/datetime-picker'
|
||||
|
||||
// Available notification types for teams entering a round
|
||||
@@ -71,9 +72,38 @@ function CreateRoundContent() {
|
||||
const [roundType, setRoundType] = useState<'FILTERING' | 'EVALUATION' | 'LIVE_EVENT'>('EVALUATION')
|
||||
const [roundSettings, setRoundSettings] = useState<Record<string, unknown>>({})
|
||||
const [entryNotificationType, setEntryNotificationType] = useState<string>('')
|
||||
const [selectedTemplateId, setSelectedTemplateId] = useState<string>('')
|
||||
|
||||
const utils = trpc.useUtils()
|
||||
const { data: programs, isLoading: loadingPrograms } = trpc.program.list.useQuery()
|
||||
const { data: templates } = trpc.roundTemplate.list.useQuery()
|
||||
|
||||
const loadTemplate = (templateId: string) => {
|
||||
if (!templateId || !templates) return
|
||||
const template = templates.find((t) => t.id === templateId)
|
||||
if (!template) return
|
||||
|
||||
// Apply template settings
|
||||
const typeMap: Record<string, 'FILTERING' | 'EVALUATION' | 'LIVE_EVENT'> = {
|
||||
EVALUATION: 'EVALUATION',
|
||||
SELECTION: 'EVALUATION',
|
||||
FINAL: 'EVALUATION',
|
||||
LIVE_VOTING: 'LIVE_EVENT',
|
||||
FILTERING: 'FILTERING',
|
||||
}
|
||||
setRoundType(typeMap[template.roundType] || 'EVALUATION')
|
||||
|
||||
if (template.settingsJson && typeof template.settingsJson === 'object') {
|
||||
setRoundSettings(template.settingsJson as Record<string, unknown>)
|
||||
}
|
||||
|
||||
if (template.name) {
|
||||
form.setValue('name', template.name)
|
||||
}
|
||||
|
||||
setSelectedTemplateId(templateId)
|
||||
toast.success(`Loaded template: ${template.name}`)
|
||||
}
|
||||
|
||||
const createRound = trpc.round.create.useMutation({
|
||||
onSuccess: (data) => {
|
||||
@@ -155,6 +185,56 @@ function CreateRoundContent() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Template Selector */}
|
||||
{templates && templates.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<LayoutTemplate className="h-5 w-5" />
|
||||
Start from Template
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Load settings from a saved template to get started quickly
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-3">
|
||||
<Select
|
||||
value={selectedTemplateId}
|
||||
onValueChange={loadTemplate}
|
||||
>
|
||||
<SelectTrigger className="w-full max-w-sm">
|
||||
<SelectValue placeholder="Select a template..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{templates.map((t) => (
|
||||
<SelectItem key={t.id} value={t.id}>
|
||||
{t.name}
|
||||
{t.description ? ` - ${t.description}` : ''}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{selectedTemplateId && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setSelectedTemplateId('')
|
||||
setRoundType('EVALUATION')
|
||||
setRoundSettings({})
|
||||
form.reset()
|
||||
toast.info('Template cleared')
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Form */}
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
|
||||
|
||||
431
src/app/(admin)/admin/settings/templates/page.tsx
Normal file
431
src/app/(admin)/admin/settings/templates/page.tsx
Normal file
@@ -0,0 +1,431 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { trpc } from '@/lib/trpc/client'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Plus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Copy,
|
||||
Loader2,
|
||||
LayoutTemplate,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
|
||||
const ROUND_TYPES = [
|
||||
{ value: 'EVALUATION', label: 'Evaluation' },
|
||||
{ value: 'FILTERING', label: 'Filtering' },
|
||||
{ value: 'LIVE_EVENT', label: 'Live Event' },
|
||||
]
|
||||
|
||||
interface TemplateFormData {
|
||||
name: string
|
||||
description: string
|
||||
roundType: string
|
||||
programId: string
|
||||
criteriaJson: string
|
||||
settingsJson: string
|
||||
}
|
||||
|
||||
const defaultForm: TemplateFormData = {
|
||||
name: '',
|
||||
description: '',
|
||||
roundType: 'EVALUATION',
|
||||
programId: '',
|
||||
criteriaJson: '[]',
|
||||
settingsJson: '{}',
|
||||
}
|
||||
|
||||
export default function RoundTemplatesPage() {
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null)
|
||||
const [formData, setFormData] = useState<TemplateFormData>(defaultForm)
|
||||
|
||||
const utils = trpc.useUtils()
|
||||
|
||||
const { data: templates, isLoading } = trpc.roundTemplate.list.useQuery()
|
||||
const { data: programs } = trpc.program.list.useQuery()
|
||||
|
||||
const createMutation = trpc.roundTemplate.create.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.roundTemplate.list.invalidate()
|
||||
toast.success('Template created')
|
||||
closeDialog()
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const updateMutation = trpc.roundTemplate.update.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.roundTemplate.list.invalidate()
|
||||
toast.success('Template updated')
|
||||
closeDialog()
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const deleteMutation = trpc.roundTemplate.delete.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.roundTemplate.list.invalidate()
|
||||
toast.success('Template deleted')
|
||||
setDeleteId(null)
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const closeDialog = () => {
|
||||
setDialogOpen(false)
|
||||
setEditingId(null)
|
||||
setFormData(defaultForm)
|
||||
}
|
||||
|
||||
const openEdit = (template: Record<string, unknown>) => {
|
||||
setEditingId(String(template.id))
|
||||
setFormData({
|
||||
name: String(template.name || ''),
|
||||
description: String(template.description || ''),
|
||||
roundType: String(template.roundType || 'EVALUATION'),
|
||||
programId: String(template.programId || ''),
|
||||
criteriaJson: JSON.stringify(template.criteriaJson || [], null, 2),
|
||||
settingsJson: JSON.stringify(template.settingsJson || {}, null, 2),
|
||||
})
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleSubmit = () => {
|
||||
let criteriaJson: unknown
|
||||
let settingsJson: unknown
|
||||
|
||||
try {
|
||||
criteriaJson = JSON.parse(formData.criteriaJson)
|
||||
} catch {
|
||||
toast.error('Invalid criteria JSON')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
settingsJson = JSON.parse(formData.settingsJson)
|
||||
} catch {
|
||||
toast.error('Invalid settings JSON')
|
||||
return
|
||||
}
|
||||
|
||||
const payload = {
|
||||
name: formData.name,
|
||||
description: formData.description || undefined,
|
||||
roundType: formData.roundType as 'FILTERING' | 'EVALUATION' | 'LIVE_EVENT',
|
||||
programId: formData.programId || undefined,
|
||||
criteriaJson,
|
||||
settingsJson,
|
||||
}
|
||||
|
||||
if (editingId) {
|
||||
updateMutation.mutate({ id: editingId, ...payload })
|
||||
} else {
|
||||
createMutation.mutate(payload)
|
||||
}
|
||||
}
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" asChild className="-ml-4">
|
||||
<Link href="/admin/settings">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back to Settings
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">Round Templates</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Create reusable templates for round configuration
|
||||
</p>
|
||||
</div>
|
||||
<Dialog open={dialogOpen} onOpenChange={(open) => !open && closeDialog()}>
|
||||
<DialogTrigger asChild>
|
||||
<Button onClick={() => { setFormData(defaultForm); setEditingId(null); setDialogOpen(true) }}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create Template
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingId ? 'Edit Template' : 'Create Template'}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{editingId
|
||||
? 'Update the template configuration.'
|
||||
: 'Define a reusable round template.'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Template Name</Label>
|
||||
<Input
|
||||
placeholder="e.g., Standard Evaluation Round"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Description</Label>
|
||||
<Textarea
|
||||
placeholder="Template description..."
|
||||
value={formData.description}
|
||||
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Round Type</Label>
|
||||
<Select
|
||||
value={formData.roundType}
|
||||
onValueChange={(v) => setFormData({ ...formData, roundType: v })}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ROUND_TYPES.map((rt) => (
|
||||
<SelectItem key={rt.value} value={rt.value}>
|
||||
{rt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Program (optional)</Label>
|
||||
<Select
|
||||
value={formData.programId}
|
||||
onValueChange={(v) => setFormData({ ...formData, programId: v === '__none__' ? '' : v })}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Global (all programs)" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__none__">Global (all programs)</SelectItem>
|
||||
{(programs as Array<{ id: string; name: string }> | undefined)?.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Criteria (JSON)</Label>
|
||||
<Textarea
|
||||
value={formData.criteriaJson}
|
||||
onChange={(e) => setFormData({ ...formData, criteriaJson: e.target.value })}
|
||||
rows={5}
|
||||
className="font-mono text-sm"
|
||||
placeholder='[{"name":"Innovation","maxScore":10,"weight":1}]'
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Settings (JSON)</Label>
|
||||
<Textarea
|
||||
value={formData.settingsJson}
|
||||
onChange={(e) => setFormData({ ...formData, settingsJson: e.target.value })}
|
||||
rows={3}
|
||||
className="font-mono text-sm"
|
||||
placeholder='{"requiredReviews":3}'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={closeDialog}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={!formData.name || isPending}>
|
||||
{isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{editingId ? 'Update' : 'Create'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{/* Templates list */}
|
||||
{isLoading ? (
|
||||
<TemplatesSkeleton />
|
||||
) : templates && (templates as unknown[]).length > 0 ? (
|
||||
<Card>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead className="hidden md:table-cell">Round Type</TableHead>
|
||||
<TableHead className="hidden md:table-cell">Program</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">Created</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{(templates as Array<Record<string, unknown>>).map((template) => (
|
||||
<TableRow key={String(template.id)}>
|
||||
<TableCell>
|
||||
<div>
|
||||
<p className="font-medium">{String(template.name)}</p>
|
||||
{!!template.description && (
|
||||
<p className="text-sm text-muted-foreground line-clamp-1">
|
||||
{String(template.description)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="hidden md:table-cell">
|
||||
<Badge variant="secondary">
|
||||
{String(template.roundType || 'EVALUATION')}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="hidden md:table-cell">
|
||||
{template.program
|
||||
? String((template.program as Record<string, unknown>).name)
|
||||
: 'Global'}
|
||||
</TableCell>
|
||||
<TableCell className="hidden lg:table-cell text-sm text-muted-foreground">
|
||||
{template.createdAt ? formatDate(template.createdAt as string | Date) : ''}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => openEdit(template)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setDeleteId(String(template.id))}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<LayoutTemplate className="h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="mt-2 font-medium">No templates yet</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Create a template to reuse round configurations across programs.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Delete confirmation */}
|
||||
<AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Template</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete this template? This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => deleteId && deleteMutation.mutate({ id: deleteId })}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleteMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TemplatesSkeleton() {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="space-y-4">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<div key={i} className="flex items-center gap-4">
|
||||
<Skeleton className="h-4 w-40" />
|
||||
<Skeleton className="h-6 w-24" />
|
||||
<Skeleton className="h-4 w-20" />
|
||||
<Skeleton className="h-8 w-16 ml-auto" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
706
src/app/(admin)/admin/settings/webhooks/page.tsx
Normal file
706
src/app/(admin)/admin/settings/webhooks/page.tsx
Normal file
@@ -0,0 +1,706 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { trpc } from '@/lib/trpc/client'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog'
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Plus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Loader2,
|
||||
Webhook,
|
||||
Send,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Copy,
|
||||
Eye,
|
||||
EyeOff,
|
||||
RefreshCw,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
|
||||
interface WebhookFormData {
|
||||
name: string
|
||||
url: string
|
||||
events: string[]
|
||||
headers: Array<{ key: string; value: string }>
|
||||
maxRetries: number
|
||||
}
|
||||
|
||||
const defaultForm: WebhookFormData = {
|
||||
name: '',
|
||||
url: '',
|
||||
events: [],
|
||||
headers: [],
|
||||
maxRetries: 3,
|
||||
}
|
||||
|
||||
export default function WebhooksPage() {
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null)
|
||||
const [formData, setFormData] = useState<WebhookFormData>(defaultForm)
|
||||
const [expandedWebhook, setExpandedWebhook] = useState<string | null>(null)
|
||||
const [revealedSecrets, setRevealedSecrets] = useState<Set<string>>(new Set())
|
||||
const [deliveryPage, setDeliveryPage] = useState(1)
|
||||
|
||||
const utils = trpc.useUtils()
|
||||
|
||||
const { data: webhooks, isLoading } = trpc.webhook.list.useQuery()
|
||||
const { data: availableEvents } = trpc.webhook.getAvailableEvents.useQuery()
|
||||
|
||||
const { data: deliveryLog, isLoading: loadingDeliveries } =
|
||||
trpc.webhook.getDeliveryLog.useQuery(
|
||||
{ webhookId: expandedWebhook!, page: deliveryPage, pageSize: 10 },
|
||||
{ enabled: !!expandedWebhook }
|
||||
)
|
||||
|
||||
const createMutation = trpc.webhook.create.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.webhook.list.invalidate()
|
||||
toast.success('Webhook created')
|
||||
closeDialog()
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const updateMutation = trpc.webhook.update.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.webhook.list.invalidate()
|
||||
toast.success('Webhook updated')
|
||||
closeDialog()
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const deleteMutation = trpc.webhook.delete.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.webhook.list.invalidate()
|
||||
toast.success('Webhook deleted')
|
||||
setDeleteId(null)
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const testMutation = trpc.webhook.test.useMutation({
|
||||
onSuccess: (data) => {
|
||||
const status = (data as Record<string, unknown>)?.status
|
||||
if (status === 'DELIVERED') {
|
||||
toast.success('Test webhook delivered successfully')
|
||||
} else {
|
||||
toast.error(`Test delivery status: ${String(status || 'unknown')}`)
|
||||
}
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const regenerateSecretMutation = trpc.webhook.regenerateSecret.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.webhook.list.invalidate()
|
||||
toast.success('Secret regenerated')
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const closeDialog = () => {
|
||||
setDialogOpen(false)
|
||||
setEditingId(null)
|
||||
setFormData(defaultForm)
|
||||
}
|
||||
|
||||
const openEdit = (webhook: Record<string, unknown>) => {
|
||||
setEditingId(String(webhook.id))
|
||||
const headers = webhook.headers as Array<{ key: string; value: string }> | undefined
|
||||
setFormData({
|
||||
name: String(webhook.name || ''),
|
||||
url: String(webhook.url || ''),
|
||||
events: Array.isArray(webhook.events) ? webhook.events.map(String) : [],
|
||||
headers: Array.isArray(headers) ? headers : [],
|
||||
maxRetries: Number(webhook.maxRetries || 3),
|
||||
})
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
const toggleEvent = (event: string) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
events: prev.events.includes(event)
|
||||
? prev.events.filter((e) => e !== event)
|
||||
: [...prev.events, event],
|
||||
}))
|
||||
}
|
||||
|
||||
const addHeader = () => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
headers: [...prev.headers, { key: '', value: '' }],
|
||||
}))
|
||||
}
|
||||
|
||||
const removeHeader = (index: number) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
headers: prev.headers.filter((_, i) => i !== index),
|
||||
}))
|
||||
}
|
||||
|
||||
const updateHeader = (index: number, field: 'key' | 'value', value: string) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
headers: prev.headers.map((h, i) =>
|
||||
i === index ? { ...h, [field]: value } : h
|
||||
),
|
||||
}))
|
||||
}
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!formData.name || !formData.url || formData.events.length === 0) {
|
||||
toast.error('Please fill in name, URL, and select at least one event')
|
||||
return
|
||||
}
|
||||
|
||||
const payload = {
|
||||
name: formData.name,
|
||||
url: formData.url,
|
||||
events: formData.events,
|
||||
headers: formData.headers.filter((h) => h.key) as Record<string, string>[] | undefined,
|
||||
maxRetries: formData.maxRetries,
|
||||
}
|
||||
|
||||
if (editingId) {
|
||||
updateMutation.mutate({ id: editingId, ...payload })
|
||||
} else {
|
||||
createMutation.mutate(payload)
|
||||
}
|
||||
}
|
||||
|
||||
const copySecret = (secret: string) => {
|
||||
navigator.clipboard.writeText(secret)
|
||||
toast.success('Secret copied to clipboard')
|
||||
}
|
||||
|
||||
const toggleSecretVisibility = (id: string) => {
|
||||
setRevealedSecrets((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const toggleDeliveryLog = (webhookId: string) => {
|
||||
if (expandedWebhook === webhookId) {
|
||||
setExpandedWebhook(null)
|
||||
} else {
|
||||
setExpandedWebhook(webhookId)
|
||||
setDeliveryPage(1)
|
||||
}
|
||||
}
|
||||
|
||||
const events = availableEvents || []
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" asChild className="-ml-4">
|
||||
<Link href="/admin/settings">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back to Settings
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">Webhooks</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Configure webhook endpoints for platform events
|
||||
</p>
|
||||
</div>
|
||||
<Dialog open={dialogOpen} onOpenChange={(open) => !open && closeDialog()}>
|
||||
<DialogTrigger asChild>
|
||||
<Button onClick={() => { setFormData(defaultForm); setEditingId(null); setDialogOpen(true) }}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Webhook
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingId ? 'Edit Webhook' : 'Add Webhook'}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure a webhook endpoint to receive platform events.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Name</Label>
|
||||
<Input
|
||||
placeholder="e.g., Slack Notifications"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>URL</Label>
|
||||
<Input
|
||||
placeholder="https://example.com/webhook"
|
||||
type="url"
|
||||
value={formData.url}
|
||||
onChange={(e) => setFormData({ ...formData, url: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Events</Label>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{(events as string[]).map((event) => (
|
||||
<div key={event} className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id={`event-${event}`}
|
||||
checked={formData.events.includes(event)}
|
||||
onCheckedChange={() => toggleEvent(event)}
|
||||
/>
|
||||
<label
|
||||
htmlFor={`event-${event}`}
|
||||
className="text-sm cursor-pointer"
|
||||
>
|
||||
{event}
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>Custom Headers</Label>
|
||||
<Button variant="outline" size="sm" onClick={addHeader}>
|
||||
<Plus className="mr-1 h-3 w-3" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
{formData.headers.map((header, i) => (
|
||||
<div key={i} className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Header name"
|
||||
value={header.key}
|
||||
onChange={(e) => updateHeader(i, 'key', e.target.value)}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
placeholder="Value"
|
||||
value={header.value}
|
||||
onChange={(e) => updateHeader(i, 'value', e.target.value)}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removeHeader(i)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Max Retries</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={10}
|
||||
value={formData.maxRetries}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, maxRetries: parseInt(e.target.value) || 0 })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{editingId && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="webhook-active"
|
||||
checked={
|
||||
(webhooks as Array<Record<string, unknown>> | undefined)?.find(
|
||||
(w) => String(w.id) === editingId
|
||||
)?.isActive !== false
|
||||
}
|
||||
onCheckedChange={(checked) => {
|
||||
updateMutation.mutate({ id: editingId, isActive: checked })
|
||||
}}
|
||||
/>
|
||||
<label htmlFor="webhook-active" className="text-sm cursor-pointer">
|
||||
Active
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={closeDialog}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={isPending}>
|
||||
{isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{editingId ? 'Update' : 'Create'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{/* Webhooks list */}
|
||||
{isLoading ? (
|
||||
<WebhooksSkeleton />
|
||||
) : webhooks && (webhooks as unknown[]).length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
{(webhooks as Array<Record<string, unknown>>).map((webhook) => {
|
||||
const webhookId = String(webhook.id)
|
||||
const webhookEvents = Array.isArray(webhook.events) ? webhook.events : []
|
||||
const isActive = Boolean(webhook.isActive)
|
||||
const secret = String(webhook.secret || '')
|
||||
const isRevealed = revealedSecrets.has(webhookId)
|
||||
const isExpanded = expandedWebhook === webhookId
|
||||
const recentDelivered = Number(webhook.recentDelivered || 0)
|
||||
const recentFailed = Number(webhook.recentFailed || 0)
|
||||
const deliveryCount = webhook._count
|
||||
? Number((webhook._count as Record<string, unknown>).deliveries || 0)
|
||||
: 0
|
||||
|
||||
return (
|
||||
<Card key={webhookId}>
|
||||
<CardHeader>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="space-y-1">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
{String(webhook.name)}
|
||||
{isActive ? (
|
||||
<Badge variant="default" className="text-xs">Active</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs">Inactive</Badge>
|
||||
)}
|
||||
</CardTitle>
|
||||
<CardDescription className="font-mono text-xs break-all max-w-md truncate">
|
||||
{String(webhook.url)}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-sm text-muted-foreground">
|
||||
<span>{webhookEvents.length} events</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="flex items-center gap-1">
|
||||
<CheckCircle2 className="h-3 w-3 text-green-500" />
|
||||
{recentDelivered}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<XCircle className="h-3 w-3 text-destructive" />
|
||||
{recentFailed}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Events */}
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{webhookEvents.map((event: unknown) => (
|
||||
<Badge key={String(event)} variant="outline" className="text-xs">
|
||||
{String(event)}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Secret */}
|
||||
{secret && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">Secret:</span>
|
||||
<code className="text-xs bg-muted rounded px-2 py-1 font-mono">
|
||||
{isRevealed ? secret : '****************************'}
|
||||
</code>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6"
|
||||
onClick={() => toggleSecretVisibility(webhookId)}
|
||||
>
|
||||
{isRevealed ? <EyeOff className="h-3 w-3" /> : <Eye className="h-3 w-3" />}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6"
|
||||
onClick={() => copySecret(secret)}
|
||||
>
|
||||
<Copy className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => testMutation.mutate({ id: webhookId })}
|
||||
disabled={testMutation.isPending}
|
||||
>
|
||||
{testMutation.isPending ? (
|
||||
<Loader2 className="mr-2 h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<Send className="mr-2 h-3 w-3" />
|
||||
)}
|
||||
Test
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => openEdit(webhook)}>
|
||||
<Pencil className="mr-2 h-3 w-3" />
|
||||
Edit
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => regenerateSecretMutation.mutate({ id: webhookId })}
|
||||
disabled={regenerateSecretMutation.isPending}
|
||||
>
|
||||
<RefreshCw className="mr-2 h-3 w-3" />
|
||||
Regenerate Secret
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setDeleteId(webhookId)}
|
||||
className="text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="mr-2 h-3 w-3" />
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Delivery log */}
|
||||
{deliveryCount > 0 && (
|
||||
<Collapsible
|
||||
open={isExpanded}
|
||||
onOpenChange={() => toggleDeliveryLog(webhookId)}
|
||||
>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="w-full justify-between">
|
||||
<span>Delivery Log ({deliveryCount})</span>
|
||||
{isExpanded ? (
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="mt-2 rounded-lg border overflow-hidden">
|
||||
{loadingDeliveries ? (
|
||||
<div className="p-4 space-y-2">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Skeleton key={i} className="h-8 w-full" />
|
||||
))}
|
||||
</div>
|
||||
) : deliveryLog && deliveryLog.items.length > 0 ? (
|
||||
<>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Timestamp</TableHead>
|
||||
<TableHead>Event</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Response</TableHead>
|
||||
<TableHead>Attempts</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{(deliveryLog.items as Array<Record<string, unknown>>).map(
|
||||
(delivery, i) => (
|
||||
<TableRow key={i}>
|
||||
<TableCell className="font-mono text-xs">
|
||||
{delivery.createdAt
|
||||
? formatDate(delivery.createdAt as string | Date)
|
||||
: ''}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs">
|
||||
{String(delivery.event || '')}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{delivery.status === 'DELIVERED' ? (
|
||||
<Badge variant="default" className="text-xs gap-1">
|
||||
<CheckCircle2 className="h-3 w-3" />
|
||||
OK
|
||||
</Badge>
|
||||
) : delivery.status === 'PENDING' ? (
|
||||
<Badge variant="secondary" className="text-xs gap-1">
|
||||
Pending
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="destructive" className="text-xs gap-1">
|
||||
<XCircle className="h-3 w-3" />
|
||||
Failed
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs font-mono">
|
||||
{String(delivery.responseStatus || '-')}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs">
|
||||
{String(delivery.attempts || 0)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
{deliveryLog.totalPages > 1 && (
|
||||
<div className="flex items-center justify-between p-2 border-t">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Page {deliveryLog.page} of {deliveryLog.totalPages}
|
||||
</span>
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={deliveryPage <= 1}
|
||||
onClick={() => setDeliveryPage((p) => p - 1)}
|
||||
>
|
||||
Previous
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={deliveryPage >= deliveryLog.totalPages}
|
||||
onClick={() => setDeliveryPage((p) => p + 1)}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||
No deliveries recorded yet.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<Webhook className="h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="mt-2 font-medium">No webhooks configured</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Add a webhook to receive real-time notifications about platform events.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Delete confirmation */}
|
||||
<AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Webhook</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete this webhook? All delivery history will be lost.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => deleteId && deleteMutation.mutate({ id: deleteId })}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleteMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function WebhooksSkeleton() {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{[1, 2].map((i) => (
|
||||
<Card key={i}>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-5 w-40" />
|
||||
<Skeleton className="h-4 w-64" />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex gap-1">
|
||||
<Skeleton className="h-5 w-24" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
<Skeleton className="h-5 w-28" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-32" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
397
src/app/(jury)/jury/compare/page.tsx
Normal file
397
src/app/(jury)/jury/compare/page.tsx
Normal file
@@ -0,0 +1,397 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { trpc } from '@/lib/trpc/client'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
ArrowLeft,
|
||||
GitCompare,
|
||||
MapPin,
|
||||
Users,
|
||||
FileText,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
} from 'lucide-react'
|
||||
|
||||
export default function CompareProjectsPage() {
|
||||
const [selectedRoundId, setSelectedRoundId] = useState<string>('')
|
||||
const [selectedIds, setSelectedIds] = useState<string[]>([])
|
||||
const [comparing, setComparing] = useState(false)
|
||||
|
||||
// Fetch all assigned projects
|
||||
const { data: assignments, isLoading: loadingAssignments } =
|
||||
trpc.assignment.myAssignments.useQuery({})
|
||||
|
||||
// Derive unique rounds from assignments
|
||||
const rounds = useMemo(() => {
|
||||
if (!assignments) return []
|
||||
const roundMap = new Map<string, { id: string; name: string }>()
|
||||
for (const a of assignments as Array<{ round: { id: string; name: string } }>) {
|
||||
if (a.round && !roundMap.has(a.round.id)) {
|
||||
roundMap.set(a.round.id, { id: a.round.id, name: String(a.round.name) })
|
||||
}
|
||||
}
|
||||
return Array.from(roundMap.values())
|
||||
}, [assignments])
|
||||
|
||||
// Auto-select the first round if none selected
|
||||
const activeRoundId = selectedRoundId || (rounds.length > 0 ? rounds[0].id : '')
|
||||
|
||||
// Filter assignments to current round
|
||||
const roundProjects = useMemo(() => {
|
||||
if (!assignments || !activeRoundId) return []
|
||||
return (assignments as Array<{
|
||||
project: Record<string, unknown>
|
||||
round: { id: string; name: string }
|
||||
evaluation?: Record<string, unknown>
|
||||
}>)
|
||||
.filter((a) => a.round.id === activeRoundId)
|
||||
.map((a) => ({
|
||||
...a.project,
|
||||
roundName: a.round.name,
|
||||
evaluation: a.evaluation,
|
||||
}))
|
||||
}, [assignments, activeRoundId])
|
||||
|
||||
// Fetch comparison data when comparing
|
||||
const { data: comparisonData, isLoading: loadingComparison } =
|
||||
trpc.evaluation.getMultipleForComparison.useQuery(
|
||||
{ projectIds: selectedIds, roundId: activeRoundId },
|
||||
{ enabled: comparing && selectedIds.length >= 2 && !!activeRoundId }
|
||||
)
|
||||
|
||||
const toggleProject = (projectId: string) => {
|
||||
setSelectedIds((prev) => {
|
||||
if (prev.includes(projectId)) {
|
||||
return prev.filter((id) => id !== projectId)
|
||||
}
|
||||
if (prev.length >= 3) return prev
|
||||
return [...prev, projectId]
|
||||
})
|
||||
setComparing(false)
|
||||
}
|
||||
|
||||
const handleCompare = () => {
|
||||
if (selectedIds.length >= 2) {
|
||||
setComparing(true)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
setComparing(false)
|
||||
setSelectedIds([])
|
||||
}
|
||||
|
||||
const handleRoundChange = (roundId: string) => {
|
||||
setSelectedRoundId(roundId)
|
||||
setSelectedIds([])
|
||||
setComparing(false)
|
||||
}
|
||||
|
||||
if (loadingAssignments) {
|
||||
return <CompareSkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" asChild className="-ml-4">
|
||||
<Link href="/jury/assignments">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back to Assignments
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between flex-wrap gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">Compare Projects</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Select 2-3 projects from the same round to compare side by side
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{comparing && (
|
||||
<Button variant="outline" onClick={handleReset}>
|
||||
Reset
|
||||
</Button>
|
||||
)}
|
||||
{!comparing && (
|
||||
<Button
|
||||
onClick={handleCompare}
|
||||
disabled={selectedIds.length < 2}
|
||||
>
|
||||
<GitCompare className="mr-2 h-4 w-4" />
|
||||
Compare ({selectedIds.length})
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Round selector */}
|
||||
{rounds.length > 1 && !comparing && (
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm font-medium text-muted-foreground">Round:</span>
|
||||
<Select value={activeRoundId} onValueChange={handleRoundChange}>
|
||||
<SelectTrigger className="w-[280px]">
|
||||
<SelectValue placeholder="Select a round" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{rounds.map((r) => (
|
||||
<SelectItem key={r.id} value={r.id}>
|
||||
{r.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Project selector */}
|
||||
{!comparing && (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{roundProjects.map((project: Record<string, unknown>) => {
|
||||
const projectId = project.id as string
|
||||
const isSelected = selectedIds.includes(projectId)
|
||||
const isDisabled = !isSelected && selectedIds.length >= 3
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={projectId}
|
||||
className={`cursor-pointer transition-colors ${
|
||||
isSelected
|
||||
? 'border-primary ring-2 ring-primary/20'
|
||||
: isDisabled
|
||||
? 'opacity-50'
|
||||
: 'hover:border-primary/50'
|
||||
}`}
|
||||
onClick={() => !isDisabled && toggleProject(projectId)}
|
||||
>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
checked={isSelected}
|
||||
disabled={isDisabled}
|
||||
onCheckedChange={() => toggleProject(projectId)}
|
||||
className="mt-1"
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium truncate">
|
||||
{String(project.title || 'Untitled')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground truncate">
|
||||
{String(project.teamName || '')}
|
||||
</p>
|
||||
{!!project.roundName && (
|
||||
<Badge variant="secondary" className="mt-1 text-xs">
|
||||
{String(project.roundName)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{project.evaluation ? (
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500 shrink-0" />
|
||||
) : (
|
||||
<Clock className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{roundProjects.length === 0 && !loadingAssignments && (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<GitCompare className="h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="mt-2 font-medium">No projects assigned</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You need at least 2 assigned projects to use the comparison feature.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Comparison view */}
|
||||
{comparing && loadingComparison && <CompareSkeleton />}
|
||||
|
||||
{comparing && comparisonData && (
|
||||
<div
|
||||
className={`grid gap-4 grid-cols-1 ${
|
||||
selectedIds.length === 2 ? 'md:grid-cols-2' : 'md:grid-cols-2 lg:grid-cols-3'
|
||||
}`}
|
||||
>
|
||||
{(comparisonData as Array<{
|
||||
project: Record<string, unknown>
|
||||
evaluation: Record<string, unknown> | null
|
||||
assignmentId: string
|
||||
}>).map((item) => (
|
||||
<ComparisonCard
|
||||
key={String(item.project.id)}
|
||||
project={item.project}
|
||||
evaluation={item.evaluation}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ComparisonCard({
|
||||
project,
|
||||
evaluation,
|
||||
}: {
|
||||
project: Record<string, unknown>
|
||||
evaluation: Record<string, unknown> | null
|
||||
}) {
|
||||
const tags = Array.isArray(project.tags) ? project.tags : []
|
||||
const files = Array.isArray(project.files) ? project.files : []
|
||||
const scores = evaluation?.scores as Record<string, unknown> | undefined
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">{String(project.title || 'Untitled')}</CardTitle>
|
||||
<CardDescription className="flex items-center gap-1">
|
||||
<Users className="h-3 w-3" />
|
||||
{String(project.teamName || 'N/A')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Country */}
|
||||
{!!project.country && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<MapPin className="h-4 w-4 text-muted-foreground" />
|
||||
{String(project.country)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Description */}
|
||||
{!!project.description && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground mb-1">Description</p>
|
||||
<p className="text-sm line-clamp-4">{String(project.description)}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tags */}
|
||||
{tags.length > 0 && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground mb-1">Tags</p>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{tags.map((tag: unknown, i: number) => (
|
||||
<Badge key={i} variant="secondary" className="text-xs">
|
||||
{String(tag)}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Files */}
|
||||
{files.length > 0 && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground mb-1">
|
||||
Files ({files.length})
|
||||
</p>
|
||||
<div className="space-y-1">
|
||||
{files.map((file: unknown, i: number) => {
|
||||
const f = file as Record<string, unknown>
|
||||
return (
|
||||
<div key={i} className="flex items-center gap-2 text-sm">
|
||||
<FileText className="h-3 w-3 text-muted-foreground" />
|
||||
<span className="truncate">{String(f.fileName || f.fileType || 'File')}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Evaluation scores */}
|
||||
{evaluation && (
|
||||
<div className="border-t pt-3">
|
||||
<p className="text-xs font-medium text-muted-foreground mb-2">Your Evaluation</p>
|
||||
{scores && typeof scores === 'object' ? (
|
||||
<div className="space-y-1">
|
||||
{Object.entries(scores).map(([criterion, score]) => (
|
||||
<div key={criterion} className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground truncate">{criterion}</span>
|
||||
<span className="font-medium tabular-nums">{String(score)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Badge variant="outline">
|
||||
<CheckCircle2 className="mr-1 h-3 w-3" />
|
||||
Submitted
|
||||
</Badge>
|
||||
)}
|
||||
{evaluation.globalScore != null && (
|
||||
<div className="mt-2 flex items-center justify-between font-medium text-sm border-t pt-2">
|
||||
<span>Overall Score</span>
|
||||
<span className="text-primary">{String(evaluation.globalScore)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!evaluation && (
|
||||
<div className="border-t pt-3">
|
||||
<Badge variant="outline">
|
||||
<Clock className="mr-1 h-3 w-3" />
|
||||
Not yet evaluated
|
||||
</Badge>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function CompareSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Skeleton className="h-9 w-36" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-64" />
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Card key={i}>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-5 w-32" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-16 w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { use, useState, useEffect } from 'react'
|
||||
import { use, useState, useEffect, useCallback } from 'react'
|
||||
import { trpc } from '@/lib/trpc/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -15,7 +15,8 @@ import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { toast } from 'sonner'
|
||||
import { Clock, CheckCircle, AlertCircle, Zap } from 'lucide-react'
|
||||
import { Clock, CheckCircle, AlertCircle, Zap, Wifi, WifiOff } from 'lucide-react'
|
||||
import { useLiveVotingSSE } from '@/hooks/use-live-voting-sse'
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ sessionId: string }>
|
||||
@@ -27,12 +28,28 @@ function JuryVotingContent({ sessionId }: { sessionId: string }) {
|
||||
const [selectedScore, setSelectedScore] = useState<number | null>(null)
|
||||
const [countdown, setCountdown] = useState<number | null>(null)
|
||||
|
||||
// Fetch session data with polling
|
||||
// Fetch session data - reduced polling since SSE handles real-time
|
||||
const { data, isLoading, refetch } = trpc.liveVoting.getSessionForVoting.useQuery(
|
||||
{ sessionId },
|
||||
{ refetchInterval: 2000 } // Poll every 2 seconds
|
||||
{ refetchInterval: 10000 }
|
||||
)
|
||||
|
||||
// SSE for real-time updates
|
||||
const onSessionStatus = useCallback(() => {
|
||||
refetch()
|
||||
}, [refetch])
|
||||
|
||||
const onProjectChange = useCallback(() => {
|
||||
setSelectedScore(null)
|
||||
setCountdown(null)
|
||||
refetch()
|
||||
}, [refetch])
|
||||
|
||||
const { isConnected } = useLiveVotingSSE(sessionId, {
|
||||
onSessionStatus,
|
||||
onProjectChange,
|
||||
})
|
||||
|
||||
// Vote mutation
|
||||
const vote = trpc.liveVoting.vote.useMutation({
|
||||
onSuccess: () => {
|
||||
@@ -207,9 +224,16 @@ function JuryVotingContent({ sessionId }: { sessionId: string }) {
|
||||
</Card>
|
||||
|
||||
{/* Mobile-friendly footer */}
|
||||
<p className="text-white/60 text-sm mt-4">
|
||||
MOPC Live Voting
|
||||
</p>
|
||||
<div className="flex items-center justify-center gap-2 mt-4">
|
||||
{isConnected ? (
|
||||
<Wifi className="h-3 w-3 text-green-400" />
|
||||
) : (
|
||||
<WifiOff className="h-3 w-3 text-red-400" />
|
||||
)}
|
||||
<p className="text-white/60 text-sm">
|
||||
MOPC Live Voting {isConnected ? '- Connected' : '- Reconnecting...'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
366
src/app/(jury)/jury/projects/[id]/discussion/page.tsx
Normal file
366
src/app/(jury)/jury/projects/[id]/discussion/page.tsx
Normal file
@@ -0,0 +1,366 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useParams, useSearchParams } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { trpc } from '@/lib/trpc/client'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import {
|
||||
ArrowLeft,
|
||||
BarChart3,
|
||||
MessageSquare,
|
||||
Send,
|
||||
Loader2,
|
||||
Lock,
|
||||
User,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { formatDate, cn, getInitials } from '@/lib/utils'
|
||||
|
||||
export default function DiscussionPage() {
|
||||
const params = useParams()
|
||||
const searchParams = useSearchParams()
|
||||
const projectId = params.id as string
|
||||
const roundId = searchParams.get('roundId') || ''
|
||||
|
||||
const [commentText, setCommentText] = useState('')
|
||||
|
||||
const utils = trpc.useUtils()
|
||||
|
||||
// Fetch peer summary
|
||||
const { data: peerSummary, isLoading: loadingSummary } =
|
||||
trpc.evaluation.getPeerSummary.useQuery(
|
||||
{ projectId, roundId },
|
||||
{ enabled: !!roundId }
|
||||
)
|
||||
|
||||
// Fetch discussion thread
|
||||
const { data: discussion, isLoading: loadingDiscussion } =
|
||||
trpc.evaluation.getDiscussion.useQuery(
|
||||
{ projectId, roundId },
|
||||
{ enabled: !!roundId }
|
||||
)
|
||||
|
||||
// Add comment mutation
|
||||
const addCommentMutation = trpc.evaluation.addComment.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.evaluation.getDiscussion.invalidate({ projectId, roundId })
|
||||
toast.success('Comment added')
|
||||
setCommentText('')
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const handleSubmitComment = () => {
|
||||
if (!commentText.trim()) {
|
||||
toast.error('Please enter a comment')
|
||||
return
|
||||
}
|
||||
addCommentMutation.mutate({
|
||||
projectId,
|
||||
roundId,
|
||||
content: commentText.trim(),
|
||||
})
|
||||
}
|
||||
|
||||
const isLoading = loadingSummary || loadingDiscussion
|
||||
|
||||
if (!roundId) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Button variant="ghost" asChild className="-ml-4">
|
||||
<Link href="/jury/assignments">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back to Assignments
|
||||
</Link>
|
||||
</Button>
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<MessageSquare className="h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="mt-2 font-medium">No round specified</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Please access the discussion from your assignments page.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return <DiscussionSkeleton />
|
||||
}
|
||||
|
||||
// Parse peer summary data
|
||||
const summary = peerSummary as Record<string, unknown> | undefined
|
||||
const averageScore = summary ? Number(summary.averageScore || 0) : 0
|
||||
const scoreRange = summary?.scoreRange as { min: number; max: number } | undefined
|
||||
const evaluationCount = summary ? Number(summary.evaluationCount || 0) : 0
|
||||
const individualScores = (summary?.scores || summary?.individualScores) as
|
||||
| Array<number>
|
||||
| undefined
|
||||
|
||||
// Parse discussion data
|
||||
const discussionData = discussion as Record<string, unknown> | undefined
|
||||
const comments = (discussionData?.comments || []) as Array<{
|
||||
id: string
|
||||
user: { id: string; name: string | null; email: string }
|
||||
content: string
|
||||
createdAt: string
|
||||
}>
|
||||
const discussionStatus = String(discussionData?.status || 'OPEN')
|
||||
const isClosed = discussionStatus === 'CLOSED'
|
||||
const closedAt = discussionData?.closedAt as string | undefined
|
||||
const closedBy = discussionData?.closedBy as Record<string, unknown> | undefined
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" asChild className="-ml-4">
|
||||
<Link href="/jury/assignments">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back to Assignments
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">
|
||||
Project Discussion
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Peer review discussion and anonymized score summary
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Peer Summary Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<BarChart3 className="h-5 w-5" />
|
||||
Peer Summary
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Anonymized scoring overview across all evaluations
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Stats row */}
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div className="rounded-lg border p-3 text-center">
|
||||
<p className="text-2xl font-bold">{averageScore.toFixed(1)}</p>
|
||||
<p className="text-xs text-muted-foreground">Average Score</p>
|
||||
</div>
|
||||
<div className="rounded-lg border p-3 text-center">
|
||||
<p className="text-2xl font-bold">
|
||||
{scoreRange
|
||||
? `${scoreRange.min.toFixed(1)} - ${scoreRange.max.toFixed(1)}`
|
||||
: '--'}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">Score Range</p>
|
||||
</div>
|
||||
<div className="rounded-lg border p-3 text-center">
|
||||
<p className="text-2xl font-bold">{evaluationCount}</p>
|
||||
<p className="text-xs text-muted-foreground">Evaluations</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Anonymized score bars */}
|
||||
{individualScores && individualScores.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">Anonymized Individual Scores</p>
|
||||
<div className="flex items-end gap-2 h-24">
|
||||
{individualScores.map((score, i) => {
|
||||
const maxPossible = scoreRange?.max || 10
|
||||
const height =
|
||||
maxPossible > 0
|
||||
? Math.max((score / maxPossible) * 100, 4)
|
||||
: 4
|
||||
|
||||
return (
|
||||
<div
|
||||
key={i}
|
||||
className="flex-1 flex flex-col items-center gap-1"
|
||||
>
|
||||
<span className="text-[10px] font-medium tabular-nums">
|
||||
{score.toFixed(1)}
|
||||
</span>
|
||||
<div
|
||||
className={cn(
|
||||
'w-full rounded-t transition-all',
|
||||
score >= averageScore
|
||||
? 'bg-primary/60'
|
||||
: 'bg-muted-foreground/30'
|
||||
)}
|
||||
style={{ height: `${height}%` }}
|
||||
/>
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
#{i + 1}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Discussion Section */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<MessageSquare className="h-5 w-5" />
|
||||
Discussion
|
||||
</CardTitle>
|
||||
{isClosed && (
|
||||
<Badge variant="secondary" className="flex items-center gap-1">
|
||||
<Lock className="h-3 w-3" />
|
||||
Closed
|
||||
{closedAt && (
|
||||
<span className="ml-1">- {formatDate(closedAt)}</span>
|
||||
)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<CardDescription>
|
||||
{isClosed
|
||||
? 'This discussion has been closed.'
|
||||
: 'Share your thoughts with fellow jurors about this project.'}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Comments */}
|
||||
{comments.length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
{comments.map((comment) => (
|
||||
<div key={comment.id} className="flex gap-3">
|
||||
{/* Avatar */}
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-medium">
|
||||
{comment.user?.name
|
||||
? getInitials(comment.user.name)
|
||||
: <User className="h-4 w-4" />}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">
|
||||
{comment.user?.name || 'Anonymous Juror'}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{formatDate(comment.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm mt-1 whitespace-pre-wrap">
|
||||
{comment.content}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center py-8 text-center">
|
||||
<MessageSquare className="h-10 w-10 text-muted-foreground/30" />
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
No comments yet. Be the first to start the discussion.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Comment input */}
|
||||
{!isClosed ? (
|
||||
<div className="space-y-2 border-t pt-4">
|
||||
<Textarea
|
||||
placeholder="Write your comment..."
|
||||
value={commentText}
|
||||
onChange={(e) => setCommentText(e.target.value)}
|
||||
rows={3}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
onClick={handleSubmitComment}
|
||||
disabled={
|
||||
addCommentMutation.isPending || !commentText.trim()
|
||||
}
|
||||
>
|
||||
{addCommentMutation.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Send className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Post Comment
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="border-t pt-4">
|
||||
<p className="text-sm text-muted-foreground text-center">
|
||||
This discussion is closed and no longer accepts new comments.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DiscussionSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Skeleton className="h-9 w-36" />
|
||||
<div>
|
||||
<Skeleton className="h-8 w-64" />
|
||||
<Skeleton className="h-4 w-40 mt-2" />
|
||||
</div>
|
||||
|
||||
{/* Peer summary skeleton */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-5 w-40" />
|
||||
<Skeleton className="h-4 w-56" />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Skeleton key={i} className="h-20 w-full" />
|
||||
))}
|
||||
</div>
|
||||
<Skeleton className="h-24 w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Discussion skeleton */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-5 w-32" />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<div key={i} className="flex gap-3">
|
||||
<Skeleton className="h-8 w-8 rounded-full" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-32" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<Skeleton className="h-20 w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
|
||||
import {
|
||||
Users,
|
||||
@@ -23,8 +24,11 @@ import {
|
||||
GraduationCap,
|
||||
Waves,
|
||||
Crown,
|
||||
CheckCircle2,
|
||||
Circle,
|
||||
Clock,
|
||||
} from 'lucide-react'
|
||||
import { getInitials, formatDateOnly } from '@/lib/utils'
|
||||
import { formatDateOnly } from '@/lib/utils'
|
||||
|
||||
// Status badge colors
|
||||
const statusColors: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
|
||||
@@ -36,6 +40,13 @@ const statusColors: Record<string, 'default' | 'secondary' | 'destructive' | 'ou
|
||||
REJECTED: 'destructive',
|
||||
}
|
||||
|
||||
// Completion status display
|
||||
const completionBadge: Record<string, { label: string; variant: 'default' | 'secondary' | 'outline' }> = {
|
||||
in_progress: { label: 'In Progress', variant: 'secondary' },
|
||||
completed: { label: 'Completed', variant: 'default' },
|
||||
paused: { label: 'Paused', variant: 'outline' },
|
||||
}
|
||||
|
||||
function DashboardSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -44,7 +55,8 @@ function DashboardSkeleton() {
|
||||
<Skeleton className="h-4 w-64 mt-2" />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<Skeleton className="h-24" />
|
||||
<Skeleton className="h-24" />
|
||||
<Skeleton className="h-24" />
|
||||
</div>
|
||||
@@ -66,6 +78,8 @@ export default function MentorDashboard() {
|
||||
}
|
||||
|
||||
const projects = assignments || []
|
||||
const completedCount = projects.filter((a) => a.completionStatus === 'completed').length
|
||||
const inProgressCount = projects.filter((a) => a.completionStatus === 'in_progress').length
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -80,7 +94,7 @@ export default function MentorDashboard() {
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
@@ -96,6 +110,29 @@ export default function MentorDashboard() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
Completed
|
||||
</CardTitle>
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{completedCount}</div>
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
{projects.length > 0 && (
|
||||
<Progress
|
||||
value={(completedCount / projects.length) * 100}
|
||||
className="h-1.5 flex-1"
|
||||
/>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{projects.length > 0 ? Math.round((completedCount / projects.length) * 100) : 0}%
|
||||
</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">
|
||||
@@ -141,6 +178,7 @@ export default function MentorDashboard() {
|
||||
const teamLead = project.teamMembers?.find(
|
||||
(m) => m.role === 'LEAD'
|
||||
)
|
||||
const badge = completionBadge[assignment.completionStatus] || completionBadge.in_progress
|
||||
|
||||
return (
|
||||
<Card key={assignment.id}>
|
||||
@@ -153,12 +191,12 @@ export default function MentorDashboard() {
|
||||
</span>
|
||||
{project.round && (
|
||||
<>
|
||||
<span>•</span>
|
||||
<span>-</span>
|
||||
<span>{project.round.name}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<CardTitle className="flex items-center gap-2 flex-wrap">
|
||||
{project.title}
|
||||
{project.status && (
|
||||
<Badge
|
||||
@@ -167,6 +205,18 @@ export default function MentorDashboard() {
|
||||
{project.status.replace('_', ' ')}
|
||||
</Badge>
|
||||
)}
|
||||
<Badge variant={badge.variant}>
|
||||
{assignment.completionStatus === 'completed' && (
|
||||
<CheckCircle2 className="mr-1 h-3 w-3" />
|
||||
)}
|
||||
{assignment.completionStatus === 'in_progress' && (
|
||||
<Circle className="mr-1 h-3 w-3" />
|
||||
)}
|
||||
{assignment.completionStatus === 'paused' && (
|
||||
<Clock className="mr-1 h-3 w-3" />
|
||||
)}
|
||||
{badge.label}
|
||||
</Badge>
|
||||
</CardTitle>
|
||||
{project.teamName && (
|
||||
<CardDescription>{project.teamName}</CardDescription>
|
||||
@@ -242,10 +292,13 @@ export default function MentorDashboard() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Assignment date */}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Assigned {formatDateOnly(assignment.assignedAt)}
|
||||
</p>
|
||||
{/* Assignment date + last viewed */}
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>Assigned {formatDateOnly(assignment.assignedAt)}</span>
|
||||
{assignment.lastViewedAt && (
|
||||
<span>Last viewed {formatDateOnly(assignment.lastViewedAt)}</span>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { Suspense, use } from 'react'
|
||||
import { Suspense, use, useState, useEffect } from 'react'
|
||||
import Link from 'next/link'
|
||||
import type { Route } from 'next'
|
||||
import { trpc } from '@/lib/trpc/client'
|
||||
@@ -15,6 +15,19 @@ import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog'
|
||||
import { FileViewer } from '@/components/shared/file-viewer'
|
||||
import { MentorChat } from '@/components/shared/mentor-chat'
|
||||
import { ProjectLogoWithUrl } from '@/components/shared/project-logo-with-url'
|
||||
@@ -32,8 +45,19 @@ import {
|
||||
FileText,
|
||||
ExternalLink,
|
||||
MessageSquare,
|
||||
StickyNote,
|
||||
Plus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Loader2,
|
||||
Target,
|
||||
CheckCircle2,
|
||||
Circle,
|
||||
Eye,
|
||||
EyeOff,
|
||||
} from 'lucide-react'
|
||||
import { formatDateOnly, getInitials } from '@/lib/utils'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ id: string }>
|
||||
@@ -65,6 +89,15 @@ function ProjectDetailContent({ projectId }: { projectId: string }) {
|
||||
},
|
||||
})
|
||||
|
||||
// Track view when project loads
|
||||
const trackView = trpc.mentor.trackView.useMutation()
|
||||
useEffect(() => {
|
||||
if (project?.mentorAssignment?.id) {
|
||||
trackView.mutate({ mentorAssignmentId: project.mentorAssignment.id })
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [project?.mentorAssignment?.id])
|
||||
|
||||
if (isLoading) {
|
||||
return <ProjectDetailSkeleton />
|
||||
}
|
||||
@@ -99,6 +132,8 @@ function ProjectDetailContent({ projectId }: { projectId: string }) {
|
||||
|
||||
const teamLead = project.teamMembers?.find((m) => m.role === 'LEAD')
|
||||
const otherMembers = project.teamMembers?.filter((m) => m.role !== 'LEAD') || []
|
||||
const mentorAssignmentId = project.mentorAssignment?.id
|
||||
const programId = project.round?.program?.id
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -126,7 +161,7 @@ function ProjectDetailContent({ projectId }: { projectId: string }) {
|
||||
</span>
|
||||
{project.round && (
|
||||
<>
|
||||
<span>•</span>
|
||||
<span>-</span>
|
||||
<span>{project.round.name}</span>
|
||||
</>
|
||||
)}
|
||||
@@ -157,6 +192,19 @@ function ProjectDetailContent({ projectId }: { projectId: string }) {
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Milestones Section */}
|
||||
{programId && mentorAssignmentId && (
|
||||
<MilestonesSection
|
||||
programId={programId}
|
||||
mentorAssignmentId={mentorAssignmentId}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Private Notes Section */}
|
||||
{mentorAssignmentId && (
|
||||
<NotesSection mentorAssignmentId={mentorAssignmentId} />
|
||||
)}
|
||||
|
||||
{/* Project Info */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -359,6 +407,7 @@ function ProjectDetailContent({ projectId }: { projectId: string }) {
|
||||
<CardContent>
|
||||
{project.files && project.files.length > 0 ? (
|
||||
<FileViewer
|
||||
projectId={projectId}
|
||||
files={project.files.map((f) => ({
|
||||
id: f.id,
|
||||
fileName: f.fileName,
|
||||
@@ -367,6 +416,7 @@ function ProjectDetailContent({ projectId }: { projectId: string }) {
|
||||
size: f.size,
|
||||
bucket: f.bucket,
|
||||
objectKey: f.objectKey,
|
||||
version: f.version,
|
||||
}))}
|
||||
/>
|
||||
) : (
|
||||
@@ -404,6 +454,386 @@ function ProjectDetailContent({ projectId }: { projectId: string }) {
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Milestones Section
|
||||
// =============================================================================
|
||||
|
||||
function MilestonesSection({
|
||||
programId,
|
||||
mentorAssignmentId,
|
||||
}: {
|
||||
programId: string
|
||||
mentorAssignmentId: string
|
||||
}) {
|
||||
const { data: milestones, isLoading } = trpc.mentor.getMilestones.useQuery({ programId })
|
||||
const utils = trpc.useUtils()
|
||||
|
||||
const completeMutation = trpc.mentor.completeMilestone.useMutation({
|
||||
onSuccess: (data) => {
|
||||
utils.mentor.getMilestones.invalidate({ programId })
|
||||
if (data.allRequiredDone) {
|
||||
toast.success('All required milestones completed!')
|
||||
} else {
|
||||
toast.success('Milestone completed')
|
||||
}
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const uncompleteMutation = trpc.mentor.uncompleteMilestone.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.mentor.getMilestones.invalidate({ programId })
|
||||
toast.success('Milestone unchecked')
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-5 w-32" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<Skeleton className="h-8 w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
if (!milestones || milestones.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const completedCount = milestones.filter(
|
||||
(m) => m.myCompletions.length > 0
|
||||
).length
|
||||
const totalRequired = milestones.filter((m) => m.isRequired).length
|
||||
const requiredCompleted = milestones.filter(
|
||||
(m) => m.isRequired && m.myCompletions.length > 0
|
||||
).length
|
||||
|
||||
const handleToggle = (milestoneId: string, isCompleted: boolean) => {
|
||||
if (isCompleted) {
|
||||
uncompleteMutation.mutate({ milestoneId, mentorAssignmentId })
|
||||
} else {
|
||||
completeMutation.mutate({ milestoneId, mentorAssignmentId })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Target className="h-5 w-5" />
|
||||
Milestones
|
||||
</CardTitle>
|
||||
<Badge variant="secondary">
|
||||
{completedCount}/{milestones.length} done
|
||||
</Badge>
|
||||
</div>
|
||||
{totalRequired > 0 && (
|
||||
<CardDescription>
|
||||
{requiredCompleted}/{totalRequired} required milestones completed
|
||||
</CardDescription>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{milestones.map((milestone) => {
|
||||
const isCompleted = milestone.myCompletions.length > 0
|
||||
const isPending = completeMutation.isPending || uncompleteMutation.isPending
|
||||
|
||||
return (
|
||||
<div
|
||||
key={milestone.id}
|
||||
className={`flex items-start gap-3 p-3 rounded-lg border transition-colors ${
|
||||
isCompleted ? 'bg-green-50/50 border-green-200 dark:bg-green-950/20 dark:border-green-900' : ''
|
||||
}`}
|
||||
>
|
||||
<Checkbox
|
||||
checked={isCompleted}
|
||||
disabled={isPending}
|
||||
onCheckedChange={() => handleToggle(milestone.id, isCompleted)}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className={`text-sm font-medium ${isCompleted ? 'line-through text-muted-foreground' : ''}`}>
|
||||
{milestone.name}
|
||||
</p>
|
||||
{milestone.isRequired && (
|
||||
<Badge variant="outline" className="text-xs">Required</Badge>
|
||||
)}
|
||||
</div>
|
||||
{milestone.description && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{milestone.description}
|
||||
</p>
|
||||
)}
|
||||
{isCompleted && milestone.myCompletions[0] && (
|
||||
<p className="text-xs text-green-600 mt-1">
|
||||
Completed {formatDateOnly(milestone.myCompletions[0].completedAt)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{isCompleted ? (
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500 shrink-0 mt-0.5" />
|
||||
) : (
|
||||
<Circle className="h-4 w-4 text-muted-foreground shrink-0 mt-0.5" />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Notes Section
|
||||
// =============================================================================
|
||||
|
||||
function NotesSection({ mentorAssignmentId }: { mentorAssignmentId: string }) {
|
||||
const [isAdding, setIsAdding] = useState(false)
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null)
|
||||
const [noteContent, setNoteContent] = useState('')
|
||||
const [isVisibleToAdmin, setIsVisibleToAdmin] = useState(true)
|
||||
|
||||
const { data: notes, isLoading } = trpc.mentor.getNotes.useQuery({ mentorAssignmentId })
|
||||
const utils = trpc.useUtils()
|
||||
|
||||
const createMutation = trpc.mentor.createNote.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.mentor.getNotes.invalidate({ mentorAssignmentId })
|
||||
toast.success('Note saved')
|
||||
resetForm()
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const updateMutation = trpc.mentor.updateNote.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.mentor.getNotes.invalidate({ mentorAssignmentId })
|
||||
toast.success('Note updated')
|
||||
resetForm()
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const deleteMutation = trpc.mentor.deleteNote.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.mentor.getNotes.invalidate({ mentorAssignmentId })
|
||||
toast.success('Note deleted')
|
||||
setDeleteId(null)
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const resetForm = () => {
|
||||
setIsAdding(false)
|
||||
setEditingId(null)
|
||||
setNoteContent('')
|
||||
setIsVisibleToAdmin(true)
|
||||
}
|
||||
|
||||
const handleEdit = (note: { id: string; content: string; isVisibleToAdmin: boolean }) => {
|
||||
setEditingId(note.id)
|
||||
setNoteContent(note.content)
|
||||
setIsVisibleToAdmin(note.isVisibleToAdmin)
|
||||
setIsAdding(false)
|
||||
}
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!noteContent.trim()) return
|
||||
|
||||
if (editingId) {
|
||||
updateMutation.mutate({
|
||||
noteId: editingId,
|
||||
content: noteContent.trim(),
|
||||
isVisibleToAdmin,
|
||||
})
|
||||
} else {
|
||||
createMutation.mutate({
|
||||
mentorAssignmentId,
|
||||
content: noteContent.trim(),
|
||||
isVisibleToAdmin,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<StickyNote className="h-5 w-5" />
|
||||
Private Notes
|
||||
</CardTitle>
|
||||
{!isAdding && !editingId && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setIsAdding(true)
|
||||
setEditingId(null)
|
||||
setNoteContent('')
|
||||
setIsVisibleToAdmin(true)
|
||||
}}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Note
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<CardDescription>
|
||||
Personal notes about this mentorship (private to you unless shared with admin)
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Add/Edit form */}
|
||||
{(isAdding || editingId) && (
|
||||
<div className="space-y-3 p-4 border rounded-lg bg-muted/30">
|
||||
<Textarea
|
||||
value={noteContent}
|
||||
onChange={(e) => setNoteContent(e.target.value)}
|
||||
placeholder="Write your note..."
|
||||
rows={4}
|
||||
className="resize-none"
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="visible-to-admin"
|
||||
checked={isVisibleToAdmin}
|
||||
onCheckedChange={(checked) =>
|
||||
setIsVisibleToAdmin(checked === true)
|
||||
}
|
||||
/>
|
||||
<Label htmlFor="visible-to-admin" className="text-sm flex items-center gap-1">
|
||||
{isVisibleToAdmin ? (
|
||||
<Eye className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
) : (
|
||||
<EyeOff className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
)}
|
||||
Visible to admins
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 justify-end">
|
||||
<Button variant="outline" size="sm" onClick={resetForm}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSubmit}
|
||||
disabled={!noteContent.trim() || isPending}
|
||||
>
|
||||
{isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{editingId ? 'Update' : 'Save'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Notes list */}
|
||||
{isLoading ? (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-20 w-full" />
|
||||
<Skeleton className="h-20 w-full" />
|
||||
</div>
|
||||
) : notes && notes.length > 0 ? (
|
||||
<div className="space-y-3">
|
||||
{notes.map((note) => (
|
||||
<div
|
||||
key={note.id}
|
||||
className="p-4 rounded-lg border space-y-2"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>{formatDateOnly(note.createdAt)}</span>
|
||||
{note.isVisibleToAdmin ? (
|
||||
<Badge variant="outline" className="text-xs gap-1">
|
||||
<Eye className="h-3 w-3" />
|
||||
Admin visible
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="text-xs gap-1">
|
||||
<EyeOff className="h-3 w-3" />
|
||||
Private
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={() => handleEdit(note)}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={() => setDeleteId(note.id)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm whitespace-pre-wrap">{note.content}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
!isAdding && (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">
|
||||
No notes yet. Click "Add Note" to start taking notes.
|
||||
</p>
|
||||
)
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Delete confirmation */}
|
||||
<AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Note</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete this note? This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => deleteId && deleteMutation.mutate({ noteId: deleteId })}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleteMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Skeletons
|
||||
// =============================================================================
|
||||
|
||||
function ProjectDetailSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
|
||||
@@ -35,7 +35,12 @@ import {
|
||||
ClipboardList,
|
||||
CheckCircle2,
|
||||
TrendingUp,
|
||||
GitCompare,
|
||||
UserCheck,
|
||||
Globe,
|
||||
Printer,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { formatDateOnly } from '@/lib/utils'
|
||||
import {
|
||||
ScoreDistributionChart,
|
||||
@@ -44,6 +49,9 @@ import {
|
||||
JurorWorkloadChart,
|
||||
ProjectRankingsChart,
|
||||
CriteriaScoresChart,
|
||||
CrossRoundComparisonChart,
|
||||
JurorConsistencyChart,
|
||||
DiversityMetricsChart,
|
||||
} from '@/components/charts'
|
||||
|
||||
function OverviewTab({ selectedRoundId }: { selectedRoundId: string | null }) {
|
||||
@@ -410,6 +418,121 @@ function AnalyticsTab({ selectedRoundId }: { selectedRoundId: string }) {
|
||||
)
|
||||
}
|
||||
|
||||
function CrossRoundTab() {
|
||||
const { data: programs, isLoading: programsLoading } = trpc.program.list.useQuery({ includeRounds: true })
|
||||
|
||||
const rounds = programs?.flatMap(p =>
|
||||
p.rounds.map(r => ({ id: r.id, name: r.name, programName: `${p.year} Edition` }))
|
||||
) || []
|
||||
|
||||
const [selectedRoundIds, setSelectedRoundIds] = useState<string[]>([])
|
||||
|
||||
const { data: comparison, isLoading: comparisonLoading } =
|
||||
trpc.analytics.getCrossRoundComparison.useQuery(
|
||||
{ roundIds: selectedRoundIds },
|
||||
{ enabled: selectedRoundIds.length >= 2 }
|
||||
)
|
||||
|
||||
const toggleRound = (roundId: string) => {
|
||||
setSelectedRoundIds((prev) =>
|
||||
prev.includes(roundId)
|
||||
? prev.filter((id) => id !== roundId)
|
||||
: [...prev, roundId]
|
||||
)
|
||||
}
|
||||
|
||||
if (programsLoading) return <Skeleton className="h-[400px]" />
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Select Rounds to Compare</CardTitle>
|
||||
<CardDescription>Choose at least 2 rounds</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{rounds.map((round) => (
|
||||
<Badge
|
||||
key={round.id}
|
||||
variant={selectedRoundIds.includes(round.id) ? 'default' : 'outline'}
|
||||
className="cursor-pointer text-sm py-1.5 px-3"
|
||||
onClick={() => toggleRound(round.id)}
|
||||
>
|
||||
{round.programName} - {round.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
{selectedRoundIds.length < 2 && (
|
||||
<p className="text-sm text-muted-foreground mt-3">
|
||||
Select at least 2 rounds to enable comparison
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{comparisonLoading && selectedRoundIds.length >= 2 && <Skeleton className="h-[350px]" />}
|
||||
|
||||
{comparison && (
|
||||
<CrossRoundComparisonChart data={comparison as Array<{
|
||||
roundId: string; roundName: string; projectCount: number; evaluationCount: number
|
||||
completionRate: number; averageScore: number | null
|
||||
scoreDistribution: { score: number; count: number }[]
|
||||
}>} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function JurorConsistencyTab({ selectedRoundId }: { selectedRoundId: string }) {
|
||||
const { data: consistency, isLoading } =
|
||||
trpc.analytics.getJurorConsistency.useQuery(
|
||||
{ roundId: selectedRoundId },
|
||||
{ enabled: !!selectedRoundId }
|
||||
)
|
||||
|
||||
if (isLoading) return <Skeleton className="h-[400px]" />
|
||||
|
||||
if (!consistency) return null
|
||||
|
||||
return (
|
||||
<JurorConsistencyChart
|
||||
data={consistency as {
|
||||
overallAverage: number
|
||||
jurors: Array<{
|
||||
userId: string; name: string; email: string
|
||||
evaluationCount: number; averageScore: number
|
||||
stddev: number; deviationFromOverall: number; isOutlier: boolean
|
||||
}>
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DiversityTab({ selectedRoundId }: { selectedRoundId: string }) {
|
||||
const { data: diversity, isLoading } =
|
||||
trpc.analytics.getDiversityMetrics.useQuery(
|
||||
{ roundId: selectedRoundId },
|
||||
{ enabled: !!selectedRoundId }
|
||||
)
|
||||
|
||||
if (isLoading) return <Skeleton className="h-[400px]" />
|
||||
|
||||
if (!diversity) return null
|
||||
|
||||
return (
|
||||
<DiversityMetricsChart
|
||||
data={diversity as {
|
||||
total: number
|
||||
byCountry: { country: string; count: number; percentage: number }[]
|
||||
byCategory: { category: string; count: number; percentage: number }[]
|
||||
byOceanIssue: { issue: string; count: number; percentage: number }[]
|
||||
byTag: { tag: string; count: number; percentage: number }[]
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default function ObserverReportsPage() {
|
||||
const [selectedRoundId, setSelectedRoundId] = useState<string | null>(null)
|
||||
|
||||
@@ -462,16 +585,38 @@ export default function ObserverReportsPage() {
|
||||
|
||||
{/* Tabs */}
|
||||
<Tabs defaultValue="overview" className="space-y-6">
|
||||
<TabsList>
|
||||
<TabsTrigger value="overview" className="gap-2">
|
||||
<FileSpreadsheet className="h-4 w-4" />
|
||||
Overview
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="analytics" className="gap-2" disabled={!selectedRoundId}>
|
||||
<TrendingUp className="h-4 w-4" />
|
||||
Analytics
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<div className="flex items-center justify-between flex-wrap gap-4">
|
||||
<TabsList>
|
||||
<TabsTrigger value="overview" className="gap-2">
|
||||
<FileSpreadsheet className="h-4 w-4" />
|
||||
Overview
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="analytics" className="gap-2" disabled={!selectedRoundId}>
|
||||
<TrendingUp className="h-4 w-4" />
|
||||
Analytics
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="cross-round" className="gap-2">
|
||||
<GitCompare className="h-4 w-4" />
|
||||
Cross-Round
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="consistency" className="gap-2" disabled={!selectedRoundId}>
|
||||
<UserCheck className="h-4 w-4" />
|
||||
Juror Consistency
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="diversity" className="gap-2" disabled={!selectedRoundId}>
|
||||
<Globe className="h-4 w-4" />
|
||||
Diversity
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.print()}
|
||||
>
|
||||
<Printer className="mr-2 h-4 w-4" />
|
||||
Export PDF
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<TabsContent value="overview">
|
||||
<OverviewTab selectedRoundId={selectedRoundId} />
|
||||
@@ -492,6 +637,42 @@ export default function ObserverReportsPage() {
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="cross-round">
|
||||
<CrossRoundTab />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="consistency">
|
||||
{selectedRoundId ? (
|
||||
<JurorConsistencyTab selectedRoundId={selectedRoundId} />
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<UserCheck className="h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="mt-2 font-medium">Select a round</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Choose a round above to view juror consistency metrics
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="diversity">
|
||||
{selectedRoundId ? (
|
||||
<DiversityTab selectedRoundId={selectedRoundId} />
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<Globe className="h-12 w-12 text-muted-foreground/50" />
|
||||
<p className="mt-2 font-medium">Select a round</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Choose a round above to view diversity metrics
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { use } from 'react'
|
||||
import { use, useCallback, useState } from 'react'
|
||||
import { trpc } from '@/lib/trpc/client'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
@@ -12,19 +12,65 @@ import {
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Trophy, Star, Clock, AlertCircle, Zap } from 'lucide-react'
|
||||
import { Trophy, Star, Clock, AlertCircle, Zap, Wifi, WifiOff } from 'lucide-react'
|
||||
import { useLiveVotingSSE, type VoteUpdate } from '@/hooks/use-live-voting-sse'
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ sessionId: string }>
|
||||
}
|
||||
|
||||
interface PublicSession {
|
||||
id: string
|
||||
status: string
|
||||
currentProjectId: string | null
|
||||
votingEndsAt: string | null
|
||||
presentationSettings: Record<string, unknown> | null
|
||||
allowAudienceVotes: boolean
|
||||
}
|
||||
|
||||
interface PublicProject {
|
||||
id: string | undefined
|
||||
title: string | undefined
|
||||
teamName: string | null | undefined
|
||||
averageScore: number
|
||||
voteCount: number
|
||||
}
|
||||
|
||||
function PublicScoresContent({ sessionId }: { sessionId: string }) {
|
||||
// Fetch session data with polling
|
||||
const { data, isLoading } = trpc.liveVoting.getPublicSession.useQuery(
|
||||
// Track SSE-based score updates keyed by projectId
|
||||
const [liveScores, setLiveScores] = useState<Record<string, { avg: number; count: number }>>({})
|
||||
|
||||
// Use public (no-auth) endpoint with reduced polling since SSE handles real-time
|
||||
const { data, isLoading, refetch } = trpc.liveVoting.getPublicResults.useQuery(
|
||||
{ sessionId },
|
||||
{ refetchInterval: 2000 } // Poll every 2 seconds
|
||||
{ refetchInterval: 10000 }
|
||||
)
|
||||
|
||||
// SSE for real-time updates
|
||||
const onVoteUpdate = useCallback((update: VoteUpdate) => {
|
||||
setLiveScores((prev) => ({
|
||||
...prev,
|
||||
[update.projectId]: {
|
||||
avg: update.averageScore ?? 0,
|
||||
count: update.totalVotes,
|
||||
},
|
||||
}))
|
||||
}, [])
|
||||
|
||||
const onSessionStatus = useCallback(() => {
|
||||
refetch()
|
||||
}, [refetch])
|
||||
|
||||
const onProjectChange = useCallback(() => {
|
||||
refetch()
|
||||
}, [refetch])
|
||||
|
||||
const { isConnected } = useLiveVotingSSE(sessionId, {
|
||||
onVoteUpdate,
|
||||
onSessionStatus,
|
||||
onProjectChange,
|
||||
})
|
||||
|
||||
if (isLoading) {
|
||||
return <PublicScoresSkeleton />
|
||||
}
|
||||
@@ -43,16 +89,32 @@ function PublicScoresContent({ sessionId }: { sessionId: string }) {
|
||||
)
|
||||
}
|
||||
|
||||
const isCompleted = data.session.status === 'COMPLETED'
|
||||
const isVoting = data.session.status === 'IN_PROGRESS'
|
||||
const session = data.session as PublicSession
|
||||
const projects = data.projects as PublicProject[]
|
||||
|
||||
const isCompleted = session.status === 'COMPLETED'
|
||||
const isVoting = session.status === 'IN_PROGRESS'
|
||||
|
||||
// Merge live SSE scores with fetched data
|
||||
const projectsWithLive = projects.map((project) => {
|
||||
const live = project.id ? liveScores[project.id] : null
|
||||
return {
|
||||
...project,
|
||||
averageScore: live ? live.avg : (project.averageScore || 0),
|
||||
voteCount: live ? live.count : (project.voteCount || 0),
|
||||
}
|
||||
})
|
||||
|
||||
// Sort projects by score for leaderboard
|
||||
const sortedProjects = [...data.projects].sort(
|
||||
const sortedProjects = [...projectsWithLive].sort(
|
||||
(a, b) => (b.averageScore || 0) - (a.averageScore || 0)
|
||||
)
|
||||
|
||||
// Find max score for progress bars
|
||||
const maxScore = Math.max(...data.projects.map((p) => p.averageScore || 0), 1)
|
||||
const maxScore = Math.max(...sortedProjects.map((p) => p.averageScore || 0), 1)
|
||||
|
||||
// Get presentation settings
|
||||
const presentationSettings = session.presentationSettings
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-[#053d57] to-[#557f8c] p-4 md:p-8">
|
||||
@@ -62,20 +124,22 @@ function PublicScoresContent({ sessionId }: { sessionId: string }) {
|
||||
<div className="flex items-center justify-center gap-2 mb-2">
|
||||
<Zap className="h-8 w-8" />
|
||||
<h1 className="text-3xl font-bold">Live Scores</h1>
|
||||
{isConnected ? (
|
||||
<Wifi className="h-4 w-4 text-green-400" />
|
||||
) : (
|
||||
<WifiOff className="h-4 w-4 text-red-400" />
|
||||
)}
|
||||
</div>
|
||||
<p className="text-white/80">
|
||||
{data.round.program.name} - {data.round.name}
|
||||
</p>
|
||||
<Badge
|
||||
variant={isVoting ? 'default' : isCompleted ? 'secondary' : 'outline'}
|
||||
className="mt-2"
|
||||
>
|
||||
{isVoting ? 'LIVE' : isCompleted ? 'COMPLETED' : data.session.status}
|
||||
{isVoting ? 'LIVE' : isCompleted ? 'COMPLETED' : session.status}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* Current project highlight */}
|
||||
{isVoting && data.session.currentProjectId && (
|
||||
{isVoting && session.currentProjectId && (
|
||||
<Card className="border-2 border-green-500 bg-green-500/10 animate-pulse">
|
||||
<CardHeader className="pb-2">
|
||||
<div className="flex items-center gap-2 text-green-400">
|
||||
@@ -85,7 +149,7 @@ function PublicScoresContent({ sessionId }: { sessionId: string }) {
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-xl font-semibold text-white">
|
||||
{data.projects.find((p) => p?.id === data.session.currentProjectId)?.title}
|
||||
{projects.find((p) => p?.id === session.currentProjectId)?.title}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -108,12 +172,13 @@ function PublicScoresContent({ sessionId }: { sessionId: string }) {
|
||||
<div className="space-y-4">
|
||||
{sortedProjects.map((project, index) => {
|
||||
if (!project) return null
|
||||
const isCurrent = project.id === data.session.currentProjectId
|
||||
const isCurrent = project.id === session.currentProjectId
|
||||
const scoreFormat = presentationSettings?.scoreDisplayFormat as string || 'bar'
|
||||
|
||||
return (
|
||||
<div
|
||||
key={project.id}
|
||||
className={`rounded-lg p-4 ${
|
||||
className={`rounded-lg p-4 transition-all duration-300 ${
|
||||
isCurrent
|
||||
? 'bg-green-500/10 border border-green-500'
|
||||
: 'bg-muted/50'
|
||||
@@ -147,29 +212,58 @@ function PublicScoresContent({ sessionId }: { sessionId: string }) {
|
||||
|
||||
{/* Score */}
|
||||
<div className="shrink-0 text-right">
|
||||
<div className="flex items-center gap-1">
|
||||
<Star className="h-4 w-4 text-yellow-500" />
|
||||
<span className="text-xl font-bold">
|
||||
{project.averageScore?.toFixed(1) || '--'}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{project.voteCount} votes
|
||||
</p>
|
||||
{scoreFormat === 'radial' ? (
|
||||
<div className="relative w-14 h-14">
|
||||
<svg viewBox="0 0 36 36" className="w-14 h-14 -rotate-90">
|
||||
<path
|
||||
d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
className="text-muted/30"
|
||||
/>
|
||||
<path
|
||||
d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2.5"
|
||||
strokeDasharray={`${((project.averageScore || 0) / 10) * 100}, 100`}
|
||||
className="text-primary"
|
||||
/>
|
||||
</svg>
|
||||
<span className="absolute inset-0 flex items-center justify-center text-sm font-bold">
|
||||
{project.averageScore?.toFixed(1) || '--'}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center gap-1">
|
||||
<Star className="h-4 w-4 text-yellow-500" />
|
||||
<span className="text-xl font-bold">
|
||||
{project.averageScore?.toFixed(1) || '--'}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{project.voteCount} votes
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Score bar */}
|
||||
<div className="mt-3">
|
||||
<Progress
|
||||
value={
|
||||
project.averageScore
|
||||
? (project.averageScore / maxScore) * 100
|
||||
: 0
|
||||
}
|
||||
className="h-2"
|
||||
/>
|
||||
</div>
|
||||
{/* Score bar - shown for 'bar' format */}
|
||||
{scoreFormat !== 'number' && scoreFormat !== 'radial' && (
|
||||
<div className="mt-3">
|
||||
<Progress
|
||||
value={
|
||||
project.averageScore
|
||||
? (project.averageScore / maxScore) * 100
|
||||
: 0
|
||||
}
|
||||
className="h-2"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
@@ -178,10 +272,28 @@ function PublicScoresContent({ sessionId }: { sessionId: string }) {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Audience voting info */}
|
||||
{session.allowAudienceVotes && isVoting && (
|
||||
<Card className="border-primary/30 bg-primary/5">
|
||||
<CardContent className="py-4 text-center">
|
||||
<p className="text-sm font-medium">
|
||||
Audience voting is enabled for this session
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
<p className="text-center text-white/60 text-sm">
|
||||
Scores update in real-time
|
||||
</p>
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
{isConnected ? (
|
||||
<Wifi className="h-3 w-3 text-green-400" />
|
||||
) : (
|
||||
<WifiOff className="h-3 w-3 text-red-400" />
|
||||
)}
|
||||
<p className="text-center text-white/60 text-sm">
|
||||
Scores update in real-time
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -42,6 +42,8 @@ import {
|
||||
Camera,
|
||||
Lock,
|
||||
Bell,
|
||||
Mail,
|
||||
Calendar,
|
||||
Trash2,
|
||||
User,
|
||||
Tags,
|
||||
@@ -61,6 +63,10 @@ export default function ProfileSettingsPage() {
|
||||
const [phoneNumber, setPhoneNumber] = useState('')
|
||||
const [notificationPreference, setNotificationPreference] = useState('EMAIL')
|
||||
const [expertiseTags, setExpertiseTags] = useState<string[]>([])
|
||||
const [digestFrequency, setDigestFrequency] = useState('none')
|
||||
const [preferredWorkload, setPreferredWorkload] = useState<number | null>(null)
|
||||
const [availabilityStart, setAvailabilityStart] = useState('')
|
||||
const [availabilityEnd, setAvailabilityEnd] = useState('')
|
||||
const [profileLoaded, setProfileLoaded] = useState(false)
|
||||
|
||||
// Password form state
|
||||
@@ -81,6 +87,13 @@ export default function ProfileSettingsPage() {
|
||||
setPhoneNumber(user.phoneNumber || '')
|
||||
setNotificationPreference(user.notificationPreference || 'EMAIL')
|
||||
setExpertiseTags(user.expertiseTags || [])
|
||||
setDigestFrequency(user.digestFrequency || 'none')
|
||||
setPreferredWorkload(user.preferredWorkload ?? null)
|
||||
const avail = user.availabilityJson as { startDate?: string; endDate?: string } | null
|
||||
if (avail) {
|
||||
setAvailabilityStart(avail.startDate || '')
|
||||
setAvailabilityEnd(avail.endDate || '')
|
||||
}
|
||||
setProfileLoaded(true)
|
||||
}
|
||||
}, [user, profileLoaded])
|
||||
@@ -93,6 +106,12 @@ export default function ProfileSettingsPage() {
|
||||
phoneNumber: phoneNumber || null,
|
||||
notificationPreference: notificationPreference as 'EMAIL' | 'WHATSAPP' | 'BOTH' | 'NONE',
|
||||
expertiseTags,
|
||||
digestFrequency: digestFrequency as 'none' | 'daily' | 'weekly',
|
||||
preferredWorkload: preferredWorkload ?? undefined,
|
||||
availabilityJson: (availabilityStart || availabilityEnd) ? {
|
||||
startDate: availabilityStart || undefined,
|
||||
endDate: availabilityEnd || undefined,
|
||||
} : undefined,
|
||||
})
|
||||
toast.success('Profile updated successfully')
|
||||
refetch()
|
||||
@@ -275,6 +294,89 @@ export default function ProfileSettingsPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Email Digest */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Mail className="h-5 w-5" />
|
||||
Email Digest
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Receive periodic email summaries of pending actions and updates
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="digest-frequency">Digest Frequency</Label>
|
||||
<Select value={digestFrequency} onValueChange={setDigestFrequency}>
|
||||
<SelectTrigger id="digest-frequency">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">No digest</SelectItem>
|
||||
<SelectItem value="daily">Daily summary</SelectItem>
|
||||
<SelectItem value="weekly">Weekly summary</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Get a summary of pending evaluations, upcoming deadlines, and recent activity
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Availability & Workload */}
|
||||
{(user.role === 'JURY_MEMBER' || user.role === 'SUPER_ADMIN' || user.role === 'PROGRAM_ADMIN') && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Calendar className="h-5 w-5" />
|
||||
Availability & Workload
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Set your availability window and preferred evaluation workload
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="avail-start">Available From</Label>
|
||||
<Input
|
||||
id="avail-start"
|
||||
type="date"
|
||||
value={availabilityStart}
|
||||
onChange={(e) => setAvailabilityStart(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="avail-end">Available Until</Label>
|
||||
<Input
|
||||
id="avail-end"
|
||||
type="date"
|
||||
value={availabilityEnd}
|
||||
onChange={(e) => setAvailabilityEnd(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="workload">Preferred Workload (projects per round)</Label>
|
||||
<Input
|
||||
id="workload"
|
||||
type="number"
|
||||
min={1}
|
||||
max={50}
|
||||
value={preferredWorkload ?? ''}
|
||||
onChange={(e) => setPreferredWorkload(e.target.value ? parseInt(e.target.value) : null)}
|
||||
placeholder="e.g. 10"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
How many projects you prefer to evaluate per round
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Expertise Tags */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
48
src/app/api/cron/audit-cleanup/route.ts
Normal file
48
src/app/api/cron/audit-cleanup/route.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
export async function GET(request: NextRequest): Promise<NextResponse> {
|
||||
const cronSecret = request.headers.get('x-cron-secret')
|
||||
|
||||
if (!cronSecret || cronSecret !== process.env.CRON_SECRET) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
// Read retention period from system settings (default: 365 days)
|
||||
const retentionSetting = await prisma.systemSettings.findUnique({
|
||||
where: { key: 'audit_retention_days' },
|
||||
})
|
||||
|
||||
const retentionDays = retentionSetting
|
||||
? parseInt(retentionSetting.value, 10) || 365
|
||||
: 365
|
||||
|
||||
const cutoffDate = new Date()
|
||||
cutoffDate.setDate(cutoffDate.getDate() - retentionDays)
|
||||
|
||||
// Delete audit log entries older than the retention period
|
||||
const result = await prisma.auditLog.deleteMany({
|
||||
where: {
|
||||
timestamp: {
|
||||
lt: cutoffDate,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
cleanedUp: result.count,
|
||||
retentionDays,
|
||||
cutoffDate: cutoffDate.toISOString(),
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Cron audit cleanup failed:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
39
src/app/api/cron/digest/route.ts
Normal file
39
src/app/api/cron/digest/route.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { processDigests } from '@/server/services/email-digest'
|
||||
|
||||
export async function GET(request: NextRequest): Promise<NextResponse> {
|
||||
const cronSecret = request.headers.get('x-cron-secret')
|
||||
|
||||
if (!cronSecret || cronSecret !== process.env.CRON_SECRET) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
// Determine digest type: check query param, or default based on day of week
|
||||
const { searchParams } = new URL(request.url)
|
||||
let digestType = searchParams.get('type') as 'daily' | 'weekly' | null
|
||||
|
||||
if (!digestType) {
|
||||
const dayOfWeek = new Date().getDay()
|
||||
// Monday = 1 → run weekly; all other days → run daily
|
||||
digestType = dayOfWeek === 1 ? 'weekly' : 'daily'
|
||||
}
|
||||
|
||||
const result = await processDigests(digestType)
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
digestType,
|
||||
sent: result.sent,
|
||||
errors: result.errors,
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Cron digest processing failed:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
37
src/app/api/cron/draft-cleanup/route.ts
Normal file
37
src/app/api/cron/draft-cleanup/route.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
export async function GET(request: NextRequest): Promise<NextResponse> {
|
||||
const cronSecret = request.headers.get('x-cron-secret')
|
||||
|
||||
if (!cronSecret || cronSecret !== process.env.CRON_SECRET) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const now = new Date()
|
||||
|
||||
// Delete projects where isDraft=true AND draftExpiresAt has passed
|
||||
const result = await prisma.project.deleteMany({
|
||||
where: {
|
||||
isDraft: true,
|
||||
draftExpiresAt: {
|
||||
lt: now,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
cleanedUp: result.count,
|
||||
timestamp: now.toISOString(),
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Cron draft cleanup failed:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
124
src/app/api/files/bulk-download/route.ts
Normal file
124
src/app/api/files/bulk-download/route.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { getPresignedUrl, BUCKET_NAME } from '@/lib/minio'
|
||||
|
||||
export async function POST(request: NextRequest): Promise<NextResponse> {
|
||||
const session = await auth()
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { projectId, fileIds } = body as {
|
||||
projectId?: string
|
||||
fileIds?: string[]
|
||||
}
|
||||
|
||||
if (!projectId || !fileIds || !Array.isArray(fileIds) || fileIds.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'projectId and fileIds array are required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
const userRole = session.user.role
|
||||
|
||||
// Authorization: must be admin or assigned jury/mentor for this project
|
||||
const isAdmin = userRole === 'SUPER_ADMIN' || userRole === 'PROGRAM_ADMIN'
|
||||
|
||||
if (!isAdmin) {
|
||||
// Check if user is assigned as jury
|
||||
const juryAssignment = await prisma.assignment.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
projectId,
|
||||
},
|
||||
})
|
||||
|
||||
// Check if user is assigned as mentor
|
||||
const mentorAssignment = await prisma.mentorAssignment.findFirst({
|
||||
where: {
|
||||
mentorId: userId,
|
||||
projectId,
|
||||
},
|
||||
})
|
||||
|
||||
if (!juryAssignment && !mentorAssignment) {
|
||||
return NextResponse.json(
|
||||
{ error: 'You do not have access to this project\'s files' },
|
||||
{ status: 403 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch file metadata from DB
|
||||
const files = await prisma.projectFile.findMany({
|
||||
where: {
|
||||
id: { in: fileIds },
|
||||
projectId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
fileName: true,
|
||||
objectKey: true,
|
||||
mimeType: true,
|
||||
size: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (files.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No matching files found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Generate signed download URLs for each file
|
||||
const downloadUrls = await Promise.all(
|
||||
files.map(async (file) => {
|
||||
try {
|
||||
const downloadUrl = await getPresignedUrl(
|
||||
BUCKET_NAME,
|
||||
file.objectKey,
|
||||
'GET',
|
||||
3600 // 1 hour expiry for bulk downloads
|
||||
)
|
||||
|
||||
return {
|
||||
id: file.id,
|
||||
fileName: file.fileName,
|
||||
mimeType: file.mimeType,
|
||||
size: file.size,
|
||||
downloadUrl,
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[BulkDownload] Failed to get URL for file ${file.id}:`, error)
|
||||
return {
|
||||
id: file.id,
|
||||
fileName: file.fileName,
|
||||
mimeType: file.mimeType,
|
||||
size: file.size,
|
||||
downloadUrl: null,
|
||||
error: 'Failed to generate download URL',
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
projectId,
|
||||
files: downloadUrls,
|
||||
expiresIn: 3600,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('[BulkDownload] Error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
180
src/app/api/live-voting/stream/route.ts
Normal file
180
src/app/api/live-voting/stream/route.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function GET(request: NextRequest): Promise<Response> {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const sessionId = searchParams.get('sessionId')
|
||||
|
||||
if (!sessionId) {
|
||||
return new Response(JSON.stringify({ error: 'sessionId is required' }), {
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
// Verify the session exists
|
||||
const session = await prisma.liveVotingSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
select: { id: true, status: true },
|
||||
})
|
||||
|
||||
if (!session) {
|
||||
return new Response(JSON.stringify({ error: 'Session not found' }), {
|
||||
status: 404,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
// Track state for change detection
|
||||
let lastVoteCount = -1
|
||||
let lastProjectId: string | null = null
|
||||
let lastStatus: string | null = null
|
||||
|
||||
const sendEvent = (event: string, data: unknown) => {
|
||||
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
|
||||
controller.enqueue(encoder.encode(payload))
|
||||
}
|
||||
|
||||
// Send initial connection event
|
||||
sendEvent('connected', { sessionId, timestamp: new Date().toISOString() })
|
||||
|
||||
const poll = async () => {
|
||||
try {
|
||||
const currentSession = await prisma.liveVotingSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
select: {
|
||||
status: true,
|
||||
currentProjectId: true,
|
||||
currentProjectIndex: true,
|
||||
votingEndsAt: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!currentSession) {
|
||||
sendEvent('session_status', { status: 'DELETED' })
|
||||
controller.close()
|
||||
return false
|
||||
}
|
||||
|
||||
// Check for status changes
|
||||
if (lastStatus !== null && currentSession.status !== lastStatus) {
|
||||
sendEvent('session_status', {
|
||||
status: currentSession.status,
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
lastStatus = currentSession.status
|
||||
|
||||
// Check for project changes
|
||||
if (
|
||||
lastProjectId !== null &&
|
||||
currentSession.currentProjectId !== lastProjectId
|
||||
) {
|
||||
sendEvent('project_change', {
|
||||
projectId: currentSession.currentProjectId,
|
||||
projectIndex: currentSession.currentProjectIndex,
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
lastProjectId = currentSession.currentProjectId
|
||||
|
||||
// Check for vote updates on the current project
|
||||
if (currentSession.currentProjectId) {
|
||||
const voteCount = await prisma.liveVote.count({
|
||||
where: {
|
||||
sessionId,
|
||||
projectId: currentSession.currentProjectId,
|
||||
},
|
||||
})
|
||||
|
||||
if (lastVoteCount !== -1 && voteCount !== lastVoteCount) {
|
||||
// Get the latest vote info
|
||||
const latestVotes = await prisma.liveVote.findMany({
|
||||
where: {
|
||||
sessionId,
|
||||
projectId: currentSession.currentProjectId,
|
||||
},
|
||||
select: {
|
||||
score: true,
|
||||
isAudienceVote: true,
|
||||
votedAt: true,
|
||||
},
|
||||
orderBy: { votedAt: 'desc' },
|
||||
take: 1,
|
||||
})
|
||||
|
||||
const avgScore = await prisma.liveVote.aggregate({
|
||||
where: {
|
||||
sessionId,
|
||||
projectId: currentSession.currentProjectId,
|
||||
},
|
||||
_avg: { score: true },
|
||||
_count: true,
|
||||
})
|
||||
|
||||
sendEvent('vote_update', {
|
||||
projectId: currentSession.currentProjectId,
|
||||
totalVotes: voteCount,
|
||||
averageScore: avgScore._avg.score,
|
||||
latestVote: latestVotes[0] || null,
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
lastVoteCount = voteCount
|
||||
}
|
||||
|
||||
// Stop polling if session is completed
|
||||
if (currentSession.status === 'COMPLETED') {
|
||||
sendEvent('session_status', {
|
||||
status: 'COMPLETED',
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
controller.close()
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('[SSE] Poll error:', error)
|
||||
return true // Keep trying
|
||||
}
|
||||
}
|
||||
|
||||
// Initial poll to set baseline state
|
||||
const shouldContinue = await poll()
|
||||
if (!shouldContinue) return
|
||||
|
||||
// Poll every 2 seconds
|
||||
const interval = setInterval(async () => {
|
||||
const cont = await poll()
|
||||
if (!cont) {
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, 2000)
|
||||
|
||||
// Clean up on abort
|
||||
request.signal.addEventListener('abort', () => {
|
||||
clearInterval(interval)
|
||||
try {
|
||||
controller.close()
|
||||
} catch {
|
||||
// Stream may already be closed
|
||||
}
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { Metadata } from 'next'
|
||||
import { NextIntlClientProvider } from 'next-intl'
|
||||
import { getLocale, getMessages } from 'next-intl/server'
|
||||
import './globals.css'
|
||||
import { Providers } from './providers'
|
||||
import { Toaster } from 'sonner'
|
||||
@@ -14,15 +16,20 @@ export const metadata: Metadata = {
|
||||
},
|
||||
}
|
||||
|
||||
export default function RootLayout({
|
||||
export default async function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode
|
||||
}>) {
|
||||
const locale = await getLocale()
|
||||
const messages = await getMessages()
|
||||
|
||||
return (
|
||||
<html lang="en" className="light">
|
||||
<html lang={locale} className="light">
|
||||
<body className="min-h-screen bg-background font-sans antialiased">
|
||||
<Providers>{children}</Providers>
|
||||
<NextIntlClientProvider messages={messages}>
|
||||
<Providers>{children}</Providers>
|
||||
</NextIntlClientProvider>
|
||||
<Toaster
|
||||
position="top-right"
|
||||
toastOptions={{
|
||||
|
||||
Reference in New Issue
Block a user