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
@@ -155,6 +155,7 @@ const originInputs = {
thinking_to_content: false,
proxy: '',
pass_through_body_enabled: false,
pass_through_model_mapping_enabled: false,
chat_image_to_images_enabled: false,
system_prompt: '',
system_prompt_override: false,
@@ -404,6 +405,7 @@ const EditChannelModal = (props) => {
thinking_to_content: false,
proxy: '',
pass_through_body_enabled: false,
pass_through_model_mapping_enabled: false,
chat_image_to_images_enabled: false,
system_prompt: '',
system_prompt_override: false,
@@ -602,6 +604,8 @@ const EditChannelModal = (props) => {
data.proxy = parsedSettings.proxy || '';
data.pass_through_body_enabled =
parsedSettings.pass_through_body_enabled || false;
data.pass_through_model_mapping_enabled =
parsedSettings.pass_through_model_mapping_enabled === true;
data.chat_image_to_images_enabled =
parsedSettings.chat_image_to_images_enabled || false;
data.system_prompt = parsedSettings.system_prompt || '';
@@ -643,6 +647,7 @@ const EditChannelModal = (props) => {
data.thinking_to_content = false;
data.proxy = '';
data.pass_through_body_enabled = false;
data.pass_through_model_mapping_enabled = false;
data.chat_image_to_images_enabled = false;
data.system_prompt = '';
data.system_prompt_override = false;
@@ -665,6 +670,7 @@ const EditChannelModal = (props) => {
data.thinking_to_content = false;
data.proxy = '';
data.pass_through_body_enabled = false;
data.pass_through_model_mapping_enabled = false;
data.chat_image_to_images_enabled = false;
data.system_prompt = '';
data.system_prompt_override = false;
@@ -778,6 +784,8 @@ const EditChannelModal = (props) => {
thinking_to_content: data.thinking_to_content,
proxy: data.proxy,
pass_through_body_enabled: data.pass_through_body_enabled,
pass_through_model_mapping_enabled:
data.pass_through_model_mapping_enabled,
chat_image_to_images_enabled:
data.chat_image_to_images_enabled || false,
system_prompt: data.system_prompt,
@@ -1065,6 +1073,7 @@ const EditChannelModal = (props) => {
thinking_to_content: false,
proxy: '',
pass_through_body_enabled: false,
pass_through_model_mapping_enabled: false,
chat_image_to_images_enabled: false,
system_prompt: '',
system_prompt_override: false,
@@ -1394,6 +1403,8 @@ const EditChannelModal = (props) => {
thinking_to_content: localInputs.thinking_to_content || false,
proxy: localInputs.proxy || '',
pass_through_body_enabled: localInputs.pass_through_body_enabled || false,
pass_through_model_mapping_enabled:
localInputs.pass_through_model_mapping_enabled === true,
chat_image_to_images_enabled:
localInputs.chat_image_to_images_enabled || false,
system_prompt: localInputs.system_prompt || '',
@@ -1499,6 +1510,7 @@ const EditChannelModal = (props) => {
delete localInputs.thinking_to_content;
delete localInputs.proxy;
delete localInputs.pass_through_body_enabled;
delete localInputs.pass_through_model_mapping_enabled;
delete localInputs.chat_image_to_images_enabled;
delete localInputs.client_only;
delete localInputs.os_restriction;
@@ -3514,6 +3526,22 @@ const EditChannelModal = (props) => {
extraText={t('启用请求体透传功能')}
/>
<Form.Switch
field='pass_through_model_mapping_enabled'
label={t('透传时应用模型映射')}
checkedText={t('开')}
uncheckedText={t('关')}
onChange={(value) =>
handleChannelSettingsChange(
'pass_through_model_mapping_enabled',
value,
)
}
extraText={t(
'请求体透传时,使用本渠道模型重定向后的模型名发送给上游,其余字段按原请求转发。',
)}
/>
{(inputs.type === 1 || inputs.type === 3) && (
<Form.Switch
field='chat_image_to_images_enabled'
@@ -46,7 +46,9 @@ function TagEditorSection({ icon, color, title, description, children }) {
</Avatar>
<div>
<Text className='text-lg font-medium'>{title}</Text>
<div className='text-xs text-gray-600'>{description}</div>
<Text type='secondary' className='block text-xs'>
{description}
</Text>
</div>
</div>
{children}
@@ -1,9 +1,11 @@
import React, { useState } from 'react';
import { Button } from 'antd';
import { Copy, Plus, Trash2 } from '@/components/common/icons/ActionIcons';
import { isAdmin } from '../../../helpers';
const RedemptionsActions = ({
canQuery,
canCreate,
canDelete,
selectedKeys,
busy,
setEditingRedemption,
@@ -32,16 +34,18 @@ const RedemptionsActions = ({
return (
<div className='console-list-tool-actions'>
<Button
icon={<Copy size={16} aria-hidden />}
disabled={busy || selectedKeys.length === 0}
loading={copying}
onClick={handleCopy}
>
{t('复制所选兑换码到剪贴板')}
</Button>
{canQuery && (
<Button
icon={<Copy size={16} aria-hidden />}
disabled={busy || selectedKeys.length === 0}
loading={copying}
onClick={handleCopy}
>
{t('复制所选兑换码到剪贴板')}
</Button>
)}
{isAdmin() && (
{canDelete && (
<Button
danger
className='redemption-invalid-action'
@@ -52,7 +56,7 @@ const RedemptionsActions = ({
{t('清除失效兑换码')}
</Button>
)}
{isAdmin() && (
{canCreate && (
<Button
type='primary'
className='console-create-action'
@@ -1,6 +1,6 @@
import React from 'react';
import { Button, Tag, Tooltip } from 'antd';
import { renderQuota, timestamp2string, isAdmin } from '../../../helpers';
import { renderQuota, timestamp2string } from '../../../helpers';
import {
REDEMPTION_STATUS,
REDEMPTION_STATUS_MAP,
@@ -44,6 +44,8 @@ export const renderRedemptionStatus = (status, record, t) => {
* Get redemption code table column definitions
*/
export const getRedemptionsColumns = ({
canEdit,
canDelete,
t,
manageRedemption,
copyText,
@@ -125,7 +127,7 @@ export const getRedemptionsColumns = ({
>
{t('复制')}
</Button>
{isAdmin() && (
{canEdit && (
<>
<Button
type='link'
@@ -156,16 +158,18 @@ export const getRedemptionsColumns = ({
{isUnused ? t('禁用') : t('启用')}
</Button>
)}
<Button
type='link'
size='small'
danger
onClick={() => showDeleteRedemptionModal(record)}
>
{t('删除')}
</Button>
</>
)}
{canDelete && (
<Button
type='link'
size='small'
danger
onClick={() => showDeleteRedemptionModal(record)}
>
{t('删除')}
</Button>
)}
</div>
);
},
@@ -9,6 +9,8 @@ const SELECTION_COLUMN_WIDTH = 34;
const RedemptionsTable = (redemptionsData) => {
const {
canEdit,
canDelete,
redemptions,
loading,
searching,
@@ -35,6 +37,8 @@ const RedemptionsTable = (redemptionsData) => {
// Get all columns
const columns = getRedemptionsColumns({
canEdit,
canDelete,
t,
manageRedemption,
copyText,
@@ -71,7 +75,7 @@ const RedemptionsTable = (redemptionsData) => {
/>
<DeleteRedemptionModal
visible={showDeleteModal}
visible={canDelete && showDeleteModal}
onCancel={() => setShowDeleteModal(false)}
record={deletingRecord}
manageRedemption={manageRedemption}
+54 -29
View File
@@ -8,11 +8,17 @@ import EditRedemptionModal from './modals/EditRedemptionModal';
import { useRedemptionsData } from '../../../hooks/redemptions/useRedemptionsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils';
import { isAdmin } from '@/helpers';
import { usePerm } from '@/authz';
import '../../console/module-alignment.css';
import './redemptions.css';
const RedemptionsPage = () => {
const redemptionsData = useRedemptionsData();
const canQuery = usePerm('platform.redemption.query', isAdmin);
const canCreate = usePerm('platform.redemption.create', isAdmin);
const canEdit = usePerm('platform.redemption.edit', isAdmin);
const canDelete = usePerm('platform.redemption.delete', isAdmin);
const redemptionsData = useRedemptionsData(canQuery);
const isMobile = useIsMobile();
const {
@@ -49,34 +55,44 @@ const RedemptionsPage = () => {
<EditRedemptionModal
refresh={refresh}
editingRedemption={editingRedemption}
visible={showEdit}
visible={
showEdit &&
(editingRedemption.id === undefined ? canCreate : canQuery && canEdit)
}
handleClose={closeEdit}
/>
<CardPro
tableTitle={t('兑换码列表')}
searchArea={
<RedemptionsFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
searchRedemptions={searchRedemptions}
activePage={redemptionsData.activePage}
setSelectedKeys={redemptionsData.setSelectedKeys}
loading={loading}
searching={searching}
t={t}
/>
canQuery && (
<RedemptionsFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
searchRedemptions={searchRedemptions}
activePage={redemptionsData.activePage}
setSelectedKeys={redemptionsData.setSelectedKeys}
loading={loading}
searching={searching}
t={t}
/>
)
}
type='type1'
descriptionArea={
<RedemptionsDescription
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
canQuery && (
<RedemptionsDescription
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
)
}
tableActions={
<RedemptionsActions
canQuery={canQuery}
canCreate={canCreate}
canDelete={canDelete}
selectedKeys={selectedKeys}
busy={loading || searching}
setEditingRedemption={setEditingRedemption}
@@ -86,20 +102,29 @@ const RedemptionsPage = () => {
t={t}
/>
}
paginationArea={createCardProPagination({
preservePage: true,
showRange: false,
currentPage: redemptionsData.activePage,
pageSize: redemptionsData.pageSize,
total: redemptionsData.tokenCount,
onPageChange: redemptionsData.handlePageChange,
onPageSizeChange: redemptionsData.handlePageSizeChange,
isMobile: isMobile,
t: redemptionsData.t,
})}
paginationArea={
canQuery &&
createCardProPagination({
preservePage: true,
showRange: false,
currentPage: redemptionsData.activePage,
pageSize: redemptionsData.pageSize,
total: redemptionsData.tokenCount,
onPageChange: redemptionsData.handlePageChange,
onPageSizeChange: redemptionsData.handlePageSizeChange,
isMobile: isMobile,
t: redemptionsData.t,
})
}
t={redemptionsData.t}
>
<RedemptionsTable {...redemptionsData} />
{canQuery && (
<RedemptionsTable
{...redemptionsData}
canEdit={canEdit}
canDelete={canDelete}
/>
)}
</CardPro>
</>
);
@@ -261,20 +261,11 @@ const EditTokenModal = (props) => {
setLoading(false);
};
const onScopeChange = useEffectEvent(() => {
if (formApiRef.current) {
if (!isEdit) {
formApiRef.current.setValues(getInitValues());
}
}
loadModels();
loadGroups();
loadSkillOptions();
});
useEffect(() => onScopeChange(), [onScopeChange, props.editingToken.id]);
const onVisibilityChange2 = useEffectEvent(() => {
const onVisibilityChange = useEffectEvent(() => {
if (props.visiable) {
loadModels();
loadGroups();
loadSkillOptions();
if (isEdit) {
loadToken();
} else {
@@ -295,8 +286,8 @@ const EditTokenModal = (props) => {
}
});
useEffect(
() => onVisibilityChange2(),
[onVisibilityChange2, props.visiable, props.editingToken.id],
() => onVisibilityChange(),
[onVisibilityChange, props.visiable, props.editingToken.id],
);
const generateRandomSuffix = () => {
@@ -74,6 +74,7 @@
.usage-billing-detail .usage-billing-heading {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 5px;
line-height: 20px;
@@ -84,6 +85,127 @@
flex-shrink: 0;
}
/* 「仅超级管理员可见」提示:跟在区块标题后,不继承标题的大写与字距 */
.usage-billing-root-hint {
margin-left: 4px;
padding: 0 6px;
border: 1px solid var(--border-subtle);
border-radius: 6px;
color: var(--text-secondary);
font-size: 12px;
font-weight: 400;
letter-spacing: 0;
line-height: 18px;
text-transform: none;
}
/* 计费详情 · 费用明细:公式行 + 分项表(两处日志页共用,颜色只取语义变量) */
.usage-billing-formula {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
padding: 8px 12px;
border-radius: 8px;
background: var(--ui-color-fill-0);
color: var(--text-secondary);
font-size: 13px;
line-height: 22px;
}
.usage-billing-formula-label {
color: var(--text-primary);
font-weight: 600;
}
/* 一项 = 名称 + 金额。窄屏下名称可以折行,金额不拆开:整项不换行的话,较长的名称
(其他语言里更长)会撑出灰底,被弹窗的横向裁剪截掉末尾几位数字 */
.usage-billing-formula-term {
display: inline-flex;
flex-wrap: wrap;
align-items: baseline;
gap: 0 4px;
min-width: 0;
overflow-wrap: anywhere;
}
.usage-billing-formula-term strong {
color: var(--text-primary);
font-weight: 600;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.usage-billing-formula-total {
color: var(--brand-primary);
font-size: 15px;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.usage-billing-table-wrap {
margin-top: 8px;
overflow-x: auto;
}
.usage-billing-table {
width: 100%;
min-width: 480px;
border-collapse: collapse;
font-size: 13px;
line-height: 20px;
}
.usage-billing-table th,
.usage-billing-table td {
padding: 8px;
border-bottom: 1px solid var(--border-subtle);
color: var(--text-primary);
font-weight: 400;
text-align: right;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.usage-billing-table th:first-child {
text-align: left;
white-space: normal;
}
.usage-billing-table thead th {
color: var(--text-secondary);
font-size: 12px;
}
.usage-billing-table tbody td:last-child {
font-weight: 600;
}
.usage-billing-table-note {
display: block;
color: var(--text-secondary);
font-size: 12px;
line-height: 18px;
}
.usage-billing-table tfoot th,
.usage-billing-table tfoot td {
border-bottom: 0;
font-size: 14px;
font-weight: 600;
}
.usage-billing-table tfoot td {
color: var(--brand-primary);
}
.usage-billing-footnote {
margin-top: 4px;
color: var(--text-secondary);
font-size: 12px;
line-height: 18px;
}
.usage-logs-date-panel {
--usage-date-accent: var(--brand-gradient-via);
--usage-date-accent-strong: var(--brand-gradient-to);
@@ -3,19 +3,34 @@ import React, { useMemo, useState } from 'react';
import AntTable from '../../ui/CenterActionTable';
import { Button as AntButton } from 'antd';
import { Modal, Typography } from '@/components/ui';
import i18next from 'i18next';
import {
Coins,
Cpu,
Gauge,
Landmark,
Layers3,
Percent,
ReceiptText,
RadioTower,
ShieldCheck,
Sparkles,
TrendingUp,
} from 'lucide-react';
import CardTable from '../../common/ui/CardTable';
import { getLogOther, renderQuota } from '../../../helpers';
import {
formatDiscountLabel,
getCurrencyConfig,
getLogOther,
getQuotaPerUnit,
renderQuota,
} from '../../../helpers';
import { getLogsColumns } from './UsageLogsColumnDefs';
import {
buildBillingBreakdown,
reconcileDisplayAmounts,
} from './billingBreakdown';
const { Text } = Typography;
@@ -28,7 +43,24 @@ const formatCount = (value) => {
const formatRatio = (value) => {
const num = Number(value);
if (!Number.isFinite(num)) return '-';
return `${Number.isInteger(num) ? num : num.toFixed(3).replace(/0+$/, '').replace(/\.$/, '')}x`;
// 保留到 6 位:倍率是费用明细里单价的构成因子,截到 3 位(0.7825 → 0.783)
// 用户照着界面上的数字就乘不出小计;toFixed 再转 Number 是为了去掉尾随 0 和浮点噪声
return `${Number(num.toFixed(6))}x`;
};
// 分项金额(额度单位,可带小数)→ 当前展示货币;trim 时去掉多余的尾随 0(用于单价)。
// 站点按额度展示时没有货币换算,小数位由 tokenDigits 单独控制
const formatAmount = (
quota,
{ digits = 6, tokenDigits = 2, trim = false } = {},
) => {
if (!Number.isFinite(quota)) return '-';
const { symbol, rate, type } = getCurrencyConfig();
const isToken = type === 'TOKENS';
const value = isToken ? quota : (quota / getQuotaPerUnit()) * rate;
let text = Math.abs(value).toFixed(isToken ? tokenDigits : digits);
if (trim) text = text.replace(/(\.\d{2}\d*?)0+$/, '$1');
return `${value < 0 ? '-' : ''}${isToken ? '' : symbol}${text}`;
};
const MetricCard = ({ icon: Icon, label, value, tone = 'brand', plain }) => {
@@ -67,6 +99,153 @@ const MetricCard = ({ icon: Icon, label, value, tone = 'brand', plain }) => {
);
};
const BillingBreakdown = ({ breakdown, t }) => {
const { symbol, rate, type } = getCurrencyConfig();
const isToken = type === 'TOKENS';
const digits = isToken ? 2 : 6;
const quotaPerUnit = getQuotaPerUnit();
// 各行与合计先换算成展示金额再对平:每行各自四舍五入后直接相加,常会和合计差最后一位
// (0.001315 + 0.001568 + 0.000550 = 0.003433,实扣 0.003432)。差额归入「舍入与其他
// 调整」一项,保证界面上的数字逐项相加恰好等于合计
const reconciled = reconcileDisplayAmounts(breakdown, {
digits,
// 与 renderQuota 是同一个表达式,合计才会和弹窗顶部的「本次花费」一致
toDisplay: (quota) => (isToken ? quota : (quota / quotaPerUnit) * rate),
});
const formatDisplayed = (amount) =>
`${amount < 0 ? '-' : ''}${isToken ? '' : symbol}${Math.abs(amount).toFixed(digits)}`;
const total = formatDisplayed(reconciled.total);
const itemLabels = {
input: t('输入'),
inputUncached: t('输入(未命中缓存)'),
cacheRead: t('缓存命中'),
cacheCreation: t('缓存创建'),
cacheCreation5m: t('5m 缓存创建'),
cacheCreation1h: t('1h 缓存创建'),
cacheCreationUnlabeled: t('未分档缓存创建'),
imageInput: t('图片输入'),
output: t('输出'),
textInput: t('文字输入'),
textOutput: t('文字输出'),
audioInput: t('音频输入'),
audioOutput: t('音频输出'),
webSearch: t('联网搜索'),
claudeWebSearch: t('Claude 联网搜索'),
fileSearch: t('文件搜索'),
imageGeneration: t('图片生成'),
perCall: t('按次计费'),
videoSecond: t('按秒计费'),
};
const ratioLabels = {
model: t('模型倍率'),
completion: t('输出倍率'),
cache: t('缓存倍率'),
cacheCreation: t('缓存创建倍率'),
image: t('图片倍率'),
audio: t('音频倍率'),
audioCompletion: t('音频输出倍率'),
group: t('分组倍率'),
};
const rows = reconciled.rows.map((item) => {
const isTokens = item.unit === 'tokens';
return {
key: item.key,
label: itemLabels[item.key] || item.key,
note: item.ratios
.map((ratio) => `${ratioLabels[ratio.key]} ${formatRatio(ratio.value)}`)
.join(' × '),
qty: isTokens
? `${formatCount(item.qty)} tokens`
: item.unit === 'seconds'
? t('{{n}} 秒', { n: formatCount(item.qty) })
: t('{{n}} 次', { n: formatCount(item.qty), count: item.qty }),
price: isTokens
? t('{{price}} / 1M tokens', {
price: formatAmount(item.unitQuota * 1000000, { trim: true }),
})
: item.unit === 'seconds'
? t('{{price}} / 秒', {
price: formatAmount(item.unitQuota, { trim: true }),
})
: t('{{price}} / 次', {
price: formatAmount(item.unitQuota, { trim: true }),
}),
amount: item.amount,
};
});
if (reconciled.adjustment !== 0) {
rows.push({
key: 'adjustment',
label: t('舍入与其他调整'),
amount: reconciled.adjustment,
});
}
return (
<>
<div className='usage-billing-formula' aria-label={t('计算公式')}>
<span className='usage-billing-formula-label'>{t('总金额')}</span>
{rows.map((row, index) => (
<React.Fragment key={row.key}>
<span className='usage-billing-formula-op'>
{index === 0 ? '=' : row.amount < 0 ? '−' : '+'}
</span>
<span className='usage-billing-formula-term'>
<span>{row.label}</span>
<strong>
{formatDisplayed(
index === 0 ? row.amount : Math.abs(row.amount),
)}
</strong>
</span>
</React.Fragment>
))}
<span className='usage-billing-formula-op'>=</span>
<strong className='usage-billing-formula-total'>{total}</strong>
</div>
<div className='usage-billing-table-wrap'>
<table className='usage-billing-table'>
<thead>
<tr>
<th scope='col'>{t('计费项')}</th>
<th scope='col'>{t('用量')}</th>
<th scope='col'>{t('单价')}</th>
<th scope='col'>{t('小计')}</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.key}>
<th scope='row'>
<span>{row.label}</span>
{row.note && (
<span className='usage-billing-table-note'>{row.note}</span>
)}
</th>
<td>{row.qty || '-'}</td>
<td>{row.price || '-'}</td>
<td>{formatDisplayed(row.amount)}</td>
</tr>
))}
</tbody>
<tfoot>
<tr>
<th scope='row' colSpan={3}>
{t('合计')}
</th>
<td>{total}</td>
</tr>
</tfoot>
</table>
</div>
<div className='usage-billing-footnote'>
{t('各项小计为四舍五入后的近似值,合计以实际扣费为准')}
</div>
</>
);
};
const DetailPill = ({ label, value, plain }) => {
if (value === undefined || value === null || value === '' || value === '-')
return null;
@@ -116,27 +295,40 @@ const UsageBillingDetail = ({
: other.group_ratio;
const details = [
{ label: t('输入'), value: formatCount(inputTokens) },
outputTokens > 0 && { label: t('输出'), value: formatCount(outputTokens) },
inputTokens > 0 && {
label: t('输入'),
usage: 'tokens',
value: formatCount(inputTokens),
},
outputTokens > 0 && {
label: t('输出'),
usage: 'tokens',
value: formatCount(outputTokens),
},
other.cache_tokens > 0 && {
label: t('缓存命中'),
usage: 'tokens',
value: formatCount(other.cache_tokens),
},
!hasSplitCacheCreation &&
other.cache_creation_tokens > 0 && {
label: t('缓存创建'),
usage: 'tokens',
value: formatCount(other.cache_creation_tokens),
},
other.cache_creation_tokens_5m > 0 && {
label: t('5m 缓存创建'),
usage: 'tokens',
value: formatCount(other.cache_creation_tokens_5m),
},
other.cache_creation_tokens_1h > 0 && {
label: t('1h 缓存创建'),
usage: 'tokens',
value: formatCount(other.cache_creation_tokens_1h),
},
showUnlabeledCacheCreation && {
label: t('未分档缓存创建'),
usage: 'tokens',
value: formatCount(unlabeledCacheCreation),
},
other.model_ratio != null && {
@@ -182,14 +374,17 @@ const UsageBillingDetail = ({
},
other.audio_input > 0 && {
label: t('音频输入'),
usage: 'tokens',
value: formatCount(other.audio_input),
},
other.audio_output > 0 && {
label: t('音频输出'),
usage: 'tokens',
value: formatCount(other.audio_output),
},
other.audio_input_token_count > 0 && {
label: t('音频计费 Tokens'),
usage: 'tokens',
value: formatCount(other.audio_input_token_count),
},
other.audio_ratio != null &&
@@ -205,17 +400,29 @@ const UsageBillingDetail = ({
other.image &&
other.image_output > 0 && {
label: t('图片 Tokens'),
usage: 'tokens',
value: formatCount(other.image_output),
},
other.web_search && {
label: t('联网搜索'),
usage: 'webSearch',
value: t('{{n}} 次', {
n: formatCount(other.web_search_call_count || 0),
count: other.web_search_call_count || 0,
}),
},
// 模型名以 search-preview 结尾却由 Claude 渠道承接时,两种联网搜索各计一笔
other.claude_web_search_call_count > 0 && {
label: t('Claude 联网搜索'),
usage: 'claudeWebSearch',
value: t('{{n}} 次', {
n: formatCount(other.claude_web_search_call_count),
count: other.claude_web_search_call_count,
}),
},
other.file_search && {
label: t('文件搜索'),
usage: 'fileSearch',
value: t('{{n}} 次', {
n: formatCount(other.file_search_call_count || 0),
count: other.file_search_call_count || 0,
@@ -223,10 +430,28 @@ const UsageBillingDetail = ({
},
other.image_generation_call && {
label: t('图片生成'),
usage: 'imageGeneration',
value: t('已计费'),
},
].filter(Boolean);
const breakdown = buildBillingBreakdown(record, other, {
quotaPerUnit: getQuotaPerUnit(),
});
// 已经在费用明细里逐行列出的用量不在成本因子区重复。按次 / 按秒计费的明细里没有
// token 行,这类日志的 token 用量仍然留在这里,否则它在弹窗里就看不到了
const breakdownKeys = new Set(
(breakdown?.items || []).map((item) => item.key),
);
const hasTokenRows = (breakdown?.items || []).some(
(item) => item.unit === 'tokens',
);
const isItemised = (item) =>
item.usage === 'tokens' ? hasTokenRows : breakdownKeys.has(item.usage);
const sectionClass = plain
? 'usage-billing-factors'
: 'mt-3 rounded-2xl border border-white/55 bg-white/[0.35] p-3 backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.04]';
const mappedModel =
other?.is_model_mapped &&
other?.upstream_model_name &&
@@ -238,6 +463,19 @@ const UsageBillingDetail = ({
? t('本地计费')
: t('上游返回')
: '';
const factorPills = [
...details.filter((item) => !item.usage || !isItemised(item)),
mappedModel && { label: t('实际模型'), value: other.upstream_model_name },
billingMode && { label: t('计费源'), value: billingMode },
// 与 DetailPill 的判空同口径('-' 是倍率无法解析时的占位),否则整块可能只剩一个空框
].filter(
(item) =>
item &&
item.value !== undefined &&
item.value !== null &&
item.value !== '' &&
item.value !== '-',
);
const metrics = [
{
icon: Coins,
@@ -267,6 +505,45 @@ const UsageBillingDetail = ({
},
].filter(Boolean);
// 超管指标只在超级管理员的接口响应里存在(后端按角色附加),其余角色拿不到
const rootBilling =
Number(other.root_billing?.overall_ratio) > 0 ? other.root_billing : null;
const rootDiscount = Number(rootBilling?.discount);
// 接近 1 的比值不附折扣写法:0.999 会被四舍五入成「10折」
const rootDiscountLabel =
rootDiscount < 0.995
? formatDiscountLabel(rootDiscount, i18next.language)
: '';
const rootOfficialQuota = Number(rootBilling?.official_quota);
const rootMetrics = rootBilling
? [
{
icon: Landmark,
label: t('官方价金额(1 倍率)'),
// 不足 1 个额度单位的金额按默认位数会显示成 0,多给几位
value: formatAmount(
rootOfficialQuota,
rootOfficialQuota < 1 ? { digits: 8, tokenDigits: 6 } : undefined,
),
tone: 'cyan',
},
{
icon: TrendingUp,
label: t('整体倍率'),
value: formatRatio(rootBilling.overall_ratio),
tone: 'brand',
},
{
icon: Percent,
label: t('实际折扣'),
value: Number.isFinite(rootDiscount)
? `${Number(rootDiscount.toFixed(4))}${rootDiscountLabel ? ` · ${rootDiscountLabel}` : ''}`
: '-',
tone: 'emerald',
},
]
: [];
if (record.type !== 2) {
return (
<div className='usage-billing-detail'>
@@ -294,7 +571,9 @@ const UsageBillingDetail = ({
<span>{t('计费摘要')}</span>
</div>
<Text type='tertiary' size='small'>
{t('保留关键成本因子,省略冗长计算公式')}
{breakdown
? t('总金额 = 各计费项小计之和,小计 = 用量 × 单价')
: t('保留关键成本因子,省略冗长计算公式')}
</Text>
</div>
<div className='rounded-full border border-brand/20 bg-brand/10 px-3 py-1 text-sm font-semibold text-brand-deep dark:bg-brand/15 dark:text-brand-from'>
@@ -308,33 +587,60 @@ const UsageBillingDetail = ({
))}
</div>
<div
className={
plain
? 'usage-billing-factors'
: 'mt-3 rounded-2xl border border-white/55 bg-white/[0.35] p-3 backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.04]'
}
>
<div className='usage-billing-heading mb-2 flex items-center text-xs font-medium uppercase tracking-[0.18em] text-gray-400'>
<Layers3 size={13} />
<span>{t('成本因子')}</span>
{rootBilling && (
<div className={sectionClass}>
<div className='usage-billing-heading mb-2 flex items-center text-xs font-medium uppercase tracking-[0.18em] text-gray-400'>
<ShieldCheck size={13} />
<span>{t('超管指标')}</span>
<span className='usage-billing-root-hint'>
{t('仅超级管理员可见')}
</span>
</div>
<div className='grid gap-3 sm:grid-cols-3'>
{rootMetrics.map((item) => (
<MetricCard key={item.label} {...item} plain={plain} />
))}
</div>
<div className='usage-billing-footnote'>
{t(
'整体倍率 = 实扣 ÷ 官方价金额;实际折扣 = 整体倍率 ÷ 登记汇率({{rate}})',
{ rate: rootBilling.exchange_rate },
)}
</div>
</div>
<div className='flex flex-wrap gap-2'>
{details.map((item) => (
<DetailPill key={item.label} {...item} plain={plain} />
))}
{mappedModel && (
<DetailPill
label={t('实际模型')}
value={other.upstream_model_name}
plain={plain}
/>
)}
{billingMode && (
<DetailPill label={t('计费源')} value={billingMode} plain={plain} />
)}
)}
{breakdown && (
<div className={sectionClass}>
<div className='usage-billing-heading mb-2 flex items-center text-xs font-medium uppercase tracking-[0.18em] text-gray-400'>
<ReceiptText size={13} />
<span>{t('费用明细')}</span>
</div>
<BillingBreakdown breakdown={breakdown} t={t} />
</div>
</div>
)}
{/* 没有任何可展示的因子时整块不渲染(如只带按秒计价字段的任务日志),免得留一个空框 */}
{factorPills.length > 0 && (
<div className={sectionClass}>
<div className='usage-billing-heading mb-2 flex items-center text-xs font-medium uppercase tracking-[0.18em] text-gray-400'>
<Layers3 size={13} />
<span>{t('成本因子')}</span>
</div>
<div className='flex flex-wrap gap-2'>
{/* 列表是静态的,用下标作 key:两个标签在某个语言里译成同一个词时,
按标签作 key 会重复 */}
{factorPills.map((item, index) => (
<DetailPill
key={index}
label={item.label}
value={item.value}
plain={plain}
/>
))}
</div>
</div>
)}
</div>
);
};
@@ -0,0 +1,261 @@
// 计费详情的「分项小计」:把一条消费日志拆成 用量 × 单价 的若干行,各行相加即本次扣费。
// 口径逐项对照后端结算(relay/compatible_handler.go postConsumeQuota、
// service/quota.go PostClaudeConsumeQuota / calculateAudioQuota),改后端公式时须同步这里。
// 纯函数、不依赖浏览器环境,单测见 test/unit/usage-billing-breakdown.test.js。
const num = (value) => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
};
// 字段存在且是数字(null / undefined 视为缺失:Number(null) 是 0,会被当成有效值)
const hasNumber = (value) =>
value !== undefined && value !== null && Number.isFinite(Number(value));
// 实扣与分项之和最多允许差 1 个额度单位:结算四舍五入到 1 个单位、有费用至少扣 1 个单位,
// 历史日志是向下取整,这些差异都不超过 1 个单位。超过就说明这条日志的计费口径这里没覆盖
// (如任务按分辨率 / 时长系数计价),此时不展示拆分。不能按比例放宽:大额请求里
// 几千个额度单位的真实费用会被说成「舍入」
const MAX_UNEXPLAINED = 1;
const isReliable = (diff) => Math.abs(diff) <= MAX_UNEXPLAINED + 1e-6;
/**
* @param {object} record 日志行(prompt_tokens / completion_tokens / quota)
* @param {object} other getLogOther(record.other) 的结果
* @param {{ quotaPerUnit?: number }} options quotaPerUnit:1 美元对应的额度单位
* @returns {{ items: Array, estimated: number, actual: number } | null}
* items[].quota 为该项金额(额度单位,未取整);unitQuota 为每 1 个用量单位的金额;
* ratios 为单价的构成倍率;estimated 为各项之和,actual 为实扣。信息不足、或两者
* 对不上时返回 null。两者之间的取整差额由 reconcileDisplayAmounts 在展示层处理。
*/
export function buildBillingBreakdown(record, other, options = {}) {
if (!record || !other) return null;
// 差额调整行(实扣 = 实际 − 预扣)与 token 兜底预扣都不是「用量 × 单价」的完整一笔。
// 这两类日志同样会带按秒计价的字段(作为成本基准),不能当按秒计费来拆
if (other.quota_adjustment || other.video_token_fallback) return null;
const quotaPerUnit = num(options.quotaPerUnit) || 500000;
const actual = num(record.quota);
const group = hasNumber(other.group_ratio) ? num(other.group_ratio) : 1;
const groupRatio = { key: 'group', value: group };
const items = [];
const push = (key, qty, unit, unitQuota, ratios) => {
if (!(qty > 0)) return;
items.push({ key, qty, unit, unitQuota, ratios, quota: qty * unitQuota });
};
const finish = () => {
if (items.length === 0) return null;
const estimated = items.reduce((sum, item) => sum + item.quota, 0);
// 分项全是 0 元却有实扣:整笔钱都没解释,不能把它整个算作「舍入与其他调整」
if (estimated === 0 && actual !== 0) return null;
const diff = actual - estimated;
if (!isReliable(diff)) return null;
return { items, estimated, actual };
};
// 独立标价项(美元价 × 分组倍率),不乘模型倍率;按次计费的请求同样会叠加工具调用费
const pushExtras = (audioSeparateTokens = 0) => {
push(
'audioInput',
audioSeparateTokens,
'tokens',
(num(other.audio_input_price) / 1000000) * quotaPerUnit * group,
[groupRatio],
);
if (other.web_search) {
push(
'webSearch',
num(other.web_search_call_count),
'calls',
(num(other.web_search_price) / 1000) * quotaPerUnit * group,
[groupRatio],
);
}
// 模型名以 search-preview 结尾却由 Claude 渠道承接时,两种联网搜索各计一笔
push(
'claudeWebSearch',
num(other.claude_web_search_call_count),
'calls',
(num(other.claude_web_search_price) / 1000) * quotaPerUnit * group,
[groupRatio],
);
if (other.file_search) {
push(
'fileSearch',
num(other.file_search_call_count),
'calls',
(num(other.file_search_price) / 1000) * quotaPerUnit * group,
[groupRatio],
);
}
if (other.image_generation_call) {
push(
'imageGeneration',
1,
'calls',
num(other.image_generation_call_price) * quotaPerUnit * group,
[groupRatio],
);
}
};
// 视频按秒计费:单价 × 时长 × 分组倍率(此时 model_price 为 0,不是按次)
const videoSecondPrice = num(other.video_second_unit_price);
if (videoSecondPrice > 0) {
const videoGroup = hasNumber(other.video_second_group_ratio)
? num(other.video_second_group_ratio)
: group;
push(
'videoSecond',
num(other.video_second_duration),
'seconds',
videoSecondPrice * quotaPerUnit * videoGroup,
[{ key: 'group', value: videoGroup }],
);
return finish();
}
// 按次计费:模型价格 × 分组倍率。按倍率计费的日志 model_price 为 -1;
// 个别日志写的是 0 却带着有效的模型倍率,这类仍按 token 拆分
const modelPrice = hasNumber(other.model_price)
? Number(other.model_price)
: NaN;
const usesModelRatio = modelPrice === 0 && num(other.model_ratio) > 0;
if (Number.isFinite(modelPrice) && modelPrice !== -1 && !usesModelRatio) {
push('perCall', 1, 'calls', modelPrice * quotaPerUnit * group, [
groupRatio,
]);
pushExtras();
return finish();
}
if (!hasNumber(other.model_ratio)) return null;
const model = num(other.model_ratio);
const modelRatio = { key: 'model', value: model };
const completion = num(other.completion_ratio);
const completionRatio = { key: 'completion', value: completion };
// 按 token 计费的一行:用量 × 模型倍率 × 该项倍率 × 分组倍率
const pushTokens = (key, tokens, extraRatios = []) => {
const weight = extraRatios.reduce((acc, r) => acc * r.value, 1);
push(key, num(tokens), 'tokens', model * weight * group, [
modelRatio,
...extraRatios,
groupRatio,
]);
};
// 实时语音 / 音频:文字与音频各按自己的倍率
if (other.ws || other.audio) {
const audio = { key: 'audio', value: num(other.audio_ratio) };
const audioCompletion = {
key: 'audioCompletion',
value: num(other.audio_completion_ratio),
};
pushTokens('textInput', other.text_input);
pushTokens('textOutput', other.text_output, [completionRatio]);
pushTokens('audioInput', other.audio_input, [audio]);
pushTokens('audioOutput', other.audio_output, [audio, audioCompletion]);
return finish();
}
const cacheTokens = num(other.cache_tokens);
const tokens5m = num(other.cache_creation_tokens_5m);
const tokens1h = num(other.cache_creation_tokens_1h);
const hasSplit = tokens5m > 0 || tokens1h > 0;
// 与分档并存时未分档是独立一桶;没有分档时 cache_creation_tokens 整体就是这一桶
const tokensUnlabeled = hasSplit
? num(other.cache_creation_tokens_unlabeled)
: num(other.cache_creation_tokens);
const ratioUnlabeled = hasSplit
? num(other.cache_creation_ratio_unlabeled)
: num(other.cache_creation_ratio);
const creationTokens = tokens5m + tokens1h + tokensUnlabeled;
const imageTokens = other.image ? num(other.image_output) : 0;
const audioSeparateTokens = other.audio_input_seperate_price
? num(other.audio_input_token_count)
: 0;
// Claude 协议的 prompt_tokens 不含缓存;其余协议含缓存 / 图片 / 音频,须逐项剥离,
// 且与后端一致:不够减时不减(上游本就没把这部分算进 prompt_tokens)
let baseTokens = num(record.prompt_tokens);
if (!other.claude) {
for (const part of [
cacheTokens,
creationTokens,
imageTokens,
audioSeparateTokens,
]) {
if (part > 0 && baseTokens >= part) baseTokens -= part;
}
}
pushTokens(
cacheTokens > 0 || creationTokens > 0 ? 'inputUncached' : 'input',
baseTokens,
);
pushTokens('cacheRead', cacheTokens, [
{ key: 'cache', value: num(other.cache_ratio) },
]);
pushTokens('cacheCreation5m', tokens5m, [
{ key: 'cacheCreation', value: num(other.cache_creation_ratio_5m) },
]);
pushTokens('cacheCreation1h', tokens1h, [
{ key: 'cacheCreation', value: num(other.cache_creation_ratio_1h) },
]);
pushTokens(
hasSplit ? 'cacheCreationUnlabeled' : 'cacheCreation',
tokensUnlabeled,
[{ key: 'cacheCreation', value: ratioUnlabeled }],
);
pushTokens('imageInput', imageTokens, [
{ key: 'image', value: num(other.image_ratio) },
]);
pushTokens('output', record.completion_tokens, [completionRatio]);
pushExtras(audioSeparateTokens);
return finish();
}
/**
* 把分项与实扣换算成展示金额并对平。
*
* 各行先按展示精度四舍五入,再用一项「调整」吸收「展示合计 − 各行展示金额之和」,
* 保证界面上的数字逐项相加恰好等于合计——拿计算器把公式行加一遍就能对上。
* 调整项同时包含结算取整(四舍五入到 1 个额度单位、有费用至少扣 1 个单位)与
* 各行展示取整两部分误差。
*
* @param {{ items: Array, actual: number }} breakdown buildBillingBreakdown 的结果
* @param {{ toDisplay: (quota: number) => number, digits: number }} display
* toDisplay:额度单位 → 展示金额,须与页面其余位置的金额换算是同一个表达式;
* digits:展示保留的小数位
* @returns {{ rows: Array, adjustment: number, total: number }}
* rows[].amount、adjustment、total 都已按 digits 取整,且 Σ amount + adjustment 恰等于 total
*/
export function reconcileDisplayAmounts(breakdown, { toDisplay, digits }) {
const unit = 10 ** digits;
// 先 toFixed 再放大取整:toFixed 的舍入方向与页面上其余金额的展示一致;放大后的值
// 离整数只差浮点噪声,Math.round 不会再改变舍入方向。全程用整数个最小展示单位做加减,
// 避免 0.1 + 0.2 式的误差让「差额为 0」判断失准
const toUnits = (quota) =>
Math.round(Number(toDisplay(quota).toFixed(digits)) * unit);
let totalUnits = toUnits(breakdown.actual);
// 与 renderQuota 一致:实扣大于 0 却被舍成 0 时按最小展示单位显示
if (
totalUnits === 0 &&
breakdown.actual > 0 &&
toDisplay(breakdown.actual) > 0
)
totalUnits = 1;
let sumUnits = 0;
const rows = breakdown.items.map((item) => {
const amountUnits = toUnits(item.quota);
sumUnits += amountUnits;
return { ...item, amount: amountUnits / unit };
});
return {
rows,
adjustment: (totalUnits - sumUnits) / unit,
total: totalUnits / unit,
};
}
+4 -1
View File
@@ -2,8 +2,11 @@ import { Plus as ActionPlus } from '@/components/common/icons/ActionIcons';
import React from 'react';
import { Button } from 'antd';
import { isAdmin } from '../../../helpers';
import { usePerm } from '../../../authz';
const UsersActions = ({ setShowAddUser, t }) => {
// 已切换模块按权限点,未切换与原判断一致
const canCreate = usePerm('platform.user.create', isAdmin());
// Add new user
const handleAddUser = () => {
setShowAddUser(true);
@@ -11,7 +14,7 @@ const UsersActions = ({ setShowAddUser, t }) => {
return (
<div className='flex justify-end gap-2'>
{isAdmin() && (
{canCreate && (
<Button
className='console-create-action'
type='primary'
+112 -48
View File
@@ -16,9 +16,23 @@ import {
renderNumber,
renderQuota,
getUserData,
isAdmin,
} from '../../../helpers';
/**
* 当前登录人能否管理这一行(与后端 canManageUserOfRole 同口径,按钮权限另由 perms 决定)
* - 超级管理员:全部可管理
* - 用户管理已切到新体系:不能操作自己和超级管理员(目标权限是否被覆盖由后端校验)
* - 未切换:只能管理角色低于自己的用户
*/
const canManageRow = (record, enforced) => {
const me = getUserData();
const currentRole = Number(me?.role || 0);
const recordRole = Number(record.role || 0);
if (currentRole >= 100) return true;
if (enforced) return record.id !== me?.id && recordRole < 100;
return recordRole < currentRole;
};
/**
* Render user role
*/
@@ -98,19 +112,21 @@ const renderUsername = (text, record) => {
/**
* Render user statistics
*/
const renderStatistics = (text, record, showEnableDisableModal, t) => {
const renderStatistics = (text, record, showEnableDisableModal, perms, t) => {
const isDeleted = record.DeletedAt !== null;
const currentRole = Number(getUserData()?.role || 0);
const canManage =
isAdmin() && (currentRole >= 100 || Number(record.role || 0) < 100);
// 超级管理员是受保护对象,不可切换;其余按「禁用/启用」按钮权限与行级可管理性
const canToggle =
perms.canStatus &&
Number(record.role || 0) < 100 &&
canManageRow(record, perms.enforced);
const content = isDeleted ? (
<Tag color='red'>{t('已注销')}</Tag>
) : (
<TableStatusSwitch
checked={record.status === 1}
aria-label={t('状态')}
disabled={!canManage}
disabled={!canToggle}
onChange={(checked, event) => {
event.stopPropagation();
showEnableDisableModal(record, checked ? 'enable' : 'disable');
@@ -215,6 +231,9 @@ const renderOperations = (
showResetPasskeyModal,
showResetTwoFAModal,
showInvitedUsersModal,
showAssignRolesModal,
showAddQuotaModal,
perms,
t,
},
) => {
@@ -224,15 +243,23 @@ const renderOperations = (
const currentRole = Number(getUserData()?.role || 0);
const recordRole = Number(record.role || 0);
// 与后端 canManageUserOfRole 一致:非超级管理员只能管理角色低于自己的用户;提升/降级仅超级管理员
const canManage =
isAdmin() && (currentRole >= 100 || recordRole < currentRole);
const canChangeRole = canManage && currentRole >= 100 && recordRole < 100;
const manageable = canManageRow(record, perms.enforced);
// 提升/降级仅超级管理员;用户管理切到新体系后冻结,改用「分配角色」
const canChangeRole =
!perms.enforced &&
perms.canPromote &&
manageable &&
currentRole >= 100 &&
recordRole < 100;
const canEditRow = perms.canEdit && manageable;
// 分配平台角色:超级管理员本身不参与角色授权
const canAssignRow =
perms.canAssignRole && recordRole < 100 && !!showAssignRolesModal;
// 低频动作全部收进「更多」下拉,操作列稳定为一行三个控件,避免跨行撑高行高
const moreMenu = [];
// 低频动作收进「更多」下拉;分组之间用分割线
const groups = [];
if (canChangeRole) {
moreMenu.push(
groups.push([
{
key: 'promote',
label: t('提升'),
@@ -243,51 +270,82 @@ const renderOperations = (
label: t('降级'),
onClick: () => showDemoteModal(record),
},
{ type: 'divider' },
);
]);
}
moreMenu.push({
key: 'invitations',
label: t('邀请记录'),
onClick: () => showInvitedUsersModal(record),
});
if (canManage) {
moreMenu.push(
{ type: 'divider' },
{
key: 'reset-passkey',
label: t('重置 Passkey'),
onClick: () => showResetPasskeyModal(record),
},
{
key: 'reset-2fa',
label: t('重置 2FA'),
onClick: () => showResetTwoFAModal(record),
},
{ type: 'divider' },
groups.push([
{
key: 'invitations',
label: t('邀请记录'),
onClick: () => showInvitedUsersModal(record),
},
]);
const resetItems = [];
if (perms.canResetPasskey && manageable) {
resetItems.push({
key: 'reset-passkey',
label: t('重置 Passkey'),
onClick: () => showResetPasskeyModal(record),
});
}
if (perms.canReset2FA && manageable) {
resetItems.push({
key: 'reset-2fa',
label: t('重置 2FA'),
onClick: () => showResetTwoFAModal(record),
});
}
if (resetItems.length) groups.push(resetItems);
// 超级管理员不可注销(后端同样拒绝)
if (perms.canDelete && manageable && recordRole < 100) {
groups.push([
{
key: 'delete',
label: t('注销'),
danger: true,
onClick: () => showDeleteModal(record),
},
);
]);
}
const moreMenu = groups.flatMap((group, index) =>
index === 0
? group
: [{ type: 'divider', key: `divider-${index}` }, ...group],
);
return (
<TableRowActions items={moreMenu}>
{canManage && (
{(canEditRow || canAssignRow) && (
<>
<Button
type='link'
size='small'
onClick={() => {
setEditingUser(record);
setShowEditUser(true);
}}
>
{t('编辑')}
</Button>
{canEditRow && (
<Button
type='link'
size='small'
onClick={() => {
setEditingUser(record);
setShowEditUser(true);
}}
>
{t('编辑')}
</Button>
)}
{canEditRow && (
<Button
type='link'
size='small'
onClick={() => showAddQuotaModal(record)}
>
{t('添加额度')}
</Button>
)}
{canAssignRow && (
<Button
type='link'
size='small'
onClick={() => showAssignRolesModal(record)}
>
{t('分配角色')}
</Button>
)}
</>
)}
</TableRowActions>
@@ -308,6 +366,9 @@ export const getUsersColumns = ({
showResetPasskeyModal,
showResetTwoFAModal,
showInvitedUsersModal,
showAssignRolesModal,
showAddQuotaModal,
perms,
}) => {
return [
{
@@ -332,7 +393,7 @@ export const getUsersColumns = ({
title: t('状态'),
dataIndex: 'info',
render: (text, record, index) =>
renderStatistics(text, record, showEnableDisableModal, t),
renderStatistics(text, record, showEnableDisableModal, perms, t),
},
{
title: t('剩余额度/总额度'),
@@ -363,7 +424,7 @@ export const getUsersColumns = ({
title: t('操作'),
dataIndex: 'operate',
fixed: 'right',
width: 135,
width: 290,
render: (text, record, index) =>
renderOperations(text, record, {
setEditingUser,
@@ -375,6 +436,9 @@ export const getUsersColumns = ({
showResetPasskeyModal,
showResetTwoFAModal,
showInvitedUsersModal,
showAssignRolesModal,
showAddQuotaModal,
perms,
t,
}),
},
+17 -3
View File
@@ -7,7 +7,7 @@ import { IconSearch } from '@/components/ui/icons';
const UsersFilters = ({
formInitValues,
setFormApi,
searchUsers,
refresh,
loadUsers,
activePage,
pageSize,
@@ -17,8 +17,7 @@ const UsersFilters = ({
t,
}) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
(_, signal) =>
searchUsers(Math.max(1, activePage), pageSize, null, null, signal),
(_, signal) => refresh(activePage, pageSize, signal),
);
const formApiRef = useRef(null);
@@ -35,6 +34,7 @@ const UsersFilters = ({
initValues={{
...formInitValues,
searchGroup: formInitValues.searchGroup || undefined,
searchStatus: formInitValues.searchStatus || undefined,
}}
getFormApi={(api) => {
setFormApi(api);
@@ -71,6 +71,20 @@ const UsersFilters = ({
size='small'
/>
</div>
<div className='console-module-field'>
<Form.Select
label={t('状态')}
field='searchStatus'
placeholder={t('全部状态')}
optionList={[
{ value: 1, label: t('启用') },
{ value: 2, label: t('禁用') },
]}
className='w-full'
showClear
size='small'
/>
</div>
</div>
<ConsoleFilterActions
onReset={handleReset}
+65
View File
@@ -10,6 +10,10 @@ import DeleteUserModal from './modals/DeleteUserModal';
import ResetPasskeyModal from './modals/ResetPasskeyModal';
import ResetTwoFAModal from './modals/ResetTwoFAModal';
import InvitedUsersModal from './modals/InvitedUsersModal';
import AssignRolesModal from './modals/AssignRolesModal';
import AddUserQuotaModal from './modals/AddUserQuotaModal';
import { isAdmin, isRoot } from '../../../helpers';
import { usePerm, useAuthzView } from '../../../authz';
const UsersTable = (usersData) => {
const {
@@ -25,6 +29,7 @@ const UsersTable = (usersData) => {
setEditingUser,
setShowEditUser,
manageUser,
adjustUserQuota,
refresh,
resetUserPasskey,
resetUserTwoFA,
@@ -41,6 +46,33 @@ const UsersTable = (usersData) => {
const [showResetPasskeyModal, setShowResetPasskeyModal] = useState(false);
const [showResetTwoFAModal, setShowResetTwoFAModal] = useState(false);
const [showInvitedUsersModal, setShowInvitedUsersModal] = useState(false);
const [showAssignRolesModal, setShowAssignRolesModal] = useState(false);
const [showAddQuotaModal, setShowAddQuotaModal] = useState(false);
// 按钮权限:模块已切到新体系按权限点,未切换与原判断一致
const canEdit = usePerm('platform.user.edit', isAdmin());
const canStatus = usePerm('platform.user.status', isAdmin());
const canDelete = usePerm('platform.user.delete', isAdmin());
const canPromote = usePerm('platform.user.promote', isRoot());
const canResetPasskey = usePerm('platform.user.reset_passkey', isAdmin());
const canReset2FA = usePerm('platform.user.reset_2fa', isAdmin());
// 分配平台角色:模块切换前仅 root 可用;弹窗要拉取角色列表,须同时持有 platform.authz.role.query
const canAssignRoleOp = usePerm('platform.authz.role.assign', isRoot());
const canQueryRole = usePerm('platform.authz.role.query', isRoot());
// 用户管理模块是否已切到新体系:切换后提升/降级冻结,行级可管理性不再按 users.role 分层
const platformView = useAuthzView('platform');
const userModule = platformView?.moduleOf?.['platform.user.edit'];
const enforced = !!userModule && platformView.enforcedSet.has(userModule);
const perms = {
canEdit,
canStatus,
canDelete,
canPromote,
canResetPasskey,
canReset2FA,
canAssignRole: canAssignRoleOp && canQueryRole,
enforced,
};
// Modal handlers
const showPromoteUserModal = (user) => {
@@ -79,6 +111,16 @@ const UsersTable = (usersData) => {
setShowInvitedUsersModal(true);
};
const showAssignRolesUserModal = (user) => {
setModalUser(user);
setShowAssignRolesModal(true);
};
const showAddQuotaUserModal = (user) => {
setModalUser(user);
setShowAddQuotaModal(true);
};
// Modal confirm handlers
const handlePromoteConfirm = () => {
manageUser(modalUser.id, 'promote', modalUser);
@@ -90,6 +132,7 @@ const UsersTable = (usersData) => {
setShowDemoteModal(false);
};
// 状态 Switch 受控于 record.status:请求失败时 manageUser 已提示原因,列表保持原状态
const handleEnableDisableConfirm = () => {
manageUser(modalUser.id, enableDisableAction, modalUser);
setShowEnableDisableModal(false);
@@ -117,6 +160,9 @@ const UsersTable = (usersData) => {
showResetPasskeyModal: showResetPasskeyUserModal,
showResetTwoFAModal: showResetTwoFAUserModal,
showInvitedUsersModal: showInvitedUsersUserModal,
showAssignRolesModal: showAssignRolesUserModal,
showAddQuotaModal: showAddQuotaUserModal,
perms,
});
// Handle compact mode by removing fixed positioning
@@ -214,6 +260,25 @@ const UsersTable = (usersData) => {
user={modalUser}
t={t}
/>
<AssignRolesModal
visible={showAssignRolesModal}
onCancel={() => setShowAssignRolesModal(false)}
user={modalUser}
t={t}
/>
<AddUserQuotaModal
visible={showAddQuotaModal}
onCancel={() => setShowAddQuotaModal(false)}
onSubmit={adjustUserQuota}
user={
modalUser
? users.find((u) => u.id === modalUser.id) || modalUser
: null
}
t={t}
/>
</>
);
};
+1 -2
View File
@@ -27,7 +27,6 @@ const UsersPage = () => {
// Form state
formInitValues,
setFormApi,
searchUsers,
loadUsers,
activePage,
pageSize,
@@ -64,7 +63,7 @@ const UsersPage = () => {
<UsersFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
searchUsers={searchUsers}
refresh={refresh}
loadUsers={loadUsers}
activePage={activePage}
pageSize={pageSize}
@@ -1,7 +1,15 @@
import React, { useState, useRef } from 'react';
import { API, showError, showSuccess } from '../../../../helpers';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import { Button, SideSheet, Spin, Form, Row, Col } from '@/components/ui';
import {
Button,
SideSheet,
Spin,
Form,
Row,
Col,
Typography,
} from '@/components/ui';
import { useTranslation } from 'react-i18next';
const AddUserModal = (props) => {
@@ -70,6 +78,19 @@ const AddUserModal = (props) => {
}}
>
<Row gutter={12}>
<Col span={24}>
{/* 账号类型用语统一为"个人账号"(PRD AC52);平台角色不在新建表单中选择(AC57) */}
<Form.Slot label={t('账号类型')}>
<Typography.Text>{t('个人账号')}</Typography.Text>
<div>
<Typography.Text type='secondary' className='text-xs'>
{t(
'创建后为启用状态;平台角色请在列表操作列通过「分配角色」设置',
)}
</Typography.Text>
</div>
</Form.Slot>
</Col>
<Col span={24}>
<Form.Input
field='username'
@@ -0,0 +1,93 @@
import React, { useEffect, useState } from 'react';
import { Typography } from 'antd';
import { ConsoleModal } from '../../../console/ConsolePrimitives';
import QuotaInput from '../../../common/ui/QuotaInput';
import { renderQuota } from '../../../../helpers';
const { Text } = Typography;
// 添加额度弹窗(PRD §4.1、AC59):输入调整量(可正可负,不能为 0),实时展示
// 「当前剩余额度 + 调整额度 = 新剩余额度」;新剩余额度不能小于 0。
// QuotaInput 的 value/onChange 始终是内部额度单位,金额换算由它完成。
const AddUserQuotaModal = ({ visible, onCancel, onSubmit, user, t }) => {
const [delta, setDelta] = useState(null);
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (visible) setDelta(null);
}, [visible, user?.id]);
const current = parseInt(user?.quota) || 0;
const amount = Number.isFinite(delta) ? delta : 0;
const next = current + amount;
const error =
delta === null
? ''
: amount === 0
? t('调整额度不能为 0')
: next < 0
? t('调整后的剩余额度不能小于 0')
: '';
const canSubmit = delta !== null && !error;
const handleOk = async () => {
if (!canSubmit || submitting || !user?.id) return;
setSubmitting(true);
try {
const ok = await onSubmit(user.id, amount);
if (ok) onCancel();
} finally {
setSubmitting(false);
}
};
return (
<ConsoleModal
title={`${t('添加额度')} - ${user?.display_name || user?.username || ''}`}
open={visible}
onOk={handleOk}
onCancel={onCancel}
okText={t('确定')}
cancelText={t('取消')}
confirmLoading={submitting}
okButtonProps={{ disabled: !canSubmit }}
centered
destroyOnHidden
>
<div className='flex flex-col gap-3'>
<div>
<div className='mb-2'>
<Text>{t('调整额度(正数增加,负数减少)')}</Text>
</div>
<QuotaInput
value={delta}
onChange={setDelta}
placeholder={t('需要添加的金额(支持负数)')}
style={{ width: '100%' }}
status={error ? 'error' : undefined}
aria-label={t('调整额度')}
/>
{error && (
<div className='mt-1'>
<Text type='danger' className='text-xs'>
{error}
</Text>
</div>
)}
</div>
<Text type='secondary' className='tabular-nums'>
{t(
'当前剩余额度 {{current}} + 调整额度 {{delta}} = 新剩余额度 {{next}}',
{
current: renderQuota(current),
delta: renderQuota(amount),
next: renderQuota(next),
},
)}
</Text>
</div>
</ConsoleModal>
);
};
export default AddUserQuotaModal;
@@ -0,0 +1,131 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState } from 'react';
import { Select, Spin, Tag, Typography } from 'antd';
import { ConsoleModal } from '../../../console/ConsolePrimitives';
import { API, showError, showSuccess } from '../../../../helpers';
// 分配平台角色弹窗:读写 /api/user/:id/roles(整体替换)。
// 角色列表来自 /api/authz/platform/roles,停用的角色仍可展示但标注"停用"。
const AssignRolesModal = ({ visible, onCancel, user, t }) => {
const [roles, setRoles] = useState([]);
const [selected, setSelected] = useState([]);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!visible || !user?.id) return;
let alive = true;
const load = async () => {
setLoading(true);
try {
const [rolesRes, mineRes] = await Promise.all([
API.get('/api/authz/platform/roles'),
API.get(`/api/user/${user.id}/roles`),
]);
if (!alive) return;
if (rolesRes.data.success) {
setRoles(rolesRes.data.data || []);
} else {
showError(rolesRes.data.message);
}
if (mineRes.data.success) {
setSelected(mineRes.data.data || []);
} else {
showError(mineRes.data.message);
}
} catch (err) {
showError(err);
} finally {
if (alive) setLoading(false);
}
};
load();
return () => {
alive = false;
};
}, [visible, user?.id]);
const handleOk = async () => {
if (!user?.id || saving) return;
setSaving(true);
try {
const res = await API.put(`/api/user/${user.id}/roles`, {
ids: selected,
});
if (res.data.success) {
showSuccess(t('角色已更新'));
onCancel();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err);
} finally {
setSaving(false);
}
};
return (
<ConsoleModal
title={`${t('分配角色')} - ${user?.display_name || user?.username || ''}`}
open={visible}
onOk={handleOk}
onCancel={onCancel}
confirmLoading={saving}
okButtonProps={{ disabled: loading }}
okText={t('保存')}
cancelText={t('取消')}
centered
width='min(520px, calc(100vw - 32px))'
>
<Spin spinning={loading}>
<Typography.Text type='secondary' className='text-xs'>
{t('为该用户分配平台角色,保存后整体替换原有角色。')}
</Typography.Text>
<Select
className='mt-3'
style={{ width: '100%' }}
mode='multiple'
value={selected}
onChange={setSelected}
placeholder={t('选择平台角色')}
aria-label={t('选择平台角色')}
options={roles.map((r) => ({
value: r.id,
label: (
<span className='inline-flex items-center gap-1'>
<span>{r.name}</span>
{r.status !== 1 ? (
<Tag variant='filled'>{t('停用')}</Tag>
) : null}
</span>
),
searchText: `${r.name} ${r.code}`,
}))}
showSearch={{ optionFilterProp: 'searchText' }}
notFoundContent={t('暂无角色')}
/>
</Spin>
</ConsoleModal>
);
};
export default AssignRolesModal;
@@ -30,6 +30,7 @@ const DeleteUserModal = ({
onCancel={onCancel}
onOk={handleConfirm}
type='danger'
okType='danger'
>
{t('相当于删除用户,此修改将不可逆')}
</TableActionModal>
@@ -5,7 +5,6 @@ import { API, showError, showSuccess, renderQuota } from '../../../../helpers';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import {
Button,
Modal,
SideSheet,
Spin,
Typography,
@@ -15,27 +14,28 @@ import {
Row,
Col,
} from '@/components/ui';
import QuotaInput, { FormQuotaInput } from '../../../common/ui/QuotaInput';
import { FormQuotaInput } from '../../../common/ui/QuotaInput';
import {
User as ActionUser,
Link as ActionLink,
Users as ActionUsers,
Plus as ActionPlus,
} from '@/components/common/icons/ActionIcons';
import { toGroupList } from '@/helpers/groupList';
const { Text } = Typography;
// User.Group is a single lookup key. Preserve historical keys containing commas.
const userGroupKey = (group) =>
Array.isArray(group) ? group.join(',') : group;
const EditUserModal = (props) => {
const { t } = useTranslation();
const userId = props.editingUser.id;
const [loading, setLoading] = useState(true);
// 剩余额度只读展示(PRD AC56):调整额度走列表操作列的「添加额度」(按调整量累加)
const [loadedQuota, setLoadedQuota] = useState(0);
const [loadedUserId, setLoadedUserId] = useState(null);
const [submitting, setSubmitting] = useState(false);
const pending = useRef(false);
const [addQuotaModalOpen, setIsModalOpen] = useState(false);
const [addQuotaLocal, setAddQuotaLocal] = useState('');
const isMobile = useIsMobile();
const [groupOptions, setGroupOptions] = useState([]);
const [levelOptions, setLevelOptions] = useState([]);
@@ -63,7 +63,9 @@ const EditUserModal = (props) => {
const fetchGroups = async () => {
try {
let res = await API.get(`/api/group/`);
setGroupOptions(res.data.data.map((g) => ({ label: g, value: g })));
if (res.data.success && Array.isArray(res.data.data)) {
setGroupOptions(res.data.data.map((g) => ({ label: g, value: g })));
}
} catch (e) {
showError(e.message);
}
@@ -95,8 +97,6 @@ const EditUserModal = (props) => {
const handleCancel = () => {
if (pending.current) return;
setIsModalOpen(false);
setAddQuotaLocal('');
props.handleClose();
};
@@ -112,11 +112,14 @@ const EditUserModal = (props) => {
const { data: response } = await API.get(url);
if (!isCurrent()) return;
if (response.success) {
setLoadedQuota(Number(response.data.quota) || 0);
formApiRef.current?.setValues({
...getInitValues(),
...response.data,
...(userId && {
group: toGroupList(response.data.group ?? 'default'),
group: [userGroupKey(response.data.group) ?? 'default'].filter(
Boolean,
),
}),
password: '',
});
@@ -147,13 +150,13 @@ const EditUserModal = (props) => {
setSubmitting(true);
try {
const payload = { ...values };
if (typeof payload.quota === 'string')
payload.quota = parseInt(payload.quota) || 0;
// 额度通过列表按增量调整;编辑资料时省略该字段,保留服务端当前余额。
delete payload.quota;
if (typeof payload.gift_quota === 'string')
payload.gift_quota = parseInt(payload.gift_quota) || 0;
if (userId) {
payload.id = parseInt(userId);
payload.group = toGroupList(values.group).join(',');
payload.group = userGroupKey(values.group);
}
const url = userId ? '/api/user/' : '/api/user/self';
const { data } = await API.put(url, payload);
@@ -172,13 +175,6 @@ const EditUserModal = (props) => {
}
};
/* --------------------- quota helper -------------------- */
const addLocalQuota = () => {
const current = parseInt(formApiRef.current?.getValue('quota') || 0);
const delta = parseInt(addQuotaLocal) || 0;
formApiRef.current?.setValue('quota', current + delta);
};
/* --------------------------- UI --------------------------- */
return (
<>
@@ -298,6 +294,7 @@ const EditUserModal = (props) => {
placeholder={t('请选择分组')}
optionList={groupOptions}
allowAdditions
maxCount={1}
search
rules={[{ required: true, message: t('请选择分组') }]}
/>
@@ -318,12 +315,16 @@ const EditUserModal = (props) => {
</Col>
<Col xs={24} sm={12}>
<FormQuotaInput
field='quota'
label={t('剩余额度')}
rules={[{ required: true, message: t('请输入额度') }]}
style={{ width: '100%' }}
/>
<Form.Slot label={t('剩余额度')}>
<Text className='tabular-nums'>
{renderQuota(loadedQuota)}
</Text>
<div>
<Text type='secondary' className='text-xs'>
{t('只读;调整请使用列表操作列的「添加额度」')}
</Text>
</div>
</Form.Slot>
</Col>
<Col xs={24} sm={12}>
@@ -336,16 +337,6 @@ const EditUserModal = (props) => {
style={{ width: '100%' }}
/>
</Col>
<Col span={24}>
<Form.Slot label={t('添加额度')}>
<Button
icon={<ActionPlus size={16} />}
aria-label={t('添加额度')}
onClick={() => setIsModalOpen(true)}
/>
</Form.Slot>
</Col>
</Row>
</Card>
)}
@@ -395,42 +386,6 @@ const EditUserModal = (props) => {
)}
</Form>
</SideSheet>
{/* 添加额度模态框 */}
<Modal
centered
visible={addQuotaModalOpen}
onOk={() => {
addLocalQuota();
setIsModalOpen(false);
}}
onCancel={() => setIsModalOpen(false)}
closable={null}
title={
<div className='flex items-center'>
<ActionPlus size={16} className='mr-2' />
{t('添加额度')}
</div>
}
>
<div className='mb-4'>
{(() => {
const current = formApiRef.current?.getValue('quota') || 0;
return (
<Text type='secondary' className='block mb-2'>
{`${t('新额度:')}${renderQuota(current)} + ${renderQuota(addQuotaLocal || 0)} = ${renderQuota(current + parseInt(addQuotaLocal || 0))}`}
</Text>
);
})()}
</div>
<QuotaInput
placeholder={t('需要添加的金额(支持负数)')}
value={addQuotaLocal}
onChange={setAddQuotaLocal}
style={{ width: '100%' }}
showClear
/>
</Modal>
</>
);
};