Compare commits

..

19 Commits

Author SHA1 Message Date
github-actions[bot]
94aca4dc22 chore: sync VERSION file with release v1.1.222 [skip ci] 2025-12-05 01:06:39 +00:00
shaw
6bfef2525a Merge PR #753: feat: 新增 API Key
请求时间线接口与管理端详情页面
2025-12-05 09:03:53 +08:00
github-actions[bot]
5a636a36f6 chore: sync VERSION file with release v1.1.221 [skip ci] 2025-12-05 00:38:43 +00:00
shaw
b61e1062bf fix: 修复create_proxyagent调用方式 2025-12-05 08:37:43 +08:00
github-actions[bot]
1b18a1226d chore: sync VERSION file with release v1.1.220 [skip ci] 2025-12-04 13:01:54 +00:00
Wesley Liddick
0b2372abab Merge pull request #756 from SunSeekerX/feature_api_disable_switch
feat(account): 新增账户自动防护禁用开关
2025-12-04 08:01:35 -05:00
SunSeekerX
8aca1f9dd1 feat(account): 新增账户自动防护禁用开关
支持 disableAutoProtection 配置项,启用后上游 401/400/429/529 错误不再自动禁用账户
2025-12-04 20:47:12 +08:00
atoz03
95ef04c1a3 fix: 保持仪表盘趋势图非负并纠正小时区间
- 小时粒度请求使用用户选择的起止时间,避免近24小时被截成整天
  - 修正日期展示格式化逻辑,减少时区偏移导致的窗口错位
  - 趋势图 Y 轴(Token/请求数/费用等)强制最小值为 0,防止出现负刻度
2025-12-04 17:05:36 +08:00
atoz03
4919e392a5 feat: 仪表盘日期筛选默认今日并记忆用户偏好 2025-12-04 16:48:11 +08:00
atoz03
354d8da13f feat:已修复详情弹窗位置问题:RecordDetailModal 现在 append-to-body、destroy-on-close,并设定 top="10vh",点击列表底部的“详情”不会被滚动容器截断或浮在页面顶部看不到。 2025-12-04 15:17:48 +08:00
atoz03
3df0c7c650 feat:已修复 ESLint no-shadow 问题:geminiApiAccountService 不再重复声明,改用顶部引入的实例。后端/前端 lint 均通过(npm run lint:check、cd web/admin-spa && npm run lint) 2025-12-04 15:05:09 +08:00
atoz03
6a3dce523b chore: format usage stats route 2025-12-04 15:02:07 +08:00
atoz03
9fe2918a54 feat: keep API key stats modal and add timeline entry point 2025-12-04 14:56:27 +08:00
atoz03
92b30e1924 feat: add API key usage timeline API and admin UI 2025-12-04 14:41:38 +08:00
github-actions[bot]
b63f2f78fc chore: sync VERSION file with release v1.1.219 [skip ci] 2025-12-04 01:48:56 +00:00
Wesley Liddick
c971d239ff Merge pull request #752 from IanShaw027/fix/filter-cloudflare-cdn-headers
fix: 过滤 Cloudflare CDN headers 以防止 API 安全检查
2025-12-03 20:48:41 -05:00
Wesley Liddick
01d6e30e82 Merge pull request #751 from atoz03/feature/account-sort-toggle [skip ci]
feat(accounts): 支持账户排序正序/倒序切换
2025-12-03 20:48:24 -05:00
IanShaw027
5fd78b6411 fix: 过滤 Cloudflare CDN headers 以防止 API 安全检查
使用 Cloudflare 橙色云(CDN 代理模式)时,Cloudflare 会自动添加 CDN 相关的 headers
(cf-*, x-forwarded-*, cdn-loop 等),这会触发上游 API 提供商的安全检查:

1. 已确认问题:88code API 检测到 CDN headers 后返回 403 Forbidden,
   导致 Codex CLI 无法使用
2. 潜在风险:其他 API 提供商(OpenAI、Anthropic)可能也会因检测到
   代理/CDN 特征而采取限制措施

创建统一的 headerFilter 工具类,在所有转发服务中过滤 Cloudflare CDN headers,
使转发请求伪装成正常的直接客户端请求。

1. 新增 src/utils/headerFilter.js
   - 统一的 CDN headers 过滤列表(13 个 Cloudflare headers)
   - 提供 filterForOpenAI() 和 filterForClaude() 方法
   - 在现有过滤逻辑基础上添加 CDN header 过滤

2. 更新 src/services/openaiResponsesRelayService.js
   - 使用 filterForOpenAI() 替代内联的 _filterRequestHeaders()
   - 保持向后兼容性

3. 更新 src/services/claudeRelayService.js
   - 使用 filterForClaude() 替代 _filterClientHeaders() 实现
   - 简化代码,移除重复的 header 列表定义

4. 修复 src/routes/openaiRoutes.js
   - 添加对 input 字段的类型检查(可以是数组或字符串)
   - 防止 "startsWith is not a function" 错误

x-real-ip, x-forwarded-for, x-forwarded-proto, x-forwarded-host,
x-forwarded-port, x-accel-buffering, cf-ray, cf-connecting-ip,
cf-ipcountry, cf-visitor, cf-request-id, cdn-loop, true-client-ip

-  Codex CLI 通过中转服务成功调用 88code API(之前返回 403)
-  保留所有业务必需的 headers(conversation_id、session_id 等)
-  移除所有 Cloudflare CDN 痕迹
-  保持橙色云的 DDoS 防护和 CDN 加速优势
-  Docker 构建成功

1. 解决 88code 403 问题,Codex CLI 可正常使用
2. 降低因 CDN/代理特征被上游 API 识别的风险
3. 提升与各种 API 提供商的兼容性
4. 统一管理 CDN headers 过滤逻辑,便于维护
2025-12-03 07:07:12 -08:00
atoz03
9ad5c85c2c feat(accounts): 支持排序切换正序/倒序
- 统一下拉选择器和表头的排序变量
  - 再次点击同一排序选项/列头时切换排序方向
  - 动态更新排序图标指示当前方向
2025-12-03 20:25:26 +08:00
22 changed files with 8055 additions and 365 deletions

View File

@@ -1 +1 @@
1.1.218 1.1.222

8
package-lock.json generated
View File

@@ -890,6 +890,7 @@
"integrity": "sha512-2BCOP7TN8M+gVDj7/ht3hsaO/B/n5oDbiAyyvnRlNOs+u1o+JWNYTQrmpuNp1/Wq2gcFrI01JAW+paEKDMx/CA==", "integrity": "sha512-2BCOP7TN8M+gVDj7/ht3hsaO/B/n5oDbiAyyvnRlNOs+u1o+JWNYTQrmpuNp1/Wq2gcFrI01JAW+paEKDMx/CA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/code-frame": "^7.27.1", "@babel/code-frame": "^7.27.1",
"@babel/generator": "^7.28.3", "@babel/generator": "^7.28.3",
@@ -2998,6 +2999,7 @@
"integrity": "sha512-yCAeZl7a0DxgNVteXFHt9+uyFbqXGy/ShC4BlcHkoE0AfGXYv/BUiplV72DjMYXHDBXFjhvr6DD1NiRVfB4j8g==", "integrity": "sha512-yCAeZl7a0DxgNVteXFHt9+uyFbqXGy/ShC4BlcHkoE0AfGXYv/BUiplV72DjMYXHDBXFjhvr6DD1NiRVfB4j8g==",
"devOptional": true, "devOptional": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"undici-types": "~6.21.0" "undici-types": "~6.21.0"
} }
@@ -3079,6 +3081,7 @@
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"acorn": "bin/acorn" "acorn": "bin/acorn"
}, },
@@ -3534,6 +3537,7 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"caniuse-lite": "^1.0.30001737", "caniuse-lite": "^1.0.30001737",
"electron-to-chromium": "^1.5.211", "electron-to-chromium": "^1.5.211",
@@ -4421,6 +4425,7 @@
"deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.6.1", "@eslint-community/regexpp": "^4.6.1",
@@ -4477,6 +4482,7 @@
"integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==", "integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"eslint-config-prettier": "bin/cli.js" "eslint-config-prettier": "bin/cli.js"
}, },
@@ -7575,6 +7581,7 @@
"integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"prettier": "bin/prettier.cjs" "prettier": "bin/prettier.cjs"
}, },
@@ -9014,6 +9021,7 @@
"resolved": "https://registry.npmmirror.com/winston/-/winston-3.17.0.tgz", "resolved": "https://registry.npmmirror.com/winston/-/winston-3.17.0.tgz",
"integrity": "sha512-DLiFIXYC5fMPxaRg832S6F5mJYvePtmO5G9v9IgUFPhXm9/GkXarH/TUrBAVzhTCzAj9anE/+GjrgXp/54nOgw==", "integrity": "sha512-DLiFIXYC5fMPxaRg832S6F5mJYvePtmO5G9v9IgUFPhXm9/GkXarH/TUrBAVzhTCzAj9anE/+GjrgXp/54nOgw==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@colors/colors": "^1.6.0", "@colors/colors": "^1.6.0",
"@dabh/diagnostics": "^2.0.2", "@dabh/diagnostics": "^2.0.2",

6357
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -449,9 +449,8 @@ async function handleMessages(req, res) {
// 添加代理配置 // 添加代理配置
if (proxyConfig) { if (proxyConfig) {
const proxyHelper = new ProxyHelper() axiosConfig.httpsAgent = ProxyHelper.createProxyAgent(proxyConfig)
axiosConfig.httpsAgent = proxyHelper.createProxyAgent(proxyConfig) axiosConfig.httpAgent = ProxyHelper.createProxyAgent(proxyConfig)
axiosConfig.httpAgent = proxyHelper.createProxyAgent(proxyConfig)
} }
try { try {
@@ -732,9 +731,8 @@ async function handleModels(req, res) {
headers: { 'Content-Type': 'application/json' } headers: { 'Content-Type': 'application/json' }
} }
if (proxyConfig) { if (proxyConfig) {
const proxyHelper = new ProxyHelper() axiosConfig.httpsAgent = ProxyHelper.createProxyAgent(proxyConfig)
axiosConfig.httpsAgent = proxyHelper.createProxyAgent(proxyConfig) axiosConfig.httpAgent = ProxyHelper.createProxyAgent(proxyConfig)
axiosConfig.httpAgent = proxyHelper.createProxyAgent(proxyConfig)
} }
const response = await axios(axiosConfig) const response = await axios(axiosConfig)
models = (response.data.models || []).map((m) => ({ models = (response.data.models || []).map((m) => ({
@@ -1234,9 +1232,8 @@ async function handleCountTokens(req, res) {
} }
if (proxyConfig) { if (proxyConfig) {
const proxyHelper = new ProxyHelper() axiosConfig.httpsAgent = ProxyHelper.createProxyAgent(proxyConfig)
axiosConfig.httpsAgent = proxyHelper.createProxyAgent(proxyConfig) axiosConfig.httpAgent = ProxyHelper.createProxyAgent(proxyConfig)
axiosConfig.httpAgent = proxyHelper.createProxyAgent(proxyConfig)
} }
try { try {
@@ -1963,9 +1960,8 @@ async function handleStandardGenerateContent(req, res) {
} }
if (proxyConfig) { if (proxyConfig) {
const proxyHelper = new ProxyHelper() axiosConfig.httpsAgent = ProxyHelper.createProxyAgent(proxyConfig)
axiosConfig.httpsAgent = proxyHelper.createProxyAgent(proxyConfig) axiosConfig.httpAgent = ProxyHelper.createProxyAgent(proxyConfig)
axiosConfig.httpAgent = proxyHelper.createProxyAgent(proxyConfig)
} }
try { try {
@@ -2246,9 +2242,8 @@ async function handleStandardStreamGenerateContent(req, res) {
} }
if (proxyConfig) { if (proxyConfig) {
const proxyHelper = new ProxyHelper() axiosConfig.httpsAgent = ProxyHelper.createProxyAgent(proxyConfig)
axiosConfig.httpsAgent = proxyHelper.createProxyAgent(proxyConfig) axiosConfig.httpAgent = ProxyHelper.createProxyAgent(proxyConfig)
axiosConfig.httpAgent = proxyHelper.createProxyAgent(proxyConfig)
} }
try { try {

View File

@@ -131,7 +131,8 @@ router.post('/claude-console-accounts', authenticateAdmin, async (req, res) => {
groupId, groupId,
dailyQuota, dailyQuota,
quotaResetTime, quotaResetTime,
maxConcurrentTasks maxConcurrentTasks,
disableAutoProtection
} = req.body } = req.body
if (!name || !apiUrl || !apiKey) { if (!name || !apiUrl || !apiKey) {
@@ -151,6 +152,10 @@ router.post('/claude-console-accounts', authenticateAdmin, async (req, res) => {
} }
} }
// 校验上游错误自动防护开关
const normalizedDisableAutoProtection =
disableAutoProtection === true || disableAutoProtection === 'true'
// 验证accountType的有效性 // 验证accountType的有效性
if (accountType && !['shared', 'dedicated', 'group'].includes(accountType)) { if (accountType && !['shared', 'dedicated', 'group'].includes(accountType)) {
return res return res
@@ -180,7 +185,8 @@ router.post('/claude-console-accounts', authenticateAdmin, async (req, res) => {
maxConcurrentTasks: maxConcurrentTasks:
maxConcurrentTasks !== undefined && maxConcurrentTasks !== null maxConcurrentTasks !== undefined && maxConcurrentTasks !== null
? Number(maxConcurrentTasks) ? Number(maxConcurrentTasks)
: 0 : 0,
disableAutoProtection: normalizedDisableAutoProtection
}) })
// 如果是分组类型将账户添加到分组CCR 归属 Claude 平台分组) // 如果是分组类型将账户添加到分组CCR 归属 Claude 平台分组)
@@ -250,6 +256,13 @@ router.put('/claude-console-accounts/:accountId', authenticateAdmin, async (req,
return res.status(404).json({ error: 'Account not found' }) return res.status(404).json({ error: 'Account not found' })
} }
// 规范化上游错误自动防护开关
if (mappedUpdates.disableAutoProtection !== undefined) {
mappedUpdates.disableAutoProtection =
mappedUpdates.disableAutoProtection === true ||
mappedUpdates.disableAutoProtection === 'true'
}
// 处理分组的变更 // 处理分组的变更
if (mappedUpdates.accountType !== undefined) { if (mappedUpdates.accountType !== undefined) {
// 如果之前是分组类型,需要从所有分组中移除 // 如果之前是分组类型,需要从所有分组中移除

View File

@@ -1,8 +1,10 @@
const express = require('express') const express = require('express')
const apiKeyService = require('../../services/apiKeyService') const apiKeyService = require('../../services/apiKeyService')
const ccrAccountService = require('../../services/ccrAccountService')
const claudeAccountService = require('../../services/claudeAccountService') const claudeAccountService = require('../../services/claudeAccountService')
const claudeConsoleAccountService = require('../../services/claudeConsoleAccountService') const claudeConsoleAccountService = require('../../services/claudeConsoleAccountService')
const geminiAccountService = require('../../services/geminiAccountService') const geminiAccountService = require('../../services/geminiAccountService')
const geminiApiAccountService = require('../../services/geminiApiAccountService')
const openaiAccountService = require('../../services/openaiAccountService') const openaiAccountService = require('../../services/openaiAccountService')
const openaiResponsesAccountService = require('../../services/openaiResponsesAccountService') const openaiResponsesAccountService = require('../../services/openaiResponsesAccountService')
const droidAccountService = require('../../services/droidAccountService') const droidAccountService = require('../../services/droidAccountService')
@@ -148,7 +150,6 @@ router.get('/accounts/:accountId/usage-history', authenticateAdmin, async (req,
accountData = await geminiAccountService.getAccount(accountId) accountData = await geminiAccountService.getAccount(accountId)
break break
case 'gemini-api': { case 'gemini-api': {
const geminiApiAccountService = require('../../services/geminiApiAccountService')
accountData = await geminiApiAccountService.getAccount(accountId) accountData = await geminiApiAccountService.getAccount(accountId)
break break
} }
@@ -369,7 +370,9 @@ router.get('/usage-trend', authenticateAdmin, async (req, res) => {
logger.info(` endDate (raw): ${endDate}`) logger.info(` endDate (raw): ${endDate}`)
logger.info(` startTime (parsed): ${startTime.toISOString()}`) logger.info(` startTime (parsed): ${startTime.toISOString()}`)
logger.info(` endTime (parsed): ${endTime.toISOString()}`) logger.info(` endTime (parsed): ${endTime.toISOString()}`)
logger.info(` System timezone offset: ${require('../../../config/config').system.timezoneOffset || 8}`) logger.info(
` System timezone offset: ${require('../../../config/config').system.timezoneOffset || 8}`
)
} else { } else {
// 默认最近24小时 // 默认最近24小时
endTime = new Date() endTime = new Date()
@@ -890,7 +893,6 @@ router.get('/account-usage-trend', authenticateAdmin, async (req, res) => {
}) })
] ]
} else if (group === 'gemini') { } else if (group === 'gemini') {
const geminiApiAccountService = require('../../services/geminiApiAccountService')
const [geminiAccounts, geminiApiAccounts] = await Promise.all([ const [geminiAccounts, geminiApiAccounts] = await Promise.all([
geminiAccountService.getAllAccounts(), geminiAccountService.getAllAccounts(),
geminiApiAccountService.getAllAccounts(true) geminiApiAccountService.getAllAccounts(true)
@@ -1818,4 +1820,330 @@ router.get('/usage-costs', authenticateAdmin, async (req, res) => {
} }
}) })
// 获取 API Key 的请求记录时间线
router.get('/api-keys/:keyId/usage-records', authenticateAdmin, async (req, res) => {
try {
const { keyId } = req.params
const {
page = 1,
pageSize = 50,
startDate,
endDate,
model,
accountId,
sortOrder = 'desc'
} = req.query
const pageNumber = Math.max(parseInt(page, 10) || 1, 1)
const pageSizeNumber = Math.min(Math.max(parseInt(pageSize, 10) || 50, 1), 200)
const normalizedSortOrder = sortOrder === 'asc' ? 'asc' : 'desc'
const startTime = startDate ? new Date(startDate) : null
const endTime = endDate ? new Date(endDate) : null
if (
(startDate && Number.isNaN(startTime?.getTime())) ||
(endDate && Number.isNaN(endTime?.getTime()))
) {
return res.status(400).json({ success: false, error: 'Invalid date range' })
}
if (startTime && endTime && startTime > endTime) {
return res
.status(400)
.json({ success: false, error: 'Start date must be before or equal to end date' })
}
const apiKeyInfo = await redis.getApiKey(keyId)
if (!apiKeyInfo || Object.keys(apiKeyInfo).length === 0) {
return res.status(404).json({ success: false, error: 'API key not found' })
}
const rawRecords = await redis.getUsageRecords(keyId, 5000)
const accountTypeNames = {
claude: 'Claude官方',
'claude-console': 'Claude Console',
ccr: 'Claude Console Relay',
openai: 'OpenAI',
'openai-responses': 'OpenAI Responses',
gemini: 'Gemini',
'gemini-api': 'Gemini API',
droid: 'Droid',
unknown: '未知渠道'
}
const accountServices = [
{ type: 'claude', getter: (id) => claudeAccountService.getAccount(id) },
{ type: 'claude-console', getter: (id) => claudeConsoleAccountService.getAccount(id) },
{ type: 'ccr', getter: (id) => ccrAccountService.getAccount(id) },
{ type: 'openai', getter: (id) => openaiAccountService.getAccount(id) },
{ type: 'openai-responses', getter: (id) => openaiResponsesAccountService.getAccount(id) },
{ type: 'gemini', getter: (id) => geminiAccountService.getAccount(id) },
{ type: 'gemini-api', getter: (id) => geminiApiAccountService.getAccount(id) },
{ type: 'droid', getter: (id) => droidAccountService.getAccount(id) }
]
const accountCache = new Map()
const resolveAccountInfo = async (id, type) => {
if (!id) {
return null
}
const cacheKey = `${type || 'any'}:${id}`
if (accountCache.has(cacheKey)) {
return accountCache.get(cacheKey)
}
const servicesToTry = type
? accountServices.filter((svc) => svc.type === type)
: accountServices
for (const service of servicesToTry) {
try {
const account = await service.getter(id)
if (account) {
const info = {
id,
name: account.name || account.email || id,
type: service.type,
status: account.status || account.isActive
}
accountCache.set(cacheKey, info)
return info
}
} catch (error) {
logger.debug(`⚠️ Failed to resolve account ${id} via ${service.type}: ${error.message}`)
}
}
accountCache.set(cacheKey, null)
return null
}
const toUsageObject = (record) => ({
input_tokens: record.inputTokens || 0,
output_tokens: record.outputTokens || 0,
cache_creation_input_tokens: record.cacheCreateTokens || 0,
cache_read_input_tokens: record.cacheReadTokens || 0,
cache_creation: record.cacheCreation || record.cache_creation || null
})
const withinRange = (record) => {
if (!record.timestamp) {
return false
}
const ts = new Date(record.timestamp)
if (Number.isNaN(ts.getTime())) {
return false
}
if (startTime && ts < startTime) {
return false
}
if (endTime && ts > endTime) {
return false
}
return true
}
const filteredRecords = rawRecords.filter((record) => {
if (!withinRange(record)) {
return false
}
if (model && record.model !== model) {
return false
}
if (accountId && record.accountId !== accountId) {
return false
}
return true
})
filteredRecords.sort((a, b) => {
const aTime = new Date(a.timestamp).getTime()
const bTime = new Date(b.timestamp).getTime()
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
return 0
}
return normalizedSortOrder === 'asc' ? aTime - bTime : bTime - aTime
})
const summary = {
totalRequests: 0,
inputTokens: 0,
outputTokens: 0,
cacheCreateTokens: 0,
cacheReadTokens: 0,
totalTokens: 0,
totalCost: 0
}
const modelSet = new Set()
const accountOptionMap = new Map()
let earliestTimestamp = null
let latestTimestamp = null
for (const record of filteredRecords) {
const usage = toUsageObject(record)
const costData = CostCalculator.calculateCost(usage, record.model || 'unknown')
const computedCost =
typeof record.cost === 'number' ? record.cost : costData?.costs?.total || 0
const totalTokens =
record.totalTokens ||
usage.input_tokens +
usage.output_tokens +
usage.cache_creation_input_tokens +
usage.cache_read_input_tokens
summary.totalRequests += 1
summary.inputTokens += usage.input_tokens
summary.outputTokens += usage.output_tokens
summary.cacheCreateTokens += usage.cache_creation_input_tokens
summary.cacheReadTokens += usage.cache_read_input_tokens
summary.totalTokens += totalTokens
summary.totalCost += computedCost
if (record.model) {
modelSet.add(record.model)
}
if (record.accountId) {
const key = `${record.accountId}:${record.accountType || 'unknown'}`
if (!accountOptionMap.has(key)) {
accountOptionMap.set(key, {
id: record.accountId,
accountType: record.accountType || 'unknown'
})
}
}
if (record.timestamp) {
const ts = new Date(record.timestamp)
if (!Number.isNaN(ts.getTime())) {
if (!earliestTimestamp || ts < earliestTimestamp) {
earliestTimestamp = ts
}
if (!latestTimestamp || ts > latestTimestamp) {
latestTimestamp = ts
}
}
}
}
const totalRecords = filteredRecords.length
const totalPages = totalRecords > 0 ? Math.ceil(totalRecords / pageSizeNumber) : 0
const safePage = totalPages > 0 ? Math.min(pageNumber, totalPages) : 1
const startIndex = (safePage - 1) * pageSizeNumber
const pageRecords =
totalRecords === 0 ? [] : filteredRecords.slice(startIndex, startIndex + pageSizeNumber)
const enrichedRecords = []
for (const record of pageRecords) {
const usage = toUsageObject(record)
const costData = CostCalculator.calculateCost(usage, record.model || 'unknown')
const computedCost =
typeof record.cost === 'number' ? record.cost : costData?.costs?.total || 0
const totalTokens =
record.totalTokens ||
usage.input_tokens +
usage.output_tokens +
usage.cache_creation_input_tokens +
usage.cache_read_input_tokens
const accountInfo = await resolveAccountInfo(record.accountId, record.accountType)
const resolvedAccountType = accountInfo?.type || record.accountType || 'unknown'
enrichedRecords.push({
timestamp: record.timestamp,
model: record.model || 'unknown',
accountId: record.accountId || null,
accountName: accountInfo?.name || null,
accountStatus: accountInfo?.status ?? null,
accountType: resolvedAccountType,
accountTypeName: accountTypeNames[resolvedAccountType] || '未知渠道',
inputTokens: usage.input_tokens,
outputTokens: usage.output_tokens,
cacheCreateTokens: usage.cache_creation_input_tokens,
cacheReadTokens: usage.cache_read_input_tokens,
ephemeral5mTokens: record.ephemeral5mTokens || 0,
ephemeral1hTokens: record.ephemeral1hTokens || 0,
totalTokens,
isLongContextRequest: record.isLongContext || record.isLongContextRequest || false,
cost: Number(computedCost.toFixed(6)),
costFormatted:
record.costFormatted ||
costData?.formatted?.total ||
CostCalculator.formatCost(computedCost),
costBreakdown: record.costBreakdown || {
input: costData?.costs?.input || 0,
output: costData?.costs?.output || 0,
cacheCreate: costData?.costs?.cacheWrite || 0,
cacheRead: costData?.costs?.cacheRead || 0,
total: costData?.costs?.total || computedCost
},
responseTime: record.responseTime || null
})
}
const accountOptions = []
for (const option of accountOptionMap.values()) {
const info = await resolveAccountInfo(option.id, option.accountType)
const resolvedType = info?.type || option.accountType || 'unknown'
accountOptions.push({
id: option.id,
name: info?.name || option.id,
accountType: resolvedType,
accountTypeName: accountTypeNames[resolvedType] || '未知渠道'
})
}
return res.json({
success: true,
data: {
records: enrichedRecords,
pagination: {
currentPage: safePage,
pageSize: pageSizeNumber,
totalRecords,
totalPages,
hasNextPage: totalPages > 0 && safePage < totalPages,
hasPreviousPage: totalPages > 0 && safePage > 1
},
filters: {
startDate: startTime ? startTime.toISOString() : null,
endDate: endTime ? endTime.toISOString() : null,
model: model || null,
accountId: accountId || null,
sortOrder: normalizedSortOrder
},
apiKeyInfo: {
id: keyId,
name: apiKeyInfo.name || apiKeyInfo.label || keyId
},
summary: {
...summary,
totalCost: Number(summary.totalCost.toFixed(6)),
avgCost:
summary.totalRequests > 0
? Number((summary.totalCost / summary.totalRequests).toFixed(6))
: 0
},
availableFilters: {
models: Array.from(modelSet),
accounts: accountOptions,
dateRange: {
earliest: earliestTimestamp ? earliestTimestamp.toISOString() : null,
latest: latestTimestamp ? latestTimestamp.toISOString() : null
}
}
}
})
} catch (error) {
logger.error('❌ Failed to get API key usage records:', error)
return res
.status(500)
.json({ error: 'Failed to get API key usage records', message: error.message })
}
})
module.exports = router module.exports = router

View File

@@ -33,7 +33,9 @@ function mapExpiryField(updates, accountType, accountId) {
if ('expiresAt' in mappedUpdates) { if ('expiresAt' in mappedUpdates) {
mappedUpdates.subscriptionExpiresAt = mappedUpdates.expiresAt mappedUpdates.subscriptionExpiresAt = mappedUpdates.expiresAt
delete mappedUpdates.expiresAt delete mappedUpdates.expiresAt
logger.info(`Mapping expiresAt to subscriptionExpiresAt for ${accountType} account ${accountId}`) logger.info(
`Mapping expiresAt to subscriptionExpiresAt for ${accountType} account ${accountId}`
)
} }
return mappedUpdates return mappedUpdates
} }

View File

@@ -67,7 +67,8 @@ class ClaudeConsoleAccountService {
schedulable = true, // 是否可被调度 schedulable = true, // 是否可被调度
dailyQuota = 0, // 每日额度限制美元0表示不限制 dailyQuota = 0, // 每日额度限制美元0表示不限制
quotaResetTime = '00:00', // 额度重置时间HH:mm格式 quotaResetTime = '00:00', // 额度重置时间HH:mm格式
maxConcurrentTasks = 0 // 最大并发任务数0表示无限制 maxConcurrentTasks = 0, // 最大并发任务数0表示无限制
disableAutoProtection = false // 是否关闭自动防护429/401/400/529 不自动禁用)
} = options } = options
// 验证必填字段 // 验证必填字段
@@ -115,7 +116,8 @@ class ClaudeConsoleAccountService {
lastResetDate: redis.getDateStringInTimezone(), // 最后重置日期(按配置时区) lastResetDate: redis.getDateStringInTimezone(), // 最后重置日期(按配置时区)
quotaResetTime, // 额度重置时间 quotaResetTime, // 额度重置时间
quotaStoppedAt: '', // 因额度停用的时间 quotaStoppedAt: '', // 因额度停用的时间
maxConcurrentTasks: maxConcurrentTasks.toString() // 最大并发任务数0表示无限制 maxConcurrentTasks: maxConcurrentTasks.toString(), // 最大并发任务数0表示无限制
disableAutoProtection: disableAutoProtection.toString() // 关闭自动防护
} }
const client = redis.getClientSafe() const client = redis.getClientSafe()
@@ -153,6 +155,7 @@ class ClaudeConsoleAccountService {
quotaResetTime, quotaResetTime,
quotaStoppedAt: null, quotaStoppedAt: null,
maxConcurrentTasks, // 新增:返回并发限制配置 maxConcurrentTasks, // 新增:返回并发限制配置
disableAutoProtection, // 新增:返回自动防护开关
activeTaskCount: 0 // 新增新建账户当前并发数为0 activeTaskCount: 0 // 新增新建账户当前并发数为0
} }
} }
@@ -213,7 +216,8 @@ class ClaudeConsoleAccountService {
// 并发控制相关 // 并发控制相关
maxConcurrentTasks: parseInt(accountData.maxConcurrentTasks) || 0, maxConcurrentTasks: parseInt(accountData.maxConcurrentTasks) || 0,
activeTaskCount activeTaskCount,
disableAutoProtection: accountData.disableAutoProtection === 'true'
}) })
} }
} }
@@ -259,6 +263,7 @@ class ClaudeConsoleAccountService {
} }
accountData.isActive = accountData.isActive === 'true' accountData.isActive = accountData.isActive === 'true'
accountData.schedulable = accountData.schedulable !== 'false' // 默认为true accountData.schedulable = accountData.schedulable !== 'false' // 默认为true
accountData.disableAutoProtection = accountData.disableAutoProtection === 'true'
if (accountData.proxy) { if (accountData.proxy) {
accountData.proxy = JSON.parse(accountData.proxy) accountData.proxy = JSON.parse(accountData.proxy)
@@ -367,6 +372,9 @@ class ClaudeConsoleAccountService {
if (updates.maxConcurrentTasks !== undefined) { if (updates.maxConcurrentTasks !== undefined) {
updatedData.maxConcurrentTasks = updates.maxConcurrentTasks.toString() updatedData.maxConcurrentTasks = updates.maxConcurrentTasks.toString()
} }
if (updates.disableAutoProtection !== undefined) {
updatedData.disableAutoProtection = updates.disableAutoProtection.toString()
}
// ✅ 直接保存 subscriptionExpiresAt如果提供 // ✅ 直接保存 subscriptionExpiresAt如果提供
// Claude Console 没有 token 刷新逻辑,不会覆盖此字段 // Claude Console 没有 token 刷新逻辑,不会覆盖此字段

View File

@@ -37,6 +37,8 @@ class ClaudeConsoleRelayService {
throw new Error('Claude Console Claude account not found') throw new Error('Claude Console Claude account not found')
} }
const autoProtectionDisabled = account.disableAutoProtection === true
logger.info( logger.info(
`📤 Processing Claude Console API request for key: ${apiKeyData.name || apiKeyData.id}, account: ${account.name} (${accountId}), request: ${requestId}` `📤 Processing Claude Console API request for key: ${apiKeyData.name || apiKeyData.id}, account: ${account.name} (${accountId}), request: ${requestId}`
) )
@@ -248,27 +250,41 @@ class ClaudeConsoleRelayService {
// 检查错误状态并相应处理 // 检查错误状态并相应处理
if (response.status === 401) { if (response.status === 401) {
logger.warn(`🚫 Unauthorized error detected for Claude Console account ${accountId}`) logger.warn(
`🚫 Unauthorized error detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
)
if (!autoProtectionDisabled) {
await claudeConsoleAccountService.markAccountUnauthorized(accountId) await claudeConsoleAccountService.markAccountUnauthorized(accountId)
}
} else if (accountDisabledError) { } else if (accountDisabledError) {
logger.error( logger.error(
`🚫 Account disabled error (400) detected for Claude Console account ${accountId}, marking as blocked` `🚫 Account disabled error (400) detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
) )
// 传入完整的错误详情到 webhook // 传入完整的错误详情到 webhook
const errorDetails = const errorDetails =
typeof response.data === 'string' ? response.data : JSON.stringify(response.data) typeof response.data === 'string' ? response.data : JSON.stringify(response.data)
if (!autoProtectionDisabled) {
await claudeConsoleAccountService.markConsoleAccountBlocked(accountId, errorDetails) await claudeConsoleAccountService.markConsoleAccountBlocked(accountId, errorDetails)
}
} else if (response.status === 429) { } else if (response.status === 429) {
logger.warn(`🚫 Rate limit detected for Claude Console account ${accountId}`) logger.warn(
`🚫 Rate limit detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
)
// 收到429先检查是否因为超过了手动配置的每日额度 // 收到429先检查是否因为超过了手动配置的每日额度
await claudeConsoleAccountService.checkQuotaUsage(accountId).catch((err) => { await claudeConsoleAccountService.checkQuotaUsage(accountId).catch((err) => {
logger.error('❌ Failed to check quota after 429 error:', err) logger.error('❌ Failed to check quota after 429 error:', err)
}) })
if (!autoProtectionDisabled) {
await claudeConsoleAccountService.markAccountRateLimited(accountId) await claudeConsoleAccountService.markAccountRateLimited(accountId)
}
} else if (response.status === 529) { } else if (response.status === 529) {
logger.warn(`🚫 Overload error detected for Claude Console account ${accountId}`) logger.warn(
`🚫 Overload error detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
)
if (!autoProtectionDisabled) {
await claudeConsoleAccountService.markAccountOverloaded(accountId) await claudeConsoleAccountService.markAccountOverloaded(accountId)
}
} else if (response.status === 200 || response.status === 201) { } else if (response.status === 200 || response.status === 201) {
// 如果请求成功,检查并移除错误状态 // 如果请求成功,检查并移除错误状态
const isRateLimited = await claudeConsoleAccountService.isAccountRateLimited(accountId) const isRateLimited = await claudeConsoleAccountService.isAccountRateLimited(accountId)
@@ -597,6 +613,7 @@ class ClaudeConsoleRelayService {
}) })
response.data.on('end', async () => { response.data.on('end', async () => {
const autoProtectionDisabled = account.disableAutoProtection === true
// 记录原始错误消息到日志(方便调试,包含供应商信息) // 记录原始错误消息到日志(方便调试,包含供应商信息)
logger.error( logger.error(
`📝 [Stream] Upstream error response from ${account?.name || accountId}: ${errorDataForCheck.substring(0, 500)}` `📝 [Stream] Upstream error response from ${account?.name || accountId}: ${errorDataForCheck.substring(0, 500)}`
@@ -609,25 +626,42 @@ class ClaudeConsoleRelayService {
) )
if (response.status === 401) { if (response.status === 401) {
logger.warn(
`🚫 [Stream] Unauthorized error detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
)
if (!autoProtectionDisabled) {
await claudeConsoleAccountService.markAccountUnauthorized(accountId) await claudeConsoleAccountService.markAccountUnauthorized(accountId)
}
} else if (accountDisabledError) { } else if (accountDisabledError) {
logger.error( logger.error(
`🚫 [Stream] Account disabled error (400) detected for Claude Console account ${accountId}, marking as blocked` `🚫 [Stream] Account disabled error (400) detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
) )
// 传入完整的错误详情到 webhook // 传入完整的错误详情到 webhook
if (!autoProtectionDisabled) {
await claudeConsoleAccountService.markConsoleAccountBlocked( await claudeConsoleAccountService.markConsoleAccountBlocked(
accountId, accountId,
errorDataForCheck errorDataForCheck
) )
}
} else if (response.status === 429) { } else if (response.status === 429) {
await claudeConsoleAccountService.markAccountRateLimited(accountId) logger.warn(
`🚫 [Stream] Rate limit detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
)
// 检查是否因为超过每日额度 // 检查是否因为超过每日额度
claudeConsoleAccountService.checkQuotaUsage(accountId).catch((err) => { claudeConsoleAccountService.checkQuotaUsage(accountId).catch((err) => {
logger.error('❌ Failed to check quota after 429 error:', err) logger.error('❌ Failed to check quota after 429 error:', err)
}) })
if (!autoProtectionDisabled) {
await claudeConsoleAccountService.markAccountRateLimited(accountId)
}
} else if (response.status === 529) { } else if (response.status === 529) {
logger.warn(
`🚫 [Stream] Overload error detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
)
if (!autoProtectionDisabled) {
await claudeConsoleAccountService.markAccountOverloaded(accountId) await claudeConsoleAccountService.markAccountOverloaded(accountId)
} }
}
// 设置响应头 // 设置响应头
if (!responseStream.headersSent) { if (!responseStream.headersSent) {

View File

@@ -3,6 +3,7 @@ const zlib = require('zlib')
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const ProxyHelper = require('../utils/proxyHelper') const ProxyHelper = require('../utils/proxyHelper')
const { filterForClaude } = require('../utils/headerFilter')
const claudeAccountService = require('./claudeAccountService') const claudeAccountService = require('./claudeAccountService')
const unifiedClaudeScheduler = require('./unifiedClaudeScheduler') const unifiedClaudeScheduler = require('./unifiedClaudeScheduler')
const sessionHelper = require('../utils/sessionHelper') const sessionHelper = require('../utils/sessionHelper')
@@ -877,62 +878,9 @@ class ClaudeRelayService {
// 🔧 过滤客户端请求头 // 🔧 过滤客户端请求头
_filterClientHeaders(clientHeaders) { _filterClientHeaders(clientHeaders) {
// 需要移除的敏感 headers // 使用统一的 headerFilter 工具类 - 移除 CDN、浏览器和代理相关 headers
const sensitiveHeaders = [ // 同时伪装成正常的直接客户端请求,避免触发上游 API 的安全检查
'content-type', return filterForClaude(clientHeaders)
'user-agent',
'x-api-key',
'authorization',
'x-authorization',
'host',
'content-length',
'connection',
'proxy-authorization',
'content-encoding',
'transfer-encoding'
]
// 🆕 需要移除的浏览器相关 headers避免CORS问题
const browserHeaders = [
'origin',
'referer',
'sec-fetch-mode',
'sec-fetch-site',
'sec-fetch-dest',
'sec-ch-ua',
'sec-ch-ua-mobile',
'sec-ch-ua-platform',
'accept-language',
'accept-encoding',
'accept',
'cache-control',
'pragma',
'anthropic-dangerous-direct-browser-access' // 这个头可能触发CORS检查
]
// 应该保留的 headers用于会话一致性和追踪
const allowedHeaders = [
'x-request-id',
'anthropic-version', // 保留API版本
'anthropic-beta' // 保留beta功能
]
const filteredHeaders = {}
// 转发客户端的非敏感 headers
Object.keys(clientHeaders || {}).forEach((key) => {
const lowerKey = key.toLowerCase()
// 如果在允许列表中,直接保留
if (allowedHeaders.includes(lowerKey)) {
filteredHeaders[key] = clientHeaders[key]
}
// 如果不在敏感列表和浏览器列表中,也保留
else if (!sensitiveHeaders.includes(lowerKey) && !browserHeaders.includes(lowerKey)) {
filteredHeaders[key] = clientHeaders[key]
}
})
return filteredHeaders
} }
_applyRequestIdentityTransform(body, headers, context = {}) { _applyRequestIdentityTransform(body, headers, context = {}) {

View File

@@ -1,6 +1,7 @@
const axios = require('axios') const axios = require('axios')
const ProxyHelper = require('../utils/proxyHelper') const ProxyHelper = require('../utils/proxyHelper')
const logger = require('../utils/logger') const logger = require('../utils/logger')
const { filterForOpenAI } = require('../utils/headerFilter')
const openaiResponsesAccountService = require('./openaiResponsesAccountService') const openaiResponsesAccountService = require('./openaiResponsesAccountService')
const apiKeyService = require('./apiKeyService') const apiKeyService = require('./apiKeyService')
const unifiedOpenAIScheduler = require('./unifiedOpenAIScheduler') const unifiedOpenAIScheduler = require('./unifiedOpenAIScheduler')
@@ -73,9 +74,9 @@ class OpenAIResponsesRelayService {
const targetUrl = `${fullAccount.baseApi}${req.path}` const targetUrl = `${fullAccount.baseApi}${req.path}`
logger.info(`🎯 Forwarding to: ${targetUrl}`) logger.info(`🎯 Forwarding to: ${targetUrl}`)
// 构建请求头 // 构建请求头 - 使用统一的 headerFilter 移除 CDN headers
const headers = { const headers = {
...this._filterRequestHeaders(req.headers), ...filterForOpenAI(req.headers),
Authorization: `Bearer ${fullAccount.apiKey}`, Authorization: `Bearer ${fullAccount.apiKey}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
@@ -810,29 +811,10 @@ class OpenAIResponsesRelayService {
return { resetsInSeconds, errorData } return { resetsInSeconds, errorData }
} }
// 过滤请求头 // 过滤请求头 - 已迁移到 headerFilter 工具类
// 此方法保留用于向后兼容,实际使用 filterForOpenAI()
_filterRequestHeaders(headers) { _filterRequestHeaders(headers) {
const filtered = {} return filterForOpenAI(headers)
const skipHeaders = [
'host',
'content-length',
'authorization',
'x-api-key',
'x-cr-api-key',
'connection',
'upgrade',
'sec-websocket-key',
'sec-websocket-version',
'sec-websocket-extensions'
]
for (const [key, value] of Object.entries(headers)) {
if (!skipHeaders.includes(key.toLowerCase())) {
filtered[key] = value
}
}
return filtered
} }
// 估算费用(简化版本,实际应该根据不同的定价模型) // 估算费用(简化版本,实际应该根据不同的定价模型)

133
src/utils/headerFilter.js Normal file
View File

@@ -0,0 +1,133 @@
/**
* 统一的 CDN Headers 过滤列表
*
* 用于各服务在原有过滤逻辑基础上,额外移除 Cloudflare CDN 和代理相关的 headers
* 避免触发上游 API如 88code的安全检查
*/
// Cloudflare CDN headers橙色云代理模式会添加这些
const cdnHeaders = [
'x-real-ip',
'x-forwarded-for',
'x-forwarded-proto',
'x-forwarded-host',
'x-forwarded-port',
'x-accel-buffering',
'cf-ray',
'cf-connecting-ip',
'cf-ipcountry',
'cf-visitor',
'cf-request-id',
'cdn-loop',
'true-client-ip'
]
/**
* 为 OpenAI/Responses API 过滤 headers
* 在原有 skipHeaders 基础上添加 CDN headers
*/
function filterForOpenAI(headers) {
const skipHeaders = [
'host',
'content-length',
'authorization',
'x-api-key',
'x-cr-api-key',
'connection',
'upgrade',
'sec-websocket-key',
'sec-websocket-version',
'sec-websocket-extensions',
...cdnHeaders // 添加 CDN headers
]
const filtered = {}
for (const [key, value] of Object.entries(headers)) {
if (!skipHeaders.includes(key.toLowerCase())) {
filtered[key] = value
}
}
return filtered
}
/**
* 为 Claude/Anthropic API 过滤 headers
* 在原有逻辑基础上添加 CDN headers 到敏感列表
*/
function filterForClaude(headers) {
const sensitiveHeaders = [
'content-type',
'user-agent',
'x-api-key',
'authorization',
'x-authorization',
'host',
'content-length',
'connection',
'proxy-authorization',
'content-encoding',
'transfer-encoding',
...cdnHeaders // 添加 CDN headers
]
const browserHeaders = [
'origin',
'referer',
'sec-fetch-mode',
'sec-fetch-site',
'sec-fetch-dest',
'sec-ch-ua',
'sec-ch-ua-mobile',
'sec-ch-ua-platform',
'accept-language',
'accept-encoding',
'accept',
'cache-control',
'pragma',
'anthropic-dangerous-direct-browser-access'
]
const allowedHeaders = ['x-request-id', 'anthropic-version', 'anthropic-beta']
const filtered = {}
Object.keys(headers || {}).forEach((key) => {
const lowerKey = key.toLowerCase()
if (allowedHeaders.includes(lowerKey)) {
filtered[key] = headers[key]
} else if (!sensitiveHeaders.includes(lowerKey) && !browserHeaders.includes(lowerKey)) {
filtered[key] = headers[key]
}
})
return filtered
}
/**
* 为 Gemini API 过滤 headers如果需要转发客户端 headers 时使用)
* 目前 Gemini 服务不转发客户端 headers仅提供此方法备用
*/
function filterForGemini(headers) {
const skipHeaders = [
'host',
'content-length',
'authorization',
'x-api-key',
'connection',
...cdnHeaders // 添加 CDN headers
]
const filtered = {}
for (const [key, value] of Object.entries(headers)) {
if (!skipHeaders.includes(key.toLowerCase())) {
filtered[key] = value
}
}
return filtered
}
module.exports = {
cdnHeaders,
filterForOpenAI,
filterForClaude,
filterForGemini
}

View File

@@ -1157,6 +1157,7 @@
"resolved": "https://registry.npmmirror.com/@types/lodash-es/-/lodash-es-4.17.12.tgz", "resolved": "https://registry.npmmirror.com/@types/lodash-es/-/lodash-es-4.17.12.tgz",
"integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==", "integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/lodash": "*" "@types/lodash": "*"
} }
@@ -1351,6 +1352,7 @@
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"acorn": "bin/acorn" "acorn": "bin/acorn"
}, },
@@ -1587,6 +1589,7 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"caniuse-lite": "^1.0.30001726", "caniuse-lite": "^1.0.30001726",
"electron-to-chromium": "^1.5.173", "electron-to-chromium": "^1.5.173",
@@ -3060,13 +3063,15 @@
"version": "4.17.21", "version": "4.17.21",
"resolved": "https://registry.npmmirror.com/lodash/-/lodash-4.17.21.tgz", "resolved": "https://registry.npmmirror.com/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
"license": "MIT" "license": "MIT",
"peer": true
}, },
"node_modules/lodash-es": { "node_modules/lodash-es": {
"version": "4.17.21", "version": "4.17.21",
"resolved": "https://registry.npmmirror.com/lodash-es/-/lodash-es-4.17.21.tgz", "resolved": "https://registry.npmmirror.com/lodash-es/-/lodash-es-4.17.21.tgz",
"integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==", "integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==",
"license": "MIT" "license": "MIT",
"peer": true
}, },
"node_modules/lodash-unified": { "node_modules/lodash-unified": {
"version": "1.0.3", "version": "1.0.3",
@@ -3618,6 +3623,7 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"nanoid": "^3.3.11", "nanoid": "^3.3.11",
"picocolors": "^1.1.1", "picocolors": "^1.1.1",
@@ -3764,6 +3770,7 @@
"integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"prettier": "bin/prettier.cjs" "prettier": "bin/prettier.cjs"
}, },
@@ -3789,7 +3796,7 @@
}, },
"node_modules/prettier-plugin-tailwindcss": { "node_modules/prettier-plugin-tailwindcss": {
"version": "0.6.14", "version": "0.6.14",
"resolved": "https://registry.npmmirror.com/prettier-plugin-tailwindcss/-/prettier-plugin-tailwindcss-0.6.14.tgz", "resolved": "https://registry.npmjs.org/prettier-plugin-tailwindcss/-/prettier-plugin-tailwindcss-0.6.14.tgz",
"integrity": "sha512-pi2e/+ZygeIqntN+vC573BcW5Cve8zUB0SSAGxqpB4f96boZF4M3phPVoOFCeypwkpRYdi7+jQ5YJJUwrkGUAg==", "integrity": "sha512-pi2e/+ZygeIqntN+vC573BcW5Cve8zUB0SSAGxqpB4f96boZF4M3phPVoOFCeypwkpRYdi7+jQ5YJJUwrkGUAg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
@@ -4028,6 +4035,7 @@
"integrity": "sha512-33xGNBsDJAkzt0PvninskHlWnTIPgDtTwhg0U38CUoNP/7H6wI2Cz6dUeoNPbjdTdsYTGuiFFASuUOWovH0SyQ==", "integrity": "sha512-33xGNBsDJAkzt0PvninskHlWnTIPgDtTwhg0U38CUoNP/7H6wI2Cz6dUeoNPbjdTdsYTGuiFFASuUOWovH0SyQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/estree": "1.0.8" "@types/estree": "1.0.8"
}, },
@@ -4525,6 +4533,7 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },
@@ -4915,6 +4924,7 @@
"integrity": "sha512-qO3aKv3HoQC8QKiNSTuUM1l9o/XX3+c+VTgLHbJWHZGeTPVAg2XwazI9UWzoxjIJCGCV2zU60uqMzjeLZuULqA==", "integrity": "sha512-qO3aKv3HoQC8QKiNSTuUM1l9o/XX3+c+VTgLHbJWHZGeTPVAg2XwazI9UWzoxjIJCGCV2zU60uqMzjeLZuULqA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"esbuild": "^0.21.3", "esbuild": "^0.21.3",
"postcss": "^8.4.43", "postcss": "^8.4.43",
@@ -5115,6 +5125,7 @@
"resolved": "https://registry.npmmirror.com/vue/-/vue-3.5.18.tgz", "resolved": "https://registry.npmmirror.com/vue/-/vue-3.5.18.tgz",
"integrity": "sha512-7W4Y4ZbMiQ3SEo+m9lnoNpV9xG7QVMLa+/0RFwwiAVkeYoyGXqWE85jabU4pllJNUzqfLShJ5YLptewhCWUgNA==", "integrity": "sha512-7W4Y4ZbMiQ3SEo+m9lnoNpV9xG7QVMLa+/0RFwwiAVkeYoyGXqWE85jabU4pllJNUzqfLShJ5YLptewhCWUgNA==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@vue/compiler-dom": "3.5.18", "@vue/compiler-dom": "3.5.18",
"@vue/compiler-sfc": "3.5.18", "@vue/compiler-sfc": "3.5.18",

View File

@@ -1451,6 +1451,26 @@
</p> </p>
</div> </div>
</div> </div>
<!-- 上游错误处理 -->
<div v-if="form.platform === 'claude-console'">
<label class="mb-3 block text-sm font-semibold text-gray-700 dark:text-gray-300"
>上游错误处理</label
>
<label class="inline-flex cursor-pointer items-center">
<input
v-model="form.disableAutoProtection"
class="mr-2 rounded border-gray-300 text-blue-600 focus:border-blue-500 focus:ring focus:ring-blue-200 dark:border-gray-600 dark:bg-gray-700"
type="checkbox"
/>
<span class="text-sm text-gray-700 dark:text-gray-300">
上游错误不自动暂停调度
</span>
</label>
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
勾选后遇到 401/400/429/529 等上游错误仅记录日志并透传,不自动禁用或限流
</p>
</div>
</div> </div>
<!-- OpenAI-Responses 特定字段 --> <!-- OpenAI-Responses 特定字段 -->
@@ -3070,6 +3090,26 @@
<p class="mt-1 text-xs text-gray-500">账号被限流后暂停调度的时间(分钟)</p> <p class="mt-1 text-xs text-gray-500">账号被限流后暂停调度的时间(分钟)</p>
</div> </div>
</div> </div>
<!-- 上游错误处理(编辑模式)-->
<div v-if="form.platform === 'claude-console'">
<label class="mb-3 block text-sm font-semibold text-gray-700 dark:text-gray-300">
上游错误处理
</label>
<label class="inline-flex cursor-pointer items-center">
<input
v-model="form.disableAutoProtection"
class="mr-2 rounded border-gray-300 text-blue-600 focus:border-blue-500 focus:ring focus:ring-blue-200 dark:border-gray-600 dark:bg-gray-700"
type="checkbox"
/>
<span class="text-sm text-gray-700 dark:text-gray-300">
上游错误不自动暂停调度
</span>
</label>
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
勾选后遇到 401/400/429/529 等上游错误仅记录日志并透传,不自动禁用或限流
</p>
</div>
</div> </div>
<!-- OpenAI-Responses 特定字段(编辑模式)--> <!-- OpenAI-Responses 特定字段(编辑模式)-->
@@ -3912,6 +3952,7 @@ const form = ref({
})(), })(),
userAgent: props.account?.userAgent || '', userAgent: props.account?.userAgent || '',
enableRateLimit: props.account ? props.account.rateLimitDuration > 0 : true, enableRateLimit: props.account ? props.account.rateLimitDuration > 0 : true,
disableAutoProtection: props.account?.disableAutoProtection === true,
// 额度管理字段 // 额度管理字段
dailyQuota: props.account?.dailyQuota || 0, dailyQuota: props.account?.dailyQuota || 0,
dailyUsage: props.account?.dailyUsage || 0, dailyUsage: props.account?.dailyUsage || 0,
@@ -5015,6 +5056,10 @@ const createAccount = async () => {
data.userAgent = form.value.userAgent || null data.userAgent = form.value.userAgent || null
// 如果不启用限流,传递 0 表示不限流 // 如果不启用限流,传递 0 表示不限流
data.rateLimitDuration = form.value.enableRateLimit ? form.value.rateLimitDuration || 60 : 0 data.rateLimitDuration = form.value.enableRateLimit ? form.value.rateLimitDuration || 60 : 0
// 上游错误处理(仅 Claude Console
if (form.value.platform === 'claude-console') {
data.disableAutoProtection = !!form.value.disableAutoProtection
}
// 额度管理字段 // 额度管理字段
data.dailyQuota = form.value.dailyQuota || 0 data.dailyQuota = form.value.dailyQuota || 0
data.quotaResetTime = form.value.quotaResetTime || '00:00' data.quotaResetTime = form.value.quotaResetTime || '00:00'
@@ -5343,6 +5388,8 @@ const updateAccount = async () => {
data.userAgent = form.value.userAgent || null data.userAgent = form.value.userAgent || null
// 如果不启用限流,传递 0 表示不限流 // 如果不启用限流,传递 0 表示不限流
data.rateLimitDuration = form.value.enableRateLimit ? form.value.rateLimitDuration || 60 : 0 data.rateLimitDuration = form.value.enableRateLimit ? form.value.rateLimitDuration || 60 : 0
// 上游错误处理
data.disableAutoProtection = !!form.value.disableAutoProtection
// 额度管理字段 // 额度管理字段
data.dailyQuota = form.value.dailyQuota || 0 data.dailyQuota = form.value.dailyQuota || 0
data.quotaResetTime = form.value.quotaResetTime || '00:00' data.quotaResetTime = form.value.quotaResetTime || '00:00'
@@ -5964,7 +6011,9 @@ watch(
dailyUsage: newAccount.dailyUsage || 0, dailyUsage: newAccount.dailyUsage || 0,
quotaResetTime: newAccount.quotaResetTime || '00:00', quotaResetTime: newAccount.quotaResetTime || '00:00',
// 并发控制字段 // 并发控制字段
maxConcurrentTasks: newAccount.maxConcurrentTasks || 0 maxConcurrentTasks: newAccount.maxConcurrentTasks || 0,
// 上游错误处理
disableAutoProtection: newAccount.disableAutoProtection === true
} }
// 如果是Claude Console账户加载实时使用情况 // 如果是Claude Console账户加载实时使用情况

View File

@@ -0,0 +1,211 @@
<template>
<el-dialog
:append-to-body="true"
class="record-detail-modal"
:close-on-click-modal="false"
:destroy-on-close="true"
:model-value="show"
:show-close="false"
top="10vh"
width="720px"
@close="emitClose"
>
<template #header>
<div class="flex items-center justify-between">
<div>
<p class="text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">
请求详情
</p>
<p class="text-lg font-bold text-gray-900 dark:text-gray-100">
{{ record?.model || '未知模型' }}
</p>
</div>
<button
aria-label="关闭"
class="rounded-full p-2 text-gray-500 transition hover:bg-gray-100 hover:text-gray-700 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100"
@click="emitClose"
>
<i class="fas fa-times" />
</button>
</div>
</template>
<div class="space-y-4">
<div class="grid gap-3 md:grid-cols-2">
<div
class="rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-gray-800 dark:bg-gray-900"
>
<h4 class="mb-3 text-sm font-semibold text-gray-800 dark:text-gray-200">基本信息</h4>
<ul class="space-y-2 text-sm text-gray-700 dark:text-gray-300">
<li class="flex items-center justify-between">
<span class="text-gray-500 dark:text-gray-400">时间</span>
<span class="font-medium">{{ formattedTime }}</span>
</li>
<li class="flex items-center justify-between">
<span class="text-gray-500 dark:text-gray-400">模型</span>
<span class="font-medium">{{ record?.model || '未知模型' }}</span>
</li>
<li class="flex items-center justify-between">
<span class="text-gray-500 dark:text-gray-400">账户</span>
<span class="font-medium">{{ record?.accountName || '未知账户' }}</span>
</li>
<li class="flex items-center justify-between">
<span class="text-gray-500 dark:text-gray-400">渠道</span>
<span class="font-medium">{{ record?.accountTypeName || '未知渠道' }}</span>
</li>
</ul>
</div>
<div
class="rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-gray-800 dark:bg-gray-900"
>
<h4 class="mb-3 text-sm font-semibold text-gray-800 dark:text-gray-200">Token 使用</h4>
<ul class="space-y-2 text-sm text-gray-700 dark:text-gray-300">
<li class="flex items-center justify-between">
<span class="text-gray-500 dark:text-gray-400">输入 Token</span>
<span class="font-semibold text-blue-600 dark:text-blue-400">
{{ formatNumber(record?.inputTokens) }}
</span>
</li>
<li class="flex items-center justify-between">
<span class="text-gray-500 dark:text-gray-400">输出 Token</span>
<span class="font-semibold text-green-600 dark:text-green-400">
{{ formatNumber(record?.outputTokens) }}
</span>
</li>
<li class="flex items-center justify-between">
<span class="text-gray-500 dark:text-gray-400">缓存创建</span>
<span class="font-semibold text-purple-600 dark:text-purple-400">
{{ formatNumber(record?.cacheCreateTokens) }}
</span>
</li>
<li class="flex items-center justify-between">
<span class="text-gray-500 dark:text-gray-400">缓存读取</span>
<span class="font-semibold text-orange-600 dark:text-orange-400">
{{ formatNumber(record?.cacheReadTokens) }}
</span>
</li>
<li class="flex items-center justify-between">
<span class="text-gray-500 dark:text-gray-400">总计</span>
<span class="font-semibold text-gray-900 dark:text-gray-100">
{{ formatNumber(record?.totalTokens) }}
</span>
</li>
</ul>
</div>
</div>
<div
class="rounded-lg border border-gray-200 bg-white p-4 dark:border-gray-800 dark:bg-gray-900"
>
<h4 class="mb-3 text-sm font-semibold text-gray-800 dark:text-gray-200">费用详情</h4>
<div class="grid gap-3 sm:grid-cols-2">
<div
class="flex items-center justify-between rounded-md bg-gray-50 px-3 py-2 dark:bg-gray-800"
>
<span class="text-sm text-gray-500 dark:text-gray-400">输入费用</span>
<span class="text-sm font-semibold text-gray-900 dark:text-gray-100">
{{ formattedCosts.input }}
</span>
</div>
<div
class="flex items-center justify-between rounded-md bg-gray-50 px-3 py-2 dark:bg-gray-800"
>
<span class="text-sm text-gray-500 dark:text-gray-400">输出费用</span>
<span class="text-sm font-semibold text-gray-900 dark:text-gray-100">
{{ formattedCosts.output }}
</span>
</div>
<div
class="flex items-center justify-between rounded-md bg-gray-50 px-3 py-2 dark:bg-gray-800"
>
<span class="text-sm text-gray-500 dark:text-gray-400">缓存创建</span>
<span class="text-sm font-semibold text-gray-900 dark:text-gray-100">
{{ formattedCosts.cacheCreate }}
</span>
</div>
<div
class="flex items-center justify-between rounded-md bg-gray-50 px-3 py-2 dark:bg-gray-800"
>
<span class="text-sm text-gray-500 dark:text-gray-400">缓存读取</span>
<span class="text-sm font-semibold text-gray-900 dark:text-gray-100">
{{ formattedCosts.cacheRead }}
</span>
</div>
</div>
<div
class="mt-4 flex items-center justify-between rounded-md border border-gray-200 bg-gray-50 px-4 py-3 dark:border-gray-800 dark:bg-gray-800"
>
<span class="text-sm font-semibold text-gray-700 dark:text-gray-200">总费用</span>
<div class="text-base font-bold text-yellow-600 dark:text-yellow-400">
{{ record?.costFormatted || formattedCosts.total }}
</div>
</div>
</div>
</div>
<template #footer>
<div class="flex justify-end">
<el-button type="primary" @click="emitClose">关闭</el-button>
</div>
</template>
</el-dialog>
</template>
<script setup>
import { computed } from 'vue'
import dayjs from 'dayjs'
import { formatNumber } from '@/utils/format'
const props = defineProps({
show: {
type: Boolean,
default: false
},
record: {
type: Object,
default: () => ({})
}
})
const emit = defineEmits(['close'])
const emitClose = () => emit('close')
const formattedTime = computed(() => {
if (!props.record?.timestamp) return '未知时间'
return dayjs(props.record.timestamp).format('YYYY-MM-DD HH:mm:ss')
})
const formattedCosts = computed(() => {
const breakdown = props.record?.costBreakdown || {}
const formatValue = (value) => {
const num = typeof value === 'number' ? value : 0
if (num >= 1) return `$${num.toFixed(2)}`
if (num >= 0.001) return `$${num.toFixed(4)}`
return `$${num.toFixed(6)}`
}
return {
input: formatValue(breakdown.input),
output: formatValue(breakdown.output),
cacheCreate: formatValue(breakdown.cacheCreate),
cacheRead: formatValue(breakdown.cacheRead),
total: formatValue(breakdown.total)
}
})
</script>
<style scoped>
.record-detail-modal :deep(.el-dialog__header) {
margin: 0;
padding: 16px 16px 0;
}
.record-detail-modal :deep(.el-dialog__body) {
padding: 12px 16px 4px;
}
.record-detail-modal :deep(.el-dialog__footer) {
padding: 8px 16px 16px;
}
</style>

View File

@@ -231,6 +231,9 @@
<!-- 底部按钮 --> <!-- 底部按钮 -->
<div class="mt-4 flex justify-end gap-2 sm:mt-6 sm:gap-3"> <div class="mt-4 flex justify-end gap-2 sm:mt-6 sm:gap-3">
<button class="btn btn-primary px-4 py-2 text-sm" type="button" @click="openTimeline">
查看请求时间线
</button>
<button class="btn btn-secondary px-4 py-2 text-sm" type="button" @click="close"> <button class="btn btn-secondary px-4 py-2 text-sm" type="button" @click="close">
关闭 关闭
</button> </button>
@@ -256,7 +259,7 @@ const props = defineProps({
} }
}) })
const emit = defineEmits(['close']) const emit = defineEmits(['close', 'open-timeline'])
// 计算属性 // 计算属性
const totalRequests = computed(() => props.apiKey.usage?.total?.requests || 0) const totalRequests = computed(() => props.apiKey.usage?.total?.requests || 0)
@@ -320,6 +323,10 @@ const formatTokenCount = (count) => {
const close = () => { const close = () => {
emit('close') emit('close')
} }
const openTimeline = () => {
emit('open-timeline', props.apiKey?.id)
}
</script> </script>
<style scoped> <style scoped>

View File

@@ -11,6 +11,7 @@ const UserManagementView = () => import('@/views/UserManagementView.vue')
const MainLayout = () => import('@/components/layout/MainLayout.vue') const MainLayout = () => import('@/components/layout/MainLayout.vue')
const DashboardView = () => import('@/views/DashboardView.vue') const DashboardView = () => import('@/views/DashboardView.vue')
const ApiKeysView = () => import('@/views/ApiKeysView.vue') const ApiKeysView = () => import('@/views/ApiKeysView.vue')
const ApiKeyUsageRecordsView = () => import('@/views/ApiKeyUsageRecordsView.vue')
const AccountsView = () => import('@/views/AccountsView.vue') const AccountsView = () => import('@/views/AccountsView.vue')
const TutorialView = () => import('@/views/TutorialView.vue') const TutorialView = () => import('@/views/TutorialView.vue')
const SettingsView = () => import('@/views/SettingsView.vue') const SettingsView = () => import('@/views/SettingsView.vue')
@@ -85,6 +86,18 @@ const routes = [
} }
] ]
}, },
{
path: '/api-keys/:keyId/usage-records',
component: MainLayout,
meta: { requiresAuth: true },
children: [
{
path: '',
name: 'ApiKeyUsageRecords',
component: ApiKeyUsageRecordsView
}
]
},
{ {
path: '/accounts', path: '/accounts',
component: MainLayout, component: MainLayout,

View File

@@ -67,22 +67,72 @@ export const useDashboardStore = defineStore('dashboard', () => {
groupLabel: 'Claude账户' groupLabel: 'Claude账户'
}) })
// 日期筛选 // 本地偏好
const dateFilter = ref({ const STORAGE_KEYS = {
type: 'preset', // preset 或 custom preset: 'dashboard:date:preset',
preset: '7days', // today, 7days, 30days granularity: 'dashboard:trend:granularity'
customStart: '', }
customEnd: '', const defaultPreset = 'today'
customRange: null, const defaultGranularity = 'day'
presetOptions: [
const getPresetOptions = (granularity) =>
granularity === 'hour'
? [
{ value: 'last24h', label: '近24小时', hours: 24 },
{ value: 'yesterday', label: '昨天', hours: 24 },
{ value: 'dayBefore', label: '前天', hours: 24 }
]
: [
{ value: 'today', label: '今日', days: 1 }, { value: 'today', label: '今日', days: 1 },
{ value: '7days', label: '7天', days: 7 }, { value: '7days', label: '7天', days: 7 },
{ value: '30days', label: '30天', days: 30 } { value: '30days', label: '30天', days: 30 }
] ]
const readFromStorage = (key, fallback) => {
try {
const value = localStorage.getItem(key)
return value || fallback
} catch (error) {
return fallback
}
}
const saveToStorage = (key, value) => {
try {
localStorage.setItem(key, value)
} catch (error) {
// 忽略存储错误,避免影响渲染
}
}
const normalizePresetForGranularity = (preset, granularity) => {
const options = getPresetOptions(granularity)
const hasPreset = options.some((opt) => opt.value === preset)
if (hasPreset) return preset
return granularity === 'hour' ? 'last24h' : defaultPreset
}
const storedGranularity = readFromStorage(STORAGE_KEYS.granularity, defaultGranularity)
const initialGranularity = ['day', 'hour'].includes(storedGranularity)
? storedGranularity
: defaultGranularity
const initialPreset = normalizePresetForGranularity(
readFromStorage(STORAGE_KEYS.preset, defaultPreset),
initialGranularity
)
// 日期筛选
const dateFilter = ref({
type: 'preset', // preset 或 custom
preset: initialPreset, // today, 7days, 30days
customStart: '',
customEnd: '',
customRange: null,
presetOptions: getPresetOptions(initialGranularity)
}) })
// 趋势图粒度 // 趋势图粒度
const trendGranularity = ref('day') // 'day' 或 'hour' const trendGranularity = ref(initialGranularity) // 'day' 或 'hour'
const apiKeysTrendMetric = ref('requests') // 'requests' 或 'tokens' const apiKeysTrendMetric = ref('requests') // 'requests' 或 'tokens'
const accountUsageGroup = ref('claude') // claude | openai | gemini const accountUsageGroup = ref('claude') // claude | openai | gemini
@@ -138,6 +188,21 @@ export const useDashboardStore = defineStore('dashboard', () => {
} }
} }
const persistDatePreferences = (
preset = dateFilter.value.preset,
granularity = trendGranularity.value
) => {
saveToStorage(STORAGE_KEYS.preset, preset)
saveToStorage(STORAGE_KEYS.granularity, granularity)
}
const getEffectiveGranularity = () =>
dateFilter.value.type === 'preset' &&
dateFilter.value.preset === 'today' &&
trendGranularity.value === 'day'
? 'hour'
: trendGranularity.value
// 方法 // 方法
async function loadDashboardData(timeRange = null) { async function loadDashboardData(timeRange = null) {
loading.value = true loading.value = true
@@ -232,7 +297,7 @@ export const useDashboardStore = defineStore('dashboard', () => {
} }
} }
async function loadUsageTrend(days = 7, granularity = 'day') { async function loadUsageTrend(days = 7, granularity = getEffectiveGranularity()) {
try { try {
let url = '/admin/usage-trend?' let url = '/admin/usage-trend?'
@@ -241,26 +306,9 @@ export const useDashboardStore = defineStore('dashboard', () => {
url += `granularity=hour` url += `granularity=hour`
if (dateFilter.value.customRange && dateFilter.value.customRange.length === 2) { if (dateFilter.value.customRange && dateFilter.value.customRange.length === 2) {
// 使用自定义时间范围 - 需要将系统时区时间转换为UTC // 使用自定义时间范围 - 直接按系统时区字符串传递,避免额外时区偏移导致窗口错位
const convertToUTC = (systemTzTimeStr) => { url += `&startDate=${encodeURIComponent(dateFilter.value.customRange[0])}`
// 固定使用UTC+8因为后端系统时区是UTC+8 url += `&endDate=${encodeURIComponent(dateFilter.value.customRange[1])}`
const systemTz = 8
// 解析系统时区时间字符串
const [datePart, timePart] = systemTzTimeStr.split(' ')
const [year, month, day] = datePart.split('-').map(Number)
const [hours, minutes, seconds] = timePart.split(':').map(Number)
// 创建UTC时间使其在系统时区显示为用户选择的时间
// 例如:用户选择 UTC+8 的 2025-07-25 00:00:00
// 对应的UTC时间是 2025-07-24 16:00:00
const utcDate = new Date(
Date.UTC(year, month - 1, day, hours - systemTz, minutes, seconds)
)
return utcDate.toISOString()
}
url += `&startDate=${encodeURIComponent(convertToUTC(dateFilter.value.customRange[0]))}`
url += `&endDate=${encodeURIComponent(convertToUTC(dateFilter.value.customRange[1]))}`
} else { } else {
// 使用预设计算时间范围与loadApiKeysTrend保持一致 // 使用预设计算时间范围与loadApiKeysTrend保持一致
const now = new Date() const now = new Date()
@@ -268,6 +316,12 @@ export const useDashboardStore = defineStore('dashboard', () => {
if (dateFilter.value.type === 'preset') { if (dateFilter.value.type === 'preset') {
switch (dateFilter.value.preset) { switch (dateFilter.value.preset) {
case 'today': {
// 今日使用系统时区的当日0点-23:59
startTime = getSystemTimezoneDay(now, true)
endTime = getSystemTimezoneDay(now, false)
break
}
case 'last24h': { case 'last24h': {
// 近24小时从当前时间往前推24小时 // 近24小时从当前时间往前推24小时
endTime = new Date(now) endTime = new Date(now)
@@ -318,34 +372,28 @@ export const useDashboardStore = defineStore('dashboard', () => {
} }
} }
async function loadModelStats(period = 'daily') { async function loadModelStats(period = 'daily', granularity = null) {
const currentGranularity = granularity || getEffectiveGranularity()
try { try {
let url = `/admin/model-stats?period=${period}` let url = `/admin/model-stats?period=${period}`
// 如果是自定义时间范围或小时粒度,传递具体的时间参数 // 如果是自定义时间范围或小时粒度,传递具体的时间参数
if (dateFilter.value.type === 'custom' || trendGranularity.value === 'hour') { if (dateFilter.value.type === 'custom' || currentGranularity === 'hour') {
if (dateFilter.value.customRange && dateFilter.value.customRange.length === 2) { if (dateFilter.value.customRange && dateFilter.value.customRange.length === 2) {
// 系统时区时间转换为UTC // 系统时区字符串直传,避免额外时区转换
const convertToUTC = (systemTzTimeStr) => { url += `&startDate=${encodeURIComponent(dateFilter.value.customRange[0])}`
const systemTz = 8 url += `&endDate=${encodeURIComponent(dateFilter.value.customRange[1])}`
const [datePart, timePart] = systemTzTimeStr.split(' ') } else if (currentGranularity === 'hour' && dateFilter.value.type === 'preset') {
const [year, month, day] = datePart.split('-').map(Number)
const [hours, minutes, seconds] = timePart.split(':').map(Number)
const utcDate = new Date(
Date.UTC(year, month - 1, day, hours - systemTz, minutes, seconds)
)
return utcDate.toISOString()
}
url += `&startDate=${encodeURIComponent(convertToUTC(dateFilter.value.customRange[0]))}`
url += `&endDate=${encodeURIComponent(convertToUTC(dateFilter.value.customRange[1]))}`
} else if (trendGranularity.value === 'hour' && dateFilter.value.type === 'preset') {
// 小时粒度的预设时间范围 // 小时粒度的预设时间范围
const now = new Date() const now = new Date()
let startTime, endTime let startTime, endTime
switch (dateFilter.value.preset) { switch (dateFilter.value.preset) {
case 'today': {
startTime = getSystemTimezoneDay(now, true)
endTime = getSystemTimezoneDay(now, false)
break
}
case 'last24h': { case 'last24h': {
endTime = new Date(now) endTime = new Date(now)
startTime = new Date(now.getTime() - 24 * 60 * 60 * 1000) startTime = new Date(now.getTime() - 24 * 60 * 60 * 1000)
@@ -374,7 +422,7 @@ export const useDashboardStore = defineStore('dashboard', () => {
url += `&startDate=${encodeURIComponent(startTime.toISOString())}` url += `&startDate=${encodeURIComponent(startTime.toISOString())}`
url += `&endDate=${encodeURIComponent(endTime.toISOString())}` url += `&endDate=${encodeURIComponent(endTime.toISOString())}`
} }
} else if (dateFilter.value.type === 'preset' && trendGranularity.value === 'day') { } else if (dateFilter.value.type === 'preset' && currentGranularity === 'day') {
// 天粒度的预设时间范围需要传递startDate和endDate参数 // 天粒度的预设时间范围需要传递startDate和endDate参数
const now = new Date() const now = new Date()
let startDate, endDate let startDate, endDate
@@ -409,36 +457,20 @@ export const useDashboardStore = defineStore('dashboard', () => {
} }
} }
async function loadApiKeysTrend(metric = 'requests') { async function loadApiKeysTrend(metric = 'requests', granularity = null) {
const currentGranularity = granularity || getEffectiveGranularity()
try { try {
let url = '/admin/api-keys-usage-trend?' let url = '/admin/api-keys-usage-trend?'
let days = 7 let days = 7
if (trendGranularity.value === 'hour') { if (currentGranularity === 'hour') {
// 小时粒度,计算时间范围 // 小时粒度,计算时间范围
url += `granularity=hour` url += `granularity=hour`
if (dateFilter.value.customRange && dateFilter.value.customRange.length === 2) { if (dateFilter.value.customRange && dateFilter.value.customRange.length === 2) {
// 使用自定义时间范围 - 需要将系统时区时间转换为UTC // 使用自定义时间范围 - 系统时区字符串直传
const convertToUTC = (systemTzTimeStr) => { url += `&startDate=${encodeURIComponent(dateFilter.value.customRange[0])}`
// 固定使用UTC+8因为后端系统时区是UTC+8 url += `&endDate=${encodeURIComponent(dateFilter.value.customRange[1])}`
const systemTz = 8
// 解析系统时区时间字符串
const [datePart, timePart] = systemTzTimeStr.split(' ')
const [year, month, day] = datePart.split('-').map(Number)
const [hours, minutes, seconds] = timePart.split(':').map(Number)
// 创建UTC时间使其在系统时区显示为用户选择的时间
// 例如:用户选择 UTC+8 的 2025-07-25 00:00:00
// 对应的UTC时间是 2025-07-24 16:00:00
const utcDate = new Date(
Date.UTC(year, month - 1, day, hours - systemTz, minutes, seconds)
)
return utcDate.toISOString()
}
url += `&startDate=${encodeURIComponent(convertToUTC(dateFilter.value.customRange[0]))}`
url += `&endDate=${encodeURIComponent(convertToUTC(dateFilter.value.customRange[1]))}`
} else { } else {
// 使用预设计算时间范围与setDateFilterPreset保持一致 // 使用预设计算时间范围与setDateFilterPreset保持一致
const now = new Date() const now = new Date()
@@ -446,6 +478,11 @@ export const useDashboardStore = defineStore('dashboard', () => {
if (dateFilter.value.type === 'preset') { if (dateFilter.value.type === 'preset') {
switch (dateFilter.value.preset) { switch (dateFilter.value.preset) {
case 'today': {
startTime = getSystemTimezoneDay(now, true)
endTime = getSystemTimezoneDay(now, false)
break
}
case 'last24h': { case 'last24h': {
// 近24小时从当前时间往前推24小时 // 近24小时从当前时间往前推24小时
endTime = new Date(now) endTime = new Date(now)
@@ -511,29 +548,18 @@ export const useDashboardStore = defineStore('dashboard', () => {
} }
} }
async function loadAccountUsageTrend(group = accountUsageGroup.value) { async function loadAccountUsageTrend(group = accountUsageGroup.value, granularity = null) {
const currentGranularity = granularity || getEffectiveGranularity()
try { try {
let url = '/admin/account-usage-trend?' let url = '/admin/account-usage-trend?'
let days = 7 let days = 7
if (trendGranularity.value === 'hour') { if (currentGranularity === 'hour') {
url += `granularity=hour` url += `granularity=hour`
if (dateFilter.value.customRange && dateFilter.value.customRange.length === 2) { if (dateFilter.value.customRange && dateFilter.value.customRange.length === 2) {
const convertToUTC = (systemTzTimeStr) => { url += `&startDate=${encodeURIComponent(dateFilter.value.customRange[0])}`
const systemTz = 8 url += `&endDate=${encodeURIComponent(dateFilter.value.customRange[1])}`
const [datePart, timePart] = systemTzTimeStr.split(' ')
const [year, month, day] = datePart.split('-').map(Number)
const [hours, minutes, seconds] = timePart.split(':').map(Number)
const utcDate = new Date(
Date.UTC(year, month - 1, day, hours - systemTz, minutes, seconds)
)
return utcDate.toISOString()
}
url += `&startDate=${encodeURIComponent(convertToUTC(dateFilter.value.customRange[0]))}`
url += `&endDate=${encodeURIComponent(convertToUTC(dateFilter.value.customRange[1]))}`
} else { } else {
const now = new Date() const now = new Date()
let startTime let startTime
@@ -541,6 +567,11 @@ export const useDashboardStore = defineStore('dashboard', () => {
if (dateFilter.value.type === 'preset') { if (dateFilter.value.type === 'preset') {
switch (dateFilter.value.preset) { switch (dateFilter.value.preset) {
case 'today': {
startTime = getSystemTimezoneDay(now, true)
endTime = getSystemTimezoneDay(now, false)
break
}
case 'last24h': { case 'last24h': {
endTime = new Date(now) endTime = new Date(now)
startTime = new Date(now.getTime() - 24 * 60 * 60 * 1000) startTime = new Date(now.getTime() - 24 * 60 * 60 * 1000)
@@ -603,111 +634,88 @@ export const useDashboardStore = defineStore('dashboard', () => {
} }
// 日期筛选相关方法 // 日期筛选相关方法
function setDateFilterPreset(preset) { function setDateFilterPreset(preset, options = {}) {
dateFilter.value.type = 'preset' const { silent = false, skipSave = false } = options
dateFilter.value.preset = preset const normalizedPreset = normalizePresetForGranularity(preset, trendGranularity.value)
// 根据预设计算并设置具体的日期范围 dateFilter.value.type = 'preset'
const option = dateFilter.value.presetOptions.find((opt) => opt.value === preset) dateFilter.value.preset = normalizedPreset
if (option) {
const option = dateFilter.value.presetOptions.find((opt) => opt.value === normalizedPreset)
const now = new Date() const now = new Date()
let startDate, endDate let startDate
let endDate
if (trendGranularity.value === 'hour') { if (trendGranularity.value === 'hour') {
// 小时粒度的预设 switch (normalizedPreset) {
switch (preset) { case 'today': {
startDate = getSystemTimezoneDay(now, true)
endDate = getSystemTimezoneDay(now, false)
break
}
case 'last24h': { case 'last24h': {
// 近24小时从当前时间往前推24小时
endDate = new Date(now) endDate = new Date(now)
startDate = new Date(now.getTime() - 24 * 60 * 60 * 1000) startDate = new Date(now.getTime() - 24 * 60 * 60 * 1000)
break break
} }
case 'yesterday': { case 'yesterday': {
// 昨天:获取本地时间的昨天
const yesterday = new Date() const yesterday = new Date()
yesterday.setDate(yesterday.getDate() - 1) yesterday.setDate(yesterday.getDate() - 1)
// 转换为系统时区的昨天0点和23:59
startDate = getSystemTimezoneDay(yesterday, true) startDate = getSystemTimezoneDay(yesterday, true)
endDate = getSystemTimezoneDay(yesterday, false) endDate = getSystemTimezoneDay(yesterday, false)
break break
} }
case 'dayBefore': { case 'dayBefore': {
// 前天:获取本地时间的前天
const dayBefore = new Date() const dayBefore = new Date()
dayBefore.setDate(dayBefore.getDate() - 2) dayBefore.setDate(dayBefore.getDate() - 2)
// 转换为系统时区的前天0点和23:59
startDate = getSystemTimezoneDay(dayBefore, true) startDate = getSystemTimezoneDay(dayBefore, true)
endDate = getSystemTimezoneDay(dayBefore, false) endDate = getSystemTimezoneDay(dayBefore, false)
break break
} }
default: {
endDate = new Date(now)
startDate = new Date(now.getTime() - 24 * 60 * 60 * 1000)
}
} }
} else { } else {
// 天粒度的预设
startDate = new Date(now) startDate = new Date(now)
endDate = new Date(now) endDate = new Date(now)
if (preset === 'today') { if (normalizedPreset === 'today') {
// 今日:从凌晨开始
startDate.setHours(0, 0, 0, 0) startDate.setHours(0, 0, 0, 0)
endDate.setHours(23, 59, 59, 999) endDate.setHours(23, 59, 59, 999)
} else { } else if (option?.days) {
// 其他预设:按天数计算
startDate.setDate(now.getDate() - (option.days - 1)) startDate.setDate(now.getDate() - (option.days - 1))
startDate.setHours(0, 0, 0, 0) startDate.setHours(0, 0, 0, 0)
endDate.setHours(23, 59, 59, 999) endDate.setHours(23, 59, 59, 999)
} }
} }
dateFilter.value.customStart = startDate.toISOString().split('T')[0]
dateFilter.value.customEnd = endDate.toISOString().split('T')[0]
// 设置 customRange 为 Element Plus 需要的格式
// 对于小时粒度的昨天/前天,需要特殊处理显示
if (trendGranularity.value === 'hour' && (preset === 'yesterday' || preset === 'dayBefore')) {
// 获取本地日期
const targetDate = new Date()
if (preset === 'yesterday') {
targetDate.setDate(targetDate.getDate() - 1)
} else {
targetDate.setDate(targetDate.getDate() - 2)
}
// 显示系统时区的完整一天
const year = targetDate.getFullYear()
const month = String(targetDate.getMonth() + 1).padStart(2, '0')
const day = String(targetDate.getDate()).padStart(2, '0')
dateFilter.value.customRange = [
`${year}-${month}-${day} 00:00:00`,
`${year}-${month}-${day} 23:59:59`
]
} else {
// 其他情况近24小时或天粒度
const formatDateForDisplay = (date) => { const formatDateForDisplay = (date) => {
// 固定使用UTC+8来显示时间 // 使用本地时间直接格式化,避免多余的时区偏移导致日期错位
const systemTz = 8 const localTime = new Date(date)
const tzOffset = systemTz * 60 * 60 * 1000 const year = localTime.getFullYear()
const localTime = new Date(date.getTime() + tzOffset) const month = String(localTime.getMonth() + 1).padStart(2, '0')
const day = String(localTime.getDate()).padStart(2, '0')
const year = localTime.getUTCFullYear() const hours = String(localTime.getHours()).padStart(2, '0')
const month = String(localTime.getUTCMonth() + 1).padStart(2, '0') const minutes = String(localTime.getMinutes()).padStart(2, '0')
const day = String(localTime.getUTCDate()).padStart(2, '0') const seconds = String(localTime.getSeconds()).padStart(2, '0')
const hours = String(localTime.getUTCHours()).padStart(2, '0')
const minutes = String(localTime.getUTCMinutes()).padStart(2, '0')
const seconds = String(localTime.getUTCSeconds()).padStart(2, '0')
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}` return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
} }
dateFilter.value.customRange = [ dateFilter.value.customStart = startDate ? startDate.toISOString().split('T')[0] : ''
formatDateForDisplay(startDate), dateFilter.value.customEnd = endDate ? endDate.toISOString().split('T')[0] : ''
formatDateForDisplay(endDate) dateFilter.value.customRange =
] startDate && endDate ? [formatDateForDisplay(startDate), formatDateForDisplay(endDate)] : null
}
if (!skipSave) {
persistDatePreferences(dateFilter.value.preset, trendGranularity.value)
} }
// 触发数据刷新 if (!silent) {
refreshChartsData() refreshChartsData()
} }
}
function onCustomDateRangeChange(value) { function onCustomDateRangeChange(value) {
if (value && value.length === 2) { if (value && value.length === 2) {
@@ -751,20 +759,17 @@ export const useDashboardStore = defineStore('dashboard', () => {
refreshChartsData() refreshChartsData()
} else if (value === null) { } else if (value === null) {
// 清空时恢复默认 // 清空时恢复默认
setDateFilterPreset(trendGranularity.value === 'hour' ? 'last24h' : '7days') setDateFilterPreset(trendGranularity.value === 'hour' ? 'last24h' : defaultPreset)
} }
} }
function setTrendGranularity(granularity) { function setTrendGranularity(granularity, options = {}) {
const { silent = false, skipSave = false, presetOverride } = options
trendGranularity.value = granularity trendGranularity.value = granularity
// 根据粒度更新预设选项 // 根据粒度更新预设选项
if (granularity === 'hour') { if (granularity === 'hour') {
dateFilter.value.presetOptions = [ dateFilter.value.presetOptions = getPresetOptions('hour')
{ value: 'last24h', label: '近24小时', hours: 24 },
{ value: 'yesterday', label: '昨天', hours: 24 },
{ value: 'dayBefore', label: '前天', hours: 24 }
]
// 检查当前自定义日期范围是否超过24小时 // 检查当前自定义日期范围是否超过24小时
if ( if (
@@ -777,46 +782,53 @@ export const useDashboardStore = defineStore('dashboard', () => {
const hoursDiff = (end - start) / (1000 * 60 * 60) const hoursDiff = (end - start) / (1000 * 60 * 60)
if (hoursDiff > 24) { if (hoursDiff > 24) {
showToast('小时粒度下日期范围不能超过24小时已切换到近24小时', 'warning') showToast('小时粒度下日期范围不能超过24小时已切换到近24小时', 'warning')
setDateFilterPreset('last24h') setDateFilterPreset('last24h', { silent, skipSave })
return return
} }
} }
// 如果当前是天粒度的预设,切换到小时粒度的默认预设
if (['today', '7days', '30days'].includes(dateFilter.value.preset)) {
setDateFilterPreset('last24h')
return
}
} else { } else {
// 天粒度 // 天粒度
dateFilter.value.presetOptions = [ dateFilter.value.presetOptions = getPresetOptions('day')
{ value: 'today', label: '今日', days: 1 }, }
{ value: '7days', label: '7天', days: 7 },
{ value: '30days', label: '30天', days: 30 }
]
// 如果当前是小时粒度的预设,切换到天粒度的默认预设 if (dateFilter.value.type === 'custom') {
if (['last24h', 'yesterday', 'dayBefore'].includes(dateFilter.value.preset)) { if (!skipSave) {
setDateFilterPreset('7days') persistDatePreferences(dateFilter.value.preset || defaultPreset, trendGranularity.value)
}
if (!silent) {
refreshChartsData()
}
return return
} }
const nextPreset =
presetOverride ||
normalizePresetForGranularity(dateFilter.value.preset, trendGranularity.value)
setDateFilterPreset(nextPreset, { silent: true, skipSave: true })
if (!skipSave) {
persistDatePreferences(dateFilter.value.preset, trendGranularity.value)
} }
// 触发数据刷新 if (!silent) {
refreshChartsData() refreshChartsData()
} }
}
async function refreshChartsData() { async function refreshChartsData() {
// 根据当前筛选条件刷新数据 // 根据当前筛选条件刷新数据
let days let days
let modelPeriod = 'monthly' let modelPeriod = 'monthly'
const effectiveGranularity = getEffectiveGranularity()
if (dateFilter.value.type === 'preset') { if (dateFilter.value.type === 'preset') {
const option = dateFilter.value.presetOptions.find( const option = dateFilter.value.presetOptions.find(
(opt) => opt.value === dateFilter.value.preset (opt) => opt.value === dateFilter.value.preset
) )
if (trendGranularity.value === 'hour') { if (effectiveGranularity === 'hour') {
// 小时粒度 // 小时粒度
days = 1 // 小时粒度默认查看1天的数据 days = 1 // 小时粒度默认查看1天的数据
modelPeriod = 'daily' // 小时粒度使用日统计 modelPeriod = 'daily' // 小时粒度使用日统计
@@ -832,7 +844,7 @@ export const useDashboardStore = defineStore('dashboard', () => {
} }
} else { } else {
// 自定义日期范围 // 自定义日期范围
if (trendGranularity.value === 'hour') { if (effectiveGranularity === 'hour') {
// 小时粒度下的自定义范围,计算小时数 // 小时粒度下的自定义范围,计算小时数
const start = new Date(dateFilter.value.customRange[0]) const start = new Date(dateFilter.value.customRange[0])
const end = new Date(dateFilter.value.customRange[1]) const end = new Date(dateFilter.value.customRange[1])
@@ -845,16 +857,16 @@ export const useDashboardStore = defineStore('dashboard', () => {
} }
await Promise.all([ await Promise.all([
loadUsageTrend(days, trendGranularity.value), loadUsageTrend(days, effectiveGranularity),
loadModelStats(modelPeriod), loadModelStats(modelPeriod, effectiveGranularity),
loadApiKeysTrend(apiKeysTrendMetric.value), loadApiKeysTrend(apiKeysTrendMetric.value, effectiveGranularity),
loadAccountUsageTrend(accountUsageGroup.value) loadAccountUsageTrend(accountUsageGroup.value, effectiveGranularity)
]) ])
} }
function setAccountUsageGroup(group) { function setAccountUsageGroup(group) {
accountUsageGroup.value = group accountUsageGroup.value = group
return loadAccountUsageTrend(group) return loadAccountUsageTrend(group, getEffectiveGranularity())
} }
function calculateDaysBetween(start, end) { function calculateDaysBetween(start, end) {
@@ -870,6 +882,10 @@ export const useDashboardStore = defineStore('dashboard', () => {
return date > new Date() return date > new Date()
} }
// 初始化日期筛选:同步本地偏好并填充范围
setDateFilterPreset(dateFilter.value.preset, { silent: true, skipSave: true })
persistDatePreferences(dateFilter.value.preset, trendGranularity.value)
return { return {
// 状态 // 状态
loading, loading,

View File

@@ -19,12 +19,12 @@
class="absolute -inset-0.5 rounded-lg bg-gradient-to-r from-indigo-500 to-blue-500 opacity-0 blur transition duration-300 group-hover:opacity-20" class="absolute -inset-0.5 rounded-lg bg-gradient-to-r from-indigo-500 to-blue-500 opacity-0 blur transition duration-300 group-hover:opacity-20"
></div> ></div>
<CustomDropdown <CustomDropdown
v-model="accountSortBy" v-model="accountsSortBy"
icon="fa-sort-amount-down" :icon="accountsSortOrder === 'asc' ? 'fa-sort-amount-up' : 'fa-sort-amount-down'"
icon-color="text-indigo-500" icon-color="text-indigo-500"
:options="sortOptions" :options="sortOptions"
placeholder="选择排序" placeholder="选择排序"
@change="sortAccounts()" @change="handleDropdownSort"
/> />
</div> </div>
@@ -1873,8 +1873,7 @@ const { showConfirmModal, confirmOptions, showConfirm, handleConfirm, handleCanc
// 数据状态 // 数据状态
const accounts = ref([]) const accounts = ref([])
const accountsLoading = ref(false) const accountsLoading = ref(false)
const accountSortBy = ref('name') const accountsSortBy = ref('name')
const accountsSortBy = ref('')
const accountsSortOrder = ref('asc') const accountsSortOrder = ref('asc')
const apiKeys = ref([]) // 保留用于其他功能(如删除账户时显示绑定信息) const apiKeys = ref([]) // 保留用于其他功能(如删除账户时显示绑定信息)
const bindingCounts = ref({}) // 轻量级绑定计数,用于显示"绑定: X 个API Key" const bindingCounts = ref({}) // 轻量级绑定计数,用于显示"绑定: X 个API Key"
@@ -2735,7 +2734,10 @@ const loadClaudeUsage = async () => {
} }
} }
// 排序账户 // 记录上一次的排序字段,用于判断下拉选择是否是同一字段被再次选择
let lastDropdownSortField = 'name'
// 排序账户(表头点击使用)
const sortAccounts = (field) => { const sortAccounts = (field) => {
if (field) { if (field) {
if (accountsSortBy.value === field) { if (accountsSortBy.value === field) {
@@ -2744,9 +2746,23 @@ const sortAccounts = (field) => {
accountsSortBy.value = field accountsSortBy.value = field
accountsSortOrder.value = 'asc' accountsSortOrder.value = 'asc'
} }
// 同步下拉选择器的状态记录
lastDropdownSortField = field
} }
} }
// 下拉选择器排序处理(支持再次选择同一选项时切换排序方向)
const handleDropdownSort = (field) => {
if (field === lastDropdownSortField) {
// 选择同一字段,切换排序方向
accountsSortOrder.value = accountsSortOrder.value === 'asc' ? 'desc' : 'asc'
} else {
// 选择不同字段,重置为升序
accountsSortOrder.value = 'asc'
}
lastDropdownSortField = field
}
// 格式化数字(与原版保持一致) // 格式化数字(与原版保持一致)
const formatNumber = (num) => { const formatNumber = (num) => {
if (num === null || num === undefined) return '0' if (num === null || num === undefined) return '0'
@@ -3993,20 +4009,20 @@ watch(
} }
) )
// 监听排序选择变化 // 监听排序选择变化 - 已重构为 handleDropdownSort此处注释保留原逻辑参考
watch(accountSortBy, (newVal) => { // watch(accountSortBy, (newVal) => {
const fieldMap = { // const fieldMap = {
name: 'name', // name: 'name',
dailyTokens: 'dailyTokens', // dailyTokens: 'dailyTokens',
dailyRequests: 'dailyRequests', // dailyRequests: 'dailyRequests',
totalTokens: 'totalTokens', // totalTokens: 'totalTokens',
lastUsed: 'lastUsed' // lastUsed: 'lastUsed'
} // }
//
if (fieldMap[newVal]) { // if (fieldMap[newVal]) {
sortAccounts(fieldMap[newVal]) // sortAccounts(fieldMap[newVal])
} // }
}) // })
watch(currentPage, () => { watch(currentPage, () => {
updateSelectAllState() updateSelectAllState()

View File

@@ -0,0 +1,549 @@
<template>
<div class="space-y-4 p-4 lg:p-6">
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-3">
<button
class="rounded-full border border-gray-200 px-3 py-2 text-sm text-gray-700 transition hover:bg-gray-100 dark:border-gray-700 dark:text-gray-200 dark:hover:bg-gray-800"
@click="goBack"
>
返回
</button>
<div>
<p class="text-xs font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-400">
API Key 请求详情时间线
</p>
<h2 class="text-xl font-bold text-gray-900 dark:text-gray-100">
{{ apiKeyDisplayName }}
</h2>
<p class="text-xs text-gray-500 dark:text-gray-400">ID: {{ keyId }}</p>
</div>
</div>
<div class="flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400">
<i class="fas fa-clock text-blue-500" />
<span v-if="dateRangeHint">{{ dateRangeHint }}</span>
<span v-else>显示近 5000 条记录</span>
</div>
</div>
<div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
<div
class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900"
>
<p class="text-xs uppercase text-gray-500 dark:text-gray-400">总请求</p>
<p class="mt-1 text-2xl font-bold text-gray-900 dark:text-gray-100">
{{ formatNumber(summary.totalRequests) }}
</p>
</div>
<div
class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900"
>
<p class="text-xs uppercase text-gray-500 dark:text-gray-400"> Token</p>
<p class="mt-1 text-2xl font-bold text-gray-900 dark:text-gray-100">
{{ formatNumber(summary.totalTokens) }}
</p>
</div>
<div
class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900"
>
<p class="text-xs uppercase text-gray-500 dark:text-gray-400">总费用</p>
<p class="mt-1 text-2xl font-bold text-yellow-600 dark:text-yellow-400">
{{ formatCost(summary.totalCost) }}
</p>
</div>
<div
class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900"
>
<p class="text-xs uppercase text-gray-500 dark:text-gray-400">平均费用/</p>
<p class="mt-1 text-2xl font-bold text-gray-900 dark:text-gray-100">
{{ formatCost(summary.avgCost) }}
</p>
</div>
</div>
<div
class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900"
>
<div class="flex flex-wrap items-center gap-3">
<el-date-picker
v-model="filters.dateRange"
class="max-w-[320px]"
clearable
end-placeholder="结束时间"
format="YYYY-MM-DD HH:mm:ss"
start-placeholder="开始时间"
type="datetimerange"
unlink-panels
value-format="YYYY-MM-DDTHH:mm:ss[Z]"
/>
<el-select
v-model="filters.model"
class="w-[180px]"
clearable
filterable
placeholder="所有模型"
>
<el-option
v-for="modelOption in availableModels"
:key="modelOption"
:label="modelOption"
:value="modelOption"
/>
</el-select>
<el-select
v-model="filters.accountId"
class="w-[220px]"
clearable
filterable
placeholder="所有账户"
>
<el-option
v-for="account in availableAccounts"
:key="account.id"
:label="`${account.name}${account.accountTypeName}`"
:value="account.id"
/>
</el-select>
<el-select v-model="filters.sortOrder" class="w-[140px]" placeholder="排序">
<el-option label="时间降序" value="desc" />
<el-option label="时间升序" value="asc" />
</el-select>
<el-button @click="resetFilters"> <i class="fas fa-undo mr-2" /> 重置 </el-button>
<el-button :loading="exporting" type="primary" @click="exportCsv">
<i class="fas fa-file-export mr-2" /> 导出 CSV
</el-button>
</div>
</div>
<div
class="rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900"
>
<div
v-if="loading"
class="flex items-center justify-center p-10 text-gray-500 dark:text-gray-400"
>
<i class="fas fa-spinner fa-spin mr-2" /> 加载中...
</div>
<div v-else>
<div
v-if="records.length === 0"
class="flex flex-col items-center gap-2 p-10 text-gray-500 dark:text-gray-400"
>
<i class="fas fa-inbox text-2xl" />
<p>暂无记录</p>
</div>
<div v-else class="space-y-4">
<div class="hidden overflow-x-auto md:block">
<table class="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
<thead class="bg-gray-50 dark:bg-gray-800">
<tr>
<th
class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300"
>
时间
</th>
<th
class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300"
>
账户
</th>
<th
class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300"
>
模型
</th>
<th
class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300"
>
输入
</th>
<th
class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300"
>
输出
</th>
<th
class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300"
>
缓存(/)
</th>
<th
class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300"
>
Token
</th>
<th
class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300"
>
费用
</th>
<th
class="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300"
>
操作
</th>
</tr>
</thead>
<tbody
class="divide-y divide-gray-200 bg-white dark:divide-gray-800 dark:bg-gray-900"
>
<tr v-for="record in records" :key="record.timestamp + record.model">
<td class="whitespace-nowrap px-4 py-3 text-sm text-gray-800 dark:text-gray-100">
{{ formatDate(record.timestamp) }}
</td>
<td class="px-4 py-3 text-sm text-gray-800 dark:text-gray-100">
<div class="flex flex-col">
<span class="font-semibold">{{ record.accountName || '未知账户' }}</span>
<span class="text-xs text-gray-500 dark:text-gray-400">
{{ record.accountTypeName || '未知渠道' }}
</span>
</div>
</td>
<td class="whitespace-nowrap px-4 py-3 text-sm text-gray-800 dark:text-gray-100">
{{ record.model }}
</td>
<td class="whitespace-nowrap px-4 py-3 text-sm text-blue-600 dark:text-blue-400">
{{ formatNumber(record.inputTokens) }}
</td>
<td
class="whitespace-nowrap px-4 py-3 text-sm text-green-600 dark:text-green-400"
>
{{ formatNumber(record.outputTokens) }}
</td>
<td
class="whitespace-nowrap px-4 py-3 text-sm text-purple-600 dark:text-purple-400"
>
{{ formatNumber(record.cacheCreateTokens) }} /
{{ formatNumber(record.cacheReadTokens) }}
</td>
<td class="whitespace-nowrap px-4 py-3 text-sm text-gray-800 dark:text-gray-100">
{{ formatNumber(record.totalTokens) }}
</td>
<td
class="whitespace-nowrap px-4 py-3 text-sm text-yellow-600 dark:text-yellow-400"
>
{{ record.costFormatted || formatCost(record.cost) }}
</td>
<td class="whitespace-nowrap px-4 py-3 text-right text-sm">
<el-button size="small" @click="openDetail(record)">详情</el-button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="space-y-3 md:hidden">
<div
v-for="record in records"
:key="record.timestamp + record.model"
class="rounded-lg border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900"
>
<div class="flex items-center justify-between">
<div>
<p class="text-sm font-semibold text-gray-900 dark:text-gray-100">
{{ record.accountName || '未知账户' }}
</p>
<p class="text-xs text-gray-500 dark:text-gray-400">
{{ formatDate(record.timestamp) }}
</p>
</div>
<el-button size="small" @click="openDetail(record)">详情</el-button>
</div>
<div class="mt-3 grid grid-cols-2 gap-2 text-sm text-gray-700 dark:text-gray-300">
<div>模型{{ record.model }}</div>
<div> Token{{ formatNumber(record.totalTokens) }}</div>
<div>输入{{ formatNumber(record.inputTokens) }}</div>
<div>输出{{ formatNumber(record.outputTokens) }}</div>
<div>
缓存创/{{ formatNumber(record.cacheCreateTokens) }} /
{{ formatNumber(record.cacheReadTokens) }}
</div>
<div class="text-yellow-600 dark:text-yellow-400">
费用{{ record.costFormatted || formatCost(record.cost) }}
</div>
</div>
</div>
</div>
<div class="flex items-center justify-between px-4 pb-4">
<div class="text-sm text-gray-500 dark:text-gray-400">
{{ pagination.totalRecords }} 条记录
</div>
<el-pagination
background
:current-page="pagination.currentPage"
layout="prev, pager, next, sizes"
:page-size="pagination.pageSize"
:page-sizes="[20, 50, 100, 200]"
:total="pagination.totalRecords"
@current-change="handlePageChange"
@size-change="handleSizeChange"
/>
</div>
</div>
</div>
</div>
<RecordDetailModal :record="activeRecord" :show="detailVisible" @close="closeDetail" />
</div>
</template>
<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import dayjs from 'dayjs'
import { useRoute, useRouter } from 'vue-router'
import { apiClient } from '@/config/api'
import { showToast } from '@/utils/toast'
import { formatNumber } from '@/utils/format'
import RecordDetailModal from '@/components/apikeys/RecordDetailModal.vue'
const route = useRoute()
const router = useRouter()
const keyId = computed(() => route.params.keyId)
const loading = ref(false)
const exporting = ref(false)
const records = ref([])
const availableModels = ref([])
const availableAccounts = ref([])
const pagination = reactive({
currentPage: 1,
pageSize: 50,
totalRecords: 0
})
const filters = reactive({
dateRange: null,
model: '',
accountId: '',
sortOrder: 'desc'
})
const summary = reactive({
totalRequests: 0,
totalTokens: 0,
totalCost: 0,
avgCost: 0
})
const apiKeyInfo = reactive({
id: keyId.value,
name: ''
})
const detailVisible = ref(false)
const activeRecord = ref(null)
const apiKeyDisplayName = computed(() => apiKeyInfo.name || apiKeyInfo.id || keyId.value)
const dateRangeHint = computed(() => {
if (!filters.dateRange || filters.dateRange.length !== 2) return ''
return `${formatDate(filters.dateRange[0])} ~ ${formatDate(filters.dateRange[1])}`
})
const formatDate = (value) => {
if (!value) return '--'
return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
}
const formatCost = (value) => {
const num = typeof value === 'number' ? value : 0
if (num >= 1) return `$${num.toFixed(2)}`
if (num >= 0.001) return `$${num.toFixed(4)}`
return `$${num.toFixed(6)}`
}
const buildParams = (page) => {
const params = {
page,
pageSize: pagination.pageSize,
sortOrder: filters.sortOrder
}
if (filters.model) params.model = filters.model
if (filters.accountId) params.accountId = filters.accountId
if (filters.dateRange && filters.dateRange.length === 2) {
params.startDate = dayjs(filters.dateRange[0]).toISOString()
params.endDate = dayjs(filters.dateRange[1]).toISOString()
}
return params
}
const syncResponseState = (data) => {
records.value = data.records || []
const pageInfo = data.pagination || {}
pagination.currentPage = pageInfo.currentPage || 1
pagination.pageSize = pageInfo.pageSize || pagination.pageSize
pagination.totalRecords = pageInfo.totalRecords || 0
const filterEcho = data.filters || {}
if (filterEcho.model !== undefined) filters.model = filterEcho.model || ''
if (filterEcho.accountId !== undefined) filters.accountId = filterEcho.accountId || ''
if (filterEcho.sortOrder) filters.sortOrder = filterEcho.sortOrder
if (filterEcho.startDate && filterEcho.endDate) {
const nextRange = [filterEcho.startDate, filterEcho.endDate]
const currentRange = filters.dateRange || []
if (currentRange[0] !== nextRange[0] || currentRange[1] !== nextRange[1]) {
filters.dateRange = nextRange
}
}
const summaryData = data.summary || {}
summary.totalRequests = summaryData.totalRequests || 0
summary.totalTokens = summaryData.totalTokens || 0
summary.totalCost = summaryData.totalCost || 0
summary.avgCost = summaryData.avgCost || 0
apiKeyInfo.id = data.apiKeyInfo?.id || keyId.value
apiKeyInfo.name = data.apiKeyInfo?.name || ''
availableModels.value = data.availableFilters?.models || []
availableAccounts.value = data.availableFilters?.accounts || []
}
const fetchRecords = async (page = pagination.currentPage) => {
loading.value = true
try {
const response = await apiClient.get(`/admin/api-keys/${keyId.value}/usage-records`, {
params: buildParams(page)
})
syncResponseState(response.data || {})
} catch (error) {
showToast(`加载请求记录失败:${error.message || '未知错误'}`, 'error')
} finally {
loading.value = false
}
}
const handlePageChange = (page) => {
pagination.currentPage = page
fetchRecords(page)
}
const handleSizeChange = (size) => {
pagination.pageSize = size
pagination.currentPage = 1
fetchRecords(1)
}
const resetFilters = () => {
filters.model = ''
filters.accountId = ''
filters.dateRange = null
filters.sortOrder = 'desc'
pagination.currentPage = 1
fetchRecords(1)
}
const openDetail = (record) => {
activeRecord.value = record
detailVisible.value = true
}
const closeDetail = () => {
detailVisible.value = false
activeRecord.value = null
}
const goBack = () => {
router.push('/api-keys')
}
const exportCsv = async () => {
if (exporting.value) return
exporting.value = true
try {
const aggregated = []
let page = 1
let totalPages = 1
const maxPages = 50 // 50 * 200 = 10000超过后端 5000 上限已足够
while (page <= totalPages && page <= maxPages) {
const response = await apiClient.get(`/admin/api-keys/${keyId.value}/usage-records`, {
params: { ...buildParams(page), pageSize: 200 }
})
const payload = response.data || {}
aggregated.push(...(payload.records || []))
totalPages = payload.pagination?.totalPages || 1
page += 1
}
if (aggregated.length === 0) {
showToast('没有可导出的记录', 'info')
return
}
const headers = [
'时间',
'账户',
'渠道',
'模型',
'输入Token',
'输出Token',
'缓存创建Token',
'缓存读取Token',
'总Token',
'费用'
]
const csvRows = [headers.join(',')]
aggregated.forEach((record) => {
const row = [
formatDate(record.timestamp),
record.accountName || '',
record.accountTypeName || '',
record.model || '',
record.inputTokens || 0,
record.outputTokens || 0,
record.cacheCreateTokens || 0,
record.cacheReadTokens || 0,
record.totalTokens || 0,
record.costFormatted || formatCost(record.cost)
]
csvRows.push(row.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(','))
})
const blob = new Blob([csvRows.join('\n')], {
type: 'text/csv;charset=utf-8;'
})
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = `api-key-${keyId.value}-usage-records.csv`
link.click()
URL.revokeObjectURL(url)
showToast('导出 CSV 成功', 'success')
} catch (error) {
showToast(`导出失败:${error.message || '未知错误'}`, 'error')
} finally {
exporting.value = false
}
}
watch(
() => [filters.model, filters.accountId, filters.sortOrder],
() => {
pagination.currentPage = 1
fetchRecords(1)
}
)
watch(
() => filters.dateRange,
() => {
pagination.currentPage = 1
fetchRecords(1)
},
{ deep: true }
)
onMounted(() => {
fetchRecords()
})
</script>

View File

@@ -2085,17 +2085,18 @@
@save="handleSaveExpiry" @save="handleSaveExpiry"
/> />
<!-- 使用详情弹窗 -->
<UsageDetailModal <UsageDetailModal
:api-key="selectedApiKeyForDetail || {}" :api-key="selectedApiKeyForDetail || {}"
:show="showUsageDetailModal" :show="showUsageDetailModal"
@close="showUsageDetailModal = false" @close="showUsageDetailModal = false"
@open-timeline="openTimeline"
/> />
</div> </div>
</template> </template>
<script setup> <script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue' import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from '@/utils/toast' import { showToast } from '@/utils/toast'
import { apiClient } from '@/config/api' import { apiClient } from '@/config/api'
import { useClientsStore } from '@/stores/clients' import { useClientsStore } from '@/stores/clients'
@@ -2114,6 +2115,7 @@ import CustomDropdown from '@/components/common/CustomDropdown.vue'
import ActionDropdown from '@/components/common/ActionDropdown.vue' import ActionDropdown from '@/components/common/ActionDropdown.vue'
// 响应式数据 // 响应式数据
const router = useRouter()
const clientsStore = useClientsStore() const clientsStore = useClientsStore()
const authStore = useAuthStore() const authStore = useAuthStore()
const apiKeys = ref([]) const apiKeys = ref([])
@@ -4193,19 +4195,15 @@ const formatWindowTime = (seconds) => {
// 显示使用详情 // 显示使用详情
const showUsageDetails = (apiKey) => { const showUsageDetails = (apiKey) => {
// 获取异步加载的统计数据
const cachedStats = getCachedStats(apiKey.id) const cachedStats = getCachedStats(apiKey.id)
// 合并异步统计数据到 apiKey 对象
const enrichedApiKey = { const enrichedApiKey = {
...apiKey, ...apiKey,
// 合并实时限制数据
dailyCost: cachedStats?.dailyCost ?? apiKey.dailyCost ?? 0, dailyCost: cachedStats?.dailyCost ?? apiKey.dailyCost ?? 0,
currentWindowCost: cachedStats?.currentWindowCost ?? apiKey.currentWindowCost ?? 0, currentWindowCost: cachedStats?.currentWindowCost ?? apiKey.currentWindowCost ?? 0,
windowRemainingSeconds: cachedStats?.windowRemainingSeconds ?? apiKey.windowRemainingSeconds, windowRemainingSeconds: cachedStats?.windowRemainingSeconds ?? apiKey.windowRemainingSeconds,
windowStartTime: cachedStats?.windowStartTime ?? apiKey.windowStartTime ?? null, windowStartTime: cachedStats?.windowStartTime ?? apiKey.windowStartTime ?? null,
windowEndTime: cachedStats?.windowEndTime ?? apiKey.windowEndTime ?? null, windowEndTime: cachedStats?.windowEndTime ?? apiKey.windowEndTime ?? null,
// 合并 usage 数据(用于详情弹窗中的统计卡片)
usage: { usage: {
...apiKey.usage, ...apiKey.usage,
total: { total: {
@@ -4226,6 +4224,13 @@ const showUsageDetails = (apiKey) => {
showUsageDetailModal.value = true showUsageDetailModal.value = true
} }
const openTimeline = (keyId) => {
const id = keyId || selectedApiKeyForDetail.value?.id
if (!id) return
showUsageDetailModal.value = false
router.push(`/api-keys/${id}/usage-records`)
}
// 格式化时间(秒转换为可读格式) - 已移到 WindowLimitBar 组件中 // 格式化时间(秒转换为可读格式) - 已移到 WindowLimitBar 组件中
// const formatTime = (seconds) => { // const formatTime = (seconds) => {
// if (seconds === null || seconds === undefined) return '--:--' // if (seconds === null || seconds === undefined) return '--:--'

View File

@@ -1036,6 +1036,7 @@ function createUsageTrendChart() {
type: 'linear', type: 'linear',
display: true, display: true,
position: 'left', position: 'left',
min: 0,
title: { title: {
display: true, display: true,
text: 'Token数量', text: 'Token数量',
@@ -1055,6 +1056,7 @@ function createUsageTrendChart() {
type: 'linear', type: 'linear',
display: true, display: true,
position: 'right', position: 'right',
min: 0,
title: { title: {
display: true, display: true,
text: '请求数', text: '请求数',
@@ -1073,7 +1075,8 @@ function createUsageTrendChart() {
y2: { y2: {
type: 'linear', type: 'linear',
display: false, // 隐藏费用轴在tooltip中显示 display: false, // 隐藏费用轴在tooltip中显示
position: 'right' position: 'right',
min: 0
} }
} }
} }
@@ -1253,6 +1256,7 @@ function createApiKeysUsageTrendChart() {
}, },
y: { y: {
beginAtZero: true, beginAtZero: true,
min: 0,
title: { title: {
display: true, display: true,
text: apiKeysTrendMetric.value === 'tokens' ? 'Token 数量' : '请求次数', text: apiKeysTrendMetric.value === 'tokens' ? 'Token 数量' : '请求次数',
@@ -1428,6 +1432,7 @@ function createAccountUsageTrendChart() {
}, },
y: { y: {
beginAtZero: true, beginAtZero: true,
min: 0,
title: { title: {
display: true, display: true,
text: '消耗金额 (USD)', text: '消耗金额 (USD)',