feat: 同步权限管理、企业成员排行与消费计费明细

- 接入平台与企业角色权限,按权限展示菜单、页面及操作。
- 企业成员排行按需加载,翻页沿用同一榜单快照,保留连续名次与前三名样式。
- 更新消费日志的费用明细、超管指标和官方价格汇率设置,补齐翻译与回归测试。
This commit is contained in:
qiubaishen
2026-11-25 21:08:24 +08:00
parent ed693a450a
commit 870b51d054
134 changed files with 20354 additions and 4133 deletions
@@ -0,0 +1,230 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { loadFrontendModule } from './frontend-module.js';
// 原厂价登记汇率设置项的行为测试。不走真实渲染:把 hooks 换成可手动推进的桩,直接调用
// 组件函数拿到元素树,再触发 InputNumber / Button 上的回调——这样才能复现
// 「onChange 与 onPressEnter 在同一次渲染里先后同步触发」这个时序。
const filename = new URL(
'../../src/pages/Setting/Ratio/OfficialPriceExchangeRateSetting.jsx',
import.meta.url,
);
async function mount({ put } = {}) {
const hooks = [];
let cursor = 0;
let effects = [];
const calls = { put: [], error: [], success: [], warning: [], refresh: 0 };
const react = {
...React,
useState(initial) {
const index = cursor++;
if (!(index in hooks)) hooks[index] = { value: initial };
const slot = hooks[index];
return [
slot.value,
(next) => {
slot.value = next;
},
];
},
useRef(initial) {
const index = cursor++;
if (!(index in hooks)) hooks[index] = { current: initial };
return hooks[index];
},
useEffect(effect, deps) {
const index = cursor++;
const previous = hooks[index];
if (
!previous ||
deps.some((dep, i) => !Object.is(dep, previous.deps[i]))
) {
hooks[index] = { deps };
effects.push(effect);
}
},
};
const antd = {
Button: 'Button',
InputNumber: 'InputNumber',
Space: 'Space',
Typography: { Text: 'Text' },
};
const Component = (
await loadFrontendModule(filename, {
react,
antd,
'react-i18next': { useTranslation: () => ({ t: (key) => key }) },
'../../../helpers': {
API: {
put: (...args) => {
calls.put.push(args);
return put
? put(...args)
: Promise.resolve({ data: { success: true } });
},
},
showError: (message) => calls.error.push(message),
showSuccess: (message) => calls.success.push(message),
showWarning: (message) => calls.warning.push(message),
},
})
).default;
const find = (node, type) => {
if (!node || typeof node !== 'object') return null;
if (Array.isArray(node)) {
for (const child of node) {
const hit = find(child, type);
if (hit) return hit;
}
return null;
}
if (node.type === type) return node;
return find(node.props?.children, type);
};
let tree;
let props;
// 渲染一轮并执行这一轮登记的 effect;effect 里若改了 state,需要再 render 一次才会体现
const render = (nextProps = props) => {
props = nextProps;
cursor = 0;
effects = [];
tree = Component({ ...props, refresh: () => (calls.refresh += 1) });
effects.forEach((effect) => effect());
return tree;
};
return {
calls,
render,
input: () => find(tree, antd.InputNumber),
button: () => find(tree, antd.Button),
};
}
const saved = (value) => ({ options: { OfficialPriceExchangeRate: value } });
const RANGE_ERROR = '请输入大于 0 且不超过 1000 的数字';
test('shows the saved rate once options arrive after mount', async () => {
const widget = await mount();
widget.render({ options: {} });
assert.equal(widget.input().props.value, null);
widget.render(saved('7'));
widget.render();
assert.equal(widget.input().props.value, 7);
// 不设 min / max:组件不会把超范围的输入悄悄改成边界值;
// 不设 step:小数位跟着 step 走,7 会显示成 7.0
for (const prop of ['min', 'max', 'step'])
assert.equal(widget.input().props[prop], undefined, prop);
});
test('follows the server value only while the input is untouched', async () => {
const widget = await mount();
widget.render(saved('7'));
widget.render();
// 没动过输入框:别处改了配置,刷新后跟着变
widget.render(saved('9'));
widget.render();
assert.equal(widget.input().props.value, 9);
// 正在改:刷新带来的新值不能把输入中的内容冲掉
widget.input().props.onChange(5);
widget.render(saved('9.5'));
widget.render();
assert.equal(widget.input().props.value, 5);
await widget.input().props.onPressEnter();
assert.equal(
JSON.stringify(widget.calls.put.map((args) => args[1].value)),
JSON.stringify(['5']),
);
});
test('Enter saves the value just typed, not the previous render state', async () => {
const widget = await mount();
widget.render(saved('7'));
widget.render();
// InputNumber 在回车时先同步 onChange 再 onPressEnter,中间没有重新渲染
const input = widget.input();
input.props.onChange(8.5);
await input.props.onPressEnter();
// 请求参数是组件所在 VM 域里创建的对象,原型与这里不同,按 JSON 比较
assert.equal(
JSON.stringify(widget.calls.put),
JSON.stringify([
[
'/api/option/',
{ key: 'OfficialPriceExchangeRate', value: '8.5' },
{ skipErrorHandler: true },
],
]),
);
assert.deepEqual(widget.calls.success, ['保存成功']);
assert.equal(widget.calls.refresh, 1);
});
test('out-of-range or empty input is rejected instead of saving something else', async () => {
for (const typed of [2000, 0, -3, null]) {
const widget = await mount();
widget.render(saved('7'));
widget.render();
const input = widget.input();
input.props.onChange(typed);
await input.props.onPressEnter();
assert.deepEqual(widget.calls.put, [], `输入 ${typed} 不应发请求`);
assert.deepEqual(widget.calls.error, [RANGE_ERROR]);
}
});
test('saving an unchanged rate only warns', async () => {
const widget = await mount();
widget.render(saved('7'));
widget.render();
await widget.button().props.onClick();
assert.deepEqual(widget.calls.put, []);
assert.deepEqual(widget.calls.warning, ['你似乎并没有修改什么']);
});
test('a second Enter while the request is pending does not send it twice', async () => {
let release;
const pending = new Promise((resolve) => {
release = resolve;
});
const widget = await mount({ put: () => pending });
widget.render(saved('7'));
widget.render();
const input = widget.input();
input.props.onChange(8);
const first = input.props.onPressEnter();
const second = input.props.onPressEnter();
release({ data: { success: true } });
await Promise.all([first, second]);
assert.equal(widget.calls.put.length, 1);
// 请求结束后可以再次提交
input.props.onChange(9);
await input.props.onPressEnter();
assert.equal(widget.calls.put.length, 2);
});
test('a rejected or failed save surfaces the error and unlocks the form', async () => {
const rejected = await mount({
put: () =>
Promise.resolve({ data: { success: false, message: '后端拒绝' } }),
});
rejected.render(saved('7'));
rejected.render();
rejected.input().props.onChange(8);
await rejected.input().props.onPressEnter();
assert.deepEqual(rejected.calls.error, ['后端拒绝']);
assert.equal(rejected.calls.refresh, 0);
const failed = await mount({ put: () => Promise.reject(new Error('net')) });
failed.render(saved('7'));
failed.render();
failed.input().props.onChange(8);
await failed.input().props.onPressEnter();
assert.deepEqual(failed.calls.error, ['保存失败,请重试']);
await failed.input().props.onPressEnter();
assert.equal(failed.calls.put.length, 2);
});
+164 -9
View File
@@ -9,6 +9,10 @@ import * as Ant from 'antd';
import { transformWithEsbuild } from 'vite';
import i18next from 'i18next';
import * as pagination from '../../src/components/ui/pagination.js';
import {
buildOrgLogFilters,
sameOrgRankingFilters,
} from '../../src/helpers/orgLogFilters.js';
await i18next.init({
lng: 'zh',
@@ -53,6 +57,8 @@ async function exercise(
expectedPage = 3,
pageKey = 'p',
values = {},
responseData,
response,
},
failure = false,
) {
@@ -62,6 +68,7 @@ async function exercise(
errors = [];
const context = {
URLSearchParams,
AbortController,
Date,
Promise,
console: { error() {} },
@@ -129,18 +136,21 @@ async function exercise(
get: async (url, options = {}) => {
calls.push({ url, options });
if (failure) throw new Error('simulated pagination failure');
if (response) return { data: await response(options) };
return {
data: {
success: true,
data: {
items: [sentinel],
list: [sentinel],
total: 156,
page: expectedPage,
page_size: expectedSize,
requests: { items: [sentinel], total: 156 },
audits: { items: [sentinel], total: 156 },
},
data: responseData
? responseData(options)
: {
items: [sentinel],
list: [sentinel],
total: 156,
page: expectedPage,
page_size: expectedSize,
requests: { items: [sentinel], total: 156 },
audits: { items: [sentinel], total: 156 },
},
},
};
},
@@ -366,6 +376,151 @@ for (const cfg of [
exercise(cfg, true));
}
const rankingValues = () => ({
buildOrgLogFilters,
request: { current: null },
emptyRankingPage: { items: [], total: 0, page: 1, page_size: 10 },
});
test('Member ranking sends applied filters and uses the server page and total', async () => {
const signal = new AbortController().signal;
const { calls, states } = await exercise({
file: 'src/hooks/org/useOrgData.js',
fn: 'fetch',
root: 'useOrgMemberRanking',
expectedPath: '/api/org/logs/ranking',
args: [
{
userId: 7,
modelName: 'model-a',
startTimestamp: 100,
endTimestamp: 200,
},
{ page: 3, pageSize: 50, noCache: true, signal },
],
values: rankingValues(),
});
assert.equal(calls.length, 1);
assert.deepEqual(
{ ...calls[0].options.params },
{
p: 3,
page_size: 50,
user_id: 7,
model_name: 'model-a',
start_timestamp: 100,
end_timestamp: 200,
nocache: 1,
},
);
assert.equal(calls[0].options.headers['X-Org-Id'], '77');
assert.equal(calls[0].options.signal, signal);
assert.equal(states.setRankingPage.page, 3);
assert.equal(states.setRankingPage.page_size, 50);
assert.equal(states.setRankingPage.total, 156);
assert.deepEqual(states.setRankingPage.items, [sentinel]);
});
test('Member ranking returns to the last available page when a refresh shrinks the results', async () => {
const { calls, states } = await exercise({
file: 'src/hooks/org/useOrgData.js',
fn: 'fetch',
root: 'useOrgMemberRanking',
expectedPath: '/api/org/logs/ranking',
args: [{}, { page: 3, pageSize: 50, noCache: true }],
values: rankingValues(),
responseData: ({ params }) => ({
items: params.p === 2 ? [sentinel] : [],
total: 51,
page: params.p,
page_size: params.page_size,
snapshot: 'fresh',
}),
});
assert.deepEqual(
calls.map(({ options }) => options.params.p),
[3, 2],
);
assert.equal(calls[1].options.params.snapshot, 'fresh');
assert.equal(calls[1].options.params.nocache, undefined);
assert.equal(states.setRankingPage.page, 2);
assert.deepEqual(states.setRankingPage.items, [sentinel]);
assert.equal(states.setLoading, false);
});
for (const expiresAgain of [false, true]) {
test(`Expired ranking snapshot restarts once on page one (retry fails: ${expiresAgain})`, async () => {
const expired = {
success: false,
code: 'ranking_snapshot_expired',
message: 'expired',
};
const { calls, errors, states } = await exercise({
file: 'src/hooks/org/useOrgData.js',
fn: 'fetch',
root: 'useOrgMemberRanking',
expectedPath: '/api/org/logs/ranking',
args: [
{ modelName: 'sample' },
{ page: 3, pageSize: 50, snapshot: 'old' },
],
values: rankingValues(),
response: ({ params }) =>
params.snapshot || expiresAgain
? expired
: {
success: true,
data: {
items: [sentinel],
total: 1,
page: 1,
page_size: 50,
snapshot: 'new',
},
},
});
assert.deepEqual(
calls.map(({ options }) => ({ ...options.params })),
[
{ model_name: 'sample', p: 3, page_size: 50, snapshot: 'old' },
{ model_name: 'sample', p: 1, page_size: 50 },
],
);
assert.equal(states.setRankingPage.page, 1);
assert.equal(
states.setRankingPage.snapshot,
expiresAgain ? undefined : 'new',
);
assert.deepEqual(errors, expiresAgain ? ['expired'] : []);
assert.equal(states.setLoading, false);
});
}
test('Member ranking refresh preserves the page only for the same applied filters', () => {
const applied = {
userId: 7,
modelName: 'model-a',
startTimestamp: 10,
endTimestamp: 20,
};
assert.equal(
sameOrgRankingFilters(applied, { ...applied, modelName: 'model-b' }, true),
false,
);
assert.equal(
sameOrgRankingFilters(applied, { ...applied, userId: 8 }, true),
false,
);
assert.equal(
sameOrgRankingFilters(applied, { ...applied, endTimestamp: 21 }, false),
false,
);
assert.equal(
sameOrgRankingFilters(applied, { ...applied, endTimestamp: 21 }, true),
true,
);
});
test('Resizing emits one size callback and never a stale page request', () => {
const calls = [];
const events = pagination.centerPaginationEvents({
+448
View File
@@ -0,0 +1,448 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
buildBillingBreakdown,
reconcileDisplayAmounts,
} from '../../src/components/table/usage-logs/billingBreakdown.js';
const near = (actual, expected) =>
assert.ok(
Math.abs(actual - expected) < 1e-6,
`expected ${actual} ≈ ${expected}`,
);
const keys = (result) => result.items.map((item) => item.key);
test('splits cached input out of prompt tokens for OpenAI-style logs', () => {
const result = buildBillingBreakdown(
{ prompt_tokens: 88630, completion_tokens: 153, quota: 1716 },
{
model_ratio: 0.575,
completion_ratio: 4,
cache_tokens: 87168,
cache_ratio: 0.02,
group_ratio: 0.782,
model_price: -1,
},
);
assert.deepEqual(keys(result), ['inputUncached', 'cacheRead', 'output']);
assert.equal(result.items[0].qty, 1462);
near(result.items[0].quota, 1462 * 0.575 * 0.782);
near(result.items[1].quota, 87168 * 0.02 * 0.575 * 0.782);
near(result.items[2].quota, 153 * 4 * 0.575 * 0.782);
near(result.estimated, 3817.36 * 0.575 * 0.782);
assert.equal(result.actual, 1716);
});
test('keeps Claude prompt tokens intact and prices each cache bucket', () => {
const result = buildBillingBreakdown(
{ prompt_tokens: 100, completion_tokens: 10, quota: 2138 },
{
claude: true,
model_ratio: 1.5,
completion_ratio: 5,
group_ratio: 1,
model_price: -1,
cache_tokens: 1000,
cache_ratio: 0.1,
cache_creation_tokens: 700,
cache_creation_ratio: 1.25,
cache_creation_tokens_5m: 200,
cache_creation_ratio_5m: 1.25,
cache_creation_tokens_1h: 400,
cache_creation_ratio_1h: 2,
cache_creation_tokens_unlabeled: 100,
cache_creation_ratio_unlabeled: 1.25,
},
);
assert.deepEqual(keys(result), [
'inputUncached',
'cacheRead',
'cacheCreation5m',
'cacheCreation1h',
'cacheCreationUnlabeled',
'output',
]);
assert.equal(result.items[0].qty, 100);
near(result.estimated, (100 + 100 + 250 + 800 + 125 + 50) * 1.5);
// 分项之和 2137.5,四舍五入后实扣 2138
near(result.actual - result.estimated, 0.5);
});
test('per-call pricing yields a single line', () => {
const result = buildBillingBreakdown(
{ prompt_tokens: 0, completion_tokens: 0, quota: 20000 },
{ model_price: 0.05, group_ratio: 0.8, model_ratio: 0 },
{ quotaPerUnit: 500000 },
);
assert.deepEqual(keys(result), ['perCall']);
near(result.items[0].quota, 20000);
near(result.actual - result.estimated, 0);
});
test('audio logs price text and audio separately', () => {
const result = buildBillingBreakdown(
{ prompt_tokens: 30, completion_tokens: 20, quota: 1040 },
{
audio: true,
model_ratio: 2,
completion_ratio: 2,
group_ratio: 1,
model_price: -1,
audio_ratio: 10,
audio_completion_ratio: 2,
text_input: 10,
text_output: 5,
audio_input: 20,
audio_output: 15,
},
);
assert.deepEqual(keys(result), [
'textInput',
'textOutput',
'audioInput',
'audioOutput',
]);
near(result.estimated, (10 + 5 * 2 + 20 * 10 + 15 * 10 * 2) * 2);
});
test('tool calls are priced by group ratio only', () => {
const result = buildBillingBreakdown(
{ prompt_tokens: 1000, completion_tokens: 0, quota: 32000 },
{
model_ratio: 1,
completion_ratio: 1,
group_ratio: 2,
model_price: -1,
web_search: true,
web_search_call_count: 3,
web_search_price: 10,
},
);
assert.deepEqual(keys(result), ['input', 'webSearch']);
near(result.items[1].quota, (10 / 1000) * 3 * 2 * 500000);
});
test('returns null when the log carries no pricing info', () => {
assert.equal(buildBillingBreakdown({ quota: 10 }, {}), null);
assert.equal(buildBillingBreakdown({ quota: 10 }, null), null);
});
test('per-call pricing still carries tool charges', () => {
const result = buildBillingBreakdown(
{ prompt_tokens: 0, completion_tokens: 0, quota: 30000 },
{
model_price: 0.05,
group_ratio: 0.8,
image_generation_call: true,
image_generation_call_price: 0.025,
},
);
assert.deepEqual(keys(result), ['perCall', 'imageGeneration']);
near(result.estimated, 30000);
});
test('per-second video tasks are priced by duration, not per call', () => {
const result = buildBillingBreakdown(
{ quota: 200000 },
{
model_price: 0,
group_ratio: 0.8,
video_second_unit_price: 0.1,
video_second_duration: 5,
video_second_group_ratio: 0.8,
},
);
assert.deepEqual(keys(result), ['videoSecond']);
assert.equal(result.items[0].qty, 5);
near(result.estimated, 200000);
});
test('hides the breakdown when it cannot explain the actual charge', () => {
// 任务按时长 / 分辨率系数计价:日志只有 model_price,系数不在结构化字段里
assert.equal(
buildBillingBreakdown(
{ quota: 150000 },
{ model_price: 0.1, group_ratio: 1 },
),
null,
);
// token 兜底预扣:model_price 为 0,实际扣费来自估算
assert.equal(
buildBillingBreakdown(
{ quota: 8000 },
{ model_price: 0, group_ratio: 1, video_token_fallback: true },
),
null,
);
});
test('tolerance is one quota unit, not a share of the charge', () => {
// 100 万额度的请求里有 9500 个单位对不上:占比不到 1%,但绝不是「舍入」
assert.equal(
buildBillingBreakdown(
{ prompt_tokens: 990500, completion_tokens: 0, quota: 1000000 },
{ model_price: -1, model_ratio: 1, completion_ratio: 1, group_ratio: 1 },
),
null,
);
// 差 2 个单位同样不展示;差 1 个单位以内才算取整
const base = { model_price: -1, model_ratio: 1, completion_ratio: 1 };
assert.equal(
buildBillingBreakdown(
{ prompt_tokens: 1000, quota: 1002 },
{ ...base, group_ratio: 1 },
),
null,
);
const withinOne = buildBillingBreakdown(
{ prompt_tokens: 1000, quota: 1001 },
{ ...base, group_ratio: 1 },
);
near(withinOne.actual - withinOne.estimated, 1);
});
test('never presents a whole charge as an adjustment', () => {
// 按次价 0 却有实扣:分项全是 0 元,这笔钱没有被任何一行解释
assert.equal(
buildBillingBreakdown({ quota: 1 }, { model_price: 0, group_ratio: 1 }),
null,
);
// model_price 为 null 等于没有这个字段,不能当成「按次 0 元」
assert.equal(
buildBillingBreakdown({ quota: 0 }, { model_price: null, group_ratio: 1 }),
null,
);
const tokenBilled = buildBillingBreakdown(
{ prompt_tokens: 1000, quota: 1000 },
{ model_price: null, model_ratio: 1, completion_ratio: 1, group_ratio: 1 },
);
assert.deepEqual(keys(tokenBilled), ['input']);
});
test('cost-basis video fields do not turn other logs into per-second billing', () => {
const perSecond = {
model_price: 0,
group_ratio: 0.8,
video_second_unit_price: 0.1,
video_second_duration: 5,
};
// 即使金额恰好等于 单价 × 时长 × 分组倍率,这两类也不是按秒结算的一整笔
assert.equal(
buildBillingBreakdown(
{ quota: 200000 },
{ ...perSecond, video_token_fallback: true },
),
null,
);
assert.equal(
buildBillingBreakdown(
{ quota: 200000 },
{ ...perSecond, quota_adjustment: true },
),
null,
);
// 字段只是成本基准、实扣是别的算法算出来的
assert.equal(buildBillingBreakdown({ quota: 150000 }, perSecond), null);
assert.deepEqual(keys(buildBillingBreakdown({ quota: 200000 }, perSecond)), [
'videoSecond',
]);
});
test('zero model price with a model ratio is still token billing', () => {
const result = buildBillingBreakdown(
{ prompt_tokens: 1000, completion_tokens: 0, quota: 1000 },
{ model_price: 0, model_ratio: 1, completion_ratio: 1, group_ratio: 1 },
);
assert.deepEqual(keys(result), ['input']);
near(result.estimated, 1000);
});
test('a minimum charge is within tolerance', () => {
// 10 tokens × 0.02 = 0.2 个额度单位,结算按最低 1 个单位扣
const result = buildBillingBreakdown(
{ prompt_tokens: 10, completion_tokens: 0, quota: 1 },
{ model_price: -1, model_ratio: 0.02, completion_ratio: 1, group_ratio: 1 },
);
assert.deepEqual(keys(result), ['input']);
near(result.actual - result.estimated, 0.8);
});
test('both web-search charges get their own line', () => {
// 模型名以 search-preview 结尾却由 Claude 渠道承接:OpenAI 口径 1 次 + Claude 口径 2 次
const result = buildBillingBreakdown(
{ prompt_tokens: 1000, quota: 11750 },
{
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,
},
);
assert.deepEqual(keys(result), ['input', 'webSearch', 'claudeWebSearch']);
near(result.items[2].quota, (10 / 1000) * 2 * 0.5 * 500000);
near(result.estimated, 11750);
});
// ---------------------------------------------------------------------------
// reconcileDisplayAmounts:界面上逐项相加必须恰好等于合计
// ---------------------------------------------------------------------------
const usd = { digits: 6, toDisplay: (quota) => (quota / 500000) * 1 };
const units = (value, digits) => Math.round(value * 10 ** digits);
const addsUp = (result, digits) =>
result.rows.reduce((sum, row) => sum + units(row.amount, digits), 0) +
units(result.adjustment, digits) ===
units(result.total, digits);
test('displayed rows plus the adjustment equal the displayed total', () => {
// 截图那条记录:三行展示金额之和是 0.003433,实扣 0.003432
const breakdown = buildBillingBreakdown(
{ prompt_tokens: 88630, completion_tokens: 153, quota: 1716 },
{
model_ratio: 0.575,
completion_ratio: 4,
cache_tokens: 87168,
cache_ratio: 0.02,
group_ratio: 0.782,
model_price: -1,
},
);
const result = reconcileDisplayAmounts(breakdown, usd);
assert.deepEqual(
result.rows.map((row) => row.amount),
[0.001315, 0.001568, 0.00055],
);
assert.equal(result.total, 0.003432);
assert.equal(result.adjustment, -0.000001);
assert.ok(addsUp(result, 6));
});
test('no adjustment when the rows already add up', () => {
const breakdown = buildBillingBreakdown(
{ quota: 20000 },
{ model_price: 0.05, group_ratio: 0.8 },
);
const result = reconcileDisplayAmounts(breakdown, usd);
assert.equal(result.adjustment, 0);
assert.equal(result.total, 0.04);
});
test('a minimum charge lands in the adjustment', () => {
// 0.2 个额度单位的用量按最低 1 个单位扣:行金额展示为 0,差额全在调整项
const breakdown = buildBillingBreakdown(
{ prompt_tokens: 10, quota: 1 },
{ model_price: -1, model_ratio: 0.02, completion_ratio: 1, group_ratio: 1 },
);
const result = reconcileDisplayAmounts(breakdown, usd);
assert.equal(result.rows[0].amount, 0);
assert.equal(result.adjustment, 0.000002);
assert.ok(addsUp(result, 6));
});
test('reconciles in quota units and with a currency rate', () => {
const breakdown = buildBillingBreakdown(
{ prompt_tokens: 88630, completion_tokens: 153, quota: 1716 },
{
model_ratio: 0.575,
completion_ratio: 4,
cache_tokens: 87168,
cache_ratio: 0.02,
group_ratio: 0.782,
model_price: -1,
},
);
// 按额度展示:两位小数,合计是整数个额度单位
const inUnits = reconcileDisplayAmounts(breakdown, {
digits: 2,
toDisplay: (quota) => quota,
});
assert.deepEqual(
inUnits.rows.map((row) => row.amount),
[657.39, 783.9, 275.19],
);
assert.equal(inUnits.total, 1716);
assert.equal(inUnits.adjustment, -0.48);
assert.ok(addsUp(inUnits, 2));
// 人民币展示(汇率 7.3)
const cny = reconcileDisplayAmounts(breakdown, {
digits: 6,
toDisplay: (quota) => (quota / 500000) * 7.3,
});
assert.equal(cny.total, 0.025054);
assert.ok(addsUp(cny, 6));
});
test('a positive charge never displays as zero', () => {
// 展示汇率极小时实扣会被舍成 0:与页面其余位置一样按最小展示单位显示
const breakdown = buildBillingBreakdown(
{ prompt_tokens: 1000, quota: 1000 },
{ model_price: -1, model_ratio: 1, completion_ratio: 1, group_ratio: 1 },
);
const result = reconcileDisplayAmounts(breakdown, {
digits: 6,
toDisplay: (quota) => (quota / 500000) * 0.0001,
});
assert.equal(result.total, 0.000001);
assert.ok(addsUp(result, 6));
});
test('rows always add up across random logs', () => {
// 固定种子的线性同余:失败时可复现
let seed = 20261124;
const random = () => {
seed = (seed * 1664525 + 1013904223) % 4294967296;
return seed / 4294967296;
};
const pick = (list) => list[Math.floor(random() * list.length)];
let checked = 0;
for (let i = 0; i < 2000; i += 1) {
const cache = Math.floor(random() * 50000);
const prompt = cache + Math.floor(random() * 5000);
const completion = Math.floor(random() * 3000);
const other = {
model_price: -1,
model_ratio: pick([0.0375, 0.25, 0.575, 1.5, 7.5]),
completion_ratio: pick([1, 2, 4, 5]),
cache_tokens: cache,
cache_ratio: pick([0.02, 0.1, 0.5]),
group_ratio: pick([0.5, 0.782, 1, 1.3]),
};
const weighted =
(prompt -
cache +
cache * other.cache_ratio +
completion * other.completion_ratio) *
other.model_ratio *
other.group_ratio;
// 与后端一致:四舍五入到 1 个额度单位,有费用至少扣 1 个单位
const quota = weighted > 0 ? Math.max(1, Math.round(weighted)) : 0;
const breakdown = buildBillingBreakdown(
{ prompt_tokens: prompt, completion_tokens: completion, quota },
other,
);
if (!breakdown) continue;
checked += 1;
for (const display of [
usd,
{ digits: 6, toDisplay: (q) => (q / 500000) * 7.3 },
{ digits: 2, toDisplay: (q) => q },
]) {
const result = reconcileDisplayAmounts(breakdown, display);
assert.ok(addsUp(result, display.digits), `第 ${i} 条对不平`);
// 调整项只应是取整量级:不超过「行数 × 半个最小展示单位 + 1 个额度单位」
const bound =
(result.rows.length * 0.5 + 0.5) / 10 ** display.digits +
Math.abs(display.toDisplay(1));
assert.ok(
Math.abs(result.adjustment) <= bound + 1e-12,
`第 ${i} 条调整项过大`,
);
}
}
assert.ok(checked > 1500, `随机样本大多应可拆分,实际 ${checked}`);
});
@@ -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 });
}
});