import React, { useState } from 'react' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { client } from '@/ui/api/client' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card' import { Button } from '@/ui/components/ui/button' import { Badge } from '@/ui/components/ui/badge' import { Switch } from '@/ui/components/ui/switch' import { ScrollArea } from '@/ui/components/ui/scroll-area' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '@/ui/components/ui/dropdown-menu' import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@/ui/components/ui/alert-dialog' import { Gauge, Plus, Loader2, MoreVertical, Trash2, Cpu, DollarSign, Server, Terminal, Wrench, Users, UserCheck, User, Clock, Eye, } from 'lucide-react' import { toast } from 'sonner' import { m } from '@/ui/paraglide/messages.js' import type { QuotaRuleResponse, QuotaResourceTypeEnum } from '@shumai/dtos' import { formatQuotaPeriod } from '@shumai/dtos' import { QuotaRuleDialog } from './QuotaRuleDialog' import { QuotaUsageRecordsDialog } from './QuotaUsageRecordsDialog' interface QuotasSettingsProps { teamId: string } /* eslint-disable @typescript-eslint/naming-convention */ const RESOURCE_META: Record< QuotaResourceTypeEnum, { label: () => string; icon: React.ElementType; unit: string } > = { agent_total_tokens: { label: () => m.quota_resource_agent_total_tokens(), icon: Cpu, unit: 'tokens', }, agent_cost: { label: () => m.quota_resource_agent_cost(), icon: DollarSign, unit: '$', }, agent_mcp_call_count: { label: () => m.quota_resource_agent_mcp_call_count(), icon: Server, unit: 'calls', }, agent_bash_call_count: { label: () => m.quota_resource_agent_bash_call_count(), icon: Terminal, unit: 'calls', }, agent_tool_call_count: { label: () => m.quota_resource_agent_tool_call_count(), icon: Wrench, unit: 'calls', }, } /* eslint-enable @typescript-eslint/naming-convention */ function getPeriodLabel(period: string): string { const norm = formatQuotaPeriod(period) switch (norm) { case '1hour': return m.quota_period_1hour() case '5hour': return m.quota_period_5hour() case '1day': return m.quota_period_1day() case '7day': return m.quota_period_7day() default: return norm } } function formatResourceValue(resource: QuotaResourceTypeEnum, val: number): string { if (resource === 'agent_cost') { return `$${val.toFixed(2)}` } return val.toLocaleString() } export const QuotasSettings: React.FC = ({ teamId }) => { const queryClient = useQueryClient() const [isCreateOpen, setIsCreateOpen] = useState(false) const [selectedRule, setSelectedRule] = useState(null) const [viewingUsageRule, setViewingUsageRule] = useState(null) const [deletingRule, setDeletingRule] = useState(null) // Fetch quota rules const { data, isLoading } = useQuery({ queryKey: ['teams', teamId, 'quotas'], queryFn: async () => { const res = await client.api.teams[':teamId'].quotas.$get({ param: { teamId } }) if (!res.ok) throw new Error(m.failed_load_settings()) return await res.json() }, }) // Quick toggle enabled mutation const toggleMutation = useMutation({ mutationFn: async ({ id, enabled }: { id: string; enabled: boolean }) => { const res = await client.api.teams[':teamId'].quotas[':id'].$put({ param: { teamId, id }, json: { enabled }, }) if (!res.ok) throw new Error(m.failed_to_update_quota()) return await res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'quotas'] }) toast.success(m.quota_status_updated()) }, onError: (err) => { toast.error(err instanceof Error ? err.message : m.failed_to_update_quota()) }, }) // Delete rule mutation const deleteMutation = useMutation({ mutationFn: async (id: string) => { const res = await client.api.teams[':teamId'].quotas[':id'].$delete({ param: { teamId, id }, }) if (!res.ok) throw new Error(m.failed_to_delete_quota()) }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'quotas'] }) toast.success(m.quota_deleted_successfully()) setDeletingRule(null) }, onError: (err) => { toast.error(err instanceof Error ? err.message : m.failed_to_delete_quota()) }, }) const rules: QuotaRuleResponse[] = data?.rules || [] return (
{m.resource_quotas()} {m.resource_quotas_description()}
{isLoading ? (
) : rules.length === 0 ? (

{m.no_quotas_title()}

{m.no_quotas_description()}

) : (
{rules.map((rule) => { const meta = RESOURCE_META[rule.resource] const resData = (rule.resourceData as Record | null) || {} return (
setSelectedRule(rule)} className={`group relative flex flex-col justify-between p-5 rounded-xl border bg-card text-card-foreground shadow-2xs transition-all hover:border-primary/40 hover:shadow-xs cursor-pointer ${ !rule.enabled ? 'opacity-60 bg-muted/20' : '' }`} > {/* Top Row: Resource, Details, Switch, Actions */}
{meta?.label ? meta.label() : rule.resource}
{/* Subtitle / target details */}
{rule.resource === 'agent_mcp_call_count' && ( Server: {String(resData.id || '')} )} {rule.resource === 'agent_bash_call_count' && ( Match: {String(resData.match || '*')} )} {rule.resource === 'agent_tool_call_count' && ( Tool: {String(resData.name || resData.toolName || '*')} )}
{/* Quick Switch & Card Menu */}
e.stopPropagation()} > toggleMutation.mutate({ id: rule.id, enabled: checked }) } disabled={toggleMutation.isPending} /> setDeletingRule(rule)} className="text-destructive focus:text-destructive" > {m.delete()}
{/* Badges Row & View Usage Action */}
{/* Scope Mode & Role badge */} {rule.scopeMode === 'all_members' && ( {m.quota_scope_mode_all_members()} {rule.role ? ` (${rule.role})` : ` (${m.quota_scope_team()})`} )} {rule.scopeMode === 'each_member' && ( {m.quota_scope_mode_each_member()} {rule.role ? ` (${rule.role})` : ` (${m.quota_scope_team()})`} )} {rule.scopeMode === 'selected_members' && ( {m.quota_scope_mode_selected_members()} ( {rule.userIds?.length || 0}) )} {/* Limit & Period badge */} {formatResourceValue(rule.resource, rule.limit)} {meta?.unit} /{' '} {getPeriodLabel(rule.period)}
{/* View Usage Button */}
) })}
)}
{/* Create / Edit Rule Dialog */} {(isCreateOpen || !!selectedRule) && ( { if (!open) { setIsCreateOpen(false) setSelectedRule(null) } }} teamId={teamId} rule={selectedRule} /> )} {/* View Usage Records Dialog */} {!!viewingUsageRule && ( { if (!open) setViewingUsageRule(null) }} teamId={teamId} rule={viewingUsageRule} /> )} {/* Delete Confirmation Alert Dialog */} { if (!open) setDeletingRule(null) }} > {m.delete_quota()} {m.delete_quota_confirm()} {m.cancel()} { e.preventDefault() if (deletingRule) { deleteMutation.mutate(deletingRule.id) } }} disabled={deleteMutation.isPending} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" > {deleteMutation.isPending && } {m.delete()}
) }