feat(后管): 密钥管理拆两列显示余额(LLM 人民币余额/代理余量),实时查不落库

按拍板:数据源=实时查上游不落库(⇒ 本窗零 Flyway、零 Schema);列形态=拆两列,不是一列两行——
两张货源字典本就互不相通(LLM 行为渠道 longtaitou/t8star,代理行为供应商 qingguo/jikip),合成一格
就是 11-02 那次"代理行贴出龙抬头"的串档形状重来一遍(铁律 25)。不加 v-if="isSuperAdmin":主管必须
能解释组员任务为什么挂欠费,鉴权维持 requireAdmin + DataReadScope。

- src/api/user-secrets.ts:fetchAdminSecretBalances(userIds, companyId?),POST /api/admin/user-secrets/balances,
  超时放宽到 30s(服务端整请求预算 10s,客户端必须比它长,否则拿到的是本地掐断而不是"上游未应答")。
- user-secret-model.ts:llmBalanceLines/proxyBalanceLine 纯函数——**两张字典各查各的**、跨域一律 —、
  未知渠道只出 — 不出钱;available=false 时把 message 挂进 title 而不是画成 0;同一账号两个模块归到
  同一个渠道名下只列一次钱。保持零 @/ 别名以便 node --test 直测。
- UserSecretsPage.vue:两个 <th>(LLM 余额 170px/代理余量 160px,放「更新时间」前),两个 <td> 首屏画 —/查询中,
  列表返回后异步填(不阻塞首屏);colspan 由 isSuperAdmin ? 10 : 9 改成 12 : 11(两处同改,892d88ed 的提交信息
  专门写过这句);表格 min-width 相应 +240px;「刷新余额」按钮按 BALANCE_BATCH=20 分批请求。
- 已核对 ops-cell-must-wrap.test.ts:它的 opsColDecl() 正则锚在表头文字「操作」上,新增 <th> 排在它之前不影响
  UserSecretsPage: 314 下限 ⇒ 那张表不改(实测绿)。
- mock-admin-server.mjs 补两列夹具(一条有数、一条全查不到)供 dev/e2e。

测试:tests/密钥余额列读数.test.ts 12 例(跨域不认、坏值不画 0)+
tests/mount/user-secret-balance-columns.mount.test.ts 9 例——按表头文字定位不靠列序数,并钉 <th> 数=<td> 数=
空行 colspan(超管与非超管两种形状各一遍),把"加列忘改 colspan"直接钉死。既有 status-band 挂载格的夹具 mock
补一个 fetchAdminSecretBalances 函数名(页面挂载即取余额,缺它整个模块 mock 会炸),不是判据改动。
刻意不新增 readSource 钉 ⇒ 不动 tests/baselines/source-pin-ledger.json。vue-tsc rc=0、node --test 1890 例、vitest 77 例。
This commit is contained in:
2026-11-05 12:03:43 +08:00
parent a10aa6bda3
commit cc22600a07
7 changed files with 695 additions and 3 deletions
@@ -499,6 +499,32 @@ const server = createServer((req, res) => {
},
})
}
if (url === '/api/admin/user-secrets/balances') {
// 余额侧写夹具(POST):两把密钥同渠道 ⇒ 界面折叠成一行;代理给「你的套餐」形状
const llmCell = (moduleKey, moduleLabel, over = {}) => ({
moduleKey, moduleLabel,
channel: 'longtaitou', channelLabel: '龙抬头',
available: true, balance: '88.888882', availableBalance: '85.288882', frozen: '3.6',
unit: 'CREDIT', message: null, checkedAt: '2026-11-05T10:30:00', ...over,
})
return json(res, {
success: true,
data: {
items: [
{
userId: 1,
llm: [
llmCell('appearance-patent', '外观专利密钥'),
llmCell('similar-asin', '货源查询密钥'),
],
proxy: { available: true, surplus: '1234', balance: '56', scope: 'user', message: null },
},
],
deniedUserIds: [],
timedOutUserIds: [],
},
})
}
if (url === '/api/admin/shop-manage-groups') {
return json(res, { success: true, data: { items: [] } })
}
@@ -63,6 +63,53 @@ export interface GroupOption {
groupName: string
}
/**
* LLM 一格的余额(**人民币口径**,后端取龙抬头 `credits` 块)。
* 与 `AdminProxyBalanceCell` 是两套语义:这里的 `balance` 是钱、单位 CREDIT(=⚡=人民币),
* 代理那边的 `surplus` 是「次」。界面不得用一张函数渲染两域(同 `channel` 那张表的教训)。
*/
export interface AdminLlmBalanceCell {
moduleKey: string
moduleLabel: string
channel: string
channelLabel: string
available: boolean
/** 上游原样小数串(未取整);available=false 时为 null。 */
balance: string | null
availableBalance: string | null
frozen: string | null
/** 恒为 CREDIT;不是这个值就按「认不出口径」处理,不猜。 */
unit: string | null
message: string | null
checkedAt: string | null
}
/** 代理余量一格:jikip 套餐口径(`surplus`=IP 次数、`scope`=谁的池子)。青果为 scope=none。 */
export interface AdminProxyBalanceCell {
available: boolean
surplus: string | null
balance: string | null
/** user=该用户自己的套餐;platform=平台池子(不是这个用户的钱);none=查不了。 */
scope: string | null
message: string | null
low?: boolean
lowReason?: string | null
}
export interface AdminUserSecretBalanceItem {
userId: number
llm: AdminLlmBalanceCell[]
proxy: AdminProxyBalanceCell
}
export interface AdminUserSecretBalances {
items: AdminUserSecretBalanceItem[]
/** 被数据权限剔出、本次没查的用户(不静默少给数)。 */
deniedUserIds?: number[]
/** 超出整请求时间预算、这轮没取到数的用户。 */
timedOutUserIds?: number[]
}
export interface UserSecretQuery {
keyword?: string
checkStatus?: string
@@ -87,6 +134,23 @@ export async function fetchUserSecretList(params: UserSecretQuery): Promise<Admi
return unwrap<AdminUserSecretPage>(data)
}
/**
* 刷新本页用户的余额侧写:POST /api/admin/user-secrets/balances。
*
* 实时打上游、不落库,所以服务端带三条护栏(单次 ≤20 个用户、固定并发、整请求 10s 预算),
* 客户端的超时必须**长于**服务端预算,否则服务端还在取数、这边先报错,
* 界面就会把「查得慢」显示成「查不到」(与铁律 10「前端超时不得短于服务端预算」同形)。
*/
export async function fetchAdminSecretBalances(
userIds: number[],
companyId?: number | null,
): Promise<AdminUserSecretBalances> {
const body: Record<string, unknown> = { userIds }
if (companyId != null) body.company_id = companyId
const { data } = await http.post('/api/admin/user-secrets/balances', body, { timeout: 30_000 })
return unwrap<AdminUserSecretBalances>(data)
}
/** 立即检测该用户全部已配置项:POST /api/admin/user-secrets/{userId}/check
* 逐模块检测(每项最多「首查 + 传输层失败重试一次」,最坏约 31s/项),故放宽超时到 180s。 */
export async function checkUserSecret(userId: number) {
@@ -8,15 +8,19 @@ import {
checkUserSecret,
clearUserSecretModule,
deleteUserSecret,
fetchAdminSecretBalances,
fetchUserSecretList,
type AdminUserSecretBalanceItem,
type AdminUserSecretModule,
type AdminUserSecretRow,
type GroupOption,
} from '@/api/user-secrets'
import {
PROXY_MODULE_KEY,
llmBalanceLines,
llmSourceLabel,
moduleStatusBand,
proxyBalanceLine,
proxyDisplayText,
proxySourceLabel,
rowDetailLines,
@@ -51,6 +55,14 @@ const proxyBusyId = ref<number | null>(null)
/** 代填/改代理弹窗的目标行(脱敏后没有原文可预填,只能重填账密)。 */
const proxyDialog = ref<{ userId: number; username: string; provider: string | null; locked: boolean } | null>(null)
/** 余额侧写(实时查上游、不落库):按 userId 存,列表接口本身不带这些数。 */
const balances = ref<Record<number, AdminUserSecretBalanceItem>>({})
const balanceLoading = ref(false)
/** 本轮「没取到」的原因(越权剔除/上游未应答/请求失败):进工具行悬停,不弹全局打扰。 */
const balanceNotice = ref('')
/** 服务端单次上限 20 个用户;超出会被当场拒,所以这里按批顺取(并发留给服务端那个线程池)。 */
const BALANCE_BATCH = 20
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
const STATUS_OPTIONS = [
@@ -131,6 +143,7 @@ async function load() {
rows.value = result?.items || []
total.value = Number(result?.total || 0)
groupOptions.value = result?.groupOptions || []
void loadBalances()
} catch (error) {
loadFailure.value = error instanceof Error ? error.message : '加载失败'
showAdminFeedback(loadFailure.value, 'error')
@@ -139,6 +152,57 @@ async function load() {
}
}
/**
* 取本页用户的余额:列表已经画完,这两列随后填(余额要实时打上游,不能让它在列表主数据前占位)。
*
* 失败只影响这两列并留一句说明——不 `showAdminFeedback`、不把整页判成加载失败:
* 一次上游抖动就红整页,管理员会以为密钥数据本身出了问题。
*/
async function loadBalances() {
const ids = rows.value.map((row) => row.userId)
balances.value = {}
balanceNotice.value = ''
if (!ids.length) return
balanceLoading.value = true
try {
const merged: Record<number, AdminUserSecretBalanceItem> = {}
let denied = 0
let timedOut = 0
for (let start = 0; start < ids.length; start += BALANCE_BATCH) {
const batch = ids.slice(start, start + BALANCE_BATCH)
const result = await fetchAdminSecretBalances(batch, companyTab.requestCompanyId)
for (const item of result?.items || []) {
if (item && item.userId != null) merged[Number(item.userId)] = item
}
denied += result?.deniedUserIds?.length || 0
timedOut += result?.timedOutUserIds?.length || 0
}
balances.value = merged
const notices: string[] = []
if (denied) notices.push(`${denied} 个用户不在当前数据权限内,本轮未查`)
if (timedOut) notices.push(`${timedOut} 个用户本轮上游未应答(不是余额为 0)`)
balanceNotice.value = notices.join(';')
} catch (error) {
balanceNotice.value = error instanceof Error ? error.message : '余额本轮没取到(不是余额为 0)'
} finally {
balanceLoading.value = false
}
}
/** 某行的 LLM 余额行(按渠道折叠);没取到时给一格占位而不是空白。 */
function llmLinesOf(userId: number) {
const lines = llmBalanceLines(balances.value[userId]?.llm, balanceLoading.value)
return lines.length ? lines : [{ text: '—', title: balanceNotice.value || '本轮没取到数(不是余额为 0)' }]
}
function proxyLineOf(userId: number) {
const item = balances.value[userId]
if (item?.proxy) return proxyBalanceLine(item.proxy, false)
return balanceLoading.value
? { text: '查询中…', title: '余额按实时查询,不落库' }
: { text: '—', title: balanceNotice.value || '本轮没取到数(不是余量为 0)' }
}
// 切公司 = 重新取数。不重取的页 = tab 在那页上是假的(G1 的 pageFiles 断言盯着这条)。
watch(() => companyTab.activeId, () => void load())
@@ -276,6 +340,15 @@ onMounted(load)
<div class="filter-actions">
<button class="btn" type="button" @click="search">查询</button>
<button class="btn btn-ghost" type="button" @click="reset">重置</button>
<button
class="btn btn-ghost"
type="button"
:disabled="balanceLoading || !rows.length"
:title="balanceNotice || '余额是实时查上游、不落库;这两列没取到时显示 —,不是 0'"
@click="loadBalances"
>
{{ balanceLoading ? '余额查询中…' : '刷新余额' }}
</button>
</div>
</div>
</div>
@@ -290,7 +363,9 @@ onMounted(load)
<th v-if="isSuperAdmin" style="width: 130px">分组</th>
<th style="width: 230px">货源查询密钥</th>
<th style="width: 230px">外观专利密钥</th>
<th style="width: 170px">LLM 余额</th>
<th style="width: 380px">代理设置</th>
<th style="width: 160px">代理余量</th>
<th style="width: 130px">状态</th>
<th style="width: 170px">创建时间</th>
<th style="width: 170px">更新时间</th>
@@ -331,6 +406,16 @@ onMounted(load)
</span>
</div>
</td>
<td>
<div class="module-cell module-cell--stack">
<span
v-for="(line, lineIndex) in llmLinesOf(row.userId)"
:key="`llm-${lineIndex}`"
class="balance-line"
:title="line.title"
>{{ line.text }}</span>
</div>
</td>
<td>
<div class="module-cell module-cell--stack">
<span v-if="row.proxy?.exists" class="mono-mask" :title="moduleTooltip(row.proxy)">{{ proxyDisplayText(row.proxy) }}</span>
@@ -352,6 +437,13 @@ onMounted(load)
</span>
</div>
</td>
<td>
<div class="module-cell module-cell--stack">
<span class="balance-line" :title="proxyLineOf(row.userId).title">
{{ proxyLineOf(row.userId).text }}
</span>
</div>
</td>
<td>
<span class="wh-pill" :class="rowStatusBand(row).tone" :title="rowStatusTooltip(row)">
{{ rowStatusBand(row).label }}
@@ -389,10 +481,10 @@ onMounted(load)
</tr>
</template>
<tr v-else-if="loading">
<td :colspan="isSuperAdmin ? 10 : 9" class="empty-tip">加载中...</td>
<td :colspan="isSuperAdmin ? 12 : 11" class="empty-tip">加载中...</td>
</tr>
<tr v-else>
<td :colspan="isSuperAdmin ? 10 : 9" class="empty-tip">{{ keyword || statusFilter || groupFilter ? '暂无匹配记录' : '暂无用户密钥记录' }}</td>
<td :colspan="isSuperAdmin ? 12 : 11" class="empty-tip">{{ keyword || statusFilter || groupFilter ? '暂无匹配记录' : '暂无用户密钥记录' }}</td>
</tr>
</tbody>
</table>
@@ -616,6 +708,16 @@ h3 {
.empty-value {
color: #a7b4c1;
}
/* 余额列:数字按等宽数位对齐(两行叠着看差值才不用竖着对),超长进 title。 */
.balance-line {
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-variant-numeric: tabular-nums;
font-size: 12.5px;
color: #2f4256;
}
.ops-cell {
display: flex;
gap: 8px;
@@ -1,7 +1,7 @@
/**
* 密钥管理页的纯逻辑模型(货源标签 + 代理重填 + 检测结果档位)。
*
* 三条收口都在这个文件里,页模板只调这里导出的函数,不各写各的字典:
* 四条收口都在这个文件里,页模板只调这里导出的函数,不各写各的字典:
*
* 1. **货源标签按模块分字典**(2026-11-02 修):原先 `UserSecretsPage.vue` 里是一整张
* `sourceLabel()`,把 LLM 渠道(longtaitou/t8star)与代理供应商(qingguo/jikip)混在同一个
@@ -312,3 +312,152 @@ export function buildProxyEntryPayload(
}
return { value: String(draft.link || '').trim(), channel: 'jikip' }
}
/* ------------------------------------------------------------------ *
* 余额侧写(2026-11-05 B83):第四处收口,仍守「两张字典互不相通」那一条。
*
* LLM 那格的单位是**钱**(人民币=龙抬头站内 ⚡,后端只取 `credits` 块),
* 代理那格的 `surplus` 是**次数**、`scope` 说这份量属于谁的池子。
* 两者都叫「余额」,混用一张函数就会读出「极客 ¥34」这种既不像钱也不像次的数——
* 所以这里各写各的,跨域字段一个都不读,认不出来一律 `—`(同货源标签那条判据)。
* ------------------------------------------------------------------ */
/** 后端 credits 块登记的单位;不是这个值就说明口径换了,宁可不显示也不猜。 */
export const LLM_BALANCE_UNIT = 'CREDIT'
interface LlmBalanceLike {
moduleKey?: string | null
moduleLabel?: string | null
channel?: string | null
channelLabel?: string | null
available?: boolean | null
balance?: string | null
availableBalance?: string | null
frozen?: string | null
unit?: string | null
message?: string | null
checkedAt?: string | null
}
interface ProxyBalanceLike {
available?: boolean | null
surplus?: string | null
balance?: string | null
scope?: string | null
message?: string | null
}
/** 一行的显示内容:`text` 进格子,`title` 进悬停(整句原因与取数时刻都在那儿)。 */
export interface BalanceLine {
text: string
title: string
}
const BALANCE_PLACEHOLDER: BalanceLine = { text: UNKNOWN_SOURCE_LABEL, title: '本轮没取到数(不是余额为 0)' }
const BALANCE_PENDING: BalanceLine = { text: '查询中…', title: '余额按实时查询,不落库' }
/** 人民币读数:解析不出数字时原样回显,不返回 `¥0`(一格 0 会被读成「没钱了」)。 */
export function formatYuan(raw: string | null | undefined): string {
const text = String(raw ?? '').trim()
if (!text) return ''
const value = Number(text.replace(/,/g, ''))
if (!Number.isFinite(value)) return text
return `¥${value.toFixed(2)}`
}
function llmDetail(cell: LlmBalanceLike): string {
const parts: string[] = []
if (cell.moduleLabel) parts.push(String(cell.moduleLabel))
const total = formatYuan(cell.balance)
const usable = formatYuan(cell.availableBalance)
const frozen = formatYuan(cell.frozen)
if (total) parts.push(`总 ${total}`)
if (usable) parts.push(`可用 ${usable}`)
if (frozen) parts.push(`预冻结 ${frozen}`)
if (cell.checkedAt) parts.push(`取数于 ${String(cell.checkedAt).replace('T', ' ').slice(0, 16)}`)
const message = String(cell.message ?? '').trim()
if (message) parts.push(message)
return parts.join(';') || '暂无余额信息'
}
/**
* LLM 余额列:一把密钥一行,前缀是**渠道名**(钱挂在渠道账户上,不在模块上)。
*
* `pending=true` ⇒ 这一轮还在取数;取到但不合格(单位不是 CREDIT/available=false)
* 一律走占位与后端原文,不显示金额。
*/
export function llmBalanceLine(cell: LlmBalanceLike | null | undefined, pending = false): BalanceLine {
if (pending && !cell) return BALANCE_PENDING
if (!cell) return BALANCE_PLACEHOLDER
const label = known(LLM_CHANNEL_LABELS, cell.channel) ?? UNKNOWN_SOURCE_LABEL
// 渠道认不出(LLM 列被喂了供应商名这类跨域值)时整格给占位:宁可什么都不显示,
// 也不让一个不知道属于谁的数字或句子进界面(同货源标签那张表「跨域一律 —」的判据)
if (label === UNKNOWN_SOURCE_LABEL) {
return { text: UNKNOWN_SOURCE_LABEL, title: `${llmDetail(cell)}|渠道值认不出,未显示金额` }
}
if (!cell.available || String(cell.unit ?? '').trim().toUpperCase() !== LLM_BALANCE_UNIT) {
const message = String(cell.message ?? '').trim()
return { text: message ? `${label} 查不到` : `${label} ${UNKNOWN_SOURCE_LABEL}`, title: llmDetail(cell) }
}
const total = formatYuan(cell.balance)
if (!total) return { text: `${label} ${UNKNOWN_SOURCE_LABEL}`, title: llmDetail(cell) }
return { text: `${label} ${total}`, title: llmDetail(cell) }
}
/**
* LLM 余额列的整格内容:**按渠道折叠**,一个渠道一行。
*
* 钱挂在渠道账户上、不挂在模块上:两把密钥(外观专利/货源查询)都在龙抬头时,
* 上游回的是同一个余额——排两遍会读成「这个账户有两笔钱」。折叠后 title 里仍留每一把的原文,
* 运维要判「是哪把密钥的渠道」看得回来。
*/
export function llmBalanceLines(
cells: Array<LlmBalanceLike | null | undefined> | null | undefined,
pending = false,
): BalanceLine[] {
const list = (cells ?? []).filter((cell): cell is LlmBalanceLike => Boolean(cell))
if (!list.length) return pending ? [BALANCE_PENDING] : []
const grouped = new Map<string, BalanceLine>()
for (const cell of list) {
const key = normalizeKey(cell.channel) || 'unknown'
const line = llmBalanceLine(cell, pending)
const hit = grouped.get(key)
grouped.set(key, hit ? { text: hit.text, title: `${hit.title}|${line.title}` } : line)
}
return [...grouped.values()]
}
/** 代理池子的归属说法:platform 那份是**平台的钱**,绝不允许被读成这个用户的余量。 */
const PROXY_SCOPE_LABELS: Record<string, string> = {
user: '你的套餐',
platform: '平台池',
none: '查不了',
}
/**
* 代理余量列:极客给「剩余 IP 次数」(单位是次、不是钱);青果按 scope=none 说查不了。
* `scope` 认不出来时不硬认(回落「来源未标注」并保留原值进 title 供运维核)。
*/
export function proxyBalanceLine(cell: ProxyBalanceLike | null | undefined, pending = false): BalanceLine {
if (pending && !cell) return BALANCE_PENDING
if (!cell) return BALANCE_PLACEHOLDER
const scopeKey = normalizeKey(cell.scope)
const scopeLabel = Object.prototype.hasOwnProperty.call(PROXY_SCOPE_LABELS, scopeKey)
? PROXY_SCOPE_LABELS[scopeKey]
: '来源未标注'
const message = String(cell.message ?? '').trim()
const detailParts = [`${scopeLabel}`]
const surplus = String(cell.surplus ?? '').trim()
const amount = String(cell.balance ?? '').trim()
if (surplus) detailParts.push(`剩余 IP ${surplus}`)
if (amount) detailParts.push(`账户余额 ${amount}`)
if (message) detailParts.push(message)
const title = detailParts.join(';') || '暂无余量信息'
if (!cell.available) {
// 后端那句原文(「青果不提供余量查询…」「上游未在预算内应答…」)全在 title 里;
// 格子只说「查不了」——留 `—` 会被读成「这人没配代理」,那是另一件事。
return { text: message ? '查不了' : `${scopeLabel} ${UNKNOWN_SOURCE_LABEL}`, title }
}
// 次数就是次数:这里不套 ¥ 符号、不换算,读数带「次」把单位写在格子里
return { text: `${scopeLabel} ${surplus || UNKNOWN_SOURCE_LABEL} 次`, title }
}
@@ -0,0 +1,210 @@
/**
* 密钥管理列表页「余额两列」的界面侧判据(2026-11-05 B83)。
*
* 读数本身在 `user-secret-model.ts` 里被那颗纯函数尺子钉着;这一支管的是**接上去的形状**:
* ① 两列都在,且 `<th>` 数=每行 `<td>` 数=空态行的 colspan —— 加列忘改 colspan 是本仓常踩的残行,
* 历史上专门为此写过提交说明,所以这里把它钉成算术关系而不是逐个数字;
* ② 有数时 LLM 列给人民币、代理列给次数,两者不混;
* ③ 整轮没取到时两列都是 `—`,**不是 0**(一格 0 会被读成「这人欠费了」);
* ④ 非超管少一列「分组」时,上述三个数仍然彼此相等。
*
* 跑法:`npx vitest run tests/mount/user-secret-balance-columns.mount.test.ts`
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { createPinia, setActivePinia, type Pinia } from 'pinia'
import UserSecretsPage from '@/pages/account/UserSecretsPage.vue'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
const secretsApi = vi.hoisted(() => ({
fetchUserSecretList: vi.fn(),
fetchAdminSecretBalances: vi.fn(),
checkUserSecret: vi.fn(),
deleteUserSecret: vi.fn(),
saveUserSecretModule: vi.fn(),
clearUserSecretModule: vi.fn(),
}))
vi.mock('@/api/user-secrets', () => secretsApi)
function moduleCell(moduleKey: string, over: Record<string, unknown> = {}) {
return {
moduleKey, moduleLabel: moduleKey, channel: null,
masked: 'sk-f****9BgQ', full: '', exists: true, locked: false,
checkStatus: 'passed', checkCode: 'ok', checkMessage: '连通正常',
checkLatencyMs: 12, checkedAt: '2026-11-05T10:30:00', updatedAt: '2026-11-05T10:30:00',
...over,
}
}
function row(userId: number, over: Record<string, unknown> = {}) {
return {
userId,
username: `user${userId}`,
groups: [],
leaderUsername: '',
similarAsin: moduleCell('similar-asin', { moduleLabel: '货源查询密钥', channel: 'longtaitou' }),
appearancePatent: moduleCell('appearance-patent', { moduleLabel: '外观专利密钥', channel: 'longtaitou' }),
proxy: moduleCell('proxy', { moduleLabel: '代理设置', channel: 'jikip' }),
status: 'passed',
statusMessage: '三项均检测通过',
createdAt: '2026-11-01T09:00:00',
updatedAt: '2026-11-05T10:30:00',
...over,
}
}
function llmCells(userId: number) {
return [
{
moduleKey: 'appearance-patent', moduleLabel: '外观专利密钥',
channel: 'longtaitou', channelLabel: '龙抬头',
available: true, balance: '88.888882', availableBalance: '85.288882', frozen: '3.6',
unit: 'CREDIT', message: null, checkedAt: '2026-11-05T10:30:00',
},
{
moduleKey: 'similar-asin', moduleLabel: '货源查询密钥',
channel: 'longtaitou', channelLabel: '龙抬头',
available: true, balance: '88.888882', availableBalance: '85.288882', frozen: '3.6',
unit: 'CREDIT', message: null, checkedAt: '2026-11-05T10:30:00',
},
].map((cell) => (userId === 7 ? cell : { ...cell, balance: '12.5', availableBalance: '10', frozen: null }))
}
function indexByHeader(wrapper: VueWrapper<Element>, header: string) {
const headers = wrapper.findAll('thead th').map((th) => th.text().trim())
const index = headers.findIndex((label) => label.includes(header))
expect(index, `表头里找不到「${header}」`).toBeGreaterThanOrEqual(0)
return index
}
function cellText(wrapper: VueWrapper<Element>, header: string, rowIndex = 0): string {
const index = indexByHeader(wrapper, header)
return wrapper.findAll('tbody tr')[rowIndex].findAll('td')[index].text().trim()
}
function cellTitle(wrapper: VueWrapper<Element>, header: string, rowIndex = 0): string {
const index = indexByHeader(wrapper, header)
const cell = wrapper.findAll('tbody tr')[rowIndex].findAll('td')[index]
return cell.find('.balance-line').attributes('title') ?? ''
}
let pinia: Pinia
beforeEach(() => {
vi.clearAllMocks()
pinia = createPinia()
setActivePinia(pinia)
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
useCompanyTabStore().setActiveId(1)
})
async function mountWith(rowValues: unknown[], balances?: unknown) {
secretsApi.fetchUserSecretList.mockResolvedValue({
items: rowValues, total: rowValues.length, page: 1, pageSize: 15, groupOptions: [],
})
secretsApi.fetchAdminSecretBalances.mockResolvedValue(
balances === undefined
? { items: rowValues.map((item: any) => ({ userId: item.userId, llm: llmCells(item.userId), proxy: { available: true, surplus: '1234', balance: '56', scope: 'user', message: null } })), deniedUserIds: [], timedOutUserIds: [] }
: balances,
)
const wrapper = mount(UserSecretsPage, { global: { plugins: [pinia] } })
await flushPromises()
await flushPromises()
return wrapper
}
describe('余额两列接在密钥管理列表上', () => {
it('表头数=行内格数=空态 colspan(加列忘改 colspan 直接红)', async () => {
const wrapper = await mountWith([row(7)])
const headerCount = wrapper.findAll('thead th').length
const cellCount = wrapper.findAll('tbody tr')[0].findAll('td').length
expect(cellCount, '每行的 td 数必须等于表头列数').toBe(headerCount)
expect(headerCount).toBe(12)
const emptyWrapper = await mountWith([])
const colspan = Number(emptyWrapper.find('tbody td').attributes('colspan'))
expect(colspan, '空态行的 colspan 必须跟着列数走').toBe(headerCount)
})
it('非超管少一列分组时,三个数仍然彼此相等', async () => {
useAdminSessionStore().user = { id: 2, username: 'leader', role: 'admin' }
const wrapper = await mountWith([row(7)])
const headerCount = wrapper.findAll('thead th').length
expect(headerCount).toBe(11)
expect(wrapper.findAll('tbody tr')[0].findAll('td').length).toBe(headerCount)
const emptyWrapper = await mountWith([])
expect(Number(emptyWrapper.find('tbody td').attributes('colspan'))).toBe(headerCount)
})
it('LLM 列给人民币读数,按渠道折成一行(同一个钱不排两遍)', async () => {
const wrapper = await mountWith([row(7)])
expect(cellText(wrapper, 'LLM 余额')).toBe('龙抬头 ¥88.89')
expect(cellTitle(wrapper, 'LLM 余额')).toContain('外观专利密钥')
expect(cellTitle(wrapper, 'LLM 余额')).toContain('货源查询密钥')
expect(cellTitle(wrapper, 'LLM 余额')).toContain('取数于 2026-11-05 10:30')
})
it('代理列给次数并说清是谁的池子,不套 ¥', async () => {
const wrapper = await mountWith([row(7)])
const text = cellText(wrapper, '代理余量')
expect(text).toContain('你的套餐')
expect(text).toContain('1234 次')
expect(text).not.toContain('¥')
})
it('两列各读各的:LLM 列里不出现次数、代理列里不出现金额', async () => {
const wrapper = await mountWith([row(7)])
expect(cellText(wrapper, 'LLM 余额')).not.toMatch(/\d+\s*次/)
expect(cellText(wrapper, '代理余量')).not.toContain('¥')
})
it('整轮没取到时两列都是 —,一格都不许是 0', async () => {
const wrapper = await mountWith([row(7)], { items: [], deniedUserIds: [7], timedOutUserIds: [] })
expect(cellText(wrapper, 'LLM 余额')).toBe('—')
expect(cellText(wrapper, '代理余量')).toBe('—')
expect(cellText(wrapper, 'LLM 余额')).not.toContain('0.00')
})
it('超预算的行说「本轮未应答」,不冒充欠费', async () => {
const wrapper = await mountWith([row(7)], {
items: [{ userId: 7, llm: [], proxy: { available: false, surplus: null, balance: null, scope: null, message: '上游未在本轮时间预算内应答,稍后重试;这不代表余量为 0' } }],
deniedUserIds: [],
timedOutUserIds: [7],
})
expect(cellText(wrapper, 'LLM 余额')).toBe('—')
expect(cellText(wrapper, '代理余量')).toBe('查不了')
expect(cellTitle(wrapper, '代理余量')).toContain('不代表余量为 0')
})
it('余额接口整个失败也不把整页判成加载失败', async () => {
secretsApi.fetchUserSecretList.mockResolvedValue({ items: [row(7)], total: 1, page: 1, pageSize: 15, groupOptions: [] })
secretsApi.fetchAdminSecretBalances.mockRejectedValue(new Error('上游 502'))
const wrapper = mount(UserSecretsPage, { global: { plugins: [pinia] } })
await flushPromises()
await flushPromises()
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
expect(wrapper.find('.load-failure-bar').exists(), '列表主数据在,就不该把整页报成加载失败').toBe(false)
expect(cellText(wrapper, 'LLM 余额')).toBe('—')
})
it('点「刷新余额」重取一轮,不动列表请求', async () => {
const wrapper = await mountWith([row(7)])
const listCalls = secretsApi.fetchUserSecretList.mock.calls.length
await wrapper.findAll('.filter-actions button').at(-1)!.trigger('click')
await flushPromises()
expect(secretsApi.fetchAdminSecretBalances).toHaveBeenCalledTimes(2)
expect(secretsApi.fetchUserSecretList).toHaveBeenCalledTimes(listCalls)
})
})
@@ -25,6 +25,7 @@ import { useCompanyTabStore } from '@/stores/company-tab'
const secretsApi = vi.hoisted(() => ({
fetchUserSecretList: vi.fn(),
fetchAdminSecretBalances: vi.fn(),
checkUserSecret: vi.fn(),
deleteUserSecret: vi.fn(),
saveUserSecretModule: vi.fn(),
@@ -0,0 +1,140 @@
/**
* 密钥管理页「余额两列」的读数判据(2026-11-05 B83)。
*
* 靶子是口径与归属,不是排版:
* ① LLM 那格只认 `unit=CREDIT`(人民币=龙抬头 ⚡),认不出就一律 `—`,不猜、不给 0;
* ② 两把密钥同属一个渠道账户时**折成一行**(同一个钱排两遍会被读成两笔钱);
* ③ 代理那格的 `surplus` 是**次数**,读数带「次」不带 `¥`;`scope=platform` 必须说清是平台池,
* 不许被读成这个用户自己的量(铁律 25 的串档形状);
* ④ 查不到 ≠ 没钱:`available=false` 与「整格没取到」都得出可分辨的文字。
*
* 跑法:`cd crawler-plugin/admin-frontend-vue && npm test`
*/
import test from 'node:test'
import assert from 'node:assert/strict'
import {
formatYuan,
llmBalanceLine,
llmBalanceLines,
proxyBalanceLine,
} from '../src/pages/account/user-secret-model.ts'
function llmCell(over: Record<string, unknown> = {}) {
return {
moduleKey: 'appearance-patent',
moduleLabel: '外观专利密钥',
channel: 'longtaitou',
channelLabel: '龙抬头',
available: true,
balance: '88.888882',
availableBalance: '85.288882',
frozen: '3.6',
unit: 'CREDIT',
message: null,
checkedAt: '2026-11-05T10:30:00',
...over,
}
}
test('人民币读数保留两位且不提前取整', () => {
assert.equal(formatYuan('88.888882'), '¥88.89')
assert.equal(formatYuan('0'), '¥0.00')
assert.equal(formatYuan(''), '')
assert.equal(formatYuan(null), '')
// 认不出数字时原样回显,不套 ¥(套了就是宣称它是人民币)
assert.equal(formatYuan('$12.345678'), '$12.345678')
})
test('LLM 一行给渠道名与金额,悬停带模块原文与取数时刻', () => {
const line = llmBalanceLine(llmCell())
assert.equal(line.text, '龙抬头 ¥88.89')
assert.match(line.title, /外观专利密钥/)
assert.match(line.title, /可用 ¥85\.29/)
assert.match(line.title, /预冻结 ¥3\.60/)
assert.match(line.title, /取数于 2026-11-05 10:30/)
})
test('单位不是 CREDIT 时按认不出处理,一个金额都不给', () => {
const line = llmBalanceLine(llmCell({ unit: 'USD', message: '龙抬头没返回人民币口径的余额块' }))
assert.equal(line.text, '龙抬头 查不到')
assert.ok(!line.text.includes('¥'), `认不出口径不许显示金额:${line.text}`)
assert.match(line.title, /没返回人民币/)
})
test('available=false 说查不到,不显示 0', () => {
const line = llmBalanceLine(llmCell({
available: false, balance: null, availableBalance: null, frozen: null,
channel: 't8star', channelLabel: '贞贞', message: '贞贞渠道不提供余额查询',
}))
assert.equal(line.text, '贞贞 查不到')
assert.ok(!line.text.includes('0.00'), '查不到不许读成欠费')
})
test('两把密钥同渠道时折成一行,同一个钱不排两遍', () => {
const lines = llmBalanceLines([
llmCell(),
llmCell({ moduleKey: 'similar-asin', moduleLabel: '货源查询密钥' }),
])
assert.equal(lines.length, 1)
assert.equal(lines[0].text, '龙抬头 ¥88.89')
assert.match(lines[0].title, /外观专利密钥/)
assert.match(lines[0].title, /货源查询密钥/, '折叠后每一把的原文都要还在悬停里')
})
test('两把密钥分属两渠道时各出一行', () => {
const lines = llmBalanceLines([
llmCell(),
llmCell({
channel: 't8star', channelLabel: '贞贞', available: false,
balance: null, availableBalance: null, frozen: null, unit: null,
message: '贞贞渠道不提供余额查询',
}),
])
assert.deepEqual(lines.map((line) => line.text), ['龙抬头 ¥88.89', '贞贞 查不到'])
})
test('没取到数与查询中是两件事,都不许画成 0', () => {
assert.equal(llmBalanceLine(null).text, '—')
assert.match(llmBalanceLine(null).title, /不是余额为 0/)
assert.equal(llmBalanceLine(undefined, true).text, '查询中…')
assert.deepEqual(llmBalanceLines([], true).map((l) => l.text), ['查询中…'])
assert.deepEqual(llmBalanceLines([], false), [])
})
test('渠道认不出时整格占位,连金额都不给', () => {
const line = llmBalanceLine(llmCell({ channel: 'jikip', channelLabel: '极客' }))
assert.equal(line.text, '—')
assert.ok(!line.text.includes('¥'), '把供应商名贴到 LLM 列就是那处错标的形状')
assert.match(line.title, /渠道值认不出,未显示金额/)
})
test('代理余量给的是次数,带单位且不套 ¥', () => {
const line = proxyBalanceLine({ available: true, surplus: '1234', balance: '56', scope: 'user', message: null })
assert.equal(line.text, '你的套餐 1234 次')
assert.ok(!line.text.includes('¥'), `次数不是钱:${line.text}`)
assert.match(line.title, /剩余 IP 1234/)
assert.match(line.title, /账户余额 56/)
})
test('平台池必须自报是平台的钱,不许冒充这个用户的余量', () => {
const line = proxyBalanceLine({ available: true, surplus: '9', balance: '1', scope: 'platform', message: null })
assert.match(line.text, /^平台池/)
assert.match(line.title, /平台池/)
assert.ok(!line.text.includes('你的套餐'), '串档形状:平台池的量被写成用户自己的套餐')
})
test('青果那一档说查不了,句子用后端原文', () => {
const line = proxyBalanceLine({
available: false, surplus: null, balance: null, scope: 'none',
message: '青果不提供余量/余额查询(它的余额接口要控制台 Appid 与 Appkey 签名)',
})
assert.equal(line.text, '查不了')
assert.match(line.title, /查不了/)
assert.match(line.title, /青果不提供/)
})
test('scope 缺失时不硬认,标成来源未标注', () => {
const line = proxyBalanceLine({ available: true, surplus: '5', balance: null, scope: null, message: null })
assert.match(line.text, /^来源未标注/)
})