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, Users, UserCheck, User, Clock, } from 'lucide-react' import { toast } from 'sonner' import { m } from '@/ui/paraglide/messages.js' import type { QuotaRuleResponse } from '@shumai/dtos' import { QUOTA_RESOURCE_META, formatQuotaResourceValue, getQuotaPeriodLabel, } from '../quota/quota-display' import { QuotaRuleDialog } from './QuotaRuleDialog' interface QuotasSettingsProps { teamId: string } export const QuotasSettings: React.FC = ({ teamId }) => { const queryClient = useQueryClient() const [isCreateOpen, setIsCreateOpen] = useState(false) const [selectedRule, setSelectedRule] = 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 = QUOTA_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 */}
{/* 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 */} {formatQuotaResourceValue(rule.resource, rule.limit)} {meta?.unit} /{' '} {getQuotaPeriodLabel(rule.period)}
) })}
)}
{/* Create / Edit Rule Dialog */} {(isCreateOpen || !!selectedRule) && ( { if (!open) { setIsCreateOpen(false) setSelectedRule(null) } }} teamId={teamId} rule={selectedRule} /> )} {/* 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()}
) }