feat(console): add deletion lifecycle, usage history and balance adjustments
This commit is contained in:
1 parent
32e977df5c
commit
7360cf3ebe
18 files changed
+832
-68
No files matched your search
@@ -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>
|
||||
@@ -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; }
|
||||
|
||||
@@ -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>
|
||||
@@ -50,6 +50,8 @@ export interface WalletEntry {
|
||||
id: string
|
||||
amount: number
|
||||
balanceAfter: number
|
||||
balanceBefore: number
|
||||
operation: 'increase' | 'decrease' | 'set'
|
||||
currency: 'CNY'
|
||||
reason: string
|
||||
createdAt: string
|
||||
@@ -200,6 +202,31 @@ export class CatalogApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export interface UserUsageRecord extends UsageAuditRecord {
|
||||
logicalModelId?: string
|
||||
groupName?: string
|
||||
endpoint?: string
|
||||
callMode?: string
|
||||
requestSource?: string
|
||||
userAgent?: string
|
||||
cachedInputUnits?: number
|
||||
cacheWriteUnits?: number
|
||||
firstTokenMs?: number
|
||||
reasoningEffort?: string
|
||||
taskId?: string
|
||||
progress?: number
|
||||
result?: unknown
|
||||
}
|
||||
export interface UserUsagePage extends UsageAuditPage {
|
||||
records: UserUsageRecord[]
|
||||
summary: { totalRequests: number; inputUnits: number; outputUnits: number; cachedInputUnits?: number; cacheWriteUnits?: number; totalCost?: number; pricedRequests: number; averageLatencyMs?: number }
|
||||
}
|
||||
export interface UsageOptions {
|
||||
keys: Array<{ id: string; name: string; deleted: boolean }>
|
||||
models: Array<{ id: string; name: string }>
|
||||
groups: Array<{ id: string; modelId: string; name: string; channel: string }>
|
||||
}
|
||||
|
||||
class HttpCatalogClient {
|
||||
constructor(private readonly baseUrl: string) {}
|
||||
|
||||
@@ -238,10 +265,32 @@ class HttpCatalogClient {
|
||||
await this.request(`/api/keys/${encodeURIComponent(id)}/revoke`, { method: 'POST' })
|
||||
}
|
||||
|
||||
async setKeyStatus(id: string, status: 'active' | 'disabled') {
|
||||
await this.request(`/api/keys/${encodeURIComponent(id)}/status`, { method: 'PATCH', body: JSON.stringify({ status }) })
|
||||
}
|
||||
async deleteKey(id: string) { await this.request(`/api/keys/${encodeURIComponent(id)}`, { method: 'DELETE' }) }
|
||||
async deleteCatalog(kind: 'channel' | 'model' | 'group', id: string) {
|
||||
const resource = { channel: 'providers', model: 'model-definitions', group: 'models' }[kind]
|
||||
await this.request(`/api/admin/${resource}/${encodeURIComponent(id)}`, { method: 'DELETE' })
|
||||
}
|
||||
async adjustCredit(userId: string, input: { requestId: string; operation: 'increase' | 'decrease' | 'set'; amount: string; reason: string; expectedBalance: string }) {
|
||||
return this.request<{ id: string; balance: number; currency: 'CNY' }>(`/api/admin/users/${encodeURIComponent(userId)}/wallet/adjustments`, { method: 'POST', body: JSON.stringify(input) })
|
||||
}
|
||||
async listUsage(filters: Record<string, string | number>) {
|
||||
return this.request<UserUsagePage>(`/api/usage?${new URLSearchParams(Object.entries(filters).map(([k, v]) => [k, String(v)]))}`)
|
||||
}
|
||||
async usageOptions() { return this.request<UsageOptions>('/api/usage/options') }
|
||||
async usageDetail(id: string) { return this.request<{ record: UserUsageRecord }>(`/api/usage/${encodeURIComponent(id)}`) }
|
||||
async exportUsage(filters: Record<string, string | number>) {
|
||||
const response = await fetch(`${this.baseUrl}/api/usage/export?${new URLSearchParams(Object.entries(filters).map(([k,v]) => [k,String(v)]))}`, { credentials: 'include' })
|
||||
if (!response.ok) { const data = await response.json().catch(() => ({})); throw new Error(data.error?.message || '导出失败') }
|
||||
return response.blob()
|
||||
}
|
||||
|
||||
async chatCompletion(apiKey: string, input: { model: string; prompt: string }) {
|
||||
return this.request<ChatCompletionResult>('/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
headers: { Authorization: `Bearer ${apiKey}`, 'X-Moyi-Source': 'playground' },
|
||||
body: JSON.stringify({ model: input.model, messages: [{ role: 'user', content: input.prompt }] }),
|
||||
})
|
||||
}
|
||||
@@ -249,7 +298,7 @@ class HttpCatalogClient {
|
||||
async createMediaTask(apiKey: string, input: { model: string; prompt: string; mediaType: '3d' | 'video' }) {
|
||||
const payload = await this.request<{ task: AsyncTaskResult }>(input.mediaType === 'video' ? '/v1/video/tasks' : '/v1/3d/tasks', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
headers: { Authorization: `Bearer ${apiKey}`, 'X-Moyi-Source': 'playground' },
|
||||
body: JSON.stringify({ model: input.model, prompt: input.prompt }),
|
||||
})
|
||||
return payload.task
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
CheckCircle2,
|
||||
ChevronDown,
|
||||
CircleDollarSign,
|
||||
Clock3,
|
||||
Code2,
|
||||
Copy,
|
||||
Download,
|
||||
@@ -33,15 +32,17 @@ import {
|
||||
Sparkles,
|
||||
Terminal,
|
||||
Timer,
|
||||
Trash2,
|
||||
WalletCards,
|
||||
Zap,
|
||||
} from 'lucide-vue-next'
|
||||
import type { ApiKeyItem, CallMode, ModelItem, ModelType, TaskItem, TaskStatus } from '../types'
|
||||
import { catalogClient, platformApiBaseUrl, type AsyncTaskResult, type CatalogApiKey, type CatalogModel, type CatalogProject, type PlatformOverview } from '../services/catalog'
|
||||
import { catalogClient, platformApiBaseUrl, type AsyncTaskResult, type CatalogApiKey, type CatalogModel, type CatalogProject, type PlatformOverview, type UserUsageRecord } from '../services/catalog'
|
||||
import { copyText, type CopyResult } from '../services/clipboard'
|
||||
import SlidePanel from '../components/SlidePanel.vue'
|
||||
import UiModal from '../components/UiModal.vue'
|
||||
import ModelGroupPermissions from '../components/ModelGroupPermissions.vue'
|
||||
import UsageHistory from '../components/UsageHistory.vue'
|
||||
|
||||
defineProps<{ view: string; displayName?: string }>()
|
||||
const emit = defineEmits<{ navigate: [view: string]; notify: [message: string]; balance: [value: number | undefined] }>()
|
||||
@@ -71,7 +72,19 @@ const running = ref(false)
|
||||
const response = ref('')
|
||||
const keys = ref<ApiKeyItem[]>([])
|
||||
const tasks = ref<TaskItem[]>([])
|
||||
const taskFilter = ref<'全部' | TaskStatus>('全部')
|
||||
const historyRevision = ref(0)
|
||||
const keyBusy = ref(false)
|
||||
const deleteKeyTarget = ref<ApiKeyItem>()
|
||||
function restoreHistory(record: UserUsageRecord) {
|
||||
const input = record.input as { prompt?: unknown; messages?: unknown } | undefined
|
||||
const group = catalogModels.value.find(item => item.id === record.modelId)
|
||||
if (group) selectPlaygroundGroup(group.id)
|
||||
const messages = Array.isArray(input?.messages) ? input.messages : []
|
||||
const text = typeof input?.prompt === 'string' ? input.prompt : messages.filter(message => message?.role === 'user' && typeof message.content === 'string').map(message => message.content).join('\n')
|
||||
prompt.value = text.slice(0, 4000)
|
||||
response.value = ''
|
||||
emit('notify', !group ? '历史文本已载入,原分组已不可用,请重新选择模型和分组' : text.length > 4000 ? '已载入前 4000 字,请检查输入后再调用' : text ? '历史输入已载入,确认配置后可再次调用' : '该记录没有可恢复的纯文本输入,请手动填写')
|
||||
}
|
||||
const selectedTask = ref<TaskItem | null>(null)
|
||||
const createKeyOpen = ref(false)
|
||||
const secretOpen = ref(false)
|
||||
@@ -149,11 +162,7 @@ const activeModelFilters = computed(() => [
|
||||
modelMode.value !== '全部' ? modelMode.value : '',
|
||||
modelAvailability.value !== '全部' ? modelAvailability.value : '',
|
||||
].filter(Boolean))
|
||||
const filteredTasks = computed(() => taskFilter.value === '全部' ? tasks.value : tasks.value.filter((task) => task.status === taskFilter.value))
|
||||
const activeTask = computed(() => tasks.value.find((task) => task.id === activeTaskId.value))
|
||||
const runningTaskCount = computed(() => tasks.value.filter((task) => task.status === '执行中').length)
|
||||
const queuedTaskCount = computed(() => tasks.value.filter((task) => task.status === '排队中').length)
|
||||
const completedTaskCount = computed(() => tasks.value.filter((task) => task.status === '已完成').length)
|
||||
const usageSeries = computed(() => {
|
||||
const maximum = Math.max(...overview.value.series.map((item) => item.count), 0)
|
||||
return overview.value.series.map((item) => ({
|
||||
@@ -239,6 +248,7 @@ async function runModel() {
|
||||
emit('notify', error instanceof Error ? error.message : '模型调用失败')
|
||||
} finally {
|
||||
running.value = false
|
||||
historyRevision.value++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,17 +422,28 @@ async function saveModelPermissions() {
|
||||
}
|
||||
|
||||
async function toggleKey(key: ApiKeyItem) {
|
||||
if (catalogConnected.value && key.status === '正常') {
|
||||
try {
|
||||
await catalogClient.revokeKey(String(key.id))
|
||||
key.status = '已停用'
|
||||
emit('notify', `${key.name} 已停用`)
|
||||
} catch (error) {
|
||||
emit('notify', error instanceof Error ? error.message : '停用 Key 失败')
|
||||
}
|
||||
return
|
||||
}
|
||||
emit('notify', key.status === '已停用' ? '已停用的 Key 不能重新启用,请创建新 Key' : 'Control Plane 未连接')
|
||||
if (keyBusy.value) return
|
||||
keyBusy.value = true
|
||||
try {
|
||||
const enabled = key.status !== '正常'
|
||||
await catalogClient.setKeyStatus(String(key.id), enabled ? 'active' : 'disabled')
|
||||
key.status = enabled ? '正常' : '已停用'
|
||||
emit('notify', `${key.name} ${enabled ? '已重新启用' : '已停用'}`)
|
||||
} catch (error) { emit('notify', error instanceof Error ? error.message : '更新 Key 状态失败') }
|
||||
finally { keyBusy.value = false }
|
||||
}
|
||||
async function deleteKey() {
|
||||
if (!deleteKeyTarget.value || keyBusy.value) return
|
||||
keyBusy.value = true
|
||||
try {
|
||||
const id = deleteKeyTarget.value.id
|
||||
await catalogClient.deleteKey(String(id))
|
||||
keys.value = keys.value.filter(key => key.id !== id)
|
||||
if (id === createdKeyId.value) { remoteApiKey.value = ''; createdSecret.value = ''; createdKeyId.value = '' }
|
||||
deleteKeyTarget.value = undefined
|
||||
emit('notify', 'API Key 已删除,使用记录已保留')
|
||||
} catch (error) { emit('notify', error instanceof Error ? error.message : '删除 Key 失败') }
|
||||
finally { keyBusy.value = false }
|
||||
}
|
||||
|
||||
async function createProject() {
|
||||
@@ -515,18 +536,18 @@ async function createProject() {
|
||||
<div v-else class="response-state empty"><span class="response-icon"><Sparkles :size="28" /></span><strong>等待模型响应</strong><p>配置请求并点击“开始调用”</p></div>
|
||||
</article>
|
||||
</section>
|
||||
<UsageHistory history :revision="historyRevision" @notify="emit('notify', $event)" @restore="restoreHistory" />
|
||||
</template>
|
||||
|
||||
<template v-else-if="view === 'keys'">
|
||||
<section class="page-heading"><div><span>DEVELOPER ACCESS</span><h1>API Keys</h1><p>为不同应用和环境创建独立访问凭证。</p></div><button class="button primary" @click="createKeyOpen = true"><Plus :size="16" />创建 API Key</button></section>
|
||||
<section class="notice"><ShieldCheck :size="19" /><div><strong>妥善保管访问凭证</strong><p>完整 Key 只在创建时展示一次,请存放在安全的环境变量或密钥管理服务中。</p></div></section>
|
||||
<section class="panel table-card"><header class="panel-header"><div><span>CREDENTIALS</span><h3>个人与项目 Keys</h3></div><small>{{ keys.length }} 个凭证{{ catalogConnected ? ' · 已连接 Control Plane' : ' · 服务未连接' }}</small></header><div class="responsive-table"><table><thead><tr><th>名称</th><th>Key</th><th>归属范围</th><th>模型权限</th><th>最近使用</th><th>状态</th><th></th></tr></thead><tbody><tr v-for="key in keys" :key="key.id"><td><div class="entity-cell"><span class="icon-tile violet"><KeyRound :size="16" /></span><div><strong>{{ key.name }}</strong><small>创建于 {{ key.createdAt }}</small></div></div></td><td><span class="code-value readonly" title="完整 Key 仅在创建时展示"><code>{{ key.value }}</code><ShieldCheck :size="14" /></span></td><td>{{ key.scope }}</td><td><button class="model-permission-summary" :disabled="key.status !== '正常'" @click="openModelPermissions(key)"><span>{{ key.modelIds.length ? `${key.modelIds.length} 个分组` : '未配置' }}</span><SlidersHorizontal :size="14" /></button></td><td>{{ key.lastUsed }}</td><td><span class="status-chip" :class="key.status === '正常' ? 'success' : 'muted'"><i></i>{{ key.status }}</span></td><td><button class="icon-button" :title="key.status === '正常' ? '停用 Key' : '已停用'" @click="toggleKey(key)"><EyeOff v-if="key.status === '正常'" :size="16" /><Eye v-else :size="16" /></button></td></tr><tr v-if="!keys.length"><td colspan="7"><div class="empty-state compact"><KeyRound :size="22" /><strong>暂无 API Key</strong><span>创建后完整 Key 只会展示一次</span></div></td></tr></tbody></table></div></section>
|
||||
<section class="panel table-card"><header class="panel-header"><div><span>CREDENTIALS</span><h3>个人与项目 Keys</h3></div><small>{{ keys.length }} 个凭证{{ catalogConnected ? ' · 已连接 Control Plane' : ' · 服务未连接' }}</small></header><div class="responsive-table"><table><thead><tr><th>名称</th><th>Key</th><th>归属范围</th><th>模型权限</th><th>最近使用</th><th>状态</th><th></th></tr></thead><tbody><tr v-for="key in keys" :key="key.id"><td><div class="entity-cell"><span class="icon-tile violet"><KeyRound :size="16" /></span><div><strong>{{ key.name }}</strong><small>创建于 {{ key.createdAt }}</small></div></div></td><td><span class="code-value readonly" title="完整 Key 仅在创建时展示"><code>{{ key.value }}</code><ShieldCheck :size="14" /></span></td><td>{{ key.scope }}</td><td><button class="model-permission-summary" :disabled="key.status !== '正常'" @click="openModelPermissions(key)"><span>{{ key.modelIds.length ? `${key.modelIds.length} 个分组` : '未配置' }}</span><SlidersHorizontal :size="14" /></button></td><td>{{ key.lastUsed }}</td><td><span class="status-chip" :class="key.status === '正常' ? 'success' : 'muted'"><i></i>{{ key.status }}</span></td><td><button class="icon-button" :title="key.status === '正常' ? '停用 Key' : '重新启用 Key'" :disabled="keyBusy" @click="toggleKey(key)"><EyeOff v-if="key.status === '正常'" :size="16" /><Eye v-else :size="16" /></button><button class="icon-button" :title="key.status === '正常' ? '请先停用后再删除' : '删除 Key'" :disabled="keyBusy || key.status === '正常'" @click="deleteKeyTarget = key"><Trash2 :size="16" /></button></td></tr><tr v-if="!keys.length"><td colspan="7"><div class="empty-state compact"><KeyRound :size="22" /><strong>暂无 API Key</strong><span>创建后完整 Key 只会展示一次</span></div></td></tr></tbody></table></div></section>
|
||||
</template>
|
||||
|
||||
<template v-else-if="view === 'tasks'">
|
||||
<section class="page-heading"><div><span>ASYNC TASKS</span><h1>任务中心</h1><p>统一查看 3D、图像和视频等异步模型任务。</p></div><button class="button secondary" @click="emit('navigate', 'models')"><Plus :size="16" />新建任务</button></section>
|
||||
<section class="compact-metrics"><article><Clock3 :size="18" /><div><span>执行中</span><strong>{{ runningTaskCount }}</strong></div></article><article><FileClock :size="18" /><div><span>排队中</span><strong>{{ queuedTaskCount }}</strong></div></article><article><CheckCircle2 :size="18" /><div><span>已完成</span><strong>{{ completedTaskCount }}</strong></div></article><article><Timer :size="18" /><div><span>实时任务</span><strong>{{ tasks.filter((task) => task.remote).length }}</strong></div></article></section>
|
||||
<section class="panel table-card"><header class="panel-header table-toolbar"><div><span>TASK QUEUE</span><h3>当前会话任务</h3></div><div class="tabs compact"><button v-for="filter in ['全部','排队中','执行中','已完成','失败']" :key="filter" :class="{ active: taskFilter === filter }" @click="taskFilter = filter as '全部' | TaskStatus">{{ filter }}</button></div></header><div class="responsive-table"><table><thead><tr><th>任务</th><th>模型</th><th>进度</th><th>创建时间</th><th>状态</th></tr></thead><tbody><tr v-for="task in filteredTasks" :key="task.id" class="clickable" @click="selectedTask = task"><td><div class="entity-cell"><span class="icon-tile orange"><Box :size="16" /></span><div><strong>{{ task.name }}</strong><small>{{ task.id }}</small></div></div></td><td>{{ task.model }}</td><td><div class="progress-cell"><span><i :style="{ width: `${task.progress}%` }"></i></span><small>{{ task.progress }}%</small></div></td><td><div class="stacked-cell"><span>{{ task.createdAt }}</span><small>{{ task.duration }}</small></div></td><td><span class="status-chip" :class="task.status"><i></i>{{ task.status }}</span></td></tr><tr v-if="!filteredTasks.length"><td colspan="5"><div class="empty-state compact"><FileClock :size="22" /><strong>暂无任务</strong><span>提交异步模型后,任务会在这里显示</span></div></td></tr></tbody></table></div></section>
|
||||
<section class="page-heading"><div><span>USAGE HISTORY</span><h1>任务中心 · 使用记录</h1><p>查看模型调用与异步任务,按密钥、模型、分组和时间追踪用量。</p></div><button class="button secondary" @click="emit('navigate', 'playground')"><Play :size="16" />在线调试</button></section>
|
||||
<UsageHistory @notify="emit('notify', $event)" />
|
||||
</template>
|
||||
|
||||
<template v-else-if="view === 'usage'">
|
||||
@@ -549,6 +570,7 @@ MOYI_MODEL=<model-id></code></pre></div></section><section><b>02</b><div><
|
||||
<SlidePanel v-if="selectedModel" :title="selectedModel.name" eyebrow="MODEL DETAILS" @close="selectedModel = null"><div class="drawer-model-head"><span class="model-icon" :class="selectedModel.accent"><component :is="selectedModel.icon" :size="22" /></span><div><small>{{ selectedModel.provider }}</small><strong>{{ selectedModel.type }} · {{ selectedModel.mode }}调用</strong></div></div><p class="drawer-description">{{ selectedModel.description }}</p><div class="detail-health"><span class="status-chip" :class="selectedModel.availability === '在线' ? 'success' : 'muted'"><i></i>{{ selectedModel.availability }}</span><strong>{{ selectedModel.availability }}</strong></div><dl class="detail-list"><div><dt>模型名称</dt><dd><code>{{ selectedModel.id }}</code><button class="icon-button" title="复制模型名称" @click="copy(selectedModel.id, '模型名称', 'model-id')"><Check v-if="copySucceeded('model-id')" :size="14" /><Copy v-else :size="14" /></button></dd></div><div><dt>典型延迟</dt><dd>{{ selectedModel.latency }}</dd></div><div><dt>能力规格</dt><dd>{{ selectedModel.specification }}</dd></div><div><dt>调用模式</dt><dd>{{ selectedModel.mode }}</dd></div></dl><div class="drawer-note"><Info :size="16" /><span>{{ selectedModel.mode === '异步' ? '提交后进入任务队列,在任务中心查询进度与结果。' : '支持通过统一兼容接口直接调用。' }}</span></div><template #footer><button class="button primary full" @click="tryModel(selectedModel)"><Play :size="16" />在线试用</button><button class="button secondary full" @click="selectedModel = null; emit('navigate', 'docs')"><BookOpen :size="16" />查看文档</button></template></SlidePanel>
|
||||
<SlidePanel v-if="selectedTask" :title="selectedTask.name" eyebrow="TASK DETAILS" @close="selectedTask = null"><div v-if="selectedTask.videoUrl || selectedTask.previewUrl" class="drawer-task-preview"><video v-if="selectedTask.videoUrl" :src="selectedTask.videoUrl" controls></video><img v-else :src="selectedTask.previewUrl" alt="任务结果预览" /></div><div class="task-drawer-status"><span class="status-chip" :class="selectedTask.status"><i></i>{{ selectedTask.status }}</span><strong>{{ selectedTask.progress }}%</strong></div><div class="drawer-progress"><span><i :style="{ width: `${selectedTask.progress}%` }"></i></span><small>{{ selectedTask.result }}</small></div><dl class="detail-list"><div><dt>任务 ID</dt><dd><code>{{ selectedTask.id }}</code></dd></div><div><dt>模型</dt><dd>{{ selectedTask.model }}</dd></div><div v-if="selectedTask.provider"><dt>上游通道</dt><dd>{{ selectedTask.provider }}</dd></div><div v-if="selectedTask.creditsConsumed !== undefined"><dt>任务消耗</dt><dd>{{ selectedTask.creditsConsumed }} credits</dd></div><div><dt>创建时间</dt><dd>{{ selectedTask.createdAt }}</dd></div><div><dt>耗时</dt><dd>{{ selectedTask.duration }}</dd></div></dl><div v-if="selectedTask.prompt" class="drawer-note"><Info :size="16" /><span>{{ selectedTask.prompt }}</span></div><template #footer><button v-if="selectedTask.modelUrl" class="button primary full" @click="openTaskAsset(selectedTask.modelUrl)"><Download :size="16" />下载 GLB 模型</button><button v-if="selectedTask.videoUrl" class="button primary full" @click="openTaskAsset(selectedTask.videoUrl)"><ExternalLink :size="16" />打开生成视频</button><button class="button secondary full" @click="selectedTask = null">关闭详情</button></template></SlidePanel>
|
||||
|
||||
<UiModal v-if="deleteKeyTarget" title="删除 API Key" @close="!keyBusy && (deleteKeyTarget = undefined)"><p>确认删除「{{ deleteKeyTarget.name }}」?删除后无法重新启用,已有调用记录和任务会保留。</p><template #footer><button class="button secondary" :disabled="keyBusy" @click="deleteKeyTarget = undefined">取消</button><button class="button danger" :disabled="keyBusy" @click="deleteKey">{{ keyBusy ? '删除中…' : '确认删除' }}</button></template></UiModal>
|
||||
<UiModal v-if="createKeyOpen" title="创建 API Key" eyebrow="NEW CREDENTIAL" @close="createKeyOpen = false"><p class="modal-description">个人 Key 适合个人开发调试,项目 Key 适合服务端应用和团队协作。创建后再配置该 Key 可调用的具体模型。</p><label class="form-label">Key 名称</label><input v-model="keyName" class="text-input" placeholder="例如:生产环境" /><label class="form-label">Key 归属</label><div class="option-list"><button :class="{ active: keyScopeType === 'personal' }" @click="keyScopeType = 'personal'"><span><i></i><strong>个人 Key</strong><small>归属当前账号</small></span><Check v-if="keyScopeType === 'personal'" :size="16" /></button><button :class="{ active: keyScopeType === 'project' }" @click="keyScopeType = 'project'"><span><i></i><strong>项目 Key</strong><small>归属工作区/项目</small></span><Check v-if="keyScopeType === 'project'" :size="16" /></button></div><div v-if="keyScopeType === 'project'"><label class="form-label"><span>选择项目</span><button class="text-link" type="button" @click="openProjectModal">新建项目</button></label><select v-model="selectedProjectId" class="text-input"><option value="" disabled>请选择项目</option><option v-for="project in projects" :key="project.id" :value="project.id">{{ project.name }}</option></select></div><div class="permission-hint"><ShieldCheck :size="16" /><span>Key 创建后默认不开放模型权限,请在下一步选择具体可调用模型。</span></div><template #footer><button class="button secondary" @click="createKeyOpen = false">取消</button><button class="button primary" @click="createKey"><KeyRound :size="16" />生成 Key</button></template></UiModal>
|
||||
<UiModal v-if="secretOpen" title="请立即保存你的 Key" eyebrow="CREDENTIAL CREATED" @close="secretOpen = false"><div class="secret-success"><CheckCircle2 :size="25" /><strong>API Key 创建成功</strong></div><p class="modal-description centered">完整 Key 只展示一次,关闭后无法再次查看。保存后继续配置模型权限。</p><div class="secret-box"><code>{{ revealSecret ? createdSecret : `${createdSecret.slice(0, 10)}••••••••••••` }}</code><button title="显示或隐藏 Key" @click="revealSecret = !revealSecret"><EyeOff v-if="revealSecret" :size="16" /><Eye v-else :size="16" /></button><button title="复制完整 Key" @click="copy(createdSecret, 'API Key', 'secret-key')"><Check v-if="copySucceeded('secret-key')" :size="16" /><Copy v-else :size="16" /></button></div><template #footer><button class="button secondary" @click="secretOpen = false; revealSecret = false">稍后配置</button><button class="button primary" @click="openCreatedKeyPermissions"><SlidersHorizontal :size="16" />配置可调用模型</button></template></UiModal>
|
||||
<UiModal v-if="projectOpen" title="新建工作区 / 项目" eyebrow="NEW PROJECT" @close="projectOpen = false"><p class="modal-description">项目用于归属团队 Key,并为后续用量、额度和权限隔离预留空间。</p><label class="form-label">项目名称</label><input v-model="projectName" class="text-input" placeholder="例如:AI SoulMate 研发项目" @keyup.enter="createProject" /><label class="form-label">项目描述(可选)</label><textarea v-model="projectDescription" class="text-input modal-textarea" placeholder="描述项目用途或成员范围"></textarea><template #footer><button class="button secondary" @click="projectOpen = false">取消</button><button class="button primary" @click="createProject"><Plus :size="16" />创建项目</button></template></UiModal>
|
||||
|
||||
Reference in new issue
Block a user