fix(*): 全量 UI 审查与 undefined 展示异常修复

分析模块:补齐看板、排行、趋势及报表数值兜底
企业与用户中心:修复统计、成员、技能及资金字段展示
充值与交易:修复充值、发票、订单、订阅及支付字段拼接
平台页面:修复渠道、模型、服务监控与状态空值展示
通用能力:新增安全展示工具,补齐九语言文案与回归测试
文档记录:更新修复范围、影响及回滚说明
This commit is contained in:
zhanjunhao
2026-11-20 10:18:17 +08:00
parent 74ca103334
commit c492e2b7c0
65 changed files with 507 additions and 274 deletions
+10
View File
@@ -8,6 +8,16 @@
**记录规则**:每条写“范围、变更、影响、回滚、关联”五项;回滚优先 `git revert <提交>`,提交含多项改动时按文件还原(`git checkout <提交>^ -- <文件>`),不整仓 reset。本文不作为规则依据。 **记录规则**:每条写“范围、变更、影响、回滚、关联”五项;回滚优先 `git revert <提交>`,提交含多项改动时按文件还原(`git checkout <提交>^ -- <文件>`),不整仓 reset。本文不作为规则依据。
## 2026-11-20
### 修复 · 全量 undefined / NaN 展示防护与主题兼容回归
- **范围**:分析看板、组织/个人中心、充值/发票/订单/订阅、佣金、渠道模型测试、服务监控,以及亮色/暗色主题下的数字展示路径。
- **变更**:新增并复用安全数字、金额、百分比与编号展示兜底;缺失或非法接口字段不再拼接为 `undefined`、`NaN%`、`xxundefined`;补齐 9 个语言包的未知档位文案与单元测试隔离 mock。
- **影响**:只收敛用户可见展示和格式化健壮性,不改变请求载荷、权限、路由、计费或登录业务语义;主题色继续遵循现有 token 与亮暗主题派生规则。
- **回滚**:按本条关联文件逐项回退;不使用整库 reset,保留其他会话的独立改动。
- **关联**:`src/helpers/safeDisplay.js`、`src/helpers/render.jsx`、相关 `src/components/` 与 `src/pages/` 展示文件、`test/unit/safe-display.test.js`、`test/unit/market-name-search.test.js`、`.e2e/report/report.html`。
## 2026-11-19 ## 2026-11-19
### 更新 · ESLint 9 ### 更新 · ESLint 9
+3 -2
View File
@@ -21,6 +21,7 @@ import React from 'react';
import { Card, Table, Button } from '@/components/ui'; import { Card, Table, Button } from '@/components/ui';
import { IconDownload } from '@/components/ui/icons'; import { IconDownload } from '@/components/ui/icons';
import { renderQuota } from '../../helpers'; import { renderQuota } from '../../helpers';
import { formatNumber, toFiniteNumber } from '../../helpers/safeDisplay';
const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => { const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => {
const columns = [ const columns = [
@@ -68,7 +69,7 @@ const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => {
align: 'right', align: 'right',
render: (val) => ( render: (val) => (
<span className='text-yellow-600 font-medium'> <span className='text-yellow-600 font-medium'>
¥{(val || 0).toFixed(2)} ¥{formatNumber(val, 2, '0.00')}
</span> </span>
), ),
}, },
@@ -99,7 +100,7 @@ const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => {
width: 120, width: 120,
align: 'right', align: 'right',
render: (val) => { render: (val) => {
const tokens = val || 0; const tokens = toFiniteNumber(val) ?? 0;
if (tokens >= 1000000) { if (tokens >= 1000000) {
return <span>{(tokens / 1000000).toFixed(2)}M</span>; return <span>{(tokens / 1000000).toFixed(2)}M</span>;
} else if (tokens >= 1000) { } else if (tokens >= 1000) {
@@ -25,6 +25,7 @@ import { RefreshCw } from '@/components/common/icons/ActionIcons';
import { ConsoleDrawer } from '@/components/console/ConsolePrimitives'; import { ConsoleDrawer } from '@/components/console/ConsolePrimitives';
import useOrgCacheHourly from '../../hooks/analytics/useOrgCacheHourly'; import useOrgCacheHourly from '../../hooks/analytics/useOrgCacheHourly';
import { useIsMobile } from '../../hooks/common/useIsMobile'; import { useIsMobile } from '../../hooks/common/useIsMobile';
import { formatIdReference, formatPercent } from '../../helpers/safeDisplay';
// 图表序列色属于专用图表(VChart)配色,统计块沿用同色以便与图例对应。 // 图表序列色属于专用图表(VChart)配色,统计块沿用同色以便与图例对应。
// 千分位缩写。线上单小时 cache_read 能到十亿量级,不缩写轴标签会糊成一片。 // 千分位缩写。线上单小时 cache_read 能到十亿量级,不缩写轴标签会糊成一片。
@@ -179,7 +180,7 @@ const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => {
value: (datum) => value: (datum) =>
datum?.hit_rate === null || datum?.hit_rate === undefined datum?.hit_rate === null || datum?.hit_rate === undefined
? t('无流量') ? t('无流量')
: `${Number(datum.hit_rate).toFixed(1)}%`, : formatPercent(datum.hit_rate, 1),
}, },
{ {
key: () => t('实际消费'), key: () => t('实际消费'),
@@ -228,14 +229,15 @@ const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => {
// 自适应量程会把 76%~87% 的波动拉成满屏振荡,像出了故障。 // 自适应量程会把 76%~87% 的波动拉成满屏振荡,像出了故障。
min: 0, min: 0,
max: 100, max: 100,
label: { formatMethod: (v) => `${Math.round(v)}%` }, label: { formatMethod: (v) => formatPercent(v, 0) },
seriesIndex: [1], seriesIndex: [1],
}, },
], ],
}; };
}, [points, hasTraffic, t]); }, [points, hasTraffic, t]);
const orgTitle = org?.org_name || (org ? `${t('企业')} ${org.org_id}` : ''); const orgReference = formatIdReference(org?.org_id);
const orgTitle = org?.org_name || (org ? `${t('企业')} ${orgReference}` : '');
return ( return (
<ConsoleDrawer <ConsoleDrawer
@@ -250,7 +252,7 @@ const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => {
</span> </span>
{org?.org_id ? ( {org?.org_id ? (
<span className='text-xs font-normal text-[var(--text-secondary)]'> <span className='text-xs font-normal text-[var(--text-secondary)]'>
#{org.org_id} {orgReference}
</span> </span>
) : null} ) : null}
</div> </div>
@@ -284,7 +286,7 @@ const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => {
value={ value={
totals.hit_rate === null || totals.hit_rate === undefined totals.hit_rate === null || totals.hit_rate === undefined
? '--' ? '--'
: `${Number(totals.hit_rate).toFixed(2)}%` : formatPercent(totals.hit_rate, 2)
} }
sub={t('按 token 加权')} sub={t('按 token 加权')}
color={SERIES_COLORS.hitRate} color={SERIES_COLORS.hitRate}
+14 -11
View File
@@ -17,7 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatPercent } from '../../helpers/safeDisplay'; import { formatIdReference, formatPercent } from '../../helpers/safeDisplay';
import React, { useState, useCallback } from 'react'; import React, { useState, useCallback } from 'react';
import { Badge, Empty, Progress, Skeleton, Tag, Tooltip, theme } from 'antd'; import { Badge, Empty, Progress, Skeleton, Tag, Tooltip, theme } from 'antd';
import { ArrowDown } from 'lucide-react'; import { ArrowDown } from 'lucide-react';
@@ -104,16 +104,19 @@ const OrgRealtimeUsage = ({
key: 'org_name', key: 'org_name',
width: 220, width: 220,
fixed: 'left', fixed: 'left',
render: (text, record) => ( render: (text, record) => {
<div className='flex items-center gap-2 min-w-0'> const orgReference = formatIdReference(record.org_id);
<span className='text-sm font-medium truncate' title={text || ''}> return (
{text || `${t('企业')} ${record.org_id}`} <div className='flex items-center gap-2 min-w-0'>
</span> <span className='text-sm font-medium truncate' title={text || ''}>
<span className='text-xs text-[var(--text-secondary)] flex-shrink-0'> {text || `${t('企业')} ${orgReference}`}
#{record.org_id} </span>
</span> <span className='text-xs text-[var(--text-secondary)] flex-shrink-0'>
</div> {orgReference}
), </span>
</div>
);
},
}, },
{ {
title: ( title: (
+3 -3
View File
@@ -16,7 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatPercent } from '../../helpers/safeDisplay'; import { formatNumber, formatPercent } from '../../helpers/safeDisplay';
import React from 'react'; import React from 'react';
import { Card } from '@/components/ui'; import { Card } from '@/components/ui';
@@ -66,7 +66,7 @@ const OverviewCards = ({ overview, loading = false, t }) => {
}, },
{ {
title: t('今日充值'), title: t('今日充值'),
value: `¥${overview.today_topup?.toFixed(2) || '0.00'}`, value: `¥${formatNumber(overview.today_topup, 2, '0.00')}`,
change: overview.today_topup_change, change: overview.today_topup_change,
icon: <DollarSign className='w-5 h-5' />, icon: <DollarSign className='w-5 h-5' />,
color: 'yellow', color: 'yellow',
@@ -93,7 +93,7 @@ const OverviewCards = ({ overview, loading = false, t }) => {
}, },
{ {
title: t('付费率'), title: t('付费率'),
value: `${overview.pay_rate?.toFixed(1) || '0.0'}%`, value: formatPercent(overview.pay_rate, 1, '0.0%'),
change: null, change: null,
icon: <Percent className='w-5 h-5' />, icon: <Percent className='w-5 h-5' />,
color: 'pink', color: 'pink',
+12 -7
View File
@@ -18,6 +18,11 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import {
formatNumber,
formatPercent,
toFiniteNumber,
} from '../../helpers/safeDisplay';
import React, { useMemo } from 'react'; import React, { useMemo } from 'react';
import { Card } from '@/components/ui'; import { Card } from '@/components/ui';
import { VChart } from '@visactor/react-vchart'; import { VChart } from '@visactor/react-vchart';
@@ -48,8 +53,8 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
const chartData = data.map((item) => ({ const chartData = data.map((item) => ({
name: item.payment_method ? t(item.payment_method) : t('未知'), name: item.payment_method ? t(item.payment_method) : t('未知'),
rawName: item.payment_method, rawName: item.payment_method,
value: item.amount || 0, value: toFiniteNumber(item.amount) ?? 0,
count: item.count || 0, count: toFiniteNumber(item.count) ?? 0,
})); }));
// 根据支付渠道名称生成颜色数组 // 根据支付渠道名称生成颜色数组
@@ -78,7 +83,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
content: [ content: [
{ {
key: (datum) => datum?.name, key: (datum) => datum?.name,
value: (datum) => `¥${(datum?.value || 0).toFixed(2)}`, value: (datum) => `¥${formatNumber(datum?.value, 2, '0.00')}`,
}, },
{ {
key: () => t('笔数'), key: () => t('笔数'),
@@ -108,7 +113,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
// 统计列表 // 统计列表
const channelList = data || []; const channelList = data || [];
const totalAmount = channelList.reduce( const totalAmount = channelList.reduce(
(sum, item) => sum + (item.amount || 0), (sum, item) => sum + (toFiniteNumber(item.amount) ?? 0),
0, 0,
); );
@@ -141,10 +146,10 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
</span> </span>
<div className='text-right'> <div className='text-right'>
<span className='font-medium'> <span className='font-medium'>
¥{(item.amount || 0).toFixed(2)} ¥{formatNumber(item.amount, 2, '0.00')}
</span> </span>
<span className='text-gray-400 text-xs ml-2'> <span className='text-gray-400 text-xs ml-2'>
({item.percent?.toFixed(1)} ({formatPercent(item.percent, 1).replace('%', '')}
{I18N_TECHNICAL_TEXT.PERCENT_CLOSE} {I18N_TECHNICAL_TEXT.PERCENT_CLOSE}
</span> </span>
</div> </div>
@@ -152,7 +157,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
))} ))}
<div className='flex items-center justify-between text-sm pt-2 font-semibold'> <div className='flex items-center justify-between text-sm pt-2 font-semibold'>
<span>{t('合计')}</span> <span>{t('合计')}</span>
<span>¥{totalAmount.toFixed(2)}</span> <span>¥{formatNumber(totalAmount, 2, '0.00')}</span>
</div> </div>
</div> </div>
</div> </div>
+3 -3
View File
@@ -20,6 +20,7 @@ For commercial licensing, please contact support@quantumnous.com
import React, { useMemo } from 'react'; import React, { useMemo } from 'react';
import { Card } from '@/components/ui'; import { Card } from '@/components/ui';
import { VChart } from '@visactor/react-vchart'; import { VChart } from '@visactor/react-vchart';
import { formatCurrency } from '@/helpers/safeDisplay';
const TrendCharts = ({ title, icon, data, type, t }) => { const TrendCharts = ({ title, icon, data, type, t }) => {
const spec = useMemo(() => { const spec = useMemo(() => {
@@ -142,7 +143,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => {
content: [ content: [
{ {
key: () => topupKey, key: () => topupKey,
value: (datum) => `¥${(datum?.[topupKey] || 0).toFixed(2)}`, value: (datum) => formatCurrency(datum?.[topupKey]),
}, },
], ],
}, },
@@ -174,8 +175,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => {
content: [ content: [
{ {
key: () => consumeKey, key: () => consumeKey,
value: (datum) => value: (datum) => formatCurrency(datum?.[consumeKey]),
`¥${(datum?.[consumeKey] || 0).toFixed(2)}`,
}, },
], ],
}, },
+5 -2
View File
@@ -16,7 +16,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay'; import {
formatIdReference,
formatUserReference,
} from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
@@ -113,7 +116,7 @@ const UserRanking = ({ data, title, icon, t }) => {
t('未知用户'), t('未知用户'),
)} )}
<span className='text-xs text-gray-400 ml-1'> <span className='text-xs text-gray-400 ml-1'>
#{item.user_id} {formatIdReference(item.user_id)}
</span> </span>
</span> </span>
<span className='text-sm font-semibold text-gray-700 dark:text-gray-300 ml-2'> <span className='text-sm font-semibold text-gray-700 dark:text-gray-300 ml-2'>
+14 -13
View File
@@ -16,7 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatPercent } from '../../helpers/safeDisplay'; import { formatPercent, formatRatioPercent } from '../../helpers/safeDisplay';
import React, { useMemo, useState, useEffect, useCallback } from 'react'; import React, { useMemo, useState, useEffect, useCallback } from 'react';
import { Card, Spin, Tag, Progress } from '@/components/ui'; import { Card, Spin, Tag, Progress } from '@/components/ui';
@@ -335,10 +335,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
{techUsers} {techUsers}
</div> </div>
<div className='text-xs text-gray-400 mt-1'> <div className='text-xs text-gray-400 mt-1'>
{totalUsers > 0 {formatRatioPercent(techUsers, totalUsers, 1, '0.0%')}
? ((techUsers / totalUsers) * 100).toFixed(1)
: 0}
%
</div> </div>
</div> </div>
<div className='p-4 bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-900/20 dark:to-emerald-900/20 rounded-xl'> <div className='p-4 bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-900/20 dark:to-emerald-900/20 rounded-xl'>
@@ -352,10 +349,12 @@ const UserSurveyStats = ({ title, icon, t }) => {
{activeAIUsers} {activeAIUsers}
</div> </div>
<div className='text-xs text-gray-400 mt-1'> <div className='text-xs text-gray-400 mt-1'>
{totalUsers > 0 {formatRatioPercent(
? ((activeAIUsers / totalUsers) * 100).toFixed(1) activeAIUsers,
: 0} totalUsers,
% 1,
'0.0%',
)}
</div> </div>
</div> </div>
<div className='p-4 bg-gradient-to-br from-orange-50 to-amber-50 dark:from-orange-900/20 dark:to-amber-900/20 rounded-xl'> <div className='p-4 bg-gradient-to-br from-orange-50 to-amber-50 dark:from-orange-900/20 dark:to-amber-900/20 rounded-xl'>
@@ -369,10 +368,12 @@ const UserSurveyStats = ({ title, icon, t }) => {
{interestedUsers} {interestedUsers}
</div> </div>
<div className='text-xs text-gray-400 mt-1'> <div className='text-xs text-gray-400 mt-1'>
{totalUsers > 0 {formatRatioPercent(
? ((interestedUsers / totalUsers) * 100).toFixed(1) interestedUsers,
: 0} totalUsers,
% 1,
'0.0%',
)}
</div> </div>
</div> </div>
</div> </div>
@@ -16,7 +16,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay'; import {
formatNumber,
formatIdReference,
formatUserReference,
} from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
@@ -86,7 +90,7 @@ const UserTopupRanking = ({ data, title, icon, t, embedded = false }) => {
{formatUserReference(text, record.user_id, t('未知用户'))} {formatUserReference(text, record.user_id, t('未知用户'))}
</span> </span>
<span className='text-xs text-gray-400 truncate'> <span className='text-xs text-gray-400 truncate'>
{I18N_TECHNICAL_TEXT.ID} {record.user_id} {I18N_TECHNICAL_TEXT.ID} {formatIdReference(record.user_id)}
</span> </span>
</div> </div>
), ),
@@ -99,7 +103,7 @@ const UserTopupRanking = ({ data, title, icon, t, embedded = false }) => {
defaultSortOrder: 'descend', defaultSortOrder: 'descend',
render: (value) => ( render: (value) => (
<span className='font-semibold text-red-500'> <span className='font-semibold text-red-500'>
¥{(value || 0).toFixed(2)} ¥{formatNumber(value, 2, '0.00')}
</span> </span>
), ),
}, },
+13 -7
View File
@@ -16,8 +16,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../../helpers/safeDisplay'; import {
import { formatPercent } from '../../../helpers/safeDisplay'; formatIdReference,
formatPercent,
toFiniteNumber,
} from '../../../helpers/safeDisplay';
// 企业经营决策报表:口径常量、行动清单派生、要点生成、CSV 导出 // 企业经营决策报表:口径常量、行动清单派生、要点生成、CSV 导出
@@ -29,7 +32,8 @@ export const getCnyParams = () => {
let usdRate = 1; let usdRate = 1;
try { try {
const s = JSON.parse(localStorage.getItem('status') || '{}'); const s = JSON.parse(localStorage.getItem('status') || '{}');
usdRate = s?.usd_exchange_rate || 1; const parsedRate = toFiniteNumber(s?.usd_exchange_rate);
usdRate = parsedRate !== null && parsedRate > 0 ? parsedRate : 1;
} catch (e) { } catch (e) {
usdRate = 1; usdRate = 1;
} }
@@ -37,7 +41,7 @@ export const getCnyParams = () => {
}; };
export const quotaToCny = (quota, { quotaPerUnit, usdRate }) => export const quotaToCny = (quota, { quotaPerUnit, usdRate }) =>
((quota || 0) / quotaPerUnit) * usdRate; ((toFiniteNumber(quota) ?? 0) / quotaPerUnit) * usdRate;
export const formatCny = (quota, params, digits = 2) => export const formatCny = (quota, params, digits = 2) =>
`¥${quotaToCny(quota, params).toLocaleString(undefined, { `¥${quotaToCny(quota, params).toLocaleString(undefined, {
@@ -49,10 +53,12 @@ export const formatCny = (quota, params, digits = 2) =>
export const changeRate = (cur, prev) => export const changeRate = (cur, prev) =>
prev > 0 ? (((cur || 0) - prev) / prev) * 100 : null; prev > 0 ? (((cur || 0) - prev) / prev) * 100 : null;
export const formatRate = (rate) => export const formatRate = (rate) => {
rate === null || rate === undefined const number = Number(rate);
return rate === null || rate === undefined || !Number.isFinite(number)
? '—' ? '—'
: `${rate >= 0 ? '+' : ''}${rate.toFixed(1)}%`; : `${number >= 0 ? '+' : ''}${number.toFixed(1)}%`;
};
export const pct = (part, total) => { export const pct = (part, total) => {
const numerator = Number(part); const numerator = Number(part);
@@ -22,6 +22,7 @@ import { Empty as AntEmpty, Tag as AntTag } from 'antd';
import { Modal, Table, Typography, Pagination, Toast } from '@/components/ui'; import { Modal, Table, Typography, Pagination, Toast } from '@/components/ui';
import i18next from 'i18next'; import i18next from 'i18next';
import { API, renderQuota } from '../../helpers'; import { API, renderQuota } from '../../helpers';
import { formatCurrency } from '../../helpers/safeDisplay';
const { Text } = Typography; const { Text } = Typography;
@@ -200,7 +201,7 @@ export const MembershipHistoryContent = ({ visible, t, inline = false }) => {
dataIndex: 'price_paid', dataIndex: 'price_paid',
key: 'price_paid', key: 'price_paid',
width: 100, width: 100,
render: (price) => `¥${price?.toFixed(2) || '0.00'}`, render: (price) => formatCurrency(price, '¥', 2, '¥0.00'),
}, },
{ {
title: t('生效日期'), title: t('生效日期'),
+4 -3
View File
@@ -34,6 +34,7 @@ import {
} from '@/components/ui'; } from '@/components/ui';
import { BellRing } from 'lucide-react'; import { BellRing } from 'lucide-react';
import { useIsMobile } from '../../hooks/common/useIsMobile'; import { useIsMobile } from '../../hooks/common/useIsMobile';
import { formatIdReference, formatNumber } from '../../helpers/safeDisplay';
import { import {
ALERT_DIM_TYPES, ALERT_DIM_TYPES,
ALERT_METRICS, ALERT_METRICS,
@@ -265,7 +266,7 @@ const QualityAlerts = ({ quality, t }) => {
width: 160, width: 160,
render: (v, r) => ( render: (v, r) => (
<span className='quality-num'> <span className='quality-num'>
{Number(v).toFixed(2)} / {r.threshold} {formatNumber(v, 2)} / {formatNumber(r.threshold, 2)}
</span> </span>
), ),
}, },
@@ -311,7 +312,7 @@ const QualityAlerts = ({ quality, t }) => {
placeholder={t('选择渠道')} placeholder={t('选择渠道')}
optionList={(options.channels || []).map((c) => ({ optionList={(options.channels || []).map((c) => ({
value: String(c.id), value: String(c.id),
label: `${c.name} (#${c.id})`, label: `${c.name || t('未知渠道')} (${formatIdReference(c.id)})`,
}))} }))}
onChange={(v) => patch({ dim_key: v || '' })} onChange={(v) => patch({ dim_key: v || '' })}
style={{ width: '100%' }} style={{ width: '100%' }}
@@ -529,7 +530,7 @@ const QualityAlerts = ({ quality, t }) => {
{ {
start: fmtTs(testResult.start), start: fmtTs(testResult.start),
end: fmtTs(testResult.end), end: fmtTs(testResult.end),
value: Number(testResult.value).toFixed(2), value: formatNumber(testResult.value, 2),
samples: fmtInt(testResult.samples), samples: fmtInt(testResult.samples),
}, },
)} )}
+21 -14
View File
@@ -104,15 +104,19 @@ const RemoteSelect = ({
useEffect(() => () => window.clearTimeout(timer.current), []); useEffect(() => () => window.clearTimeout(timer.current), []);
const optionList = useMemo(() => { const optionList = useMemo(() => {
const opts = list.map((it) => ({ const opts = list
value: String(it.id), .filter((it) => it?.id !== null && it?.id !== undefined)
label: `${it.name || '-'} (#${it.id})`, .map((it) => ({
})); value: String(it.id),
label: `${it.name || '-'} (${formatIdReference(it.id)})`,
}));
if (value && !opts.some((o) => o.value === String(value))) { if (value && !opts.some((o) => o.value === String(value))) {
const name = labels.current[String(value)]; const name = labels.current[String(value)];
opts.unshift({ opts.unshift({
value: String(value), value: String(value),
label: name ? `${name} (#${value})` : formatIdReference(value), label: name
? `${name} (${formatIdReference(value)})`
: formatIdReference(value),
}); });
} }
return opts; return opts;
@@ -149,10 +153,12 @@ const QualityFilterBar = ({ quality, t, onOpenDetail }) => {
const [moreOpen, setMoreOpen] = useState(false); const [moreOpen, setMoreOpen] = useState(false);
const idOptions = (items) => const idOptions = (items) =>
(items || []).map((it) => ({ (items || [])
value: String(it.id), .filter((it) => it?.id !== null && it?.id !== undefined)
label: `${it.name || '-'} (#${it.id})`, .map((it) => ({
})); value: String(it.id),
label: `${it.name || '-'} (${formatIdReference(it.id)})`,
}));
const strOptions = (items) => const strOptions = (items) =>
(items || []).map((v) => ({ value: v, label: v })); (items || []).map((v) => ({ value: v, label: v }));
@@ -178,19 +184,20 @@ const QualityFilterBar = ({ quality, t, onOpenDetail }) => {
if (filters.channel_id) if (filters.channel_id)
push( push(
'channel_id', 'channel_id',
`${t('渠道')}: ${nameOf(options.channels, filters.channel_id) || '#' + filters.channel_id}`, `${t('渠道')}: ${nameOf(options.channels, filters.channel_id) || formatIdReference(filters.channel_id)}`,
); );
if (filters.group) push('group', `${t('分组')}: ${filters.group}`); if (filters.group) push('group', `${t('分组')}: ${filters.group}`);
if (filters.org_id) push('org_id', `${t('企业')}: #${filters.org_id}`); if (filters.org_id)
push('org_id', `${t('企业')}: ${formatIdReference(filters.org_id)}`);
if (filters.dept_id) if (filters.dept_id)
push( push(
'dept_id', 'dept_id',
`${t('部门')}: ${nameOf(options.depts, filters.dept_id) || (filters.dept_id === '0' ? t('未分配部门') : '#' + filters.dept_id)}`, `${t('部门')}: ${nameOf(options.depts, filters.dept_id) || (filters.dept_id === '0' ? t('未分配部门') : formatIdReference(filters.dept_id))}`,
); );
if (filters.project_id) if (filters.project_id)
push( push(
'project_id', 'project_id',
`${t('项目')}: ${nameOf(options.projects, filters.project_id) || (filters.project_id === '0' ? t('未绑定项目') : '#' + filters.project_id)}`, `${t('项目')}: ${nameOf(options.projects, filters.project_id) || (filters.project_id === '0' ? t('未绑定项目') : formatIdReference(filters.project_id))}`,
); );
if (filters.user_id) if (filters.user_id)
push( push(
@@ -200,7 +207,7 @@ const QualityFilterBar = ({ quality, t, onOpenDetail }) => {
if (filters.token_id) if (filters.token_id)
push( push(
'token_id', 'token_id',
`${t('密钥')}: ${nameOf(options.tokens, filters.token_id) || '#' + filters.token_id}`, `${t('密钥')}: ${nameOf(options.tokens, filters.token_id) || formatIdReference(filters.token_id)}`,
); );
if (filters.path) push('path', `${t('接口')}: ${filters.path}`); if (filters.path) push('path', `${t('接口')}: ${filters.path}`);
if (filters.error_code) if (filters.error_code)
+3 -2
View File
@@ -22,6 +22,7 @@ import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import React, { useMemo } from 'react'; import React, { useMemo } from 'react';
import { Button, Skeleton, Tooltip } from '@/components/ui'; import { Button, Skeleton, Tooltip } from '@/components/ui';
import { useActualTheme } from '../../context/Theme'; import { useActualTheme } from '../../context/Theme';
import { formatPercent } from '../../helpers/safeDisplay';
import { VChart } from '@visactor/react-vchart'; import { VChart } from '@visactor/react-vchart';
import { Activity, AlertTriangle, Info, PieChart } from 'lucide-react'; import { Activity, AlertTriangle, Info, PieChart } from 'lucide-react';
import { import {
@@ -372,7 +373,7 @@ export const QualityTrendChart = ({ trend, loading, onZoom, t }) => {
min: 0, min: 0,
max: 100, max: 100,
grid: { visible: false }, grid: { visible: false },
label: { formatMethod: (v) => `${v}%` }, label: { formatMethod: (v) => formatPercent(v, 0) },
}, },
{ orient: 'bottom', type: 'band' }, { orient: 'bottom', type: 'band' },
], ],
@@ -388,7 +389,7 @@ export const QualityTrendChart = ({ trend, loading, onZoom, t }) => {
{ {
seriesId: 'rateLine', seriesId: 'rateLine',
key: t('成功率'), key: t('成功率'),
value: (d) => (d?.rate === null ? '-' : `${d?.rate}%`), value: (d) => formatPercent(d?.rate, 1),
}, },
], ],
}, },
+5 -3
View File
@@ -183,10 +183,12 @@ export const outcomeTagColor = {
6: 'purple', 6: 'purple',
}; };
export const pct = (v, digits = 1) => export const pct = (v, digits = 1) => {
v === null || v === undefined || Number.isNaN(v) const number = Number(v);
return v === null || v === undefined || !Number.isFinite(number)
? '-' ? '-'
: `${(v * 100).toFixed(digits)}%`; : `${(number * 100).toFixed(digits)}%`;
};
export const fmtInt = (v) => Number(v || 0).toLocaleString(); export const fmtInt = (v) => Number(v || 0).toLocaleString();
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { formatIdReference } from '../../helpers/safeDisplay';
import { TestTube2 as ActionTestTube2 } from '@/components/common/icons/ActionIcons'; import { TestTube2 as ActionTestTube2 } from '@/components/common/icons/ActionIcons';
import { import {
RefreshCw as ActionRefreshCw, RefreshCw as ActionRefreshCw,
@@ -484,7 +485,7 @@ export default function ContentGuardSetting() {
}} }}
optionList={users.map((user) => ({ optionList={users.map((user) => ({
value: user.id, value: user.id,
label: `${user.display_name || user.username} (#${user.id})`, label: `${user.display_name || user.username || t('未知用户')} (${formatIdReference(user.id)})`,
}))} }))}
emptyContent={ emptyContent={
userKeyword userKeyword
@@ -45,6 +45,11 @@ import { CHANNEL_OPTIONS } from '../../../constants';
import { IconTreeTriangleDown } from '@/components/ui/icons'; import { IconTreeTriangleDown } from '@/components/ui/icons';
import { ShuffleBrandIcon } from '../../common/icons/BrandIcons'; import { ShuffleBrandIcon } from '../../common/icons/BrandIcons';
const formatDisplayPercent = (value, digits = 0) => {
const number = Number(value);
return Number.isFinite(number) ? `${number.toFixed(digits)}%` : '-';
};
function ChannelStatusSwitch({ record, manageChannel, t }) { function ChannelStatusSwitch({ record, manageChannel, t }) {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
return ( return (
@@ -311,7 +316,7 @@ const renderDailyQuota = (record, dailyQuotaInfo, t) => {
{t('已使用')}: {formatQuotaCount(info.daily_quota)} {t('已使用')}: {formatQuotaCount(info.daily_quota)}
</div> </div>
<div> <div>
{t('使用率')}: {percent}% {t('使用率')}: {formatDisplayPercent(percent)}
</div> </div>
{isExceeded && ( {isExceeded && (
<div style={{ color: 'var(--ui-color-danger)' }}> <div style={{ color: 'var(--ui-color-danger)' }}>
@@ -327,7 +332,7 @@ const renderDailyQuota = (record, dailyQuotaInfo, t) => {
strokeColor={strokeColor} strokeColor={strokeColor}
size='small' size='small'
showInfo showInfo
format={(percent) => `${percent}%`} format={(percent) => formatDisplayPercent(percent)}
/> />
</div> </div>
</Tooltip> </Tooltip>
@@ -25,6 +25,11 @@ import { copy, showError, showInfo, showSuccess } from '../../../../helpers';
import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants'; import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants';
import './model-test-modal.css'; import './model-test-modal.css';
const formatTestTime = (value) => {
const number = Number(value);
return Number.isFinite(number) ? number.toFixed(2) : '0.00';
};
const ModelTestModal = ({ const ModelTestModal = ({
showModelTestModal, showModelTestModal,
currentTestChannel, currentTestChannel,
@@ -141,7 +146,7 @@ const ModelTestModal = ({
{testResult.success && ( {testResult.success && (
<Typography.Text type='secondary'> <Typography.Text type='secondary'>
{t('请求时长: {{time}}s', { {t('请求时长: {{time}}s', {
time: testResult.time.toFixed(2), time: formatTestTime(testResult.time),
})} })}
</Typography.Text> </Typography.Text>
)} )}
+17 -11
View File
@@ -39,6 +39,7 @@ import {
import { IconGift } from '@/components/ui/icons'; import { IconGift } from '@/components/ui/icons';
import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime'; import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
import { getCurrencyConfig } from '../../helpers/render'; import { getCurrencyConfig } from '../../helpers/render';
import { formatNumber, toFiniteNumber } from '../../helpers/safeDisplay';
const { Text } = Typography; const { Text } = Typography;
@@ -300,7 +301,7 @@ const RechargeCard = ({
return ( return (
<span className='text-xs font-normal px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded-full text-gray-500'> <span className='text-xs font-normal px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded-full text-gray-500'>
{I18N_TECHNICAL_TEXT.USD_EXCHANGE_PREFIX}{' '} {I18N_TECHNICAL_TEXT.USD_EXCHANGE_PREFIX}{' '}
{rate.toFixed(2)} {symbol} {formatNumber(rate, 2, '1.00')} {symbol}
</span> </span>
); );
})()} })()}
@@ -309,11 +310,14 @@ const RechargeCard = ({
> >
<div className='grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4'> <div className='grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4'>
{presetAmounts.map((preset, index) => { {presetAmounts.map((preset, index) => {
const presetValue = toFiniteNumber(preset.value) ?? 0;
const discount = const discount =
preset.discount || toFiniteNumber(
topupInfo?.discount?.[preset.value] || preset.discount ??
1.0; topupInfo?.discount?.[preset.value],
const originalPrice = preset.value * priceRatio; ) ?? 1.0;
const originalPrice =
presetValue * (toFiniteNumber(priceRatio) ?? 0);
const discountedPrice = originalPrice * discount; const discountedPrice = originalPrice * discount;
const hasDiscount = discount < 1.0; const hasDiscount = discount < 1.0;
const actualPay = discountedPrice; const actualPay = discountedPrice;
@@ -326,15 +330,17 @@ const RechargeCard = ({
if (statusStr) { if (statusStr) {
const s = JSON.parse(statusStr); const s = JSON.parse(statusStr);
// 注意:如果设置了汇率值(包括1),使用设置值;只有未设置(undefined/null)时才用默认值1 // 注意:如果设置了汇率值(包括1),使用设置值;只有未设置(undefined/null)时才用默认值1
const parsedRate = toFiniteNumber(
s?.usd_exchange_rate,
);
usdRate = usdRate =
s?.usd_exchange_rate !== undefined && parsedRate !== null && parsedRate > 0
s?.usd_exchange_rate !== null ? parsedRate
? s.usd_exchange_rate
: 1; : 1;
} }
} catch (e) {} } catch (e) {}
let displayValue = preset.value; let displayValue = presetValue;
let displayActualPay = actualPay; let displayActualPay = actualPay;
let displaySave = save; let displaySave = save;
@@ -393,7 +399,7 @@ const RechargeCard = ({
{hasDiscount && ( {hasDiscount && (
<div className='text-xs font-semibold px-2 py-0.5 bg-green-100 text-green-700 rounded-full mb-2'> <div className='text-xs font-semibold px-2 py-0.5 bg-green-100 text-green-700 rounded-full mb-2'>
{t('省')} {symbol} {t('省')} {symbol}
{displaySave.toFixed(0)} {formatNumber(displaySave, 0, '0')}
</div> </div>
)} )}
@@ -403,7 +409,7 @@ const RechargeCard = ({
className={`font-bold ${isSelected ? 'text-blue-600' : 'text-gray-900 dark:text-gray-100'}`} className={`font-bold ${isSelected ? 'text-blue-600' : 'text-gray-900 dark:text-gray-100'}`}
> >
{symbol} {symbol}
{displayActualPay.toFixed(2)} {formatNumber(displayActualPay, 2, '0.00')}
</span> </span>
</div> </div>
</div> </div>
@@ -43,6 +43,7 @@ import { IconSearch } from '@/components/ui/icons';
import { API, timestamp2string } from '../../../helpers'; import { API, timestamp2string } from '../../../helpers';
import { isAdmin } from '../../../helpers/utils'; import { isAdmin } from '../../../helpers/utils';
import { useIsMobile } from '../../../hooks/common/useIsMobile'; import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { formatCurrency } from '../../../helpers/safeDisplay';
const { Text } = Typography; const { Text } = Typography;
@@ -236,7 +237,7 @@ const TopupHistoryModal = ({ visible, onCancel, t }) => {
key: 'money', key: 'money',
render: (money) => ( render: (money) => (
<span className='text-base font-semibold text-rose-500'> <span className='text-base font-semibold text-rose-500'>
¥{Number(money || 0).toFixed(2)} {formatCurrency(money, '¥', 2, '¥0.00')}
</span> </span>
), ),
}, },
@@ -24,6 +24,7 @@ import { IconRefresh, IconClose } from '@/components/ui/icons';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import QRCode from 'qrcode'; import QRCode from 'qrcode';
import { API, renderQuota } from '../../../helpers'; import { API, renderQuota } from '../../../helpers';
import { formatCurrency } from '../../../helpers/safeDisplay';
const { Text } = Typography; const { Text } = Typography;
@@ -228,7 +229,7 @@ const WechatQRModal = ({ visible, onClose, orderData, pollFn }) => {
<div> <div>
<Text type='secondary'>{t('支付金额:')}</Text> <Text type='secondary'>{t('支付金额:')}</Text>
<Text strong style={{ fontSize: 20, color: '#f5222d' }}> <Text strong style={{ fontSize: 20, color: '#f5222d' }}>
¥{orderData.amount?.toFixed(2)} {formatCurrency(orderData.amount)}
</Text> </Text>
</div> </div>
<div> <div>
+37 -27
View File
@@ -30,6 +30,7 @@ import {
showSuccess, showSuccess,
showError, showError,
} from './utils'; } from './utils';
import { formatPercent, toFiniteNumber } from './safeDisplay.js';
import { import {
STORAGE_KEYS, STORAGE_KEYS,
DEFAULT_TIME_INTERVALS, DEFAULT_TIME_INTERVALS,
@@ -217,37 +218,46 @@ export const renderMonitorList = (
grouped[g].push(m); grouped[g].push(m);
}); });
const renderItem = (monitor, idx) => ( const renderItem = (monitor, idx) => {
<div key={idx} className='p-2 hover:bg-white rounded-lg transition-colors'> const uptime = Math.max(
<div className='flex items-center justify-between mb-1'> 0,
<div className='flex items-center gap-2'> Math.min(1, toFiniteNumber(monitor.uptime) ?? 0),
<div );
className='w-2 h-2 rounded-full flex-shrink-0' return (
style={{ backgroundColor: getUptimeStatusColor(monitor.status) }} <div
/> key={idx}
<span className='text-sm font-medium text-gray-900'> className='p-2 hover:bg-white rounded-lg transition-colors'
{monitor.name} >
<div className='flex items-center justify-between mb-1'>
<div className='flex items-center gap-2'>
<div
className='w-2 h-2 rounded-full flex-shrink-0'
style={{ backgroundColor: getUptimeStatusColor(monitor.status) }}
/>
<span className='text-sm font-medium text-gray-900'>
{monitor.name}
</span>
</div>
<span className='text-xs text-gray-500'>
{formatPercent(uptime * 100, 2)}
</span> </span>
</div> </div>
<span className='text-xs text-gray-500'> <div className='flex items-center gap-2'>
{((monitor.uptime || 0) * 100).toFixed(2)}% <span className='text-xs text-gray-500'>
</span> {getUptimeStatusText(monitor.status)}
</div> </span>
<div className='flex items-center gap-2'> <div className='flex-1'>
<span className='text-xs text-gray-500'> <Progress
{getUptimeStatusText(monitor.status)} percent={uptime * 100}
</span> showInfo={false}
<div className='flex-1'> aria-label={`${monitor.name} uptime`}
<Progress stroke={getUptimeStatusColor(monitor.status)}
percent={(monitor.uptime || 0) * 100} />
showInfo={false} </div>
aria-label={`${monitor.name} uptime`}
stroke={getUptimeStatusColor(monitor.status)}
/>
</div> </div>
</div> </div>
</div> );
); };
return Object.entries(grouped).map(([gname, list]) => ( return Object.entries(grouped).map(([gname, list]) => (
<div key={gname || 'default'} className='mb-2'> <div key={gname || 'default'} className='mb-2'>
+28 -29
View File
@@ -56,6 +56,7 @@ import { Lock, Bot as FastGPT, Image as Jimeng } from 'lucide-react';
import { Modal, Tag, Typography } from '@/components/ui'; import { Modal, Tag, Typography } from '@/components/ui';
import { copy, getCurrencySymbol, showSuccess } from './utils'; import { copy, getCurrencySymbol, showSuccess } from './utils';
import { visit } from 'unist-util-visit'; import { visit } from 'unist-util-visit';
import { toFiniteNumber } from './safeDisplay';
// Full Avatar/Text/Combine variants are loaded only when configured icons render. // Full Avatar/Text/Combine variants are loaded only when configured icons render.
const LobeHubIcon = lazy(() => import('../components/common/LobeHubIcon')); const LobeHubIcon = lazy(() => import('../components/common/LobeHubIcon'));
@@ -783,35 +784,30 @@ export function renderNumber(num) {
} }
export function getQuotaPerUnit() { export function getQuotaPerUnit() {
let quotaPerUnit = localStorage.getItem('quota_per_unit'); const quotaPerUnit = toFiniteNumber(localStorage.getItem('quota_per_unit'));
quotaPerUnit = parseFloat(quotaPerUnit); return quotaPerUnit !== null && quotaPerUnit > 0 ? quotaPerUnit : 500000;
return quotaPerUnit;
} }
export function renderUnitWithQuota(quota) { export function renderUnitWithQuota(quota) {
let quotaPerUnit = localStorage.getItem('quota_per_unit'); return getQuotaPerUnit() * (toFiniteNumber(quota) ?? 0);
quotaPerUnit = parseFloat(quotaPerUnit);
quota = parseFloat(quota);
return quotaPerUnit * quota;
} }
export function getQuotaWithUnit(quota, digits = 6) { export function getQuotaWithUnit(quota, digits = 6) {
let quotaPerUnit = localStorage.getItem('quota_per_unit'); return ((toFiniteNumber(quota) ?? 0) / getQuotaPerUnit()).toFixed(digits);
quotaPerUnit = parseFloat(quotaPerUnit);
return (quota / quotaPerUnit).toFixed(digits);
} }
export function renderQuotaWithAmount(amount) { export function renderQuotaWithAmount(amount) {
const normalizedAmount = toFiniteNumber(amount) ?? 0;
const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD'; const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
if (quotaDisplayType === 'TOKENS') { if (quotaDisplayType === 'TOKENS') {
return renderNumber(renderUnitWithQuota(amount)); return renderNumber(renderUnitWithQuota(normalizedAmount));
} }
if (quotaDisplayType === 'CNY') { if (quotaDisplayType === 'CNY') {
return getCurrencySymbol('CNY') + amount; return getCurrencySymbol('CNY') + normalizedAmount;
} else if (quotaDisplayType === 'CUSTOM') { } else if (quotaDisplayType === 'CUSTOM') {
return getCurrencySymbol('CUSTOM') + amount; return getCurrencySymbol('CUSTOM') + normalizedAmount;
} }
return getCurrencySymbol('USD') + amount; return getCurrencySymbol('USD') + normalizedAmount;
} }
/** /**
@@ -830,11 +826,8 @@ export function getCurrencyConfig() {
try { try {
if (statusStr) { if (statusStr) {
const s = JSON.parse(statusStr); const s = JSON.parse(statusStr);
// 注意:如果设置了汇率值(包括1),使用设置值;只有未设置(undefined/null)时才用默认值1 const parsedRate = toFiniteNumber(s?.usd_exchange_rate);
rate = rate = parsedRate !== null && parsedRate > 0 ? parsedRate : 1;
s?.usd_exchange_rate !== undefined && s?.usd_exchange_rate !== null
? s.usd_exchange_rate
: 1;
} }
} catch (e) {} } catch (e) {}
} else if (quotaDisplayType === 'CUSTOM') { } else if (quotaDisplayType === 'CUSTOM') {
@@ -842,7 +835,8 @@ export function getCurrencyConfig() {
if (statusStr) { if (statusStr) {
const s = JSON.parse(statusStr); const s = JSON.parse(statusStr);
symbol = getCurrencySymbol('CUSTOM', s?.custom_currency_symbol); symbol = getCurrencySymbol('CUSTOM', s?.custom_currency_symbol);
rate = s?.custom_currency_exchange_rate || 1; const parsedRate = toFiniteNumber(s?.custom_currency_exchange_rate);
rate = parsedRate !== null && parsedRate > 0 ? parsedRate : 1;
} }
} catch (e) { } catch (e) {
symbol = getCurrencySymbol('CUSTOM'); symbol = getCurrencySymbol('CUSTOM');
@@ -860,18 +854,18 @@ export function getCurrencyConfig() {
*/ */
export function convertUSDToCurrency(usdAmount, digits = 2) { export function convertUSDToCurrency(usdAmount, digits = 2) {
const { symbol, rate } = getCurrencyConfig(); const { symbol, rate } = getCurrencyConfig();
const convertedAmount = usdAmount * rate; const convertedAmount = (toFiniteNumber(usdAmount) ?? 0) * rate;
return symbol + convertedAmount.toFixed(digits); return symbol + convertedAmount.toFixed(digits);
} }
export function renderQuota(quota, digits = 2) { export function renderQuota(quota, digits = 2) {
let quotaPerUnit = localStorage.getItem('quota_per_unit'); const normalizedQuota = toFiniteNumber(quota) ?? 0;
const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD'; const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
quotaPerUnit = parseFloat(quotaPerUnit); const quotaPerUnit = getQuotaPerUnit();
if (quotaDisplayType === 'TOKENS') { if (quotaDisplayType === 'TOKENS') {
return renderNumber(quota); return renderNumber(normalizedQuota);
} }
const resultUSD = quota / quotaPerUnit; const resultUSD = normalizedQuota / quotaPerUnit;
let symbol = getCurrencySymbol('USD'); let symbol = getCurrencySymbol('USD');
let value = resultUSD; let value = resultUSD;
if (quotaDisplayType === 'CNY') { if (quotaDisplayType === 'CNY') {
@@ -880,7 +874,8 @@ export function renderQuota(quota, digits = 2) {
try { try {
if (statusStr) { if (statusStr) {
const s = JSON.parse(statusStr); const s = JSON.parse(statusStr);
usdRate = s?.usd_exchange_rate || 1; const parsedRate = toFiniteNumber(s?.usd_exchange_rate);
usdRate = parsedRate !== null && parsedRate > 0 ? parsedRate : 1;
} }
} catch (e) {} } catch (e) {}
value = resultUSD * usdRate; value = resultUSD * usdRate;
@@ -893,14 +888,15 @@ export function renderQuota(quota, digits = 2) {
if (statusStr) { if (statusStr) {
const s = JSON.parse(statusStr); const s = JSON.parse(statusStr);
symbolCustom = getCurrencySymbol('CUSTOM', s?.custom_currency_symbol); symbolCustom = getCurrencySymbol('CUSTOM', s?.custom_currency_symbol);
rate = s?.custom_currency_exchange_rate || rate; const parsedRate = toFiniteNumber(s?.custom_currency_exchange_rate);
rate = parsedRate !== null && parsedRate > 0 ? parsedRate : 1;
} }
} catch (e) {} } catch (e) {}
value = resultUSD * rate; value = resultUSD * rate;
symbol = symbolCustom; symbol = symbolCustom;
} }
const fixedResult = value.toFixed(digits); const fixedResult = value.toFixed(digits);
if (parseFloat(fixedResult) === 0 && quota > 0 && value > 0) { if (parseFloat(fixedResult) === 0 && normalizedQuota > 0 && value > 0) {
const minValue = Math.pow(10, -digits); const minValue = Math.pow(10, -digits);
return symbol + minValue.toFixed(digits); return symbol + minValue.toFixed(digits);
} }
@@ -947,7 +943,10 @@ export function renderExportQuota(quota, digits = 6) {
if (!Number.isFinite(quotaPerUnit) || quotaPerUnit <= 0) { if (!Number.isFinite(quotaPerUnit) || quotaPerUnit <= 0) {
quotaPerUnit = 500000; quotaPerUnit = 500000;
} }
return getCurrencySymbol() + (quota / quotaPerUnit).toFixed(digits); return (
getCurrencySymbol() +
((toFiniteNumber(quota) ?? 0) / quotaPerUnit).toFixed(digits)
);
} }
function isValidGroupRatio(ratio) { function isValidGroupRatio(ratio) {
+17 -1
View File
@@ -18,7 +18,8 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
export const toFiniteNumber = (value) => { export const toFiniteNumber = (value) => {
if (value === null || value === undefined || value === '') return null; if (value === null || value === undefined) return null;
if (typeof value === 'string' && value.trim() === '') return null;
const number = Number(value); const number = Number(value);
return Number.isFinite(number) ? number : null; return Number.isFinite(number) ? number : null;
}; };
@@ -28,6 +29,21 @@ export const formatPercent = (value, digits = 1, fallback = '-') => {
return number === null ? fallback : `${number.toFixed(digits)}%`; return number === null ? fallback : `${number.toFixed(digits)}%`;
}; };
export const formatNumber = (value, digits = 2, fallback = '-') => {
const number = toFiniteNumber(value);
return number === null ? fallback : number.toFixed(digits);
};
export const formatCurrency = (
value,
symbol = '¥',
digits = 2,
fallback = '-',
) => {
const formatted = formatNumber(value, digits, null);
return formatted === null ? fallback : symbol + formatted;
};
export const formatRatioPercent = (part, total, digits = 1, fallback = '-') => { export const formatRatioPercent = (part, total, digits = 1, fallback = '-') => {
const numerator = toFiniteNumber(part); const numerator = toFiniteNumber(part);
const denominator = toFiniteNumber(total); const denominator = toFiniteNumber(total);
@@ -31,6 +31,7 @@ import {
import { Modal } from '@/components/ui'; import { Modal } from '@/components/ui';
import { UserContext } from '../../context/User'; import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status'; import { StatusContext } from '../../context/Status';
import { formatNumber, toFiniteNumber } from '../../helpers/safeDisplay';
export const useModelPricingData = () => { export const useModelPricingData = () => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -189,17 +190,27 @@ export const useModelPricingData = () => {
); );
const displayPrice = (usdPrice) => { const displayPrice = (usdPrice) => {
let priceInUSD = usdPrice; const basePrice = toFiniteNumber(usdPrice) ?? 0;
const rechargeRate = toFiniteNumber(priceRate) ?? 1;
const exchangeRate = toFiniteNumber(usdExchangeRate) ?? 1;
const customRate = toFiniteNumber(customExchangeRate) ?? 1;
let priceInUSD = basePrice;
if (showWithRecharge) { if (showWithRecharge) {
priceInUSD = (usdPrice * priceRate) / usdExchangeRate; priceInUSD = (basePrice * rechargeRate) / exchangeRate;
} }
if (currency === 'CNY') { if (currency === 'CNY') {
return `${getCurrencySymbol('CNY')}${(priceInUSD * usdExchangeRate).toFixed(3)}`; return (
getCurrencySymbol('CNY') +
formatNumber(priceInUSD * exchangeRate, 3, '0.000')
);
} else if (currency === 'CUSTOM') { } else if (currency === 'CUSTOM') {
return `${getCurrencySymbol('CUSTOM', customCurrencySymbol)}${(priceInUSD * customExchangeRate).toFixed(3)}`; return (
getCurrencySymbol('CUSTOM', customCurrencySymbol) +
formatNumber(priceInUSD * customRate, 3, '0.000')
);
} }
return `${getCurrencySymbol('USD')}${priceInUSD.toFixed(3)}`; return getCurrencySymbol('USD') + formatNumber(priceInUSD, 3, '0.000');
}; };
const setModelsFormat = ( const setModelsFormat = (
+1
View File
@@ -6118,6 +6118,7 @@
"未找到匹配会话": "No matching conversations", "未找到匹配会话": "No matching conversations",
"未找到视频URL": "Video URL not found", "未找到视频URL": "Video URL not found",
"未知": "Unknown", "未知": "Unknown",
"未知档位": "Unknown tier",
"未知错误": "Unknown error", "未知错误": "Unknown error",
"未知供应商": "Unknown", "未知供应商": "Unknown",
"未知计费类型,暂不支持配置官方价": "Unknown billing type; official price cannot be configured", "未知计费类型,暂不支持配置官方价": "Unknown billing type; official price cannot be configured",
+1
View File
@@ -5868,6 +5868,7 @@
"未找到匹配会话": "Aucune session match trouvée", "未找到匹配会话": "Aucune session match trouvée",
"未找到视频URL": "Vidéo introuvable URL", "未找到视频URL": "Vidéo introuvable URL",
"未知": "Inconnu", "未知": "Inconnu",
"未知档位": "Niveau inconnu",
"未知错误": "Erreur inconnue", "未知错误": "Erreur inconnue",
"未知供应商": "Inconnu", "未知供应商": "Inconnu",
"未知计费类型,暂不支持配置官方价": "Type de facturation inconnu, configuration du prix officiel non prise en charge temporairement", "未知计费类型,暂不支持配置官方价": "Type de facturation inconnu, configuration du prix officiel non prise en charge temporairement",
+1
View File
@@ -6118,6 +6118,7 @@
"未找到匹配会话": "一致する会話が見つかりません", "未找到匹配会话": "一致する会話が見つかりません",
"未找到视频URL": "動画URLが見つかりません", "未找到视频URL": "動画URLが見つかりません",
"未知": "不明", "未知": "不明",
"未知档位": "不明なティア",
"未知错误": "不明なエラー", "未知错误": "不明なエラー",
"未知供应商": "不明なプロバイダー", "未知供应商": "不明なプロバイダー",
"未知计费类型,暂不支持配置官方价": "不明な課金タイプのため、公式価格は設定できません", "未知计费类型,暂不支持配置官方价": "不明な課金タイプのため、公式価格は設定できません",
+1
View File
@@ -6118,6 +6118,7 @@
"未找到匹配会话": "일치하는 대화가 없습니다", "未找到匹配会话": "일치하는 대화가 없습니다",
"未找到视频URL": "동영상 URL을 찾을 수 없습니다", "未找到视频URL": "동영상 URL을 찾을 수 없습니다",
"未知": "알 수 없음", "未知": "알 수 없음",
"未知档位": "알 수 없는 등급",
"未知错误": "알 수 없는 오류", "未知错误": "알 수 없는 오류",
"未知供应商": "알 수 없음", "未知供应商": "알 수 없음",
"未知计费类型,暂不支持配置官方价": "알 수 없는 과금 유형이라 아직 정가를 설정할 수 없습니다", "未知计费类型,暂不支持配置官方价": "알 수 없는 과금 유형이라 아직 정가를 설정할 수 없습니다",
+1
View File
@@ -5905,6 +5905,7 @@
"未找到匹配会话": "Нет совпадений разговоров", "未找到匹配会话": "Нет совпадений разговоров",
"未找到视频URL": "Видео URL не найден", "未找到视频URL": "Видео URL не найден",
"未知": "Неизвестно", "未知": "Неизвестно",
"未知档位": "Неизвестный уровень",
"未知错误": "Неизвестная ошибка", "未知错误": "Неизвестная ошибка",
"未知供应商": "Неизвестный поставщик", "未知供应商": "Неизвестный поставщик",
"未知计费类型,暂不支持配置官方价": "Неизвестный тип выставления счетов; официальная цена не может быть настроена", "未知计费类型,暂不支持配置官方价": "Неизвестный тип выставления счетов; официальная цена не может быть настроена",
+1
View File
@@ -6118,6 +6118,7 @@
"未找到匹配会话": "ไม่พบบทสนทนาที่ตรงกัน", "未找到匹配会话": "ไม่พบบทสนทนาที่ตรงกัน",
"未找到视频URL": "ไม่พบ URL ของวิดีโอ", "未找到视频URL": "ไม่พบ URL ของวิดีโอ",
"未知": "ไม่ทราบ", "未知": "ไม่ทราบ",
"未知档位": "ระดับที่ไม่รู้จัก",
"未知错误": "ข้อผิดพลาดที่ไม่ทราบสาเหตุ", "未知错误": "ข้อผิดพลาดที่ไม่ทราบสาเหตุ",
"未知供应商": "ไม่ทราบ", "未知供应商": "ไม่ทราบ",
"未知计费类型,暂不支持配置官方价": "ประเภทการคิดค่าบริการที่ไม่รู้จัก ยังไม่รองรับการตั้งราคาทางการ", "未知计费类型,暂不支持配置官方价": "ประเภทการคิดค่าบริการที่ไม่รู้จัก ยังไม่รองรับการตั้งราคาทางการ",
+1
View File
@@ -6118,6 +6118,7 @@
"未找到匹配会话": "Không tìm thấy hội thoại phù hợp", "未找到匹配会话": "Không tìm thấy hội thoại phù hợp",
"未找到视频URL": "Không tìm thấy URL video", "未找到视频URL": "Không tìm thấy URL video",
"未知": "không xác định", "未知": "không xác định",
"未知档位": "Bậc không xác định",
"未知错误": "Lỗi không xác định", "未知错误": "Lỗi không xác định",
"未知供应商": "Không xác định", "未知供应商": "Không xác định",
"未知计费类型,暂不支持配置官方价": "Loại tính phí không xác định, tạm không hỗ trợ cấu hình giá chính thức", "未知计费类型,暂不支持配置官方价": "Loại tính phí không xác định, tạm không hỗ trợ cấu hình giá chính thức",
+1
View File
@@ -6118,6 +6118,7 @@
"未找到匹配会话": "未找到匹配會話", "未找到匹配会话": "未找到匹配會話",
"未找到视频URL": "未找到影片URL", "未找到视频URL": "未找到影片URL",
"未知": "未知", "未知": "未知",
"未知档位": "未知檔位",
"未知错误": "未知錯誤", "未知错误": "未知錯誤",
"未知供应商": "未知供應商", "未知供应商": "未知供應商",
"未知计费类型,暂不支持配置官方价": "未知計費類型,暫不支援配置官方價", "未知计费类型,暂不支持配置官方价": "未知計費類型,暫不支援配置官方價",
+1
View File
@@ -6057,6 +6057,7 @@
"未找到匹配会话": "未找到匹配会话", "未找到匹配会话": "未找到匹配会话",
"未找到视频URL": "未找到视频URL", "未找到视频URL": "未找到视频URL",
"未知": "未知", "未知": "未知",
"未知档位": "未知档位",
"未知错误": "未知错误", "未知错误": "未知错误",
"未知供应商": "未知供应商", "未知供应商": "未知供应商",
"未知计费类型,暂不支持配置官方价": "未知计费类型,暂不支持配置官方价", "未知计费类型,暂不支持配置官方价": "未知计费类型,暂不支持配置官方价",
+19 -8
View File
@@ -16,7 +16,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay'; import {
formatCurrency,
formatNumber,
formatUserReference,
toFiniteNumber,
} from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { import {
@@ -269,7 +274,7 @@ const AdminInvoice = () => {
displayName || displayName ||
username || ( username || (
<span className='text-gray-400'> <span className='text-gray-400'>
{t('用户 #{{id}}', { id: record.user_id })} {formatUserReference(null, record.user_id)}
</span> </span>
) )
); );
@@ -292,7 +297,7 @@ const AdminInvoice = () => {
title: t('金额'), title: t('金额'),
dataIndex: 'amount', dataIndex: 'amount',
width: 90, width: 90,
render: (v) => `¥${Number(v).toFixed(2)}`, render: (v) => formatCurrency(v),
}, },
{ {
title: t('状态'), title: t('状态'),
@@ -542,7 +547,7 @@ const AdminInvoice = () => {
<div> <div>
<Text className='text-gray-400 text-sm'>{t('开票金额')}</Text> <Text className='text-gray-400 text-sm'>{t('开票金额')}</Text>
<div className='font-bold text-amber-600'> <div className='font-bold text-amber-600'>
¥{Number(detailData.amount).toFixed(2)} {formatCurrency(detailData.amount)}
</div> </div>
</div> </div>
<div> <div>
@@ -600,9 +605,15 @@ const AdminInvoice = () => {
i18nKey='关联充值记录 ({{length}} 笔,合计 ¥{{value}})' i18nKey='关联充值记录 ({{length}} 笔,合计 ¥{{value}})'
values={{ values={{
length: detailData.topup_list.length, length: detailData.topup_list.length,
value: detailData.topup_list value: formatNumber(
.reduce((s, item) => s + (item.money || 0), 0) detailData.topup_list.reduce(
.toFixed(2), (sum, item) =>
sum + (toFiniteNumber(item.money) ?? 0),
0,
),
2,
'0.00',
),
}} }}
/> />
</Text> </Text>
@@ -629,7 +640,7 @@ const AdminInvoice = () => {
title: t('金额'), title: t('金额'),
dataIndex: 'money', dataIndex: 'money',
width: 90, width: 90,
render: (v) => `¥${Number(v).toFixed(2)}`, render: (v) => formatCurrency(v),
}, },
]} ]}
/> />
+4 -3
View File
@@ -43,6 +43,7 @@ import {
import { API } from '../../helpers/api'; import { API } from '../../helpers/api';
import { showError, copy } from '../../helpers'; import { showError, copy } from '../../helpers';
import { renderQuota } from '../../helpers/render'; import { renderQuota } from '../../helpers/render';
import { formatCurrency, toFiniteNumber } from '../../helpers/safeDisplay';
const paymentMethodMap = { const paymentMethodMap = {
wechat: '微信', wechat: '微信',
@@ -72,8 +73,8 @@ const payPalSettlementStateMap = {
}; };
const formatUSDMinor = (value) => { const formatUSDMinor = (value) => {
if (value === null || value === undefined) return '-'; const minor = toFiniteNumber(value);
return `$${(Number(value) / 100).toFixed(2)}`; return minor === null ? '-' : formatCurrency(minor / 100, '$');
}; };
import { Descriptions } from 'antd'; import { Descriptions } from 'antd';
@@ -298,7 +299,7 @@ const AdminOrder = () => {
title: t('支付金额'), title: t('支付金额'),
dataIndex: 'money', dataIndex: 'money',
width: 90, width: 90,
render: (v) => (v ? `¥${Number(v).toFixed(2)}` : '-'), render: (v) => (v ? formatCurrency(v) : '-'),
}, },
{ {
title: t('支付方式'), title: t('支付方式'),
+4 -4
View File
@@ -1094,7 +1094,7 @@ export default function PartnerPortal({
<b> <b>
{row.customer_name || {row.customer_name ||
row.subject_name || row.subject_name ||
`${commissionLabel(t, 'subjectType', row.subject_type)} #${row.subject_id}`} `${commissionLabel(t, 'subjectType', row.subject_type)} ${formatIdReference(row.subject_id)}`}
</b> </b>
), ),
}, },
@@ -1357,7 +1357,7 @@ export default function PartnerPortal({
title={t(pageTitle)} title={t(pageTitle)}
subtitle={ subtitle={
selected ? ( selected ? (
`${t('账单号')} #${selected.id} · ${selected.statement_month}` `${t('账单号')} ${formatIdReference(selected.id)} · ${selected.statement_month}`
) : ( ) : (
<> <>
{t(subtitles[active])} {t(subtitles[active])}
@@ -1375,7 +1375,7 @@ export default function PartnerPortal({
{!embedded && ( {!embedded && (
<Text type='secondary'> <Text type='secondary'>
{selected {selected
? `${t('账单号')} #${selected.id} · ${selected.statement_month}` ? `${t('账单号')} ${formatIdReference(selected.id)} · ${selected.statement_month}`
: t(subtitles[active])} : t(subtitles[active])}
{!selected && {!selected &&
['overview', 'estimate'].includes(active) && ['overview', 'estimate'].includes(active) &&
@@ -1462,7 +1462,7 @@ export default function PartnerPortal({
style={themeStyle} style={themeStyle}
className='commission-modal partner-portal-modal' className='commission-modal partner-portal-modal'
visible={!!action} visible={!!action}
title={`${t(action === 'reject' ? '驳回账单' : '确认账单')} · #${selected?.id || ''}`} title={`${t(action === 'reject' ? '驳回账单' : '确认账单')} · ${formatIdReference(selected?.id)}`}
confirmLoading={mutationLoading} confirmLoading={mutationLoading}
closeOnEsc={!mutationLoading} closeOnEsc={!mutationLoading}
maskClosable={!mutationLoading} maskClosable={!mutationLoading}
+11 -5
View File
@@ -16,7 +16,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay'; import {
formatCurrency,
formatIdReference,
formatPercent,
toFiniteNumber,
} from '../../helpers/safeDisplay';
import React, { import React, {
useCallback, useCallback,
@@ -89,7 +94,8 @@ const { Title, Text } = Typography;
const emptyState = (description) => ( const emptyState = (description) => (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={description} /> <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={description} />
); );
const money = (value) => `¥${(Number(value || 0) / 1e6).toFixed(2)}`; const money = (value) =>
formatCurrency((toFiniteNumber(value) ?? 0) / 1e6, '¥', 2, '¥0.00');
const protectionUntil = (row) => const protectionUntil = (row) =>
Number(row.extended_until || row.protected_until || 0); Number(row.extended_until || row.protected_until || 0);
const date = (value) => const date = (value) =>
@@ -222,7 +228,7 @@ function TierSummary({ items }) {
{ {
title: t('比例'), title: t('比例'),
dataIndex: 'rate_bps', dataIndex: 'rate_bps',
render: (value) => `${Number(value || 0) / 100}%`, render: (value) => formatPercent(Number(value || 0) / 100, 2),
}, },
{ title: t('调用笔数'), dataIndex: 'count' }, { title: t('调用笔数'), dataIndex: 'count' },
{ title: t('有效销售额'), dataIndex: 'sales', render: money }, { title: t('有效销售额'), dataIndex: 'sales', render: money },
@@ -1076,7 +1082,7 @@ function AdminPage() {
? t('企业组织') ? t('企业组织')
: t('个人用户')) : t('个人用户'))
} }
reference={`${commissionLabel(t, 'subjectType', row.subject_type)} #${row.subject_id}`} reference={`${commissionLabel(t, 'subjectType', row.subject_type)} ${formatIdReference(row.subject_id)}`}
/> />
), ),
}, },
@@ -1282,7 +1288,7 @@ function AdminPage() {
{ {
title: t('比例'), title: t('比例'),
dataIndex: 'rate_bps', dataIndex: 'rate_bps',
render: (v) => `${(Number(v || 0) / 100).toFixed(2)}%`, render: (v) => formatPercent(Number(v) / 100, 2),
}, },
{ {
title: t('生效时间'), title: t('生效时间'),
+3 -1
View File
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay.js';
export function latestTierURL(filters = {}, page = 1, snapshot = {}) { export function latestTierURL(filters = {}, page = 1, snapshot = {}) {
const params = new URLSearchParams({ const params = new URLSearchParams({
view: 'latest', view: 'latest',
@@ -83,5 +85,5 @@ export function identityOptionLabel(item) {
const name = const name =
item.name || item.display_name || item.username || item.code || ''; item.name || item.display_name || item.username || item.code || '';
const identifier = item.name ? item.code : item.username; const identifier = item.name ? item.code : item.username;
return `${name}${identifier && identifier !== name ? ` · ${identifier}` : ''} (#${item.id})${item.disabled_reason ? ` · ${item.disabled_reason}` : ''}`; return `${name}${identifier && identifier !== name ? ` · ${identifier}` : ''} (${formatIdReference(item.id)})${item.disabled_reason ? ` · ${item.disabled_reason}` : ''}`;
} }
+18 -7
View File
@@ -51,6 +51,12 @@ import {
} from './operationForm'; } from './operationForm';
import { pickerEpoch } from './datePicker'; import { pickerEpoch } from './datePicker';
import { API } from '../../helpers'; import { API } from '../../helpers';
import {
formatCurrency,
formatIdReference,
formatPercent,
toFiniteNumber,
} from '../../helpers/safeDisplay';
import RemoteIdentitySelect from './RemoteIdentitySelect'; import RemoteIdentitySelect from './RemoteIdentitySelect';
import { fetchAllLatestTiers } from './latestTiers'; import { fetchAllLatestTiers } from './latestTiers';
import './formSections.css'; import './formSections.css';
@@ -340,7 +346,7 @@ export function OperationsDialog({
style={{ width: '100%' }} style={{ width: '100%' }}
optionList={rows.map((item) => ({ optionList={rows.map((item) => ({
value: item.id, value: item.id,
label: `${name(item)} (#${item.id})`, label: `${name(item)} (${formatIdReference(item.id)})`,
}))} }))}
/> />
</Field> </Field>
@@ -848,7 +854,7 @@ export function OperationsDialog({
channel.id, channel.id,
{ {
value: channel.id, value: channel.id,
label: `${channel.name} (#${channel.id})`, label: `${channel.name || t('未知渠道')} (${formatIdReference(channel.id)})`,
}, },
]), ]),
]).values(), ]).values(),
@@ -944,7 +950,7 @@ export function OperationsDialog({
'等级档位', '等级档位',
bindingConfigs.map((item) => ({ ...item, id: item.config_id })), bindingConfigs.map((item) => ({ ...item, id: item.config_id })),
(item) => (item) =>
`${item.name || item.tier_key} · 配置 #${item.config_id}`, `${item.name || item.tier_key || t('未知档位')} · 配置 ${formatIdReference(item.config_id)}`,
)} )}
{dateField('effective_from', '绑定生效时间', true)} {dateField('effective_from', '绑定生效时间', true)}
<Alert <Alert
@@ -1148,7 +1154,7 @@ export function BillingColumns(t, money, date) {
{ {
title: t('比例'), title: t('比例'),
dataIndex: 'rate_bps', dataIndex: 'rate_bps',
render: (value) => `${Number(value || 0) / 100}%`, render: (value) => formatPercent(Number(value || 0) / 100, 2),
}, },
{ title: t('提成金额'), dataIndex: 'commission_uyuan', render: money }, { title: t('提成金额'), dataIndex: 'commission_uyuan', render: money },
]; ];
@@ -1358,11 +1364,16 @@ export function SettlementDialog({
<Descriptions <Descriptions
row row
data={[ data={[
{ key: t('账单编号'), value: `#${statement.id}` }, { key: t('账单编号'), value: formatIdReference(statement.id) },
{ key: t('账期'), value: statement.statement_month || '—' }, { key: t('账期'), value: statement.statement_month || '—' },
{ {
key: t('应付金额'), key: t('应付金额'),
value: `¥${(Number(statement.payable_uyuan || 0) / 1e6).toFixed(2)}`, value: formatCurrency(
(toFiniteNumber(statement.payable_uyuan) ?? 0) / 1e6,
'¥',
2,
'¥0.00',
),
}, },
]} ]}
/> />
@@ -1449,7 +1460,7 @@ export function SettlementDialog({
onChange={(value) => set('detail_id', value)} onChange={(value) => set('detail_id', value)}
optionList={items.map((item) => ({ optionList={items.map((item) => ({
value: item.detail_id, value: item.detail_id,
label: `${item.billing_record_id} · ${item.model_name || ''} · ${Number(item.rate_bps || 0) / 100}%`, label: `${formatIdReference(item.billing_record_id)} · ${item.model_name || t('未知模型')} · ${formatPercent(Number(item.rate_bps) / 100, 2)}`,
}))} }))}
/> />
</Field> </Field>
+2 -2
View File
@@ -16,7 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay'; import { formatIdReference, formatNumber } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { import {
@@ -2346,7 +2346,7 @@ const ExpertPlatform = () => {
</strong> </strong>
<small> <small>
{row.success {row.success
? `${t('通过')} · ${Number(row.time || 0).toFixed(2)}s` ? `${t('通过')} · ${formatNumber(row.time, 2, '0.00')}s`
: row.message || t('失败')} : row.message || t('失败')}
</small> </small>
</div> </div>
+1 -1
View File
@@ -327,7 +327,7 @@ const OrgDeptManage = ({ orgId, featureFlags }) => {
placeholder={t('选择部门')} placeholder={t('选择部门')}
style={{ width: 180 }} style={{ width: 180 }}
optionList={departments.map((d) => ({ optionList={departments.map((d) => ({
label: `${d.name}(${d.member_count})`, label: `${d.name || t('未命名部门')}(${d.member_count ?? 0})`,
value: d.id, value: d.id,
}))} }))}
/> />
+10 -7
View File
@@ -16,8 +16,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay'; import {
import { formatPercent } from '../../helpers/safeDisplay'; formatIdReference,
formatNumber,
formatPercent,
} from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons'; import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons';
@@ -271,7 +274,7 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
{ {
label: t('质量评分'), label: t('质量评分'),
value: metric.has('quality.score') value: metric.has('quality.score')
? value('quality.score', true).toFixed(1) ? formatNumber(value('quality.score', true), 1, t('数据不足'))
: t('数据不足'), : t('数据不足'),
detail: `${Math.round(value('quality.feedback_count'))} ${t('反馈样本')}`, detail: `${Math.round(value('quality.feedback_count'))} ${t('反馈样本')}`,
icon: FlaskConical, icon: FlaskConical,
@@ -475,7 +478,7 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
</Tag> </Tag>
</div> </div>
<span> <span>
{t('评分')}: {Number(row.score).toFixed(1)} {t('评分')}: {formatNumber(row.score, 1)}
</span> </span>
<span> <span>
{t('样本')}: {row.sample_count} {t('样本')}: {row.sample_count}
@@ -496,7 +499,7 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
{ {
title: t('评分'), title: t('评分'),
dataIndex: 'score', dataIndex: 'score',
render: (score) => Number(score).toFixed(1), render: (score) => formatNumber(score, 1),
}, },
{ title: t('样本'), dataIndex: 'sample_count' }, { title: t('样本'), dataIndex: 'sample_count' },
{ {
@@ -564,7 +567,7 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
<span> <span>
{t('平均成本')}:{' '} {t('平均成本')}:{' '}
{row.data_sufficient {row.data_sufficient
? Number(row.average_quota).toFixed(1) ? formatNumber(row.average_quota, 1)
: t('数据不足')} : t('数据不足')}
</span> </span>
</article> </article>
@@ -598,7 +601,7 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
title: t('平均成本'), title: t('平均成本'),
render: (_, row) => render: (_, row) =>
row.data_sufficient row.data_sufficient
? Number(row.average_quota).toFixed(1) ? formatNumber(row.average_quota, 1)
: t('数据不足'), : t('数据不足'),
}, },
]} ]}
+8 -4
View File
@@ -16,8 +16,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay'; import {
import { formatPercent } from '../../helpers/safeDisplay'; formatIdReference,
formatPercent,
toFiniteNumber,
} from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { import {
@@ -100,9 +103,10 @@ const uploadContentType = (file) => {
}; };
const formatBytes = (bytes, t) => { const formatBytes = (bytes, t) => {
if (!bytes) return `0 ${t('字节')}`; const numericBytes = toFiniteNumber(bytes);
if (numericBytes === null || numericBytes <= 0) return `0 ${t('字节')}`;
const units = [t('字节'), 'KiB', 'MiB', 'GiB']; const units = [t('字节'), 'KiB', 'MiB', 'GiB'];
let value = Number(bytes); let value = numericBytes;
let unit = 0; let unit = 0;
while (value >= 1024 && unit < units.length - 1) { while (value >= 1024 && unit < units.length - 1) {
value /= 1024; value /= 1024;
+11 -3
View File
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { formatNumber } from '../../helpers/safeDisplay';
import { Check as ActionCheck } from '@/components/common/icons/ActionIcons'; import { Check as ActionCheck } from '@/components/common/icons/ActionIcons';
import React, { useEffect, useState, useCallback, useMemo } from 'react'; import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { timestamp2string } from '../../helpers/utils'; import { timestamp2string } from '../../helpers/utils';
@@ -467,7 +468,7 @@ const OrgRecharge = ({ orgId }) => {
} }
if (effectiveAmountYuan <= 0) return ''; if (effectiveAmountYuan <= 0) return '';
const pay = effectiveAmountYuan * effectiveDiscount; const pay = effectiveAmountYuan * effectiveDiscount;
return `${pay.toFixed(2)} ${t('元')}`; return `${formatNumber(pay, 2, '0.00')} ${t('元')}`;
}; };
// 充值记录状态渲染 // 充值记录状态渲染
@@ -508,7 +509,7 @@ const OrgRecharge = ({ orgId }) => {
title: t('金额'), title: t('金额'),
dataIndex: 'money', dataIndex: 'money',
width: 140, width: 140,
render: (v) => `¥${Number(v).toFixed(2)}`, render: (v) => `¥${formatNumber(v, 2, '0.00')}`,
}, },
{ {
title: t('获得额度'), title: t('获得额度'),
@@ -776,7 +777,14 @@ const OrgRecharge = ({ orgId }) => {
</div> </div>
<div> <div>
<dt>{t('优惠金额')}</dt> <dt>{t('优惠金额')}</dt>
<dd>¥{(effectiveAmountYuan - payableYuan).toFixed(2)}</dd> <dd>
¥
{formatNumber(
effectiveAmountYuan - payableYuan,
2,
'0.00',
)}
</dd>
</div> </div>
<div> <div>
<dt>{t('支付方式')}</dt> <dt>{t('支付方式')}</dt>
+2 -1
View File
@@ -25,6 +25,7 @@ import { Table, Button, Tag, Toast, Input, Popconfirm } from '@/components/ui';
import { API } from '../../helpers/api'; import { API } from '../../helpers/api';
import { showError, collectPagedItems } from '../../helpers'; import { showError, collectPagedItems } from '../../helpers';
import { renderQuota } from '../../helpers/render'; import { renderQuota } from '../../helpers/render';
import { formatIdReference } from '../../helpers/safeDisplay';
import OrgPageHeader from './components/OrgPageHeader'; import OrgPageHeader from './components/OrgPageHeader';
import { OrgListCard, OrgRowActions } from './components/OrgListCard'; import { OrgListCard, OrgRowActions } from './components/OrgListCard';
import OrgModal from './components/OrgModal'; import OrgModal from './components/OrgModal';
@@ -158,7 +159,7 @@ const OrgRequests = ({ orgId, orgRole, featureFlags }) => {
// 后端已富化 subject_name;主体被删除等极端情况回退为 #ID // 后端已富化 subject_name;主体被删除等极端情况回退为 #ID
return r.subject_name return r.subject_name
? `${label} · ${r.subject_name}` ? `${label} · ${r.subject_name}`
: `${label} #${r.subject_id}`; : `${label} ${formatIdReference(r.subject_id, t('未知主体'))}`;
}, },
}, },
{ {
+7 -2
View File
@@ -16,7 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay'; import { formatCurrency, formatUserReference } from '../../helpers/safeDisplay';
import { import {
RefreshCw as ActionRefreshCw, RefreshCw as ActionRefreshCw,
@@ -654,7 +654,12 @@ const OrgSettings = ({ orgId, orgRole }) => {
extra={ extra={
Number(alertYuan) >= 0.005 Number(alertYuan) >= 0.005
? t('当企业剩余额度低于 {{amount}} 时触发预警', { ? t('当企业剩余额度低于 {{amount}} 时触发预警', {
amount: `${getCurrencySymbol()}${Number(alertYuan).toFixed(2)}`, amount: formatCurrency(
alertYuan,
getCurrencySymbol(),
2,
getCurrencySymbol() + '0.00',
),
}) })
: t('当前为 0:已关闭余额预警') : t('当前为 0:已关闭余额预警')
} }
@@ -29,6 +29,7 @@ import {
} from '@/components/ui'; } from '@/components/ui';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { API } from '../../helpers'; import { API } from '../../helpers';
import { formatIdReference } from '../../helpers/safeDisplay';
import { import {
ActivationModeTag, ActivationModeTag,
AssignmentModeTag, AssignmentModeTag,
@@ -354,7 +355,7 @@ const OrgSkillAssignments = ({ orgId, orgRole = '' }) => {
> >
{library.map((item) => ( {library.map((item) => (
<Select.Option key={item.skill_id} value={item.skill_id}> <Select.Option key={item.skill_id} value={item.skill_id}>
Skill #{item.skill_id} Skill {formatIdReference(item.skill_id)}
</Select.Option> </Select.Option>
))} ))}
</Select> </Select>
+4 -3
View File
@@ -42,6 +42,7 @@ import { Search } from 'lucide-react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { API } from '../../helpers'; import { API } from '../../helpers';
import { formatIdReference } from '../../helpers/safeDisplay';
import { import {
LicenseBadge, LicenseBadge,
RiskBadge, RiskBadge,
@@ -164,8 +165,8 @@ const OrgSkillLibrary = ({ orgId, orgRole, canAssignSkills = false }) => {
item?.locales?.find((locale) => locale.locale === 'zh')?.name || item?.locales?.find((locale) => locale.locale === 'zh')?.name ||
item?.locales?.[0]?.name || item?.locales?.[0]?.name ||
item?.definition?.canonical_id || item?.definition?.canonical_id ||
`Skill #${item?.definition?.id}`, `Skill ${formatIdReference(item?.definition?.id, t('未知技能'))}`,
[], [t],
); );
const importCandidates = useMemo(() => { const importCandidates = useMemo(() => {
const keyword = importKeyword.trim().toLowerCase(); const keyword = importKeyword.trim().toLowerCase();
@@ -516,7 +517,7 @@ const OrgSkillLibrary = ({ orgId, orgRole, canAssignSkills = false }) => {
catalog catalog
.get(policy.skill_id) .get(policy.skill_id)
?.locales?.find((item) => item.locale === 'zh')?.name || ?.locales?.find((item) => item.locale === 'zh')?.name ||
`Skill #${policy.skill_id}` `Skill ${formatIdReference(policy.skill_id, t('未知技能'))}`
} }
actions={ actions={
<SkillStatusTag <SkillStatusTag
@@ -16,7 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatPercent } from '../../../helpers/safeDisplay'; import { formatIdReference, formatPercent } from '../../../helpers/safeDisplay';
import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons'; import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons';
import React, { useCallback, useEffect, useMemo, useState } from 'react'; import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -142,9 +142,9 @@ const localizeAnalyticsRows = (rows, dimension, t) =>
}[dimension]; }[dimension];
if (zeroName) name = zeroName; if (zeroName) name = zeroName;
} else if (dimension === 'member' && name === `成员#${row.key}`) { } else if (dimension === 'member' && name === `成员#${row.key}`) {
name = `${t('成员')}#${row.key}`; name = `${t('成员')}${formatIdReference(row.key, t('未知成员'))}`;
} else if (dimension === 'token' && name === `\u4ee4\u724c#${row.key}`) { } else if (dimension === 'token' && name === `\u4ee4\u724c#${row.key}`) {
name = `${t('密钥')}#${row.key}`; name = `${t('密钥')}${formatIdReference(row.key, t('未知密钥'))}`;
} }
return name === row.name ? row : { ...row, name }; return name === row.name ? row : { ...row, name };
}); });
+3 -1
View File
@@ -17,6 +17,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../../helpers/safeDisplay';
// 与后端 model/org_fund.go 常量一一对应 // 与后端 model/org_fund.go 常量一一对应
export const FUND_STATE = { NEVER: 0, ON: 1, OFF: 2 }; export const FUND_STATE = { NEVER: 0, ON: 1, OFF: 2 };
export const FUND_ACCOUNT_TYPE = { POOL: 0, UNALLOCATED: 1, DEPT: 2 }; export const FUND_ACCOUNT_TYPE = { POOL: 0, UNALLOCATED: 1, DEPT: 2 };
@@ -62,7 +64,7 @@ export const fundAccountDisplay = (t, accountType, deptName) => {
export const fundDeptDisplay = (t, deptId, deptName) => { export const fundDeptDisplay = (t, deptId, deptName) => {
if (deptId === null || deptId === undefined) return '—'; if (deptId === null || deptId === undefined) return '—';
if (!deptId) return t('未归属部门'); if (!deptId) return t('未归属部门');
return deptName || `#${deptId}`; return deptName || formatIdReference(deptId);
}; };
// 一次分配/回收的幂等键:打开弹窗时生成,重试沿用(F-12)。 // 一次分配/回收的幂等键:打开弹窗时生成,重试沿用(F-12)。
+13 -6
View File
@@ -49,12 +49,16 @@ import {
} from 'lucide-react'; } from 'lucide-react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { API, copy, showError, showSuccess } from '../../helpers'; import { API, copy, showError, showSuccess } from '../../helpers';
import {
formatNumber,
formatPercent,
toFiniteNumber,
} from '../../helpers/safeDisplay';
const { Text, Title } = Typography; const { Text, Title } = Typography;
const fmtDate = (ts) => (ts ? new Date(ts * 1000).toLocaleDateString() : '-'); const fmtDate = (ts) => (ts ? new Date(ts * 1000).toLocaleDateString() : '-');
const fmtYuan = (v) => const fmtYuan = (v) => formatNumber(v, 2, '-');
v === undefined || v === null ? '-' : Number(v).toFixed(2);
const LEAD_STATUS = { const LEAD_STATUS = {
pending: ['orange', '待审核'], pending: ['orange', '待审核'],
@@ -845,12 +849,15 @@ function Bills({ t, readOnly }) {
{ title: t('毛利(元)'), dataIndex: 'gross_profit_yuan', render: fmtYuan }, { title: t('毛利(元)'), dataIndex: 'gross_profit_yuan', render: fmtYuan },
{ {
title: t('返佣(元)'), title: t('返佣(元)'),
render: (r) => fmtYuan((r.l1_yuan || 0) + (r.l2_yuan || 0)), render: (r) =>
fmtYuan(
(toFiniteNumber(r.l1_yuan) ?? 0) + (toFiniteNumber(r.l2_yuan) ?? 0),
),
}, },
{ {
title: t('应发(元)'), title: t('应发(元)'),
dataIndex: 'payable_yuan', dataIndex: 'payable_yuan',
render: (v) => Number(v ?? 0).toFixed(2), render: (v) => formatNumber(v, 2, '0.00'),
}, },
{ {
title: '', title: '',
@@ -965,7 +972,7 @@ function Bills({ t, readOnly }) {
data={[ data={[
{ {
key: t('定档'), key: t('定档'),
value: `${t('第 {{tier}} 档', { tier: detail.bill.tier })} · ${(detail.bill.tier_rate * 100).toFixed(0)}%`, value: `${t('第 {{tier}} 档', { tier: detail.bill.tier })} · ${formatPercent(Number(detail.bill.tier_rate) * 100, 0)}`,
}, },
{ key: t('一层(元)'), value: fmtYuan(detail.bill.l1_yuan) }, { key: t('一层(元)'), value: fmtYuan(detail.bill.l1_yuan) },
{ key: t('二层(元)'), value: fmtYuan(detail.bill.l2_yuan) }, { key: t('二层(元)'), value: fmtYuan(detail.bill.l2_yuan) },
@@ -980,7 +987,7 @@ function Bills({ t, readOnly }) {
}, },
{ {
key: t('应发(元)'), key: t('应发(元)'),
value: Number(detail.bill.payable_yuan ?? 0).toFixed(2), value: formatNumber(detail.bill.payable_yuan, 2, '0.00'),
}, },
]} ]}
/> />
+20 -11
View File
@@ -27,16 +27,23 @@ import {
PayPalBrandIcon, PayPalBrandIcon,
} from '../../components/common/icons/BrandIcons'; } from '../../components/common/icons/BrandIcons';
import { getCurrencyConfig } from '../../helpers/render'; import { getCurrencyConfig } from '../../helpers/render';
import { formatNumber, toFiniteNumber } from '../../helpers/safeDisplay';
import { CUSTOMER_SERVICE_OPEN_EVENT } from '../../components/customer-service'; import { CUSTOMER_SERVICE_OPEN_EVENT } from '../../components/customer-service';
import { showInfo } from '../../helpers'; import { showInfo } from '../../helpers';
import AmountCard from './AmountCard'; import AmountCard from './AmountCard';
import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime'; import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
const formatCny = (value) => const formatCny = (value) => {
`¥${Number(value || 0).toLocaleString('en-US', { const number = toFiniteNumber(value);
minimumFractionDigits: 2, if (number === null) return '-';
maximumFractionDigits: 2, return (
})}`; '¥' +
number.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
);
};
// 需要发票时的联系提示(原型:充值订单按钮下方) // 需要发票时的联系提示(原型:充值订单按钮下方)
export const InvoiceNote = ({ t }) => ( export const InvoiceNote = ({ t }) => (
@@ -126,19 +133,21 @@ const RechargePanel = ({
// ---- 充值订单:仅由已选档位、金额与支付方式派生展示 ---- // ---- 充值订单:仅由已选档位、金额与支付方式派生展示 ----
const { symbol } = getCurrencyConfig(); const { symbol } = getCurrencyConfig();
const preset = selectedPreset !== null ? selectedPresetObj : null; const preset = selectedPreset !== null ? selectedPresetObj : null;
const presetValue = toFiniteNumber(preset?.value) ?? 0;
const discount = const discount =
preset?.discount || topupInfo?.discount?.[preset?.value] || 1.0; toFiniteNumber(preset?.discount ?? topupInfo?.discount?.[preset?.value]) ??
1.0;
const isNewVersion = preset?.id !== undefined; const isNewVersion = preset?.id !== undefined;
const originalPrice = preset const originalPrice = preset
? isNewVersion ? isNewVersion
? preset.value ? presetValue
: preset.value * priceRatio : presetValue * (toFiniteNumber(priceRatio) ?? 0)
: 0; : 0;
const arrivalText = preset const arrivalText = preset
? preset.label || ? preset.label ||
(isNewVersion (isNewVersion
? formatCny(preset.value) ? formatCny(preset.value)
: `${symbol}${Number(preset.value).toLocaleString('en-US')}`) : `${symbol}${presetValue.toLocaleString('en-US')}`)
: '-'; : '-';
const selectedMethod = payMethods?.find((method) => method.type === payWay); const selectedMethod = payMethods?.find((method) => method.type === payWay);
const payPalQuoted = payWay === 'paypal' && payPalQuote; const payPalQuoted = payWay === 'paypal' && payPalQuote;
@@ -149,7 +158,7 @@ const RechargePanel = ({
? payPalQuoted ? payPalQuoted
? { ? {
symbol: '$', symbol: '$',
value: Number(payPalQuote.payAmount).toFixed(2), value: formatNumber(payPalQuote.payAmount, 2, '0.00'),
unit: 'USD', unit: 'USD',
} }
: null : null
@@ -300,7 +309,7 @@ const RechargePanel = ({
{payPalQuoted && ( {payPalQuoted && (
<div> <div>
<dt>{t('支付服务费')}</dt> <dt>{t('支付服务费')}</dt>
<dd>{`$${Number(payPalQuote.serviceFee).toFixed(2)} USD`}</dd> <dd>{`$${formatNumber(payPalQuote.serviceFee, 2, '0.00')} USD`}</dd>
</div> </div>
)} )}
</dl> </dl>
+20 -7
View File
@@ -34,6 +34,11 @@ import {
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { UserContext } from '../../context/User'; import { UserContext } from '../../context/User';
import { API, showError, showSuccess, renderQuota } from '../../helpers'; import { API, showError, showSuccess, renderQuota } from '../../helpers';
import {
formatCurrency,
formatNumber,
toFiniteNumber,
} from '../../helpers/safeDisplay';
import WechatQRModal from '../../components/topup/modals/WechatQRModal'; import WechatQRModal from '../../components/topup/modals/WechatQRModal';
import './RechargeV2.css'; import './RechargeV2.css';
@@ -263,7 +268,11 @@ const RechargeV2 = () => {
}} }}
> >
{t('{{rate}}折优惠', { {t('{{rate}}折优惠', {
rate: (option.discount * 10).toFixed(1), rate: formatNumber(
(toFiniteNumber(option.discount) ?? 1) * 10,
1,
'10.0',
),
})} })}
</div> </div>
)} )}
@@ -288,13 +297,17 @@ const RechargeV2 = () => {
<Space vertical align='start' spacing='medium'> <Space vertical align='start' spacing='medium'>
<div> <div>
<Text type='secondary'>{t('原价:')}</Text> <Text type='secondary'>{t('原价:')}</Text>
<Text delete>¥{payInfo.original_money.toFixed(2)}</Text> <Text delete>{formatCurrency(payInfo.original_money)}</Text>
</div> </div>
<div> <div>
<Text type='secondary'>{t('折扣:')}</Text> <Text type='secondary'>{t('折扣:')}</Text>
<Text strong> <Text strong>
{t('{{rate}}折', { {t('{{rate}}折', {
rate: (payInfo.discount_rate * 10).toFixed(1), rate: formatNumber(
(toFiniteNumber(payInfo.discount_rate) ?? 1) * 10,
1,
'10.0',
),
})} })}
</Text> </Text>
</div> </div>
@@ -304,18 +317,18 @@ const RechargeV2 = () => {
style={{ fontSize: 24, color: 'var(--ui-color-danger)' }} style={{ fontSize: 24, color: 'var(--ui-color-danger)' }}
strong strong
> >
¥{payInfo.pay_money.toFixed(2)} {formatCurrency(payInfo.pay_money)}
</Text> </Text>
</div> </div>
<div> <div>
<Text type='secondary'>{t('获得额度:')}</Text> <Text type='secondary'>{t('获得额度:')}</Text>
<Text strong>{renderQuota(payInfo.quota)}</Text> <Text strong>{renderQuota(payInfo.quota)}</Text>
</div> </div>
{payInfo.save_money > 0 && ( {(toFiniteNumber(payInfo.save_money) ?? 0) > 0 && (
<div> <div>
<Text type='secondary'>{t('节省:')}</Text> <Text type='secondary'>{t('节省:')}</Text>
<Text style={{ color: 'var(--ui-color-success)' }}> <Text style={{ color: 'var(--ui-color-success)' }}>
¥{payInfo.save_money.toFixed(2)} {formatCurrency(payInfo.save_money)}
</Text> </Text>
</div> </div>
)} )}
@@ -390,7 +403,7 @@ const RechargeV2 = () => {
? t('处理中...') ? t('处理中...')
: calculating : calculating
? t('计算中...') ? t('计算中...')
: `${t('支付')} ¥${payInfo?.pay_money?.toFixed(2) || '0.00'}`} : `${t('支付')} ${formatCurrency(payInfo?.pay_money, '¥', 2, '¥0.00')}`}
</Button> </Button>
</div> </div>
</Card> </Card>
+23 -20
View File
@@ -16,7 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatPercent } from '../../helpers/safeDisplay'; import { formatPercent, toFiniteNumber } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { import {
@@ -97,7 +97,7 @@ const StatusBars = ({ dataPoints = [], loading = false, t }) => {
<div className='text-xs p-1'> <div className='text-xs p-1'>
<div style={{ color: bgColor }} className='font-semibold'> <div style={{ color: bgColor }} className='font-semibold'>
{isHealthy ? t('正常') : t('异常')} ( {isHealthy ? t('正常') : t('异常')} (
{point.uptime_percent?.toFixed(1)} {formatPercent(point.uptime_percent, 1).replace('%', '')}
{I18N_TECHNICAL_TEXT.PERCENT_CLOSE} {I18N_TECHNICAL_TEXT.PERCENT_CLOSE}
</div> </div>
<div className='text-gray-400 mt-1'> <div className='text-gray-400 mt-1'>
@@ -352,25 +352,28 @@ const GroupMonitor = () => {
title: t('可用率'), title: t('可用率'),
dataIndex: 'uptime_percent', dataIndex: 'uptime_percent',
key: 'uptime_percent', key: 'uptime_percent',
render: (value) => ( render: (value) => {
<div className='flex items-center gap-2'> const uptime = Math.max(0, Math.min(100, toFiniteNumber(value) ?? 0));
<div className='w-16 h-1.5 bg-gray-100 dark:bg-gray-700 rounded-full overflow-hidden'> return (
<div <div className='flex items-center gap-2'>
className='h-full rounded-full' <div className='w-16 h-1.5 bg-gray-100 dark:bg-gray-700 rounded-full overflow-hidden'>
style={{ <div
width: `${Math.min(100, value || 0)}%`, className='h-full rounded-full'
backgroundColor: getUptimeColor(value), style={{
}} width: `${uptime}%`,
/> backgroundColor: getUptimeColor(uptime),
}}
/>
</div>
<span
className='text-sm font-medium'
style={{ color: getUptimeColor(uptime) }}
>
{formatPercent(uptime, 1)}
</span>
</div> </div>
<span );
className='text-sm font-medium' },
style={{ color: getUptimeColor(value) }}
>
{formatPercent(value || 0, 1)}
</span>
</div>
),
sorter: (a, b) => (a.uptime_percent || 0) - (b.uptime_percent || 0), sorter: (a, b) => (a.uptime_percent || 0) - (b.uptime_percent || 0),
}, },
{ {
@@ -47,6 +47,7 @@ import {
showSuccess, showSuccess,
} from '../../../helpers'; } from '../../../helpers';
import { mergePayPalFeePolicyFormValues } from '../../../helpers/paypalPayment'; import { mergePayPalFeePolicyFormValues } from '../../../helpers/paypalPayment';
import { formatPercent } from '../../../helpers/safeDisplay';
const { Text } = Typography; const { Text } = Typography;
const SECRET_PLACEHOLDER = '***ALREADY_SET***'; const SECRET_PLACEHOLDER = '***ALREADY_SET***';
@@ -563,7 +564,7 @@ export default function SettingsPaymentGatewayPayPal(props) {
{ {
title: t('费率'), title: t('费率'),
dataIndex: 'new_rate_bps', dataIndex: 'new_rate_bps',
render: (value) => `${(Number(value) / 100).toFixed(2)}%`, render: (value) => formatPercent(Number(value) / 100, 2),
}, },
{ {
title: t('操作人'), title: t('操作人'),
+5 -1
View File
@@ -251,7 +251,11 @@ function AccessGroupSelect({ id, value, onChange, groupOptions, placeholder }) {
); );
} }
const orgOptionLabel = (org) => `${org.name || ''} (#${org.id})`; const orgOptionLabel = (org) => {
const name = org?.name?.trim();
const reference = formatIdReference(org?.id);
return name ? `${name} (${reference})` : reference;
};
// 开放企业多选:远程搜索管理端企业列表(名称 / 代码 / 联系人),值只存企业 ID。 // 开放企业多选:远程搜索管理端企业列表(名称 / 代码 / 联系人),值只存企业 ID。
// 已保存的企业由父组件按 ID 批量回填名称(orgLabels),已删除的企业回显为 // 已保存的企业由父组件按 ID 批量回填名称(orgLabels),已删除的企业回显为
@@ -354,7 +354,7 @@ const SettingsWeyAiContent = () => {
style={{ minWidth: 260 }} style={{ minWidth: 260 }}
optionList={(overview?.slots || []).map((s) => ({ optionList={(overview?.slots || []).map((s) => ({
value: s.id, value: s.id,
label: `${t(s.name)}(${s.item_count})`, label: `${t(s.name)}(${s.item_count ?? 0})`,
}))} }))}
/> />
</div> </div>
+4 -2
View File
@@ -36,6 +36,7 @@ import {
import { IconPlus, IconRefresh, IconSearch } from '@/components/ui/icons'; import { IconPlus, IconRefresh, IconSearch } from '@/components/ui/icons';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { API } from '../../helpers'; import { API } from '../../helpers';
import { formatNumber } from '../../helpers/safeDisplay';
import { skillTagLabel } from '../../constants/skillCategories'; import { skillTagLabel } from '../../constants/skillCategories';
import { import {
CapabilityTags, CapabilityTags,
@@ -740,7 +741,7 @@ const SkillPlatform = () => {
{ value: '', label: t('全部分类') }, { value: '', label: t('全部分类') },
...tagFacets.map((facet) => ({ ...tagFacets.map((facet) => ({
value: facet.tag, value: facet.tag,
label: `${skillTagLabel(facet.tag, tagLanguage)}(${facet.count})`, label: `${skillTagLabel(facet.tag, tagLanguage)}(${facet.count ?? 0})`,
})), })),
]} ]}
/> />
@@ -1337,7 +1338,8 @@ const SkillPlatform = () => {
{modelTestResult.ok ? t('测试成功') : t('测试失败')} {modelTestResult.ok ? t('测试成功') : t('测试失败')}
</Text> </Text>
<Text type='tertiary' size='small'> <Text type='tertiary' size='small'>
{t('耗时')} {modelTestResult.elapsed.toFixed(2)}s {t('耗时')} {formatNumber(modelTestResult.elapsed, 2, '0.00')}
s
{modelTestResult.usage?.total_tokens {modelTestResult.usage?.total_tokens
? ` · ${modelTestResult.usage.total_tokens} tokens` ? ` · ${modelTestResult.usage.total_tokens} tokens`
: ''} : ''}
+2 -1
View File
@@ -30,6 +30,7 @@ import {
import { Iconbolt, IconActivity } from '@/components/ui/icons'; import { Iconbolt, IconActivity } from '@/components/ui/icons';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { API, showError } from '../../helpers'; import { API, showError } from '../../helpers';
import { formatPercent } from '../../helpers/safeDisplay';
const { Content } = Layout; const { Content } = Layout;
const { Text, Title } = Typography; const { Text, Title } = Typography;
@@ -84,7 +85,7 @@ const Status = () => {
size='small' size='small'
style={{ height: 8 }} style={{ height: 8 }}
showInfo={true} showInfo={true}
format={(per) => `${per}%`} format={(per) => formatPercent(per, 0)}
/> />
</div> </div>
); );
+10 -4
View File
@@ -16,7 +16,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay'; import {
formatIdReference,
formatUserReference,
} from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { import {
@@ -39,6 +42,7 @@ import { Button as AntButton } from 'antd';
import React, { useCallback, useEffect, useMemo, useState } from 'react'; import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useEffectEvent } from '../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { formatCurrency } from '../../helpers/safeDisplay';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { CreditCard, Search, History } from 'lucide-react'; import { CreditCard, Search, History } from 'lucide-react';
import { import {
@@ -423,7 +427,7 @@ const Subscription = () => {
title: t('支付金额'), title: t('支付金额'),
dataIndex: 'price_paid', dataIndex: 'price_paid',
width: 100, width: 100,
render: (v) => (v != null ? `¥${Number(v).toFixed(2)}` : '-'), render: (v) => (v != null ? formatCurrency(v) : '-'),
}, },
{ {
title: t('操作'), title: t('操作'),
@@ -1440,7 +1444,7 @@ const DetailDrawer = ({ visible, row, loading, auditLogs, onClose, t }) => {
</div> </div>
<div className='flex justify-between'> <div className='flex justify-between'>
<span className='text-gray-500'>{t('支付金额')}</span> <span className='text-gray-500'>{t('支付金额')}</span>
<span>¥{Number(row.price_paid || 0).toFixed(2)}</span> <span>{formatCurrency(row.price_paid, '¥', 2, '¥0.00')}</span>
</div> </div>
<div className='flex justify-between'> <div className='flex justify-between'>
<span className='text-gray-500'>{t('支付方式')}</span> <span className='text-gray-500'>{t('支付方式')}</span>
@@ -1503,7 +1507,9 @@ const DetailDrawer = ({ visible, row, loading, auditLogs, onClose, t }) => {
<span className='ml-2 text-gray-700 dark:text-gray-200'> <span className='ml-2 text-gray-700 dark:text-gray-200'>
{log.admin_display_name || {log.admin_display_name ||
log.admin_username || log.admin_username ||
`Admin#${log.admin_id}`} (log.admin_id == null
? t('未知管理员')
: `Admin${formatIdReference(log.admin_id)}`)}
</span> </span>
</div> </div>
{log.reason && ( {log.reason && (
+11 -6
View File
@@ -50,6 +50,11 @@ import {
INVOICE_STATUS_COLOR, INVOICE_STATUS_COLOR,
} from '../../constants'; } from '../../constants';
import { StatusContext } from '../../context/Status'; import { StatusContext } from '../../context/Status';
import {
formatCurrency,
formatNumber,
toFiniteNumber,
} from '../../helpers/safeDisplay';
const { Text } = Typography; const { Text } = Typography;
@@ -150,7 +155,7 @@ const Invoice = () => {
// 计算选中记录的金额合计 // 计算选中记录的金额合计
const selectedAmount = availableTopups const selectedAmount = availableTopups
.filter((t) => selectedTopupIds.includes(t.id)) .filter((t) => selectedTopupIds.includes(t.id))
.reduce((sum, t) => sum + (t.money || 0), 0); .reduce((sum, t) => sum + (toFiniteNumber(t.money) ?? 0), 0);
// 选择常用开票信息 // 选择常用开票信息
const handleSelectTitle = (titleId) => { const handleSelectTitle = (titleId) => {
@@ -315,7 +320,7 @@ const Invoice = () => {
title: t('支付金额'), title: t('支付金额'),
dataIndex: 'money', dataIndex: 'money',
width: 100, width: 100,
render: (v) => (v ? `¥${Number(v).toFixed(2)}` : '-'), render: (v) => formatCurrency(v),
}, },
{ {
title: t('订单号'), title: t('订单号'),
@@ -343,7 +348,7 @@ const Invoice = () => {
title: t('开票金额'), title: t('开票金额'),
dataIndex: 'amount', dataIndex: 'amount',
width: 100, width: 100,
render: (v) => `¥${Number(v).toFixed(2)}`, render: (v) => formatCurrency(v),
}, },
{ {
title: t('状态'), title: t('状态'),
@@ -449,7 +454,7 @@ const Invoice = () => {
<span className='text-lg font-bold text-amber-600 dark:text-amber-400'> <span className='text-lg font-bold text-amber-600 dark:text-amber-400'>
{t('合计')} {t('合计')}
{I18N_TECHNICAL_TEXT.CNY_TOTAL_SEPARATOR} {I18N_TECHNICAL_TEXT.CNY_TOTAL_SEPARATOR}
{selectedAmount.toFixed(2)} {formatNumber(selectedAmount, 2, '0.00')}
</span> </span>
</div> </div>
)} )}
@@ -584,7 +589,7 @@ const Invoice = () => {
<div className='flex justify-between'> <div className='flex justify-between'>
<Text>{t('开票金额')}</Text> <Text>{t('开票金额')}</Text>
<Text strong className='text-amber-600'> <Text strong className='text-amber-600'>
¥{Number(detailData.amount).toFixed(2)} {formatCurrency(detailData.amount)}
</Text> </Text>
</div> </div>
<div className='flex justify-between'> <div className='flex justify-between'>
@@ -640,7 +645,7 @@ const Invoice = () => {
)} )}
</span> </span>
<span className='font-medium'> <span className='font-medium'>
¥{Number(topup.money).toFixed(2)} {formatCurrency(topup.money)}
</span> </span>
</div> </div>
))} ))}
+5
View File
@@ -83,6 +83,11 @@ async function search(query, filters = {}) {
'@/components/ui': { Modal: {} }, '@/components/ui': { Modal: {} },
'../../context/User': { UserContext: {} }, '../../context/User': { UserContext: {} },
'../../context/Status': { StatusContext: {} }, '../../context/Status': { StatusContext: {} },
'../../helpers/safeDisplay': {
formatNumber: (value) => String(value),
toFiniteNumber: (value) =>
Number.isFinite(Number(value)) ? Number(value) : null,
},
}, },
); );
return runHook().filteredModels.map((model) => model.model_name); return runHook().filteredModels.map((model) => model.model_name);
+10
View File
@@ -20,6 +20,8 @@ For commercial licensing, please contact support@quantumnous.com
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import { import {
formatCurrency,
formatNumber,
formatPercent, formatPercent,
formatRatioPercent, formatRatioPercent,
formatIdReference, formatIdReference,
@@ -30,11 +32,19 @@ import {
test('toFiniteNumber rejects missing and non-finite display values', () => { test('toFiniteNumber rejects missing and non-finite display values', () => {
assert.equal(toFiniteNumber(undefined), null); assert.equal(toFiniteNumber(undefined), null);
assert.equal(toFiniteNumber(''), null); assert.equal(toFiniteNumber(''), null);
assert.equal(toFiniteNumber(' '), null);
assert.equal(toFiniteNumber('not-a-number'), null); assert.equal(toFiniteNumber('not-a-number'), null);
assert.equal(toFiniteNumber('12.5'), 12.5); assert.equal(toFiniteNumber('12.5'), 12.5);
assert.equal(toFiniteNumber(Infinity), null); assert.equal(toFiniteNumber(Infinity), null);
}); });
test('currency and number formatters never expose invalid values', () => {
assert.equal(formatNumber('12.5', 2), '12.50');
assert.equal(formatNumber('bad'), '-');
assert.equal(formatCurrency('12.5'), '¥12.50');
assert.equal(formatCurrency(undefined), '-');
});
test('percent formatters never expose invalid values', () => { test('percent formatters never expose invalid values', () => {
assert.equal(formatPercent(undefined), '-'); assert.equal(formatPercent(undefined), '-');
assert.equal(formatPercent('12.5'), '12.5%'); assert.equal(formatPercent('12.5'), '12.5%');