diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 4807075d..2b208c3f 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,16 @@ **记录规则**:每条写“范围、变更、影响、回滚、关联”五项;回滚优先 `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 ### 更新 · ESLint 9 diff --git a/src/components/analytics/DailyStatsTable.jsx b/src/components/analytics/DailyStatsTable.jsx index 8c479a8c..a224a038 100644 --- a/src/components/analytics/DailyStatsTable.jsx +++ b/src/components/analytics/DailyStatsTable.jsx @@ -21,6 +21,7 @@ import React from 'react'; import { Card, Table, Button } from '@/components/ui'; import { IconDownload } from '@/components/ui/icons'; import { renderQuota } from '../../helpers'; +import { formatNumber, toFiniteNumber } from '../../helpers/safeDisplay'; const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => { const columns = [ @@ -68,7 +69,7 @@ const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => { align: 'right', render: (val) => ( - ¥{(val || 0).toFixed(2)} + ¥{formatNumber(val, 2, '0.00')} ), }, @@ -99,7 +100,7 @@ const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => { width: 120, align: 'right', render: (val) => { - const tokens = val || 0; + const tokens = toFiniteNumber(val) ?? 0; if (tokens >= 1000000) { return {(tokens / 1000000).toFixed(2)}M; } else if (tokens >= 1000) { diff --git a/src/components/analytics/OrgCacheHourlySheet.jsx b/src/components/analytics/OrgCacheHourlySheet.jsx index 5215112b..8fefa144 100644 --- a/src/components/analytics/OrgCacheHourlySheet.jsx +++ b/src/components/analytics/OrgCacheHourlySheet.jsx @@ -25,6 +25,7 @@ import { RefreshCw } from '@/components/common/icons/ActionIcons'; import { ConsoleDrawer } from '@/components/console/ConsolePrimitives'; import useOrgCacheHourly from '../../hooks/analytics/useOrgCacheHourly'; import { useIsMobile } from '../../hooks/common/useIsMobile'; +import { formatIdReference, formatPercent } from '../../helpers/safeDisplay'; // 图表序列色属于专用图表(VChart)配色,统计块沿用同色以便与图例对应。 // 千分位缩写。线上单小时 cache_read 能到十亿量级,不缩写轴标签会糊成一片。 @@ -179,7 +180,7 @@ const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => { value: (datum) => datum?.hit_rate === null || datum?.hit_rate === undefined ? t('无流量') - : `${Number(datum.hit_rate).toFixed(1)}%`, + : formatPercent(datum.hit_rate, 1), }, { key: () => t('实际消费'), @@ -228,14 +229,15 @@ const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => { // 自适应量程会把 76%~87% 的波动拉成满屏振荡,像出了故障。 min: 0, max: 100, - label: { formatMethod: (v) => `${Math.round(v)}%` }, + label: { formatMethod: (v) => formatPercent(v, 0) }, seriesIndex: [1], }, ], }; }, [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 ( { {org?.org_id ? ( - #{org.org_id} + {orgReference} ) : null} @@ -284,7 +286,7 @@ const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => { value={ totals.hit_rate === null || totals.hit_rate === undefined ? '--' - : `${Number(totals.hit_rate).toFixed(2)}%` + : formatPercent(totals.hit_rate, 2) } sub={t('按 token 加权')} color={SERIES_COLORS.hitRate} diff --git a/src/components/analytics/OrgRealtimeUsage.jsx b/src/components/analytics/OrgRealtimeUsage.jsx index f9273764..4443acba 100644 --- a/src/components/analytics/OrgRealtimeUsage.jsx +++ b/src/components/analytics/OrgRealtimeUsage.jsx @@ -17,7 +17,7 @@ along with this program. If not, see . 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 { Badge, Empty, Progress, Skeleton, Tag, Tooltip, theme } from 'antd'; import { ArrowDown } from 'lucide-react'; @@ -104,16 +104,19 @@ const OrgRealtimeUsage = ({ key: 'org_name', width: 220, fixed: 'left', - render: (text, record) => ( -
- - {text || `${t('企业')} ${record.org_id}`} - - - #{record.org_id} - -
- ), + render: (text, record) => { + const orgReference = formatIdReference(record.org_id); + return ( +
+ + {text || `${t('企业')} ${orgReference}`} + + + {orgReference} + +
+ ); + }, }, { title: ( diff --git a/src/components/analytics/OverviewCards.jsx b/src/components/analytics/OverviewCards.jsx index 20dc7ce4..0533f555 100644 --- a/src/components/analytics/OverviewCards.jsx +++ b/src/components/analytics/OverviewCards.jsx @@ -16,7 +16,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import { formatPercent } from '../../helpers/safeDisplay'; +import { formatNumber, formatPercent } from '../../helpers/safeDisplay'; import React from 'react'; import { Card } from '@/components/ui'; @@ -66,7 +66,7 @@ const OverviewCards = ({ overview, loading = false, t }) => { }, { title: t('今日充值'), - value: `¥${overview.today_topup?.toFixed(2) || '0.00'}`, + value: `¥${formatNumber(overview.today_topup, 2, '0.00')}`, change: overview.today_topup_change, icon: , color: 'yellow', @@ -93,7 +93,7 @@ const OverviewCards = ({ overview, loading = false, t }) => { }, { title: t('付费率'), - value: `${overview.pay_rate?.toFixed(1) || '0.0'}%`, + value: formatPercent(overview.pay_rate, 1, '0.0%'), change: null, icon: , color: 'pink', diff --git a/src/components/analytics/TopupChannelChart.jsx b/src/components/analytics/TopupChannelChart.jsx index cb8e121e..3b7adf13 100644 --- a/src/components/analytics/TopupChannelChart.jsx +++ b/src/components/analytics/TopupChannelChart.jsx @@ -18,6 +18,11 @@ For commercial licensing, please contact support@quantumnous.com */ import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; +import { + formatNumber, + formatPercent, + toFiniteNumber, +} from '../../helpers/safeDisplay'; import React, { useMemo } from 'react'; import { Card } from '@/components/ui'; import { VChart } from '@visactor/react-vchart'; @@ -48,8 +53,8 @@ const TopupChannelChart = ({ data, title, icon, t }) => { const chartData = data.map((item) => ({ name: item.payment_method ? t(item.payment_method) : t('未知'), rawName: item.payment_method, - value: item.amount || 0, - count: item.count || 0, + value: toFiniteNumber(item.amount) ?? 0, + count: toFiniteNumber(item.count) ?? 0, })); // 根据支付渠道名称生成颜色数组 @@ -78,7 +83,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => { content: [ { key: (datum) => datum?.name, - value: (datum) => `¥${(datum?.value || 0).toFixed(2)}`, + value: (datum) => `¥${formatNumber(datum?.value, 2, '0.00')}`, }, { key: () => t('笔数'), @@ -108,7 +113,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => { // 统计列表 const channelList = data || []; const totalAmount = channelList.reduce( - (sum, item) => sum + (item.amount || 0), + (sum, item) => sum + (toFiniteNumber(item.amount) ?? 0), 0, ); @@ -141,10 +146,10 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
- ¥{(item.amount || 0).toFixed(2)} + ¥{formatNumber(item.amount, 2, '0.00')} - ({item.percent?.toFixed(1)} + ({formatPercent(item.percent, 1).replace('%', '')} {I18N_TECHNICAL_TEXT.PERCENT_CLOSE}
@@ -152,7 +157,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => { ))}
{t('合计')} - ¥{totalAmount.toFixed(2)} + ¥{formatNumber(totalAmount, 2, '0.00')}
diff --git a/src/components/analytics/TrendCharts.jsx b/src/components/analytics/TrendCharts.jsx index f4be8377..4460c447 100644 --- a/src/components/analytics/TrendCharts.jsx +++ b/src/components/analytics/TrendCharts.jsx @@ -20,6 +20,7 @@ For commercial licensing, please contact support@quantumnous.com import React, { useMemo } from 'react'; import { Card } from '@/components/ui'; import { VChart } from '@visactor/react-vchart'; +import { formatCurrency } from '@/helpers/safeDisplay'; const TrendCharts = ({ title, icon, data, type, t }) => { const spec = useMemo(() => { @@ -142,7 +143,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => { content: [ { 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: [ { key: () => consumeKey, - value: (datum) => - `¥${(datum?.[consumeKey] || 0).toFixed(2)}`, + value: (datum) => formatCurrency(datum?.[consumeKey]), }, ], }, diff --git a/src/components/analytics/UserRanking.jsx b/src/components/analytics/UserRanking.jsx index c9127a9c..06e7afe2 100644 --- a/src/components/analytics/UserRanking.jsx +++ b/src/components/analytics/UserRanking.jsx @@ -16,7 +16,10 @@ along with this program. If not, see . 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 { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; @@ -113,7 +116,7 @@ const UserRanking = ({ data, title, icon, t }) => { t('未知用户'), )} - #{item.user_id} + {formatIdReference(item.user_id)} diff --git a/src/components/analytics/UserSurveyStats.jsx b/src/components/analytics/UserSurveyStats.jsx index 44779383..d5a34636 100644 --- a/src/components/analytics/UserSurveyStats.jsx +++ b/src/components/analytics/UserSurveyStats.jsx @@ -16,7 +16,7 @@ along with this program. If not, see . 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 { Card, Spin, Tag, Progress } from '@/components/ui'; @@ -335,10 +335,7 @@ const UserSurveyStats = ({ title, icon, t }) => { {techUsers}
- {totalUsers > 0 - ? ((techUsers / totalUsers) * 100).toFixed(1) - : 0} - % + {formatRatioPercent(techUsers, totalUsers, 1, '0.0%')}
@@ -352,10 +349,12 @@ const UserSurveyStats = ({ title, icon, t }) => { {activeAIUsers}
- {totalUsers > 0 - ? ((activeAIUsers / totalUsers) * 100).toFixed(1) - : 0} - % + {formatRatioPercent( + activeAIUsers, + totalUsers, + 1, + '0.0%', + )}
@@ -369,10 +368,12 @@ const UserSurveyStats = ({ title, icon, t }) => { {interestedUsers}
- {totalUsers > 0 - ? ((interestedUsers / totalUsers) * 100).toFixed(1) - : 0} - % + {formatRatioPercent( + interestedUsers, + totalUsers, + 1, + '0.0%', + )}
diff --git a/src/components/analytics/UserTopupRanking.jsx b/src/components/analytics/UserTopupRanking.jsx index 24f354d4..21521423 100644 --- a/src/components/analytics/UserTopupRanking.jsx +++ b/src/components/analytics/UserTopupRanking.jsx @@ -16,7 +16,11 @@ along with this program. If not, see . 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 { 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('未知用户'))}
- {I18N_TECHNICAL_TEXT.ID} {record.user_id} + {I18N_TECHNICAL_TEXT.ID} {formatIdReference(record.user_id)} ), @@ -99,7 +103,7 @@ const UserTopupRanking = ({ data, title, icon, t, embedded = false }) => { defaultSortOrder: 'descend', render: (value) => ( - ¥{(value || 0).toFixed(2)} + ¥{formatNumber(value, 2, '0.00')} ), }, diff --git a/src/components/analytics/orgReport/utils.js b/src/components/analytics/orgReport/utils.js index 23876bcd..ee45aa4e 100644 --- a/src/components/analytics/orgReport/utils.js +++ b/src/components/analytics/orgReport/utils.js @@ -16,8 +16,11 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import { formatIdReference } from '../../../helpers/safeDisplay'; -import { formatPercent } from '../../../helpers/safeDisplay'; +import { + formatIdReference, + formatPercent, + toFiniteNumber, +} from '../../../helpers/safeDisplay'; // 企业经营决策报表:口径常量、行动清单派生、要点生成、CSV 导出 @@ -29,7 +32,8 @@ export const getCnyParams = () => { let usdRate = 1; try { 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) { usdRate = 1; } @@ -37,7 +41,7 @@ export const getCnyParams = () => { }; export const quotaToCny = (quota, { quotaPerUnit, usdRate }) => - ((quota || 0) / quotaPerUnit) * usdRate; + ((toFiniteNumber(quota) ?? 0) / quotaPerUnit) * usdRate; export const formatCny = (quota, params, digits = 2) => `¥${quotaToCny(quota, params).toLocaleString(undefined, { @@ -49,10 +53,12 @@ export const formatCny = (quota, params, digits = 2) => export const changeRate = (cur, prev) => prev > 0 ? (((cur || 0) - prev) / prev) * 100 : null; -export const formatRate = (rate) => - rate === null || rate === undefined +export const formatRate = (rate) => { + 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) => { const numerator = Number(part); diff --git a/src/components/membership/MembershipHistoryModal.jsx b/src/components/membership/MembershipHistoryModal.jsx index 8df1d7c5..973eef08 100644 --- a/src/components/membership/MembershipHistoryModal.jsx +++ b/src/components/membership/MembershipHistoryModal.jsx @@ -22,6 +22,7 @@ import { Empty as AntEmpty, Tag as AntTag } from 'antd'; import { Modal, Table, Typography, Pagination, Toast } from '@/components/ui'; import i18next from 'i18next'; import { API, renderQuota } from '../../helpers'; +import { formatCurrency } from '../../helpers/safeDisplay'; const { Text } = Typography; @@ -200,7 +201,7 @@ export const MembershipHistoryContent = ({ visible, t, inline = false }) => { dataIndex: 'price_paid', key: 'price_paid', width: 100, - render: (price) => `¥${price?.toFixed(2) || '0.00'}`, + render: (price) => formatCurrency(price, '¥', 2, '¥0.00'), }, { title: t('生效日期'), diff --git a/src/components/quality/QualityAlerts.jsx b/src/components/quality/QualityAlerts.jsx index d1e8dc70..2f3889d6 100644 --- a/src/components/quality/QualityAlerts.jsx +++ b/src/components/quality/QualityAlerts.jsx @@ -34,6 +34,7 @@ import { } from '@/components/ui'; import { BellRing } from 'lucide-react'; import { useIsMobile } from '../../hooks/common/useIsMobile'; +import { formatIdReference, formatNumber } from '../../helpers/safeDisplay'; import { ALERT_DIM_TYPES, ALERT_METRICS, @@ -265,7 +266,7 @@ const QualityAlerts = ({ quality, t }) => { width: 160, render: (v, r) => ( - {Number(v).toFixed(2)} / {r.threshold} + {formatNumber(v, 2)} / {formatNumber(r.threshold, 2)} ), }, @@ -311,7 +312,7 @@ const QualityAlerts = ({ quality, t }) => { placeholder={t('选择渠道')} optionList={(options.channels || []).map((c) => ({ value: String(c.id), - label: `${c.name} (#${c.id})`, + label: `${c.name || t('未知渠道')} (${formatIdReference(c.id)})`, }))} onChange={(v) => patch({ dim_key: v || '' })} style={{ width: '100%' }} @@ -529,7 +530,7 @@ const QualityAlerts = ({ quality, t }) => { { start: fmtTs(testResult.start), end: fmtTs(testResult.end), - value: Number(testResult.value).toFixed(2), + value: formatNumber(testResult.value, 2), samples: fmtInt(testResult.samples), }, )} diff --git a/src/components/quality/QualityFilterBar.jsx b/src/components/quality/QualityFilterBar.jsx index bed1db40..9ff7d791 100644 --- a/src/components/quality/QualityFilterBar.jsx +++ b/src/components/quality/QualityFilterBar.jsx @@ -104,15 +104,19 @@ const RemoteSelect = ({ useEffect(() => () => window.clearTimeout(timer.current), []); const optionList = useMemo(() => { - const opts = list.map((it) => ({ - value: String(it.id), - label: `${it.name || '-'} (#${it.id})`, - })); + const opts = list + .filter((it) => it?.id !== null && it?.id !== undefined) + .map((it) => ({ + value: String(it.id), + label: `${it.name || '-'} (${formatIdReference(it.id)})`, + })); if (value && !opts.some((o) => o.value === String(value))) { const name = labels.current[String(value)]; opts.unshift({ value: String(value), - label: name ? `${name} (#${value})` : formatIdReference(value), + label: name + ? `${name} (${formatIdReference(value)})` + : formatIdReference(value), }); } return opts; @@ -149,10 +153,12 @@ const QualityFilterBar = ({ quality, t, onOpenDetail }) => { const [moreOpen, setMoreOpen] = useState(false); const idOptions = (items) => - (items || []).map((it) => ({ - value: String(it.id), - label: `${it.name || '-'} (#${it.id})`, - })); + (items || []) + .filter((it) => it?.id !== null && it?.id !== undefined) + .map((it) => ({ + value: String(it.id), + label: `${it.name || '-'} (${formatIdReference(it.id)})`, + })); const strOptions = (items) => (items || []).map((v) => ({ value: v, label: v })); @@ -178,19 +184,20 @@ const QualityFilterBar = ({ quality, t, onOpenDetail }) => { if (filters.channel_id) push( '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.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) push( '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) push( '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) push( @@ -200,7 +207,7 @@ const QualityFilterBar = ({ quality, t, onOpenDetail }) => { if (filters.token_id) push( '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.error_code) diff --git a/src/components/quality/QualityOverview.jsx b/src/components/quality/QualityOverview.jsx index 3663d567..58013ca6 100644 --- a/src/components/quality/QualityOverview.jsx +++ b/src/components/quality/QualityOverview.jsx @@ -22,6 +22,7 @@ import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import React, { useMemo } from 'react'; import { Button, Skeleton, Tooltip } from '@/components/ui'; import { useActualTheme } from '../../context/Theme'; +import { formatPercent } from '../../helpers/safeDisplay'; import { VChart } from '@visactor/react-vchart'; import { Activity, AlertTriangle, Info, PieChart } from 'lucide-react'; import { @@ -372,7 +373,7 @@ export const QualityTrendChart = ({ trend, loading, onZoom, t }) => { min: 0, max: 100, grid: { visible: false }, - label: { formatMethod: (v) => `${v}%` }, + label: { formatMethod: (v) => formatPercent(v, 0) }, }, { orient: 'bottom', type: 'band' }, ], @@ -388,7 +389,7 @@ export const QualityTrendChart = ({ trend, loading, onZoom, t }) => { { seriesId: 'rateLine', key: t('成功率'), - value: (d) => (d?.rate === null ? '-' : `${d?.rate}%`), + value: (d) => formatPercent(d?.rate, 1), }, ], }, diff --git a/src/components/quality/qualityConstants.js b/src/components/quality/qualityConstants.js index b6845741..0a37e36e 100644 --- a/src/components/quality/qualityConstants.js +++ b/src/components/quality/qualityConstants.js @@ -183,10 +183,12 @@ export const outcomeTagColor = { 6: 'purple', }; -export const pct = (v, digits = 1) => - v === null || v === undefined || Number.isNaN(v) +export const pct = (v, digits = 1) => { + 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(); diff --git a/src/components/settings/ContentGuardSetting.jsx b/src/components/settings/ContentGuardSetting.jsx index bc7cb5ca..3241456a 100644 --- a/src/components/settings/ContentGuardSetting.jsx +++ b/src/components/settings/ContentGuardSetting.jsx @@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com */ import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; +import { formatIdReference } from '../../helpers/safeDisplay'; import { TestTube2 as ActionTestTube2 } from '@/components/common/icons/ActionIcons'; import { RefreshCw as ActionRefreshCw, @@ -484,7 +485,7 @@ export default function ContentGuardSetting() { }} optionList={users.map((user) => ({ value: user.id, - label: `${user.display_name || user.username} (#${user.id})`, + label: `${user.display_name || user.username || t('未知用户')} (${formatIdReference(user.id)})`, }))} emptyContent={ userKeyword diff --git a/src/components/table/channels/ChannelsColumnDefs.jsx b/src/components/table/channels/ChannelsColumnDefs.jsx index 1d03871c..c426810c 100644 --- a/src/components/table/channels/ChannelsColumnDefs.jsx +++ b/src/components/table/channels/ChannelsColumnDefs.jsx @@ -45,6 +45,11 @@ import { CHANNEL_OPTIONS } from '../../../constants'; import { IconTreeTriangleDown } from '@/components/ui/icons'; 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 }) { const [loading, setLoading] = useState(false); return ( @@ -311,7 +316,7 @@ const renderDailyQuota = (record, dailyQuotaInfo, t) => { {t('已使用')}: {formatQuotaCount(info.daily_quota)}
- {t('使用率')}: {percent}% + {t('使用率')}: {formatDisplayPercent(percent)}
{isExceeded && (
@@ -327,7 +332,7 @@ const renderDailyQuota = (record, dailyQuotaInfo, t) => { strokeColor={strokeColor} size='small' showInfo - format={(percent) => `${percent}%`} + format={(percent) => formatDisplayPercent(percent)} />
diff --git a/src/components/table/channels/modals/ModelTestModal.jsx b/src/components/table/channels/modals/ModelTestModal.jsx index 10d7458d..de203b49 100644 --- a/src/components/table/channels/modals/ModelTestModal.jsx +++ b/src/components/table/channels/modals/ModelTestModal.jsx @@ -25,6 +25,11 @@ import { copy, showError, showInfo, showSuccess } from '../../../../helpers'; import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants'; import './model-test-modal.css'; +const formatTestTime = (value) => { + const number = Number(value); + return Number.isFinite(number) ? number.toFixed(2) : '0.00'; +}; + const ModelTestModal = ({ showModelTestModal, currentTestChannel, @@ -141,7 +146,7 @@ const ModelTestModal = ({ {testResult.success && ( {t('请求时长: {{time}}s', { - time: testResult.time.toFixed(2), + time: formatTestTime(testResult.time), })} )} diff --git a/src/components/topup/RechargeCard.jsx b/src/components/topup/RechargeCard.jsx index d7e8bb3f..04b99cb1 100644 --- a/src/components/topup/RechargeCard.jsx +++ b/src/components/topup/RechargeCard.jsx @@ -39,6 +39,7 @@ import { import { IconGift } from '@/components/ui/icons'; import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime'; import { getCurrencyConfig } from '../../helpers/render'; +import { formatNumber, toFiniteNumber } from '../../helpers/safeDisplay'; const { Text } = Typography; @@ -300,7 +301,7 @@ const RechargeCard = ({ return ( {I18N_TECHNICAL_TEXT.USD_EXCHANGE_PREFIX}{' '} - {rate.toFixed(2)} {symbol} + {formatNumber(rate, 2, '1.00')} {symbol} ); })()} @@ -309,11 +310,14 @@ const RechargeCard = ({ >
{presetAmounts.map((preset, index) => { + const presetValue = toFiniteNumber(preset.value) ?? 0; const discount = - preset.discount || - topupInfo?.discount?.[preset.value] || - 1.0; - const originalPrice = preset.value * priceRatio; + toFiniteNumber( + preset.discount ?? + topupInfo?.discount?.[preset.value], + ) ?? 1.0; + const originalPrice = + presetValue * (toFiniteNumber(priceRatio) ?? 0); const discountedPrice = originalPrice * discount; const hasDiscount = discount < 1.0; const actualPay = discountedPrice; @@ -326,15 +330,17 @@ const RechargeCard = ({ if (statusStr) { const s = JSON.parse(statusStr); // 注意:如果设置了汇率值(包括1),使用设置值;只有未设置(undefined/null)时才用默认值1 + const parsedRate = toFiniteNumber( + s?.usd_exchange_rate, + ); usdRate = - s?.usd_exchange_rate !== undefined && - s?.usd_exchange_rate !== null - ? s.usd_exchange_rate + parsedRate !== null && parsedRate > 0 + ? parsedRate : 1; } } catch (e) {} - let displayValue = preset.value; + let displayValue = presetValue; let displayActualPay = actualPay; let displaySave = save; @@ -393,7 +399,7 @@ const RechargeCard = ({ {hasDiscount && (
{t('省')} {symbol} - {displaySave.toFixed(0)} + {formatNumber(displaySave, 0, '0')}
)} @@ -403,7 +409,7 @@ const RechargeCard = ({ className={`font-bold ${isSelected ? 'text-blue-600' : 'text-gray-900 dark:text-gray-100'}`} > {symbol} - {displayActualPay.toFixed(2)} + {formatNumber(displayActualPay, 2, '0.00')}
diff --git a/src/components/topup/modals/TopupHistoryModal.jsx b/src/components/topup/modals/TopupHistoryModal.jsx index d7b5645f..dbf3058d 100644 --- a/src/components/topup/modals/TopupHistoryModal.jsx +++ b/src/components/topup/modals/TopupHistoryModal.jsx @@ -43,6 +43,7 @@ import { IconSearch } from '@/components/ui/icons'; import { API, timestamp2string } from '../../../helpers'; import { isAdmin } from '../../../helpers/utils'; import { useIsMobile } from '../../../hooks/common/useIsMobile'; +import { formatCurrency } from '../../../helpers/safeDisplay'; const { Text } = Typography; @@ -236,7 +237,7 @@ const TopupHistoryModal = ({ visible, onCancel, t }) => { key: 'money', render: (money) => ( - ¥{Number(money || 0).toFixed(2)} + {formatCurrency(money, '¥', 2, '¥0.00')} ), }, diff --git a/src/components/topup/modals/WechatQRModal.jsx b/src/components/topup/modals/WechatQRModal.jsx index 13b0a64b..85c71b16 100644 --- a/src/components/topup/modals/WechatQRModal.jsx +++ b/src/components/topup/modals/WechatQRModal.jsx @@ -24,6 +24,7 @@ import { IconRefresh, IconClose } from '@/components/ui/icons'; import { useTranslation } from 'react-i18next'; import QRCode from 'qrcode'; import { API, renderQuota } from '../../../helpers'; +import { formatCurrency } from '../../../helpers/safeDisplay'; const { Text } = Typography; @@ -228,7 +229,7 @@ const WechatQRModal = ({ visible, onClose, orderData, pollFn }) => {
{t('支付金额:')} - ¥{orderData.amount?.toFixed(2)} + {formatCurrency(orderData.amount)}
diff --git a/src/helpers/dashboard.jsx b/src/helpers/dashboard.jsx index a38afd67..67df7dfa 100644 --- a/src/helpers/dashboard.jsx +++ b/src/helpers/dashboard.jsx @@ -30,6 +30,7 @@ import { showSuccess, showError, } from './utils'; +import { formatPercent, toFiniteNumber } from './safeDisplay.js'; import { STORAGE_KEYS, DEFAULT_TIME_INTERVALS, @@ -217,37 +218,46 @@ export const renderMonitorList = ( grouped[g].push(m); }); - const renderItem = (monitor, idx) => ( -
-
-
-
- - {monitor.name} + const renderItem = (monitor, idx) => { + const uptime = Math.max( + 0, + Math.min(1, toFiniteNumber(monitor.uptime) ?? 0), + ); + return ( +
+
+
+
+ + {monitor.name} + +
+ + {formatPercent(uptime * 100, 2)}
- - {((monitor.uptime || 0) * 100).toFixed(2)}% - -
-
- - {getUptimeStatusText(monitor.status)} - -
- +
+ + {getUptimeStatusText(monitor.status)} + +
+ +
-
- ); + ); + }; return Object.entries(grouped).map(([gname, list]) => (
diff --git a/src/helpers/render.jsx b/src/helpers/render.jsx index 7c470983..dece4a39 100644 --- a/src/helpers/render.jsx +++ b/src/helpers/render.jsx @@ -56,6 +56,7 @@ import { Lock, Bot as FastGPT, Image as Jimeng } from 'lucide-react'; import { Modal, Tag, Typography } from '@/components/ui'; import { copy, getCurrencySymbol, showSuccess } from './utils'; import { visit } from 'unist-util-visit'; +import { toFiniteNumber } from './safeDisplay'; // Full Avatar/Text/Combine variants are loaded only when configured icons render. const LobeHubIcon = lazy(() => import('../components/common/LobeHubIcon')); @@ -783,35 +784,30 @@ export function renderNumber(num) { } export function getQuotaPerUnit() { - let quotaPerUnit = localStorage.getItem('quota_per_unit'); - quotaPerUnit = parseFloat(quotaPerUnit); - return quotaPerUnit; + const quotaPerUnit = toFiniteNumber(localStorage.getItem('quota_per_unit')); + return quotaPerUnit !== null && quotaPerUnit > 0 ? quotaPerUnit : 500000; } export function renderUnitWithQuota(quota) { - let quotaPerUnit = localStorage.getItem('quota_per_unit'); - quotaPerUnit = parseFloat(quotaPerUnit); - quota = parseFloat(quota); - return quotaPerUnit * quota; + return getQuotaPerUnit() * (toFiniteNumber(quota) ?? 0); } export function getQuotaWithUnit(quota, digits = 6) { - let quotaPerUnit = localStorage.getItem('quota_per_unit'); - quotaPerUnit = parseFloat(quotaPerUnit); - return (quota / quotaPerUnit).toFixed(digits); + return ((toFiniteNumber(quota) ?? 0) / getQuotaPerUnit()).toFixed(digits); } export function renderQuotaWithAmount(amount) { + const normalizedAmount = toFiniteNumber(amount) ?? 0; const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD'; if (quotaDisplayType === 'TOKENS') { - return renderNumber(renderUnitWithQuota(amount)); + return renderNumber(renderUnitWithQuota(normalizedAmount)); } if (quotaDisplayType === 'CNY') { - return getCurrencySymbol('CNY') + amount; + return getCurrencySymbol('CNY') + normalizedAmount; } 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 { if (statusStr) { const s = JSON.parse(statusStr); - // 注意:如果设置了汇率值(包括1),使用设置值;只有未设置(undefined/null)时才用默认值1 - rate = - s?.usd_exchange_rate !== undefined && s?.usd_exchange_rate !== null - ? s.usd_exchange_rate - : 1; + const parsedRate = toFiniteNumber(s?.usd_exchange_rate); + rate = parsedRate !== null && parsedRate > 0 ? parsedRate : 1; } } catch (e) {} } else if (quotaDisplayType === 'CUSTOM') { @@ -842,7 +835,8 @@ export function getCurrencyConfig() { if (statusStr) { const s = JSON.parse(statusStr); 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) { symbol = getCurrencySymbol('CUSTOM'); @@ -860,18 +854,18 @@ export function getCurrencyConfig() { */ export function convertUSDToCurrency(usdAmount, digits = 2) { const { symbol, rate } = getCurrencyConfig(); - const convertedAmount = usdAmount * rate; + const convertedAmount = (toFiniteNumber(usdAmount) ?? 0) * rate; return symbol + convertedAmount.toFixed(digits); } 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'; - quotaPerUnit = parseFloat(quotaPerUnit); + const quotaPerUnit = getQuotaPerUnit(); if (quotaDisplayType === 'TOKENS') { - return renderNumber(quota); + return renderNumber(normalizedQuota); } - const resultUSD = quota / quotaPerUnit; + const resultUSD = normalizedQuota / quotaPerUnit; let symbol = getCurrencySymbol('USD'); let value = resultUSD; if (quotaDisplayType === 'CNY') { @@ -880,7 +874,8 @@ export function renderQuota(quota, digits = 2) { try { if (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) {} value = resultUSD * usdRate; @@ -893,14 +888,15 @@ export function renderQuota(quota, digits = 2) { if (statusStr) { const s = JSON.parse(statusStr); 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) {} value = resultUSD * rate; symbol = symbolCustom; } 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); return symbol + minValue.toFixed(digits); } @@ -947,7 +943,10 @@ export function renderExportQuota(quota, digits = 6) { if (!Number.isFinite(quotaPerUnit) || quotaPerUnit <= 0) { quotaPerUnit = 500000; } - return getCurrencySymbol() + (quota / quotaPerUnit).toFixed(digits); + return ( + getCurrencySymbol() + + ((toFiniteNumber(quota) ?? 0) / quotaPerUnit).toFixed(digits) + ); } function isValidGroupRatio(ratio) { diff --git a/src/helpers/safeDisplay.js b/src/helpers/safeDisplay.js index 75a6dc1d..bd97d992 100644 --- a/src/helpers/safeDisplay.js +++ b/src/helpers/safeDisplay.js @@ -18,7 +18,8 @@ For commercial licensing, please contact support@quantumnous.com */ 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); return Number.isFinite(number) ? number : null; }; @@ -28,6 +29,21 @@ export const formatPercent = (value, digits = 1, fallback = '-') => { 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 = '-') => { const numerator = toFiniteNumber(part); const denominator = toFiniteNumber(total); diff --git a/src/hooks/model-pricing/useModelPricingData.jsx b/src/hooks/model-pricing/useModelPricingData.jsx index 9059090f..4118f442 100644 --- a/src/hooks/model-pricing/useModelPricingData.jsx +++ b/src/hooks/model-pricing/useModelPricingData.jsx @@ -31,6 +31,7 @@ import { import { Modal } from '@/components/ui'; import { UserContext } from '../../context/User'; import { StatusContext } from '../../context/Status'; +import { formatNumber, toFiniteNumber } from '../../helpers/safeDisplay'; export const useModelPricingData = () => { const { t } = useTranslation(); @@ -189,17 +190,27 @@ export const useModelPricingData = () => { ); 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) { - priceInUSD = (usdPrice * priceRate) / usdExchangeRate; + priceInUSD = (basePrice * rechargeRate) / exchangeRate; } if (currency === 'CNY') { - return `${getCurrencySymbol('CNY')}${(priceInUSD * usdExchangeRate).toFixed(3)}`; + return ( + getCurrencySymbol('CNY') + + formatNumber(priceInUSD * exchangeRate, 3, '0.000') + ); } 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 = ( diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 48832b65..a84f2089 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -6118,6 +6118,7 @@ "未找到匹配会话": "No matching conversations", "未找到视频URL": "Video URL not found", "未知": "Unknown", + "未知档位": "Unknown tier", "未知错误": "Unknown error", "未知供应商": "Unknown", "未知计费类型,暂不支持配置官方价": "Unknown billing type; official price cannot be configured", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 03ee4dc9..aaabbadc 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -5868,6 +5868,7 @@ "未找到匹配会话": "Aucune session match trouvée", "未找到视频URL": "Vidéo introuvable URL", "未知": "Inconnu", + "未知档位": "Niveau inconnu", "未知错误": "Erreur inconnue", "未知供应商": "Inconnu", "未知计费类型,暂不支持配置官方价": "Type de facturation inconnu, configuration du prix officiel non prise en charge temporairement", diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index ae3600e0..292ea889 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -6118,6 +6118,7 @@ "未找到匹配会话": "一致する会話が見つかりません", "未找到视频URL": "動画URLが見つかりません", "未知": "不明", + "未知档位": "不明なティア", "未知错误": "不明なエラー", "未知供应商": "不明なプロバイダー", "未知计费类型,暂不支持配置官方价": "不明な課金タイプのため、公式価格は設定できません", diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.json index ba72a2af..1bb7cd7f 100644 --- a/src/i18n/locales/ko.json +++ b/src/i18n/locales/ko.json @@ -6118,6 +6118,7 @@ "未找到匹配会话": "일치하는 대화가 없습니다", "未找到视频URL": "동영상 URL을 찾을 수 없습니다", "未知": "알 수 없음", + "未知档位": "알 수 없는 등급", "未知错误": "알 수 없는 오류", "未知供应商": "알 수 없음", "未知计费类型,暂不支持配置官方价": "알 수 없는 과금 유형이라 아직 정가를 설정할 수 없습니다", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index b280593a..48de1189 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -5905,6 +5905,7 @@ "未找到匹配会话": "Нет совпадений разговоров", "未找到视频URL": "Видео URL не найден", "未知": "Неизвестно", + "未知档位": "Неизвестный уровень", "未知错误": "Неизвестная ошибка", "未知供应商": "Неизвестный поставщик", "未知计费类型,暂不支持配置官方价": "Неизвестный тип выставления счетов; официальная цена не может быть настроена", diff --git a/src/i18n/locales/th.json b/src/i18n/locales/th.json index 5d1cfeef..90ee0ae7 100644 --- a/src/i18n/locales/th.json +++ b/src/i18n/locales/th.json @@ -6118,6 +6118,7 @@ "未找到匹配会话": "ไม่พบบทสนทนาที่ตรงกัน", "未找到视频URL": "ไม่พบ URL ของวิดีโอ", "未知": "ไม่ทราบ", + "未知档位": "ระดับที่ไม่รู้จัก", "未知错误": "ข้อผิดพลาดที่ไม่ทราบสาเหตุ", "未知供应商": "ไม่ทราบ", "未知计费类型,暂不支持配置官方价": "ประเภทการคิดค่าบริการที่ไม่รู้จัก ยังไม่รองรับการตั้งราคาทางการ", diff --git a/src/i18n/locales/vi.json b/src/i18n/locales/vi.json index 0779f8a6..9cbc6746 100644 --- a/src/i18n/locales/vi.json +++ b/src/i18n/locales/vi.json @@ -6118,6 +6118,7 @@ "未找到匹配会话": "Không tìm thấy hội thoại phù hợp", "未找到视频URL": "Không tìm thấy URL video", "未知": "không xác định", + "未知档位": "Bậc không xác định", "未知错误": "Lỗi 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", diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json index e728d6bc..984233e7 100644 --- a/src/i18n/locales/zh-TW.json +++ b/src/i18n/locales/zh-TW.json @@ -6118,6 +6118,7 @@ "未找到匹配会话": "未找到匹配會話", "未找到视频URL": "未找到影片URL", "未知": "未知", + "未知档位": "未知檔位", "未知错误": "未知錯誤", "未知供应商": "未知供應商", "未知计费类型,暂不支持配置官方价": "未知計費類型,暫不支援配置官方價", diff --git a/src/i18n/locales/zh.json b/src/i18n/locales/zh.json index 41e99aa4..5e19ef1e 100644 --- a/src/i18n/locales/zh.json +++ b/src/i18n/locales/zh.json @@ -6057,6 +6057,7 @@ "未找到匹配会话": "未找到匹配会话", "未找到视频URL": "未找到视频URL", "未知": "未知", + "未知档位": "未知档位", "未知错误": "未知错误", "未知供应商": "未知供应商", "未知计费类型,暂不支持配置官方价": "未知计费类型,暂不支持配置官方价", diff --git a/src/pages/AdminInvoice/index.jsx b/src/pages/AdminInvoice/index.jsx index 605ce9a0..83c7287d 100644 --- a/src/pages/AdminInvoice/index.jsx +++ b/src/pages/AdminInvoice/index.jsx @@ -16,7 +16,12 @@ along with this program. If not, see . 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 { @@ -269,7 +274,7 @@ const AdminInvoice = () => { displayName || username || ( - {t('用户 #{{id}}', { id: record.user_id })} + {formatUserReference(null, record.user_id)} ) ); @@ -292,7 +297,7 @@ const AdminInvoice = () => { title: t('金额'), dataIndex: 'amount', width: 90, - render: (v) => `¥${Number(v).toFixed(2)}`, + render: (v) => formatCurrency(v), }, { title: t('状态'), @@ -542,7 +547,7 @@ const AdminInvoice = () => {
{t('开票金额')}
- ¥{Number(detailData.amount).toFixed(2)} + {formatCurrency(detailData.amount)}
@@ -600,9 +605,15 @@ const AdminInvoice = () => { i18nKey='关联充值记录 ({{length}} 笔,合计 ¥{{value}})' values={{ length: detailData.topup_list.length, - value: detailData.topup_list - .reduce((s, item) => s + (item.money || 0), 0) - .toFixed(2), + value: formatNumber( + detailData.topup_list.reduce( + (sum, item) => + sum + (toFiniteNumber(item.money) ?? 0), + 0, + ), + 2, + '0.00', + ), }} /> @@ -629,7 +640,7 @@ const AdminInvoice = () => { title: t('金额'), dataIndex: 'money', width: 90, - render: (v) => `¥${Number(v).toFixed(2)}`, + render: (v) => formatCurrency(v), }, ]} /> diff --git a/src/pages/AdminOrder/index.jsx b/src/pages/AdminOrder/index.jsx index af8f3b2d..0c726e70 100644 --- a/src/pages/AdminOrder/index.jsx +++ b/src/pages/AdminOrder/index.jsx @@ -43,6 +43,7 @@ import { import { API } from '../../helpers/api'; import { showError, copy } from '../../helpers'; import { renderQuota } from '../../helpers/render'; +import { formatCurrency, toFiniteNumber } from '../../helpers/safeDisplay'; const paymentMethodMap = { wechat: '微信', @@ -72,8 +73,8 @@ const payPalSettlementStateMap = { }; const formatUSDMinor = (value) => { - if (value === null || value === undefined) return '-'; - return `$${(Number(value) / 100).toFixed(2)}`; + const minor = toFiniteNumber(value); + return minor === null ? '-' : formatCurrency(minor / 100, '$'); }; import { Descriptions } from 'antd'; @@ -298,7 +299,7 @@ const AdminOrder = () => { title: t('支付金额'), dataIndex: 'money', width: 90, - render: (v) => (v ? `¥${Number(v).toFixed(2)}` : '-'), + render: (v) => (v ? formatCurrency(v) : '-'), }, { title: t('支付方式'), diff --git a/src/pages/CommissionV2/PartnerPortal.jsx b/src/pages/CommissionV2/PartnerPortal.jsx index 3f95c5ae..679d9d71 100644 --- a/src/pages/CommissionV2/PartnerPortal.jsx +++ b/src/pages/CommissionV2/PartnerPortal.jsx @@ -1094,7 +1094,7 @@ export default function PartnerPortal({ {row.customer_name || row.subject_name || - `${commissionLabel(t, 'subjectType', row.subject_type)} #${row.subject_id}`} + `${commissionLabel(t, 'subjectType', row.subject_type)} ${formatIdReference(row.subject_id)}`} ), }, @@ -1357,7 +1357,7 @@ export default function PartnerPortal({ title={t(pageTitle)} subtitle={ selected ? ( - `${t('账单号')} #${selected.id} · ${selected.statement_month}` + `${t('账单号')} ${formatIdReference(selected.id)} · ${selected.statement_month}` ) : ( <> {t(subtitles[active])} @@ -1375,7 +1375,7 @@ export default function PartnerPortal({ {!embedded && ( {selected - ? `${t('账单号')} #${selected.id} · ${selected.statement_month}` + ? `${t('账单号')} ${formatIdReference(selected.id)} · ${selected.statement_month}` : t(subtitles[active])} {!selected && ['overview', 'estimate'].includes(active) && @@ -1462,7 +1462,7 @@ export default function PartnerPortal({ style={themeStyle} className='commission-modal partner-portal-modal' visible={!!action} - title={`${t(action === 'reject' ? '驳回账单' : '确认账单')} · #${selected?.id || ''}`} + title={`${t(action === 'reject' ? '驳回账单' : '确认账单')} · ${formatIdReference(selected?.id)}`} confirmLoading={mutationLoading} closeOnEsc={!mutationLoading} maskClosable={!mutationLoading} diff --git a/src/pages/CommissionV2/index.jsx b/src/pages/CommissionV2/index.jsx index 3fe544f7..584737af 100644 --- a/src/pages/CommissionV2/index.jsx +++ b/src/pages/CommissionV2/index.jsx @@ -16,7 +16,12 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import { formatIdReference } from '../../helpers/safeDisplay'; +import { + formatCurrency, + formatIdReference, + formatPercent, + toFiniteNumber, +} from '../../helpers/safeDisplay'; import React, { useCallback, @@ -89,7 +94,8 @@ const { Title, Text } = Typography; const emptyState = (description) => ( ); -const money = (value) => `¥${(Number(value || 0) / 1e6).toFixed(2)}`; +const money = (value) => + formatCurrency((toFiniteNumber(value) ?? 0) / 1e6, '¥', 2, '¥0.00'); const protectionUntil = (row) => Number(row.extended_until || row.protected_until || 0); const date = (value) => @@ -222,7 +228,7 @@ function TierSummary({ items }) { { title: t('比例'), dataIndex: 'rate_bps', - render: (value) => `${Number(value || 0) / 100}%`, + render: (value) => formatPercent(Number(value || 0) / 100, 2), }, { title: t('调用笔数'), dataIndex: 'count' }, { title: t('有效销售额'), dataIndex: 'sales', render: money }, @@ -1076,7 +1082,7 @@ function AdminPage() { ? 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('比例'), dataIndex: 'rate_bps', - render: (v) => `${(Number(v || 0) / 100).toFixed(2)}%`, + render: (v) => formatPercent(Number(v) / 100, 2), }, { title: t('生效时间'), diff --git a/src/pages/CommissionV2/latestTiers.js b/src/pages/CommissionV2/latestTiers.js index 41a6cd50..b7c9c465 100644 --- a/src/pages/CommissionV2/latestTiers.js +++ b/src/pages/CommissionV2/latestTiers.js @@ -16,6 +16,8 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatIdReference } from '../../helpers/safeDisplay.js'; + export function latestTierURL(filters = {}, page = 1, snapshot = {}) { const params = new URLSearchParams({ view: 'latest', @@ -83,5 +85,5 @@ export function identityOptionLabel(item) { const name = item.name || item.display_name || item.username || item.code || ''; 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}` : ''}`; } diff --git a/src/pages/CommissionV2/operations.jsx b/src/pages/CommissionV2/operations.jsx index 8514e65e..bd039152 100644 --- a/src/pages/CommissionV2/operations.jsx +++ b/src/pages/CommissionV2/operations.jsx @@ -51,6 +51,12 @@ import { } from './operationForm'; import { pickerEpoch } from './datePicker'; import { API } from '../../helpers'; +import { + formatCurrency, + formatIdReference, + formatPercent, + toFiniteNumber, +} from '../../helpers/safeDisplay'; import RemoteIdentitySelect from './RemoteIdentitySelect'; import { fetchAllLatestTiers } from './latestTiers'; import './formSections.css'; @@ -340,7 +346,7 @@ export function OperationsDialog({ style={{ width: '100%' }} optionList={rows.map((item) => ({ value: item.id, - label: `${name(item)} (#${item.id})`, + label: `${name(item)} (${formatIdReference(item.id)})`, }))} /> @@ -848,7 +854,7 @@ export function OperationsDialog({ channel.id, { value: channel.id, - label: `${channel.name} (#${channel.id})`, + label: `${channel.name || t('未知渠道')} (${formatIdReference(channel.id)})`, }, ]), ]).values(), @@ -944,7 +950,7 @@ export function OperationsDialog({ '等级档位', bindingConfigs.map((item) => ({ ...item, id: item.config_id })), (item) => - `${item.name || item.tier_key} · 配置 #${item.config_id}`, + `${item.name || item.tier_key || t('未知档位')} · 配置 ${formatIdReference(item.config_id)}`, )} {dateField('effective_from', '绑定生效时间', true)} `${Number(value || 0) / 100}%`, + render: (value) => formatPercent(Number(value || 0) / 100, 2), }, { title: t('提成金额'), dataIndex: 'commission_uyuan', render: money }, ]; @@ -1358,11 +1364,16 @@ export function SettlementDialog({ @@ -1449,7 +1460,7 @@ export function SettlementDialog({ onChange={(value) => set('detail_id', value)} optionList={items.map((item) => ({ 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)}`, }))} /> diff --git a/src/pages/ExpertPlatform/index.jsx b/src/pages/ExpertPlatform/index.jsx index c0b686dc..f033f576 100644 --- a/src/pages/ExpertPlatform/index.jsx +++ b/src/pages/ExpertPlatform/index.jsx @@ -16,7 +16,7 @@ along with this program. If not, see . 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 { @@ -2346,7 +2346,7 @@ const ExpertPlatform = () => { {row.success - ? `${t('通过')} · ${Number(row.time || 0).toFixed(2)}s` + ? `${t('通过')} · ${formatNumber(row.time, 2, '0.00')}s` : row.message || t('失败')}
diff --git a/src/pages/Organization/OrgDeptManage.jsx b/src/pages/Organization/OrgDeptManage.jsx index ffab25ed..cac8f239 100644 --- a/src/pages/Organization/OrgDeptManage.jsx +++ b/src/pages/Organization/OrgDeptManage.jsx @@ -327,7 +327,7 @@ const OrgDeptManage = ({ orgId, featureFlags }) => { placeholder={t('选择部门')} style={{ width: 180 }} optionList={departments.map((d) => ({ - label: `${d.name}(${d.member_count})`, + label: `${d.name || t('未命名部门')}(${d.member_count ?? 0})`, value: d.id, }))} /> diff --git a/src/pages/Organization/OrgEffectiveness.jsx b/src/pages/Organization/OrgEffectiveness.jsx index 0fc4b9c7..1e9dede2 100644 --- a/src/pages/Organization/OrgEffectiveness.jsx +++ b/src/pages/Organization/OrgEffectiveness.jsx @@ -16,8 +16,11 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import { formatIdReference } from '../../helpers/safeDisplay'; -import { formatPercent } from '../../helpers/safeDisplay'; +import { + formatIdReference, + formatNumber, + formatPercent, +} from '../../helpers/safeDisplay'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons'; @@ -271,7 +274,7 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => { { label: t('质量评分'), value: metric.has('quality.score') - ? value('quality.score', true).toFixed(1) + ? formatNumber(value('quality.score', true), 1, t('数据不足')) : t('数据不足'), detail: `${Math.round(value('quality.feedback_count'))} ${t('反馈样本')}`, icon: FlaskConical, @@ -475,7 +478,7 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
- {t('评分')}: {Number(row.score).toFixed(1)} + {t('评分')}: {formatNumber(row.score, 1)} {t('样本')}: {row.sample_count} @@ -496,7 +499,7 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => { { title: t('评分'), dataIndex: 'score', - render: (score) => Number(score).toFixed(1), + render: (score) => formatNumber(score, 1), }, { title: t('样本'), dataIndex: 'sample_count' }, { @@ -564,7 +567,7 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => { {t('平均成本')}:{' '} {row.data_sufficient - ? Number(row.average_quota).toFixed(1) + ? formatNumber(row.average_quota, 1) : t('数据不足')} @@ -598,7 +601,7 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => { title: t('平均成本'), render: (_, row) => row.data_sufficient - ? Number(row.average_quota).toFixed(1) + ? formatNumber(row.average_quota, 1) : t('数据不足'), }, ]} diff --git a/src/pages/Organization/OrgKnowledge.jsx b/src/pages/Organization/OrgKnowledge.jsx index d790b3e6..ffe636ba 100644 --- a/src/pages/Organization/OrgKnowledge.jsx +++ b/src/pages/Organization/OrgKnowledge.jsx @@ -16,8 +16,11 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import { formatIdReference } from '../../helpers/safeDisplay'; -import { formatPercent } from '../../helpers/safeDisplay'; +import { + formatIdReference, + formatPercent, + toFiniteNumber, +} from '../../helpers/safeDisplay'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { @@ -100,9 +103,10 @@ const uploadContentType = (file) => { }; 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']; - let value = Number(bytes); + let value = numericBytes; let unit = 0; while (value >= 1024 && unit < units.length - 1) { value /= 1024; diff --git a/src/pages/Organization/OrgRecharge.jsx b/src/pages/Organization/OrgRecharge.jsx index 48dee3e4..06022618 100644 --- a/src/pages/Organization/OrgRecharge.jsx +++ b/src/pages/Organization/OrgRecharge.jsx @@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com */ import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; +import { formatNumber } from '../../helpers/safeDisplay'; import { Check as ActionCheck } from '@/components/common/icons/ActionIcons'; import React, { useEffect, useState, useCallback, useMemo } from 'react'; import { timestamp2string } from '../../helpers/utils'; @@ -467,7 +468,7 @@ const OrgRecharge = ({ orgId }) => { } if (effectiveAmountYuan <= 0) return ''; 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('金额'), dataIndex: 'money', width: 140, - render: (v) => `¥${Number(v).toFixed(2)}`, + render: (v) => `¥${formatNumber(v, 2, '0.00')}`, }, { title: t('获得额度'), @@ -776,7 +777,14 @@ const OrgRecharge = ({ orgId }) => {
{t('优惠金额')}
-
¥{(effectiveAmountYuan - payableYuan).toFixed(2)}
+
+ ¥ + {formatNumber( + effectiveAmountYuan - payableYuan, + 2, + '0.00', + )} +
{t('支付方式')}
diff --git a/src/pages/Organization/OrgRequests.jsx b/src/pages/Organization/OrgRequests.jsx index a794d33e..96ae7e06 100644 --- a/src/pages/Organization/OrgRequests.jsx +++ b/src/pages/Organization/OrgRequests.jsx @@ -25,6 +25,7 @@ import { Table, Button, Tag, Toast, Input, Popconfirm } from '@/components/ui'; import { API } from '../../helpers/api'; import { showError, collectPagedItems } from '../../helpers'; import { renderQuota } from '../../helpers/render'; +import { formatIdReference } from '../../helpers/safeDisplay'; import OrgPageHeader from './components/OrgPageHeader'; import { OrgListCard, OrgRowActions } from './components/OrgListCard'; import OrgModal from './components/OrgModal'; @@ -158,7 +159,7 @@ const OrgRequests = ({ orgId, orgRole, featureFlags }) => { // 后端已富化 subject_name;主体被删除等极端情况回退为 #ID return r.subject_name ? `${label} · ${r.subject_name}` - : `${label} #${r.subject_id}`; + : `${label} ${formatIdReference(r.subject_id, t('未知主体'))}`; }, }, { diff --git a/src/pages/Organization/OrgSettings.jsx b/src/pages/Organization/OrgSettings.jsx index 1450dbbd..c97a5aa6 100644 --- a/src/pages/Organization/OrgSettings.jsx +++ b/src/pages/Organization/OrgSettings.jsx @@ -16,7 +16,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import { formatUserReference } from '../../helpers/safeDisplay'; +import { formatCurrency, formatUserReference } from '../../helpers/safeDisplay'; import { RefreshCw as ActionRefreshCw, @@ -654,7 +654,12 @@ const OrgSettings = ({ orgId, orgRole }) => { extra={ Number(alertYuan) >= 0.005 ? t('当企业剩余额度低于 {{amount}} 时触发预警', { - amount: `${getCurrencySymbol()}${Number(alertYuan).toFixed(2)}`, + amount: formatCurrency( + alertYuan, + getCurrencySymbol(), + 2, + getCurrencySymbol() + '0.00', + ), }) : t('当前为 0:已关闭余额预警') } diff --git a/src/pages/Organization/OrgSkillAssignments.jsx b/src/pages/Organization/OrgSkillAssignments.jsx index 4689f9bf..faa9e325 100644 --- a/src/pages/Organization/OrgSkillAssignments.jsx +++ b/src/pages/Organization/OrgSkillAssignments.jsx @@ -29,6 +29,7 @@ import { } from '@/components/ui'; import { useTranslation } from 'react-i18next'; import { API } from '../../helpers'; +import { formatIdReference } from '../../helpers/safeDisplay'; import { ActivationModeTag, AssignmentModeTag, @@ -354,7 +355,7 @@ const OrgSkillAssignments = ({ orgId, orgRole = '' }) => { > {library.map((item) => ( - Skill #{item.skill_id} + Skill {formatIdReference(item.skill_id)} ))} diff --git a/src/pages/Organization/OrgSkillLibrary.jsx b/src/pages/Organization/OrgSkillLibrary.jsx index 6da201f7..73ca8e3b 100644 --- a/src/pages/Organization/OrgSkillLibrary.jsx +++ b/src/pages/Organization/OrgSkillLibrary.jsx @@ -42,6 +42,7 @@ import { Search } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; import { API } from '../../helpers'; +import { formatIdReference } from '../../helpers/safeDisplay'; import { LicenseBadge, RiskBadge, @@ -164,8 +165,8 @@ const OrgSkillLibrary = ({ orgId, orgRole, canAssignSkills = false }) => { item?.locales?.find((locale) => locale.locale === 'zh')?.name || item?.locales?.[0]?.name || item?.definition?.canonical_id || - `Skill #${item?.definition?.id}`, - [], + `Skill ${formatIdReference(item?.definition?.id, t('未知技能'))}`, + [t], ); const importCandidates = useMemo(() => { const keyword = importKeyword.trim().toLowerCase(); @@ -516,7 +517,7 @@ const OrgSkillLibrary = ({ orgId, orgRole, canAssignSkills = false }) => { catalog .get(policy.skill_id) ?.locales?.find((item) => item.locale === 'zh')?.name || - `Skill #${policy.skill_id}` + `Skill ${formatIdReference(policy.skill_id, t('未知技能'))}` } actions={ . 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 React, { useCallback, useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; @@ -142,9 +142,9 @@ const localizeAnalyticsRows = (rows, dimension, t) => }[dimension]; if (zeroName) name = zeroName; } 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}`) { - name = `${t('密钥')}#${row.key}`; + name = `${t('密钥')}${formatIdReference(row.key, t('未知密钥'))}`; } return name === row.name ? row : { ...row, name }; }); diff --git a/src/pages/Organization/fund/fundFormat.js b/src/pages/Organization/fund/fundFormat.js index b12dadc9..3b0fe4cd 100644 --- a/src/pages/Organization/fund/fundFormat.js +++ b/src/pages/Organization/fund/fundFormat.js @@ -17,6 +17,8 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatIdReference } from '../../../helpers/safeDisplay'; + // 与后端 model/org_fund.go 常量一一对应 export const FUND_STATE = { NEVER: 0, ON: 1, OFF: 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) => { if (deptId === null || deptId === undefined) return '—'; if (!deptId) return t('未归属部门'); - return deptName || `#${deptId}`; + return deptName || formatIdReference(deptId); }; // 一次分配/回收的幂等键:打开弹窗时生成,重试沿用(F-12)。 diff --git a/src/pages/PartnerPortal/Workbench.jsx b/src/pages/PartnerPortal/Workbench.jsx index f067f3e6..1ffadfb8 100644 --- a/src/pages/PartnerPortal/Workbench.jsx +++ b/src/pages/PartnerPortal/Workbench.jsx @@ -49,12 +49,16 @@ import { } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { API, copy, showError, showSuccess } from '../../helpers'; +import { + formatNumber, + formatPercent, + toFiniteNumber, +} from '../../helpers/safeDisplay'; const { Text, Title } = Typography; const fmtDate = (ts) => (ts ? new Date(ts * 1000).toLocaleDateString() : '-'); -const fmtYuan = (v) => - v === undefined || v === null ? '-' : Number(v).toFixed(2); +const fmtYuan = (v) => formatNumber(v, 2, '-'); const LEAD_STATUS = { pending: ['orange', '待审核'], @@ -845,12 +849,15 @@ function Bills({ t, readOnly }) { { title: t('毛利(元)'), dataIndex: 'gross_profit_yuan', render: fmtYuan }, { 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('应发(元)'), dataIndex: 'payable_yuan', - render: (v) => Number(v ?? 0).toFixed(2), + render: (v) => formatNumber(v, 2, '0.00'), }, { title: '', @@ -965,7 +972,7 @@ function Bills({ t, readOnly }) { data={[ { 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.l2_yuan) }, @@ -980,7 +987,7 @@ function Bills({ t, readOnly }) { }, { key: t('应发(元)'), - value: Number(detail.bill.payable_yuan ?? 0).toFixed(2), + value: formatNumber(detail.bill.payable_yuan, 2, '0.00'), }, ]} /> diff --git a/src/pages/Recharge/RechargePanel.jsx b/src/pages/Recharge/RechargePanel.jsx index b64cd6dd..25e1fef7 100644 --- a/src/pages/Recharge/RechargePanel.jsx +++ b/src/pages/Recharge/RechargePanel.jsx @@ -27,16 +27,23 @@ import { PayPalBrandIcon, } from '../../components/common/icons/BrandIcons'; import { getCurrencyConfig } from '../../helpers/render'; +import { formatNumber, toFiniteNumber } from '../../helpers/safeDisplay'; import { CUSTOMER_SERVICE_OPEN_EVENT } from '../../components/customer-service'; import { showInfo } from '../../helpers'; import AmountCard from './AmountCard'; import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime'; -const formatCny = (value) => - `¥${Number(value || 0).toLocaleString('en-US', { - minimumFractionDigits: 2, - maximumFractionDigits: 2, - })}`; +const formatCny = (value) => { + const number = toFiniteNumber(value); + if (number === null) return '-'; + return ( + '¥' + + number.toLocaleString('en-US', { + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }) + ); +}; // 需要发票时的联系提示(原型:充值订单按钮下方) export const InvoiceNote = ({ t }) => ( @@ -126,19 +133,21 @@ const RechargePanel = ({ // ---- 充值订单:仅由已选档位、金额与支付方式派生展示 ---- const { symbol } = getCurrencyConfig(); const preset = selectedPreset !== null ? selectedPresetObj : null; + const presetValue = toFiniteNumber(preset?.value) ?? 0; 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 originalPrice = preset ? isNewVersion - ? preset.value - : preset.value * priceRatio + ? presetValue + : presetValue * (toFiniteNumber(priceRatio) ?? 0) : 0; const arrivalText = preset ? preset.label || (isNewVersion ? formatCny(preset.value) - : `${symbol}${Number(preset.value).toLocaleString('en-US')}`) + : `${symbol}${presetValue.toLocaleString('en-US')}`) : '-'; const selectedMethod = payMethods?.find((method) => method.type === payWay); const payPalQuoted = payWay === 'paypal' && payPalQuote; @@ -149,7 +158,7 @@ const RechargePanel = ({ ? payPalQuoted ? { symbol: '$', - value: Number(payPalQuote.payAmount).toFixed(2), + value: formatNumber(payPalQuote.payAmount, 2, '0.00'), unit: 'USD', } : null @@ -300,7 +309,7 @@ const RechargePanel = ({ {payPalQuoted && (
{t('支付服务费')}
-
{`$${Number(payPalQuote.serviceFee).toFixed(2)} USD`}
+
{`$${formatNumber(payPalQuote.serviceFee, 2, '0.00')} USD`}
)} diff --git a/src/pages/Recharge/RechargeV2.jsx b/src/pages/Recharge/RechargeV2.jsx index 6cc5a177..c6aaa91d 100644 --- a/src/pages/Recharge/RechargeV2.jsx +++ b/src/pages/Recharge/RechargeV2.jsx @@ -34,6 +34,11 @@ import { import { useTranslation } from 'react-i18next'; import { UserContext } from '../../context/User'; import { API, showError, showSuccess, renderQuota } from '../../helpers'; +import { + formatCurrency, + formatNumber, + toFiniteNumber, +} from '../../helpers/safeDisplay'; import WechatQRModal from '../../components/topup/modals/WechatQRModal'; import './RechargeV2.css'; @@ -263,7 +268,11 @@ const RechargeV2 = () => { }} > {t('{{rate}}折优惠', { - rate: (option.discount * 10).toFixed(1), + rate: formatNumber( + (toFiniteNumber(option.discount) ?? 1) * 10, + 1, + '10.0', + ), })}
)} @@ -288,13 +297,17 @@ const RechargeV2 = () => {
{t('原价:')} - ¥{payInfo.original_money.toFixed(2)} + {formatCurrency(payInfo.original_money)}
{t('折扣:')} {t('{{rate}}折', { - rate: (payInfo.discount_rate * 10).toFixed(1), + rate: formatNumber( + (toFiniteNumber(payInfo.discount_rate) ?? 1) * 10, + 1, + '10.0', + ), })}
@@ -304,18 +317,18 @@ const RechargeV2 = () => { style={{ fontSize: 24, color: 'var(--ui-color-danger)' }} strong > - ¥{payInfo.pay_money.toFixed(2)} + {formatCurrency(payInfo.pay_money)}
{t('获得额度:')} {renderQuota(payInfo.quota)}
- {payInfo.save_money > 0 && ( + {(toFiniteNumber(payInfo.save_money) ?? 0) > 0 && (
{t('节省:')} - ¥{payInfo.save_money.toFixed(2)} + {formatCurrency(payInfo.save_money)}
)} @@ -390,7 +403,7 @@ const RechargeV2 = () => { ? t('处理中...') : calculating ? t('计算中...') - : `${t('支付')} ¥${payInfo?.pay_money?.toFixed(2) || '0.00'}`} + : `${t('支付')} ${formatCurrency(payInfo?.pay_money, '¥', 2, '¥0.00')}`}
diff --git a/src/pages/ServiceDashboard/GroupMonitor.jsx b/src/pages/ServiceDashboard/GroupMonitor.jsx index d977794e..259050cf 100644 --- a/src/pages/ServiceDashboard/GroupMonitor.jsx +++ b/src/pages/ServiceDashboard/GroupMonitor.jsx @@ -16,7 +16,7 @@ along with this program. If not, see . 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 { @@ -97,7 +97,7 @@ const StatusBars = ({ dataPoints = [], loading = false, t }) => {
{isHealthy ? t('正常') : t('异常')} ( - {point.uptime_percent?.toFixed(1)} + {formatPercent(point.uptime_percent, 1).replace('%', '')} {I18N_TECHNICAL_TEXT.PERCENT_CLOSE}
@@ -352,25 +352,28 @@ const GroupMonitor = () => { title: t('可用率'), dataIndex: 'uptime_percent', key: 'uptime_percent', - render: (value) => ( -
-
-
+ render: (value) => { + const uptime = Math.max(0, Math.min(100, toFiniteNumber(value) ?? 0)); + return ( +
+
+
+
+ + {formatPercent(uptime, 1)} +
- - {formatPercent(value || 0, 1)} - -
- ), + ); + }, sorter: (a, b) => (a.uptime_percent || 0) - (b.uptime_percent || 0), }, { diff --git a/src/pages/Setting/Payment/SettingsPaymentGatewayPayPal.jsx b/src/pages/Setting/Payment/SettingsPaymentGatewayPayPal.jsx index 35123851..90710146 100644 --- a/src/pages/Setting/Payment/SettingsPaymentGatewayPayPal.jsx +++ b/src/pages/Setting/Payment/SettingsPaymentGatewayPayPal.jsx @@ -47,6 +47,7 @@ import { showSuccess, } from '../../../helpers'; import { mergePayPalFeePolicyFormValues } from '../../../helpers/paypalPayment'; +import { formatPercent } from '../../../helpers/safeDisplay'; const { Text } = Typography; const SECRET_PLACEHOLDER = '***ALREADY_SET***'; @@ -563,7 +564,7 @@ export default function SettingsPaymentGatewayPayPal(props) { { title: t('费率'), dataIndex: 'new_rate_bps', - render: (value) => `${(Number(value) / 100).toFixed(2)}%`, + render: (value) => formatPercent(Number(value) / 100, 2), }, { title: t('操作人'), diff --git a/src/pages/Setting/WeyAi/SettingsWeyAi.jsx b/src/pages/Setting/WeyAi/SettingsWeyAi.jsx index 88b338c3..7f85f80d 100644 --- a/src/pages/Setting/WeyAi/SettingsWeyAi.jsx +++ b/src/pages/Setting/WeyAi/SettingsWeyAi.jsx @@ -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 批量回填名称(orgLabels),已删除的企业回显为 diff --git a/src/pages/Setting/WeyAi/SettingsWeyAiContent.jsx b/src/pages/Setting/WeyAi/SettingsWeyAiContent.jsx index 4bf8c3cc..4d695c76 100644 --- a/src/pages/Setting/WeyAi/SettingsWeyAiContent.jsx +++ b/src/pages/Setting/WeyAi/SettingsWeyAiContent.jsx @@ -354,7 +354,7 @@ const SettingsWeyAiContent = () => { style={{ minWidth: 260 }} optionList={(overview?.slots || []).map((s) => ({ value: s.id, - label: `${t(s.name)}(${s.item_count})`, + label: `${t(s.name)}(${s.item_count ?? 0})`, }))} />
diff --git a/src/pages/SkillPlatform/index.jsx b/src/pages/SkillPlatform/index.jsx index f568391f..94ddc254 100644 --- a/src/pages/SkillPlatform/index.jsx +++ b/src/pages/SkillPlatform/index.jsx @@ -36,6 +36,7 @@ import { import { IconPlus, IconRefresh, IconSearch } from '@/components/ui/icons'; import { useTranslation } from 'react-i18next'; import { API } from '../../helpers'; +import { formatNumber } from '../../helpers/safeDisplay'; import { skillTagLabel } from '../../constants/skillCategories'; import { CapabilityTags, @@ -740,7 +741,7 @@ const SkillPlatform = () => { { value: '', label: t('全部分类') }, ...tagFacets.map((facet) => ({ 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('测试失败')} - {t('耗时')} {modelTestResult.elapsed.toFixed(2)}s + {t('耗时')} {formatNumber(modelTestResult.elapsed, 2, '0.00')} + s {modelTestResult.usage?.total_tokens ? ` · ${modelTestResult.usage.total_tokens} tokens` : ''} diff --git a/src/pages/Status/index.jsx b/src/pages/Status/index.jsx index 4037f230..71e4f54e 100644 --- a/src/pages/Status/index.jsx +++ b/src/pages/Status/index.jsx @@ -30,6 +30,7 @@ import { import { Iconbolt, IconActivity } from '@/components/ui/icons'; import { useTranslation } from 'react-i18next'; import { API, showError } from '../../helpers'; +import { formatPercent } from '../../helpers/safeDisplay'; const { Content } = Layout; const { Text, Title } = Typography; @@ -84,7 +85,7 @@ const Status = () => { size='small' style={{ height: 8 }} showInfo={true} - format={(per) => `${per}%`} + format={(per) => formatPercent(per, 0)} />
); diff --git a/src/pages/Subscription/index.jsx b/src/pages/Subscription/index.jsx index 31bc338e..e8c2bfda 100644 --- a/src/pages/Subscription/index.jsx +++ b/src/pages/Subscription/index.jsx @@ -16,7 +16,10 @@ along with this program. If not, see . 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 { @@ -39,6 +42,7 @@ import { Button as AntButton } from 'antd'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { useEffectEvent } from '../../hooks/common/useEffectEvent'; import { useTranslation } from 'react-i18next'; +import { formatCurrency } from '../../helpers/safeDisplay'; import { useNavigate } from 'react-router-dom'; import { CreditCard, Search, History } from 'lucide-react'; import { @@ -423,7 +427,7 @@ const Subscription = () => { title: t('支付金额'), dataIndex: 'price_paid', width: 100, - render: (v) => (v != null ? `¥${Number(v).toFixed(2)}` : '-'), + render: (v) => (v != null ? formatCurrency(v) : '-'), }, { title: t('操作'), @@ -1440,7 +1444,7 @@ const DetailDrawer = ({ visible, row, loading, auditLogs, onClose, t }) => {
{t('支付金额')} - ¥{Number(row.price_paid || 0).toFixed(2)} + {formatCurrency(row.price_paid, '¥', 2, '¥0.00')}
{t('支付方式')} @@ -1503,7 +1507,9 @@ const DetailDrawer = ({ visible, row, loading, auditLogs, onClose, t }) => { {log.admin_display_name || log.admin_username || - `Admin#${log.admin_id}`} + (log.admin_id == null + ? t('未知管理员') + : `Admin${formatIdReference(log.admin_id)}`)}
{log.reason && ( diff --git a/src/pages/UserCenter/Invoice.jsx b/src/pages/UserCenter/Invoice.jsx index 731cd9fe..6d93cb83 100644 --- a/src/pages/UserCenter/Invoice.jsx +++ b/src/pages/UserCenter/Invoice.jsx @@ -50,6 +50,11 @@ import { INVOICE_STATUS_COLOR, } from '../../constants'; import { StatusContext } from '../../context/Status'; +import { + formatCurrency, + formatNumber, + toFiniteNumber, +} from '../../helpers/safeDisplay'; const { Text } = Typography; @@ -150,7 +155,7 @@ const Invoice = () => { // 计算选中记录的金额合计 const selectedAmount = availableTopups .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) => { @@ -315,7 +320,7 @@ const Invoice = () => { title: t('支付金额'), dataIndex: 'money', width: 100, - render: (v) => (v ? `¥${Number(v).toFixed(2)}` : '-'), + render: (v) => formatCurrency(v), }, { title: t('订单号'), @@ -343,7 +348,7 @@ const Invoice = () => { title: t('开票金额'), dataIndex: 'amount', width: 100, - render: (v) => `¥${Number(v).toFixed(2)}`, + render: (v) => formatCurrency(v), }, { title: t('状态'), @@ -449,7 +454,7 @@ const Invoice = () => { {t('合计')} {I18N_TECHNICAL_TEXT.CNY_TOTAL_SEPARATOR} - {selectedAmount.toFixed(2)} + {formatNumber(selectedAmount, 2, '0.00')}
)} @@ -584,7 +589,7 @@ const Invoice = () => {
{t('开票金额')} - ¥{Number(detailData.amount).toFixed(2)} + {formatCurrency(detailData.amount)}
@@ -640,7 +645,7 @@ const Invoice = () => { )} - ¥{Number(topup.money).toFixed(2)} + {formatCurrency(topup.money)}
))} diff --git a/test/unit/market-name-search.test.js b/test/unit/market-name-search.test.js index 7e580917..cba72768 100644 --- a/test/unit/market-name-search.test.js +++ b/test/unit/market-name-search.test.js @@ -83,6 +83,11 @@ async function search(query, filters = {}) { '@/components/ui': { Modal: {} }, '../../context/User': { UserContext: {} }, '../../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); diff --git a/test/unit/safe-display.test.js b/test/unit/safe-display.test.js index 89f8a30b..c84c9faf 100644 --- a/test/unit/safe-display.test.js +++ b/test/unit/safe-display.test.js @@ -20,6 +20,8 @@ For commercial licensing, please contact support@quantumnous.com import assert from 'node:assert/strict'; import test from 'node:test'; import { + formatCurrency, + formatNumber, formatPercent, formatRatioPercent, formatIdReference, @@ -30,11 +32,19 @@ import { test('toFiniteNumber rejects missing and non-finite display values', () => { assert.equal(toFiniteNumber(undefined), null); assert.equal(toFiniteNumber(''), null); + assert.equal(toFiniteNumber(' '), null); assert.equal(toFiniteNumber('not-a-number'), null); assert.equal(toFiniteNumber('12.5'), 12.5); 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', () => { assert.equal(formatPercent(undefined), '-'); assert.equal(formatPercent('12.5'), '12.5%');