Apply full refactor updates plus pipeline/email UX confirmations
All checks were successful
Build and Push Docker Image / build (push) Successful in 10m33s

This commit is contained in:
Matt
2026-02-14 15:26:42 +01:00
parent e56e143a40
commit b5425e705e
374 changed files with 116737 additions and 111969 deletions

View File

@@ -1,353 +1,353 @@
'use client'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { toast } from 'sonner'
import { Cog, Loader2, Zap, AlertCircle, RefreshCw, SlidersHorizontal } from 'lucide-react'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Skeleton } from '@/components/ui/skeleton'
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
const formSchema = z.object({
ai_enabled: z.boolean(),
ai_provider: z.string(),
ai_model: z.string(),
ai_send_descriptions: z.boolean(),
openai_api_key: z.string().optional(),
})
type FormValues = z.infer<typeof formSchema>
interface AISettingsFormProps {
settings: {
ai_enabled?: string
ai_provider?: string
ai_model?: string
ai_send_descriptions?: string
openai_api_key?: string
}
}
export function AISettingsForm({ settings }: AISettingsFormProps) {
const utils = trpc.useUtils()
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
ai_enabled: settings.ai_enabled === 'true',
ai_provider: settings.ai_provider || 'openai',
ai_model: settings.ai_model || 'gpt-4o',
ai_send_descriptions: settings.ai_send_descriptions === 'true',
openai_api_key: '',
},
})
// Fetch available models from OpenAI API
const {
data: modelsData,
isLoading: modelsLoading,
error: modelsError,
refetch: refetchModels,
} = trpc.settings.listAIModels.useQuery(undefined, {
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
retry: false,
})
const updateSettings = trpc.settings.updateMultiple.useMutation({
onSuccess: () => {
toast.success('AI settings saved successfully')
utils.settings.getByCategory.invalidate({ category: 'AI' })
},
onError: (error) => {
toast.error(`Failed to save settings: ${error.message}`)
},
})
const testConnection = trpc.settings.testAIConnection.useMutation({
onSuccess: (result) => {
if (result.success) {
toast.success(`AI connection successful! Model: ${result.model || result.modelTested}`)
// Refetch models after successful API key save/test
refetchModels()
} else {
toast.error(`Connection failed: ${result.error}`)
}
},
onError: (error) => {
toast.error(`Test failed: ${error.message}`)
},
})
const onSubmit = (data: FormValues) => {
const settingsToUpdate = [
{ key: 'ai_enabled', value: String(data.ai_enabled) },
{ key: 'ai_provider', value: data.ai_provider },
{ key: 'ai_model', value: data.ai_model },
{ key: 'ai_send_descriptions', value: String(data.ai_send_descriptions) },
]
// Only update API key if a new value was entered
if (data.openai_api_key && data.openai_api_key.trim()) {
settingsToUpdate.push({ key: 'openai_api_key', value: data.openai_api_key })
}
updateSettings.mutate({ settings: settingsToUpdate })
}
// Group models by category for better display
type ModelInfo = { id: string; name: string; isReasoning: boolean; category: string }
const groupedModels = modelsData?.models?.reduce<Record<string, ModelInfo[]>>(
(acc, model) => {
const category = model.category
if (!acc[category]) acc[category] = []
acc[category].push(model)
return acc
},
{}
)
const categoryLabels: Record<string, string> = {
'gpt-5+': 'GPT-5+ Series (Latest)',
'gpt-4o': 'GPT-4o Series',
'gpt-4': 'GPT-4 Series',
'gpt-3.5': 'GPT-3.5 Series',
reasoning: 'Reasoning Models (o1, o3, o4)',
other: 'Other Models',
}
const categoryOrder = ['gpt-5+', 'gpt-4o', 'gpt-4', 'gpt-3.5', 'reasoning', 'other']
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="ai_enabled"
render={({ field }) => (
<FormItem className="flex items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Enable AI Features</FormLabel>
<FormDescription>
Use AI to suggest optimal jury-project assignments
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="ai_provider"
render={({ field }) => (
<FormItem>
<FormLabel>AI Provider</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select provider" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="openai">OpenAI</SelectItem>
</SelectContent>
</Select>
<FormDescription>
AI provider for smart assignment suggestions
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="openai_api_key"
render={({ field }) => (
<FormItem>
<FormLabel>API Key</FormLabel>
<FormControl>
<Input
type="password"
placeholder={settings.openai_api_key ? '••••••••' : 'Enter API key'}
{...field}
/>
</FormControl>
<FormDescription>
Your OpenAI API key. Leave blank to keep the existing key.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="ai_model"
render={({ field }) => (
<FormItem>
<div className="flex items-center justify-between">
<FormLabel>Model</FormLabel>
{modelsData?.success && (
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => refetchModels()}
className="h-6 px-2 text-xs"
>
<RefreshCw className="mr-1 h-3 w-3" />
Refresh
</Button>
)}
</div>
{modelsLoading ? (
<Skeleton className="h-10 w-full" />
) : modelsError || !modelsData?.success ? (
<div className="space-y-2">
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
{modelsError?.message || modelsData?.error || 'Failed to load models. Save your API key first and test the connection.'}
</AlertDescription>
</Alert>
<Input
value={field.value}
onChange={(e) => field.onChange(e.target.value)}
placeholder="Enter model ID manually (e.g., gpt-4o)"
/>
</div>
) : (
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select model" />
</SelectTrigger>
</FormControl>
<SelectContent>
{categoryOrder
.filter((cat) => groupedModels?.[cat]?.length)
.map((category) => (
<SelectGroup key={category}>
<SelectLabel className="text-xs font-semibold text-muted-foreground">
{categoryLabels[category] || category}
</SelectLabel>
{groupedModels?.[category]?.map((model) => (
<SelectItem key={model.id} value={model.id}>
<div className="flex items-center gap-2">
{model.isReasoning && (
<SlidersHorizontal className="h-3 w-3 text-purple-500" />
)}
<span>{model.name}</span>
</div>
</SelectItem>
))}
</SelectGroup>
))}
</SelectContent>
</Select>
)}
<FormDescription>
{form.watch('ai_model')?.startsWith('o') ? (
<span className="flex items-center gap-1 text-purple-600">
<SlidersHorizontal className="h-3 w-3" />
Reasoning model - optimized for complex analysis tasks
</span>
) : (
'OpenAI model to use for AI features'
)}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="ai_send_descriptions"
render={({ field }) => (
<FormItem className="flex items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Send Project Descriptions</FormLabel>
<FormDescription>
Include anonymized project descriptions in AI requests for better matching
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<div className="flex gap-2">
<Button
type="submit"
disabled={updateSettings.isPending}
>
{updateSettings.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Saving...
</>
) : (
<>
<Cog className="mr-2 h-4 w-4" />
Save AI Settings
</>
)}
</Button>
<Button
type="button"
variant="outline"
onClick={() => testConnection.mutate()}
disabled={testConnection.isPending}
>
{testConnection.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Testing...
</>
) : (
<>
<Zap className="mr-2 h-4 w-4" />
Test Connection
</>
)}
</Button>
</div>
</form>
</Form>
)
}
'use client'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { toast } from 'sonner'
import { Cog, Loader2, Zap, AlertCircle, RefreshCw, SlidersHorizontal } from 'lucide-react'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Skeleton } from '@/components/ui/skeleton'
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
const formSchema = z.object({
ai_enabled: z.boolean(),
ai_provider: z.string(),
ai_model: z.string(),
ai_send_descriptions: z.boolean(),
openai_api_key: z.string().optional(),
})
type FormValues = z.infer<typeof formSchema>
interface AISettingsFormProps {
settings: {
ai_enabled?: string
ai_provider?: string
ai_model?: string
ai_send_descriptions?: string
openai_api_key?: string
}
}
export function AISettingsForm({ settings }: AISettingsFormProps) {
const utils = trpc.useUtils()
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
ai_enabled: settings.ai_enabled === 'true',
ai_provider: settings.ai_provider || 'openai',
ai_model: settings.ai_model || 'gpt-4o',
ai_send_descriptions: settings.ai_send_descriptions === 'true',
openai_api_key: '',
},
})
// Fetch available models from OpenAI API
const {
data: modelsData,
isLoading: modelsLoading,
error: modelsError,
refetch: refetchModels,
} = trpc.settings.listAIModels.useQuery(undefined, {
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
retry: false,
})
const updateSettings = trpc.settings.updateMultiple.useMutation({
onSuccess: () => {
toast.success('AI settings saved successfully')
utils.settings.getByCategory.invalidate({ category: 'AI' })
},
onError: (error) => {
toast.error(`Failed to save settings: ${error.message}`)
},
})
const testConnection = trpc.settings.testAIConnection.useMutation({
onSuccess: (result) => {
if (result.success) {
toast.success(`AI connection successful! Model: ${result.model || result.modelTested}`)
// Refetch models after successful API key save/test
refetchModels()
} else {
toast.error(`Connection failed: ${result.error}`)
}
},
onError: (error) => {
toast.error(`Test failed: ${error.message}`)
},
})
const onSubmit = (data: FormValues) => {
const settingsToUpdate = [
{ key: 'ai_enabled', value: String(data.ai_enabled) },
{ key: 'ai_provider', value: data.ai_provider },
{ key: 'ai_model', value: data.ai_model },
{ key: 'ai_send_descriptions', value: String(data.ai_send_descriptions) },
]
// Only update API key if a new value was entered
if (data.openai_api_key && data.openai_api_key.trim()) {
settingsToUpdate.push({ key: 'openai_api_key', value: data.openai_api_key })
}
updateSettings.mutate({ settings: settingsToUpdate })
}
// Group models by category for better display
type ModelInfo = { id: string; name: string; isReasoning: boolean; category: string }
const groupedModels = modelsData?.models?.reduce<Record<string, ModelInfo[]>>(
(acc, model) => {
const category = model.category
if (!acc[category]) acc[category] = []
acc[category].push(model)
return acc
},
{}
)
const categoryLabels: Record<string, string> = {
'gpt-5+': 'GPT-5+ Series (Latest)',
'gpt-4o': 'GPT-4o Series',
'gpt-4': 'GPT-4 Series',
'gpt-3.5': 'GPT-3.5 Series',
reasoning: 'Reasoning Models (o1, o3, o4)',
other: 'Other Models',
}
const categoryOrder = ['gpt-5+', 'gpt-4o', 'gpt-4', 'gpt-3.5', 'reasoning', 'other']
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="ai_enabled"
render={({ field }) => (
<FormItem className="flex items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Enable AI Features</FormLabel>
<FormDescription>
Use AI to suggest optimal jury-project assignments
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="ai_provider"
render={({ field }) => (
<FormItem>
<FormLabel>AI Provider</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select provider" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="openai">OpenAI</SelectItem>
</SelectContent>
</Select>
<FormDescription>
AI provider for smart assignment suggestions
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="openai_api_key"
render={({ field }) => (
<FormItem>
<FormLabel>API Key</FormLabel>
<FormControl>
<Input
type="password"
placeholder={settings.openai_api_key ? '••••••••' : 'Enter API key'}
{...field}
/>
</FormControl>
<FormDescription>
Your OpenAI API key. Leave blank to keep the existing key.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="ai_model"
render={({ field }) => (
<FormItem>
<div className="flex items-center justify-between">
<FormLabel>Model</FormLabel>
{modelsData?.success && (
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => refetchModels()}
className="h-6 px-2 text-xs"
>
<RefreshCw className="mr-1 h-3 w-3" />
Refresh
</Button>
)}
</div>
{modelsLoading ? (
<Skeleton className="h-10 w-full" />
) : modelsError || !modelsData?.success ? (
<div className="space-y-2">
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
{modelsError?.message || modelsData?.error || 'Failed to load models. Save your API key first and test the connection.'}
</AlertDescription>
</Alert>
<Input
value={field.value}
onChange={(e) => field.onChange(e.target.value)}
placeholder="Enter model ID manually (e.g., gpt-4o)"
/>
</div>
) : (
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select model" />
</SelectTrigger>
</FormControl>
<SelectContent>
{categoryOrder
.filter((cat) => groupedModels?.[cat]?.length)
.map((category) => (
<SelectGroup key={category}>
<SelectLabel className="text-xs font-semibold text-muted-foreground">
{categoryLabels[category] || category}
</SelectLabel>
{groupedModels?.[category]?.map((model) => (
<SelectItem key={model.id} value={model.id}>
<div className="flex items-center gap-2">
{model.isReasoning && (
<SlidersHorizontal className="h-3 w-3 text-purple-500" />
)}
<span>{model.name}</span>
</div>
</SelectItem>
))}
</SelectGroup>
))}
</SelectContent>
</Select>
)}
<FormDescription>
{form.watch('ai_model')?.startsWith('o') ? (
<span className="flex items-center gap-1 text-purple-600">
<SlidersHorizontal className="h-3 w-3" />
Reasoning model - optimized for complex analysis tasks
</span>
) : (
'OpenAI model to use for AI features'
)}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="ai_send_descriptions"
render={({ field }) => (
<FormItem className="flex items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Send Project Descriptions</FormLabel>
<FormDescription>
Include anonymized project descriptions in AI requests for better matching
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<div className="flex gap-2">
<Button
type="submit"
disabled={updateSettings.isPending}
>
{updateSettings.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Saving...
</>
) : (
<>
<Cog className="mr-2 h-4 w-4" />
Save AI Settings
</>
)}
</Button>
<Button
type="button"
variant="outline"
onClick={() => testConnection.mutate()}
disabled={testConnection.isPending}
>
{testConnection.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Testing...
</>
) : (
<>
<Zap className="mr-2 h-4 w-4" />
Test Connection
</>
)}
</Button>
</div>
</form>
</Form>
)
}

View File

@@ -1,294 +1,294 @@
'use client'
import { trpc } from '@/lib/trpc/client'
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Badge } from '@/components/ui/badge'
import {
Coins,
Zap,
TrendingUp,
Activity,
SlidersHorizontal,
Filter,
Users,
Award,
} from 'lucide-react'
import { cn } from '@/lib/utils'
const ACTION_ICONS: Record<string, typeof Zap> = {
ASSIGNMENT: Users,
FILTERING: Filter,
AWARD_ELIGIBILITY: Award,
MENTOR_MATCHING: SlidersHorizontal,
}
const ACTION_LABELS: Record<string, string> = {
ASSIGNMENT: 'Jury Assignment',
FILTERING: 'Project Filtering',
AWARD_ELIGIBILITY: 'Award Eligibility',
MENTOR_MATCHING: 'Mentor Matching',
}
function StatCard({
label,
value,
subValue,
icon: Icon,
trend,
}: {
label: string
value: string
subValue?: string
icon: typeof Zap
trend?: 'up' | 'down' | 'neutral'
}) {
return (
<div className="flex items-start gap-3 rounded-lg border bg-card p-4">
<div className="rounded-md bg-muted p-2">
<Icon className="h-4 w-4 text-muted-foreground" />
</div>
<div className="flex-1 space-y-1">
<p className="text-sm font-medium text-muted-foreground">{label}</p>
<div className="flex items-baseline gap-2">
<p className="text-2xl font-bold">{value}</p>
{trend && trend !== 'neutral' && (
<TrendingUp
className={cn(
'h-4 w-4',
trend === 'up' ? 'text-green-500' : 'rotate-180 text-red-500'
)}
/>
)}
</div>
{subValue && (
<p className="text-xs text-muted-foreground">{subValue}</p>
)}
</div>
</div>
)
}
function UsageBar({
label,
value,
maxValue,
color,
}: {
label: string
value: number
maxValue: number
color: string
}) {
const percentage = maxValue > 0 ? (value / maxValue) * 100 : 0
return (
<div className="space-y-1">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">{label}</span>
<span className="font-medium">{value.toLocaleString()}</span>
</div>
<div className="h-2 overflow-hidden rounded-full bg-muted">
<div
className={cn('h-full transition-all duration-500', color)}
style={{ width: `${percentage}%` }}
/>
</div>
</div>
)
}
export function AIUsageCard() {
const {
data: monthCost,
isLoading: monthLoading,
} = trpc.settings.getAICurrentMonthCost.useQuery(undefined, {
staleTime: 60 * 1000, // 1 minute
})
const {
data: stats,
isLoading: statsLoading,
} = trpc.settings.getAIUsageStats.useQuery({}, {
staleTime: 60 * 1000,
})
const {
data: history,
isLoading: historyLoading,
} = trpc.settings.getAIUsageHistory.useQuery({ days: 30 }, {
staleTime: 60 * 1000,
})
const isLoading = monthLoading || statsLoading
if (isLoading) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Activity className="h-5 w-5" />
AI Usage & Costs
</CardTitle>
<CardDescription>Loading usage data...</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="grid gap-4 sm:grid-cols-2">
<Skeleton className="h-24" />
<Skeleton className="h-24" />
</div>
<Skeleton className="h-32" />
</CardContent>
</Card>
)
}
const hasUsage = monthCost && monthCost.requestCount > 0
const maxTokensByAction = stats?.byAction
? Math.max(...Object.values(stats.byAction).map((a) => a.tokens))
: 0
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Activity className="h-5 w-5" />
AI Usage & Costs
</CardTitle>
<CardDescription>
Token usage and estimated costs for AI features
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* Current month summary */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<StatCard
label="This Month Cost"
value={monthCost?.costFormatted || '$0.00'}
subValue={`${monthCost?.requestCount || 0} requests`}
icon={Coins}
/>
<StatCard
label="Tokens Used"
value={monthCost?.tokens?.toLocaleString() || '0'}
subValue="This month"
icon={Zap}
/>
{stats && (
<StatCard
label="All-Time Cost"
value={stats.totalCostFormatted || '$0.00'}
subValue={`${stats.totalTokens?.toLocaleString() || 0} tokens`}
icon={TrendingUp}
/>
)}
</div>
{/* Usage by action */}
{hasUsage && stats?.byAction && Object.keys(stats.byAction).length > 0 && (
<div className="space-y-4">
<h4 className="text-sm font-semibold">Usage by Feature</h4>
<div className="space-y-3">
{Object.entries(stats.byAction)
.sort(([, a], [, b]) => b.tokens - a.tokens)
.map(([action, data]) => {
const Icon = ACTION_ICONS[action] || Zap
return (
<div key={action} className="flex items-center gap-3">
<div className="rounded-md bg-muted p-1.5">
<Icon className="h-3.5 w-3.5 text-muted-foreground" />
</div>
<div className="flex-1">
<UsageBar
label={ACTION_LABELS[action] || action}
value={data.tokens}
maxValue={maxTokensByAction}
color="bg-primary"
/>
</div>
<Badge variant="secondary" className="ml-2 text-xs">
{(data as { costFormatted?: string }).costFormatted}
</Badge>
</div>
)
})}
</div>
</div>
)}
{/* Usage by model */}
{hasUsage && stats?.byModel && Object.keys(stats.byModel).length > 0 && (
<div className="space-y-4">
<h4 className="text-sm font-semibold">Usage by Model</h4>
<div className="flex flex-wrap gap-2">
{Object.entries(stats.byModel)
.sort(([, a], [, b]) => b.cost - a.cost)
.map(([model, data]) => (
<Badge
key={model}
variant="outline"
className="flex items-center gap-2"
>
<SlidersHorizontal className="h-3 w-3" />
<span>{model}</span>
<span className="text-muted-foreground">
{(data as { costFormatted?: string }).costFormatted}
</span>
</Badge>
))}
</div>
</div>
)}
{/* Usage history mini chart */}
{hasUsage && history && history.length > 0 && (
<div className="space-y-4">
<h4 className="text-sm font-semibold">Last 30 Days</h4>
<div className="flex h-16 items-end gap-0.5">
{(() => {
const maxCost = Math.max(...history.map((d) => d.cost), 0.001)
return history.slice(-30).map((day, i) => {
const height = (day.cost / maxCost) * 100
return (
<div
key={day.date}
className="group relative flex-1 cursor-pointer"
title={`${day.date}: ${day.costFormatted}`}
>
<div
className="w-full rounded-t bg-primary/60 transition-colors hover:bg-primary"
style={{ height: `${Math.max(height, 4)}%` }}
/>
</div>
)
})
})()}
</div>
<div className="flex justify-between text-xs text-muted-foreground">
<span>{history[0]?.date}</span>
<span>{history[history.length - 1]?.date}</span>
</div>
</div>
)}
{/* No usage message */}
{!hasUsage && (
<div className="rounded-lg border border-dashed p-8 text-center">
<Activity className="mx-auto h-8 w-8 text-muted-foreground" />
<h4 className="mt-2 text-sm font-semibold">No AI usage yet</h4>
<p className="mt-1 text-sm text-muted-foreground">
AI usage will be tracked when you use filtering, assignments, or
other AI-powered features.
</p>
</div>
)}
</CardContent>
</Card>
)
}
'use client'
import { trpc } from '@/lib/trpc/client'
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Badge } from '@/components/ui/badge'
import {
Coins,
Zap,
TrendingUp,
Activity,
SlidersHorizontal,
Filter,
Users,
Award,
} from 'lucide-react'
import { cn } from '@/lib/utils'
const ACTION_ICONS: Record<string, typeof Zap> = {
ASSIGNMENT: Users,
FILTERING: Filter,
AWARD_ELIGIBILITY: Award,
MENTOR_MATCHING: SlidersHorizontal,
}
const ACTION_LABELS: Record<string, string> = {
ASSIGNMENT: 'Jury Assignment',
FILTERING: 'Project Filtering',
AWARD_ELIGIBILITY: 'Award Eligibility',
MENTOR_MATCHING: 'Mentor Matching',
}
function StatCard({
label,
value,
subValue,
icon: Icon,
trend,
}: {
label: string
value: string
subValue?: string
icon: typeof Zap
trend?: 'up' | 'down' | 'neutral'
}) {
return (
<div className="flex items-start gap-3 rounded-lg border bg-card p-4">
<div className="rounded-md bg-muted p-2">
<Icon className="h-4 w-4 text-muted-foreground" />
</div>
<div className="flex-1 space-y-1">
<p className="text-sm font-medium text-muted-foreground">{label}</p>
<div className="flex items-baseline gap-2">
<p className="text-2xl font-bold">{value}</p>
{trend && trend !== 'neutral' && (
<TrendingUp
className={cn(
'h-4 w-4',
trend === 'up' ? 'text-green-500' : 'rotate-180 text-red-500'
)}
/>
)}
</div>
{subValue && (
<p className="text-xs text-muted-foreground">{subValue}</p>
)}
</div>
</div>
)
}
function UsageBar({
label,
value,
maxValue,
color,
}: {
label: string
value: number
maxValue: number
color: string
}) {
const percentage = maxValue > 0 ? (value / maxValue) * 100 : 0
return (
<div className="space-y-1">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">{label}</span>
<span className="font-medium">{value.toLocaleString()}</span>
</div>
<div className="h-2 overflow-hidden rounded-full bg-muted">
<div
className={cn('h-full transition-all duration-500', color)}
style={{ width: `${percentage}%` }}
/>
</div>
</div>
)
}
export function AIUsageCard() {
const {
data: monthCost,
isLoading: monthLoading,
} = trpc.settings.getAICurrentMonthCost.useQuery(undefined, {
staleTime: 60 * 1000, // 1 minute
})
const {
data: stats,
isLoading: statsLoading,
} = trpc.settings.getAIUsageStats.useQuery({}, {
staleTime: 60 * 1000,
})
const {
data: history,
isLoading: historyLoading,
} = trpc.settings.getAIUsageHistory.useQuery({ days: 30 }, {
staleTime: 60 * 1000,
})
const isLoading = monthLoading || statsLoading
if (isLoading) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Activity className="h-5 w-5" />
AI Usage & Costs
</CardTitle>
<CardDescription>Loading usage data...</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="grid gap-4 sm:grid-cols-2">
<Skeleton className="h-24" />
<Skeleton className="h-24" />
</div>
<Skeleton className="h-32" />
</CardContent>
</Card>
)
}
const hasUsage = monthCost && monthCost.requestCount > 0
const maxTokensByAction = stats?.byAction
? Math.max(...Object.values(stats.byAction).map((a) => a.tokens))
: 0
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Activity className="h-5 w-5" />
AI Usage & Costs
</CardTitle>
<CardDescription>
Token usage and estimated costs for AI features
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* Current month summary */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<StatCard
label="This Month Cost"
value={monthCost?.costFormatted || '$0.00'}
subValue={`${monthCost?.requestCount || 0} requests`}
icon={Coins}
/>
<StatCard
label="Tokens Used"
value={monthCost?.tokens?.toLocaleString() || '0'}
subValue="This month"
icon={Zap}
/>
{stats && (
<StatCard
label="All-Time Cost"
value={stats.totalCostFormatted || '$0.00'}
subValue={`${stats.totalTokens?.toLocaleString() || 0} tokens`}
icon={TrendingUp}
/>
)}
</div>
{/* Usage by action */}
{hasUsage && stats?.byAction && Object.keys(stats.byAction).length > 0 && (
<div className="space-y-4">
<h4 className="text-sm font-semibold">Usage by Feature</h4>
<div className="space-y-3">
{Object.entries(stats.byAction)
.sort(([, a], [, b]) => b.tokens - a.tokens)
.map(([action, data]) => {
const Icon = ACTION_ICONS[action] || Zap
return (
<div key={action} className="flex items-center gap-3">
<div className="rounded-md bg-muted p-1.5">
<Icon className="h-3.5 w-3.5 text-muted-foreground" />
</div>
<div className="flex-1">
<UsageBar
label={ACTION_LABELS[action] || action}
value={data.tokens}
maxValue={maxTokensByAction}
color="bg-primary"
/>
</div>
<Badge variant="secondary" className="ml-2 text-xs">
{(data as { costFormatted?: string }).costFormatted}
</Badge>
</div>
)
})}
</div>
</div>
)}
{/* Usage by model */}
{hasUsage && stats?.byModel && Object.keys(stats.byModel).length > 0 && (
<div className="space-y-4">
<h4 className="text-sm font-semibold">Usage by Model</h4>
<div className="flex flex-wrap gap-2">
{Object.entries(stats.byModel)
.sort(([, a], [, b]) => b.cost - a.cost)
.map(([model, data]) => (
<Badge
key={model}
variant="outline"
className="flex items-center gap-2"
>
<SlidersHorizontal className="h-3 w-3" />
<span>{model}</span>
<span className="text-muted-foreground">
{(data as { costFormatted?: string }).costFormatted}
</span>
</Badge>
))}
</div>
</div>
)}
{/* Usage history mini chart */}
{hasUsage && history && history.length > 0 && (
<div className="space-y-4">
<h4 className="text-sm font-semibold">Last 30 Days</h4>
<div className="flex h-16 items-end gap-0.5">
{(() => {
const maxCost = Math.max(...history.map((d) => d.cost), 0.001)
return history.slice(-30).map((day, i) => {
const height = (day.cost / maxCost) * 100
return (
<div
key={day.date}
className="group relative flex-1 cursor-pointer"
title={`${day.date}: ${day.costFormatted}`}
>
<div
className="w-full rounded-t bg-primary/60 transition-colors hover:bg-primary"
style={{ height: `${Math.max(height, 4)}%` }}
/>
</div>
)
})
})()}
</div>
<div className="flex justify-between text-xs text-muted-foreground">
<span>{history[0]?.date}</span>
<span>{history[history.length - 1]?.date}</span>
</div>
</div>
)}
{/* No usage message */}
{!hasUsage && (
<div className="rounded-lg border border-dashed p-8 text-center">
<Activity className="mx-auto h-8 w-8 text-muted-foreground" />
<h4 className="mt-2 text-sm font-semibold">No AI usage yet</h4>
<p className="mt-1 text-sm text-muted-foreground">
AI usage will be tracked when you use filtering, assignments, or
other AI-powered features.
</p>
</div>
)}
</CardContent>
</Card>
)
}

View File

@@ -1,209 +1,209 @@
'use client'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { toast } from 'sonner'
import { Loader2, Settings } from 'lucide-react'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
const COMMON_TIMEZONES = [
{ value: 'Europe/Monaco', label: 'Monaco (CET/CEST)' },
{ value: 'Europe/Paris', label: 'Paris (CET/CEST)' },
{ value: 'Europe/London', label: 'London (GMT/BST)' },
{ value: 'America/New_York', label: 'New York (EST/EDT)' },
{ value: 'America/Los_Angeles', label: 'Los Angeles (PST/PDT)' },
{ value: 'Asia/Tokyo', label: 'Tokyo (JST)' },
{ value: 'Asia/Singapore', label: 'Singapore (SGT)' },
{ value: 'Australia/Sydney', label: 'Sydney (AEST/AEDT)' },
{ value: 'UTC', label: 'UTC' },
]
const formSchema = z.object({
default_timezone: z.string().min(1, 'Timezone is required'),
default_page_size: z.string().regex(/^\d+$/, 'Must be a number'),
autosave_interval_seconds: z.string().regex(/^\d+$/, 'Must be a number'),
display_project_names_uppercase: z.string().optional(),
})
type FormValues = z.infer<typeof formSchema>
interface DefaultsSettingsFormProps {
settings: {
default_timezone?: string
default_page_size?: string
autosave_interval_seconds?: string
display_project_names_uppercase?: string
}
}
export function DefaultsSettingsForm({ settings }: DefaultsSettingsFormProps) {
const utils = trpc.useUtils()
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
default_timezone: settings.default_timezone || 'Europe/Monaco',
default_page_size: settings.default_page_size || '20',
autosave_interval_seconds: settings.autosave_interval_seconds || '30',
display_project_names_uppercase: settings.display_project_names_uppercase || 'true',
},
})
const updateSettings = trpc.settings.updateMultiple.useMutation({
onSuccess: () => {
toast.success('Default settings saved successfully')
utils.settings.getByCategory.invalidate({ category: 'DEFAULTS' })
},
onError: (error) => {
toast.error(`Failed to save settings: ${error.message}`)
},
})
const onSubmit = (data: FormValues) => {
updateSettings.mutate({
settings: [
{ key: 'default_timezone', value: data.default_timezone },
{ key: 'default_page_size', value: data.default_page_size },
{ key: 'autosave_interval_seconds', value: data.autosave_interval_seconds },
{ key: 'display_project_names_uppercase', value: data.display_project_names_uppercase || 'true' },
],
})
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="default_timezone"
render={({ field }) => (
<FormItem>
<FormLabel>Default Timezone</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select timezone" />
</SelectTrigger>
</FormControl>
<SelectContent>
{COMMON_TIMEZONES.map((tz) => (
<SelectItem key={tz.value} value={tz.value}>
{tz.label}
</SelectItem>
))}
</SelectContent>
</Select>
<FormDescription>
Timezone used for displaying dates and deadlines across the platform
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="default_page_size"
render={({ field }) => (
<FormItem>
<FormLabel>Default Page Size</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select page size" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="10">10 items per page</SelectItem>
<SelectItem value="20">20 items per page</SelectItem>
<SelectItem value="50">50 items per page</SelectItem>
<SelectItem value="100">100 items per page</SelectItem>
</SelectContent>
</Select>
<FormDescription>
Default number of items shown in lists and tables
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="autosave_interval_seconds"
render={({ field }) => (
<FormItem>
<FormLabel>Autosave Interval (seconds)</FormLabel>
<FormControl>
<Input type="number" min="10" max="120" placeholder="30" {...field} />
</FormControl>
<FormDescription>
How often evaluation forms are automatically saved while editing.
Lower values provide better data protection but increase server load.
Recommended: 30 seconds.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="display_project_names_uppercase"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">
Display Project Names in Uppercase
</FormLabel>
<FormDescription>
Show all project names in uppercase across the platform for a cleaner presentation
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value === 'true'}
onCheckedChange={(checked) => field.onChange(String(checked))}
/>
</FormControl>
</FormItem>
)}
/>
<Button type="submit" disabled={updateSettings.isPending}>
{updateSettings.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Saving...
</>
) : (
<>
<Settings className="mr-2 h-4 w-4" />
Save Default Settings
</>
)}
</Button>
</form>
</Form>
)
}
'use client'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { toast } from 'sonner'
import { Loader2, Settings } from 'lucide-react'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
const COMMON_TIMEZONES = [
{ value: 'Europe/Monaco', label: 'Monaco (CET/CEST)' },
{ value: 'Europe/Paris', label: 'Paris (CET/CEST)' },
{ value: 'Europe/London', label: 'London (GMT/BST)' },
{ value: 'America/New_York', label: 'New York (EST/EDT)' },
{ value: 'America/Los_Angeles', label: 'Los Angeles (PST/PDT)' },
{ value: 'Asia/Tokyo', label: 'Tokyo (JST)' },
{ value: 'Asia/Singapore', label: 'Singapore (SGT)' },
{ value: 'Australia/Sydney', label: 'Sydney (AEST/AEDT)' },
{ value: 'UTC', label: 'UTC' },
]
const formSchema = z.object({
default_timezone: z.string().min(1, 'Timezone is required'),
default_page_size: z.string().regex(/^\d+$/, 'Must be a number'),
autosave_interval_seconds: z.string().regex(/^\d+$/, 'Must be a number'),
display_project_names_uppercase: z.string().optional(),
})
type FormValues = z.infer<typeof formSchema>
interface DefaultsSettingsFormProps {
settings: {
default_timezone?: string
default_page_size?: string
autosave_interval_seconds?: string
display_project_names_uppercase?: string
}
}
export function DefaultsSettingsForm({ settings }: DefaultsSettingsFormProps) {
const utils = trpc.useUtils()
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
default_timezone: settings.default_timezone || 'Europe/Monaco',
default_page_size: settings.default_page_size || '20',
autosave_interval_seconds: settings.autosave_interval_seconds || '30',
display_project_names_uppercase: settings.display_project_names_uppercase || 'true',
},
})
const updateSettings = trpc.settings.updateMultiple.useMutation({
onSuccess: () => {
toast.success('Default settings saved successfully')
utils.settings.getByCategory.invalidate({ category: 'DEFAULTS' })
},
onError: (error) => {
toast.error(`Failed to save settings: ${error.message}`)
},
})
const onSubmit = (data: FormValues) => {
updateSettings.mutate({
settings: [
{ key: 'default_timezone', value: data.default_timezone },
{ key: 'default_page_size', value: data.default_page_size },
{ key: 'autosave_interval_seconds', value: data.autosave_interval_seconds },
{ key: 'display_project_names_uppercase', value: data.display_project_names_uppercase || 'true' },
],
})
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="default_timezone"
render={({ field }) => (
<FormItem>
<FormLabel>Default Timezone</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select timezone" />
</SelectTrigger>
</FormControl>
<SelectContent>
{COMMON_TIMEZONES.map((tz) => (
<SelectItem key={tz.value} value={tz.value}>
{tz.label}
</SelectItem>
))}
</SelectContent>
</Select>
<FormDescription>
Timezone used for displaying dates and deadlines across the platform
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="default_page_size"
render={({ field }) => (
<FormItem>
<FormLabel>Default Page Size</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select page size" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="10">10 items per page</SelectItem>
<SelectItem value="20">20 items per page</SelectItem>
<SelectItem value="50">50 items per page</SelectItem>
<SelectItem value="100">100 items per page</SelectItem>
</SelectContent>
</Select>
<FormDescription>
Default number of items shown in lists and tables
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="autosave_interval_seconds"
render={({ field }) => (
<FormItem>
<FormLabel>Autosave Interval (seconds)</FormLabel>
<FormControl>
<Input type="number" min="10" max="120" placeholder="30" {...field} />
</FormControl>
<FormDescription>
How often evaluation forms are automatically saved while editing.
Lower values provide better data protection but increase server load.
Recommended: 30 seconds.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="display_project_names_uppercase"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">
Display Project Names in Uppercase
</FormLabel>
<FormDescription>
Show all project names in uppercase across the platform for a cleaner presentation
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value === 'true'}
onCheckedChange={(checked) => field.onChange(String(checked))}
/>
</FormControl>
</FormItem>
)}
/>
<Button type="submit" disabled={updateSettings.isPending}>
{updateSettings.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Saving...
</>
) : (
<>
<Settings className="mr-2 h-4 w-4" />
Save Default Settings
</>
)}
</Button>
</form>
</Form>
)
}

File diff suppressed because it is too large Load Diff