Commit 7230e122 by ccran

feat: user info export; databoard export;

parent 4f24e2de
#!/usr/bin/env bash
# 本地运行、断点调试和前端热更新入口,可从任意目录调用。
set -euo pipefail
usage() {
cat <<'HELP'
用法:bash bin/local-debug.sh [run|debug|web|tunnel] [-- 后端参数...]
run 编译并前台运行 Go 后端(默认),启用 DEBUG 和 Gin debug 日志
debug 启动 Delve,等待 IDE 连接;连接后继续运行程序
web 启动前端热更新服务,在另一个终端配合 run/debug 使用
tunnel 仅建立 PostgreSQL 和 Redis SSH 隧道,保持前台运行
示例:
bash bin/local-debug.sh
bash bin/local-debug.sh debug
bash bin/local-debug.sh run -- --port 3001
VITE_REACT_APP_SERVER_URL=http://localhost:3001 bash bin/local-debug.sh web
环境变量:
DEBUG / GIN_MODE 默认 true / debug
DEBUG_PORT Delve 端口,默认 2345(仅监听 127.0.0.1)
WEB_PORT 前端端口,默认 5173
VITE_REACT_APP_SERVER_URL 前端 API 代理目标,默认 http://localhost:3000
REBUILD_WEB=1 启动后端前重新构建前端资源
SSH_TUNNEL=0 禁用 run/debug 默认建立的 SSH 隧道
SSH_HOST 默认 root@8.136.9.68,支持 ~/.ssh/config 别名
SSH_PORT 默认 22
POSTGRES_CONTAINER 默认 postgres
REDIS_CONTAINER 默认 redis
DOCKER_NETWORK 容器有多个网络时必须指定网络名称
LOCAL_POSTGRES_PORT 默认 5432,转发到容器 5432
LOCAL_REDIS_PORT 默认 6379,转发到容器 6379
run/debug 默认先 inspect 远端容器 IP,再建立仅监听 127.0.0.1 的隧道。
在根目录 .env 中将 SQL_DSN 地址改为 127.0.0.1:5432,
将 REDIS_CONN_STRING 地址改为 127.0.0.1:6379,保留远端账号、密码和库名。
若配置了 LOG_SQL_DSN 且使用同一 PostgreSQL,也需修改其地址。
脚本不会修改 .env;远端容器需要正在运行,SSH 用户需要 Docker 权限。
Ctrl+C 或后端退出会关闭本次创建的 SSH 隧道。
后端沿用项目根目录 .env;已有环境变量优先,不覆盖数据库配置。
PORT 环境变量(包括 .env 中的值)优先于后端 --port 参数。
缺少 web/dist/index.html 时自动安装前端依赖并构建资源。
需要 Go;构建/运行前端需要 Bun;断点调试还需要 PATH 中有 dlv。
Delve 安装:go install github.com/go-delve/delve/cmd/dlv@latest
IDE 使用 Go remote attach,连接 127.0.0.1:2345(Delve JSON-RPC)。
前端默认访问 http://localhost:5173;Ctrl+C 停止当前服务。
HELP
}
mode=${1:-run}
if (( $# > 0 )); then shift; fi
case "$mode" in
-h|--help|help) usage; exit 0 ;;
run|debug|web|tunnel) ;;
*) usage >&2; exit 1 ;;
esac
if [[ "${1:-}" == "--" ]]; then shift; fi
if [[ "$mode" == web && $# -ne 0 ]]; then
echo "web 模式请通过 WEB_PORT 和 VITE_REACT_APP_SERVER_URL 配置。" >&2
exit 1
fi
project_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
cd "$project_dir"
required_commands=()
if [[ "$mode" == run || "$mode" == debug ]]; then required_commands+=(go); fi
if [[ "$mode" == debug ]]; then required_commands+=(dlv); fi
if [[ "$mode" == web || ( "$mode" != tunnel && ( ! -f web/dist/index.html || "${REBUILD_WEB:-0}" == 1 ) ) ]]; then
required_commands+=(bun)
fi
if [[ "$mode" != web && ( "$mode" == tunnel || "${SSH_TUNNEL:-1}" != 0 ) ]]; then
required_commands+=(ssh)
fi
for command_name in "${required_commands[@]}"; do
if ! command -v "$command_name" >/dev/null 2>&1; then
echo "缺少命令:${command_name}。运行 $0 --help 查看依赖说明。" >&2
exit 1
fi
done
if [[ "$mode" == web ]]; then
cd web
if [[ ! -d node_modules ]]; then bun install --frozen-lockfile; fi
exec bun run dev -- --host 127.0.0.1 --port "${WEB_PORT:-5173}" --strict-port
fi
control_dir=''
child_pid=''
cleanup() {
result=$?
trap - EXIT INT TERM
if [[ -n "$child_pid" ]]; then
kill "$child_pid" 2>/dev/null || true
wait "$child_pid" 2>/dev/null || true
fi
if [[ -n "$control_dir" ]]; then
ssh -S "$control_dir/control" -O exit "$ssh_host" >/dev/null 2>&1 || true
rm -rf -- "$control_dir"
fi
exit "$result"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
if [[ "$mode" == tunnel || "${SSH_TUNNEL:-1}" != 0 ]]; then
ssh_host=${SSH_HOST:-root@8.136.9.68}
ssh_port=${SSH_PORT:-22}
pg_port=${LOCAL_POSTGRES_PORT:-5432}
redis_port=${LOCAL_REDIS_PORT:-6379}
if [[ -z "$ssh_host" || "$ssh_host" == -* || "$ssh_host" == *[[:space:]]* ]]; then
echo "SSH_HOST 无效。" >&2
exit 1
fi
for port in "$ssh_port" "$pg_port" "$redis_port"; do
if [[ ! "$port" =~ ^[1-9][0-9]{0,4}$ ]] || (( port > 65535 )); then
echo "SSH 和本地转发端口必须为 1–65535 的整数。" >&2
exit 1
fi
done
if [[ "$pg_port" == "$redis_port" ]]; then
echo "PostgreSQL 和 Redis 本地端口不能相同。" >&2
exit 1
fi
control_dir=$(mktemp -d /tmp/new-api-ssh.XXXXXX)
ssh_options=(-S "$control_dir/control" -p "$ssh_port" -o ControlMaster=no)
ssh "${ssh_options[@]}" -M -fN -o ControlPersist=no \
-o ServerAliveInterval=15 -o ServerAliveCountMax=3 "$ssh_host"
container_ips=()
for container in "${POSTGRES_CONTAINER:-postgres}" "${REDIS_CONTAINER:-redis}"; do
if [[ ! "$container" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]*$ ]]; then
echo "无效的容器名称:${container}" >&2
exit 1
fi
# Only request state/network fields; never print container environment secrets.
network_rows=$(ssh "${ssh_options[@]}" "$ssh_host" \
"docker inspect --format '{{if .State.Running}}{{range \$name, \$network := .NetworkSettings.Networks}}{{printf \"%s %s\\n\" \$name \$network.IPAddress}}{{end}}{{end}}' '$container'")
ips=()
while read -r network ip; do
[[ -n "$ip" ]] || continue
if [[ -z "${DOCKER_NETWORK:-}" || "$network" == "$DOCKER_NETWORK" ]]; then
ips+=("$ip")
fi
done <<< "$network_rows"
if (( ${#ips[@]} != 1 )); then
echo "容器 ${container} 需要唯一运行中的 IPv4 地址;多网络请设置 DOCKER_NETWORK。" >&2
exit 1
fi
if [[ ! "${ips[0]}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "容器 ${container} 返回无效 IP。" >&2
exit 1
fi
container_ips+=("${ips[0]}")
echo "容器 ${container} IP:${ips[0]}"
done
ssh "${ssh_options[@]}" -O forward -o ExitOnForwardFailure=yes \
-L "127.0.0.1:$pg_port:${container_ips[0]}:5432" \
-L "127.0.0.1:$redis_port:${container_ips[1]}:6379" "$ssh_host"
echo "隧道已建立:PostgreSQL 127.0.0.1:${pg_port},Redis 127.0.0.1:${redis_port}"
if [[ "$mode" == tunnel ]]; then
while ssh "${ssh_options[@]}" -O check "$ssh_host" >/dev/null 2>&1; do
sleep 2 &
child_pid=$!
wait "$child_pid"
child_pid=''
done
echo "SSH 隧道已断开。" >&2
exit 1
fi
fi
debug_port=${DEBUG_PORT:-2345}
if [[ "$mode" == debug ]]; then
if [[ ! "$debug_port" =~ ^[1-9][0-9]{0,4}$ ]] || (( debug_port > 65535 )); then
echo "DEBUG_PORT 必须为 1–65535 的整数。" >&2
exit 1
fi
fi
if [[ ! -f web/dist/index.html || "${REBUILD_WEB:-0}" == 1 ]]; then
echo "构建后端嵌入的前端资源..."
(
cd web
bun install --frozen-lockfile
VITE_REACT_APP_VERSION="$(cat ../VERSION)" bun run build
)
fi
export DEBUG=${DEBUG:-true}
export GIN_MODE=${GIN_MODE:-debug}
mkdir -p .cache/local-debug
if [[ "$mode" == debug ]]; then
echo "等待 IDE 连接 127.0.0.1:${debug_port},连接后继续运行。"
dlv debug . --headless --listen="127.0.0.1:$debug_port" --api-version=2 \
--output="$project_dir/.cache/local-debug/debug-bin" -- "$@" &
else
echo "编译本地后端..."
go build -o .cache/local-debug/new-api .
"$project_dir/.cache/local-debug/new-api" "$@" &
fi
child_pid=$!
wait "$child_pid"
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { Download, Loader2 } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import type { WorkBook } from 'xlsx'
import { Button } from '@/components/ui/button'
export interface ExcelExportButtonProps {
scopeKey: string
disabled?: boolean
maxRows: number
filename: string
emptyMessage: string
errorMessage: string
buildWorkbook: (
signal: AbortSignal,
onProgress: (count: number) => void
) => Promise<WorkBook | null>
}
export function ExcelExportButton(props: ExcelExportButtonProps) {
const { t } = useTranslation()
const [progress, setProgress] = useState<number | null>(null)
const activeExport = useRef<AbortController | null>(null)
const scopeKey = props.scopeKey
useEffect(() => {
setProgress(null)
return () => {
activeExport.current?.abort()
activeExport.current = null
}
}, [scopeKey])
const handleExport = async () => {
if (activeExport.current) return
const controller = new AbortController()
activeExport.current = controller
setProgress(0)
try {
const workbook = await props.buildWorkbook(controller.signal, (count) => {
if (activeExport.current === controller) setProgress(count)
})
controller.signal.throwIfAborted()
if (!workbook) {
toast.info(props.emptyMessage)
return
}
const XLSX = await import('xlsx')
controller.signal.throwIfAborted()
XLSX.writeFile(workbook, `${props.filename}-${Date.now()}.xlsx`, {
compression: true,
})
} catch (error) {
if (!controller.signal.aborted) {
toast.error(error instanceof Error ? error.message : props.errorMessage)
}
} finally {
if (activeExport.current === controller) {
activeExport.current = null
setProgress(null)
}
}
}
return (
<>
<Button
variant='outline'
disabled={props.disabled || progress !== null}
aria-busy={progress !== null}
title={t('Export applied filters to Excel (up to {{count}} rows).', {
count: props.maxRows,
})}
onClick={handleExport}
>
{progress !== null ? (
<Loader2
data-icon='inline-start'
className='animate-spin'
aria-hidden='true'
/>
) : (
<Download data-icon='inline-start' aria-hidden='true' />
)}
{progress !== null
? t('Exporting {{count}} rows', { count: progress })
: t('Export Excel')}
</Button>
{progress !== null && (
<Button
variant='ghost'
onClick={() => {
activeExport.current?.abort()
activeExport.current = null
setProgress(null)
}}
>
{t('Cancel')}
</Button>
)}
</>
)
}
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import fs from 'node:fs'
import {
act,
cleanup,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { flushSync } from 'react-dom'
import { afterEach, expect, it, vi } from 'vitest'
import * as XLSX from 'xlsx'
import { api } from '@/lib/api'
import { useAuthStore } from '@/stores/auth-store'
import {
useDashboardExportSection,
type ExportSection,
} from '../../hooks/use-dashboard-export'
import {
DashboardExportButton,
DashboardExportProvider,
} from '../dashboard-export'
import { LogStatCards } from '../models/log-stat-cards'
const ready: ExportSection = {
sheets: [
{ name: 'Details', headers: ['Name', 'Count'], rows: [['模型', 12]] },
],
}
function Source(props: { section: ExportSection }) {
useDashboardExportSection('source', props.section)
return null
}
function Harness(props: { section?: ExportSection; scope?: string }) {
return (
<DashboardExportProvider key={props.scope}>
{props.section && <Source section={props.section} />}
<DashboardExportButton
scope={props.scope ?? 'models'}
required={['source']}
/>
</DashboardExportProvider>
)
}
function downloadedWorkbook(spy: ReturnType<typeof vi.spyOn>): XLSX.WorkBook {
return XLSX.read(spy.mock.calls[0][1], { type: 'buffer' })
}
afterEach(() => {
cleanup()
useAuthStore.setState(useAuthStore.getInitialState(), true)
})
it('disables export until all page sources are mounted and finished loading', () => {
const view = render(<Harness />)
expect(screen.getByRole('button', { name: 'Export Excel' })).toBeDisabled()
view.rerender(<Harness section={{ ...ready, loading: true }} />)
expect(screen.getByRole('button', { name: 'Export Excel' })).toBeDisabled()
view.rerender(<Harness section={ready} />)
expect(screen.getByRole('button', { name: 'Export Excel' })).toBeEnabled()
})
it('downloads current data with export metadata using the shared Excel button', async () => {
const download = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
render(<Harness section={ready} />)
await userEvent.click(screen.getByRole('button', { name: 'Export Excel' }))
await waitFor(() => expect(download).toHaveBeenCalledTimes(1))
expect(download.mock.calls[0][0]).toMatch(/^dashboard-models-\d+\.xlsx$/)
const wb = downloadedWorkbook(download)
expect(wb.Sheets.Details.B2.v).toBe(12)
expect(wb.SheetNames).toContain('Export information')
})
it('reports failed sources in metadata without exporting stale or fabricated values', async () => {
const download = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
render(<Harness section={{ ...ready, error: true }} />)
await userEvent.click(screen.getByRole('button', { name: 'Export Excel' }))
await waitFor(() => expect(download).toHaveBeenCalled())
const wb = downloadedWorkbook(download)
expect(wb.SheetNames).not.toContain('Details')
expect(
JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets['Export information']))
).toContain('Failed to load')
})
it('replaces old data on scope changes and disables export when the new source has not loaded', async () => {
const download = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
const view = render(<Harness scope='models' section={ready} />)
view.rerender(<Harness scope='users' />)
expect(screen.getByRole('button', { name: 'Export Excel' })).toBeDisabled()
view.rerender(
<Harness
scope='users'
section={{
sheets: [{ name: 'New', headers: ['User'], rows: [['alice']] }],
}}
/>
)
await userEvent.click(screen.getByRole('button', { name: 'Export Excel' }))
await waitFor(() => expect(download).toHaveBeenCalled())
const wb = downloadedWorkbook(download)
expect(wb.SheetNames).not.toContain('Details')
expect(wb.Sheets.New.A2.v).toBe('alice')
})
it('exports model cards from the same filtered request and actual time window as the screen', async () => {
useAuthStore.getState().auth.setUser({
id: 1,
username: 'alice',
role: 1,
quota: 0,
used_quota: 0,
request_count: 0,
})
const get = vi.spyOn(api, 'get').mockResolvedValue({
data: {
success: true,
data: [
{
created_at: 1700000000,
model_name: 'model-a',
count: 120,
token_used: 6000,
quota: 500000,
},
],
},
})
const download = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
const start = new Date(1700000000000)
const end = new Date(1700003600000)
await act(async () => {
render(
<DashboardExportProvider>
<LogStatCards
filters={{
start_timestamp: start,
end_timestamp: end,
time_granularity: 'hour',
}}
/>
<DashboardExportButton scope='models' required={['models']} />
</DashboardExportProvider>
)
})
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Export Excel' })).toBeEnabled()
)
expect(get).toHaveBeenCalledWith('/api/data/self', {
params: {
start_timestamp: 1700000000,
end_timestamp: 1700003600,
default_time: 'hour',
},
})
await userEvent.click(screen.getByRole('button', { name: 'Export Excel' }))
await waitFor(() => expect(download).toHaveBeenCalled())
const wb = downloadedWorkbook(download)
const metrics = XLSX.utils.sheet_to_json(wb.Sheets['Model Call Analytics'], {
header: 1,
})
expect(metrics).toContainEqual(['Average RPM', 2])
expect(metrics).toContainEqual(['Average TPM', 100])
expect(wb.Sheets['Usage details'].D2.v).toBe(120)
})
for (const action of ['cancel', 'filter', 'unmount'] as const) {
it(`does not download an obsolete workbook after ${action}`, async () => {
const download = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
const view = render(<Harness section={ready} />)
await act(async () => {
flushSync(() =>
fireEvent.click(screen.getByRole('button', { name: 'Export Excel' }))
)
if (action === 'cancel') {
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
}
if (action === 'filter') {
view.rerender(<Harness section={{ ...ready, loading: true }} />)
}
if (action === 'unmount') view.unmount()
await import('xlsx')
})
expect(download).not.toHaveBeenCalled()
})
}
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useContext, useState, type ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import { ExcelExportButton } from '@/components/excel-export-button'
import { getCurrencyDisplay, getCurrencyLabel } from '@/lib/currency'
import {
ExportRegisterContext,
ExportSectionsContext,
type ExportSection,
} from '../hooks/use-dashboard-export'
import {
buildDashboardWorkbook,
MAX_DASHBOARD_EXPORT_ROWS,
metricSheet,
} from '../lib/export'
const SECTION_LABELS: Record<string, string> = {
overview: 'Setup guide',
summary: 'Usage at a glance',
models: 'Model Call Analytics',
users: 'User Analytics',
flow: 'Flow',
performance: 'Performance health',
'api-info': 'API Info',
announcements: 'Announcements',
faq: 'FAQ',
uptime: 'Uptime',
'model-charts': 'Model chart settings',
'consumption-chart': 'Consumption distribution',
}
export function DashboardExportProvider(props: { children: ReactNode }) {
const [sections, setSections] = useState<Record<string, ExportSection>>({})
const register = useCallback((id: string, section?: ExportSection) => {
setSections((previous) => {
if (JSON.stringify(previous[id]) === JSON.stringify(section)) {
return previous
}
const next = { ...previous }
if (section) next[id] = section
else delete next[id]
return next
})
}, [])
return (
<ExportRegisterContext.Provider value={register}>
<ExportSectionsContext.Provider value={sections}>
{props.children}
</ExportSectionsContext.Provider>
</ExportRegisterContext.Provider>
)
}
export function DashboardExportButton(props: {
required: string[]
scope: string
}) {
const { t } = useTranslation()
const context = useContext(ExportSectionsContext)
if (!context) return null
const sections = props.required.map((id) => context[id])
const disabled = sections.some((section) => !section || section.loading)
const snapshot = JSON.stringify(sections)
return (
<ExcelExportButton
scopeKey={`${props.scope}:${snapshot}`}
disabled={disabled}
maxRows={MAX_DASHBOARD_EXPORT_ROWS}
filename={`dashboard-${props.scope}`}
emptyMessage={t('No data available')}
errorMessage={t('Failed to export dashboard')}
buildWorkbook={async (signal, onProgress) => {
const { config, meta } = getCurrencyDisplay()
const metadata = metricSheet(
t('Export information'),
[
[t('Page'), t(SECTION_LABELS[props.scope] ?? props.scope)],
[t('Exported at'), new Date()],
[t('Timezone'), Intl.DateTimeFormat().resolvedOptions().timeZone],
[t('Currency'), getCurrencyLabel()],
[t('Quota per USD'), config.quotaPerUnit],
[
t('Exchange rate'),
meta.kind === 'tokens' ? null : meta.exchangeRate,
],
[
t('Export scope'),
t(
'Current page and filters; all loaded detail rows. Charts are exported as data tables.'
),
],
...props.required.map((id, index) => [
t(SECTION_LABELS[id] ?? id),
sections[index]?.error ? t('Failed to load') : t('Loaded'),
]),
],
t
)
return buildDashboardWorkbook(
[
metadata,
...sections.flatMap((section) =>
section?.error ? [] : (section?.sheets ?? [])
),
],
t,
signal,
onProgress
)
}}
/>
)
}
...@@ -61,6 +61,7 @@ import { ...@@ -61,6 +61,7 @@ import {
TooltipTrigger, TooltipTrigger,
} from '@/components/ui/tooltip' } from '@/components/ui/tooltip'
import { getFlowQuotaDates } from '@/features/dashboard/api' import { getFlowQuotaDates } from '@/features/dashboard/api'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import { import {
buildDashboardFlowData, buildDashboardFlowData,
buildFlowSankeySpec, buildFlowSankeySpec,
...@@ -71,6 +72,12 @@ import { ...@@ -71,6 +72,12 @@ import {
getFlowStages, getFlowStages,
} from '@/features/dashboard/lib' } from '@/features/dashboard/lib'
import { import {
metricSheet,
quotaValue,
quotaHeader,
flowSheets,
} from '@/features/dashboard/lib/export'
import {
compactFlowSelectionLabel, compactFlowSelectionLabel,
flowDisplayState, flowDisplayState,
requireSuccessfulFlowRows, requireSuccessfulFlowRows,
...@@ -92,6 +99,7 @@ import { cn } from '@/lib/utils' ...@@ -92,6 +99,7 @@ import { cn } from '@/lib/utils'
import { VCHART_OPTION } from '@/lib/vchart' import { VCHART_OPTION } from '@/lib/vchart'
import { useAuthStore } from '@/stores/auth-store' import { useAuthStore } from '@/stores/auth-store'
import { DashboardExportButton } from '../dashboard-export'
import { FlowNodeFilterControl } from './flow-node-filter' import { FlowNodeFilterControl } from './flow-node-filter'
interface FlowChartsProps { interface FlowChartsProps {
...@@ -451,6 +459,95 @@ export function FlowCharts(props: FlowChartsProps) { ...@@ -451,6 +459,95 @@ export function FlowCharts(props: FlowChartsProps) {
chartInstanceRef.current?.clearState('selected') chartInstanceRef.current?.clearState('selected')
chartInstanceRef.current?.clearState('blur') chartInstanceRef.current?.clearState('blur')
}, []) }, [])
const exportFlow = useMemo(
() =>
buildDashboardFlowData(flowRows ?? [], metric, {
role: flowRole,
selectedUsers,
selectedNodes,
visibleStages,
maskSensitive,
deletedTokenLabel: (id) => t('Deleted ({{id}})', { id }),
}),
[
flowRows,
metric,
flowRole,
selectedUsers,
selectedNodes,
visibleStages,
maskSensitive,
t,
]
)
useDashboardExportSection('flow', {
loading: isLoading,
error: isError,
sheets: [
metricSheet(
t('Flow filters'),
[
[t('Start time'), new Date(timeRange.start_timestamp * 1000)],
[t('End time'), new Date(timeRange.end_timestamp * 1000)],
[t('Flow width metric'), metricLabel],
[t('Display limit'), topNodeLimit],
[
t('Overflow items'),
overflowMode === 'aggregate' ? t('Merge into Other') : t('Hide'),
],
[t('Hide sensitive data'), maskSensitive],
[
t('Visible stages'),
visibleStages
.map((stage) => t(FLOW_STAGE_LABEL_KEYS[stage]))
.join(', '),
],
[
t('Username'),
maskSensitive ? '••••' : props.filters?.username || t('All users'),
],
[
t('User filters'),
maskSensitive
? '••••'
: selectedUsers
.map(
(id) =>
flowData.filterOptions.users.find(
(option) => option.value === id
)?.label ?? id
)
.join(', '),
],
[
t('Node filters'),
maskSensitive
? '••••'
: selectedNodes
.map((node) => {
const label =
flowData.filterOptions.nodes.find(
(option) =>
option.kind === node.kind && option.value === node.id
)?.label ?? node.id
return `${t(FLOW_STAGE_LABEL_KEYS[node.kind])}: ${label}`
})
.join(', '),
],
[t('Requests'), flowData.summary.requests],
[t('Tokens'), flowData.summary.tokens],
[t('Quota (raw)'), flowData.summary.quota],
[quotaHeader(t), quotaValue(flowData.summary.quota)],
],
t
),
...flowSheets(flowData.flow, t),
...flowSheets(exportFlow.flow, t).map((sheet) => ({
...sheet,
name: `${t('All')} ${sheet.name}`,
})),
],
})
const chartTitle = t('Flow') const chartTitle = t('Flow')
const flowSpec = useMemo( const flowSpec = useMemo(
() => () =>
...@@ -642,7 +739,8 @@ export function FlowCharts(props: FlowChartsProps) { ...@@ -642,7 +739,8 @@ export function FlowCharts(props: FlowChartsProps) {
/> />
</div> </div>
<div className='flex min-w-0 items-center gap-2 xl:justify-end'> <div className='flex min-w-0 flex-wrap items-center gap-2 xl:justify-end'>
<DashboardExportButton scope='flow' required={['flow']} />
{isAdmin && ( {isAdmin && (
<div className='flex min-w-0 flex-col gap-2 sm:flex-row xl:w-[min(24rem,34vw)]'> <div className='flex min-w-0 flex-col gap-2 sm:flex-row xl:w-[min(24rem,34vw)]'>
<MultiSelect <MultiSelect
......
...@@ -28,7 +28,9 @@ import { ...@@ -28,7 +28,9 @@ import {
CONSUMPTION_DISTRIBUTION_CHART_OPTIONS, CONSUMPTION_DISTRIBUTION_CHART_OPTIONS,
DEFAULT_TIME_GRANULARITY, DEFAULT_TIME_GRANULARITY,
} from '@/features/dashboard/constants' } from '@/features/dashboard/constants'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import { processChartData } from '@/features/dashboard/lib' import { processChartData } from '@/features/dashboard/lib'
import { chartSheet, metricSheet } from '@/features/dashboard/lib/export'
import type { import type {
ConsumptionDistributionChartType, ConsumptionDistributionChartType,
QuotaDataItem, QuotaDataItem,
...@@ -108,6 +110,33 @@ export function ConsumptionDistributionChart( ...@@ -108,6 +110,33 @@ export function ConsumptionDistributionChart(
), ),
[props.data, props.loading, timeGranularity, t, chartRadius] [props.data, props.loading, timeGranularity, t, chartRadius]
) )
useDashboardExportSection('consumption-chart', {
loading: props.loading,
sheets: [
metricSheet(
t('Consumption chart settings'),
[
[t('Chart'), t(chartType)],
[t('Time granularity'), timeGranularity],
],
t
),
chartSheet(t('Consumption distribution'), chartData.spec_line, [
['Time', t('Time')],
['Model', t('Model')],
['rawQuota', t('Quota (raw)')],
['Usage', t('Chart value (USD)')],
['TimeSum', t('Period quota (raw)')],
]),
chartSheet(t('Consumption area chart'), chartData.spec_area, [
['Time', t('Time')],
['Model', t('Model')],
['rawQuota', t('Quota (raw)')],
['Usage', t('Chart value (USD)')],
['TimeSum', t('Period quota (raw)')],
]),
],
})
const spec = chartType === 'bar' ? chartData.spec_line : chartData.spec_area const spec = chartType === 'bar' ? chartData.spec_line : chartData.spec_area
const specType = typeof spec?.type === 'string' ? spec.type : chartType const specType = typeof spec?.type === 'string' ? spec.type : chartType
const chartKey = [ const chartKey = [
......
...@@ -23,11 +23,18 @@ import { IconBadge } from '@/components/ui/icon-badge' ...@@ -23,11 +23,18 @@ import { IconBadge } from '@/components/ui/icon-badge'
import { Skeleton } from '@/components/ui/skeleton' import { Skeleton } from '@/components/ui/skeleton'
import { getUserQuotaDates } from '@/features/dashboard/api' import { getUserQuotaDates } from '@/features/dashboard/api'
import { useModelStatCardsConfig } from '@/features/dashboard/hooks/use-dashboard-config' import { useModelStatCardsConfig } from '@/features/dashboard/hooks/use-dashboard-config'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import { import {
buildQueryParams, buildQueryParams,
calculateDashboardStats, calculateDashboardStats,
getDefaultDays, getDefaultDays,
} from '@/features/dashboard/lib' } from '@/features/dashboard/lib'
import {
metricSheet,
usageSheets,
quotaValue,
quotaHeader,
} from '@/features/dashboard/lib/export'
import type { import type {
QuotaDataItem, QuotaDataItem,
DashboardFilters, DashboardFilters,
...@@ -59,7 +66,7 @@ function formatStatNumber(value: number, locale: Intl.LocalesArgument) { ...@@ -59,7 +66,7 @@ function formatStatNumber(value: number, locale: Intl.LocalesArgument) {
} }
export function LogStatCards(props: LogStatCardsProps) { export function LogStatCards(props: LogStatCardsProps) {
const { i18n } = useTranslation() const { t, i18n } = useTranslation()
const statCardsConfig = useModelStatCardsConfig() const statCardsConfig = useModelStatCardsConfig()
const user = useAuthStore((state) => state.auth.user) const user = useAuthStore((state) => state.auth.user)
const isAdmin = !!(user?.role && user.role >= 10) const isAdmin = !!(user?.role && user.role >= 10)
...@@ -72,6 +79,11 @@ export function LogStatCards(props: LogStatCardsProps) { ...@@ -72,6 +79,11 @@ export function LogStatCards(props: LogStatCardsProps) {
const [error, setError] = useState(false) const [error, setError] = useState(false)
const [timeRangeMinutes, setTimeRangeMinutes] = useState(0) const [timeRangeMinutes, setTimeRangeMinutes] = useState(0)
const [exportData, setExportData] = useState<QuotaDataItem[]>([])
const [exportRange, setExportRange] = useState({
start_timestamp: 0,
end_timestamp: 0,
})
const { filters, onDataUpdate } = props const { filters, onDataUpdate } = props
...@@ -90,11 +102,14 @@ export function LogStatCards(props: LogStatCardsProps) { ...@@ -90,11 +102,14 @@ export function LogStatCards(props: LogStatCardsProps) {
) )
const timeDiff = (timeRange.end_timestamp - timeRange.start_timestamp) / 60 const timeDiff = (timeRange.end_timestamp - timeRange.start_timestamp) / 60
setTimeRangeMinutes(timeDiff) setTimeRangeMinutes(timeDiff)
setExportRange(timeRange)
void getUserQuotaDates(buildQueryParams(timeRange, filters), isAdmin) void getUserQuotaDates(buildQueryParams(timeRange, filters), isAdmin)
.then((res) => { .then((res) => {
if (abortController.signal.aborted) return if (abortController.signal.aborted) return
if (!res.success) throw new Error(t('Failed to load'))
const data = res?.data || [] const data = res?.data || []
setExportData(data)
setStats(calculateDashboardStats(data)) setStats(calculateDashboardStats(data))
onDataUpdate?.(data, false) onDataUpdate?.(data, false)
}) })
...@@ -113,7 +128,7 @@ export function LogStatCards(props: LogStatCardsProps) { ...@@ -113,7 +128,7 @@ export function LogStatCards(props: LogStatCardsProps) {
return () => { return () => {
abortController.abort() abortController.abort()
} }
}, [filters, isAdmin, onDataUpdate]) }, [filters, isAdmin, onDataUpdate, t])
const adaptedStats = { const adaptedStats = {
rpm: stats?.totalCount ?? 0, rpm: stats?.totalCount ?? 0,
...@@ -142,6 +157,34 @@ export function LogStatCards(props: LogStatCardsProps) { ...@@ -142,6 +157,34 @@ export function LogStatCards(props: LogStatCardsProps) {
} }
}) })
useDashboardExportSection('models', {
loading,
error,
sheets: [
metricSheet(
t('Model Call Analytics'),
[
[t('Start time'), new Date(exportRange.start_timestamp * 1000)],
[t('End time'), new Date(exportRange.end_timestamp * 1000)],
[t('Time granularity'), filters?.time_granularity ?? 'hour'],
[t('Username'), filters?.username || t('All users')],
...statCardsConfig.map((config) => [
config.key === 'quota' ? t('Quota (raw)') : config.title,
config.getValue(adaptedStats, timeRangeMinutes),
]),
[quotaHeader(t), quotaValue(stats?.totalQuota ?? 0)],
],
t
),
...usageSheets(
exportData,
filters?.time_granularity ?? 'hour',
'model_name',
t
),
],
})
return ( return (
<div className='overflow-hidden rounded-lg border'> <div className='overflow-hidden rounded-lg border'>
<div className='divide-border/60 grid min-w-0 grid-cols-2 divide-x sm:grid-cols-3 lg:grid-cols-5'> <div className='divide-border/60 grid min-w-0 grid-cols-2 divide-x sm:grid-cols-3 lg:grid-cols-5'>
......
...@@ -28,7 +28,9 @@ import { ...@@ -28,7 +28,9 @@ import {
DEFAULT_TIME_GRANULARITY, DEFAULT_TIME_GRANULARITY,
MODEL_ANALYTICS_CHART_OPTIONS, MODEL_ANALYTICS_CHART_OPTIONS,
} from '@/features/dashboard/constants' } from '@/features/dashboard/constants'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import { processChartData } from '@/features/dashboard/lib' import { processChartData } from '@/features/dashboard/lib'
import { chartSheet, metricSheet } from '@/features/dashboard/lib/export'
import type { import type {
ModelAnalyticsChartTab, ModelAnalyticsChartTab,
QuotaDataItem, QuotaDataItem,
...@@ -107,6 +109,32 @@ export function ModelCharts(props: ModelChartsProps) { ...@@ -107,6 +109,32 @@ export function ModelCharts(props: ModelChartsProps) {
[props.data, props.loading, timeGranularity, t, chartRadius] [props.data, props.loading, timeGranularity, t, chartRadius]
) )
useDashboardExportSection('model-charts', {
loading: props.loading,
sheets: [
metricSheet(
t('Model chart settings'),
[
[t('Chart'), t(activeTab)],
[t('Time granularity'), timeGranularity],
],
t
),
chartSheet(t('Call Trend'), chartData.spec_model_line, [
['Time', t('Time')],
['Model', t('Model')],
['Count', t('Requests')],
]),
chartSheet(t('Call Count Distribution'), chartData.spec_pie, [
['type', t('Model')],
['value', t('Requests')],
]),
chartSheet(t('Call Count Ranking'), chartData.spec_rank_bar, [
['Model', t('Model')],
['Count', t('Requests')],
]),
],
})
const spec = chartData[CHART_SPEC_KEYS[activeTab]] const spec = chartData[CHART_SPEC_KEYS[activeTab]]
const specType = typeof spec?.type === 'string' ? spec.type : activeTab const specType = typeof spec?.type === 'string' ? spec.type : activeTab
const chartKey = [ const chartKey = [
......
...@@ -23,6 +23,8 @@ import { useTranslation } from 'react-i18next' ...@@ -23,6 +23,8 @@ import { useTranslation } from 'react-i18next'
import { IconBadge, type IconBadgeTone } from '@/components/ui/icon-badge' import { IconBadge, type IconBadgeTone } from '@/components/ui/icon-badge'
import { Skeleton } from '@/components/ui/skeleton' import { Skeleton } from '@/components/ui/skeleton'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import { performanceSheets } from '@/features/dashboard/lib/export'
import { getPerfMetricsSummary } from '@/features/performance-metrics/api' import { getPerfMetricsSummary } from '@/features/performance-metrics/api'
import { import {
formatLatency, formatLatency,
...@@ -98,6 +100,11 @@ export function PerformanceOverview() { ...@@ -98,6 +100,11 @@ export function PerformanceOverview() {
) )
const summary = useMemo(() => buildPerformanceSummary(models), [models]) const summary = useMemo(() => buildPerformanceSummary(models), [models])
const topModels = useMemo(() => models.slice(0, TOP_MODEL_LIMIT), [models]) const topModels = useMemo(() => models.slice(0, TOP_MODEL_LIMIT), [models])
useDashboardExportSection('performance', {
loading: metricsQuery.isLoading,
error: metricsQuery.isError || metricsQuery.data?.success === false,
sheets: performanceSheets(models, summary, t),
})
const loading = metricsQuery.isLoading const loading = metricsQuery.isLoading
const hasData = models.length > 0 const hasData = models.length > 0
......
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import fs from 'node:fs'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import {
createMemoryHistory,
createRootRoute,
createRouter,
RouterProvider,
} from '@tanstack/react-router'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import * as XLSX from 'xlsx'
import { api } from '@/lib/api'
import { useAuthStore } from '@/stores/auth-store'
import { useSystemConfigStore } from '@/stores/system-config-store'
import { DashboardExportProvider } from '../../dashboard-export'
import { OverviewDashboard } from '../overview-dashboard'
// jsdom has no Web Animations API; ScrollArea inspects it after layout.
const originalGetAnimations = Object.getOwnPropertyDescriptor(
Element.prototype,
'getAnimations'
)
beforeEach(() => {
Object.defineProperty(Element.prototype, 'getAnimations', {
configurable: true,
value: () => [],
})
})
let client: QueryClient
function Page() {
return (
<DashboardExportProvider>
<OverviewDashboard />
</DashboardExportProvider>
)
}
afterEach(() => {
cleanup()
client?.clear()
if (originalGetAnimations) {
Object.defineProperty(
Element.prototype,
'getAnimations',
originalGetAnimations
)
} else {
Reflect.deleteProperty(Element.prototype, 'getAnimations')
}
useAuthStore.setState(useAuthStore.getInitialState(), true)
useSystemConfigStore.setState(useSystemConfigStore.getInitialState(), true)
window.localStorage.clear()
})
it('exports every enabled overview panel, account totals and performance without plaintext keys', async () => {
useAuthStore.getState().auth.setUser({
id: 1,
username: 'alice',
role: 10,
quota: 1000000,
used_quota: 500000,
request_count: 20,
})
const download = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
vi.spyOn(api, 'get').mockImplementation(async (url) => {
switch (url) {
case '/api/status':
return {
data: {
data: {
api_info_enabled: true,
api_info: [
{
url: 'https://api.example.test',
route: 'Main',
description: 'Production',
},
],
announcements_enabled: true,
announcements: [
{
content: 'Notice',
publishDate: '2026-10-27',
type: 'success',
extra: 'Full notice',
},
],
faq_enabled: true,
faq: [{ question: 'How?', answer: 'Like this.' }],
uptime_kuma_enabled: true,
},
},
}
case '/api/token/?p=1&size=10':
return {
data: {
success: true,
data: {
items: [
{
id: 1,
name: 'App key',
key: 'do-not-export-secret',
status: 1,
},
],
},
},
}
case '/api/user/models':
return { data: { success: true, data: ['model-a'] } }
case '/api/data/self':
return {
data: {
success: true,
data: [
{
created_at: 1700000000,
model_name: 'model-a',
count: 3,
token_used: 12,
quota: 250000,
},
],
},
}
case '/api/perf-metrics/summary':
return {
data: {
success: true,
data: {
models: [
{
model_name: 'model-a',
avg_latency_ms: 123,
avg_tps: 10,
success_rate: 99.5,
},
],
},
},
}
case '/api/uptime/status':
return {
data: {
success: true,
data: [
{
categoryName: 'Production',
monitors: [
{ name: 'API', status: 1, uptime: 0.999, group: 'Main' },
],
},
],
},
}
default:
throw new Error(`Unexpected request: ${url}`)
}
})
client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const router = createRouter({
routeTree: createRootRoute({ component: Page }),
history: createMemoryHistory({ initialEntries: ['/'] }),
})
await router.load()
render(
<QueryClientProvider client={client}>
<RouterProvider router={router} />
</QueryClientProvider>
)
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Export Excel' })).toBeEnabled()
)
await userEvent.click(screen.getByRole('button', { name: 'Export Excel' }))
await waitFor(() => expect(download).toHaveBeenCalledTimes(1))
const wb = XLSX.read(download.mock.calls[0][1], { type: 'buffer' })
expect(wb.SheetNames).toEqual(
expect.arrayContaining([
'Setup guide',
'Usage at a glance',
'Model performance',
'API Info',
'Announcements',
'FAQ',
'Uptime',
'Summary chart',
])
)
expect(wb.Sheets['Model performance'].D2.v).toBe(0.995)
expect(wb.Sheets.Uptime.E2.v).toBe(0.999)
expect(wb.Sheets.Announcements.D2.v).toBe('Full notice')
expect(wb.Sheets.FAQ.B2.v).toBe('Like this.')
const allValues = JSON.stringify(
wb.SheetNames.map((name) =>
XLSX.utils.sheet_to_json(wb.Sheets[name], { header: 1 })
)
)
expect(allValues).not.toContain('do-not-export-secret')
expect(allValues).toContain('App key')
expect(allValues).toContain('sk-••••')
})
...@@ -22,6 +22,7 @@ import { useTranslation } from 'react-i18next' ...@@ -22,6 +22,7 @@ import { useTranslation } from 'react-i18next'
import { IconBadge } from '@/components/ui/icon-badge' import { IconBadge } from '@/components/ui/icon-badge'
import { ScrollArea } from '@/components/ui/scroll-area' import { ScrollArea } from '@/components/ui/scroll-area'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import { useAnnouncements } from '@/features/dashboard/hooks/use-status-data' import { useAnnouncements } from '@/features/dashboard/hooks/use-status-data'
import { getPreviewText } from '@/features/dashboard/lib' import { getPreviewText } from '@/features/dashboard/lib'
import type { AnnouncementItem } from '@/features/dashboard/types' import type { AnnouncementItem } from '@/features/dashboard/types'
...@@ -52,6 +53,21 @@ export function AnnouncementsPanel() { ...@@ -52,6 +53,21 @@ export function AnnouncementsPanel() {
useState<AnnouncementItem | null>(null) useState<AnnouncementItem | null>(null)
const [isDialogOpen, setIsDialogOpen] = useState(false) const [isDialogOpen, setIsDialogOpen] = useState(false)
useDashboardExportSection('announcements', {
loading,
sheets: [
{
name: t('Announcements'),
headers: [t('Publish date'), t('Type'), t('Content'), t('Details')],
rows: list.map((item) => [
item.publishDate,
item.type,
item.content,
item.extra,
]),
},
],
})
const handleAnnouncementClick = (item: AnnouncementItem) => { const handleAnnouncementClick = (item: AnnouncementItem) => {
setSelectedAnnouncement(item) setSelectedAnnouncement(item)
setIsDialogOpen(true) setIsDialogOpen(true)
......
...@@ -22,6 +22,7 @@ import { useTranslation } from 'react-i18next' ...@@ -22,6 +22,7 @@ import { useTranslation } from 'react-i18next'
import { IconBadge } from '@/components/ui/icon-badge' import { IconBadge } from '@/components/ui/icon-badge'
import { ScrollArea } from '@/components/ui/scroll-area' import { ScrollArea } from '@/components/ui/scroll-area'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import { useApiInfo } from '@/features/dashboard/hooks/use-status-data' import { useApiInfo } from '@/features/dashboard/hooks/use-status-data'
import { import {
testUrlLatency, testUrlLatency,
...@@ -37,6 +38,29 @@ export function ApiInfoPanel() { ...@@ -37,6 +38,29 @@ export function ApiInfoPanel() {
const { items: list, loading } = useApiInfo() const { items: list, loading } = useApiInfo()
const [pingStatus, setPingStatus] = useState<PingStatusMap>({}) const [pingStatus, setPingStatus] = useState<PingStatusMap>({})
useDashboardExportSection('api-info', {
loading,
sheets: [
{
name: t('API Info'),
headers: [
t('Route'),
t('URL'),
t('Description'),
t('Latency (ms)'),
t('Status'),
],
rows: list.map((item) => {
const ping = pingStatus[item.url]
let state = t('Not tested')
if (ping?.error) state = t('Failed')
else if (ping?.testing) state = t('Loading')
else if (ping?.latency != null) state = t('Success')
return [item.route, item.url, item.description, ping?.latency, state]
}),
},
],
})
const handleTest = useCallback(async (url: string) => { const handleTest = useCallback(async (url: string) => {
setPingStatus((prev) => ({ setPingStatus((prev) => ({
...prev, ...prev,
......
...@@ -28,6 +28,7 @@ import { ...@@ -28,6 +28,7 @@ import {
import { IconBadge } from '@/components/ui/icon-badge' import { IconBadge } from '@/components/ui/icon-badge'
import { Markdown } from '@/components/ui/markdown' import { Markdown } from '@/components/ui/markdown'
import { ScrollArea } from '@/components/ui/scroll-area' import { ScrollArea } from '@/components/ui/scroll-area'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import { useFAQ } from '@/features/dashboard/hooks/use-status-data' import { useFAQ } from '@/features/dashboard/hooks/use-status-data'
import type { FAQItem } from '@/features/dashboard/types' import type { FAQItem } from '@/features/dashboard/types'
...@@ -37,6 +38,16 @@ export function FAQPanel() { ...@@ -37,6 +38,16 @@ export function FAQPanel() {
const { t } = useTranslation() const { t } = useTranslation()
const { items: list, loading } = useFAQ() const { items: list, loading } = useFAQ()
useDashboardExportSection('faq', {
loading,
sheets: [
{
name: t('FAQ'),
headers: [t('Question'), t('Answer')],
rows: list.map((item) => [item.question, item.answer]),
},
],
})
return ( return (
<PanelWrapper <PanelWrapper
title={ title={
......
...@@ -48,6 +48,8 @@ import { ...@@ -48,6 +48,8 @@ import {
} from '@/components/page-transition' } from '@/components/page-transition'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { IconBadge, type IconBadgeTone } from '@/components/ui/icon-badge' import { IconBadge, type IconBadgeTone } from '@/components/ui/icon-badge'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import { metricSheet } from '@/features/dashboard/lib/export'
import { fetchTokenKey, getApiKeys } from '@/features/keys/api' import { fetchTokenKey, getApiKeys } from '@/features/keys/api'
import type { ApiKey } from '@/features/keys/types' import type { ApiKey } from '@/features/keys/types'
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard' import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard'
...@@ -61,6 +63,7 @@ import { ...@@ -61,6 +63,7 @@ import {
useApiInfo, useApiInfo,
useDashboardContentVisibility, useDashboardContentVisibility,
} from '../../hooks/use-status-data' } from '../../hooks/use-status-data'
import { DashboardExportButton } from '../dashboard-export'
import { AnnouncementsPanel } from './announcements-panel' import { AnnouncementsPanel } from './announcements-panel'
import { ApiInfoPanel } from './api-info-panel' import { ApiInfoPanel } from './api-info-panel'
import { FAQPanel } from './faq-panel' import { FAQPanel } from './faq-panel'
...@@ -614,6 +617,32 @@ export function OverviewDashboard() { ...@@ -614,6 +617,32 @@ export function OverviewDashboard() {
isAdmin || showApiInfoPanel || showAnnouncementsPanel || showFAQPanel isAdmin || showApiInfoPanel || showAnnouncementsPanel || showFAQPanel
const showContentPanels = showLeftContentPanels || showUptimePanel const showContentPanels = showLeftContentPanels || showUptimePanel
useDashboardExportSection('overview', {
loading: apiKeysQuery.isLoading || modelsQuery.isLoading,
error: apiKeysQuery.isError || modelsQuery.isError,
sheets: [
metricSheet(
t('Setup guide'),
[
[t('Username'), user?.username],
[t('API endpoint'), requestExample.endpoint],
[t('Model'), requestExample.model],
[t('API Key name'), requestExample.keyName],
[t('API Key'), preferredKey ? 'sk-••••' : t('No API key yet')],
...heroSignals.map((signal) => [signal.label, signal.value]),
...startSteps.map((step) => [step.title, step.completed]),
],
t
),
],
})
const exportSections = ['overview', 'summary']
if (isAdmin) exportSections.push('performance')
if (showApiInfoPanel) exportSections.push('api-info')
if (showAnnouncementsPanel) exportSections.push('announcements')
if (showFAQPanel) exportSections.push('faq')
if (showUptimePanel) exportSections.push('uptime')
const handleSetupGuideToggle = () => { const handleSetupGuideToggle = () => {
const nextExpanded = !setupGuideExpanded const nextExpanded = !setupGuideExpanded
setManualSetupGuideExpanded(nextExpanded) setManualSetupGuideExpanded(nextExpanded)
...@@ -627,6 +656,7 @@ export function OverviewDashboard() { ...@@ -627,6 +656,7 @@ export function OverviewDashboard() {
<SectionPageLayout> <SectionPageLayout>
<SectionPageLayout.Title>{t('Overview')}</SectionPageLayout.Title> <SectionPageLayout.Title>{t('Overview')}</SectionPageLayout.Title>
<SectionPageLayout.Actions> <SectionPageLayout.Actions>
<DashboardExportButton scope='overview' required={exportSections} />
{setupStatusReady && setupComplete && ( {setupStatusReady && setupComplete && (
<Button <Button
ref={setupGuideToggleRef} ref={setupGuideToggleRef}
......
...@@ -23,6 +23,8 @@ import { useTranslation } from 'react-i18next' ...@@ -23,6 +23,8 @@ import { useTranslation } from 'react-i18next'
import { IconBadge, type IconBadgeTone } from '@/components/ui/icon-badge' import { IconBadge, type IconBadgeTone } from '@/components/ui/icon-badge'
import { Skeleton } from '@/components/ui/skeleton' import { Skeleton } from '@/components/ui/skeleton'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import { performanceSheets } from '@/features/dashboard/lib/export'
import { getPerfMetricsSummary } from '@/features/performance-metrics/api' import { getPerfMetricsSummary } from '@/features/performance-metrics/api'
import { import {
formatLatency, formatLatency,
...@@ -88,6 +90,11 @@ export function PerformanceHealthPanel() { ...@@ -88,6 +90,11 @@ export function PerformanceHealthPanel() {
}, [models]) }, [models])
const topModels = useMemo(() => models.slice(0, TOP_MODEL_LIMIT), [models]) const topModels = useMemo(() => models.slice(0, TOP_MODEL_LIMIT), [models])
useDashboardExportSection('performance', {
loading: metricsQuery.isLoading,
error: metricsQuery.isError || metricsQuery.data?.success === false,
sheets: performanceSheets(models, summary, t),
})
const loading = metricsQuery.isLoading const loading = metricsQuery.isLoading
const hasData = models.length > 0 const hasData = models.length > 0
......
...@@ -26,6 +26,13 @@ import { StaggerContainer, StaggerItem } from '@/components/page-transition' ...@@ -26,6 +26,13 @@ import { StaggerContainer, StaggerItem } from '@/components/page-transition'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { getUserQuotaDates } from '@/features/dashboard/api' import { getUserQuotaDates } from '@/features/dashboard/api'
import { useSummaryCardsConfig } from '@/features/dashboard/hooks/use-dashboard-config' import { useSummaryCardsConfig } from '@/features/dashboard/hooks/use-dashboard-config'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import {
metricSheet,
usageSheets,
quotaValue,
quotaHeader,
} from '@/features/dashboard/lib/export'
import type { QuotaDataItem } from '@/features/dashboard/types' import type { QuotaDataItem } from '@/features/dashboard/types'
import { useStatus } from '@/hooks/use-status' import { useStatus } from '@/hooks/use-status'
import { getCurrencyLabel, isCurrencyDisplayEnabled } from '@/lib/currency' import { getCurrencyLabel, isCurrencyDisplayEnabled } from '@/lib/currency'
...@@ -249,6 +256,57 @@ export function SummaryCards() { ...@@ -249,6 +256,57 @@ export function SummaryCards() {
} }
}) })
useDashboardExportSection('summary', {
loading: loading || usageTrendQuery.isLoading,
error: usageTrendQuery.isError || usageTrendQuery.data?.success === false,
sheets: [
metricSheet(
t('Usage at a glance'),
[
[t('Start time'), new Date(summaryTimeRange.start_timestamp * 1000)],
[t('End time'), new Date(summaryTimeRange.end_timestamp * 1000)],
[t('Credit remaining'), quotaValue(remainQuota)],
[t('Remaining Quota (raw)'), remainQuota],
[t('Total Used'), quotaValue(usedQuota)],
[t('Used Quota (raw)'), usedQuota],
[t('Requests'), requestCount],
[t('Last 24h usage'), quotaValue(recentUsage)],
[t('Quota (raw)'), recentUsage],
[t('Currency'), currencyLabel],
[t('Status'), t(healthCfg.labelKey)],
[t('Runway'), runwayDisplay],
[t('Runway (days)'), runwayDays],
],
t
),
...usageSheets(usageTrendQuery.data?.data ?? [], 'hour', 'model_name', t),
{
name: t('Summary chart'),
headers: [
t('Start time'),
t('End time'),
t('Quota (raw)'),
quotaHeader(t),
t('Requests'),
],
rows: sparklineData.usage.map((value, i) => {
const interval =
(summaryTimeRange.end_timestamp -
summaryTimeRange.start_timestamp) /
SUMMARY_SPARKLINE_BUCKETS
return [
new Date((summaryTimeRange.start_timestamp + i * interval) * 1000),
new Date(
(summaryTimeRange.start_timestamp + (i + 1) * interval) * 1000
),
value,
quotaValue(value),
sparklineData.requests[i],
]
}),
},
],
})
return ( return (
<div className='bg-card overflow-hidden rounded-2xl border shadow-xs'> <div className='bg-card overflow-hidden rounded-2xl border shadow-xs'>
<div className='grid xl:grid-cols-[minmax(0,1fr)_19rem]'> <div className='grid xl:grid-cols-[minmax(0,1fr)_19rem]'>
......
...@@ -24,6 +24,7 @@ import { Button } from '@/components/ui/button' ...@@ -24,6 +24,7 @@ import { Button } from '@/components/ui/button'
import { IconBadge } from '@/components/ui/icon-badge' import { IconBadge } from '@/components/ui/icon-badge'
import { ScrollArea } from '@/components/ui/scroll-area' import { ScrollArea } from '@/components/ui/scroll-area'
import { getUptimeStatus } from '@/features/dashboard/api' import { getUptimeStatus } from '@/features/dashboard/api'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import type { import type {
UptimeGroupResult, UptimeGroupResult,
UptimeMonitor, UptimeMonitor,
...@@ -50,6 +51,33 @@ export function UptimePanel() { ...@@ -50,6 +51,33 @@ export function UptimePanel() {
const [groups, setGroups] = useState<UptimeGroupResult[]>([]) const [groups, setGroups] = useState<UptimeGroupResult[]>([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [refreshing, setRefreshing] = useState(false) const [refreshing, setRefreshing] = useState(false)
const [error, setError] = useState(false)
useDashboardExportSection('uptime', {
loading: loading || refreshing,
error,
sheets: [
{
name: t('Uptime'),
headers: [
t('Category'),
t('Name'),
t('Group'),
t('Status'),
t('Uptime'),
],
formats: { 4: '0.00%' },
rows: groups.flatMap((group) =>
group.monitors.map((monitor) => [
group.categoryName,
monitor.name,
monitor.group,
monitor.status,
monitor.uptime,
])
),
},
],
})
useEffect(() => { useEffect(() => {
const abortController = new AbortController() const abortController = new AbortController()
...@@ -57,10 +85,12 @@ export function UptimePanel() { ...@@ -57,10 +85,12 @@ export function UptimePanel() {
void getUptimeStatus() void getUptimeStatus()
.then((res) => { .then((res) => {
if (abortController.signal.aborted) return if (abortController.signal.aborted) return
setError(!res.success)
setGroups(res?.data || []) setGroups(res?.data || [])
}) })
.catch(() => { .catch(() => {
if (abortController.signal.aborted) return if (abortController.signal.aborted) return
setError(true)
setGroups([]) setGroups([])
}) })
.finally(() => { .finally(() => {
...@@ -81,10 +111,12 @@ export function UptimePanel() { ...@@ -81,10 +111,12 @@ export function UptimePanel() {
void getUptimeStatus() void getUptimeStatus()
.then((res) => { .then((res) => {
if (abortController.signal.aborted) return if (abortController.signal.aborted) return
setError(!res.success)
setGroups(res?.data || []) setGroups(res?.data || [])
}) })
.catch(() => { .catch(() => {
if (abortController.signal.aborted) return if (abortController.signal.aborted) return
setError(true)
setGroups([]) setGroups([])
}) })
.finally(() => { .finally(() => {
......
...@@ -31,11 +31,17 @@ import { ...@@ -31,11 +31,17 @@ import {
TIME_GRANULARITY_OPTIONS, TIME_GRANULARITY_OPTIONS,
TIME_RANGE_PRESETS, TIME_RANGE_PRESETS,
} from '@/features/dashboard/constants' } from '@/features/dashboard/constants'
import { useDashboardExportSection } from '@/features/dashboard/hooks/use-dashboard-export'
import { import {
getDefaultDays, getDefaultDays,
saveGranularity, saveGranularity,
processUserChartData, processUserChartData,
} from '@/features/dashboard/lib' } from '@/features/dashboard/lib'
import {
chartSheet,
metricSheet,
usageSheets,
} from '@/features/dashboard/lib/export'
import type { import type {
ProcessedUserChartData, ProcessedUserChartData,
UserChartsFilters, UserChartsFilters,
...@@ -136,10 +142,17 @@ export function UserCharts(props: UserChartsProps) { ...@@ -136,10 +142,17 @@ export function UserCharts(props: UserChartsProps) {
updateTheme() updateTheme()
}, [resolvedTheme]) }, [resolvedTheme])
const { data: userData, isLoading } = useQuery({ const {
data: userData,
isLoading,
isError,
} = useQuery({
queryKey: ['dashboard', 'user-quota', timeRange], queryKey: ['dashboard', 'user-quota', timeRange],
queryFn: () => getUserQuotaDataByUsers(timeRange), queryFn: () => getUserQuotaDataByUsers(timeRange),
select: (res) => (res.success ? res.data : []), select: (res) => {
if (!res.success) throw new Error(t('Failed to load'))
return res.data
},
staleTime: 60_000, staleTime: 60_000,
}) })
...@@ -154,6 +167,35 @@ export function UserCharts(props: UserChartsProps) { ...@@ -154,6 +167,35 @@ export function UserCharts(props: UserChartsProps) {
[userData, isLoading, timeGranularity, t, topUserLimit] [userData, isLoading, timeGranularity, t, topUserLimit]
) )
useDashboardExportSection('users', {
loading: isLoading,
error: isError,
sheets: [
metricSheet(
t('User Analytics'),
[
[t('Start time'), new Date(timeRange.start_timestamp * 1000)],
[t('End time'), new Date(timeRange.end_timestamp * 1000)],
[t('Time granularity'), timeGranularity],
[t('Display limit'), topUserLimit],
],
t
),
...usageSheets(userData ?? [], timeGranularity, 'username', t),
chartSheet(t('User Consumption Ranking'), chartData.spec_user_rank, [
['User', t('Username')],
['rawQuota', t('Quota (raw)')],
['Usage', t('Chart value (USD)')],
]),
chartSheet(t('User Consumption Trend'), chartData.spec_user_trend, [
['Time', t('Time')],
['User', t('Username')],
['rawQuota', t('Quota (raw)')],
['Usage', t('Chart value (USD)')],
]),
],
})
return ( return (
<div className='space-y-3'> <div className='space-y-3'>
<div className='flex items-center gap-1.5 overflow-x-auto pb-1 sm:gap-2'> <div className='flex items-center gap-1.5 overflow-x-auto pb-1 sm:gap-2'>
......
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { createContext, useContext, useEffect } from 'react'
import type { DashboardExportSheet } from '../lib/export'
export interface ExportSection {
sheets: DashboardExportSheet[]
loading?: boolean
error?: boolean
}
export const ExportRegisterContext = createContext<
((id: string, section?: ExportSection) => void) | null
>(null)
export const ExportSectionsContext = createContext<Record<
string,
ExportSection
> | null>(null)
export function useDashboardExportSection(
id: string,
section: ExportSection
): void {
const register = useContext(ExportRegisterContext)
// Capture the committed UI data, including local selections. The provider
// compares snapshots and only updates export consumers, not chart components.
useEffect(() => {
register?.(id, section)
})
useEffect(() => () => register?.(id), [id, register])
}
...@@ -35,6 +35,10 @@ import { ROLE } from '@/lib/roles' ...@@ -35,6 +35,10 @@ import { ROLE } from '@/lib/roles'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import { useAuthStore } from '@/stores/auth-store' import { useAuthStore } from '@/stores/auth-store'
import {
DashboardExportProvider,
DashboardExportButton,
} from './components/dashboard-export'
import { ModelsChartPreferences } from './components/models/models-chart-preferences' import { ModelsChartPreferences } from './components/models/models-chart-preferences'
import { ModelsFilter } from './components/models/models-filter-dialog' import { ModelsFilter } from './components/models/models-filter-dialog'
import { OverviewDashboard } from './components/overview/overview-dashboard' import { OverviewDashboard } from './components/overview/overview-dashboard'
...@@ -192,6 +196,18 @@ const SECTION_META: Record<DashboardSectionId, { titleKey: string }> = { ...@@ -192,6 +196,18 @@ const SECTION_META: Record<DashboardSectionId, { titleKey: string }> = {
} }
export function Dashboard() { export function Dashboard() {
const params = route.useParams()
const user = useAuthStore((state) => state.auth.user)
return (
<DashboardExportProvider
key={`${params.section}:${user?.id}:${user?.role}`}
>
<DashboardContent />
</DashboardExportProvider>
)
}
function DashboardContent() {
const { t } = useTranslation() const { t } = useTranslation()
const navigate = useNavigate() const navigate = useNavigate()
const params = route.useParams() const params = route.useParams()
...@@ -316,6 +332,12 @@ export function Dashboard() { ...@@ -316,6 +332,12 @@ export function Dashboard() {
</> </>
) : null ) : null
const sectionActions = modelActions ?? flowActions const sectionActions = modelActions ?? flowActions
let exportSections = ['models']
if (activeSection === 'users') exportSections = ['users']
else if (isAdmin) exportSections.push('performance')
if (activeSection === 'models') {
exportSections.push('model-charts', 'consumption-chart')
}
if (activeSection === 'overview') { if (activeSection === 'overview') {
return <OverviewDashboard /> return <OverviewDashboard />
...@@ -340,9 +362,15 @@ export function Dashboard() { ...@@ -340,9 +362,15 @@ export function Dashboard() {
) : ( ) : (
<div /> <div />
)} )}
{sectionActions != null && ( {(sectionActions != null || activeSection === 'users') && (
<div className='flex shrink-0 flex-wrap items-center gap-1.5 sm:gap-2'> <div className='flex shrink-0 flex-wrap items-center gap-1.5 sm:gap-2'>
{sectionActions} {sectionActions}
{activeSection !== 'flow' && (
<DashboardExportButton
scope={activeSection}
required={exportSections}
/>
)}
</div> </div>
)} )}
</div> </div>
......
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import i18next from 'i18next'
import { afterEach, describe, expect, it } from 'vitest'
import * as XLSX from 'xlsx'
import {
DEFAULT_CURRENCY_CONFIG,
useSystemConfigStore,
} from '@/stores/system-config-store'
import { processChartData, processUserChartData } from '../charts'
import {
buildDashboardWorkbook,
chartSheet,
flowSheets,
MAX_DASHBOARD_EXPORT_ROWS,
performanceSheets,
quotaValue,
usageSheets,
} from '../export'
import { buildDashboardFlowData } from '../flow'
const t = i18next.getFixedT('en')
afterEach(() => {
useSystemConfigStore.setState(useSystemConfigStore.getInitialState(), true)
})
const usage = [
{
created_at: 1700000000,
model_name: '模型-A',
username: 'alice',
count: 3,
token_used: 100,
quota: 500000,
},
{
created_at: 1700003600,
model_name: '模型-A',
username: 'bob',
count: 1,
token_used: 20,
quota: 250000,
},
{
created_at: 1700003600,
model_name: '模型-B',
username: 'alice',
count: 6,
token_used: 80,
quota: 250000,
},
]
it('exports all model details and reconciles ranking totals and shares without rounding the source quota', () => {
const sheets = usageSheets(usage, 'hour', 'model_name', t)
expect(sheets[0].rows).toHaveLength(3)
expect(sheets[0].rows[0]).toEqual([
new Date(1700000000000),
'alice',
'模型-A',
3,
100,
500000,
1,
])
expect(sheets[1].rows).toEqual([
['模型-B', 6, 80, 250000, 0.5, 0.6, 0.25],
['模型-A', 4, 120, 750000, 1.5, 0.4, 0.75],
])
expect(sheets[2].rows.reduce((sum, row) => sum + Number(row[4]), 0)).toBe(
1000000
)
})
it('keeps the full user ranking while the chart sheet preserves its selected top limit', () => {
const sheets = usageSheets(usage, 'hour', 'username', t)
expect(sheets[1].rows.map((row) => row[0])).toEqual(['alice', 'bob'])
const chart = processUserChartData(usage, 'hour', t, 1)
const visible = chartSheet('Top users', chart.spec_user_rank, [
['User', 'User'],
['rawQuota', 'Quota'],
])
expect(visible.rows).toEqual([['alice', 750000]])
})
it('exports the actual model trend including padded time points and Other grouping', () => {
const data = Array.from({ length: 22 }, (_, i) => ({
created_at: 1700000000,
model_name: `model-${i}`,
count: i + 1,
quota: i + 1,
}))
const charts = processChartData(data, 'hour', t)
const trend = chartSheet('Trend', charts.spec_model_line, [
['Time', 'Time'],
['Model', 'Model'],
['Count', 'Requests'],
])
expect(new Set(trend.rows.map((row) => row[0])).size).toBe(7)
expect(trend.rows.some((row) => row[1] === 'Other')).toBe(true)
expect(trend.rows.reduce((sum, row) => sum + Number(row[2]), 0)).toBe(253)
})
it('uses the configured currency conversion while retaining raw quota', () => {
useSystemConfigStore.getState().setConfig({
currency: {
...DEFAULT_CURRENCY_CONFIG,
quotaDisplayType: 'CNY',
usdExchangeRate: 7,
},
})
const sheet = usageSheets(usage, 'hour', 'model_name', t)[0]
expect(sheet.headers.at(-1)).toContain('CNY')
expect(sheet.rows[0].slice(-2)).toEqual([500000, 7])
useSystemConfigStore.getState().setConfig({
currency: { ...DEFAULT_CURRENCY_CONFIG, quotaDisplayType: 'TOKENS' },
})
expect(quotaValue(500000)).toBe(500000)
})
it('preserves fractions for performance percentages rather than multiplying rates by 100 twice', async () => {
const sheets = performanceSheets(
[
{
model_name: 'm',
avg_latency_ms: 1200,
avg_tps: 12.5,
success_rate: 99.5,
},
],
{ avgLatencyMs: 1200, avgTps: 12.5, successRate: 99.5 },
t
)
const wb = await buildDashboardWorkbook(sheets, t)
expect(wb.Sheets['Model performance'].D2).toMatchObject({
t: 'n',
v: 0.995,
z: '0.00%',
})
expect(wb.Sheets['Model performance'].E2).toBeUndefined()
})
describe('flow workbook scope', () => {
const rows = [
{
user_id: 1,
username: 'secret-alice',
token_id: 11,
token_name: 'secret-key',
channel_id: 21,
channel_name: 'secret-channel',
node_name: 'secret-node',
model_name: 'model-a',
use_group: 'default',
count: 3,
token_used: 10,
quota: 300,
},
{
user_id: 2,
username: 'bob',
token_id: 12,
token_name: 'bob-key',
channel_id: 22,
channel_name: 'channel-b',
node_name: 'node-b',
model_name: 'model-b',
use_group: 'default',
count: 8,
token_used: 90,
quota: 700,
},
]
it('does not export names or raw IDs when sensitive labels are masked', () => {
const graph = buildDashboardFlowData(rows, 'requests', {
role: 'root',
maskSensitive: true,
}).flow
const sheets = flowSheets(graph, t)
const content = JSON.stringify(sheets)
expect(content).not.toContain('secret-')
expect(content).not.toContain('bob-key')
expect(content).toContain('••••')
expect(sheets[0].rows.map((row) => row[0])).toEqual(
graph.nodes.map((_, i) => i + 1)
)
})
it('exports only the selected user paths with matching totals', () => {
const data = buildDashboardFlowData(rows, 'requests', {
role: 'root',
selectedUsers: ['user:1'],
})
expect(data.summary.requests).toBe(3)
const content = JSON.stringify(flowSheets(data.flow, t))
expect(content).toContain('secret-alice')
expect(content).not.toContain('bob')
})
it('keeps admin-only stages out of ordinary user exports even when input contains them', () => {
const graph = buildDashboardFlowData(rows, 'requests', {
role: 'user',
}).flow
const content = JSON.stringify(flowSheets(graph, t))
expect(content).not.toContain('secret-alice')
expect(content).not.toContain('secret-channel')
expect(content).not.toContain('secret-node')
expect(content).toContain('model-a')
})
})
it('round-trips Chinese text, dates, numeric values and formula-like labels as literal cells', async () => {
const wb = await buildDashboardWorkbook(
[
{
name: '数据/明细',
headers: ['名称', '次数', '时间', '金额'],
rows: [
[
'=HYPERLINK("https://example.test")',
12,
new Date(2026, 9, 27, 10),
0.00012345,
],
['中文', 0, null, Number.NaN],
],
},
],
t
)
const read = XLSX.read(XLSX.write(wb, { type: 'array', bookType: 'xlsx' }), {
type: 'array',
cellNF: true,
})
const sheet = read.Sheets[read.SheetNames[0]]
expect(sheet.A2.t).toBe('s')
expect(sheet.A2.f).toBeUndefined()
expect(sheet.B2).toMatchObject({ t: 'n', v: 12 })
expect(XLSX.SSF.parse_date_code(sheet.C2.v)).toMatchObject({
y: 2026,
m: 10,
d: 27,
H: 10,
M: 0,
S: 0,
})
expect(sheet.C2.w).toBe('2026-10-27 10:00:00')
expect(sheet.D2.v).toBe(0.00012345)
expect(sheet.A3.v).toBe('中文')
expect(sheet.D3).toBeUndefined()
expect(sheet['!autofilter']?.ref).toBe('A1:D3')
})
it('keeps header-only sheets for empty datasets and unique legal names for long translated titles', async () => {
const title = 'A'.repeat(40)
const wb = await buildDashboardWorkbook(
[
{ name: title, headers: ['Name'], rows: [] },
{ name: title.toLowerCase(), headers: ['Name'], rows: [] },
],
t
)
expect(wb.SheetNames).toHaveLength(2)
expect(new Set(wb.SheetNames.map((name) => name.toLowerCase())).size).toBe(2)
expect(wb.SheetNames.every((name) => name.length <= 31)).toBe(true)
expect(wb.Sheets[wb.SheetNames[0]].A1.v).toBe('Name')
})
it('fails explicitly rather than silently truncating too many rows or oversized cell text', async () => {
await expect(
buildDashboardWorkbook(
[
{
name: 'large',
headers: ['Value'],
rows: Array.from({ length: MAX_DASHBOARD_EXPORT_ROWS + 1 }, () => [
1,
]),
},
],
t
)
).rejects.toThrow('Too much dashboard data')
await expect(
buildDashboardWorkbook(
[{ name: 'long', headers: ['Text'], rows: [['x'.repeat(32768)]] }],
t
)
).rejects.toThrow('Excel text limit')
})
it('does not build a workbook after cancellation', async () => {
const controller = new AbortController()
controller.abort()
await expect(
buildDashboardWorkbook([], t, controller.signal)
).rejects.toThrow()
})
...@@ -16,12 +16,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>. ...@@ -16,12 +16,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { Download, Loader2 } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button' import { ExcelExportButton } from '@/components/excel-export-button'
import { import {
buildLogsWorkbook, buildLogsWorkbook,
...@@ -35,88 +32,24 @@ export function LogsExportButton(props: { ...@@ -35,88 +32,24 @@ export function LogsExportButton(props: {
disabled?: boolean disabled?: boolean
}) { }) {
const { t } = useTranslation() const { t } = useTranslation()
const [progress, setProgress] = useState<number | null>(null)
const activeExport = useRef<AbortController | null>(null)
const scopeKey = JSON.stringify(props.config)
useEffect(() => {
setProgress(null)
return () => {
activeExport.current?.abort()
activeExport.current = null
}
}, [scopeKey])
const handleExport = async () => {
if (activeExport.current) return
const controller = new AbortController()
activeExport.current = controller
setProgress(0)
try {
const logs = await collectExportLogs(
props.config,
controller.signal,
setProgress,
t
)
if (logs.length === 0) {
toast.info(t('No Logs Found'))
return
}
const workbook = await buildLogsWorkbook(logs, props.config, t)
const XLSX = await import('xlsx')
controller.signal.throwIfAborted()
XLSX.writeFile(
workbook,
`usage-logs-${props.config.logCategory}-${Date.now()}.xlsx`,
{ compression: true }
)
} catch (error) {
if (!controller.signal.aborted) {
toast.error(
error instanceof Error ? error.message : t('Failed to export logs')
)
}
} finally {
if (activeExport.current === controller) {
activeExport.current = null
setProgress(null)
}
}
}
return ( return (
<> <ExcelExportButton
<Button scopeKey={JSON.stringify(props.config)}
variant='outline' disabled={props.disabled}
disabled={props.disabled || progress !== null} maxRows={MAX_EXPORT_LOGS}
aria-busy={progress !== null} filename={`usage-logs-${props.config.logCategory}`}
title={t('Export applied filters to Excel (up to {{count}} rows).', { emptyMessage={t('No Logs Found')}
count: MAX_EXPORT_LOGS, errorMessage={t('Failed to export logs')}
})} buildWorkbook={async (signal, onProgress) => {
onClick={handleExport} const logs = await collectExportLogs(
> props.config,
{progress !== null ? ( signal,
<Loader2 className='animate-spin' aria-hidden='true' /> onProgress,
) : ( t
<Download aria-hidden='true' /> )
)} if (!logs.length) return null
{progress !== null return buildLogsWorkbook(logs, props.config, t)
? t('Exporting {{count}} rows', { count: progress }) }}
: t('Export Excel')} />
</Button>
{progress !== null && (
<Button
variant='ghost'
onClick={() => {
activeExport.current?.abort()
activeExport.current = null
setProgress(null)
}}
>
{t('Cancel')}
</Button>
)}
</>
) )
} }
...@@ -17,7 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>. ...@@ -17,7 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import type { PermissionCatalog } from '@/lib/admin-permissions' import type { PermissionCatalog } from '@/lib/admin-permissions'
import { api } from '@/lib/api' import { api, type ApiRequestConfig } from '@/lib/api'
import type { CustomOAuthBinding } from '@/lib/oauth' import type { CustomOAuthBinding } from '@/lib/oauth'
import type { import type {
...@@ -39,10 +39,12 @@ import type { ...@@ -39,10 +39,12 @@ import type {
* Get paginated users list * Get paginated users list
*/ */
export async function getUsers( export async function getUsers(
params: GetUsersParams = {} params: GetUsersParams = {},
options?: ApiRequestConfig
): Promise<GetUsersResponse> { ): Promise<GetUsersResponse> {
const { p = 1, page_size = 10, sort_by, sort_order } = params const { p = 1, page_size = 10, sort_by, sort_order } = params
const res = await api.get('/api/user/', { const res = await api.get('/api/user/', {
...options,
params: { params: {
p, p,
page_size, page_size,
...@@ -57,7 +59,8 @@ export async function getUsers( ...@@ -57,7 +59,8 @@ export async function getUsers(
* Search users by keyword or group * Search users by keyword or group
*/ */
export async function searchUsers( export async function searchUsers(
params: SearchUsersParams params: SearchUsersParams,
options?: ApiRequestConfig
): Promise<GetUsersResponse> { ): Promise<GetUsersResponse> {
const { const {
keyword = '', keyword = '',
...@@ -78,7 +81,10 @@ export async function searchUsers( ...@@ -78,7 +81,10 @@ export async function searchUsers(
queryParams.set('page_size', String(page_size)) queryParams.set('page_size', String(page_size))
if (sort_by) queryParams.set('sort_by', sort_by) if (sort_by) queryParams.set('sort_by', sort_by)
if (sort_order) queryParams.set('sort_order', sort_order) if (sort_order) queryParams.set('sort_order', sort_order)
const res = await api.get(`/api/user/search?${queryParams.toString()}`) const res = await api.get(
`/api/user/search?${queryParams.toString()}`,
options
)
return res.data return res.data
} }
......
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import fs from 'node:fs'
import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import i18next from 'i18next'
import { toast } from 'sonner'
import { expect, it, vi } from 'vitest'
import * as XLSX from 'xlsx'
import { api } from '@/lib/api'
import { buildUsersWorkbook, collectExportUsers } from '../../lib/export'
import { userSchema } from '../../types'
import { UsersExportButton } from '../users-export-button'
const user = userSchema.parse({
id: 1,
username: '=SUM(1,2)',
display_name: '测试用户',
email: 'user@example.test',
role: 1,
status: 1,
group: 'default',
quota: 0,
used_quota: 500000,
request_count: 2,
password: 'secret',
created_at: 1700000000,
})
const filters = {
keyword: 'test',
status: '1',
role: '1',
group: 'default',
sort_by: 'id' as const,
sort_order: 'asc' as const,
}
it('exports all matching pages with applied filters and sorting, independent of the visible page', async () => {
const firstPage = Array.from({ length: 100 }, (_, index) => ({
...user,
id: index + 1,
}))
const get = vi
.spyOn(api, 'get')
.mockResolvedValueOnce({
data: { success: true, data: { items: firstPage, total: 101 } },
})
.mockResolvedValueOnce({
data: {
success: true,
data: { items: [{ ...user, id: 101 }], total: 101 },
},
})
const progress = vi.fn()
const signal = new AbortController().signal
const users = await collectExportUsers(filters, signal, progress, i18next.t)
expect(users).toHaveLength(101)
const urls = get.mock.calls.map(
([url]) => new URL(url, 'https://example.test')
)
expect(urls.map((url) => url.searchParams.get('p'))).toEqual(['1', '2'])
expect(Object.fromEntries(urls[1].searchParams)).toMatchObject({
...filters,
page_size: '100',
})
expect(get.mock.calls[1][1]).toMatchObject({ signal, disableDuplicate: true })
expect(progress.mock.calls).toEqual([[100], [101]])
})
it('uses the list endpoint when no filters are applied', async () => {
const get = vi.spyOn(api, 'get').mockResolvedValue({
data: { success: true, data: { items: [user], total: 1 } },
})
expect(
await collectExportUsers(
{},
new AbortController().signal,
vi.fn(),
i18next.t
)
).toEqual([user])
expect(get).toHaveBeenCalledWith(
'/api/user/',
expect.objectContaining({
params: expect.objectContaining({ p: 1, page_size: 100 }),
})
)
})
it.each([
{ success: false, message: 'Access denied' },
{ success: true, data: { items: [user], total: 10001 } },
{ success: true, data: { items: [], total: 2 } },
])(
'rejects failed, oversized or incomplete results instead of exporting partial data: %j',
async (response) => {
vi.spyOn(api, 'get').mockResolvedValue({ data: response })
await expect(
collectExportUsers(
filters,
new AbortController().signal,
vi.fn(),
i18next.t
)
).rejects.toThrow()
}
)
it.each(['duplicate', 'total', 'network'])(
'rejects later page %s errors',
async (failure) => {
const get = vi.spyOn(api, 'get').mockResolvedValueOnce({
data: { success: true, data: { items: [user], total: 2 } },
})
if (failure === 'network') {
get.mockRejectedValueOnce(new Error('Network unavailable'))
} else {
get.mockResolvedValueOnce({
data: {
success: true,
data: { items: [user], total: failure === 'total' ? 3 : 2 },
},
})
}
await expect(
collectExportUsers(
filters,
new AbortController().signal,
vi.fn(),
i18next.t
)
).rejects.toThrow()
}
)
it('writes valid Excel with numeric quotas, Chinese text, deleted status and no secrets or formulas', async () => {
const workbook = await buildUsersWorkbook(
[user, { ...user, id: 2, DeletedAt: '2026-10-27', role: 100 }],
i18next.t
)
const parsed = XLSX.read(
XLSX.write(workbook, { type: 'array', bookType: 'xlsx' }),
{ type: 'array' }
)
const rows = XLSX.utils.sheet_to_json(parsed.Sheets.Users)
expect(rows[0]).toMatchObject({
Username: '=SUM(1,2)',
'Display Name': '测试用户',
'Remaining Quota (raw)': 0,
'Used Quota (raw)': 500000,
'Last Login': '',
Status: 'Enabled',
})
expect(rows[1]).toMatchObject({ Status: 'Deleted', Role: 'Root' })
expect(JSON.stringify(rows)).not.toContain('secret')
expect(parsed.Sheets.Users.B2.t).toBe('s')
expect(parsed.Sheets.Users.B2.f).toBeUndefined()
})
it('downloads a workbook after keyboard activation', async () => {
vi.spyOn(api, 'get').mockResolvedValue({
data: { success: true, data: { items: [user], total: 1 } },
})
const download = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
render(<UsersExportButton filters={filters} />)
screen.getByRole('button', { name: 'Export Excel' }).focus()
await userEvent.keyboard('{Enter}')
await waitFor(() =>
expect(download).toHaveBeenCalledWith(
expect.stringMatching(/^users-\d+\.xlsx$/),
expect.anything()
)
)
expect(screen.getByRole('button', { name: 'Export Excel' })).toBeEnabled()
})
it('shows an empty message without downloading when the matching users disappear', async () => {
vi.spyOn(api, 'get').mockResolvedValue({
data: { success: true, data: { items: [], total: 0 } },
})
const info = vi.spyOn(toast, 'info').mockImplementation(() => 1)
const download = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
render(<UsersExportButton filters={filters} />)
await userEvent.click(screen.getByRole('button', { name: 'Export Excel' }))
await waitFor(() => expect(info).toHaveBeenCalledWith('No Users Found'))
expect(download).not.toHaveBeenCalled()
})
it('shows request failures and permits retry', async () => {
vi.spyOn(api, 'get').mockRejectedValue(new Error('Network unavailable'))
const error = vi.spyOn(toast, 'error').mockImplementation(() => 1)
render(<UsersExportButton filters={filters} />)
await userEvent.click(screen.getByRole('button', { name: 'Export Excel' }))
await waitFor(() => expect(error).toHaveBeenCalledWith('Network unavailable'))
expect(screen.getByRole('button', { name: 'Export Excel' })).toBeEnabled()
})
it.each(['cancel', 'filter', 'unmount'])(
'aborts pending export on %s without downloading or reporting errors',
async (action) => {
let resolveRequest!: (value: unknown) => void
const get = vi.spyOn(api, 'get').mockImplementation(
() =>
new Promise((resolve) => {
resolveRequest = resolve
})
)
const download = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
const error = vi.spyOn(toast, 'error').mockImplementation(() => 1)
const view = render(<UsersExportButton filters={filters} />)
await userEvent.click(screen.getByRole('button', { name: 'Export Excel' }))
expect(
screen.getByRole('button', { name: 'Exporting 0 rows' })
).toBeDisabled()
expect(
screen.getByRole('button', { name: 'Exporting 0 rows' })
).toHaveAttribute('aria-busy', 'true')
if (action === 'cancel') {
await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))
}
if (action === 'filter') view.rerender(<UsersExportButton filters={{}} />)
if (action === 'unmount') view.unmount()
expect(get.mock.calls[0][1]?.signal?.aborted).toBe(true)
await act(async () => {
resolveRequest({
data: { success: true, data: { items: [user], total: 1 } },
})
})
expect(download).not.toHaveBeenCalled()
expect(error).not.toHaveBeenCalled()
}
)
it('disables export while the table is loading or empty', () => {
render(<UsersExportButton filters={filters} disabled />)
expect(screen.getByRole('button', { name: 'Export Excel' })).toBeDisabled()
})
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useTranslation } from 'react-i18next'
import { ExcelExportButton } from '@/components/excel-export-button'
import {
buildUsersWorkbook,
collectExportUsers,
MAX_EXPORT_USERS,
type UserExportFilters,
} from '../lib/export'
export function UsersExportButton(props: {
filters: UserExportFilters
disabled?: boolean
}) {
const { t } = useTranslation()
return (
<ExcelExportButton
scopeKey={JSON.stringify(props.filters)}
disabled={props.disabled}
maxRows={MAX_EXPORT_USERS}
filename='users'
emptyMessage={t('No Users Found')}
errorMessage={t('Failed to export users')}
buildWorkbook={async (signal, onProgress) => {
const users = await collectExportUsers(
props.filters,
signal,
onProgress,
t
)
if (!users.length) return null
return buildUsersWorkbook(users, t)
}}
/>
)
}
...@@ -42,6 +42,7 @@ import { ...@@ -42,6 +42,7 @@ import {
import type { User, UserSortBy } from '../types' import type { User, UserSortBy } from '../types'
import { DataTableBulkActions } from './data-table-bulk-actions' import { DataTableBulkActions } from './data-table-bulk-actions'
import { useUsersColumns } from './users-columns' import { useUsersColumns } from './users-columns'
import { UsersExportButton } from './users-export-button'
import { useUsers } from './users-provider' import { useUsers } from './users-provider'
const route = getRouteApi('/_authenticated/users/') const route = getRouteApi('/_authenticated/users/')
...@@ -215,6 +216,18 @@ export function UsersTable() { ...@@ -215,6 +216,18 @@ export function UsersTable() {
skeletonKeyPrefix='users-skeleton' skeletonKeyPrefix='users-skeleton'
applyHeaderSize applyHeaderSize
toolbarProps={{ toolbarProps={{
preActions: (
<UsersExportButton
filters={{
keyword: globalFilter,
status: statusFilter[0] ?? '',
role: roleFilter[0] ?? '',
group: groupFilter,
...sortParams,
}}
disabled={isFetching || !users.length}
/>
),
searchPlaceholder: t('Filter by username, name or email...'), searchPlaceholder: t('Filter by username, name or email...'),
searchDebounceMs: 500, searchDebounceMs: 500,
filters: [ filters: [
......
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { TFunction } from 'i18next'
import type { WorkBook } from 'xlsx'
import { formatQuotaWithCurrency } from '@/lib/currency'
import { formatTimestampToDate } from '@/lib/format'
import { getUsers, searchUsers } from '../api'
import { isUserDeleted, USER_ROLES, USER_STATUSES } from '../constants'
import type { SearchUsersParams, User } from '../types'
export const MAX_EXPORT_USERS = 10_000
export type UserExportFilters = Omit<SearchUsersParams, 'p' | 'page_size'>
export async function collectExportUsers(
filters: UserExportFilters,
signal: AbortSignal,
onProgress: (count: number) => void,
t: TFunction
): Promise<User[]> {
const users: User[] = []
const ids = new Set<number>()
let total = 0
const hasFilters = Boolean(
filters.keyword?.trim() || filters.group || filters.role || filters.status
)
for (let page = 1; page === 1 || users.length < total; page++) {
signal.throwIfAborted()
const params = { ...filters, p: page, page_size: 100 }
const options = {
signal,
disableDuplicate: true,
skipBusinessError: true,
skipErrorHandler: true,
}
const result = hasFilters
? await searchUsers(params, options)
: await getUsers(params, options)
signal.throwIfAborted()
if (!result.success || !result.data) {
throw new Error(result.message || t('Failed to load users'))
}
const items = result.data.items ?? []
if (page === 1) total = result.data.total
if (
total > MAX_EXPORT_USERS ||
users.length + items.length > MAX_EXPORT_USERS
) {
throw new Error(
t(
'Too many users to export. Narrow the filters to {{count}} rows or fewer.',
{ count: MAX_EXPORT_USERS }
)
)
}
if (
!Number.isSafeInteger(total) ||
total < 0 ||
result.data.total !== total ||
(items.length === 0 && users.length < total) ||
users.length + items.length > total
) {
throw new Error(t('Users changed during export. Please try again.'))
}
for (const user of items) {
if (ids.has(user.id)) {
throw new Error(t('Users changed during export. Please try again.'))
}
ids.add(user.id)
users.push(user)
}
onProgress(users.length)
}
return users
}
export async function buildUsersWorkbook(
users: User[],
t: TFunction
): Promise<WorkBook> {
const XLSX = await import('xlsx')
const headers = [
t('User ID'),
t('Username'),
t('Display Name'),
t('Email'),
t('Role'),
t('Status'),
t('Group'),
t('Available Balance'),
t('Total Used'),
t('Remaining Quota (raw)'),
t('Used Quota (raw)'),
t('Request Count'),
t('Created At'),
t('Last Login'),
]
const rows = users.map((user) => {
const role = USER_ROLES[user.role as keyof typeof USER_ROLES]
const status = USER_STATUSES[user.status as keyof typeof USER_STATUSES]
let statusLabel = status ? t(status.labelKey) : String(user.status)
if (isUserDeleted(user)) statusLabel = t('Deleted')
return [
user.id,
user.username,
user.display_name,
user.email ?? '',
role ? t(role.labelKey) : String(user.role),
statusLabel,
user.group,
formatQuotaWithCurrency(user.quota),
formatQuotaWithCurrency(user.used_quota),
user.quota,
user.used_quota,
user.request_count,
user.created_at ? formatTimestampToDate(user.created_at) : '',
user.last_login_at ? formatTimestampToDate(user.last_login_at) : '',
]
})
// Whitelist columns; strings remain text cells, never executable formulas.
const sheet = XLSX.utils.aoa_to_sheet([headers, ...rows])
sheet['!cols'] = headers.map(() => ({ wch: 22 }))
sheet['!autofilter'] = { ref: sheet['!ref'] || 'A1' }
const workbook = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(workbook, sheet, 'Users')
return workbook
}
{ {
"translation": { "translation": {
"A dashboard cell exceeds the Excel text limit.": "A dashboard cell exceeds the Excel text limit.",
"API Key name": "API Key name",
"API endpoint": "API endpoint",
"Average latency (ms)": "Average latency (ms)",
"Chart": "Chart",
"Chart value (USD)": "Chart value (USD)",
"Consumption": "Consumption",
"Consumption area chart": "Consumption area chart",
"Consumption chart settings": "Consumption chart settings",
"Consumption distribution": "Consumption distribution",
"Consumption share": "Consumption share",
"Current page and filters; all loaded detail rows. Charts are exported as data tables.": "Current page and filters; all loaded detail rows. Charts are exported as data tables.",
"End time": "End time",
"Exchange rate": "Exchange rate",
"Export information": "Export information",
"Export scope": "Export scope",
"Exported at": "Exported at",
"Failed to export dashboard": "Failed to export dashboard",
"Flow filters": "Flow filters",
"Flow links": "Flow links",
"Flow nodes": "Flow nodes",
"Flow value": "Flow value",
"Highlighted": "Highlighted",
"Latency (ms)": "Latency (ms)",
"Loaded": "Loaded",
"Metric": "Metric",
"Model chart settings": "Model chart settings",
"Model performance": "Model performance",
"Period quota (raw)": "Period quota (raw)",
"Publish date": "Publish date",
"Quota (raw)": "Quota (raw)",
"Quota per USD": "Quota per USD",
"Request share": "Request share",
"Runway (days)": "Runway (days)",
"Source index": "Source index",
"Start time": "Start time",
"Summary chart": "Summary chart",
"Target index": "Target index",
"Throughput (tokens/s)": "Throughput (tokens/s)",
"Time granularity": "Time granularity",
"Timezone": "Timezone",
"Too much dashboard data. Narrow the time range and try again.": "Too much dashboard data. Narrow the time range and try again.",
"Usage details": "Usage details",
"Usage ranking": "Usage ranking",
"Usage trend": "Usage trend",
"User filters": "User filters",
"Visible stages": "Visible stages",
"Used Quota (raw)": "Used Quota (raw)",
"Remaining Quota (raw)": "Remaining Quota (raw)",
"Users changed during export. Please try again.": "Users changed during export. Please try again.",
"Too many users to export. Narrow the filters to {{count}} rows or fewer.": "Too many users to export. Narrow the filters to {{count}} rows or fewer.",
"Failed to export users": "Failed to export users",
"360": "360", "360": "360",
"1000": "1000", "1000": "1000",
"10000": "10000", "10000": "10000",
......
{ {
"translation": { "translation": {
"A dashboard cell exceeds the Excel text limit.": "A dashboard cell exceeds the Excel text limit.",
"API Key name": "API Key name",
"API endpoint": "API endpoint",
"Average latency (ms)": "Average latency (ms)",
"Chart": "Chart",
"Chart value (USD)": "Chart value (USD)",
"Consumption": "Consumption",
"Consumption area chart": "Consumption area chart",
"Consumption chart settings": "Consumption chart settings",
"Consumption distribution": "Consumption distribution",
"Consumption share": "Consumption share",
"Current page and filters; all loaded detail rows. Charts are exported as data tables.": "Current page and filters; all loaded detail rows. Charts are exported as data tables.",
"End time": "End time",
"Exchange rate": "Exchange rate",
"Export information": "Export information",
"Export scope": "Export scope",
"Exported at": "Exported at",
"Failed to export dashboard": "Failed to export dashboard",
"Flow filters": "Flow filters",
"Flow links": "Flow links",
"Flow nodes": "Flow nodes",
"Flow value": "Flow value",
"Highlighted": "Highlighted",
"Latency (ms)": "Latency (ms)",
"Loaded": "Loaded",
"Metric": "Metric",
"Model chart settings": "Model chart settings",
"Model performance": "Model performance",
"Period quota (raw)": "Period quota (raw)",
"Publish date": "Publish date",
"Quota (raw)": "Quota (raw)",
"Quota per USD": "Quota per USD",
"Request share": "Request share",
"Runway (days)": "Runway (days)",
"Source index": "Source index",
"Start time": "Start time",
"Summary chart": "Summary chart",
"Target index": "Target index",
"Throughput (tokens/s)": "Throughput (tokens/s)",
"Time granularity": "Time granularity",
"Timezone": "Timezone",
"Too much dashboard data. Narrow the time range and try again.": "Too much dashboard data. Narrow the time range and try again.",
"Usage details": "Usage details",
"Usage ranking": "Usage ranking",
"Usage trend": "Usage trend",
"User filters": "User filters",
"Visible stages": "Visible stages",
"Used Quota (raw)": "Quota utilisé (brut)",
"Remaining Quota (raw)": "Quota restant (brut)",
"Users changed during export. Please try again.": "Les utilisateurs ont changé pendant l’exportation. Veuillez réessayer.",
"Too many users to export. Narrow the filters to {{count}} rows or fewer.": "Trop d’utilisateurs à exporter. Limitez les filtres à {{count}} lignes ou moins.",
"Failed to export users": "Échec de l’exportation des utilisateurs",
"360": "360", "360": "360",
"1000": "1000", "1000": "1000",
"10000": "10000", "10000": "10000",
......
{ {
"translation": { "translation": {
"A dashboard cell exceeds the Excel text limit.": "A dashboard cell exceeds the Excel text limit.",
"API Key name": "API Key name",
"API endpoint": "API endpoint",
"Average latency (ms)": "Average latency (ms)",
"Chart": "Chart",
"Chart value (USD)": "Chart value (USD)",
"Consumption": "Consumption",
"Consumption area chart": "Consumption area chart",
"Consumption chart settings": "Consumption chart settings",
"Consumption distribution": "Consumption distribution",
"Consumption share": "Consumption share",
"Current page and filters; all loaded detail rows. Charts are exported as data tables.": "Current page and filters; all loaded detail rows. Charts are exported as data tables.",
"End time": "End time",
"Exchange rate": "Exchange rate",
"Export information": "Export information",
"Export scope": "Export scope",
"Exported at": "Exported at",
"Failed to export dashboard": "Failed to export dashboard",
"Flow filters": "Flow filters",
"Flow links": "Flow links",
"Flow nodes": "Flow nodes",
"Flow value": "Flow value",
"Highlighted": "Highlighted",
"Latency (ms)": "Latency (ms)",
"Loaded": "Loaded",
"Metric": "Metric",
"Model chart settings": "Model chart settings",
"Model performance": "Model performance",
"Period quota (raw)": "Period quota (raw)",
"Publish date": "Publish date",
"Quota (raw)": "Quota (raw)",
"Quota per USD": "Quota per USD",
"Request share": "Request share",
"Runway (days)": "Runway (days)",
"Source index": "Source index",
"Start time": "Start time",
"Summary chart": "Summary chart",
"Target index": "Target index",
"Throughput (tokens/s)": "Throughput (tokens/s)",
"Time granularity": "Time granularity",
"Timezone": "Timezone",
"Too much dashboard data. Narrow the time range and try again.": "Too much dashboard data. Narrow the time range and try again.",
"Usage details": "Usage details",
"Usage ranking": "Usage ranking",
"Usage trend": "Usage trend",
"User filters": "User filters",
"Visible stages": "Visible stages",
"Used Quota (raw)": "使用済みクォータ(生の値)",
"Remaining Quota (raw)": "残りクォータ(生の値)",
"Users changed during export. Please try again.": "エクスポート中にユーザーデータが変更されました。再試行してください。",
"Too many users to export. Narrow the filters to {{count}} rows or fewer.": "ユーザーが多すぎます。フィルターで {{count}} 件以下に絞り込んでください。",
"Failed to export users": "ユーザーのエクスポートに失敗しました",
"360": "360", "360": "360",
"1000": "1000", "1000": "1000",
"10000": "10000", "10000": "10000",
......
{ {
"translation": { "translation": {
"A dashboard cell exceeds the Excel text limit.": "A dashboard cell exceeds the Excel text limit.",
"API Key name": "API Key name",
"API endpoint": "API endpoint",
"Average latency (ms)": "Average latency (ms)",
"Chart": "Chart",
"Chart value (USD)": "Chart value (USD)",
"Consumption": "Consumption",
"Consumption area chart": "Consumption area chart",
"Consumption chart settings": "Consumption chart settings",
"Consumption distribution": "Consumption distribution",
"Consumption share": "Consumption share",
"Current page and filters; all loaded detail rows. Charts are exported as data tables.": "Current page and filters; all loaded detail rows. Charts are exported as data tables.",
"End time": "End time",
"Exchange rate": "Exchange rate",
"Export information": "Export information",
"Export scope": "Export scope",
"Exported at": "Exported at",
"Failed to export dashboard": "Failed to export dashboard",
"Flow filters": "Flow filters",
"Flow links": "Flow links",
"Flow nodes": "Flow nodes",
"Flow value": "Flow value",
"Highlighted": "Highlighted",
"Latency (ms)": "Latency (ms)",
"Loaded": "Loaded",
"Metric": "Metric",
"Model chart settings": "Model chart settings",
"Model performance": "Model performance",
"Period quota (raw)": "Period quota (raw)",
"Publish date": "Publish date",
"Quota (raw)": "Quota (raw)",
"Quota per USD": "Quota per USD",
"Request share": "Request share",
"Runway (days)": "Runway (days)",
"Source index": "Source index",
"Start time": "Start time",
"Summary chart": "Summary chart",
"Target index": "Target index",
"Throughput (tokens/s)": "Throughput (tokens/s)",
"Time granularity": "Time granularity",
"Timezone": "Timezone",
"Too much dashboard data. Narrow the time range and try again.": "Too much dashboard data. Narrow the time range and try again.",
"Usage details": "Usage details",
"Usage ranking": "Usage ranking",
"Usage trend": "Usage trend",
"User filters": "User filters",
"Visible stages": "Visible stages",
"Used Quota (raw)": "Использованная квота (исходное значение)",
"Remaining Quota (raw)": "Оставшаяся квота (исходное значение)",
"Users changed during export. Please try again.": "Данные пользователей изменились во время экспорта. Повторите попытку.",
"Too many users to export. Narrow the filters to {{count}} rows or fewer.": "Слишком много пользователей для экспорта. Ограничьте выборку до {{count}} строк.",
"Failed to export users": "Не удалось экспортировать пользователей",
"360": "360", "360": "360",
"1000": "1000", "1000": "1000",
"10000": "10000", "10000": "10000",
......
{ {
"translation": { "translation": {
"A dashboard cell exceeds the Excel text limit.": "A dashboard cell exceeds the Excel text limit.",
"API Key name": "API Key name",
"API endpoint": "API endpoint",
"Average latency (ms)": "Average latency (ms)",
"Chart": "Chart",
"Chart value (USD)": "Chart value (USD)",
"Consumption": "Consumption",
"Consumption area chart": "Consumption area chart",
"Consumption chart settings": "Consumption chart settings",
"Consumption distribution": "Consumption distribution",
"Consumption share": "Consumption share",
"Current page and filters; all loaded detail rows. Charts are exported as data tables.": "Current page and filters; all loaded detail rows. Charts are exported as data tables.",
"End time": "End time",
"Exchange rate": "Exchange rate",
"Export information": "Export information",
"Export scope": "Export scope",
"Exported at": "Exported at",
"Failed to export dashboard": "Failed to export dashboard",
"Flow filters": "Flow filters",
"Flow links": "Flow links",
"Flow nodes": "Flow nodes",
"Flow value": "Flow value",
"Highlighted": "Highlighted",
"Latency (ms)": "Latency (ms)",
"Loaded": "Loaded",
"Metric": "Metric",
"Model chart settings": "Model chart settings",
"Model performance": "Model performance",
"Period quota (raw)": "Period quota (raw)",
"Publish date": "Publish date",
"Quota (raw)": "Quota (raw)",
"Quota per USD": "Quota per USD",
"Request share": "Request share",
"Runway (days)": "Runway (days)",
"Source index": "Source index",
"Start time": "Start time",
"Summary chart": "Summary chart",
"Target index": "Target index",
"Throughput (tokens/s)": "Throughput (tokens/s)",
"Time granularity": "Time granularity",
"Timezone": "Timezone",
"Too much dashboard data. Narrow the time range and try again.": "Too much dashboard data. Narrow the time range and try again.",
"Usage details": "Usage details",
"Usage ranking": "Usage ranking",
"Usage trend": "Usage trend",
"User filters": "User filters",
"Visible stages": "Visible stages",
"Used Quota (raw)": "Hạn mức đã dùng (giá trị gốc)",
"Remaining Quota (raw)": "Hạn mức còn lại (giá trị gốc)",
"Users changed during export. Please try again.": "Dữ liệu người dùng đã thay đổi trong khi xuất. Vui lòng thử lại.",
"Too many users to export. Narrow the filters to {{count}} rows or fewer.": "Quá nhiều người dùng để xuất. Hãy lọc xuống {{count}} dòng trở xuống.",
"Failed to export users": "Xuất người dùng thất bại",
"360": "360", "360": "360",
"1000": "1000", "1000": "1000",
"10000": "10000", "10000": "10000",
......
{ {
"translation": { "translation": {
"A dashboard cell exceeds the Excel text limit.": "看板中有文本超过 Excel 单元格长度限制。",
"API Key name": "API 密钥名称",
"API endpoint": "API 地址",
"Average latency (ms)": "平均延迟(毫秒)",
"Chart": "圖表",
"Chart value (USD)": "图表数值(美元)",
"Consumption": "消耗",
"Consumption area chart": "消耗面积图",
"Consumption chart settings": "消耗图表设置",
"Consumption distribution": "消耗分布",
"Consumption share": "消耗占比",
"Current page and filters; all loaded detail rows. Charts are exported as data tables.": "当前页面和筛选条件下的全部已加载明细;图表导出为数据表。",
"End time": "结束时间",
"Exchange rate": "汇率",
"Export information": "导出说明",
"Export scope": "导出范围",
"Exported at": "导出时间",
"Failed to export dashboard": "导出数据看板失败",
"Flow filters": "流向筛选条件",
"Flow links": "流向连线",
"Flow nodes": "流向节点",
"Flow value": "流量指标值",
"Highlighted": "当前高亮",
"Latency (ms)": "延迟(毫秒)",
"Loaded": "已加载",
"Metric": "指标",
"Model chart settings": "模型图表设置",
"Model performance": "模型性能",
"Period quota (raw)": "时段额度合计(原始值)",
"Publish date": "发布日期",
"Quota (raw)": "额度(原始值)",
"Quota per USD": "每美元对应额度",
"Request share": "请求占比",
"Runway (days)": "预计可用天数",
"Source index": "来源序号",
"Start time": "开始时间",
"Summary chart": "概览趋势",
"Target index": "目标序号",
"Throughput (tokens/s)": "吞吐量(Token/秒)",
"Time granularity": "时间粒度",
"Timezone": "时区",
"Too much dashboard data. Narrow the time range and try again.": "看板导出数据过多,请缩小时间范围后重试。",
"Usage details": "用量明细",
"Usage ranking": "用量排名(完整)",
"Usage trend": "用量趋势(完整)",
"User filters": "用户筛选",
"Visible stages": "显示的层级",
"Used Quota (raw)": "已用額度(原始值)",
"Remaining Quota (raw)": "剩餘額度(原始值)",
"Users changed during export. Please try again.": "匯出期間使用者資料發生變化,請重試。",
"Too many users to export. Narrow the filters to {{count}} rows or fewer.": "匯出使用者過多,請調整篩選條件至 {{count}} 筆以內。",
"Failed to export users": "匯出使用者失敗",
"360": "360", "360": "360",
"1000": "1000", "1000": "1000",
"10000": "10000", "10000": "10000",
......
{ {
"translation": { "translation": {
"A dashboard cell exceeds the Excel text limit.": "看板中有文本超过 Excel 单元格长度限制。",
"API Key name": "API 密钥名称",
"API endpoint": "API 地址",
"Average latency (ms)": "平均延迟(毫秒)",
"Chart": "图表",
"Chart value (USD)": "图表数值(美元)",
"Consumption": "消耗",
"Consumption area chart": "消耗面积图",
"Consumption chart settings": "消耗图表设置",
"Consumption distribution": "消耗分布",
"Consumption share": "消耗占比",
"Current page and filters; all loaded detail rows. Charts are exported as data tables.": "当前页面和筛选条件下的全部已加载明细;图表导出为数据表。",
"End time": "结束时间",
"Exchange rate": "汇率",
"Export information": "导出说明",
"Export scope": "导出范围",
"Exported at": "导出时间",
"Failed to export dashboard": "导出数据看板失败",
"Flow filters": "流向筛选条件",
"Flow links": "流向连线",
"Flow nodes": "流向节点",
"Flow value": "流量指标值",
"Highlighted": "当前高亮",
"Latency (ms)": "延迟(毫秒)",
"Loaded": "已加载",
"Metric": "指标",
"Model chart settings": "模型图表设置",
"Model performance": "模型性能",
"Period quota (raw)": "时段额度合计(原始值)",
"Publish date": "发布日期",
"Quota (raw)": "额度(原始值)",
"Quota per USD": "每美元对应额度",
"Request share": "请求占比",
"Runway (days)": "预计可用天数",
"Source index": "来源序号",
"Start time": "开始时间",
"Summary chart": "概览趋势",
"Target index": "目标序号",
"Throughput (tokens/s)": "吞吐量(Token/秒)",
"Time granularity": "时间粒度",
"Timezone": "时区",
"Too much dashboard data. Narrow the time range and try again.": "看板导出数据过多,请缩小时间范围后重试。",
"Usage details": "用量明细",
"Usage ranking": "用量排名(完整)",
"Usage trend": "用量趋势(完整)",
"User filters": "用户筛选",
"Visible stages": "显示的层级",
"Used Quota (raw)": "已用额度(原始值)",
"Remaining Quota (raw)": "剩余额度(原始值)",
"Users changed during export. Please try again.": "导出期间用户数据发生变化,请重试。",
"Too many users to export. Narrow the filters to {{count}} rows or fewer.": "导出用户过多,请调整筛选条件至 {{count}} 条以内。",
"Failed to export users": "导出用户失败",
"360": "360", "360": "360",
"1000": "1000", "1000": "1000",
"10000": "10000", "10000": "10000",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment