feat: 同步权限管理、企业成员排行与消费计费明细
- 接入平台与企业角色权限,按权限展示菜单、页面及操作。 - 企业成员排行按需加载,翻页沿用同一榜单快照,保留连续名次与前三名样式。 - 更新消费日志的费用明细、超管指标和官方价格汇率设置,补齐翻译与回归测试。
This commit is contained in:
@@ -0,0 +1,499 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { createInstance } from 'i18next';
|
||||
import * as lucide from 'lucide-react';
|
||||
import * as breakdown from '../../src/components/table/usage-logs/billingBreakdown.js';
|
||||
import { getLogOther } from '../../src/helpers/log.js';
|
||||
import { formatDiscountLabel } from '../../src/helpers/officialPrice.js';
|
||||
import { loadFrontendModule } from './frontend-module.js';
|
||||
|
||||
// 计费详情弹窗的渲染测试:把 UsageLogsTable.jsx 真正执行一遍(表格本体用桩替掉,
|
||||
// 弹窗内容走真实代码),覆盖各类日志形态下的渲染路径——纯函数单测测不到 JSX 里的
|
||||
// 运行时错误(未定义的标识符、把对象当子节点渲染、缺失的 key 与翻译)。
|
||||
|
||||
const filename = new URL(
|
||||
'../../src/components/table/usage-logs/UsageLogsTable.jsx',
|
||||
import.meta.url,
|
||||
);
|
||||
|
||||
const LANGUAGES = ['zh', 'zh-TW', 'en', 'ja', 'ko', 'vi', 'th', 'fr', 'ru'];
|
||||
const missingKeys = [];
|
||||
const loadLocale = async (code) =>
|
||||
JSON.parse(
|
||||
await readFile(
|
||||
new URL(`../../src/i18n/locales/${code}.json`, import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
// 不设回退语言:某个语言包缺 key 时必须暴露出来,而不是悄悄回退到中文
|
||||
const i18n = createInstance();
|
||||
await i18n.init({
|
||||
lng: 'zh',
|
||||
fallbackLng: false,
|
||||
keySeparator: false,
|
||||
nsSeparator: false,
|
||||
interpolation: { escapeValue: false },
|
||||
saveMissing: true,
|
||||
missingKeyHandler: (lngs, ns, key) => missingKeys.push(`${lngs}: ${key}`),
|
||||
resources: Object.fromEntries(
|
||||
await Promise.all(
|
||||
LANGUAGES.map(async (code) => [code, await loadLocale(code)]),
|
||||
),
|
||||
),
|
||||
});
|
||||
// 自检:缺失文案的探测必须真的会响,否则下面「无缺失文案」的断言什么都证明不了
|
||||
i18n.t('__missing_key_probe__');
|
||||
assert.equal(missingKeys.length, 1, 'missingKeyHandler 未生效');
|
||||
missingKeys.length = 0;
|
||||
|
||||
const state = { record: null, displayType: 'USD', language: 'zh' };
|
||||
const stub = (name) => ({ __esModule: true, default: () => null, name });
|
||||
const LogsTable = (
|
||||
await loadFrontendModule(filename, {
|
||||
// 弹窗由 detailRecord 这个 state 控制,点「详情」才会打开;这里直接让它等于待测记录
|
||||
react: { ...React, useState: () => [state.record, () => {}] },
|
||||
antd: { Button: 'button' },
|
||||
'@/components/ui': {
|
||||
Modal: ({ visible, title, children }) =>
|
||||
visible
|
||||
? React.createElement(
|
||||
'section',
|
||||
null,
|
||||
React.createElement('h1', null, title),
|
||||
children,
|
||||
)
|
||||
: null,
|
||||
Typography: {
|
||||
Text: ({ children }) => React.createElement('span', null, children),
|
||||
},
|
||||
},
|
||||
i18next: {
|
||||
__esModule: true,
|
||||
default: {
|
||||
get language() {
|
||||
return state.language;
|
||||
},
|
||||
},
|
||||
},
|
||||
'lucide-react': lucide,
|
||||
'../../common/table/TableEmpty': stub('TableEmpty'),
|
||||
'../../ui/CenterActionTable': stub('CenterActionTable'),
|
||||
'../../common/ui/CardTable': stub('CardTable'),
|
||||
'../../../helpers': {
|
||||
formatDiscountLabel,
|
||||
getLogOther,
|
||||
getQuotaPerUnit: () => 500000,
|
||||
getCurrencyConfig: () => ({
|
||||
symbol: state.displayType === 'TOKENS' ? '$' : '¥',
|
||||
rate: 1,
|
||||
type: state.displayType,
|
||||
}),
|
||||
renderQuota: (quota, digits = 2) =>
|
||||
state.displayType === 'TOKENS'
|
||||
? `${(quota / 1000).toFixed(2)}k`
|
||||
: `¥${(quota / 500000).toFixed(digits)}`,
|
||||
},
|
||||
'./UsageLogsColumnDefs': { getLogsColumns: () => [] },
|
||||
'./billingBreakdown': breakdown,
|
||||
})
|
||||
).default;
|
||||
|
||||
async function renderDetail(
|
||||
record,
|
||||
{
|
||||
expandItems = [],
|
||||
isAdminUser = false,
|
||||
usageRecordMode = true,
|
||||
language = 'zh',
|
||||
displayType = 'USD',
|
||||
} = {},
|
||||
) {
|
||||
Object.assign(state, { record, displayType, language });
|
||||
await i18n.changeLanguage(language);
|
||||
missingKeys.length = 0;
|
||||
const warnings = [];
|
||||
const originalError = console.error;
|
||||
console.error = (...args) => warnings.push(args.map(String).join(' '));
|
||||
let html;
|
||||
try {
|
||||
html = renderToStaticMarkup(
|
||||
React.createElement(LogsTable, {
|
||||
logs: [record],
|
||||
expandData: { [record.key]: expandItems },
|
||||
loading: false,
|
||||
activePage: 1,
|
||||
pageSize: 10,
|
||||
logCount: 1,
|
||||
compactMode: false,
|
||||
visibleColumns: {},
|
||||
handlePageChange() {},
|
||||
handlePageSizeChange() {},
|
||||
copyText() {},
|
||||
showUserInfoFunc() {},
|
||||
hasExpandableRows: () => true,
|
||||
isAdminUser,
|
||||
isRootUser: false,
|
||||
t: i18n.t.bind(i18n),
|
||||
COLUMN_KEYS: {},
|
||||
usageRecordMode,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
console.error = originalError;
|
||||
}
|
||||
// React 的开发期告警(缺 key、把对象当子节点、未知属性…)一律视为失败。
|
||||
// 注意服务端渲染不检查重复 key,那一类问题这里测不出来
|
||||
assert.deepEqual(warnings, [], 'React 渲染告警');
|
||||
assert.deepEqual(missingKeys, [], '语言包缺少文案');
|
||||
// 去掉 class:断言只关心结构与文字,带着 class 的话「标签紧跟数值」这类片段匹配不上
|
||||
return html.replace(/ class="[^"]*"/g, '');
|
||||
}
|
||||
|
||||
const count = (n) => n.toLocaleString();
|
||||
const consumeLog = (other, fields = {}) => ({
|
||||
key: 1,
|
||||
type: 2,
|
||||
model_name: 'demo-model',
|
||||
prompt_tokens: 0,
|
||||
completion_tokens: 0,
|
||||
quota: 0,
|
||||
...fields,
|
||||
other: JSON.stringify(other),
|
||||
});
|
||||
// 截图那条记录的形态:输入里绝大部分命中缓存
|
||||
const cachedLog = (extra = {}) =>
|
||||
consumeLog(
|
||||
{
|
||||
model_ratio: 0.575,
|
||||
completion_ratio: 4,
|
||||
cache_tokens: 87168,
|
||||
cache_ratio: 0.02,
|
||||
group_ratio: 0.782,
|
||||
user_group_ratio: -1,
|
||||
model_price: -1,
|
||||
...extra,
|
||||
},
|
||||
{ prompt_tokens: 88630, completion_tokens: 153, quota: 1716 },
|
||||
);
|
||||
|
||||
test('user view renders the formula row and the itemised table', async () => {
|
||||
const html = await renderDetail(cachedLog());
|
||||
for (const text of [
|
||||
'计费详情',
|
||||
'总金额 = 各计费项小计之和,小计 = 用量 × 单价',
|
||||
'费用明细',
|
||||
'输入(未命中缓存)',
|
||||
`${count(1462)} tokens`,
|
||||
'¥0.8993 / 1M tokens',
|
||||
'¥0.001315',
|
||||
'缓存命中',
|
||||
`${count(87168)} tokens`,
|
||||
'模型倍率 0.575x × 缓存倍率 0.02x × 分组倍率 0.782x',
|
||||
'¥0.001568',
|
||||
'模型倍率 0.575x × 输出倍率 4x × 分组倍率 0.782x',
|
||||
'¥0.000550',
|
||||
'合计',
|
||||
'¥0.003432',
|
||||
// 三行展示金额之和是 0.003433,比实扣多 0.000001:差额单独成项,逐项相加才对得上
|
||||
'舍入与其他调整',
|
||||
'¥0.000001',
|
||||
'各项小计为四舍五入后的近似值,合计以实际扣费为准',
|
||||
'成本因子',
|
||||
])
|
||||
assert.ok(html.includes(text), `缺少「${text}」`);
|
||||
// 调整项是负数:公式行里用减号连接、金额不带负号;表格里带负号
|
||||
assert.ok(html.includes('−</span>'));
|
||||
assert.ok(html.includes('<td>-¥0.000001</td>'));
|
||||
// 成本因子里的倍率小标签还在;token 用量已进分项表,不再以小标签重复
|
||||
assert.ok(html.includes('<span>模型倍率</span><strong>0.575x</strong>'));
|
||||
for (const pill of [
|
||||
`<span>输入</span><strong>${count(88630)}</strong>`,
|
||||
`<span>输出</span><strong>${count(153)}</strong>`,
|
||||
`<span>缓存命中</span><strong>${count(87168)}</strong>`,
|
||||
])
|
||||
assert.ok(!html.includes(pill), `不应再有小标签 ${pill}`);
|
||||
// 普通用户看不到渠道、计费源与超管指标
|
||||
for (const hidden of ['渠道', '计费源', '超管指标', '整体倍率'])
|
||||
assert.ok(!html.includes(hidden), `不应出现「${hidden}」`);
|
||||
});
|
||||
|
||||
test('root view adds the three summary metrics', async () => {
|
||||
const html = await renderDetail(
|
||||
cachedLog({
|
||||
root_billing: {
|
||||
official_quota: 3900,
|
||||
overall_ratio: 1.3,
|
||||
discount: 0.1857,
|
||||
exchange_rate: 7,
|
||||
},
|
||||
admin_info: { use_channel: [105] },
|
||||
}),
|
||||
{ isAdminUser: true },
|
||||
);
|
||||
for (const text of [
|
||||
'超管指标',
|
||||
'仅超级管理员可见',
|
||||
'官方价金额(1 倍率)',
|
||||
'¥0.007800',
|
||||
'整体倍率',
|
||||
'1.3x',
|
||||
'实际折扣',
|
||||
'0.1857 · 1.9折',
|
||||
'整体倍率 = 实扣 ÷ 官方价金额;实际折扣 = 整体倍率 ÷ 登记汇率(7)',
|
||||
'计费源',
|
||||
])
|
||||
assert.ok(html.includes(text), `缺少「${text}」`);
|
||||
});
|
||||
|
||||
test('root metrics handle sub-unit amounts and ratios at or above 1', async () => {
|
||||
const html = await renderDetail(
|
||||
cachedLog({
|
||||
root_billing: {
|
||||
official_quota: 0.4,
|
||||
overall_ratio: 7.5,
|
||||
discount: 1.0714,
|
||||
exchange_rate: 7,
|
||||
},
|
||||
}),
|
||||
);
|
||||
// 不足 1 个额度单位的金额多给两位小数;折扣 ≥ 1 时不附「X 折」
|
||||
assert.ok(html.includes('¥0.00000080'));
|
||||
assert.ok(html.includes('7.5x'));
|
||||
assert.ok(html.includes('1.0714'));
|
||||
assert.ok(!html.includes('折</'));
|
||||
});
|
||||
|
||||
test('a minimum charge shows up as an adjustment term', async () => {
|
||||
const html = await renderDetail(
|
||||
consumeLog(
|
||||
{
|
||||
model_price: -1,
|
||||
model_ratio: 0.02,
|
||||
completion_ratio: 1,
|
||||
group_ratio: 1,
|
||||
},
|
||||
{ prompt_tokens: 10, quota: 1 },
|
||||
),
|
||||
);
|
||||
assert.ok(html.includes('舍入与其他调整'));
|
||||
assert.ok(html.includes('¥0.000002'));
|
||||
});
|
||||
|
||||
test('logs without usable pricing fall back to the summary only', async () => {
|
||||
for (const other of [{}, { model_price: 0.1, group_ratio: 1 }]) {
|
||||
const html = await renderDetail(consumeLog(other, { quota: 150000 }));
|
||||
assert.ok(!html.includes('费用明细'));
|
||||
assert.ok(html.includes('保留关键成本因子,省略冗长计算公式'));
|
||||
assert.ok(html.includes('成本因子'));
|
||||
}
|
||||
// other 为空串 / null(旧日志、非模型消费)时弹窗照常打开
|
||||
for (const other of ['', 'null', undefined]) {
|
||||
const html = await renderDetail({
|
||||
...consumeLog({}, { quota: 10 }),
|
||||
other,
|
||||
});
|
||||
assert.ok(html.includes('计费摘要'));
|
||||
assert.ok(!html.includes('费用明细'));
|
||||
}
|
||||
});
|
||||
|
||||
test('non-consume logs render their expand items', async () => {
|
||||
const html = await renderDetail(
|
||||
{ key: 1, type: 1, quota: 0, other: '' },
|
||||
{ expandItems: [{ key: '充值方式', value: '在线充值' }] },
|
||||
);
|
||||
assert.ok(html.includes('充值方式') && html.includes('在线充值'));
|
||||
assert.ok(!html.includes('费用明细'));
|
||||
});
|
||||
|
||||
test('per-call, per-second, audio and tool-call logs each render their rows', async () => {
|
||||
const perCall = await renderDetail(
|
||||
consumeLog({ model_price: 0.05, group_ratio: 0.8 }, { quota: 20000 }),
|
||||
);
|
||||
for (const text of ['按次计费', '1 次', '¥0.04 / 次', '¥0.040000'])
|
||||
assert.ok(perCall.includes(text), `按次:缺少「${text}」`);
|
||||
|
||||
const perSecond = await renderDetail(
|
||||
consumeLog(
|
||||
{
|
||||
model_price: 0,
|
||||
group_ratio: 0.8,
|
||||
video_second_unit_price: 0.1,
|
||||
video_second_duration: 5,
|
||||
video_second_group_ratio: 0.8,
|
||||
},
|
||||
{ quota: 200000 },
|
||||
),
|
||||
);
|
||||
for (const text of ['按秒计费', '5 秒', '¥0.08 / 秒', '¥0.400000'])
|
||||
assert.ok(perSecond.includes(text), `按秒:缺少「${text}」`);
|
||||
|
||||
const audio = await renderDetail(
|
||||
consumeLog(
|
||||
{
|
||||
audio: true,
|
||||
model_price: -1,
|
||||
model_ratio: 2,
|
||||
completion_ratio: 2,
|
||||
group_ratio: 1,
|
||||
audio_ratio: 10,
|
||||
audio_completion_ratio: 2,
|
||||
text_input: 10,
|
||||
text_output: 5,
|
||||
audio_input: 20,
|
||||
audio_output: 15,
|
||||
},
|
||||
{ prompt_tokens: 30, completion_tokens: 20, quota: 1040 },
|
||||
),
|
||||
);
|
||||
for (const text of ['文字输入', '文字输出', '音频输入', '音频输出'])
|
||||
assert.ok(audio.includes(text), `音频:缺少「${text}」`);
|
||||
assert.ok(
|
||||
audio.includes(
|
||||
'模型倍率 2x × 音频倍率 10x × 音频输出倍率 2x × 分组倍率 1x',
|
||||
),
|
||||
);
|
||||
|
||||
const tools = await renderDetail(
|
||||
consumeLog(
|
||||
{
|
||||
model_price: -1,
|
||||
model_ratio: 1,
|
||||
completion_ratio: 1,
|
||||
group_ratio: 2,
|
||||
web_search: true,
|
||||
web_search_call_count: 3,
|
||||
web_search_price: 10,
|
||||
},
|
||||
{ prompt_tokens: 1000, quota: 32000 },
|
||||
),
|
||||
);
|
||||
for (const text of ['联网搜索', '3 次', '¥0.02 / 次', '¥0.060000'])
|
||||
assert.ok(tools.includes(text), `工具调用:缺少「${text}」`);
|
||||
});
|
||||
|
||||
test('token counts stay visible when the breakdown has no token rows', async () => {
|
||||
// 按次计费的明细只有一行「按次计费」,token 用量不能因为有了明细就从弹窗里消失
|
||||
const perCall = await renderDetail(
|
||||
consumeLog(
|
||||
{ model_price: 0.05, group_ratio: 1, cache_tokens: 200 },
|
||||
{ prompt_tokens: 1000, completion_tokens: 500, quota: 25000 },
|
||||
),
|
||||
);
|
||||
for (const text of [
|
||||
'费用明细',
|
||||
'按次计费',
|
||||
`输入</span><strong>${count(1000)}`,
|
||||
`输出</span><strong>${count(500)}`,
|
||||
`缓存命中</span><strong>${count(200)}`,
|
||||
])
|
||||
assert.ok(perCall.includes(text), `按次:缺少「${text}」`);
|
||||
|
||||
// 只带按秒计价字段的任务日志:没有任何倍率可展示,成本因子整块不出现
|
||||
const bareTask = await renderDetail(
|
||||
consumeLog(
|
||||
{
|
||||
origin_task_id: 'task_1',
|
||||
video_second_unit_price: 0.1,
|
||||
video_second_duration: 5,
|
||||
video_second_group_ratio: 0.8,
|
||||
},
|
||||
{ quota: 200000 },
|
||||
),
|
||||
);
|
||||
assert.ok(bareTask.includes('按秒计费'));
|
||||
assert.ok(!bareTask.includes('成本因子'));
|
||||
|
||||
// 两种联网搜索同时计费:各占一行,成本因子里不再重复
|
||||
const bothSearches = await renderDetail(
|
||||
consumeLog(
|
||||
{
|
||||
model_price: -1,
|
||||
model_ratio: 1,
|
||||
completion_ratio: 1,
|
||||
group_ratio: 0.5,
|
||||
web_search: true,
|
||||
web_search_call_count: 1,
|
||||
web_search_price: 25,
|
||||
claude_web_search_call_count: 2,
|
||||
claude_web_search_price: 10,
|
||||
},
|
||||
{ prompt_tokens: 1000, quota: 11750 },
|
||||
),
|
||||
);
|
||||
for (const text of ['联网搜索', 'Claude 联网搜索', '2 次', '¥0.010000'])
|
||||
assert.ok(bothSearches.includes(text), `双搜索:缺少「${text}」`);
|
||||
// 公式行里是「名称 + 金额」,小标签是「名称 + 次数」:后者不应再出现
|
||||
for (const pill of [
|
||||
'<span>联网搜索</span><strong>1 次</strong>',
|
||||
'<span>Claude 联网搜索</span><strong>2 次</strong>',
|
||||
])
|
||||
assert.ok(!bothSearches.includes(pill), `不应再有小标签 ${pill}`);
|
||||
});
|
||||
|
||||
test('console page, English and quota-unit display all render cleanly', async () => {
|
||||
const consolePage = await renderDetail(
|
||||
{
|
||||
...cachedLog({ admin_info: { local_count_tokens: true } }),
|
||||
channel: 105,
|
||||
channel_name: 'demo-channel',
|
||||
},
|
||||
{ isAdminUser: true, usageRecordMode: false },
|
||||
);
|
||||
for (const text of ['渠道', '105 · demo-channel', '计费源', '本地计费'])
|
||||
assert.ok(consolePage.includes(text), `控制台:缺少「${text}」`);
|
||||
|
||||
const english = await renderDetail(cachedLog(), { language: 'en' });
|
||||
for (const text of ['Cost breakdown', 'Subtotal', 'Input (uncached)'])
|
||||
assert.ok(english.includes(text), `英文:缺少「${text}」`);
|
||||
|
||||
// 按额度展示:合计不能用缩写(1.72k),否则与各行的原始数值加不起来
|
||||
const quotaUnits = await renderDetail(cachedLog(), { displayType: 'TOKENS' });
|
||||
// 657.39 + 783.90 + 275.19 − 0.48 = 1716.00
|
||||
for (const text of [
|
||||
'1716.00',
|
||||
'657.39',
|
||||
'783.90',
|
||||
'275.19',
|
||||
'<td>-0.48</td>',
|
||||
])
|
||||
assert.ok(quotaUnits.includes(text), `按额度:缺少「${text}」`);
|
||||
|
||||
// 按额度展示时,不足 1 个额度单位的官方价金额也不能显示成 0.00
|
||||
const tinyOfficial = await renderDetail(
|
||||
cachedLog({
|
||||
root_billing: {
|
||||
official_quota: 0.004,
|
||||
overall_ratio: 250,
|
||||
discount: 35.7143,
|
||||
exchange_rate: 7,
|
||||
},
|
||||
}),
|
||||
{ displayType: 'TOKENS' },
|
||||
);
|
||||
assert.ok(tinyOfficial.includes('0.004000'));
|
||||
});
|
||||
|
||||
test('every locale has the strings used by the detail modal', async () => {
|
||||
const rootLog = cachedLog({
|
||||
root_billing: {
|
||||
official_quota: 3900,
|
||||
overall_ratio: 1.3,
|
||||
discount: 0.1857,
|
||||
exchange_rate: 7,
|
||||
},
|
||||
admin_info: { use_channel: [105] },
|
||||
});
|
||||
const minimumCharge = consumeLog(
|
||||
{ model_price: -1, model_ratio: 0.02, completion_ratio: 1, group_ratio: 1 },
|
||||
{ prompt_tokens: 10, quota: 1 },
|
||||
);
|
||||
// renderDetail 内部断言了「无 React 告警、无缺失文案」
|
||||
for (const language of LANGUAGES) {
|
||||
await renderDetail(rootLog, { language, isAdminUser: true });
|
||||
await renderDetail(minimumCharge, { language });
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user