feat: Merge branch 'ui-optimization' into weiyuan

This commit is contained in:
zhanjunhao
2026-11-20 10:21:27 +08:00
190 changed files with 5519 additions and 5693 deletions
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { formatPercent } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import React, { useState } from 'react';
@@ -118,7 +119,7 @@ const ChannelConsumption = ({ data, title, icon, t, embedded = false }) => {
width: 80,
align: 'right',
render: (val) => (
<span className='text-gray-500'>{(val || 0).toFixed(1)}%</span>
<span className='text-gray-500'>{formatPercent(val || 0, 1)}</span>
),
},
];
+3 -2
View File
@@ -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) => (
<span className='text-yellow-600 font-medium'>
¥{(val || 0).toFixed(2)}
¥{formatNumber(val, 2, '0.00')}
</span>
),
},
@@ -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 <span>{(tokens / 1000000).toFixed(2)}M</span>;
} else if (tokens >= 1000) {
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { formatUserReference } from '../../helpers/safeDisplay';
import React, { useMemo, useState } from 'react';
import {
@@ -113,7 +114,9 @@ const HighFreqLowCostUsers = ({
width: 160,
render: (v, row) => (
<div className='flex flex-col'>
<Text strong>{v || row.username || `user_${row.user_id}`}</Text>
<Text strong>
{formatUserReference(v || row.username, row.user_id, t('未知用户'))}
</Text>
{row.username && v && row.username !== v && (
<Text type='tertiary' size='small'>
@{row.username}
@@ -21,6 +21,7 @@ import React, { useMemo } from 'react';
import { Card } from '@/components/ui';
import { VChart } from '@visactor/react-vchart';
import { renderQuota } from '../../helpers';
import { formatPercent } from '../../helpers/safeDisplay';
const ModelDistribution = ({ data, title, icon, t }) => {
const pieSpec = useMemo(() => {
@@ -119,12 +120,12 @@ const ModelDistribution = ({ data, title, icon, t }) => {
<span className='text-xs text-gray-500 w-4'>{index + 1}</span>
<span
className='text-sm flex-1 truncate'
title={item.model_name}
title={item.model_name || t('未知')}
>
{item.model_name}
{item.model_name || t('未知')}
</span>
<span className='text-xs text-gray-500'>
{item.percent?.toFixed(1)}%
{formatPercent(item.percent, 1)}
</span>
</div>
))}
@@ -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 (
<ConsoleDrawer
@@ -250,7 +252,7 @@ const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => {
</span>
{org?.org_id ? (
<span className='text-xs font-normal text-[var(--text-secondary)]'>
#{org.org_id}
{orgReference}
</span>
) : null}
</div>
@@ -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}
+15 -11
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
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';
@@ -103,16 +104,19 @@ const OrgRealtimeUsage = ({
key: 'org_name',
width: 220,
fixed: 'left',
render: (text, record) => (
<div className='flex items-center gap-2 min-w-0'>
<span className='text-sm font-medium truncate' title={text || ''}>
{text || `${t('企业')} ${record.org_id}`}
</span>
<span className='text-xs text-[var(--text-secondary)] flex-shrink-0'>
#{record.org_id}
</span>
</div>
),
render: (text, record) => {
const orgReference = formatIdReference(record.org_id);
return (
<div className='flex items-center gap-2 min-w-0'>
<span className='text-sm font-medium truncate' title={text || ''}>
{text || `${t('企业')} ${orgReference}`}
</span>
<span className='text-xs text-[var(--text-secondary)] flex-shrink-0'>
{orgReference}
</span>
</div>
);
},
},
{
title: (
@@ -275,7 +279,7 @@ const OrgRealtimeUsage = ({
className='text-sm font-semibold group-hover:underline'
style={{ color: cacheRateColor(rate, token) }}
>
{rate.toFixed(1)}%
{formatPercent(rate, 1)}
</span>
<span
aria-hidden
+4 -3
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { formatNumber, formatPercent } from '../../helpers/safeDisplay';
import React from 'react';
import { Card } from '@/components/ui';
@@ -65,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: <DollarSign className='w-5 h-5' />,
color: 'yellow',
@@ -92,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: <Percent className='w-5 h-5' />,
color: 'pink',
@@ -117,7 +118,7 @@ const OverviewCards = ({ overview, loading = false, t }) => {
)}
<span>
{isPositive ? '+' : ''}
{change.toFixed(1)}%
{formatPercent(change, 1)}
</span>
</div>
);
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { formatUserReference } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next';
import React, { useState } from 'react';
@@ -246,7 +247,9 @@ const RiskControlBanLogs = ({
<div>
<Text type='tertiary'>{t('用户:')}</Text>
<Text strong>
{unbanRow.user_snapshot || `user_${unbanRow.user_id}`}(ID:
{unbanRow.user_snapshot ||
formatUserReference('', unbanRow.user_id, t('未知用户'))}
(ID:
{unbanRow.user_id})
</Text>
</div>
+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 {
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 }) => {
</span>
<div className='text-right'>
<span className='font-medium'>
¥{(item.amount || 0).toFixed(2)}
¥{formatNumber(item.amount, 2, '0.00')}
</span>
<span className='text-gray-400 text-xs ml-2'>
({item.percent?.toFixed(1)}
({formatPercent(item.percent, 1).replace('%', '')}
{I18N_TECHNICAL_TEXT.PERCENT_CLOSE}
</span>
</div>
@@ -152,7 +157,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
))}
<div className='flex items-center justify-between text-sm pt-2 font-semibold'>
<span>{t('合计')}</span>
<span>¥{totalAmount.toFixed(2)}</span>
<span>¥{formatNumber(totalAmount, 2, '0.00')}</span>
</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 { 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]),
},
],
},
+11 -3
View File
@@ -16,6 +16,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
formatIdReference,
formatUserReference,
} from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
@@ -104,11 +108,15 @@ const UserRanking = ({ data, title, icon, t }) => {
<div className='flex items-center justify-between'>
<span
className='text-sm font-medium truncate'
title={`${item.display_name || item.username || 'User'} (ID: ${item.user_id})`}
title={`${formatUserReference(item.display_name || item.username, item.user_id, t('未知用户'))}`}
>
{item.display_name || item.username || `User ${item.user_id}`}
{formatUserReference(
item.display_name || item.username,
item.user_id,
t('未知用户'),
)}
<span className='text-xs text-gray-400 ml-1'>
#{item.user_id}
{formatIdReference(item.user_id)}
</span>
</span>
<span className='text-sm font-semibold text-gray-700 dark:text-gray-300 ml-2'>
+16 -14
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { formatPercent, formatRatioPercent } from '../../helpers/safeDisplay';
import React, { useMemo, useState, useEffect, useCallback } from 'react';
import { Card, Spin, Tag, Progress } from '@/components/ui';
@@ -130,7 +131,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
},
{
key: () => t('占比'),
value: (datum) => `${(datum?.percentage || 0).toFixed(1)}%`,
value: (datum) => formatPercent(datum?.percentage || 0, 1),
},
],
},
@@ -186,7 +187,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
},
{
key: () => t('占比'),
value: (datum) => `${(datum?.percentage || 0).toFixed(1)}%`,
value: (datum) => formatPercent(datum?.percentage || 0, 1),
},
],
},
@@ -334,10 +335,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
{techUsers}
</div>
<div className='text-xs text-gray-400 mt-1'>
{totalUsers > 0
? ((techUsers / totalUsers) * 100).toFixed(1)
: 0}
%
{formatRatioPercent(techUsers, totalUsers, 1, '0.0%')}
</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'>
@@ -351,10 +349,12 @@ const UserSurveyStats = ({ title, icon, t }) => {
{activeAIUsers}
</div>
<div className='text-xs text-gray-400 mt-1'>
{totalUsers > 0
? ((activeAIUsers / totalUsers) * 100).toFixed(1)
: 0}
%
{formatRatioPercent(
activeAIUsers,
totalUsers,
1,
'0.0%',
)}
</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'>
@@ -368,10 +368,12 @@ const UserSurveyStats = ({ title, icon, t }) => {
{interestedUsers}
</div>
<div className='text-xs text-gray-400 mt-1'>
{totalUsers > 0
? ((interestedUsers / totalUsers) * 100).toFixed(1)
: 0}
%
{formatRatioPercent(
interestedUsers,
totalUsers,
1,
'0.0%',
)}
</div>
</div>
</div>
@@ -16,6 +16,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
formatNumber,
formatIdReference,
formatUserReference,
} from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
@@ -80,12 +85,12 @@ const UserTopupRanking = ({ data, title, icon, t, embedded = false }) => {
<div className='flex flex-col'>
<span
className='font-medium text-sm truncate'
title={text || `User ${record.user_id}`}
title={formatUserReference(text, record.user_id, t('未知用户'))}
>
{text || `User ${record.user_id}`}
{formatUserReference(text, record.user_id, t('未知用户'))}
</span>
<span className='text-xs text-gray-400 truncate'>
{I18N_TECHNICAL_TEXT.ID} {record.user_id}
{I18N_TECHNICAL_TEXT.ID} {formatIdReference(record.user_id)}
</span>
</div>
),
@@ -98,7 +103,7 @@ const UserTopupRanking = ({ data, title, icon, t, embedded = false }) => {
defaultSortOrder: 'descend',
render: (value) => (
<span className='font-semibold text-red-500'>
¥{(value || 0).toFixed(2)}
¥{formatNumber(value, 2, '0.00')}
</span>
),
},
@@ -30,6 +30,7 @@ import {
} from '@/components/ui';
import { ClipboardList } from 'lucide-react';
import { ChangeText, OrgNameCell, ReasonTags, SectionCard } from './shared';
import { formatRatioPercent } from '../../../helpers/safeDisplay';
import {
daysSince,
downloadCsv,
@@ -284,7 +285,11 @@ const columnsFor = (tab, cny, t, atRisk) => {
{v}/{r.member_count}
{r.member_count > 0 ? (
<span className='text-xs text-gray-400 ml-1'>
{Math.min(100, (v / r.member_count) * 100).toFixed(0)}%
{formatRatioPercent(
Math.min(100, Number(v) || 0),
r.member_count,
0,
)}
</span>
) : null}
</span>
@@ -31,6 +31,10 @@ import {
} from 'lucide-react';
import { ChangeText, KpiCard, SectionCard } from './shared';
import { formatCny, formatCst, pct, SEGMENTS } from './utils';
import {
formatPercent,
formatRatioPercent,
} from '../../../helpers/safeDisplay';
// ─── 报表抬头:统计口径 + 数据状态 ─────────────────────────────────
export const ReportHeader = ({ report, onExport, t }) => {
@@ -209,7 +213,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
n: (k.active_orgs || 0).toLocaleString(),
count: k.active_orgs || 0,
}),
sub: `${t('活跃率')} ${pct(k.active_orgs, servingOrgs).toFixed(1)}% · ${t('新增')} ${k.new_orgs || 0}`,
sub: `${t('活跃率')} ${formatRatioPercent(k.active_orgs, servingOrgs)} · ${t('新增')} ${k.new_orgs || 0}`,
compare: (
<ChangeText cur={k.active_orgs} prev={k.prev_active_orgs} t={t} />
),
@@ -229,7 +233,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
n: (k.active_members || 0).toLocaleString(),
count: k.active_members || 0,
}),
sub: `${t('渗透率')} ${Math.min(100, pct(k.active_members, k.total_members)).toFixed(1)}% · ${t('成员')} ${(k.total_members || 0).toLocaleString()}`,
sub: `${t('渗透率')} ${formatPercent(Math.min(100, pct(k.active_members, k.total_members)))} · ${t('成员')} ${(k.total_members || 0).toLocaleString()}`,
tip: t('本期通过企业密钥产生调用的去重成员数(按自然日统计)'),
onClick: () => onJump('growth'),
},
@@ -277,7 +281,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
},
{
title: t('企业消耗占平台'),
value: `${share.toFixed(1)}%`,
value: formatPercent(share),
sub: `${t('个人消耗')} ${formatCny(k.personal_quota, cny)}`,
compare:
shareDelta === null ? null : (
@@ -341,7 +345,7 @@ export const HealthSegments = ({ report, cny, activeSegment, onSelect, t }) => {
{t(meta.label)}
</Tag>
<span className='text-xs text-gray-400 tabular-nums'>
{pct(s.count, totalCount).toFixed(0)}%
{formatPercent(pct(s.count, totalCount), 0)}
</span>
</div>
<div className='mt-2 text-lg font-bold text-gray-800 dark:text-gray-100 tabular-nums'>
@@ -30,6 +30,7 @@ import {
} from '@/components/ui';
import { Search, Table2, UserCog } from 'lucide-react';
import { ChangeText, OrgNameCell, SectionCard } from './shared';
import { formatPercent } from '../../../helpers/safeDisplay';
import {
ALERT_LEVELS,
ORG_STATUS,
@@ -266,7 +267,7 @@ export const OrgDetailTable = ({ report, filter, setFilter, cny, t }) => {
align: 'right',
render: (v) =>
v > 0 ? (
<span className='tabular-nums'>{v.toFixed(1)}%</span>
<span className='tabular-nums'>{formatPercent(v, 1)}</span>
) : (
<Text type='tertiary'>—</Text>
),
@@ -501,8 +502,8 @@ export const exportOrgDetail = (rows, cny, t) => {
SEGMENTS[o.segment] ? t(SEGMENTS[o.segment].label) : '',
yuan(o.quota),
yuan(o.prev_quota),
rate === null ? '' : `${rate.toFixed(1)}%`,
o.share ? `${o.share.toFixed(2)}%` : '',
rate === null ? '' : formatPercent(rate, 1),
o.share ? formatPercent(o.share, 2) : '',
o.requests,
o.active_members,
o.member_count,
@@ -21,6 +21,7 @@ import React from 'react';
import { Card, Tag, Tooltip } from '@/components/ui';
import { TrendingDown, TrendingUp } from 'lucide-react';
import { changeRate, ORG_STATUS, orgDisplayName, REASONS } from './utils';
import { formatPercent } from '../../../helpers/safeDisplay';
export const SectionCard = ({
id,
@@ -90,7 +91,7 @@ export const ChangeText = ({ cur, prev, t, size = 'xs', showNew = true }) => {
<TrendingDown className='w-3 h-3' />
)}
{up ? '+' : ''}
{rate.toFixed(1)}%
{formatPercent(rate, 1)}
</span>
);
};
+28 -10
View File
@@ -16,6 +16,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
formatIdReference,
formatPercent,
toFiniteNumber,
} from '../../../helpers/safeDisplay';
// 企业经营决策报表:口径常量、行动清单派生、要点生成、CSV 导出
@@ -27,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;
}
@@ -35,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, {
@@ -47,12 +53,22 @@ 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) => (total > 0 ? (part / total) * 100 : 0);
export const pct = (part, total) => {
const numerator = Number(part);
const denominator = Number(total);
return Number.isFinite(numerator) &&
Number.isFinite(denominator) &&
denominator > 0
? (numerator / denominator) * 100
: 0;
};
// ─── 时间(报表口径统一为 UTC+8,与浏览器时区无关) ─────────────────
const pad = (n) => String(n).padStart(2, '0');
@@ -405,11 +421,11 @@ export const deriveFindings = (report, lists, cny, t) => {
? t(
'头部依赖较高:Top5 企业贡献 {{share}} 的企业消耗,需关注大客户稳定性',
{
share: `${k.top5_share.toFixed(1)}%`,
share: formatPercent(k.top5_share, 1),
},
)
: t('客户结构较分散:Top5 企业贡献 {{share}} 的企业消耗', {
share: `${k.top5_share.toFixed(1)}%`,
share: formatPercent(k.top5_share, 1),
}),
target: 'tiers',
});
@@ -426,7 +442,7 @@ export const deriveFindings = (report, lists, cny, t) => {
text: t(
'企业成员渗透率 {{rate}},{{count}} 家企业成员活跃率低于 30%,存在增量空间',
{
rate: `${Math.min(100, penetration).toFixed(1)}%`,
rate: formatPercent(Math.min(100, penetration), 1),
count: lowPen,
},
),
@@ -467,4 +483,6 @@ export const downloadCsv = (filename, headers, rows) => {
};
export const orgDisplayName = (o, t) =>
o.deleted ? `${t('已删除企业')} #${o.org_id}` : o.name || `#${o.org_id}`;
o.deleted
? `${t('已删除企业')} ${formatIdReference(o.org_id)}`
: o.name || formatIdReference(o.org_id);
+9 -2
View File
@@ -19,8 +19,9 @@ For commercial licensing, please contact support@quantumnous.com
import React from 'react';
import { Button } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { isSafePostLoginRedirect } from '../../helpers/data';
/**
* 认证页「个人 / 企业」分段切换控件(登录与注册两种模式)。
@@ -34,6 +35,12 @@ import { useTranslation } from 'react-i18next';
const AuthLoginTabs = ({ active = 'personal', mode = 'login' }) => {
const { t } = useTranslation();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const redirect = searchParams.get('redirect');
const loginSearch =
mode === 'login' && isSafePostLoginRedirect(redirect)
? `?${new URLSearchParams({ redirect })}`
: '';
// 企业入口置于左侧首位:本产品主推企业用户,企业登录/注册是默认入口
const tabs =
@@ -57,7 +64,7 @@ const AuthLoginTabs = ({ active = 'personal', mode = 'login' }) => {
type={isActive ? 'primary' : 'text'}
aria-pressed={isActive}
onClick={() => {
if (!isActive) navigate(tab.to);
if (!isActive) navigate(`${tab.to}${loginSearch}`);
}}
className='flex-1 font-medium'
>
+13 -8
View File
@@ -220,12 +220,17 @@ const LoginForm = () => {
};
}, []);
const redirect = searchParams.get('redirect');
useEffect(() => {
const redirect = searchParams.get('redirect');
if (redirect) {
savePostLoginRedirect(redirect);
}
if (searchParams.get('expired')) {
savePostLoginRedirect(redirect);
}, [redirect]);
const expiryShown = useRef(false);
useEffect(() => {
if (!searchParams.get('expired')) {
expiryShown.current = false;
} else if (!expiryShown.current) {
expiryShown.current = true;
showError(t('未登录或登录已过期,请重新登录'));
const nextParams = new URLSearchParams(searchParams);
nextParams.delete('expired');
@@ -234,15 +239,15 @@ const LoginForm = () => {
}, [searchParams, setSearchParams, t]);
const finishLogin = useCallback(
(data, successMessage) =>
(data) =>
runLoginFlow({
data,
userDispatch,
navigate,
t,
successMessage,
redirect,
}),
[navigate, t, userDispatch],
[navigate, redirect, t, userDispatch],
);
const onWeChatLoginClicked = () => {
+1 -2
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
*/
import { Trans } from 'react-i18next';
import { API, showError, showSuccess } from '../../helpers';
import { API, showError } from '../../helpers';
import { Button, Card, Divider, Form, Typography } from '@/components/ui';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -51,7 +51,6 @@ const TwoFAVerification = ({ onSuccess, onBack, isModal = false }) => {
});
if (res.data.success) {
showSuccess(t('登录成功'));
if (onSuccess) {
onSuccess(res.data.data);
}
@@ -18,9 +18,41 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Button, Dropdown } from 'antd';
import { useTranslation } from 'react-i18next';
import { ChevronDown } from '../icons/ActionIcons';
import './table-toolbar.css';
export function TableRowActions({ children, items = [] }) {
const { t } = useTranslation();
const menuItems = items.filter(Boolean);
if (!children && !menuItems.length) return null;
return (
<div className='table-row-actions'>
{children}
{menuItems.length > 0 && (
<Dropdown
autoFocus
trigger={['click']}
placement='bottomRight'
menu={{ items: menuItems }}
>
<Button
type='link'
size='small'
icon={<ChevronDown size={14} aria-hidden />}
iconPlacement='end'
aria-haspopup='menu'
>
{t('更多')}
</Button>
</Dropdown>
)}
</div>
);
}
export function TableTitle({ children }) {
const { t } = useTranslation();
return (
@@ -1,3 +1,10 @@
.table-row-actions {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.table-toolbar {
display: flex;
align-items: center;
+22 -15
View File
@@ -24,6 +24,27 @@ import { useIsMobile } from '../../hooks/common/useIsMobile';
import { ConsoleCard, ConsoleSearchBar } from './ConsolePrimitives';
import { TableTitle } from '../common/table/TableToolbar';
export function ConsoleCollectionSearch({ children, className }) {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [expanded, setExpanded] = useState(false);
return (
<>
{isMobile && (
<Button
onClick={() => setExpanded((value) => !value)}
aria-expanded={expanded}
>
{t(expanded ? '隐藏操作项' : '显示操作项')}
</Button>
)}
<ConsoleSearchBar className={className} hidden={isMobile && !expanded}>
{children}
</ConsoleSearchBar>
</>
);
}
export default function ConsoleCollection({
children,
statsArea,
@@ -36,27 +57,13 @@ export default function ConsoleCollection({
tableActionsOffset = false,
paginationArea,
}) {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [expanded, setExpanded] = useState(false);
const showSearch = !isMobile || expanded;
return (
<div className='console-collection'>
{statsArea && (
<ConsoleCard className='console-stats'>{statsArea}</ConsoleCard>
)}
{searchArea && (
<>
{isMobile && (
<Button
onClick={() => setExpanded(!expanded)}
aria-expanded={expanded}
>
{t(expanded ? '隐藏操作项' : '显示操作项')}
</Button>
)}
<ConsoleSearchBar hidden={!showSearch}>{searchArea}</ConsoleSearchBar>
</>
<ConsoleCollectionSearch>{searchArea}</ConsoleCollectionSearch>
)}
<ConsoleCard>
{tabsArea && <div className='console-list-tabs'>{tabsArea}</div>}
+43 -15
View File
@@ -32,6 +32,8 @@ import {
} from 'antd';
import { useTranslation } from 'react-i18next';
import TableEmpty from '../common/table/TableEmpty';
import FilterSearchButton from '../common/table/FilterSearchButton';
import './console.css';
import {
ConsoleSearchContext,
useConsolePage,
@@ -96,24 +98,40 @@ export function ConsoleSearchBar({ children, className, formProps, ...props }) {
);
}
export function ConsoleSearchActions({
onReset,
onSearch,
loading,
searchLabel = '搜索',
}) {
export function ConsoleSearchActions({ onReset, loading }) {
const { t } = useTranslation();
return (
<div className='console-search-actions'>
{onReset && <Button onClick={onReset}>{t('重置')}</Button>}
<Button
type='primary'
htmlType={onSearch ? 'button' : 'submit'}
onClick={onSearch}
loading={loading}
>
{t(searchLabel)}
</Button>
{onReset && (
<Button htmlType='button' onClick={onReset}>
{t('重置')}
</Button>
)}
<FilterSearchButton loading={loading} />
</div>
);
}
export function ConsoleFilterGrid({ children, onReset, onSearch, loading }) {
return (
<form
className='console-filter-panel'
onSubmit={(event) => {
event.preventDefault();
onSearch();
}}
>
<div className='console-filter-grid'>{children}</div>
<ConsoleSearchActions onReset={onReset} loading={loading} />
</form>
);
}
export function ConsoleFilterField({ label, id, children }) {
return (
<div className='console-filter-field'>
<label htmlFor={id}>{label}</label>
{children}
</div>
);
}
@@ -167,6 +185,16 @@ export function ConsoleTabs({ className, ...props }) {
return <Tabs {...props} className={classes('console-tabs', className)} />;
}
export function ConsoleListTable({ locale, ...props }) {
return (
<ConsoleTable
{...props}
className={classes('console-list-table', props.className)}
locale={{ emptyText: <TableEmpty />, ...locale }}
/>
);
}
const isFooterButton = (node) =>
React.isValidElement(node) &&
(node.type === Button || node.type?.render?.name === 'Button');
+62 -1
View File
@@ -230,9 +230,70 @@
justify-content: flex-end;
flex: 0 0 auto;
flex-wrap: wrap;
gap: var(--console-space-1);
gap: var(--console-space-1, 8px);
margin-inline-start: auto;
}
.console-filter-panel {
width: 100%;
}
.console-page .console-search-card .console-filter-panel.ant-form {
display: block;
}
.console-filter-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1rem;
width: 100%;
}
.console-filter-field {
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
}
.console-filter-field > label,
.console-page .console-filter-grid .ant-form-item-label > label {
color: var(--console-muted, var(--ui-color-text-2));
font-size: 13px;
}
.console-filter-field > :is(.ant-input-number, .ant-picker) {
width: 100%;
}
.console-filter-panel .console-search-actions {
margin-top: 1rem;
}
.console-table.console-list-table .ant-table-thead > tr > th {
height: 46px;
padding-block: 0;
font-weight: 400;
}
.console-list-tools,
.console-list-quick-filters,
.console-list-tool-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.console-list-tools {
width: 100%;
gap: 12px 20px;
justify-content: space-between;
}
.console-list-tool-actions {
justify-content: flex-end;
margin-inline-start: auto;
}
@media (max-width: 1100px) {
.console-filter-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 768px) {
.console-filter-grid {
grid-template-columns: minmax(0, 1fr);
}
}
.console-page .console-table .ant-table-thead > tr > th {
--center-table-head-bg: var(--console-fill);
color: var(--console-muted);
+10 -1
View File
@@ -198,12 +198,20 @@ const PageLayout = () => {
return;
}
const sessionAPI = API;
const isCurrentSession = () => {
const currentUser = getUserData();
return (
sessionAPI === API && currentUser?.id === cachedUser.id && !!currentUser
);
};
userDispatch({ type: 'auth_start' });
try {
const res = await API.get('/api/user/self', {
const res = await sessionAPI.get('/api/user/self', {
skipErrorHandler: true,
disableDuplicate: true,
});
if (!isCurrentSession()) return;
const { success, data } = res.data;
if (success && data) {
setUserData(data);
@@ -213,6 +221,7 @@ const PageLayout = () => {
userDispatch({ type: 'logout' });
}
} catch (error) {
if (!isCurrentSession()) return;
if (error?.response?.status === 401 || error?.response?.status === 403) {
clearUserData();
userDispatch({ type: 'logout' });
@@ -146,7 +146,10 @@ const ActionButtons = ({
<div className='ui-header-actions flex items-center shrink-0'>
{/* Tutorial Button - 新手教程按钮 (桌面端显示) */}
{isLoggedIn && isButtonVisible('tutorial') && (
<Link to='/tutorial' className='hidden sm:block'>
<Link
to='/tutorial'
className='ui-header-action-link ui-header-desktop-action'
>
<AntButton icon={actionIcon(BookOpen)}>
{!isMobile && t('新手教程')}
</AntButton>
@@ -157,7 +160,7 @@ const ActionButtons = ({
{isLoggedIn && isButtonVisible('pricing') && (
<AntButton
icon={actionIcon(Share2)}
className='hidden sm:!inline-flex'
className='ui-header-desktop-action'
onClick={() => setPromotionVisible(true)}
>
{!isMobile && t('推广')}
@@ -169,7 +172,7 @@ const ActionButtons = ({
<Tooltip title={t('下载 WeyAi')}>
<Link
to='/weyai/download'
className='hidden sm:block'
className='ui-header-action-link ui-header-desktop-action'
aria-label={t('下载 WeyAi 桌面端')}
>
<AntButton
@@ -185,7 +188,7 @@ const ActionButtons = ({
{/* Recharge Button - 充值按钮 */}
{isButtonVisible('recharge') && !isMiniProgramWebView() && (
<Link to='/recharge'>
<Link to='/recharge' className='ui-header-action-link'>
<AntButton
icon={actionIcon(Wallet)}
aria-label={isMobile ? t('充值') : undefined}
@@ -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('生效日期'),
+195 -381
View File
@@ -19,7 +19,6 @@ For commercial licensing, please contact support@quantumnous.com
import {
Copy as ActionCopy,
CheckCircle as ActionCheckCircle,
Download as ActionDownload,
} from '@/components/common/icons/ActionIcons';
import React, { useState, useEffect, useRef, useCallback } from 'react';
@@ -30,26 +29,17 @@ import {
Button,
Typography,
Tabs,
TabPane,
Input,
Tag,
} from '@/components/ui';
Alert,
Skeleton,
Radio,
} from 'antd';
import { QRCodeCanvas } from 'qrcode.react';
import {
Share2,
Smartphone,
Monitor,
Gift,
Users,
Sparkles,
ChevronRight,
CheckCircle,
Coins,
TrendingUp,
} from 'lucide-react';
import { Smartphone, Monitor, Gift, Users, ChevronRight } from 'lucide-react';
import './promotion-poster.css';
import { API, showError, showSuccess, copy } from '../../helpers';
const { Text } = Typography;
const { Text, Title, Paragraph } = Typography;
// 默认海报模板配置
const DEFAULT_TEMPLATES = [
@@ -311,409 +301,233 @@ const PromotionPosterModal = ({ visible, onClose }) => {
copyWithFeedback(affCode, t('邀请码'));
};
// 链接分享模式 - PC友好
const renderLinkMode = () => (
<div className='flex flex-col items-center w-full'>
{/* 分享卡片 */}
<div
className='w-full rounded-2xl p-6 mb-6 relative overflow-hidden'
style={{ background: selectedTemplate.bgGradient }}
>
{/* 装饰元素 */}
<div className='absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2' />
<div className='absolute bottom-0 left-0 w-24 h-24 bg-white/10 rounded-full translate-y-1/2 -translate-x-1/2' />
<div className='absolute top-1/2 right-4 w-16 h-16 bg-white/5 rounded-full' />
<div className='relative z-10'>
{/* 平台信息 */}
<div className='flex items-center gap-3 mb-4'>
<div className='w-12 h-12 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center shadow-lg'>
<Sparkles size={24} className='text-white' />
</div>
<div>
<h3 className='text-white font-bold text-lg drop-shadow-sm'>
{systemName}
</h3>
<p className='text-white/80 text-sm'>
{posterConfig?.slogan || t('邀请好友,共享AI')}
</p>
</div>
</div>
{/* 福利说明 */}
<div className='flex gap-4 mb-5'>
<div className='flex items-center gap-2 text-white/90 text-sm bg-white/10 backdrop-blur-sm px-3 py-1.5 rounded-full'>
<Gift size={14} />
<span>{t('注册即送额度')}</span>
</div>
<div className='flex items-center gap-2 text-white/90 text-sm bg-white/10 backdrop-blur-sm px-3 py-1.5 rounded-full'>
<Users size={14} />
<span>{t('消费返佣')}</span>
</div>
</div>
{/* 二维码(小尺寸) */}
<div className='flex items-center gap-4'>
<div className='bg-white rounded-xl p-2.5 shadow-xl'>
<QRCodeCanvas
id='link-mode-qrcode'
value={affLink || 'https://example.com'}
size={80}
level='M'
includeMargin={false}
/>
</div>
<div className='flex-1'>
<p className='text-white/70 text-xs mb-1'>{t('手机扫码注册')}</p>
<p className='text-white font-mono text-sm'>
{t('邀请码')}:{' '}
<span className='font-bold bg-white/20 px-2 py-0.5 rounded'>
{affCode}
</span>
</p>
</div>
</div>
</div>
</div>
{/* 链接输入框 */}
<div className='w-full mb-4'>
<Text className='text-sm text-gray-500 dark:text-gray-400 mb-2 block font-medium'>
{t('邀请链接')}
</Text>
<div className='relative group'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-brand-from/30 to-brand-to/30 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-sm' />
<Input
<div className='pm-link-layout'>
<section className='pm-invitation-card'>
<div className='pm-eyebrow'>{t('推广分享')}</div>
<Title level={4}>{systemName}</Title>
<Paragraph type='secondary'>
{posterConfig?.slogan || t('邀请好友,共享AI')}
</Paragraph>
<div className='pm-qrcode'>
<QRCodeCanvas
id='link-mode-qrcode'
value={affLink}
readOnly
size='large'
className='!rounded-xl'
suffix={
<Button
theme='solid'
type='primary'
size='small'
icon={<ActionCopy size={14} />}
onClick={handleCopyLink}
className='!bg-gradient-to-r !from-brand-from !to-brand-to !border-0 !rounded-lg'
>
{t('复制')}
</Button>
}
size={144}
level='M'
marginSize={2}
/>
</div>
</div>
{/* 邀请码 */}
<div className='w-full mb-4'>
<Text className='text-sm text-gray-500 dark:text-gray-400 mb-2 block font-medium'>
{t('邀请码')}
</Text>
<div className='flex items-center gap-3'>
<div className='relative'>
<div className='absolute -inset-1 bg-gradient-to-r from-blue-500/20 to-brand-to/20 rounded-lg blur-sm' />
<Tag
size='large'
color='blue'
className='!text-lg !px-5 !py-2.5 !rounded-xl !font-bold relative'
>
{affCode}
</Tag>
</div>
<Text type='secondary'>{t('手机扫码注册')}</Text>
<div className='pm-benefits'>
<span>
<Gift size={14} aria-hidden />
{t('注册即送额度')}
</span>
<span>
<Users size={14} aria-hidden />
{t('消费返佣')}
</span>
</div>
</section>
<section className='pm-share-details'>
<div className='pm-field'>
<label htmlFor='promotion-link'>{t('邀请链接')}</label>
<Input id='promotion-link' value={affLink} readOnly size='large' />
<Button
theme='light'
type='tertiary'
icon={<ActionCopy size={14} />}
onClick={handleCopyCode}
className='!rounded-lg'
type='primary'
icon={<ActionCopy size={16} aria-hidden />}
onClick={handleCopyLink}
>
{t('复制')}
{t('复制链接')}
</Button>
</div>
</div>
{/* 使用说明 */}
<div className='w-full p-4 bg-gradient-to-r from-blue-50 to-brand-to/5 dark:from-blue-900/20 dark:to-brand-to/20 rounded-xl border border-blue-100 dark:border-blue-800/30'>
<div className='flex items-start gap-2'>
<CheckCircle
size={16}
className='text-blue-500 mt-0.5 flex-shrink-0'
/>
<Text className='text-sm text-blue-700 dark:text-blue-300'>
{t(
'将链接发送给好友,好友点击即可注册。支持微信、QQ、邮件等任意方式分享。',
)}
<div className='pm-field'>
<Text strong id='promotion-code-label'>
{t('邀请码')}
</Text>
<div
className='pm-code-row'
role='group'
aria-labelledby='promotion-code-label'
>
<Text id='promotion-code' className='pm-code'>
{affCode}
</Text>
<Button
icon={<ActionCopy size={16} aria-hidden />}
onClick={handleCopyCode}
>
{t('复制')}
</Button>
</div>
</div>
</div>
<Paragraph type='secondary' className='pm-share-hint'>
{t(
'将链接发送给好友,好友点击即可注册。支持微信、QQ、邮件等任意方式分享。',
)}
</Paragraph>
</section>
</div>
);
// 海报模式 - 移动端友好
const renderPosterMode = () => (
<div className='flex flex-col items-center'>
{/* 模板选择 */}
<div className='w-full mb-4'>
<Text className='text-sm text-gray-500 dark:text-gray-400 mb-2 block font-medium'>
{t('选择模板')}
</Text>
<div className='flex gap-3 flex-wrap'>
{DEFAULT_TEMPLATES.map((template) => (
<button
key={template.id}
onClick={() => setSelectedTemplate(template)}
className={[
'app-action-button',
`relative w-14 h-14 rounded-xl border-2 transition-all duration-300 overflow-hidden ${
selectedTemplate.id === template.id
? 'border-brand scale-110 shadow-lg shadow-brand/30'
: 'border-transparent hover:border-gray-300 hover:scale-105'
}`,
]
.filter(Boolean)
.join(' ')}
style={{ background: template.bgGradient }}
title={t(template.name)}
>
{selectedTemplate.id === template.id && (
<div className='absolute inset-0 flex items-center justify-center bg-black/20'>
<ActionCheckCircle size={20} className='text-white' />
</div>
)}
</button>
))}
</div>
</div>
{/* 海报预览 */}
<div
className='relative rounded-2xl overflow-hidden shadow-2xl'
style={{
width: 280,
height: 497,
background: selectedTemplate.bgGradient,
}}
>
{/* 装饰元素 */}
<div className='absolute top-0 right-0 w-24 h-24 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2' />
<div className='absolute bottom-20 left-0 w-16 h-16 bg-white/10 rounded-full -translate-x-1/2' />
<div className='absolute inset-0 flex flex-col items-center pt-10 px-5'>
<h2
className='text-xl font-bold mb-2 text-center drop-shadow-sm'
style={{ color: selectedTemplate.textColor }}
>
{posterConfig?.slogan || t('邀请好友,共享AI')}
</h2>
<p
className='text-xs mb-5 opacity-90'
style={{ color: selectedTemplate.textColor }}
>
<div className='pm-poster-layout'>
<div className='pm-preview-stage'>
<div
className='pm-poster'
style={{
'--pm-poster-background': selectedTemplate.bgGradient,
'--pm-poster-ink': selectedTemplate.textColor,
}}
>
<h2>{posterConfig?.slogan || t('邀请好友,共享AI')}</h2>
<p className='pm-poster-subtitle'>
{posterConfig?.sub_slogan || t('注册即可获得免费额度')}
</p>
<h3
className='text-lg font-bold mb-6 drop-shadow-sm'
style={{ color: selectedTemplate.textColor }}
>
{systemName}
</h3>
<div className='bg-white rounded-xl p-3 shadow-2xl'>
<h3>{systemName}</h3>
<div className='pm-poster-qr'>
<QRCodeCanvas
id='poster-qrcode'
value={affLink || 'https://example.com'}
value={affLink}
size={130}
level='H'
includeMargin={false}
marginSize={2}
/>
</div>
<p
className='text-xs mt-3 opacity-90'
style={{ color: selectedTemplate.textColor }}
>
{t('扫码注册')}
<p>{t('扫码注册')}</p>
<p className='pm-poster-code'>
{t('邀请码')}: {affCode}
</p>
<p className='pm-poster-footer'>
{posterConfig?.footer_text || t('长按识别二维码,立即体验AI')}
</p>
<div
className='mt-2 px-4 py-1.5 rounded-full'
style={{ backgroundColor: 'rgba(255,255,255,0.2)' }}
>
<p
className='text-sm font-bold'
style={{ color: selectedTemplate.textColor }}
>
{t('邀请码')}: {affCode}
</p>
</div>
<div className='absolute bottom-6 left-0 right-0 text-center'>
<div
className='h-px mx-6 mb-3 opacity-30'
style={{ backgroundColor: selectedTemplate.textColor }}
/>
<p
className='text-xs opacity-80'
style={{ color: selectedTemplate.textColor }}
>
{posterConfig?.footer_text || t('长按识别二维码,立即体验AI')}
</p>
</div>
</div>
</div>
{/* 隐藏的 canvas 用于导出 */}
<canvas ref={canvasRef} style={{ display: 'none' }} />
{/* 操作按钮 */}
<div className='flex gap-3 mt-5 w-full'>
<Button
theme='solid'
type='primary'
icon={<ActionDownload size={16} />}
onClick={handleDownload}
loading={downloading}
className='flex-1 !bg-gradient-to-r !from-brand-from !to-brand-to !border-0 !rounded-xl !h-10'
>
{t('下载海报')}
</Button>
<Button
theme='light'
type='tertiary'
icon={<ActionCopy size={16} />}
onClick={handleCopyLink}
className='flex-1 !rounded-xl !h-10'
>
{t('复制链接')}
</Button>
</div>
<section className='pm-poster-options'>
<div className='pm-field'>
<Text strong id='promotion-template-label'>
{t('选择模板')}
</Text>
<Radio.Group
className='pm-template-list'
aria-labelledby='promotion-template-label'
value={selectedTemplate.id}
onChange={(event) =>
setSelectedTemplate(
DEFAULT_TEMPLATES.find(
(item) => item.id === event.target.value,
),
)
}
>
{DEFAULT_TEMPLATES.map((template) => (
<Radio key={template.id} value={template.id}>
<span className='pm-template-label'>
<span
className='pm-template-swatch'
style={{ '--pm-template-background': template.bgGradient }}
/>
{t(template.name)}
</span>
</Radio>
))}
</Radio.Group>
</div>
<div className='pm-poster-actions'>
<Button
type='primary'
icon={<ActionDownload size={16} aria-hidden />}
onClick={handleDownload}
loading={downloading}
>
{t('下载海报')}
</Button>
<Button
icon={<ActionCopy size={16} aria-hidden />}
onClick={handleCopyLink}
>
{t('复制链接')}
</Button>
</div>
<Text type='secondary' className='pm-share-hint'>
{posterConfig?.footer_text || t('长按识别二维码,立即体验AI')}
</Text>
</section>
<canvas ref={canvasRef} hidden />
</div>
);
return (
<Modal
title={
<div className='flex items-center gap-2'>
<div className='w-8 h-8 rounded-lg bg-gradient-to-br from-brand-from to-brand-to flex items-center justify-center shadow-lg shadow-brand/30'>
<Share2 size={16} className='text-white' />
</div>
<span className='font-bold text-lg'>{t('推广分享')}</span>
</div>
}
visible={visible}
title={t('推广分享')}
open={visible}
onCancel={onClose}
footer={null}
width={520}
width={800}
centered
className='promotion-modal'
bodyStyle={{ padding: '0 24px 24px' }}
>
<div style={{ minHeight: 540 }}>
{loading ? (
<div
className='flex flex-col justify-center items-center'
style={{ height: 540 }}
>
<div className='relative'>
<div className='w-16 h-16 rounded-full border-4 border-brand/10 dark:border-brand-deep' />
<div className='absolute inset-0 w-16 h-16 rounded-full border-4 border-brand border-t-transparent animate-spin' />
</div>
<span className='mt-4 text-gray-500 dark:text-gray-400'>
{t('加载中...')}
</span>
</div>
) : (
<>
{/* 查看邀请奖励规则 - 顶部显眼横幅 */}
<div
className='group mb-5 p-4 rounded-2xl cursor-pointer transition-all duration-300 hover:scale-[1.02] hover:shadow-xl relative overflow-hidden'
style={{
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
}}
onClick={() => {
onClose();
navigate('/user-center/invite');
}}
>
{/* 装饰元素 */}
<div className='absolute top-0 right-0 w-20 h-20 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2' />
<div className='absolute bottom-0 left-1/2 w-32 h-32 bg-white/5 rounded-full translate-y-1/2' />
{/* 动态光效 */}
<div className='absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-1000' />
<div className='relative flex items-center justify-between'>
<div className='flex items-center gap-3'>
<div className='w-12 h-12 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center shadow-lg'>
<Gift size={22} className='text-white' />
</div>
<div>
<div className='text-white font-bold text-base flex items-center gap-2'>
{t('查看邀请奖励规则')}
<Sparkles
size={14}
className='text-amber-300 animate-pulse'
/>
</div>
<div className='text-white/80 text-sm mt-0.5'>
{t('了解返佣比例和奖励详情')}
</div>
</div>
</div>
<div className='flex items-center gap-1 text-white/90 group-hover:translate-x-1 transition-transform'>
<span className='text-xs font-medium hidden sm:block'>
{t('立即查看')}
</span>
<ChevronRight size={20} />
</div>
</div>
{/* 底部小标签 */}
<div className='flex gap-2 mt-3'>
<span className='text-xs bg-white/20 backdrop-blur-sm text-white px-2 py-1 rounded-full flex items-center gap-1'>
<Coins size={12} />
{t('消费返佣')}
</span>
<span className='text-xs bg-white/20 backdrop-blur-sm text-white px-2 py-1 rounded-full flex items-center gap-1'>
<TrendingUp size={12} />
{t('额度奖励')}
</span>
</div>
</div>
{/* Tab 导航 */}
{loading ? (
<div className='pm-loading' aria-label={t('加载中...')}>
<Skeleton active paragraph={{ rows: 7 }} />
</div>
) : (
<>
{affLink ? (
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
className='promotion-tabs'
>
<TabPane
tab={
<span className='flex items-center gap-2 px-2'>
<Monitor size={16} />
<span className='font-medium'>{t('链接分享')}</span>
</span>
}
itemKey='link'
>
<div className='pt-4'>{renderLinkMode()}</div>
</TabPane>
<TabPane
tab={
<span className='flex items-center gap-2 px-2'>
<Smartphone size={16} />
<span className='font-medium'>{t('海报分享')}</span>
</span>
}
itemKey='poster'
>
<div className='pt-4'>{renderPosterMode()}</div>
</TabPane>
</Tabs>
</>
)}
</div>
items={[
{
key: 'link',
label: (
<span className='pm-tab-label'>
<Monitor size={16} aria-hidden />
{t('链接分享')}
</span>
),
children: renderLinkMode(),
},
{
key: 'poster',
label: (
<span className='pm-tab-label'>
<Smartphone size={16} aria-hidden />
{t('海报分享')}
</span>
),
children: renderPosterMode(),
},
]}
/>
) : (
<Alert
type='warning'
showIcon
title={t('邀请链接获取中,请稍后')}
/>
)}
<button
type='button'
className='pm-rewards'
onClick={() => {
onClose();
navigate('/user-center/invite');
}}
>
<span className='pm-rewards-icon'>
<Gift size={20} aria-hidden />
</span>
<span className='pm-rewards-copy'>
<strong>{t('查看邀请奖励规则')}</strong>
<span>{t('了解返佣比例和奖励详情')}</span>
</span>
<ChevronRight size={18} aria-hidden />
</button>
</>
)}
</Modal>
);
};
@@ -0,0 +1,352 @@
/* Copyright (C) 2025 QuantumNous */
.promotion-modal.ant-modal {
--pm-surface: var(--surface-card);
--pm-muted: var(--surface-bg-base);
--pm-text: var(--text-primary);
--pm-secondary: var(--text-secondary);
--pm-border: var(--border-subtle);
--pm-accent: var(--brand-primary);
--pm-soft: var(--brand-primary-soft);
--pm-qr-surface: #fff;
max-width: calc(100vw - 32px);
padding-block: 24px;
}
.promotion-modal .ant-modal-container {
padding: 28px 32px;
border-radius: 12px;
}
.promotion-modal .ant-modal-header {
margin-bottom: 12px;
}
.promotion-modal .ant-modal-title {
font-size: 20px;
line-height: 28px;
}
.promotion-modal .ant-modal-close {
top: 24px;
right: 24px;
}
.promotion-modal .ant-modal-body {
max-height: calc(100dvh - 160px);
overflow-y: auto;
overscroll-behavior: contain;
}
.promotion-tabs > .ant-tabs-nav {
margin-bottom: 24px;
}
.pm-tab-label {
display: inline-flex;
align-items: center;
gap: 8px;
}
.pm-link-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr);
gap: 32px;
align-items: stretch;
}
.pm-invitation-card {
display: flex;
flex-direction: column;
align-items: center;
padding: 28px 20px;
border: 1px solid var(--pm-border);
border-radius: 12px;
background: var(--pm-muted);
text-align: center;
min-width: 0;
}
.pm-eyebrow {
margin-bottom: 12px;
color: var(--pm-accent);
font-size: 12px;
letter-spacing: 0.08em;
}
.pm-invitation-card h4.ant-typography {
margin: 0 0 8px;
font-size: 20px;
overflow-wrap: anywhere;
}
.pm-invitation-card .ant-typography {
max-width: 100%;
}
.pm-qrcode {
padding: 12px;
background: var(--pm-qr-surface);
border-radius: 12px;
margin: 8px 0 16px;
}
.pm-qrcode canvas,
.pm-poster-qr canvas {
display: block;
max-width: 100%;
height: auto;
}
.pm-benefits {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 8px 16px;
margin-top: 24px;
color: var(--pm-secondary);
font-size: 12px;
}
.pm-benefits span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.pm-share-details {
display: flex;
flex-direction: column;
justify-content: center;
gap: 28px;
min-width: 0;
padding-block: 12px;
}
.pm-field {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 12px;
min-width: 0;
}
.pm-field label {
color: var(--pm-text);
font-size: 14px;
font-weight: 600;
}
.pm-field > .ant-btn {
align-self: flex-start;
}
.pm-code-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 16px;
}
.promotion-modal .pm-code {
padding: 10px 16px;
color: var(--pm-accent);
background: var(--pm-soft);
border-radius: 8px;
font:
600 20px/28px Consolas,
monospace;
letter-spacing: 0.06em;
overflow-wrap: anywhere;
min-width: 0;
}
.promotion-modal .pm-share-hint {
margin: 0;
font-size: 13px;
line-height: 1.8;
}
.pm-rewards {
display: flex;
align-items: center;
gap: 14px;
width: 100%;
margin-top: 24px;
padding: 16px;
background: var(--pm-surface);
color: var(--pm-text);
border: 1px solid var(--pm-border);
border-radius: 10px;
font: inherit;
text-align: left;
cursor: pointer;
}
.pm-rewards:hover {
border-color: var(--pm-accent);
background: var(--pm-soft);
}
.pm-rewards-icon {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 40px;
height: 40px;
border-radius: 8px;
color: var(--pm-accent);
background: var(--pm-soft);
}
.pm-rewards-copy {
display: grid;
gap: 4px;
flex: 1;
min-width: 0;
}
.pm-rewards-copy strong {
font-size: 14px;
font-weight: 600;
}
.pm-rewards-copy > span {
color: var(--pm-secondary);
font-size: 12px;
}
.pm-rewards > svg {
flex-shrink: 0;
color: var(--pm-secondary);
}
.pm-poster-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
gap: 32px;
align-items: center;
}
.pm-preview-stage {
display: flex;
justify-content: center;
padding: 20px;
border: 1px solid var(--pm-border);
border-radius: 12px;
background: var(--pm-muted);
min-width: 0;
}
.pm-poster {
display: flex;
flex-direction: column;
align-items: center;
width: 240px;
min-width: 0;
aspect-ratio: 375 / 667;
padding: 28px 16px 20px;
background: var(--pm-poster-background);
color: var(--pm-poster-ink);
border-radius: 8px;
text-align: center;
}
.pm-poster h2 {
margin: 0 0 8px;
font-size: 18px;
line-height: 1.5;
color: inherit;
}
.pm-poster p {
margin: 0;
font-size: 12px;
line-height: 1.6;
color: inherit;
}
.pm-poster h3 {
margin: 20px 0;
font-size: 16px;
line-height: 1.5;
color: inherit;
}
.pm-poster-qr {
padding: 8px;
background: var(--pm-qr-surface);
border-radius: 8px;
margin-bottom: 12px;
}
.pm-poster .pm-poster-code {
font-weight: 600;
margin-top: 8px;
overflow-wrap: anywhere;
}
.pm-poster .pm-poster-footer {
margin-top: auto;
padding-top: 20px;
font-size: 10px;
}
.pm-poster-options {
display: grid;
gap: 24px;
min-width: 0;
}
.pm-template-list {
display: grid;
gap: 8px;
}
.promotion-modal .pm-template-list .ant-radio-wrapper {
display: flex;
align-items: center;
margin: 0;
padding: 10px 12px;
border: 1px solid var(--pm-border);
border-radius: 8px;
}
.promotion-modal .pm-template-list .ant-radio-wrapper-checked {
border-color: var(--pm-accent);
background: var(--pm-soft);
}
.pm-template-label {
display: inline-flex;
align-items: center;
gap: 10px;
}
.pm-template-swatch {
display: block;
width: 24px;
height: 24px;
border-radius: 6px;
background: var(--pm-template-background);
}
.pm-poster-actions {
display: grid;
gap: 12px;
}
.pm-loading {
padding-block: 32px;
}
.promotion-modal :is(button, input):focus-visible {
outline: 2px solid var(--pm-accent);
outline-offset: 3px;
}
@media (max-width: 600px) {
.promotion-modal .ant-modal-container {
padding: 20px;
}
.promotion-modal .ant-modal-title {
font-size: 18px;
}
.promotion-modal .ant-modal-close {
top: 18px;
right: 16px;
}
.promotion-modal .ant-modal-body {
max-height: calc(100dvh - 136px);
}
.pm-link-layout,
.pm-poster-layout {
grid-template-columns: minmax(0, 1fr);
gap: 24px;
}
.pm-invitation-card {
padding: 20px 16px;
}
.pm-benefits {
margin-top: 16px;
}
.pm-share-details {
gap: 24px;
padding: 0;
}
.pm-field > .ant-btn {
width: 100%;
}
.pm-preview-stage {
padding: 16px;
}
.pm-template-list {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.promotion-modal .pm-template-list .ant-radio-wrapper {
padding: 8px;
}
.pm-template-label {
gap: 6px;
font-size: 12px;
}
.pm-template-swatch {
width: 18px;
height: 18px;
}
.pm-rewards {
padding: 12px;
}
}
+4 -3
View File
@@ -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) => (
<span className='quality-num'>
{Number(v).toFixed(2)} / {r.threshold}
{formatNumber(v, 2)} / {formatNumber(r.threshold, 2)}
</span>
),
},
@@ -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),
},
)}
+9 -5
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
*/
import { formatIdReference } from '../../helpers/safeDisplay';
import { formatUserReference } from '../../helpers/safeDisplay';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
@@ -82,7 +84,7 @@ export const HopChain = ({ hops, outcome, t }) => {
>
<span className='font-medium truncate'>
{t('第 {{n}} 跳', { n: i + 1 })} ·{' '}
{hop.channel_name || `#${hop.channel_id}`}
{hop.channel_name || formatIdReference(hop.channel_id)}
</span>
{failed ? (
<span className='quality-mono'>
@@ -199,7 +201,7 @@ const QualityDetail = ({ quality, t }) => {
width: 130,
render: (v, row) => (
<span className='block truncate max-w-[130px]' title={v}>
{v || `#${row.user_id}`}
{v || formatUserReference('', row.user_id)}
</span>
),
},
@@ -212,7 +214,7 @@ const QualityDetail = ({ quality, t }) => {
render: (v, row) =>
row.organization_id ? (
<span className='block truncate max-w-[130px]' title={v}>
{v || `#${row.organization_id}`}
{v || formatIdReference(row.organization_id)}
</span>
) : (
<span className='text-[var(--text-secondary)]'>
@@ -240,7 +242,7 @@ const QualityDetail = ({ quality, t }) => {
width: 140,
render: (v, row) => (
<span className='block truncate max-w-[140px]' title={v}>
{row.channel_id ? v || `#${row.channel_id}` : '-'}
{row.channel_id ? v || formatIdReference(row.channel_id) : '-'}
</span>
),
},
@@ -452,7 +454,9 @@ const QualityDetail = ({ quality, t }) => {
<OutcomeTag value={row.outcome} t={t} />
<span className='text-xs'>
{row.channel_name ||
(row.channel_id ? `#${row.channel_id}` : '')}
(row.channel_id
? formatIdReference(row.channel_id)
: '')}
</span>
{(row.status_code || row.error_code) && (
<span className='quality-mono'>
+24 -15
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
*/
import { formatIdReference } from '../../helpers/safeDisplay';
import { formatUserReference } from '../../helpers/safeDisplay';
import {
SlidersHorizontal as ActionSlidersHorizontal,
@@ -102,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})` : `#${value}`,
label: name
? `${name} (${formatIdReference(value)})`
: formatIdReference(value),
});
}
return opts;
@@ -147,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 }));
@@ -176,29 +184,30 @@ 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(
'user_id',
`${isOrg ? t('成员') : t('用户')}: ${nameOf(options.members, filters.user_id) || '#' + filters.user_id}`,
`${isOrg ? t('成员') : t('用户')}: ${nameOf(options.members, filters.user_id) || formatUserReference('', filters.user_id)}`,
);
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)
+4 -1
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { formatIdReference } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
@@ -102,7 +103,9 @@ const QualityHeatmap = ({ quality, t }) => {
(row.cells || []).forEach((c) => {
byTs[c.ts] = c;
});
const name = names[row.channel_id] || `#${row.channel_id}`;
const name =
names[row.channel_id] ||
formatIdReference(row.channel_id);
return (
<tr key={row.channel_id}>
<th title={name}>
+3 -2
View File
@@ -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),
},
],
},
+5 -3
View File
@@ -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();
@@ -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
+15 -5
View File
@@ -30,6 +30,7 @@ const DecisionTable = ({ mode, orgId }) => {
const { t } = useTranslation();
const [data, setData] = useState({ items: [], total: 0 });
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
@@ -38,7 +39,10 @@ const DecisionTable = ({ mode, orgId }) => {
setError('');
try {
setData(
(await listDecisions(mode, orgId, { p: page, page_size: 20 })) || {
(await listDecisions(mode, orgId, {
p: page,
page_size: pageSize,
})) || {
items: [],
total: 0,
},
@@ -48,7 +52,7 @@ const DecisionTable = ({ mode, orgId }) => {
} finally {
setLoading(false);
}
}, [mode, orgId, page, t]);
}, [mode, orgId, page, pageSize, t]);
useEffect(() => {
load();
@@ -147,12 +151,18 @@ const DecisionTable = ({ mode, orgId }) => {
/>
}
pagination={{
// 接口固定 page_size=20,不提供每页条数切换
current: page,
pageSize: 20,
pageSize,
total: data.total || 0,
size: 'small',
showSizeChanger: false,
showSizeChanger: mode === 'org',
onPageSizeChange:
mode === 'org'
? (size) => {
setPage(1);
setPageSize(size);
}
: undefined,
showTotal: (total) => t('共 {{total}} 条', { total }),
onChange: setPage,
}}
+1 -1
View File
@@ -221,7 +221,7 @@ const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => {
loading={loading}
columns={columns}
dataSource={list}
pagination={false}
pagination={mode === 'org' ? { resetOnDataChange: true } : false}
scroll={{ x: 'max-content' }}
empty={
<Empty
@@ -18,9 +18,9 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React, { useRef } from 'react';
import { Form, Button } from '@/components/ui';
import { Form } from '@/components/ui';
import { IconSearch } from '@/components/ui/icons';
import FilterSearchButton from '../../common/table/FilterSearchButton';
import { ConsoleSearchActions } from '../../console/ConsolePrimitives';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
const AdminTokensFilters = ({
@@ -67,93 +67,85 @@ const AdminTokensFilters = ({
autoComplete='off'
layout='vertical'
trigger='change'
className='admin-tokens-filter-form'
className='console-filter-panel'
>
<div className='admin-tokens-filter-grid'>
<div className='admin-tokens-filter-field'>
<Form.Input
field='keyword'
label={t('密钥名称 / Key 片段')}
prefix={<IconSearch />}
placeholder={t('密钥名称 / Key 片段')}
showClear
/>
</div>
<div className='admin-tokens-filter-field'>
<Form.Input
field='user_keyword'
label={t('用户名/昵称')}
placeholder={t('用户名/昵称')}
showClear
/>
</div>
<div className='admin-tokens-filter-field'>
<Form.Input
field='user_id'
label={t('用户ID')}
placeholder={t('用户ID')}
type='number'
showClear
/>
</div>
<div className='admin-tokens-filter-field'>
<Form.Select
field='statuses'
label={t('状态')}
placeholder={t('状态(多选)')}
multiple
optionList={[
{ label: t('已启用'), value: 1 },
{ label: t('已禁用'), value: 2 },
{ label: t('已过期'), value: 3 },
{ label: t('已耗尽'), value: 4 },
]}
showClear
className='w-full'
/>
</div>
<div className='admin-tokens-filter-field'>
<Form.Select
field='group'
label={t('分组')}
placeholder={t('分组')}
optionList={groupOptions}
showClear
className='w-full'
/>
</div>
<div className='admin-tokens-filter-field'>
<Form.Select
field='unlimited'
label={t('剩余额度')}
placeholder={t('剩余额度')}
optionList={[
{ label: t('无限额度'), value: true },
{ label: t('有限额度'), value: false },
]}
showClear
className='w-full'
/>
</div>
<div className='admin-tokens-filter-field'>
<Form.Select
field='org_scope'
label={t('归属')}
placeholder={t('归属')}
optionList={[
{ label: t('全部'), value: 'all' },
{ label: t('个人'), value: 'personal' },
{ label: t('企业'), value: 'org' },
]}
showClear={false}
className='w-full'
/>
</div>
</div>
<div className='admin-tokens-filter-actions'>
<Button onClick={handleReset}>{t('重置')}</Button>
<FilterSearchButton loading={loading || searching} />
<div className='console-filter-grid'>
<Form.Input
field='keyword'
label={t('密钥名称 / Key 片段')}
prefix={<IconSearch />}
placeholder={t('密钥名称 / Key 片段')}
showClear
/>
<Form.Input
field='user_keyword'
label={t('用户名/昵称')}
placeholder={t('用户名/昵称')}
showClear
/>
<Form.Input
field='user_id'
label={t('用户ID')}
placeholder={t('用户ID')}
type='number'
showClear
/>
<Form.Select
field='statuses'
label={t('状态')}
placeholder={t('状态(多选)')}
multiple
optionList={[
{ label: t('已启用'), value: 1 },
{ label: t('已禁用'), value: 2 },
{ label: t('已过期'), value: 3 },
{ label: t('已耗尽'), value: 4 },
]}
showClear
className='w-full'
/>
<Form.Select
field='group'
label={t('分组')}
placeholder={t('分组')}
optionList={groupOptions}
showClear
className='w-full'
/>
<Form.Select
field='unlimited'
label={t('剩余额度')}
placeholder={t('剩余额度')}
optionList={[
{ label: t('无限额度'), value: true },
{ label: t('有限额度'), value: false },
]}
showClear
className='w-full'
/>
<Form.Select
field='org_scope'
label={t('归属')}
placeholder={t('归属')}
optionList={[
{ label: t('全部'), value: 'all' },
{ label: t('个人'), value: 'personal' },
{ label: t('企业'), value: 'org' },
]}
showClear={false}
className='w-full'
/>
</div>
<ConsoleSearchActions
onReset={handleReset}
loading={loading || searching}
/>
</Form>
);
};
@@ -1,32 +1,3 @@
.console-page .console-search-card .admin-tokens-filter-form {
display: block;
}
.admin-tokens-filter-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1rem;
width: 100%;
}
.console-page .admin-tokens-filter-grid .ant-form-item-label > label {
color: var(--console-muted);
font-size: 13px;
}
.admin-tokens-filter-actions,
.admin-tokens-tools {
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
gap: 0.5rem;
}
.admin-tokens-filter-actions {
margin-top: 1rem;
}
.admin-tokens-toolbar {
display: flex;
align-items: center;
@@ -39,6 +10,11 @@
.admin-tokens-tools {
margin-inline-start: auto;
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
gap: 8px;
}
.console-page .console-table.admin-tokens-table .ant-table-thead > tr > th {
@@ -78,15 +54,3 @@
padding: 0 4px;
font-size: 13px;
}
@media (max-width: 1100px) {
.admin-tokens-filter-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 768px) {
.admin-tokens-filter-grid {
grid-template-columns: minmax(0, 1fr);
}
}
@@ -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)}
</div>
<div>
{t('使用率')}: {percent}%
{t('使用率')}: {formatDisplayPercent(percent)}
</div>
{isExceeded && (
<div style={{ color: 'var(--ui-color-danger)' }}>
@@ -327,7 +332,7 @@ const renderDailyQuota = (record, dailyQuotaInfo, t) => {
strokeColor={strokeColor}
size='small'
showInfo
format={(percent) => `${percent}%`}
format={(percent) => formatDisplayPercent(percent)}
/>
</div>
</Tooltip>
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { formatIdReference } from '../../../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../../../i18n/technicalText.js';
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
@@ -290,11 +291,11 @@ const EditChannelModal = (props) => {
if (ch.status !== 1) {
return {
value: ch.id,
label: `#${ch.id} ${ch.name}${t('(已禁用)')}`,
label: `${formatIdReference(ch.id)} ${ch.name}${t('(已禁用)')}`,
disabled: true,
};
}
const parts = [`#${ch.id} ${ch.name}`];
const parts = [`${formatIdReference(ch.id)} ${ch.name}`];
if (ch.group) parts.push(ch.group);
if (ch.region) parts.push(ch.region);
return { value: ch.id, label: parts.join(' · ') };
@@ -345,7 +346,7 @@ const EditChannelModal = (props) => {
.filter((id) => !known.has(id) && id !== channelId)
.map((id) => ({
value: id,
label: `#${id}${t('(已删除)')}`,
label: `${formatIdReference(id)}${t('(已删除)')}`,
disabled: true,
}));
return missing.length
@@ -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 && (
<Typography.Text type='secondary'>
{t('请求时长: {{time}}s', {
time: testResult.time.toFixed(2),
time: formatTestTime(testResult.time),
})}
</Typography.Text>
)}
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { formatIdReference } from '../../../../helpers/safeDisplay';
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useState, useEffect } from 'react';
@@ -359,7 +360,7 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
{
title: t('索引'),
dataIndex: 'index',
render: (text) => `#${text}`,
render: (text) => formatIdReference(text),
},
// {
// title: t('密钥预览'),
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Copy, Plus, Trash2 } from '@/components/common/icons/ActionIcons';
import { Button } from '@/components/ui';
import { isAdmin } from '../../../helpers';
@@ -38,37 +39,29 @@ const RedemptionsActions = ({
};
return (
<div className='flex flex-wrap gap-2 w-full md:w-auto order-2 md:order-1'>
{isAdmin() && (
<Button
type='primary'
className='flex-1 md:flex-initial'
onClick={handleAddRedemption}
size='small'
>
{t('添加兑换码')}
</Button>
)}
<Button
type='tertiary'
className='flex-1 md:flex-initial'
onClick={batchCopyRedemptions}
size='small'
>
<div className='console-list-tool-actions'>
<Button icon={<Copy size={16} />} onClick={batchCopyRedemptions}>
{t('复制所选兑换码到剪贴板')}
</Button>
{isAdmin() && (
<Button
type='danger'
className='w-full md:w-auto'
icon={<Trash2 size={16} />}
onClick={batchDeleteRedemptions}
size='small'
>
{t('清除失效兑换码')}
</Button>
)}
{isAdmin() && (
<Button
type='primary'
icon={<Plus size={16} />}
onClick={handleAddRedemption}
>
{t('添加兑换码')}
</Button>
)}
</div>
);
};
@@ -144,7 +144,7 @@ export const getRedemptionsColumns = ({
},
},
{
title: '',
title: t('操作'),
dataIndex: 'operate',
fixed: 'right',
width: 205,
@@ -51,28 +51,24 @@ const RedemptionsFilters = ({
onSubmit={searchRedemptions}
allowEmpty={true}
autoComplete='off'
layout='horizontal'
layout='vertical'
trigger='change'
stopValidateWithError={false}
className='w-full'
className='console-filter-panel'
>
<div className='console-search-fields'>
<div className='console-search-field'>
<Form.Input
field='searchKeyword'
prefix={<IconSearch />}
placeholder={t('关键字(id或者名称)')}
showClear
pure
size='small'
/>
</div>
<ConsoleSearchActions
onReset={handleReset}
loading={loading || searching}
searchLabel='查询'
<div className='console-filter-grid'>
<Form.Input
field='searchKeyword'
prefix={<IconSearch />}
label={t('搜索关键字')}
placeholder={t('关键字(id或者名称)')}
showClear
/>
</div>
<ConsoleSearchActions
onReset={handleReset}
loading={loading || searching}
/>
</Form>
);
};
@@ -18,12 +18,8 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React, { useMemo, useState } from 'react';
import { Empty } from '@/components/ui';
import TableEmpty from '../../common/table/TableEmpty';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getRedemptionsColumns } from './RedemptionsColumnDefs';
import DeleteRedemptionModal from './modals/DeleteRedemptionModal';
@@ -101,17 +97,8 @@ const RedemptionsTable = (redemptionsData) => {
loading={loading}
rowSelection={rowSelection}
onRow={handleRow}
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className='rounded-xl overflow-hidden'
empty={<TableEmpty />}
className='console-list-table overflow-hidden'
size='middle'
/>
+6 -8
View File
@@ -82,15 +82,13 @@ const RedemptionsPage = () => {
/>
}
type='type1'
descriptionArea={
<RedemptionsDescription
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
}
actionsArea={
<div className='flex flex-col md:flex-row justify-between items-center gap-2 w-full'>
<div className='console-list-tools'>
<RedemptionsDescription
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
<RedemptionsActions
selectedKeys={selectedKeys}
setEditingRedemption={setEditingRedemption}
@@ -33,6 +33,29 @@
color: var(--ui-color-primary);
}
.usage-logs-table .ant-table-cell.usage-record-cell-use_time {
vertical-align: middle;
}
.usage-record-use-time {
display: inline-flex;
align-items: center;
justify-content: center;
vertical-align: middle;
gap: 6px;
white-space: nowrap;
}
.usage-logs-table .usage-record-use-time .ant-tag {
margin-inline-end: 0;
padding: 0 6px;
border-radius: 6px;
font-size: 12px;
font-weight: 500;
font-variant-numeric: tabular-nums;
line-height: 22px;
}
.usage-logs-table-shell {
position: relative;
}
@@ -130,93 +130,6 @@ function renderType(type, t) {
);
}
function renderIsStream(bool, t) {
if (bool) {
return (
<span className='inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium bg-blue-50 dark:bg-blue-950/30 text-blue-600 dark:text-blue-400 border border-blue-200/50 dark:border-blue-800/50'>
<span className='w-1 h-1 rounded-full bg-blue-500 animate-pulse' />
{t('流')}
</span>
);
} else {
return (
<span className='inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium bg-gray-50 dark:bg-gray-900/30 text-gray-500 dark:text-gray-400 border border-gray-200/50 dark:border-gray-700/50'>
{t('非流')}
</span>
);
}
}
function renderUseTime(type, t) {
const time = parseInt(type);
let colorConfig;
if (time < 101) {
colorConfig = {
bg: 'bg-emerald-50 dark:bg-emerald-950/30',
text: 'text-emerald-600 dark:text-emerald-400',
border: 'border-emerald-200/50 dark:border-emerald-800/50',
dot: 'bg-emerald-500',
};
} else if (time < 300) {
colorConfig = {
bg: 'bg-amber-50 dark:bg-amber-950/30',
text: 'text-amber-600 dark:text-amber-400',
border: 'border-amber-200/50 dark:border-amber-800/50',
dot: 'bg-amber-500',
};
} else {
colorConfig = {
bg: 'bg-rose-50 dark:bg-rose-950/30',
text: 'text-rose-600 dark:text-rose-400',
border: 'border-rose-200/50 dark:border-rose-800/50',
dot: 'bg-rose-500',
};
}
return (
<span
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium ${colorConfig.bg} ${colorConfig.text} border ${colorConfig.border}`}
>
{time}s
</span>
);
}
function renderFirstUseTime(type, t) {
let time = parseFloat(type) / 1000.0;
time = time.toFixed(1);
let colorConfig;
if (time < 3) {
colorConfig = {
bg: 'bg-teal-50 dark:bg-teal-950/30',
text: 'text-teal-600 dark:text-teal-400',
border: 'border-teal-200/50 dark:border-teal-800/50',
};
} else if (time < 10) {
colorConfig = {
bg: 'bg-orange-50 dark:bg-orange-950/30',
text: 'text-orange-600 dark:text-orange-400',
border: 'border-orange-200/50 dark:border-orange-800/50',
};
} else {
colorConfig = {
bg: 'bg-red-50 dark:bg-red-950/30',
text: 'text-red-600 dark:text-red-400',
border: 'border-red-200/50 dark:border-red-800/50',
};
}
return (
<span
className={`inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium ${colorConfig.bg} ${colorConfig.text} border ${colorConfig.border}`}
>
{time}s
</span>
);
}
function renderModelName(record, copyText, t, isRootUser) {
let other = getLogOther(record.other);
let modelMapped =
@@ -384,7 +297,7 @@ const applyUsageRecordPresentation = (
...baseColumn,
width: RECORD_COLUMN_WIDTHS[baseColumn.key],
fixed: undefined,
className: `usage-record-cell-${baseColumn.key}`,
className: baseColumn.className ?? `usage-record-cell-${baseColumn.key}`,
};
switch (column.key) {
case COLUMN_KEYS.TIME:
@@ -449,15 +362,6 @@ const applyUsageRecordPresentation = (
</button>
) : null,
};
case COLUMN_KEYS.USE_TIME:
return {
...column,
title: t('用时/首字').replace('/', ' / '),
render: (text, record) =>
record.type === 2 || record.type === 5
? renderRecordUseTime(record, t)
: null,
};
case COLUMN_KEYS.PROMPT:
case COLUMN_KEYS.COMPLETION:
return {
@@ -693,34 +597,14 @@ export const getLogsColumns = ({
},
{
key: COLUMN_KEYS.USE_TIME,
title: t('用时/首字'),
title: t('用时/首字').replace('/', ' / '),
dataIndex: 'use_time',
render: (text, record, index) => {
if (!(record.type === 2 || record.type === 5)) {
return <></>;
}
if (record.is_stream) {
let other = getLogOther(record.other);
return (
<>
<Space>
{renderUseTime(text, t)}
{renderFirstUseTime(other?.frt, t)}
{renderIsStream(record.is_stream, t)}
</Space>
</>
);
} else {
return (
<>
<Space>
{renderUseTime(text, t)}
{renderIsStream(record.is_stream, t)}
</Space>
</>
);
}
},
align: 'center',
className: 'usage-record-cell-use_time',
render: (_, record) =>
record.type === 2 || record.type === 5
? renderRecordUseTime(record, t)
: null,
},
{
key: COLUMN_KEYS.PROMPT,
@@ -435,7 +435,7 @@ const LogsTable = (logsData) => {
if (canView) setDetailRecord(record);
}}
>
{t('查看')}
{t('详情')}
</AntButton>
);
}
@@ -449,7 +449,7 @@ const LogsTable = (logsData) => {
if (canView) setDetailRecord(record);
}}
>
{t('查看')}
{t('详情')}
</AntButton>
);
},
+20 -33
View File
@@ -26,10 +26,9 @@ import {
Progress,
Popover,
Typography,
Dropdown,
} from '@/components/ui';
import { Switch } from 'antd';
import { IconMore } from '@/components/ui/icons';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import {
renderGroup,
renderNumber,
@@ -256,50 +255,48 @@ const renderOperations = (
if (canChangeRole) {
moreMenu.push(
{
node: 'item',
name: t('提升'),
key: 'promote',
label: t('提升'),
onClick: () => showPromoteModal(record),
},
{
node: 'item',
name: t('降级'),
key: 'demote',
label: t('降级'),
onClick: () => showDemoteModal(record),
},
{ node: 'divider' },
{ type: 'divider' },
);
}
moreMenu.push({
node: 'item',
name: t('邀请记录'),
key: 'invitations',
label: t('邀请记录'),
onClick: () => showInvitedUsersModal(record),
});
if (canManage) {
moreMenu.push(
{ node: 'divider' },
{ type: 'divider' },
{
node: 'item',
name: t('重置 Passkey'),
key: 'reset-passkey',
label: t('重置 Passkey'),
onClick: () => showResetPasskeyModal(record),
},
{
node: 'item',
name: t('重置 2FA'),
key: 'reset-2fa',
label: t('重置 2FA'),
onClick: () => showResetTwoFAModal(record),
},
{ node: 'divider' },
{ type: 'divider' },
{
node: 'item',
name: t('注销'),
type: 'danger',
key: 'delete',
label: t('注销'),
danger: true,
onClick: () => showDeleteModal(record),
},
);
}
return (
// wrap 保留:移动端 CardTable 把按钮放进 ~280px 的卡片行里,Semi Space 默认
// wrap:false 时溢出会被 .ant-card{overflow:hidden} 裁掉(不是滚动,是永久看不到)
<Space wrap className='console-module-row-actions'>
<TableRowActions items={moreMenu}>
{canManage && (
<>
<Button
@@ -314,15 +311,7 @@ const renderOperations = (
</Button>
</>
)}
<Dropdown menu={moreMenu} trigger='click' position='bottomRight'>
<Button
type='tertiary'
size='small'
icon={<IconMore />}
aria-label={t('更多操作')}
/>
</Dropdown>
</Space>
</TableRowActions>
);
};
@@ -394,9 +383,7 @@ export const getUsersColumns = ({
title: t('操作'),
dataIndex: 'operate',
fixed: 'right',
// 200 而不是更窄:en 下「Edit + Disable + 更多」三控件 ≈ 190px,
// 再窄会触发 Space wrap 折行,重新撑高行高(本次改版要消灭的问题)
width: 120,
width: 135,
render: (text, record, index) =>
renderOperations(text, record, {
setEditingUser,
+17 -11
View File
@@ -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 (
<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}{' '}
{rate.toFixed(2)} {symbol}
{formatNumber(rate, 2, '1.00')} {symbol}
</span>
);
})()}
@@ -309,11 +310,14 @@ const RechargeCard = ({
>
<div className='grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4'>
{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 && (
<div className='text-xs font-semibold px-2 py-0.5 bg-green-100 text-green-700 rounded-full mb-2'>
{t('省')} {symbol}
{displaySave.toFixed(0)}
{formatNumber(displaySave, 0, '0')}
</div>
)}
@@ -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')}
</span>
</div>
</div>
@@ -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) => (
<span className='text-base font-semibold text-rose-500'>
¥{Number(money || 0).toFixed(2)}
{formatCurrency(money, '¥', 2, '¥0.00')}
</span>
),
},
@@ -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 }) => {
<div>
<Text type='secondary'>{t('支付金额:')}</Text>
<Text strong style={{ fontSize: 20, color: '#f5222d' }}>
¥{orderData.amount?.toFixed(2)}
{formatCurrency(orderData.amount)}
</Text>
</div>
<div>
+67 -23
View File
@@ -39,6 +39,12 @@ import { useLocation } from 'react-router-dom';
import { useActualTheme } from '../../context/Theme';
import { normalizeLanguage } from '../../i18n/language';
import { colord } from 'colord';
import {
PROTOTYPE_DARK_PRIMARY,
PROTOTYPE_DARK_SEED,
PROTOTYPE_LIGHT_PRIMARY,
resolveBrandPalette,
} from '../../helpers/brandPalette';
import './antd-v5-compat.css';
// 与下方 Ant Design locale 一一对应的 dayjs 语言(未覆盖语言与 Ant Design 一样回退中文)。
@@ -55,8 +61,8 @@ const DAYJS_LOCALES = {
// 在线原型暗色:种子 #f2ad41 经 Ant Design 暗色算法推导出主色 #d1963a(悬停 #e8ba65、
// 选中背景 #574222 等)。系统以“最终主色”(--brand-primary) 作为 colorPrimary,
// 算法其余衍生令牌需仍按原型种子推导,否则会从 #d1963a 再推一次而整体偏暗。
const PROTOTYPE_DARK_PRIMARY = '#d1963a';
const PROTOTYPE_DARK_SEED = '#f2ad41';
const DARK_SURFACE = '#1b212b';
const LIGHT_SURFACE = '#ffffff';
// v5 used these shadows in both themes; v6 derives white shadows in dark mode.
const v5ShadowTokens = {
@@ -69,15 +75,7 @@ const v5ShadowTokens = {
'0 1px 2px 0 rgba(0,0,0,0.03), 0 1px 6px -1px rgba(0,0,0,0.02), 0 2px 4px 0 rgba(0,0,0,0.02)',
};
// 页面局部“品牌强调色”(原型 --brand):等于当前主题的种子色。
// 浅色与自定义主色时即 colorPrimary;仅默认暗色主色 #d1963a 时回到原型种子 #f2ad41,
// 保证浅色 / 深色 / 自定义主题色三态都只由主题 token 推导,不在页面里另写颜色。
export const brandAccentFromToken = (colorPrimary, dark) =>
dark && colorPrimary?.toLowerCase() === PROTOTYPE_DARK_PRIMARY
? PROTOTYPE_DARK_SEED
: colorPrimary;
export const prototypeTheme = (dark) => ({
const prototypeTheme = (dark, palette) => ({
algorithm: (seed, map) => {
const derive =
dark && seed.colorPrimary?.toLowerCase() === PROTOTYPE_DARK_PRIMARY
@@ -91,14 +89,30 @@ export const prototypeTheme = (dark) => ({
...(dark ? theme.darkAlgorithm : theme.defaultAlgorithm)(derive, map),
colorPrimary: seed.colorPrimary,
colorInfo: seed.colorInfo,
...(!palette.isPrototype && {
colorPrimaryHover: palette.hover,
colorPrimaryActive: palette.active,
colorPrimaryBg: palette.tint,
colorPrimaryBgHover: palette.tintHover,
colorPrimaryText: palette.accent,
colorPrimaryTextHover: palette.accent,
colorPrimaryTextActive: palette.accent,
colorLink: palette.accent,
colorLinkHover: palette.accent,
colorLinkActive: palette.accent,
}),
};
},
token: {
...v5ShadowTokens,
colorPrimary: dark ? PROTOTYPE_DARK_PRIMARY : '#b96508',
colorInfo: dark ? PROTOTYPE_DARK_PRIMARY : '#b96508',
colorPrimary: palette.isPrototype
? dark
? PROTOTYPE_DARK_PRIMARY
: PROTOTYPE_LIGHT_PRIMARY
: palette.normal,
colorInfo: dark ? PROTOTYPE_DARK_PRIMARY : PROTOTYPE_LIGHT_PRIMARY,
colorBgLayout: dark ? '#11151c' : '#f4f6f9',
colorBgContainer: dark ? '#1b212b' : '#ffffff',
colorBgContainer: dark ? DARK_SURFACE : LIGHT_SURFACE,
colorText: dark ? '#e6ebf3' : '#263247',
colorTextSecondary: dark ? '#8e9aaa' : '#7e8998',
colorBorderSecondary: dark ? '#2b333f' : '#e9edf2',
@@ -113,8 +127,22 @@ export const prototypeTheme = (dark) => ({
},
Menu: {
itemHeight: 42,
itemSelectedBg: dark ? '#382b1b' : '#fff3df',
itemSelectedColor: dark ? '#f2ad41' : '#a95d07',
itemSelectedBg: palette.selectionBg,
itemSelectedColor: palette.selectionText,
},
Button: {
colorPrimary: palette.normal,
colorPrimaryHover: palette.hover,
colorPrimaryActive: palette.active,
primaryColor: palette.onSolid,
},
Switch: {
colorPrimary: palette.normal,
colorPrimaryHover: palette.hover,
},
DatePicker: {
colorPrimary: palette.normal,
colorTextLightSolid: palette.onSolid,
},
Card: { headerFontSize: 15 },
Modal: { borderRadiusLG: 12 },
@@ -128,10 +156,23 @@ const v5ComponentDefaults = {
drawer: { mask: { blur: false } },
};
function TokenBridge() {
function TokenBridge({ palette }) {
const { token } = theme.useToken();
useLayoutEffect(() => {
const values = {
'brand-accent': palette.accent,
'brand-selection-bg': palette.selectionBg,
'brand-selection-text': palette.selectionText,
'brand-on-primary': palette.onSolid,
'brand-notice-bg': palette.isPrototype
? 'var(--brand-notice-default-bg)'
: palette.tint,
'brand-notice-text': palette.isPrototype
? 'var(--brand-notice-default-text)'
: palette.selectionText,
'brand-notice-border': palette.isPrototype
? 'var(--brand-notice-default-border)'
: palette.tintHover,
'ui-color-white': '#fff',
'ui-color-black': '#000',
...Object.fromEntries(
@@ -216,7 +257,7 @@ function TokenBridge() {
}
for (const [name, value] of Object.entries(values))
if (value != null) document.body.style.setProperty(`--${name}`, value);
}, [token]);
}, [token, palette]);
return null;
}
@@ -237,14 +278,17 @@ export default function UiThemeProvider({ children }) {
return () => window.removeEventListener('theme-tokens-applied', update);
}, []);
// Re-read the computed brand when the existing CSS theme is applied.
const config = useMemo(() => {
const result = prototypeTheme(dark);
const { config, palette } = useMemo(() => {
// Keep existing configured brand previews and persistence in helpers/theme.js.
const brand = getComputedStyle(document.body)
.getPropertyValue('--brand-primary')
.trim();
if (brand) result.token.colorPrimary = brand;
return result;
const palette = resolveBrandPalette(
brand,
dark,
dark ? DARK_SURFACE : LIGHT_SURFACE,
);
return { config: prototypeTheme(dark, palette), palette };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dark, revision]);
const language = normalizeLanguage(i18n.language);
@@ -281,7 +325,7 @@ export default function UiThemeProvider({ children }) {
return (
<ConfigProvider {...v5ComponentDefaults} theme={config} locale={locale}>
<App>
<TokenBridge />
<TokenBridge palette={palette} />
{children}
</App>
</ConfigProvider>
+4
View File
@@ -16,3 +16,7 @@ body[data-ui-scope='admin']
> label.ant-form-item-required::before {
font-family: SimSun, sans-serif;
}
.ant-switch.ant-switch-checked .ant-switch-inner-checked {
color: var(--brand-on-primary);
}
+8 -2
View File
@@ -288,6 +288,7 @@ export function Table({
expandedRowKeys,
onExpand,
expandRowByClick,
expandable: nativeExpandable,
pagination,
size,
onChange,
@@ -305,7 +306,7 @@ export function Table({
onExpand,
expandRowByClick,
}
: undefined;
: nativeExpandable;
return (
<Component
{...props}
@@ -348,10 +349,15 @@ function CenterPaginatedTable({
...props
}) {
const isMobile = useIsMobile();
const config = legacyPagination;
const { resetOnDataChange, ...config } = legacyPagination;
const local = config.total === undefined;
const [localPage, setLocalPage] = React.useState(config.currentPage ?? 1);
const [localSize, setLocalSize] = React.useState(config.pageSize ?? 10);
const resetLocalPage = local && resetOnDataChange;
const resetSource = resetLocalPage ? props.dataSource : undefined;
React.useEffect(() => {
if (resetLocalPage) setLocalPage(1);
}, [resetLocalPage, resetSource]);
const pageSize =
local && !config.onPageSizeChange ? localSize : (config.pageSize ?? 10);
const total = config.total ?? props.dataSource?.length ?? 0;
+3 -1
View File
@@ -21,7 +21,9 @@ import i18next from 'i18next';
export const isCenterPaginationScope = () =>
typeof window !== 'undefined' &&
/^\/(console|org)(\/|$)/.test(window.location?.pathname || '');
/^\/(?:console|org|user-center\/key-management)(?:\/|$)/.test(
window.location?.pathname || '',
);
export const centerPaginationOptions = (config, isMobile = false) => ({
...config,