feat(console): add deletion lifecycle, usage history and balance adjustments

This commit is contained in:
wlx committed 2026-09-19 21:08:45 +08:00
1 parent 32e977df5c
commit 7360cf3ebe
18 files changed
+832 -68

No files matched your search

+27 -12
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { Plus, KeyRound, CircleDollarSign, RefreshCcw, Search, ShieldCheck, List, Copy, Ban } from 'lucide-vue-next'
import { catalogClient, type AdminCatalogUser, type AdminInvitation, type WalletEntry } from '../services/catalog'
import { catalogClient, CatalogApiError, type AdminCatalogUser, type AdminInvitation, type WalletEntry } from '../services/catalog'
import type { AuthUser } from '../services/auth'
import UiModal from './UiModal.vue'
import SlidePanel from './SlidePanel.vue'
@@ -21,9 +21,15 @@ const role = ref<'user' | 'admin'>('user')
const inviteLabel = ref('')
const inviteCode = ref('')
const amount = ref('')
const creditOperation = ref<'increase' | 'decrease' | 'set'>('increase')
const creditError = ref('')
const projectedBalance = computed(() => {
const current = Number(balances.value[target.value?.id || ''] || 0), value = Number(amount.value)
return creditOperation.value === 'set' ? value : creditOperation.value === 'decrease' ? current - value : current + value
})
const reason = ref('')
const requestId = ref('')
const submittedGrant = ref<{ requestId: string; amount: string; reason: string }>()
const submittedGrant = ref<{ requestId: string; operation: 'increase' | 'decrease' | 'set'; amount: string; reason: string; expectedBalance: string }>()
const ledgerUser = ref<AdminCatalogUser>()
const entries = ref<WalletEntry[]>([])
const ledgerLoading = ref(false)
@@ -46,7 +52,7 @@ onMounted(refresh)
function createAccount() { Object.assign(account, { account: '', displayName: '', password: '' }); editor.value = 'account' }
function createInvite() { inviteCode.value = ''; inviteLabel.value = ''; editor.value = 'invite' }
function credit(user: AdminCatalogUser) {
target.value = user; amount.value = ''; reason.value = ''; requestId.value = crypto.randomUUID(); submittedGrant.value = undefined; editor.value = 'credit'
target.value = user; amount.value = ''; reason.value = ''; creditOperation.value = 'increase'; creditError.value = ''; requestId.value = crypto.randomUUID(); submittedGrant.value = undefined; editor.value = 'credit'
}
function editRole(user: AdminCatalogUser) { target.value = user; role.value = user.role === 'admin' ? 'admin' : 'user'; editor.value = 'role' }
async function ledger(user: AdminCatalogUser) {
@@ -70,14 +76,22 @@ async function save() {
} else if (editor.value === 'role' && target.value) {
await catalogClient.changeUserRole(target.value.id, role.value)
} else if (editor.value === 'credit' && target.value) {
if (!reason.value.trim()) throw new Error('请填写发放原因')
if (!submittedGrant.value) submittedGrant.value = { requestId: requestId.value, amount: amount.value, reason: reason.value.trim() }
await catalogClient.grantCredit(target.value.id, submittedGrant.value)
creditError.value = ''
if (!reason.value.trim()) throw new Error('请填写调整原因')
if (projectedBalance.value < 0) throw new Error('减少金额不能超过当前余额')
if (!submittedGrant.value) submittedGrant.value = { requestId: requestId.value, operation: creditOperation.value, amount: amount.value, reason: reason.value.trim(), expectedBalance: String(balances.value[target.value.id] || 0) }
await catalogClient.adjustCredit(target.value.id, submittedGrant.value)
}
editor.value = ''
await refresh()
emit('notify', '操作已完成')
} catch (e) { emit('notify', e instanceof Error ? e.message : '操作失败') }
} catch (e) {
const message = e instanceof Error ? e.message : '操作失败'
if (editor.value === 'credit') {
creditError.value = message
if (e instanceof CatalogApiError && e.status >= 400 && e.status < 500) { submittedGrant.value = undefined; requestId.value = crypto.randomUUID(); await refresh() }
} else emit('notify', message)
}
finally { saving.value = false }
}
async function revokeInvitation(invitation: AdminInvitation) {
@@ -101,18 +115,18 @@ async function copyText(value: string) {
<div class="account-summary"><span>用户 <strong>{{ users.length }}</strong></span><span>人民币余额合计 <strong>{{ money(totalBalance) }}</strong></span></div>
<label class="search-input account-search"><Search :size="16" /><input v-model="query" placeholder="搜索账号或姓名" /></label>
<p v-if="error" role="alert">{{ error }}</p><p v-if="loading">加载中…</p>
<div class="responsive-table"><table><thead><tr><th>用户</th><th>角色</th><th>人民币余额</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="user in filteredUsers" :key="user.id"><td><strong>{{ user.displayName }}</strong><small class="account-secondary">{{ user.account }}</small></td><td>{{ roleName(user.role) }}</td><td>{{ money(balances[user.id]) }}</td><td>{{ user.status === 'active' ? '正常' : '已停用' }}</td><td><div class="heading-actions"><button class="button secondary small" :disabled="user.status !== 'active'" @click="credit(user)"><CircleDollarSign :size="15" />发放额度</button><button class="button secondary small" @click="editRole(user)" v-if="props.currentUser?.role === 'super_admin' && user.role !== 'super_admin'"><ShieldCheck :size="15" />修改角色</button><button class="icon-button" :title="`${user.account} 额度流水`" @click="ledger(user)"><List :size="16" /></button></div></td></tr><tr v-if="!filteredUsers.length && !loading"><td colspan="5">暂无用户</td></tr></tbody></table></div>
<div class="responsive-table"><table><thead><tr><th>用户</th><th>角色</th><th>人民币余额</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="user in filteredUsers" :key="user.id"><td><strong>{{ user.displayName }}</strong><small class="account-secondary">{{ user.account }}</small></td><td>{{ roleName(user.role) }}</td><td>{{ money(balances[user.id]) }}</td><td>{{ user.status === 'active' ? '正常' : '已停用' }}</td><td><div class="heading-actions"><button class="button secondary small" :disabled="user.status !== 'active'" @click="credit(user)"><CircleDollarSign :size="15" />调整额度</button><button class="button secondary small" @click="editRole(user)" v-if="props.currentUser?.role === 'super_admin' && user.role !== 'super_admin'"><ShieldCheck :size="15" />修改角色</button><button class="icon-button" :title="`${user.account} 额度流水`" @click="ledger(user)"><List :size="16" /></button></div></td></tr><tr v-if="!filteredUsers.length && !loading"><td colspan="5">暂无用户</td></tr></tbody></table></div>
<section class="panel invitation-panel"><header class="panel-header"><div><span>INVITATION RECORDS</span><h3>邀请码记录</h3></div><small>{{ invitations.length }} 条</small></header><div class="responsive-table"><table><thead><tr><th>邀请码</th><th>备注</th><th>使用情况</th><th>创建时间</th><th>操作</th></tr></thead><tbody><tr v-for="invitation in invitations" :key="invitation.id"><td><code>{{ invitation.code || `${invitation.codePrefix}…(旧记录仅保留前缀)` }}</code><button v-if="invitation.code" class="icon-button" title="复制邀请码" @click="copyText(invitation.code)"><Copy :size="14" /></button></td><td>{{ invitation.label }}</td><td>{{ invitation.usedCount }} / {{ invitation.maxUses }}{{ invitation.disabledAt ? ' · 已停用' : '' }}</td><td>{{ new Date(invitation.createdAt).toLocaleString('zh-CN') }}</td><td><button v-if="!invitation.disabledAt" class="button danger small" :disabled="saving" @click="revokeInvitation(invitation)"><Ban :size="14" />停用</button><span v-else>—</span></td></tr><tr v-if="!invitations.length"><td colspan="5">暂无邀请码记录</td></tr></tbody></table></div></section>
<UiModal v-if="editor" :title="editor === 'account' ? '开通账号' : editor === 'invite' ? '创建邀请' : editor === 'credit' ? '发放人民币额度' : '修改角色'" @close="!saving && (editor = '')">
<UiModal v-if="editor" :title="editor === 'account' ? '开通账号' : editor === 'invite' ? '创建邀请' : editor === 'credit' ? '调整人民币额度' : '修改角色'" @close="!saving && (editor = '')">
<form id="account-editor" @submit.prevent="save">
<template v-if="editor === 'account'"><label class="form-label" for="new-account">账号</label><input id="new-account" v-model="account.account" class="text-input" required maxlength="254" autocomplete="off" placeholder="用户名、邮箱或手机号" /><label class="form-label" for="new-display">显示名称</label><input id="new-display" v-model="account.displayName" class="text-input" maxlength="80" /><label class="form-label" for="new-password">初始密码</label><input id="new-password" v-model="account.password" type="password" class="text-input" required minlength="8" maxlength="256" autocomplete="new-password" /></template>
<template v-else-if="editor === 'invite'"><label class="form-label" for="invite-label">邀请备注</label><input id="invite-label" v-model="inviteLabel" class="text-input" :disabled="!!inviteCode" /><label v-if="inviteCode" class="form-label" for="invite-code">邀请码</label><input v-if="inviteCode" id="invite-code" :value="inviteCode" class="text-input" readonly /><p v-if="inviteCode" class="form-hint">邀请码已保存到下方记录,可稍后再次复制。</p></template>
<template v-else-if="editor === 'credit'"><p>{{ target?.displayName }} · {{ target?.account }}</p><p>当前余额:{{ money(balances[target?.id || '']) }}</p><label class="form-label" for="grant-amount">发放金额(人民币元)</label><input id="grant-amount" v-model="amount" class="text-input" required type="number" min="0.01" max="1000000" step="0.01" :disabled="!!submittedGrant" /><label class="form-label" for="grant-reason">发放原因</label><textarea id="grant-reason" v-model="reason" class="text-input" required maxlength="500" :disabled="!!submittedGrant" /><p>本次增加:{{ money(Number(amount)) }}</p></template>
<template v-else-if="editor === 'credit'"><p>{{ target?.displayName }} · {{ target?.account }}</p><p>当前余额:{{ money(balances[target?.id || '']) }}</p><label class="form-label" for="credit-operation">调整方式</label><select id="credit-operation" v-model="creditOperation" class="text-input" :disabled="!!submittedGrant"><option value="increase">增加额度</option><option value="decrease">减少额度</option><option value="set">设置为指定余额</option></select><label class="form-label" for="grant-amount">{{ creditOperation === 'set' ? '目标余额' : creditOperation === 'decrease' ? '减少金额' : '增加金额' }}(人民币元)</label><input id="grant-amount" v-model="amount" class="text-input" required type="number" :min="creditOperation === 'set' ? '0' : '0.01'" max="1000000" step="0.01" :disabled="!!submittedGrant" /><label class="form-label" for="grant-reason">调整原因</label><textarea id="grant-reason" v-model="reason" class="text-input" required maxlength="500" :disabled="!!submittedGrant" /><p>调整后余额:{{ money(projectedBalance) }}</p><p v-if="creditError" role="alert" class="credit-error">{{ creditError }}</p><p class="form-hint">每次调整均保留流水和操作人;余额不能为负数。</p></template>
<template v-else><p>{{ target?.displayName }} · {{ target?.account }}</p><label class="form-label" for="account-role">角色</label><select id="account-role" v-model="role" class="text-input"><option value="user">普通用户</option><option value="admin">管理员</option></select></template>
</form>
<template #footer><button class="button secondary" :disabled="saving" @click="editor = ''">关闭</button><button v-if="!inviteCode || editor !== 'invite'" class="button primary" type="submit" form="account-editor" :disabled="saving">{{ saving ? '提交中…' : editor === 'credit' ? '确认发放' : '确认' }}</button></template>
<template #footer><button class="button secondary" :disabled="saving" @click="editor = ''">关闭</button><button v-if="!inviteCode || editor !== 'invite'" class="button primary" type="submit" form="account-editor" :disabled="saving">{{ saving ? '提交中…' : editor === 'credit' ? '确认调整' : '确认' }}</button></template>
</UiModal>
<SlidePanel v-if="ledgerUser" :title="`${ledgerUser.displayName} · 额度流水`" @close="ledgerUser = undefined"><p>币种:人民币 CNY</p><p v-if="ledgerLoading">加载中…</p><div v-for="entry in entries" :key="entry.id" class="wallet-entry"><strong>+ {{ money(entry.amount) }}</strong><p>{{ entry.reason }}</p><small>{{ entry.actor }} · {{ new Date(entry.createdAt).toLocaleString('zh-CN') }}</small><p>余额 {{ money(entry.balanceAfter) }}</p></div><p v-if="!entries.length && !ledgerLoading">暂无流水</p></SlidePanel>
<SlidePanel v-if="ledgerUser" :title="`${ledgerUser.displayName} · 额度流水`" @close="ledgerUser = undefined"><p>币种:人民币 CNY</p><p v-if="ledgerLoading">加载中…</p><div v-for="entry in entries" :key="entry.id" class="wallet-entry"><strong>{{ Number(entry.amount) >= 0 ? '+' : '−' }} {{ money(Math.abs(Number(entry.amount))) }}</strong><small> · {{ ({ increase: '增加', decrease: '减少', set: '设置余额' })[entry.operation] }}</small><p>{{ entry.reason }}</p><small>{{ entry.actor }} · {{ new Date(entry.createdAt).toLocaleString('zh-CN') }}</small><p>{{ money(entry.balanceBefore) }} → {{ money(entry.balanceAfter) }}</p></div><p v-if="!entries.length && !ledgerLoading">暂无流水</p></SlidePanel>
</template>
<style scoped>
@@ -124,5 +138,6 @@ async function copyText(value: string) {
.invitation-panel code { overflow-wrap: anywhere; }
.invitation-panel .icon-button { margin-left: 8px; vertical-align: middle; }
.form-hint { color: #687378; font-size: 13px; }
.credit-error { color: #b44837; }
@media(max-width: 700px) { .heading-actions { flex-wrap: wrap; } }
</style>
+16 -4
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { Plus, Pencil, RefreshCcw, Search } from 'lucide-vue-next'
import { Plus, Pencil, RefreshCcw, Search, Trash2 } from 'lucide-vue-next'
import { catalogClient, type CatalogProvider, type CatalogModel, type LogicalModel } from '../services/catalog'
import UiModal from './UiModal.vue'
@@ -15,6 +15,16 @@ const saving = ref(false)
const error = ref('')
const editor = ref<'channel' | 'model' | 'group' | ''>('')
const editingId = ref<string>()
const deleting = ref<{ kind: 'channel' | 'model' | 'group'; id: string; name: string }>()
const deleteError = ref('')
function confirmDelete(kind: 'channel' | 'model' | 'group', id: string, name: string) { deleting.value = { kind, id, name }; deleteError.value = '' }
async function remove() {
if (!deleting.value || saving.value) return
saving.value = true; deleteError.value = ''
try { await catalogClient.deleteCatalog(deleting.value.kind, deleting.value.id); deleting.value = undefined; await refresh(); emit('notify', '已删除,调用历史已保留') }
catch (e) { deleteError.value = e instanceof Error ? e.message : '删除失败' }
finally { saving.value = false }
}
const channel = reactive({ code: '', name: '', protocol: 'openai-compatible' as CatalogProvider['protocol'], sourceType: 'relay' as CatalogProvider['sourceType'], baseUrl: '', credentialType: 'api-key' as NonNullable<CatalogProvider['credentialType']>, credentialSecret: '', description: '', status: 'active' as CatalogProvider['status'] })
const model = reactive({ publicName: '', modelKey: '', type: 'text' as LogicalModel['type'], mode: 'sync' as LogicalModel['mode'], description: '', inputTypes: 'text', outputTypes: 'text', status: 'active' as LogicalModel['status'] })
const group = reactive({ logicalModelId: '', providerId: '', sourceLabel: '', upstreamModel: '', input: '', output: '', unit: 'CNY / 1M tokens', priority: '100', maxConcurrency: '1', status: 'active' as CatalogModel['status'] })
@@ -94,15 +104,16 @@ async function toggle(kind: 'channel' | 'model' | 'group', item: CatalogProvider
<label class="search-input catalog-search"><Search :size="16" /><input v-model="query" :placeholder="props.section === 'channels' ? '搜索渠道名称或 Code' : '搜索模型名称或标识'" /></label>
<p v-if="error" role="alert">{{ error }}</p>
<p v-if="loading">加载中…</p>
<div v-if="props.section === 'channels'" class="responsive-table"><table><thead><tr><th>渠道</th><th>来源 / 协议</th><th>Base URL</th><th>凭据</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="item in shownChannels" :key="item.id"><td><strong>{{ item.name }}</strong><small class="catalog-secondary">{{ item.code }}</small></td><td>{{ item.sourceType }}<small class="catalog-secondary">{{ item.protocol }}</small></td><td class="catalog-url">{{ item.baseUrl || '未配置' }}</td><td>{{ item.credentialMasked || '未配置' }}</td><td><label class="catalog-toggle"><input type="checkbox" :checked="item.status === 'active'" :disabled="saving" :aria-label="`${item.name} 启用`" @change="toggle('channel', item)" />{{ item.status === 'active' ? '已启用' : '已停用' }}</label></td><td><button class="icon-button" :title="`编辑渠道 ${item.name}`" @click="editChannel(item)"><Pencil :size="16" /></button></td></tr><tr v-if="!shownChannels.length && !loading"><td colspan="6">暂无渠道</td></tr></tbody></table></div>
<div v-if="props.section === 'channels'" class="responsive-table"><table><thead><tr><th>渠道</th><th>来源 / 协议</th><th>Base URL</th><th>凭据</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="item in shownChannels" :key="item.id"><td><strong>{{ item.name }}</strong><small class="catalog-secondary">{{ item.code }}</small></td><td>{{ item.sourceType }}<small class="catalog-secondary">{{ item.protocol }}</small></td><td class="catalog-url">{{ item.baseUrl || '未配置' }}</td><td>{{ item.credentialMasked || '未配置' }}</td><td><label class="catalog-toggle"><input type="checkbox" :checked="item.status === 'active'" :disabled="saving" :aria-label="`${item.name} 启用`" @change="toggle('channel', item)" />{{ item.status === 'active' ? '已启用' : '已停用' }}</label></td><td><button class="icon-button" :title="`编辑渠道 ${item.name}`" @click="editChannel(item)"><Pencil :size="16" /></button><button class="icon-button" :title="`删除渠道 ${item.name}`" :disabled="saving" @click="confirmDelete('channel', item.id, item.name)"><Trash2 :size="16" /></button></td></tr><tr v-if="!shownChannels.length && !loading"><td colspan="6">暂无渠道</td></tr></tbody></table></div>
<template v-else>
<section v-for="item in shownModels" :key="item.id" class="model-definition-section">
<header class="panel-header"><div><h3>{{ item.publicName }}</h3><small>{{ item.modelKey || item.id }} · {{ item.type }} · {{ item.mode }}</small></div><div class="heading-actions"><label class="catalog-toggle"><input type="checkbox" :checked="item.status === 'active'" :disabled="saving" :aria-label="`${item.publicName} 启用`" @change="toggle('model', item)" />启用</label><button class="icon-button" :title="`编辑模型 ${item.publicName}`" @click="editModel(item)"><Pencil :size="16" /></button><button class="button secondary small" @click="editGroup(item)"><Plus :size="15" />添加分组</button></div></header>
<header class="panel-header"><div><h3>{{ item.publicName }}</h3><small>{{ item.modelKey || item.id }} · {{ item.type }} · {{ item.mode }}</small></div><div class="heading-actions"><label class="catalog-toggle"><input type="checkbox" :checked="item.status === 'active'" :disabled="saving" :aria-label="`${item.publicName} 启用`" @change="toggle('model', item)" />启用</label><button class="icon-button" :title="`编辑模型 ${item.publicName}`" @click="editModel(item)"><Pencil :size="16" /></button><button class="icon-button" :title="`删除模型 ${item.publicName}`" :disabled="saving" @click="confirmDelete('model', item.id, item.publicName)"><Trash2 :size="16" /></button><button class="button secondary small" @click="editGroup(item)"><Plus :size="15" />添加分组</button></div></header>
<p v-if="item.description" class="catalog-secondary">{{ item.description }}</p>
<div class="responsive-table"><table><thead><tr><th>分组名称</th><th>渠道</th><th>上游模型</th><th>输入 / 输出价格</th><th>并发</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="route in modelGroups(item.id)" :key="route.id"><td>{{ route.sourceLabel }}</td><td>{{ channelName(route.providerId) }}</td><td><code>{{ route.upstreamModel }}</code></td><td>{{ route.pricing?.input ?? '—' }} / {{ route.pricing?.output ?? '—' }}<small class="catalog-secondary">{{ route.pricing?.unit }}</small></td><td>{{ route.maxConcurrency ?? '默认' }}</td><td><label class="catalog-toggle"><input type="checkbox" :checked="route.status === 'active'" :disabled="saving" :aria-label="`${route.sourceLabel} 启用`" @change="toggle('group', route)" />{{ route.status === 'active' ? '已启用' : '已停用' }}</label></td><td><button class="icon-button" :title="`编辑分组 ${route.sourceLabel}`" @click="editGroup(item, route)"><Pencil :size="16" /></button></td></tr><tr v-if="!modelGroups(item.id).length"><td colspan="7">暂无分组</td></tr></tbody></table></div>
<div class="responsive-table"><table><thead><tr><th>分组名称</th><th>渠道</th><th>上游模型</th><th>输入 / 输出价格</th><th>并发</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="route in modelGroups(item.id)" :key="route.id"><td>{{ route.sourceLabel }}</td><td>{{ channelName(route.providerId) }}</td><td><code>{{ route.upstreamModel }}</code></td><td>{{ route.pricing?.input ?? '—' }} / {{ route.pricing?.output ?? '—' }}<small class="catalog-secondary">{{ route.pricing?.unit }}</small></td><td>{{ route.maxConcurrency ?? '默认' }}</td><td><label class="catalog-toggle"><input type="checkbox" :checked="route.status === 'active'" :disabled="saving" :aria-label="`${route.sourceLabel} 启用`" @change="toggle('group', route)" />{{ route.status === 'active' ? '已启用' : '已停用' }}</label></td><td><button class="icon-button" :title="`编辑分组 ${route.sourceLabel}`" @click="editGroup(item, route)"><Pencil :size="16" /></button><button class="icon-button" :title="`删除分组 ${route.sourceLabel}`" :disabled="saving" @click="confirmDelete('group', route.id, route.sourceLabel || '默认分组')"><Trash2 :size="16" /></button></td></tr><tr v-if="!modelGroups(item.id).length"><td colspan="7">暂无分组</td></tr></tbody></table></div>
</section>
<p v-if="!shownModels.length && !loading">暂无模型</p>
</template>
<UiModal v-if="deleting" title="确认删除" @close="!saving && (deleting = undefined)"><p>确认删除「{{ deleting.name }}」?</p><p>{{ deleting.kind === 'model' ? '该模型及全部分组将从目录移除,相关 API Key 将不能再调用它们。' : deleting.kind === 'channel' ? '请先将关联分组删除或改为其他渠道,再删除渠道。' : '分组将从目录移除,相关 API Key 将不能再调用它。' }}</p><p>调用历史和已有任务会保留。删除后无法从页面恢复。</p><p v-if="deleteError" role="alert" class="delete-error">{{ deleteError }}</p><template #footer><button class="button secondary" :disabled="saving" @click="deleting = undefined">取消</button><button class="button danger" :disabled="saving" @click="remove">{{ saving ? '删除中…' : '确认删除' }}</button></template></UiModal>
<UiModal v-if="editor" :title="`${editingId ? '编辑' : '添加'}${editor === 'channel' ? '渠道' : editor === 'model' ? '模型' : '分组'}`" @close="!saving && (editor = '')">
<form id="catalog-editor" @submit.prevent="save">
<template v-if="editor === 'channel'">
@@ -142,6 +153,7 @@ async function toggle(kind: 'channel' | 'model' | 'group', item: CatalogProvider
.catalog-secondary { display: block; color: #687378; font-size: 12px; margin-top: 5px; overflow-wrap: anywhere; }
.catalog-search { max-width: 420px; }
.catalog-url { max-width: 320px; overflow-wrap: anywhere; }
.delete-error { color: #b44837; }
.catalog-toggle { display: inline-flex; align-items: center; gap: 7px; white-space: nowrap; }
.model-definition-section { padding: 20px 0; border-bottom: 1px solid #dce3e5; }
.model-definition-section h3 { margin: 0; font-size: 18px; }
+178
View File
@@ -0,0 +1,178 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { Activity, Coins, Clock3, Download, Filter, RefreshCcw, SlidersHorizontal, ChevronLeft, ChevronRight, History } from 'lucide-vue-next'
import { catalogClient, type UserUsageRecord, type UserUsagePage, type UsageOptions } from '../services/catalog'
import SlidePanel from './SlidePanel.vue'
const props = defineProps<{ history?: boolean; revision?: number }>()
const emit = defineEmits<{ notify: [message: string]; restore: [record: UserUsageRecord] }>()
const filters = reactive({ keyId: '', modelId: '', groupId: '', status: '', eventKind: '', callMode: '', source: '', costState: '', userAgent: '' })
const range = ref(props.history ? 'all' : '7')
const from = ref(''), to = ref('')
const page = ref(1), size = ref(props.history ? 10 : 20), sort = ref('time'), direction = ref('desc')
const loading = ref(false), exporting = ref(false), error = ref(''), detailsLoading = ref(false)
const selected = ref<UserUsageRecord>(), selectedId = ref('')
const data = ref<UserUsagePage>({ records: [], total: 0, pages: 1, page: 1, size: size.value, summary: { totalRequests: 0, inputUnits: 0, outputUnits: 0, pricedRequests: 0 } })
const options = ref<UsageOptions>({ keys: [], models: [], groups: [] })
const groups = computed(() => options.value.groups.filter(g => !filters.modelId || g.modelId === filters.modelId))
const columnSettings = ref(false)
const columnLabels = { key: 'API Key', model: '模型', group: '分组 / 渠道', endpoint: '端点', mode: '类型 / 来源', tokens: 'Token', cost: '费用', first: '首 Token', latency: '耗时', time: '时间', status: '状态', agent: 'User-Agent', reasoning: '推理强度' }
type Column = keyof typeof columnLabels
const columns = ref<Column[]>(['key', 'model', 'group', 'endpoint', 'mode', 'tokens', 'cost', 'latency', 'time', 'status'])
const show = (name: Column) => columns.value.includes(name)
const number = (n: unknown) => n == null ? '—' : Number(n).toLocaleString('zh-CN')
const money = (n: unknown) => n == null ? '—' : `¥ ${Number(n).toFixed(6)}`
const duration = (n: unknown) => n == null ? '—' : `${(Number(n) / 1000).toFixed(2)}s`
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
const statusName = (v: string) => ({ succeeded: '成功', failed: '失败', queued: '排队中', running: '执行中', cancelled: '已取消' })[v] || v
const modeName = (v?: string) => ({ sync: '同步', stream: '流式', async: '异步' })[v || ''] || '—'
const sourceName = (v?: string) => ({ playground: '在线调试', api: 'API', unknown: '历史调用' })[v || 'unknown'] || '历史调用'
const pretty = (v: unknown) => v == null ? '未保存内容' : JSON.stringify(v, null, 2)
const resultUrl = computed(() => {
const result = selected.value?.result as { url?: string } | undefined
if (!result?.url) return ''
try { const url = new URL(result.url); return ['https:', 'http:'].includes(url.protocol) ? url.href : '' } catch { return '' }
})
let requestSequence = 0
let timer: number | undefined
let activeFilters: Record<string, string | number> = {}
function query() {
const value: Record<string, string | number> = { ...filters, sort: sort.value, direction: direction.value }
if (range.value === 'custom') {
if (!from.value || !to.value || new Date(from.value) >= new Date(to.value)) throw new Error('请选择有效的开始和结束时间')
value.from = new Date(from.value).toISOString(); value.to = new Date(to.value).toISOString()
} else if (range.value !== 'all') value.from = new Date(Date.now() - Number(range.value) * 86400000).toISOString()
return value
}
async function refresh(reset = false) {
const sequence = ++requestSequence
if (timer) window.clearTimeout(timer)
loading.value = true; error.value = ''
try {
if (reset) page.value = 1
const applied = query()
const [result, choices] = await Promise.all([catalogClient.listUsage({ ...applied, page: page.value, size: size.value }), catalogClient.usageOptions()])
if (sequence !== requestSequence) return
data.value = result; options.value = choices; page.value = result.page; activeFilters = applied
if (result.records.some(item => ['queued', 'running'].includes(item.status))) timer = window.setTimeout(() => void refresh(), 10000)
} catch (e) { if (sequence === requestSequence) error.value = e instanceof Error ? e.message : '加载使用记录失败' }
finally { if (sequence === requestSequence) loading.value = false }
}
function changePage(next: number) { page.value = next; void refresh() }
function reset() {
Object.keys(filters).forEach(key => { filters[key as keyof typeof filters] = '' })
range.value = props.history ? 'all' : '7'; from.value = ''; to.value = ''; void refresh(true)
}
function order(field: string) {
direction.value = sort.value === field && direction.value === 'desc' ? 'asc' : 'desc'; sort.value = field; void refresh(true)
}
async function detail(record: UserUsageRecord) {
selectedId.value = record.id; selected.value = undefined; detailsLoading.value = true
try { const result = await catalogClient.usageDetail(record.id); if (selectedId.value === record.id) selected.value = result.record }
catch (e) { if (selectedId.value === record.id) { emit('notify', e instanceof Error ? e.message : '读取详情失败'); selectedId.value = ''; detailsLoading.value = false } }
finally { if (selectedId.value === record.id) detailsLoading.value = false }
}
async function exportCsv() {
exporting.value = true
try {
const blob = await catalogClient.exportUsage(activeFilters)
const url = URL.createObjectURL(blob), link = document.createElement('a')
link.href = url; link.download = `moyi-usage-${new Date().toISOString().slice(0, 10)}.csv`; link.click()
window.setTimeout(() => URL.revokeObjectURL(url), 1000)
} catch (e) { emit('notify', e instanceof Error ? e.message : '导出失败') }
finally { exporting.value = false }
}
onMounted(() => {
try { const saved = JSON.parse(localStorage.getItem('moyi-usage-columns') || 'null'); if (Array.isArray(saved) && saved.some(k => k in columnLabels)) columns.value = saved.filter(k => k in columnLabels) } catch {}
void refresh()
})
watch(columns, () => { try { localStorage.setItem('moyi-usage-columns', JSON.stringify(columns.value)) } catch {} }, { deep: true })
watch(() => props.revision, () => void refresh(true))
onUnmounted(() => { requestSequence++; selectedId.value = ''; if (timer) window.clearTimeout(timer) })
</script>
<template>
<section class="usage-history">
<header v-if="history" class="history-heading"><h3><History :size="18" />调用历史</h3><span>按账号保存,可查看请求与结果</span></header>
<section v-else class="usage-metrics">
<article class="panel"><Activity :size="23" /><div><span>总请求数</span><strong>{{ number(data.summary.totalRequests) }}</strong><small>当前筛选范围</small></div></article>
<article class="panel"><SlidersHorizontal :size="23" /><div><span>总 Token</span><strong>{{ number(Number(data.summary.inputUnits) + Number(data.summary.outputUnits)) }}</strong><small>输入 {{ number(data.summary.inputUnits) }} · 输出 {{ number(data.summary.outputUnits) }}</small><small>缓存命中 {{ number(data.summary.cachedInputUnits) }} · 写入 {{ number(data.summary.cacheWriteUnits) }}</small></div></article>
<article class="panel"><Coins :size="23" /><div><span>已记录费用 · 人民币</span><strong>{{ money(data.summary.totalCost) }}</strong><small>{{ number(data.summary.pricedRequests) }} / {{ number(data.summary.totalRequests) }} 次有费用记录</small></div></article>
<article class="panel"><Clock3 :size="23" /><div><span>平均耗时</span><strong>{{ duration(data.summary.averageLatencyMs) }}</strong><small>有耗时记录的请求</small></div></article>
</section>
<details class="panel usage-filters" :open="!history">
<summary><Filter :size="17" />筛选条件</summary>
<form @submit.prevent="refresh(true)">
<div class="usage-filter-grid">
<label>API Key<select v-model="filters.keyId" class="text-input"><option value="">全部密钥</option><option v-for="key in options.keys" :key="key.id" :value="key.id">{{ key.name }}{{ key.deleted ? '(已删除)' : '' }}</option></select></label>
<label>模型<select v-model="filters.modelId" class="text-input" @change="filters.groupId = ''"><option value="">全部模型</option><option v-for="model in options.models" :key="model.id" :value="model.id">{{ model.name }}</option></select></label>
<label>分组<select v-model="filters.groupId" class="text-input"><option value="">全部分组</option><option v-for="group in groups" :key="group.id" :value="group.id">{{ group.name }} · {{ group.channel }}</option></select></label>
<label>调用类型<select v-model="filters.callMode" class="text-input"><option value="">全部类型</option><option value="sync">同步</option><option value="stream">流式</option><option value="async">异步</option></select></label>
<label>请求类别<select v-model="filters.eventKind" class="text-input"><option value="">全部请求</option><option value="call">模型调用</option><option value="task">异步任务</option></select></label>
<label>状态<select v-model="filters.status" class="text-input"><option value="">全部状态</option><option v-for="state in ['succeeded','failed','queued','running','cancelled']" :key="state" :value="state">{{ statusName(state) }}</option></select></label>
<label>费用记录<select v-model="filters.costState" class="text-input"><option value="">全部</option><option value="recorded">已记录</option><option value="pending">未记录</option></select></label>
<label>来源<select v-model="filters.source" class="text-input"><option value="">全部来源</option><option value="playground">在线调试</option><option value="api">API</option><option value="unknown">历史调用(未标记来源)</option></select></label>
<label>User-Agent<input v-model="filters.userAgent" class="text-input" maxlength="200" placeholder="模糊搜索客户端" /></label>
<label>时间范围<select v-model="range" class="text-input"><option value="1">近 24 小时</option><option value="7">近 7 天</option><option value="30">近 30 天</option><option value="all">全部时间</option><option value="custom">自定义</option></select></label>
<template v-if="range === 'custom'"><label>开始时间<input v-model="from" type="datetime-local" class="text-input" required /></label><label>结束时间<input v-model="to" type="datetime-local" class="text-input" required /></label></template>
</div>
<div class="usage-actions"><button type="button" class="button secondary small" @click="reset">重置</button><button class="button primary small" :disabled="loading">应用筛选</button></div>
</form>
</details>
<section class="panel usage-table-card">
<header class="usage-toolbar"><span>{{ history ? '历史调用' : '使用记录' }} · {{ data.total }} 条</span><div class="usage-actions"><button class="button secondary small" :disabled="loading" @click="refresh()"><RefreshCcw :size="15" />刷新</button><button class="button secondary small" :aria-expanded="columnSettings" @click="columnSettings = !columnSettings"><SlidersHorizontal :size="15" />列设置</button><button class="button primary small" :disabled="exporting || loading || !!error" @click="exportCsv"><Download :size="15" />{{ exporting ? '导出中…' : '导出 CSV' }}</button></div></header>
<div v-if="columnSettings" class="usage-columns"><label v-for="(label, name) in columnLabels" :key="name"><input v-model="columns" type="checkbox" :value="name" :disabled="show(name) && columns.length === 1" />{{ label }}</label></div>
<p v-if="error" class="usage-error" role="alert">{{ error }} <button class="text-link" @click="refresh()">重试</button></p>
<div class="responsive-table" :aria-busy="loading"><table><thead><tr>
<th v-if="show('key')">API Key</th><th v-if="show('model')"><button class="sort-button" @click="order('model')">模型 {{ sort === 'model' ? (direction === 'desc' ? '↓' : '↑') : '↕' }}</button></th><th v-if="show('group')">分组 / 渠道</th><th v-if="show('endpoint')">端点</th><th v-if="show('mode')">类型 / 来源</th><th v-if="show('tokens')">Token</th><th v-if="show('cost')"><button class="sort-button" @click="order('cost')">费用(CNY) ↕</button></th><th v-if="show('first')">首 Token</th><th v-if="show('latency')"><button class="sort-button" @click="order('latency')">耗时 ↕</button></th><th v-if="show('time')"><button class="sort-button" @click="order('time')">时间 {{ sort === 'time' ? (direction === 'desc' ? '↓' : '↑') : '↕' }}</button></th><th v-if="show('status')">状态</th><th v-if="show('agent')">User-Agent</th><th v-if="show('reasoning')">推理强度</th><th>详情</th>
</tr></thead><tbody><tr v-for="record in data.records" :key="record.id">
<td v-if="show('key')"><strong>{{ record.keyName || '—' }}</strong><small>{{ record.keyPrefix }}</small></td><td v-if="show('model')">{{ record.modelName || record.modelId || '—' }}</td><td v-if="show('group')">{{ record.groupName || '—' }}<small>{{ record.providerName }}</small></td><td v-if="show('endpoint')"><code>{{ record.endpoint || '—' }}</code></td><td v-if="show('mode')"><span class="status-chip violet">{{ modeName(record.callMode) }}</span><small>{{ sourceName(record.requestSource) }}</small></td><td v-if="show('tokens')"><span>输入 {{ number(record.inputUnits) }}</span><small>输出 {{ number(record.outputUnits) }}</small><small v-if="record.cachedInputUnits != null">缓存命中 {{ number(record.cachedInputUnits) }}</small><small v-if="record.cacheWriteUnits != null">缓存写入 {{ number(record.cacheWriteUnits) }}</small></td><td v-if="show('cost')" class="usage-cost">{{ money(record.costAmount) }}</td><td v-if="show('first')">{{ duration(record.firstTokenMs) }}</td><td v-if="show('latency')">{{ duration(record.latencyMs) }}</td><td v-if="show('time')">{{ time(record.createdAt) }}</td><td v-if="show('status')"><span class="status-chip" :class="record.status === 'succeeded' ? 'success' : record.status === 'failed' ? 'danger' : 'muted'">{{ statusName(record.status) }}</span><small v-if="record.progress != null">{{ record.progress }}%</small></td><td v-if="show('agent')" class="agent-cell">{{ record.userAgent || '—' }}</td><td v-if="show('reasoning')">{{ record.reasoningEffort || '—' }}</td><td><button class="text-link" :aria-label="`查看 ${record.modelName || '调用'} 详情`" @click="detail(record)">查看</button></td>
</tr><tr v-if="!data.records.length"><td :colspan="columns.length + 1"><div class="empty-state compact"><History :size="24" /><strong>{{ loading ? '加载中…' : error ? '使用记录暂不可用' : '暂无使用记录' }}</strong><span v-if="!loading && !error">调整筛选范围,或完成一次模型调用后查看</span></div></td></tr></tbody></table></div>
<footer class="usage-pagination"><span>显示 {{ data.total ? (data.page - 1) * data.size + 1 : 0 }}–{{ Math.min(data.page * data.size, data.total) }},共 {{ data.total }} 条</span><label>每页 <select v-model="size" :disabled="loading" @change="refresh(true)"><option :value="10">10</option><option :value="20">20</option><option :value="50">50</option><option :value="100">100</option></select></label><div><button class="icon-button" title="上一页" :disabled="loading || data.page <= 1" @click="changePage(data.page - 1)"><ChevronLeft :size="17" /></button><span>{{ data.page }} / {{ data.pages }}</span><button class="icon-button" title="下一页" :disabled="loading || data.page >= data.pages" @click="changePage(data.page + 1)"><ChevronRight :size="17" /></button></div></footer>
</section>
<p class="usage-footnote">费用以人民币展示。“—”表示未记录,历史记录不会补算费用或耗时。CSV 导出当前已应用的筛选结果,最多 10000 条。</p>
<SlidePanel v-if="selectedId" title="调用详情" @close="selectedId = ''; selected = undefined">
<p v-if="detailsLoading">加载中…</p>
<template v-else-if="selected"><dl class="detail-list"><div><dt>记录 ID</dt><dd>{{ selected.id }}</dd></div><div><dt>模型 / 分组</dt><dd>{{ selected.modelName }} / {{ selected.groupName }}</dd></div><div><dt>状态</dt><dd>{{ statusName(selected.status) }}</dd></div><div><dt>时间</dt><dd>{{ time(selected.createdAt) }}</dd></div><div><dt>费用</dt><dd>{{ money(selected.costAmount) }}</dd></div><div v-if="selected.taskId"><dt>任务 ID</dt><dd>{{ selected.taskId }}</dd></div></dl><p v-if="selected.errorMessage" class="usage-error">{{ selected.errorCode }}:{{ selected.errorMessage }}</p><a v-if="resultUrl" class="button secondary" :href="resultUrl" target="_blank" rel="noopener noreferrer">打开任务结果</a><h4>请求内容</h4><pre class="usage-payload">{{ pretty(selected.input) }}</pre><h4>响应内容</h4><pre class="usage-payload">{{ pretty(selected.result || selected.output) }}</pre><button v-if="history && selected.input" class="button primary" @click="emit('restore', selected); selectedId = ''">载入调试</button></template>
</SlidePanel>
</section>
</template>
<style scoped>
.usage-history { display: grid; gap: 16px; min-width: 0; }
.usage-metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; }
.usage-metrics article { padding: 22px; position: relative; }
.usage-metrics article > svg { color: #7663ab; position: absolute; right: 18px; top: 20px; opacity: .55; }
.usage-metrics article span { padding-right: 22px; }
.usage-metrics span, .usage-metrics small { color: #748082; display: block; font-size: 12px; }
.usage-metrics strong { display: block; font-size: clamp(20px, 1.9vw, 26px); margin: 10px 0 6px; overflow-wrap: anywhere; }
.usage-metrics small { line-height: 1.7; }
.usage-filters { padding: 18px 22px; }
.usage-filters summary { display: flex; align-items: center; gap: 9px; cursor: pointer; font-weight: 600; }
.usage-filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 16px; margin: 22px 0; }
.usage-filter-grid label { display: grid; gap: 8px; color: #586467; font-size: 13px; }
.usage-filter-grid .text-input { width: 100%; min-width: 0; }
.usage-actions { display: flex; flex-wrap: wrap; gap: 8px; justify-content: flex-end; }
.usage-toolbar, .usage-pagination { display: flex; align-items: center; justify-content: space-between; gap: 14px; padding: 18px 22px; flex-wrap: wrap; }
.usage-toolbar > span { font-weight: 600; }
.usage-columns { display: flex; gap: 16px; flex-wrap: wrap; padding: 0 22px 18px; font-size: 13px; }
.usage-columns label { display: flex; gap: 6px; align-items: center; }
.usage-table-card { overflow: hidden; }
.usage-table-card table { font-size: 13px; white-space: nowrap; }
.usage-table-card td small { display: block; color: #7c898b; margin-top: 6px; font-size: 11px; }
.usage-table-card td { padding: 19px 16px; }
.usage-table-card td.agent-cell { max-width: 220px; white-space: normal; overflow-wrap: anywhere; }
.usage-cost { color: #168572; font-variant-numeric: tabular-nums; }
.sort-button { border: 0; background: none; color: inherit; padding: 0; font: inherit; cursor: pointer; }
.usage-pagination { border-top: 1px solid #e4e9e8; font-size: 12px; color: #6b777a; }
.usage-pagination > div { display: flex; align-items: center; gap: 12px; }
.usage-pagination select { border: 1px solid #dce4e3; border-radius: 6px; padding: 6px; background: white; }
.usage-error { color: #b44837; padding: 0 20px; }
.usage-footnote { font-size: 12px; color: #7c898b; margin: 0; }
.usage-payload { white-space: pre-wrap; overflow-wrap: anywhere; background: #f2f5f5; border-radius: 10px; padding: 16px; max-height: 380px; overflow: auto; font-size: 12px; }
.history-heading { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px; }
.history-heading h3 { display: flex; align-items: center; gap: 8px; margin: 10px 0; }
.history-heading span { font-size: 12px; color: #7c898b; }
.detail-list dd { overflow-wrap: anywhere; }
@media(max-width: 1100px) { .usage-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media(max-width: 650px) { .usage-metrics { grid-template-columns: 1fr; } .usage-filter-grid { grid-template-columns: 1fr; } .usage-toolbar { align-items: flex-start; } }
</style>