import { useEffect, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { formatRemainingTime } from '@/ui/lib/time'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import { Badge } from '@/ui/components/ui/badge'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { Progress } from '@/ui/components/ui/progress'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/ui/components/ui/collapsible'
import {
Activity,
CheckCircle2,
ChevronDown,
Clock,
Gauge,
Loader2,
Search,
Users,
User,
UserCheck,
} from 'lucide-react'
import type { QuotaRecordResponse, QuotaRuleResponse } from '@shumai/dtos'
import { toast } from 'sonner'
import {
QUOTA_RESOURCE_META,
formatQuotaResourceValue,
getQuotaPeriodLabel,
} from '@/ui/components/quota/quota-display'
interface QuotaUsageDashboardProps {
teamId: string
}
function getRoleLabel(role: string): string {
switch (role.toLowerCase()) {
case 'owner':
return m.owner()
case 'editor':
return m.editor()
case 'reviewer':
return m.reviewer()
default:
return role
}
}
function getErrorMessage(body: unknown, fallback: string): string {
if (typeof body === 'object' && body !== null && 'message' in body) {
const message = body.message
if (typeof message === 'string') return message
}
return fallback
}
function RuleTarget({ rule }: { rule: QuotaRuleResponse }) {
const resourceData = rule.resourceData ?? {}
if (rule.resource === 'agent_mcp_call_count') {
return {m.quota_target_server({ value: String(resourceData.id ?? '') })}
}
if (rule.resource === 'agent_bash_call_count') {
return {m.quota_target_match({ value: String(resourceData.match ?? '*') })}
}
if (rule.resource === 'agent_tool_call_count') {
return (
{m.quota_target_tool({ value: String(resourceData.name ?? resourceData.toolName ?? '*') })}
)
}
return null
}
function ScopeBadge({ rule }: { rule: QuotaRuleResponse }) {
if (rule.scopeMode === 'all_members') {
return (
{m.quota_scope_mode_all_members()}
{rule.role ? ` (${getRoleLabel(rule.role)})` : ` (${m.quota_scope_team()})`}
)
}
if (rule.scopeMode === 'each_member') {
return (
{m.quota_scope_mode_each_member()}
{rule.role ? ` (${getRoleLabel(rule.role)})` : ` (${m.quota_scope_team()})`}
)
}
return (
{m.quota_scope_mode_selected_members()} ({rule.userIds?.length || 0})
)
}
function QuotaUsageRecordCard({
teamId,
rule,
record,
}: {
teamId: string
rule: QuotaRuleResponse
record: QuotaRecordResponse
}) {
const queryClient = useQueryClient()
const [isResetDialogOpen, setIsResetDialogOpen] = useState(false)
const [now, setNow] = useState(() => new Date())
const meta = QUOTA_RESOURCE_META[rule.resource]
const isSharedPool = rule.scopeMode === 'all_members'
const isOverLimit = record.percent >= 100
const target = isSharedPool
? rule.role
? `${m.quota_role_shared_pool()}: ${getRoleLabel(rule.role)}`
: m.quota_team_shared_pool()
: record.user?.name || record.userId || m.unknown()
useEffect(() => {
if (!record.isWindowActive || !record.periodEnd) return
const interval = window.setInterval(() => setNow(new Date()), 60000)
return () => window.clearInterval(interval)
}, [record.isWindowActive, record.periodEnd])
const resetMutation = useMutation({
mutationFn: async () => {
const response = await client.api.teams[':teamId'].quotas[':id'].records.reset.$post({
param: { teamId, id: rule.id },
json: { userId: record.userId ?? null },
})
if (!response.ok) {
const body: unknown = await response.json().catch(() => null)
throw new Error(getErrorMessage(body, m.failed_to_reset_quota()))
}
return await response.json()
},
onSuccess: () => {
void queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'quotas', rule.id, 'records'],
})
void queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'quotas'] })
setIsResetDialogOpen(false)
toast.success(m.quota_reset_successfully())
},
onError: (error) => {
const message = error instanceof Error ? error.message : m.failed_to_reset_quota()
setIsResetDialogOpen(false)
toast.error(message)
},
})
return (
<>
{isSharedPool ? (
) : (
{record.user?.name?.[0]?.toUpperCase() || 'U'}
)}
{target}
{!isSharedPool && record.user?.email && (
{record.user.email}
)}
{record.isWindowActive && record.periodEnd ? (
{m.quota_refreshes_in({ time: formatRemainingTime(record.periodEnd, now) })}
) : (
{m.quota_available()}
)}
{formatQuotaResourceValue(rule.resource, record.consumed)} /{' '}
{formatQuotaResourceValue(rule.resource, rule.limit)} {meta?.unit}
{record.percent}%
{record.isWindowActive && record.periodEnd ? (
{m.quota_refreshes_in({ time: formatRemainingTime(record.periodEnd, now) })}
) : (
{m.quota_available()}
)}
{m.quota_remaining()}: {formatQuotaResourceValue(rule.resource, record.remaining)}{' '}
{meta?.unit}
{m.quota_reset_usage()}
{m.quota_reset_usage_confirm({ target })}
{m.cancel()}
{
event.preventDefault()
resetMutation.mutate()
}}
disabled={resetMutation.isPending}
>
{resetMutation.isPending && }
{m.confirm()}
>
)
}
function QuotaRuleUsageItem({ teamId, rule }: { teamId: string; rule: QuotaRuleResponse }) {
const [isOpen, setIsOpen] = useState(false)
const [search, setSearch] = useState('')
const meta = QUOTA_RESOURCE_META[rule.resource]
const Icon = meta?.icon || Gauge
const { data, isLoading, isError } = useQuery({
queryKey: ['teams', teamId, 'quotas', rule.id, 'records'],
queryFn: async () => {
const response = await client.api.teams[':teamId'].quotas[':id'].records.$get({
param: { teamId, id: rule.id },
})
if (!response.ok) throw new Error(m.failed_to_load_quota_usage())
return await response.json()
},
enabled: isOpen,
refetchInterval: isOpen ? 10000 : false,
})
const records = data?.records ?? []
const filteredRecords = records.filter((record) => {
if (!search.trim()) return true
const query = search.toLowerCase()
return (
record.user?.name.toLowerCase().includes(query) ||
record.user?.email.toLowerCase().includes(query)
)
})
return (
{rule.scopeMode !== 'all_members' && records.length > 3 && (
setSearch(event.target.value)}
placeholder={m.quota_search_members()}
className="h-9 pl-9 text-sm"
/>
)}
{isLoading ? (
) : isError ? (
{m.failed_to_load_quota_usage()}
) : filteredRecords.length === 0 ? (
{m.quota_no_usage_records()}
) : (
filteredRecords.map((record, index) => (
))
)}
)
}
export function QuotaUsageDashboard({ teamId }: QuotaUsageDashboardProps) {
const { data, isLoading, isError } = useQuery({
queryKey: ['teams', teamId, 'quotas'],
queryFn: async () => {
const response = await client.api.teams[':teamId'].quotas.$get({ param: { teamId } })
if (!response.ok) throw new Error(m.failed_load_settings())
return await response.json()
},
enabled: !!teamId,
})
const rules = data?.rules ?? []
return (
{m.quotas()}
{m.quota_dashboard_description()}
{isLoading ? (
) : isError ? (
{m.failed_load_settings()}
) : rules.length === 0 ? (
{m.no_quotas_title()}
{m.no_quotas_description()}
) : (
{rules.map((rule) => (
))}
)}
)
}